5 ms·
I honestly think the opposite. When I learned generators from Python the understanding of “a function that yields instead of returns” was very easy to grasp. A
by jayflux 4y ago
I honestly think the opposite.
When I learned generators from
Python the understanding of “a function that yields instead of returns” was very easy to grasp. And considering I already knew how functions worked & what their syntax was this was just an extra step (rather than starting from scratch). ECMAscript have taken a similar path to Python here.
This could also be because my mental model is they are just functions that have the ability to return to the stack at a later point in time, rather than “running to completion”.
- throwawaymaths 4y agoWell maybe it's my small brain but I remember in math class it was very important that "a function has only one return value", which probably is part of why I was confused.
- WorldMaker 4y agoTechnically generators still only have one return value: an Iterable. That Iterable represents an object with a "next()" callback and you can entirely write by hand Iterables as simple dumb objects if you like. (The generator function syntax makes it a lot easier to build complex state machines, but most languages aren't going to stop you if you prefer to write your state machine by hand.)
- Dylan16807 4y agoThe mathematical definition of function also rejects all side-effects, so probably not the best thing to use around programming. Call it a routine instead?
- int_19h 4y agoWe had a descriptive yet very generic term for function-like stuff: "subprogram".
- throwawaymaths 4y agoOh man that brings memories: gosub in basic (though I think it was subroutine). Also Pascal had procedures vs functions.
- Waterluvian 4y agoYup, I can see that! One issue I have is that my model of the stack is that "it's a literal _stack_ of frames. You pop them one by one, executing them." What happens to a frame that you pause? Does it get set aside? Is it still on the stack?
- hundt 4y agoThis article[0] and a clarifying comment[1] answer the question for JS. I think it's the same for Python. Apparently your model (which was mine, too) is out of date! [0] https://hacks.mozilla.org/2015/05/es6-in-depth-generators/ https://hacks.mozilla.org/2015/05/es6-in-depth-generators/ [1] https://hacks.mozilla.org/2015/05/es6-in-depth-generators/#comment-17692 https://hacks.mozilla.org/2015/05/es6-in-depth-generators/#c...
- int_19h 4y agoThis kind of thing shows up around several other related PL features, so much so that it has a name: https://wiki.c2.com/?SpaghettiStack https://wiki.c2.com/?SpaghettiStack