Created
December 4, 2016 02:02
-
-
Save wkimeria/2b67e88aa0138728382e97fed377af04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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