I have just started Haskell, and I want to check if my code is following the spirit of the language.

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

fibonacci :: [Int]
fibonacci = 1 : 1 : (next 1 1)
    next x y = sxy : (next y sxy)
        sxy = x + y

main = do
    putStrLn $ show $ sum $ filter odd $ takeWhile (< 4000000) fibonacci

Just a few things to point out.

There is a prelude function print that is defined print = putStrLn . show.

Additionally, using "do-notation" in this case is unnecessary as you aren't sequencing multiple IO actions.

main can be rewritten in a more point-free style using the function composition operator:

main = print . sum . filter odd . takeWhile (< 4000000) $ fibonacci

I might rewrite fibonacci like this (removes nested where clauses):

fibonacci :: [Int]
fibonacci = next 1 1
  where next x y = x : next y (x + y)

And here are a bunch of other ways to define fibonacci. One interesting way that is possible because of Haskell's laziness:

fibonacci = 1 : 1 : zipWith (+) fibonacci (tail fibonacci)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.