I have written the following code to generate a list containing the Fibonacci numbers.
fibonacci = [a + b | a <- 1:fibonacci, b <- 0:1:fibonacci]
I would expect the output of the list to be [1,2,3,5,8,13..]
, however, the output is not the Fibonacci sequence.
I can't quite understand why it doesn't work.
My reasoning is that, if the Fibonacci numbers are [1,2,3,5,8,13..]
then this will be equal to the sum of the 2 lists [1,1,2,3,5,8,13..]
and [0,1,1,2,3,5,8,13..]
, which are equivalent to 1:[1,2,3,5,8,13..]
and 0:1:[1,2,3,5,8,13..]
or 1:fibonacci
and 0:1:fibonacci
I have looked up other ways of implementing this sequence, however I would really like to know why my code doesn't work.
fibonacci = 0:1:[a + b | (a:b:_) <- iterate tail fibonacci] = 0:1:[a + b | (a,b) <- zip fibonacci (tail fibonacci)]
. – Will Ness