Haskell: nested parens vs. dot notation
Problem 2 of Project Euler says: 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.
GHCi parses this solution just fine:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs) p002fibsum x = sum (filter even (takeWhile (< (x+1)) fibs))
...but it has a problem with this one:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs) p002fibsum x = sum . filter even . takeWhile (< (x+1)) fibs Couldn't match expected type `a1 -> [c0]' with actual type `[a0]' In the return type of a call of `takeWhile' Probable cause: `takeWhile' is applied to too many arguments In the second argument of `(.)', namely `takeWhile (< (x + 1)) fibs' In the second argument of `(.)', namely `filter even . takeWhile (< (x + 1)) fibs'
takeWhile seems to take only two params, which seem to be the right amount. Am I failing because of a missing type signature? How can I get this solution to work with dot notation?
The problem is that takeWhile (< (x+1)) fibs has the type [a0] (where a0 is some Num), while the function composition expects a function for its second argument (a1 -> [c0]).
If you want to use dot notation, it would be
p002fibsum x = (sum . filter even . takeWhile (< (x+1))) fibs
though I'd rather use dollar signs:
p002fibsum x = sum $ filter even $ takeWhile (< (x+1)) fibs