6Mar/110
Scala Day 2 – Higher-Order Functions
Following up on Day 1, here's day 2 from 7 languages in 7 weeks. These problems are quite a bit more abstract but I believe the author just wanted us to get familiar with higher-order functions. The more I get into Scala the more I start to agree with Jim McBeath on the pros and cons. However, it seems like quite a bit of work is being put into the scala IDE for Eclipse and the IntelliJ scala plugin (which is what I'm using currently). Also, Martin Ordesky has created a company to address the 'commercial support' concern but many more companies would have to provide scala services for this to fall off the con list, I agree.
object FoldingStrings extends Application {
val strings = List("this", "is", "a", "list", "of", "strings")
// initValue + code block
val sum1 = (0 /: strings) { (sum, string) => sum + string.length}
// with currying
val sum2 = strings.foldLeft(0)((sum, string) => sum + string.length)
// should print 20/20 vision
println(sum1 + "/" + sum2 + " vision")
// foul sentence
val sentence = List("Darn", " ", "it!", " ", "Get", " ", "at", " ", "em,", " ", "Shoot")
val foulMouthPerson = new FoulMouth
// should print 'Beans it! Get at em, Pucky'
foulMouthPerson saySomethingCensored sentence
}
class FoulMouth extends Censor {
def saySomethingCensored(sentence:List[String]) { println(censor(sentence)) }
}
trait Censor {
val alternatives = Map("Shoot" -> "Pucky", "Darn" -> "Beans")
def censor(words : List[String]) : String = {
// wonder if this is what the author intended
words.foldLeft("")((sentence, word) => sentence + alternatives.getOrElse(word, word))
}
}
