For the love of Haskell…

Haskell never fails to impress even the mediocre programmer in me.
Here’s something I have attempted solving using Haskell.

Problem –
Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
(Source: Project Euler problem 2)

And here’s the best I could come up with –

import Control.Monad

— Calculate nth fibonacci number using
— fib n = round (((1 + (sqrt 5)) / 2) **
— fromIntegral(n) /
— (sqrt 5))
— Assumes 1,2,3,5,8,…
— So fib n is actually fibonacci(n+1)
— as the formula actually holds for
— 1,1,2,3,5,8,…

fib :: Integer -> Integer
fib n = round ((1.618033988749895) ** fromIntegral(n+1) /2.23606797749979)

main = do
print $ sum . takeWhile (<4000000) $ map fib [2, 5 .. ]

Now, Isn’t that neat? 🙂

Niranjan Nagaraju

I am Vini – Vini The Pooh aka Niranjan. I am a little “sheep in the big city”. A self-proclaimed atheist, freelance writer and cartoonist; The latter two are an avocation as yet, but I believe they really are my medium. Oh, and I code for a living. :)

Leave a Reply

Your email address will not be published. Required fields are marked *