I have written the following code which creates an infinite list of Fibonacci numbers:
fibs = 1:1:fib 1 1
where fib a b = a+b:fib b (a+b)
I don't know if it's possible to create infinite lists with foldl
. You could perhaps solve this problem by using foldr
, but then you would have to create another list to fold over. What would that list be? There is nothing with the fibonacci numbers that suggest they are generated from some other list.
What you want instead is to use unfoldr
. It can be used to create lists instead of consuming them, as is the case for foldl
and foldr
. Here's how you would use unfoldr
to generate the infinite list of fibonacci numbers.
fib = unfoldr (\(a,b) -> Just (a,(b,a+b))) (1,1)
You can find unfoldr
in the module Data.List
in the base package.