Fibonacci series in haskell

So I was tired of doing (boring) stuff, and all – so I decided to take up a new challenge, the Project Euler. To sweeten the deal, I’ve decided that I’d use only Haskell to solve them.

The second question is to generate the sum of even terms of Fibonacci series. I’m going to show how the series is generated , and thus the following is – not – the solution to the problem. I’ve assumed that the highest term generated should be less than 15000, in this snippet.

takeWhile (\(x, y) -> x < 15000) (iterate (\(x, y) -> (x+y, x)) (1, 0))

Let me break it down –

1. \  syntax is used to define a lambda. So we define two lambdas in this snippet, one for incrementing the series, and other for checking

2. Iterate function is used to generate newer terms from existing terms by using a function.

3. takeWhile is used to pick out elements from a list till the condition is satisfied.

Now, the iterate function produces an infinite list, which is bounded by using takeWhile function.

Test run:

Prelude> takeWhile (\(x,y) -> x < 15000) (iterate (\(x, y) -> (x+y, x)) (1, 0))

[(1,0),(1,1),(2,1),(3,2),(5,3),(8,5),(13,8),(21,13),(34,21),(55,34),(89,55),(144,89),(233,144),(377,233),(610,377),(987,610),(1597,987),(2584,1597),(4181,2584),(6765,4181),(10946,6765)]

As you can see, a list of tuples of fibonacci’s series are generated.

That’s it for now. Hopefully I’ve written something that makes sense 😉

PS: Interestingly, wordpress.com’s source highlighting plugin does not support haskell – so if anybody is listening, please add it soon!

Standard