可以使用折叠创建无限列表吗? [英] Can fold be used to create infinite lists?
问题描述
我写了下面的代码,它创建了斐波那契数列的无限列表:
fibs = 1:1:fib 1 1
where fib ab = a + b:fib b(a + b)
Can使用 foldl
或 foldr
来避免递归?
我不知道是否可以使用 foldl
创建无限列表。你也许可以通过使用 foldr
来解决这个问题,但是你必须创建另一个列表来折叠。那个清单会是什么?斐波纳契数字并没有表明它们是从其他列表生成的。
你想要的是使用 unfoldr
。它可以用来创建列表而不是使用它们,就像 foldl
和 foldr
一样。以下是如何使用 unfoldr
生成斐波纳契数字的无限列表。
<$ c $ (b,a + b)))(1,1)
您可以在模块 Data.List
中找到 unfoldr
基础包。
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)
Can the above code be written using foldl
or foldr
to avoid recursion?
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.
这篇关于可以使用折叠创建无限列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!