5

这里的代码可以生成这样的数字 [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 中运行代码。

4

2 回答 2

7

Let's think of it like this:

Too generate a infinite stream of integers, we would want to do

(define (integers-starting-from n)
  (cons-stream n (integers-starting-from (+ n 1))))

This would like something like this (for starting with n=1):

(+1 +2 +3 +4 +5 ...)

Now, let's assume that we take all the elements from the second place, and invert their sign:

(+1 -2 -3 -4 -5 ...)

Let's do the same for the third place and on:

(+1 -2 +3 +4 +5 ...)

Repeat twice more, each time beginning at the next place:

(+1 -2 +3 -4 -5 ...)
(+1 -2 +3 -4 +5 ...)

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.

于 2011-06-10T14:11:54.587 回答
1
(cons-stream n (stream-map - (integers-starting-from (+ n 1)))))

正在做两件事,首先是cons-streamn和值形式评估(stream-map - (integers-starting-from (+ n 1)))恰好是流的反转,因为单子情况-是否定的。因此你的交替模式。

从函数名称看来,您正在寻找更像这样的东西

(define (integers-starting-from n)
  (cons-stream n (integers-starting-from (+ n 1))))
于 2011-06-10T14:14:07.177 回答