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 )
}