1
\$\begingroup\$

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)
 where
 next x y = sxy : (next y sxy)
 where
 sxy = x + y
main = do
 putStrLn $ show $ sum $ filter odd $ takeWhile (< 4000000) fibonacci
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 22, 2017 at 20:38
\$\endgroup\$
1

1 Answer 1

4
\$\begingroup\$

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)
answered Jan 22, 2017 at 23:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.