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... )
Comments 3
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
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
main = print (sum (takeWhile (<=4000000) (filter even fibs)))
Reply
Leave a comment