JQD
JQD

Reputation: 73

Haskell Fibonacci up to maximum specified number?

I have a Haskell function that's up and running, but it's doing the wrong thing.

It's supposed to output a Fibonacci sequence up to the maximum number specified.

Like this:

fibonacciSequence 86
1 1 2 3 5 8 13 21 33 54

My code is currently outputting the first 10 numbers in a Fibonacci sequence instead of a Fibonacci sequence from 1 to 10.

It's outputting 1 1 2 3 5 8 13 21 33 54, but it should be 1,1,2,3,5,8.

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n - 2)

---print (fib n)
fibList n = map fib[1..n]

main = 
do
putStrLn "The fibonacci series from 1 to n is:"
print (fibList 10)

Any help would be greatly appreciated. Thanks!

Upvotes: 2

Views: 524

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

A more efficient way, is to generate an (infinite) list of Fibonnacci numbers:

fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

then we can stop the list from the moment one of the lists is greater than 10 with takeWhile :: (a -> Bool) -> [a] -> [a]:

takeWhile (<= 10) fibs

this is more efficient since we do not need to start from zero for each Fibonacci number. Furthermore it constructs the k-th item in O(k) time.

Upvotes: 8

developer_hatch
developer_hatch

Reputation: 16224

You want to take fibonacci numbers while they are less than 10, so:

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

fibList = map fib [0..]

takeWhile (<=10) fibList

---> [0,1,1,2,3,5,8]

Upvotes: 5

Related Questions