Skip to content

Instantly share code, notes, and snippets.

@lhoang
Created May 2, 2019 13:52
Show Gist options
  • Save lhoang/2f76399f79a0599ae5fb989e07c6cedb to your computer and use it in GitHub Desktop.
Save lhoang/2f76399f79a0599ae5fb989e07c6cedb to your computer and use it in GitHub Desktop.
Fibonacci in Scala
def fib(p: Int): List[Int] = {
def recFib(list: List[Int], len: Int): List[Int] = {
if (len == 0) {
list
} else {
list match {
case n :: n_1 :: _ => recFib(n + n_1 :: list, len -1)
case _ => recFib(1 :: list, len -1)
}
}
}
recFib(List(0), p).reverse
}
fib(1) == List(0, 1)
fib(2) == List(0, 1, 1)
fib(3) == List(0, 1, 1, 2)
fib(4) == List(0, 1, 1, 2, 3)
fib(5) == List(0, 1, 1, 2, 3, 5)
fib(45)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment