Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Last active June 29, 2018 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryuheechul/7e49de5c07e468c5835bf65431211a70 to your computer and use it in GitHub Desktop.
Save ryuheechul/7e49de5c07e468c5835bf65431211a70 to your computer and use it in GitHub Desktop.
FP in Scala exercises in Chapter 2
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