kriskowal / gtor

A General Theory of Reactivity
MIT License
3.03k stars 109 forks source link

Off by one error in echo example #32

Closed ndkrempel closed 6 years ago

ndkrempel commented 9 years ago

In the *echo() generator function example:

After .next(x), the value x is the next value yielded, so the expect calls are all off by one.

bergus commented 9 years ago

Good catch. I guess the example should be

function *echo() {
    var message,
        message2 = function.next; // the value of the first .next() call
    while (true) {
        message1 = yield message1;
        message2 = yield message2;
    }
}

or, if we wanted to get fancy and use a single yield only,

function *echo() {
    var messages = [ , function.next];
    while (true) {
        messages.push(yield messages.shift());
    }
}
kriskowal commented 9 years ago

The error is in fact a good catch. However, since the point of the example is to illustrate the behavior of the generator from a very basic implementation, the resolution is to fix the expected behavior and surrounding prose, hopefully without crippling the point. Thanks for pointing this out.

Gahen commented 6 years ago

Do you mind if I attempt a PR to fix this?

kriskowal commented 6 years ago

@Gahen You’re welcome to. See my prior note.

Gahen commented 6 years ago

@kriskowal Ok so I didn't wanted to change the code spirit because I would need to remove/rewrite most of the accompanying text, so I made a simpler fix and added an extra line just to complete the execution described. It would be like this:

function *echo() {
    var message, tmp_message, old_message;
    while (true) {
        message = yield old_message;
        old_message = tmp_message;
        tmp_message = message; 
    }
}
 We then populate the message variable with a value, receiving its former
 undefined content again.
+After that we take the value that was yielded before and save it for the next
+iteration.