简体   繁体   English

Haskell如何生成这个无限列表?

[英]Haskell how to generate this infinite list?

I saw this code to generate Fibonacci numbers. 我看到这段代码生成斐波纳契数。

fibs = 1:1:(zipWith (+) fibs (tail fibs))

Can a similar styled code be written to generate the infinite list [1..]? 是否可以编写类似的样式代码来生成无限列表[1 ..]?

I saw this link on cyclic structures on Haskell site. 我在Haskell网站上的循环结构上看到了这个链接

There an example is given 给出了一个例子

cyclic = let x = 0 : y
         y = 1 : x
     in  x

I tried to define a list for my problem in a cyclic manner, but could not succeed. 我试图以循环方式为我的问题定义一个列表,但是不能成功。 What I want is a list defined in terms of itself and which evaluates to [1..] in Hasekll. 我想要的是一个按照自身定义的列表,并在Hasekll中评估为[1 ..]。

Note: The Haskell [1..] evaluates to [1,2,3,4,5...] and not to [1,1,1...] . 注意:Haskell [1..]计算结果为[1,2,3,4,5...]而不是[1,1,1...]

The following should give you the desired result: 以下应该给你想要的结果:

nats = 1 : map (+1) nats

Or, more idiomatically: 或者,更具有惯用力:

nats = iterate (+1) 1

It's easy to see why the first snippet evaluates to [1,2,3...] by using equational reasoning: 通过使用等式推理,很容易看出为什么第一个片段的评估结果为[1,2,3...]

nats = 1 : map (+1) nats 
     = 1 : map (+1) (1 : map (+1) nats) 
     = 1 : map (+1) (1 : map (+1) (1 : map (+1) nats))
     = 1 : 1 + 1 : 1 + 1 + 1 : .... 
     = [1,2,3...]

Yes. 是。

Think about how you could write out each element of your list: 考虑如何写出列表中的每个元素:

1
1 + 1
1 + 1 + 1
1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1

After each entry, every subsequent entry has an extra + 1 . 每次输入后,每个后续条目都会额外加+ 1 So we want to start at 1 and then add 1 to each subsequent element. 所以我们想从1开始,然后在每个后续元素中加1 Then we want to take the second element and add 1 to everything after that. 然后我们想要获取第二个元素并在之后的所有内容中添加1

Here's how we can do this: 以下是我们如何做到这一点:

let xs = 1 : map (+ 1) xs

This expands like this: 这扩展如下:

1 : map (+ 1) xs
1 : (1 + 1) : map (+ 1) xs
1 : (1 + 1) : ((1 + 1) + 1) : map (+ 1) xs

and so on. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM