Though I would post up some of the exercises I have been working on to help me understand functional programming in Scala. These exercies were given to me by tony Morris to help me get my head around function programing.
1. Create a flat map using a foldRight
solution:
def myFlatMap[I, J](l : List[I], f: I => List[J] ) : List[J] = {
l.foldRight(Nil : List[J])((a,b) => (f(a) ::: b ) )
}
2. Create concatenation for a cons list (:::) using a foldRight
solution:
def append[X](xs: List[X], ys: List[X]): List[X] = {
xs.foldRight(ys)(_ :: _)
}
3. Create concatenation using matcher and recursion
solution:
def append2[X](xs: List[X], ys: List[X]): List[X] = xs match {
case Nil => ys
case x :: xs => {
x :: append2(xs, ys)
}
}
4. Find the max int in a list
solution :
def getMaxInt(xs : List[int]) : int = xs match {
case Nil => error("error")
case x :: xs =>
xs.foldLeft(x)((b,a) => if ( a > b) a else b )
}
-
1 comment:
Yo Raf, note also that scala.List has reduceRight and reduceLeft functions. http://www.scala-lang.org/docu/files/api/scala/List.html#reduceLeft%28%28B%2CB%29%3D%3EB%29
These are a specialisation of foldRight and foldLeft. While you can write max with foldLeft, you might also consider using the more specialised reduceLeft.
By "specialised" I mean reduceLeft can be written in terms of foldLeft, but not the other way around.
Post a Comment