sum(Nil) = 0
sum(head :: tail) = head + sum(tail)
def sum(list: List[Int]): Int =
if (list.isEmpty) 0
else list.head + sum(list.tail)
def sum(list: List[Int]): Int = list match {
case Nil => 0
case head :: tail => head + sum(tail)
}
sum(tree) = node.value
+ sum(leftTree) + sum(rightTree)
leftTree rightTree
+
node.value
8
6 10
4 7 E 12
E E E E E E
sum(empty) = 0
sum(tree) = node.value + sum(left) + sum(right)
trait Tree
case class Node(value: Int,
left: Tree,
right: Tree) extends Tree
case object Empty extends Tree
def sum(tree: Tree): Int = tree match {
case Empty => 0
case n: Node =>
n.value + sum(n.left) + sum(n.right)
}
def sum(list: List[Int]): Int = list match {
case Nil => 0
case head :: tail => head + sum(tail)
}
def sum(list: List[Int]): Int = {
def loop(acc: Int, l: List[Int]): Int = l match {
case Nil => acc
case head :: tail => loop(acc + head, tail)
}
loop(0, list)
}
• Functional Programming Principles in Scala
Scala Martin Odersky
https://www.coursera.org/course/progfun
•
OCaml
http://www.amazon.co.jp/dp/4781911609