Skip to content

Instantly share code, notes, and snippets.

@matt-martin
Created August 12, 2015 23:55
Show Gist options
  • Save matt-martin/ea79dca81463ca724ca1 to your computer and use it in GitHub Desktop.
Save matt-martin/ea79dca81463ca724ca1 to your computer and use it in GitHub Desktop.
An example of how tail recursion avoids stack overflow errors
// based on https://github.com/matt-martin/fpinscala/blob/05cd5a2b288677ebc67d258fcfb9c06b63052314/exercises/src/main/scala/fpinscala/datastructures/List.scala#L11
def sumNonTailRecursive(ints: List[Int]): Int = ints match {
case Nil => 0
case x :: xs => x + sumNonTailRecursive(xs)
}
@annotation.tailrec
def sumTailRecursiveHelper(ints: List[Int], sumSoFar: Int): Int = ints match {
case Nil => sumSoFar
case x :: xs => sumTailRecursiveHelper(xs, sumSoFar + x)
}
def sumTailRecursive(ints: List[Int]): Int = sumTailRecursiveHelper(ints, 0);
// works
sumTailRecursive(List((1 to 10000).toSeq:_*))
// doesn't work
sumNonTailRecursive(List((1 to 10000).toSeq:_*))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment