Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better explanation of using stream to generate numbers with alternating signs

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.

like image 810
yang-qu Avatar asked Jun 10 '11 13:06

yang-qu


2 Answers

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.

like image 142
Barak Itkin Avatar answered Nov 19 '22 02:11

Barak Itkin


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

is doing two things, firstly it's cons-stream the value n 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

(define (integers-starting-from n)
  (cons-stream n (integers-starting-from (+ n 1))))
like image 25
zellio Avatar answered Nov 19 '22 04:11

zellio