Last active
July 9, 2016 18:17
-
-
Save Krasnyanskiy/09d35e805e1f797562a0ee39cee7f89f to your computer and use it in GitHub Desktop.
-scala: naive Fibonacci
This file contains hidden or 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(i: Int): Int = i match { | |
case 0 => 0 | |
case 1 => 1 | |
case x if x > 1 | |
=> fib(i - 1) + fib(i - 2) | |
case _ => throw new IllegalArgumentException | |
} |
Via For-Comprehension
def fib(i: Int): Option[Int] = i match {
case 0 => 0.some
case 1 => 1.some
case x if x > 1
=> for { a <- fib(i - 1); b <- fib(i - 2) } yield a + b
case _ => None
}
println(fib(-1)) // would return None
println(fib(10)) // would return Some(55)
Optimized version
import scalaz._, Scalaz._
def fib(n: Int) = {
var xs = Array[BigInt](0, 1)
var idx = 1
for (i <- BigInt(2) to n) {
xs = xs :+ i
idx += 1
xs(idx) = xs(idx - 1) + xs(idx - 2)
}
xs.last
}
fib(15).print
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fix Fibonacci function using Option and Scalaz