Created
August 5, 2014 19:21
-
-
Save jehugaleahsa/3552c6e2428ac3a287e9 to your computer and use it in GitHub Desktop.
Tail Recursion Optimization
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
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