Skip to content

Instantly share code, notes, and snippets.

@akanehara
Last active December 10, 2015 05:08
Show Gist options
  • Save akanehara/4385365 to your computer and use it in GitHub Desktop.
Save akanehara/4385365 to your computer and use it in GitHub Desktop.
「fold書けないプログラマー」と聞いてドキっとしたので書いて確かめて気を落ち着かせる
def foldr[A, B](f:(A, B) => B)(z:B)(xs:List[A]):B = {
def go(xs:List[A]):B = xs match {
case Nil => z
case x :: rest => f(x, go(rest))
}
go(xs)
}
def foldl[A, B](f:(A, B) => A)(z:A)(xs:List[B]):A = {
def go(acc:A, xs:List[B]):A = xs match {
case Nil => acc
case x :: rest => go(f(acc, x), rest)
}
go(z xs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment