Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def fold[A,B](t: Tree[A])(f: (A) => B, g: (B, B) => B): B = t match {
- case Leaf(x) => f(x)
- case Branch(l, r) => g(fold(l)(f, g), fold(r)(f, g))
- }
- def max(t: Tree[Int]): Int = fold[Int,Int](t)((x) => x, (x, y) => x.max(y))
- def depth[A](t: Tree[A]): Int = fold[A, Int](t)((x) => 1, (x, y) => if (x > y) x+1 else y+1)
- def size[A](t: Tree[A]): Int = fold[A, Int](t)((x) => 1, (x, y) => x + y)
- def map[A,B](t: Tree[A])(f: (A) => B): Tree[B] = fold[A,Tree[B]](t)((x) => Leaf(f(x)), (x, y) => Branch(x, y))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement