[Haskell-cafe] Fibonacci numbers generator in Haskell
Henning Thielemann
lemming at henning-thielemann.de
Thu Jun 15 16:05:09 EDT 2006
On Thu, 15 Jun 2006, Vladimir Portnykh wrote:
> Fibonacci numbers implementations in Haskell one of the classical examples.
> An example I found is the following:
>
> fibs :: [Int]
> fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)]
>
> To get the k-th number you do the following:
> Result = fibs !! k
>
> It is elegant but creates a list of all Fibonacci numbers less than k-th, and
> the code is not very readable :).
The garbage collector will free storage for values that are no longer
needed. So if the garbage collector is hard working there will be no more
than 2 previous values stored per computation of a new value.
> I wrote my own Fibonacci numbers generator:
>
> fib :: Int -> [Int]
> fib 0 = [0,0]
> fib 1 = [1,0]
> fib n = [sum prevFib, head prevFib] where a = fib (n - 1)
>
> To get the k-th number you do the following:
>
> result = head (fib k)
>
> It does not generate full list of Fibonacci numbers, but keeps only 2
> previous numbers, and has only one recursive call.
> Because the list always has only 2 elements using the functions head and sum
> is a bit overkill.
If you want to do it that way, better use pairs of numbers instead of
lists. Lists can have any number of elements, pairs have exactly two
members. So the latter is more type safe.
More information about the Haskell-Cafe
mailing list