Skip to content

Instantly share code, notes, and snippets.

@JasonStoltz
Created February 25, 2014 14:21
Show Gist options
  • Save JasonStoltz/9209676 to your computer and use it in GitHub Desktop.
Save JasonStoltz/9209676 to your computer and use it in GitHub Desktop.
Scala tail recursion example. Returns the "nth" position in the fibonacci sequence. Tail recursive because evaluation is completed and passed to next call, nothing else needs to be evaluated after return. This lets scala compiler optimize this.
def fibNum(pos: Int) = {
def go(n: Int, curr: Int, next: Int): Int = {
if (n == 0) curr
else go(n-1, next, curr+next)
}
go(pos, 0, 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment