Skip to content

Instantly share code, notes, and snippets.

@wkimeria
Created December 4, 2016 02:02
Show Gist options
  • Save wkimeria/2b67e88aa0138728382e97fed377af04 to your computer and use it in GitHub Desktop.
Save wkimeria/2b67e88aa0138728382e97fed377af04 to your computer and use it in GitHub Desktop.
/*
Like `foldRight` for lists, `fold` receives a "handler" for each of the data constructors of the type, and recursively
accumulates some value using these handlers. As with `foldRight`, `fold(t)(Leaf(_))(Branch(_,_)) == t`, and we can use
this function to implement just about any recursive function that would otherwise be defined by pattern matching.
*/
def fold[A,B](t: Tree[A])(f: A => B)(g: (B,B) => B): B = t match {
case Leaf(a) => f(a)
case Branch(l,r) => g(fold(l)(f)(g), fold(r)(f)(g))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment