Scala and Fibonacci

Posted on Saturday, June 14, 2014


After doing a few neat one liners in Scala I wondered what was a slick way to calculate the Fibonacci numbers using Scala.


The simplest solution was made by Luigi Plinge. And here it is




val fibs: Stream[Int] = 0 #:: fibs.scanLeft(1)(_ + _)




And if you want the first 20 Fibonacci numbers just call it like this..



fibs.take(20).foreach(println)



Which will return



 
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181


I just thought that was pretty cool.  I am really liking Scala for making complex one liners that are relatively easy to read (once you get up to speed)



References
[1]        Stackoverflow Fibonacci discssion
                Accessed 06/2014



No comments:

Post a Comment