Last active
June 29, 2018 07:24
-
-
Save ryuheechul/7e49de5c07e468c5835bf65431211a70 to your computer and use it in GitHub Desktop.
FP in Scala exercises in Chapter 2
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 fib(n: Int): Int = { | |
@annotation.tailrec | |
def go(n: Int, m: Int, acc: Int): Int = | |
if (acc == 0) m | |
else go(m, n+m, acc-1) | |
if (n < 2) 0 | |
else go(0, 1, n-1) | |
} | |
// 1 2 3 4 5 6 7 | |
// 0 1 2 3 5 8 13 | |
assert(fib(2) == 1) | |
assert(fib(5) == 5) | |
assert(fib(7) == 13) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment