Hi again. Sorry for being such a nag!
I've been taking some random problems and trying to tackle them in
Haskell. I got the #2 of the project euler [1], which boils down to:
"By considering the terms in the Fibonacci sequence whose values do
not exceed four million, find the sum of the even-valued terms.".
That is: sum of evens of fibs under some value. Translated to HS as
_M = 4000000
main = putStrLn . show . sum . evens $ underK _M fibs
evens xs = [x | x <- xs, even x]
underK k (x:xs) = (if x < k then [x] else []) ++ underK k xs
-- from [2] ... how does this work anyway?
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Only to find the underK was actually running the whole infinite
elements. Meanwhile I remembered the takeWhile which does what I
want (and actually works) so I changed all to:
_M = 4000000
main = putStrLn . show . sum . filter even $ takeWhile (<_M)
fibs
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Which seems to work ok. How is takeWhile stopping at a given point
and my underK not?
Other question is regarding the "$" and ".". I know the $ has lower
priority and . has more, but is there any more difference that
matters, I mean, can I always use the "$" everywhere. For example,
this main also works:
main = putStrLn $ show $ sum $ filter even $ takeWhile
(<_M) fibs
Is it doing the same thing?
[1]: http://projecteuler.net/problem=2
[2]: http://www.cubbi.org/serious/fibonacci/haskell.html