Skip to content

Instantly share code, notes, and snippets.

@daltonhuynh
Created May 22, 2011 03:08
Show Gist options
  • Save daltonhuynh/985136 to your computer and use it in GitHub Desktop.
Save daltonhuynh/985136 to your computer and use it in GitHub Desktop.
pattern matching in scala (map/fold)
// simple map and fold left/right implementations
// in scala using pattern matching for List[Int]
def map(list:List[Int], f:(Int) => Int):List[Int] = {
list match {
case Nil => Nil
case head::tail => f(head)::map(tail, f)
}
}
def foldRight(list:List[Int], initVal:Int, f:(Int, Int) => Int):Int = {
list match {
case Nil => initVal
case head::tail => f(head, foldRight(tail, initVal, f))
}
}
def foldLeft(list:List[Int], initVal:Int, f:(Int, Int) => Int):Int = {
list match {
case Nil => initVal
case head::tail => foldLeft(tail, f(initVal, head), f)
}
}
// quick tests
val list = List(1, 2, 3, 4)
val addOne = (x:Int) => x + 1
val myMap = map(list, addOne)
val libMap = list.map(addOne)
println("Map: %s = %s, %s".format(myMap, libMap, myMap == libMap))
val subtract = (x:Int, y:Int) => x - y
val myFoldR = foldRight(list, 0, subtract)
val libFoldR = list.foldRight(0)(subtract)
val myFoldL = foldLeft(list, 0, subtract)
val libFoldL = list.foldLeft(0)(subtract)
println("Fold Right: %d = %d, %s".format(myFoldR, libFoldR, myFoldR == libFoldR))
println("Fold Left: %d = %d, %s".format(myFoldL, libFoldL, myFoldL == libFoldL))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment