Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2014
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.61 KB | None | 0 0
  1. def fold[A,B](t: Tree[A])(f: (A) => B, g: (B, B) => B): B = t match {          
  2.   case Leaf(x) => f(x)                                                          
  3.   case Branch(l, r) => g(fold(l)(f, g), fold(r)(f, g))                          
  4. }
  5.  
  6. def max(t: Tree[Int]): Int = fold[Int,Int](t)((x) => x, (x, y) => x.max(y))        
  7.  
  8. def depth[A](t: Tree[A]): Int = fold[A, Int](t)((x) => 1, (x, y) => if (x > y) x+1 else y+1)
  9.  
  10. def size[A](t: Tree[A]): Int = fold[A, Int](t)((x) => 1, (x, y) => x + y)
  11.  
  12. 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