code
Functional fibonacci numbers
On 01, Nov 2011 | No Comments | In code, Uncategorized | By admin
There are many ways to calculate the fibonacci numbers sequence in scala, but I really like this one:
def fibs(n:Int)= {
lazy val fibSeq:Stream[Int] = 0 #:: 1 #:: (fibSeq zip fibSeq.tail).map{ case (a,b) => a+b }
fibSeq.take(n).toList
}
#:: is the lazy cons method, and fibs zip fibs.tail creates a stream of pairs with the latest two numbers in the sequence.
In haskell it can be even more compact:
fib :: Int -> Integer
fib n = fibs !! n
where
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

Submit a Comment