Guest User

Untitled

a guest
Nov 17th, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. object TailRecursiveTreeFold {
  2.  
  3. sealed trait Tree[A]
  4. case class Leaf[A](value: A) extends Tree[A]
  5. case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
  6.  
  7. def fold[A, B](tree: Tree[A],
  8. f: A => B,
  9. g: (B, B) => B): B = {
  10.  
  11. def helper(rest: List[Tree[A]],
  12. acc: Option[B]): B = rest match {
  13. case Nil => acc.get // trust me
  14. case Leaf(a)::ls if acc.isEmpty => helper(ls, Some(f(a)))
  15. case Leaf(a)::ls => helper(ls, Some(g(acc.get, f(a))))
  16. case Branch(l, r)::ls => helper(r::l::ls, acc)
  17. }
  18.  
  19. helper(List(tree), None)
  20. }
  21. }
Add Comment
Please, Sign In to add comment