Created
February 25, 2014 14:21
-
-
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.
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
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