{-

  Euler #2 in Haskell

  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:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  Find the sum of all the even-valued terms in the sequence which do not 
  exceed four million.
  """

  This program was created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Haskell page: http://www.hakank.org/haskell/


-}

import Data.List
import HakankUtils


euler2a = sum $ filter even $ takeWhile (<4000000) $ fiblist 1 2

-- We have to use f<-[fib(n)] (instead of f <- fib(n) since it's a generator (with one element)
euler2b = sum [f | n <- [1..100], f <- [fib(n)], even f && f < 4000000]

-- From https://wiki.haskell.org/Euler_problems/1_to_10
-- Neat with the zipWith
euler2c = sum [ x | x <- takeWhile (<= 4000000) fibs, even x]
           where
             fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

-- The time is the fastest of two runs
main = do
         -- print euler2a -- (0.01 secs, 89,720 bytes)
         -- print euler2b -- (0.01 secs, 959,704 bytes)
         print euler2c -- (0.00 secs, 89,608 bytes)
         
         
