Skip to content

Instantly share code, notes, and snippets.

@Krasnyanskiy
Last active July 9, 2016 18:17
Show Gist options
  • Save Krasnyanskiy/09d35e805e1f797562a0ee39cee7f89f to your computer and use it in GitHub Desktop.
Save Krasnyanskiy/09d35e805e1f797562a0ee39cee7f89f to your computer and use it in GitHub Desktop.
-scala: naive Fibonacci
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
}
@Krasnyanskiy
Copy link
Author

Krasnyanskiy commented Jul 9, 2016

Fix Fibonacci function using Option and Scalaz

import scalaz._, Scalaz._

def fib(i: Int): Option[Int] = i match {
  case 0 => 0.some
  case 1 => 1.some
  case x if x > 1 
         => fib(i - 1) >>= { a => fib(i - 2) >>= { b => (a + b).some } }
  case _ => None
}

@Krasnyanskiy
Copy link
Author

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
}

@Krasnyanskiy
Copy link
Author

println(fib(-1)) // would return None
println(fib(10)) // would return Some(55)

@Krasnyanskiy
Copy link
Author

Krasnyanskiy commented Jul 9, 2016

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