Commit 95d5724a authored by Haochen Xie's avatar Haochen Xie

add ch3/Tree.scala

parent b6e711f0
package name.haochenxie.fpscala.ch3
/**
* Created by haochen on 2017/01/22.
*/
sealed trait Tree[+A]
case class Leaf[A](v: A) extends Tree[A]
case class Branch[A](l: Tree[A], r: Tree[A]) extends Tree[A]
object Tree {
// Exercise 3.25
def size[A]: Tree[A] => Int = {
case Leaf(_) => 1
case Branch(l, r) => size(l) + size(r) + 1
}
// Exercise 3.29
def reduce[A,B](tr: Tree[A])(leafCase: A => B)(branchCase: (B, B) => B): B = tr match {
case Leaf(v) => leafCase(v)
case Branch(l, r) => {
def red: Tree[A] => B = reduce(_)(leafCase)(branchCase)
branchCase(red(l), red(r))
}
}
// Exercise 3.26
def maximum(tr: Tree[Int]): Int = reduce(tr)(identity)((x, y) => x max y)
// Exercise 3.27
def depth[A](tr: Tree[A]): Int = reduce[A,Int](tr)($=>1)((x, y) => (x max y) + 1)
// Exercise 3.28
def map[A,B](tr: Tree[A])(f: A => B): Tree[B] =
reduce[A,Tree[B]](tr)(v => Leaf(f(v)))(Branch(_, _))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment