使用流生成具有交替符号的数字的更好解释
这里的代码可以生成这样的数字 [1 -2 3 -4 5 -6 7 -8 9 -10 ...]
(define (integers-starting-from n)
(cons-stream n (stream-map - (integers-starting-from (+ n 1)))))
我不太明白它生成交替符号的方式。 有人可以给我一个更好的描述来帮助我形象化这一点吗?
您可以在 mit-scheme 中运行代码。
The code here can generate numbers like this [1 -2 3 -4 5 -6 7 -8 9 -10 ...]
(define (integers-starting-from n)
(cons-stream n (stream-map - (integers-starting-from (+ n 1)))))
I don't quite understand the way it generates alternating signs.
Can someone please give me a better description to help me visualise this?
You can run the code in mit-scheme.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们这样想:
为了生成一个无限的整数流,我们想要这样做
这会像这样(从 n=1 开始):
现在,让我们假设我们从第二个位置取出所有元素,并反转它们的符号:
让我们对第三个位置执行相同的操作:
再重复两次,每次从下一个位置开始:
如我们所见,如果在每个元素之后添加整数流的其余部分,则在反转其符号后(反转流的其余部分的符号),我们将得到您想要的 - 具有交替符号的整数流。每次我们在流的其余部分上使用
stream-map
和-
来反转它的符号,其中“流的其余部分”只是从开始的流>(+ n 1)
。用
cons-stream
将其全部包装起来,您就应该拥有它了。Let's think of it like this:
Too generate a infinite stream of integers, we would want to do
This would like something like this (for starting with n=1):
Now, let's assume that we take all the elements from the second place, and invert their sign:
Let's do the same for the third place and on:
Repeat twice more, each time beginning at the next place:
As we can see, if after each element we add the rest of the integer stream, after inverting it's sign (inverting the sign of the rest of the stream), we will get exactly what you wanted - a stream of integers with alternating signs. Each time we use
stream-map
with-
on the rest of the stream to invert it's sign, where the "rest of the stream" is just the stream starting from(+ n 1)
.Wrap it all up with
cons-stream
and you should have it.正在做两件事,首先是
cons-stream
值n
和评估(stream-map - (integers-starting-from (+ n 1 )))
这恰好是流的反转,因为-
的单子情况是否定。这就是你的交替模式。从函数名称看来您正在寻找更像这样的东西
is doing two things, firstly it's
cons-stream
the valuen
and the value form evaluating(stream-map - (integers-starting-from (+ n 1)))
which happens to be inversion of the stream as the monadic case of-
is to negate. Thus your alternating pattern.From the function name it appears you are looking for something more like this