Wednesday, June 8, 2011

Amazed by Scala #1: objects and compilation

7 minutes and here is an object, that can be compiled into java classes:


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


Saved in TopStock.scala. Compiled with

> scalac TopStock.scala

ran with

> scala TopStock

Top stock of 2008 is GOOG closing at price 307,650000

No comments: