Skip to content

Instantly share code, notes, and snippets.

@andrewharmellaw
Last active November 15, 2015 20:42
Show Gist options
  • Save andrewharmellaw/af92836315a405efb63f to your computer and use it in GitHub Desktop.
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)
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