可以使用折叠创建无限列表吗? [英] Can fold be used to create infinite lists?

查看:108
本文介绍了可以使用折叠创建无限列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的代码,它创建了斐波那契数列的无限列表:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆