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
-
\$\begingroup\$ Relevant: wiki.haskell.org/The_Fibonacci_sequence \$\endgroup\$Santiago– Santiago2017年01月22日 21:03:57 +00:00Commented Jan 22, 2017 at 21:03
1 Answer 1
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)
Explore related questions
See similar questions with these tags.