Why do generator expressions return generators?

Domenic Denicola domenic at domenicdenicola.com
Fri Sep 6 10:59:47 PDT 2013


Thanks Allen; I agree those are much better definitions and will incorporate them into an edit.
________________________________
From: Allen Wirfs-Brock [allen at wirfs-brock.com]
Sent: Friday, September 06, 2013 13:45
To: Domenic Denicola
Cc: es-discuss at mozilla.org
Subject: Re: Why do generator expressions return generators?

I was originally going to make a comment about this on your blog post, but this now seems like a better place:

In http://domenic.me/2013/09/06/es6-iterators-generators-and-iterables/ you state the following difinitions:

A generator is a specific type of iterator which also has a throw method, and whose next method takes a parameter.

A generator function is a special type of function that always returns a generator, and which can use the special contextual keyword yield inside of itself. You can send values or exceptions into the body of the function, at the points where yield appears, via the returned generator's next and throw methods. They are created with function* syntax.

While these definitions aren't "wrong" I think they do not emphasizing the most important points.

I would use the following definitions:

A generator is an iterator whose 'next' results are determined by a single function body or expression.  The function body or expression typically includes explicit or implicit 'yield' points which provide the values returned by invocations of the iterator's 'next' method.

A generator function is a function that acts as a factory (or constructor) of a generators with explicit 'yield' points.  The body of a generator function is the function body of the generator.

A generator comprehension is  an expression that evaluates to a generator with an implicit yield point. The expression within a generator comprehension has an implicit yield  and is the expression that provides the values returned by invocations of the iterator's 'next' method.

In other words, the essential difference between generators and the general concept of iterators, it not the presence or absence of the 'throw' method.  Instead it is an authoring difference.  Using generator functions or generator comprehension, a JS programmer can define an iterator as as if it was a single function or expression rather than an explicit state ma;chine.

Allen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130906/2d09f66e/attachment.html>


More information about the es-discuss mailing list