Project Euler in Haskell, Problem 2:

Nov 15, 2009 11:51

I've started teaching myself Haskell by going through the Project Euler problems. This is problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be ( Read more... )

euler, haskell

Leave a comment

Comments 3

mbrubeck November 15 2009, 22:46:19 UTC

Here's mine, which is a little more gratuitously "cute":

fibs = 0 : 1 : zipWith (+) fibs (drop 1 fibs)
main = print $ sum $ takeWhile (<=4000000) $ filter even fibs

This definition of "fibs" is a classic, and worth understanding. takeWhile is a prelude function that's equivalent to (listUntil . not). Note also that the the "do" in your main has no effect.

I didn't notice at the time that every third element is even. I guess with a little arithmetic there's probably a much much cuter form...

Reply

marvinalone November 15 2009, 23:07:40 UTC
Ah, this is exactly why I'm doing this. I didn't know about takeWhile and zipWith, and I'm not that comfortable yet with $. Thank you.

While your definition of the Fibonacci sequence (starting with 0, 1) is more correct (in my book, at least), the problem says it starts with 1, 2. It doesn't matter for this problem, since 1 is odd, but I wanted to be "to the letter". No argument that your form is nicer than mine though :-)

Reply

mbrubeck November 15 2009, 23:12:34 UTC
I tend to think of ($) as an open-paren that doesn't need to be closed. With parens, that function would have been:

main = print (sum (takeWhile (<=4000000) (filter even fibs)))

Reply


Leave a comment

Up