Compare commits

...

3 Commits

Author SHA1 Message Date
bed771a04e
added assignment 8 ex 2 2025-05-05 18:43:26 +02:00
6954695a0d
added assignment 8 ex 1 2025-05-05 17:35:43 +02:00
a16b70970f
added lesson 8 2025-05-05 17:08:21 +02:00
5 changed files with 180 additions and 0 deletions

24
src/Assignment8/Ex1.scala Normal file
View File

@ -0,0 +1,24 @@
package Assignment8
import utils.timeVerbose
import scala.collection.parallel.CollectionConverters._
object Ex1 extends App {
def integrate(a: Double, b: Double, nIntervals: Int, f: (Double => Double)): Double = {
val dx: Double = (b - a) / nIntervals
//val y: Double = (1 until nIntervals).map(i => f(i * dx + a)).sum
//val y: Double = (1 until nIntervals).view.map(i => f(i * dx + a)).sum
val y: Double = (1 until nIntervals).par.map(i => f(i * dx + a)).sum
return (2 * y + f(a) + f(b)) * dx / 2
}
println(integrate(1, 2, 500, math.sin))
println(integrate(0, 1, 500, math.sin _ compose math.cos))
timeVerbose {
val i = integrate(0, 1, math.pow(20, 6).toInt, math.sin)
}
}

62
src/Assignment8/Ex2.scala Normal file
View File

@ -0,0 +1,62 @@
package Assignment8
import net.liftweb.json
import net.liftweb.json.DefaultFormats
import java.net.URI
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.sys.process._
import scala.util.{Failure, Success}
object Ex2 extends App {
implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global
implicit val formats: DefaultFormats.type = DefaultFormats
case class Coin(id: String, icon: String, name: String, symbol: String, rank: Int, price: Double, priceBtc: Double, volume: Double, marketCap: Double, availableSupply: Double, totalSupply: Double, fullyDilutedValuation: Double, priceChange1h: Double, priceChange1d: Double, priceChange1w: Double, redditUrl: String, websiteUrl: String, twitterUrl: String, explorers: List[String])
case class Currency(name: String, rate: Double, symbol: String, imageUrl: String)
val BITCOIN_TO_USD: String = "https://openapiv1.coinstats.app/coins/bitcoin"
val USD_TO_CHF: String = "https://openapiv1.coinstats.app/fiats"
private val API_KEY: String = sys.env.getOrElse("OPENAPI_KEY", "")
def getUrl(url: String): Future[String] = {
Future {
val uri: URI = new URI(url)
val cmd: String = "curl -s -H 'X-API-KEY: " + API_KEY + "' " + uri.toString
cmd.!!
}
}
def extractBitcoinToUSDRate(jsonStr: String): Double = {
val data: Coin = json.parse(jsonStr).extract[Coin]
return data.price
}
def extractUSDToCHFRate(jsonStr: String): Double = {
val data: List[Currency] = json.parse(jsonStr).extract[List[Currency]]
return data.find(currency => currency.name == "CHF")
.map(currency => currency.rate)
.get
}
def getBitcoinToUSD: Future[Double] = {
getUrl(BITCOIN_TO_USD) map extractBitcoinToUSDRate
}
def getUSDToCHF: Future[Double] = {
getUrl(USD_TO_CHF) map extractUSDToCHFRate
}
val f: Future[Double] = for {
btc2usd <- getBitcoinToUSD
usd2chf <- getUSDToCHF
} yield btc2usd * usd2chf
f onComplete {
case Success(value) => println(s"1 BTC == $value CHF")
case Failure(e) => println(s"An error occurred: $e")
}
Await.ready(f, Duration.Inf)
}

19
src/Lesson8/Actors.scala Normal file
View File

@ -0,0 +1,19 @@
package Lesson8
import akka.actor.{Actor, ActorSystem, Props}
object Actors extends App {
case class Greetings(who: String)
class SimplestActor extends Actor {
def receive = {
case Greetings(who) => println(s"Hello $who, pleased to meet you")
}
}
val system = ActorSystem("MySystem")
val simple_greeter = system.actorOf(Props[SimplestActor])
simple_greeter ! Greetings("Dr Who")
}

18
src/Lesson8/Futures.scala Normal file
View File

@ -0,0 +1,18 @@
package Lesson8
import scala.concurrent.Future
import scala.util.{Failure, Success}
object Futures extends App {
implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global
val f: Future[Int] = Future {
Thread.sleep(650)
3 + 4
}
f onComplete {
case Success(x: Int) => println(s"Computing done, result is $x")
case Failure(ex) => println("Error")
}
}

57
src/utils/package.scala Normal file
View File

@ -0,0 +1,57 @@
/**
* Some useful functions for Scala.
*
* @author Pierre-André Mudry
* @version 1.0
*/
import java.io.{BufferedOutputStream, File, FileOutputStream}
import scala.io.{Codec, Source}
package object utils {
/**
* There are functions for micro-benchmarking, but you should not
* rely on those functions for measuring short durations!
*/
// Measure the time for a block of code to run, approximately
def timeVerbose(f: Unit) = {
println("[Time] Start of measure")
val duration = time(f)
println(s"[Time] Block duration was $duration ms\n")
duration
}
// With a customized error message
def timeVerbose(s: String)(f: Unit) = {
println(s"[$s] Start of measure")
val duration = time(f)
println(s"[$s] Block duration was $duration ms\n")
duration
}
// Measure the time for a block of code to run, approximately
def time(f: Unit) = {
val start = System.currentTimeMillis
f // Execute the block
val duration = System.currentTimeMillis - start
duration
}
/**
* A class for reading and writing to files easily
*/
implicit class RichFile(file: File) {
def read() = Source.fromFile(file)(Codec.UTF8).mkString
def write(data: String) {
val fos = new BufferedOutputStream(new FileOutputStream(file))
try {
fos.write(data.getBytes("UTF-8"))
} finally {
fos.close
}
}
}
}