5 ms·
In python/javascript, I'm a big fan of using yield - https://leontrolski.github.io/recursing-with-yield.html https://leontrolski.github.io/recursing-with-yield.
by leontrolski 6y ago
In python/javascript, I'm a big fan of using yield - https://leontrolski.github.io/recursing-with-yield.html https://leontrolski.github.io/recursing-with-yield.html
It just feels nice to me.
- dsego 6y agoWhat are the benefits over the classic way?
- seanhunter 6y agoIt can be a very elegant way to encapsulate annoying complexity in an interface that is easy for callers to use correctly. Typical example: say you need to connect to an api that has pagination. You call it and you get a chunk which has a number of things and a counter of remaining chunks. Normally this king of thing requires the caller to keep a lot of messy state. with yield you can make an interface that the caller can just iterate over and it will give them one thing at a time and fetch the next chunk if the current one is exhausted and there are chunks remaining. The state of the "current chunk", "chunks remaining", index etc can all be enclosed so the caller doesn't need to know anything about them.
- gugagore 6y agoYou could require the caller to keep an opaque handle, and have all the state encapsulated on that handle. The caller won't know if this state is messy or not, and I think this does a good job of encapsulating annoying complexity. But it doesn't prevent the caller from passing the handle to another function, or copying the handle, which could mess things up, and I suppose `yield` helps with that. But most of all, I'd say it makes it easier to write the callee code, not the caller code, since the callee does not need to "reify" the state of "current chunk" and "chunks remaining" into an object, nor (more crucially) the state of loops and other control flow.
- iudqnolq 6y agoAbsolutely. It's like how async can be replaced with a struct and a giant switch statement, but that's a PITA to write manually.