Wednesday, June 8, 2011

Amazed by Scala

Top stock of 2008 is GOOG closing at price 307,650000 among (AAPL, GOOG, IBM, MSFT). Amazed by simplicity, clarity and beauty of the following code in Scala from this book.


  1. import scala.actors._  
  2. import Actor._  
  3.   
  4. val symbols = List( "AAPL""GOOG""IBM""MSFT")  
  5. val receiver = self  
  6. val year = 2008  
  7.   
  8. symbols.foreach { symbol =>  
  9.   actor { receiver ! getYearEndClosing(symbol, year) }  
  10. }  
  11.     
  12. val (topStock, highestPrice) = getTopStock(symbols.length)  
  13.   
  14. printf("Top stock of %d is %s closing at price %f\n", year,  
  15.            topStock, highestPrice)  
  16.   
  17. def getYearEndClosing(symbol : String, year : Int) = {  
  18.  val url = "http://ichart.finance.yahoo.com/table.csv?s="+   
  19.  symbol + "&a=11&b=01&c=" + year + "&d=11&e=31&f=" + year+  
  20.        "&g=m"  
  21.     
  22.  val data = io.Source.fromURL(url).mkString  
  23.  val price = data.split("\n")(1).split(",")(4).toDouble  
  24.  (symbol, price)  
  25. }  
  26.   
  27. def getTopStock(count : Int) : (String, Double) = {  
  28.  (1 to count).foldLeft(""0.0) { (previousHigh, index) =>  
  29.     receiveWithin(10000) {  
  30.   case (symbol : String, price : Double) =>  
  31.     if (price > previousHigh._2) (symbol, price) else  
  32.              previousHigh  
  33.   }  
  34.  }  
  35. }  

No comments: