Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What you have to realize is what we are dealing with here are Generators; a generalized way to create custom Iterators. This article is focusing solely on using Generators for a coroutine system and doesn't elaborate on much so it might seem a bit confusing.

Here's a basic run-down:

You create a Generator Function:

    function NumsUpTo100(start) {
        do {
            yield start;
            start += 1;
        } while (start < 100);
    }
The thing that differentiates this from a regular Function (note: the proposed function* syntax would distinguish it visually as well) is that it actually constructs a new Generator:

    var myGen = NumsUpTo100(20);

myGen now holds a Generator object. You use the arguments to initialize the state of the Generator.

Generators are Iterators, so they really shine in that respect:

    for (var n in NumsUpTo100(50)){
        console.log(n);
    }
However, sometimes you want to manually step through iteration yourself, and you can do that by repeatedly calling .next() on your generator. It will either go forever or eventually throw StopIteration depending on how you wrote it.

AFAIK this article is actually incorrect as you have to call .next() to start the Generator before you can call .send(). Calling send() with no arguments is functionally the same as calling .next(), but last I heard it would throw an error.

The utility of .send() is sometimes during iteration you might want to send information to the generator. For example, maybe you have some sort of state machine in your generator and you want to be able to explicitly reset it's state.

Generators are very useful in general, coroutines is just one fun thing you can do with them.



>Calling send() with no arguments is functionally the same as calling .next(), but last I heard it would throw an error.

I just tried one in Firefox 17, and you can prime it by calling send() with no argument. It objects if there is an argument on the initial send().


Yeah this is a nice advantage of Javascript over Python:

send() is equivalent to send(undefined) which is equivalent to next().

This equivalence is true in Python as well, but you have to explicitly call send(None) which is annoying.


Ah, yes you're right.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: