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: 1,2,3,5,8,13,21,34,55,89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
WARNING Solution ahead. Don’t read more if you want to enjoy the benefits of Project Euler and you haven’t already solved the problem.
There are many ways to express the Fibonacci sequence in Haskell.
If we choose one of the most famous, which makes good use of Haskell lazy lists:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
We can simply take the Fibonacci numbers up to four million, filter the even ones and sum the result.
solution = (sum . filter even . takeWhile (<4000001)) fibs