Last active
November 15, 2015 20:42
-
-
Save andrewharmellaw/af92836315a405efb63f to your computer and use it in GitHub Desktop.
Implementation and simple trace of a foldRight (from Functional Programming in Scala, chapter 3)
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
def foldRight[A,B](as: List[A], b: B)(f: (A, B) => B): B = | |
as match { | |
case Nil => b | |
case Cons(x, xs) => f(x, foldRight(xs, b)(f)) | |
} | |
foldRight(List(1, 2, 3)) ((x,y) => x + y) | |
foldRight(Cons(1, Cons(2, Cons(3, Nil))), 0) ((x,y) => x + y) | |
1 + foldRight(Cons(2, Cons(3, Nil)), 0) ((x,y) => x + y) | |
1 + (2 + foldRight(Cons(3, Nil), 0) ((x,y) => x + y)) | |
1 + (2 + (3 + (foldRight(Nil, 0) ((x,y) => x + y)))) | |
1 + (2 + (3 + 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment