Can fold be used to create infinite lists?

前端 未结 4 1143
执笔经年
执笔经年 2021-01-18 07:00

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)

4条回答
  •  無奈伤痛
    2021-01-18 07:26

    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.

提交回复
热议问题