3
\$\begingroup\$

I'm just starting to look into Haskell. I've written a naive Fibonacci implementation, and I've also written a more advanced one that uses tail-call recursion for efficiency.

module Fibonacci where
import System.Environment
fibonacci :: Integer -> Integer
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n
 | n < 0 = error "Cannot find a negative fibonacci number"
 | otherwise = fibonacci (n - 1) + fibonacci (n - 2)
fibonacci' :: Integer -> Integer
fibonacci' n
 | n < 0 = error "Cannot find a negative fibonacci number"
 | otherwise = fibHelper n 0 1
 where
 fibHelper :: Integer -> Integer -> Integer -> Integer
 fibHelper n a b
 | n == 0 = a
 | otherwise = fibHelper (n - 1) b (a + b)
firstNumberFrom :: [String] -> Integer
firstNumberFrom [] = 10
firstNumberFrom args = read $ args !! 0
main = do
 args <- getArgs
 let num = firstNumberFrom args in
 putStrLn $ show (fibonacci' num)

I'd appreciate any reviews on correctness and idiomatic usage.

200_success
146k22 gold badges190 silver badges479 bronze badges
asked May 5, 2018 at 18:29
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What is your purpose behind implementing a naive fibonacci function? Are you familiar with its the limitations? Are you familiar with more efficient fibonacci algorithms? \$\endgroup\$ Commented May 5, 2018 at 18:47
  • 1
    \$\begingroup\$ The Haskell wiki has an article with many different Fibonacci implementations: wiki.haskell.org/The_Fibonacci_sequence \$\endgroup\$ Commented May 5, 2018 at 18:50

1 Answer 1

2
\$\begingroup\$

The many approaches in main and firstNumberFrom can be unified:

main = print . fibonacci' . maybe 10 read . listToMaybe =<< getArgs

The explicit recursion in fibbonacci' is captured by iterate:

fibbonacci' n = fst $ iterate (\(a,b) -> (b, a+b)) (0,1) !! n
answered May 8, 2018 at 19:47
\$\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.