Generating Infinite List of Fibonacci Numbers

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. Thanks in advance. drjoliv

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
participants (2)
-
Desonte Jolivet
-
Harald Bögeholz