Skip to content

Instantly share code, notes, and snippets.

@jehugaleahsa
Created August 5, 2014 19:21
Show Gist options
  • Save jehugaleahsa/3552c6e2428ac3a287e9 to your computer and use it in GitHub Desktop.
Save jehugaleahsa/3552c6e2428ac3a287e9 to your computer and use it in GitHub Desktop.
Tail Recursion Optimization
private def foldLeftBad[T, TResult](list: List[T], initial: TResult)(folder: (TResult, T) => TResult): TResult = list match {
case Nil => initial
case head :: tail => folder(foldLeftBad(tail, initial)(folder), head)
}
private def foldLeft[T, TResult](list: List[T], initial: TResult)(folder: (TResult, T) => TResult): TResult = {
@tailrec
def foldLeftSoFar(list: List[T], computer: () => TResult): TResult = list match {
case Nil => computer()
case head :: tail => {
val result = computer()
foldLeftSoFar(tail, () => folder(result, head))
}
}
foldLeftSoFar(list, () => initial)
}
// ...
def sum(list: List[Int]): Int = foldLeft(list, 0)(_ + _)
def multiply(list: List[Int]): Int = foldLeft(list, 1)(_ * _)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment