Wednesday, October 05, 2011

Scala By Example Chapter 9 Solutions - Exercise 9.4.1

Exercise 9.4.1 Consider a function which squares all elements of a list and re- turns a list with the results. Complete the following two equivalent definitions of squareList.

object ListMap {
def squareList(xs: List[Int]): List[Int] = xs match {
case List() => xs
case y :: ys => y * y :: squareList(ys)
}
def squareListMap(xs: List[Int]): List[Int] =
xs map (x => x * x)
def main(args: Array[String]) {
println("squarelist for square of (9,13,21) returns : " + squareList(List(9, 13, 21)));
println("squareListMap for square of (9,13,21) returns : " + squareList(List(9, 13, 21)));
}
}
view raw ListMap.scala hosted with ❤ by GitHub

No comments: