Tuesday, October 2, 2012

Seven Languages in Seven Weeks - Scala Day 2 Self Study

Hey there! I'm currently reading Seven Languages in Seven Weeks by Bruce A. Tate. As the title implies, this book explores seven different programming languages. Each chapter ends with a self study section. Here are the exercises of day 2 with the Scala programming language:

Use foldLeft to compute the total size of a list of strings:
Here are two variants, the first calls the foldLeft method (note the multiple parameter list, this is used for currying, i.e. partial function application) while the second is using the /: infix operator, which is in fact an overload of foldLeft:
  val list = List("foo", "bar", "hello", "world")
  list.foldLeft(0)((len, elem) => elem.size + len)//> res0: Int = 16
  (0 /: list) {(len, elem) => elem.size + len}    //> res1: Int = 16

Write a Censor trait with a method that will replace the curse words Shoot and Darn with Pucky and Beans alternatives. Use a map to store the curse words and their alternatives. Then, load the curse words and alternatives from a file:
The trait expects the curse words dictionary in the file words.txt:
Shoot:Pucky
Darn:Beans
The words are loaded line by line, each line is splitted at the : character and the values are stored in the substitions map. The replace method takes a text as input parameter, converts it as a list of words and applies the substitutions by looking up the map.
  trait Censor {
   val substitutions = new HashMap[String, String]
   
   Source.fromFile("/words.txt", "US-ASCII").getLines.foreach { line =>
    val elem = line.split(":", 2)
    substitutions += (elem(0) -> elem(1))
   }
   
   def replace(text: String): String = {
    text.split("\\s").map({word =>
     substitutions.getOrElse(word, word)
    }).reduceLeft((concat, word) => concat + " " + word)
   }
  }
Here's a simple example showing how the trait works:
  val censor = new Censor {}
  censor.replace("hello Darn world") //> res2: String = hello Beans world
Stay tuned, I'll soon be posting the 3rd study section about Scala.