[Haskell-beginners] Generating Infinite List of Fibonacci Numbers

Harald Bögeholz bo at ct.de
Wed Jun 29 06:27:53 UTC 2016


Am 29.06.16 um 05:39 schrieb Desonte Jolivet:
> 
> Hi,
> 
> Problem: I would like to generate an infinite list of Fibonacci numbers. Although the below code does not work.
> 
> fibs :: [Integer]fibs = 0 : 1 : [ n | x <-[2..], let n = ((fibs !! x-1) + (fibs !! x-2))]
> 
> Thought: I'm assuming that I'm ignorant on how ranges/generators work with a list comprehension, which is why this code is not working.
> 
> ghci output:
> *Main> fibs !! 01*Main> fibs !! 12*Main> fibs !! 2 
> When I try and access the third element in the list ghci simply stalls.
> Can someone please give me a little more insight on why my code is not working.

You need to insert parentheses:

Prelude> let fibs = 0 : 1 : [ n | x <-[2..], let n = ((fibs !! (x-1)) +
(fibs !! (x-2)))]
Prelude> take 50 fibs
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049]

Btw a probably more efficient way to generate this list is

Prelude> let fibs' = 0 : 1 : zipWith (+) fibs' (tail fibs')
Prelude> take 50 fibs'
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049]


Cheers
Harald

-- 
Harald Bögeholz    <bo at ct.de> (PGP key available from servers)
Redaktion c't      Tel.: +49 511 5352-300  Fax: +49 511 5352-417
                   http://www.ct.de/

                   int f[9814],b,c=9814,g,i;long a=1e4,d,e,h;
                   main(){for(;b=c,c-=14;i=printf("%04d",e+d/a),e=d%a)
                   while(g=--b*2)d=h*b+a*(i?f[b]:a/5),h=d/--g,f[b]=d%g;}
                                                          (Arndt/Haenel)

                   Affe Apfel Vergaser

/*Heise Medien GmbH & Co. KG * Karl-Wiechert-Allee 10 * 30625 Hannover
Registergericht: Amtsgericht Hannover HRA 26709
Persönlich haftende Gesellschafterin: Heise Medien Geschäftsführung GmbH
Registergericht: Amtsgericht Hannover, HRB 60405
Geschäftsführer: Ansgar Heise, Dr. Alfons Schräder*/


More information about the Beginners mailing list