3 ms·
That would turn Symbol.iteratorDone into a dangerous value, that can't safely be yielded from a generator, or included in an array, or passed to a variadic func
by duckerude 8y ago
That would turn Symbol.iteratorDone into a dangerous value, that can't safely be yielded from a generator, or included in an array, or passed to a variadic function.
I don't know if that would be much of a problem in practice but it feels wrong instinctively.
- tonyg 8y agoExactly. `Symbol.iteratorDone` would be a kind of "null" value. The existing approach is equivalent to returning Either<a,b> in a language with labelled sums; it carefully distinguishes between the envelope and the payload, if you like.
- anonytrary 8y agoThese are all great points. I didn't immediately consider: [1,2, Symbol.iteratorDone, 3] which would definitely break on something like that. It would seem the only real way to fix this is with a distinct wrapper.
- duckerude 8y agoPython's solution is to throw a StopIteration exception when the iterator runs out. That works out ok as long as you don't manually throw it in weird places, but a naive implementation could have high overhead because exceptions are expensive. PHP's iterators have separate methods for advancing to the next element, checking if there's a current element, and getting the current element. That's cumbersome, and requires keeping extra state, but it's abstracted over so it doesn't typically matter. I think it mimics a bizarre old way of iterating through arrays. There are multiple ways to signal the end. Javascript's is pretty clean.
- anonytrary 8y agoOof, I'd definitely take JavaScript's wrapper objects over an exception. Iteration complete isn't something that strikes me as an error, it's just the end of the finite list you're iterating over! Does the program expect the list to never end or something? Errors should be reserved for the unexpected. A list ending is very expected, unless you're dealing with an infinite generator.
- duckerude 8y agoPython uses exceptions more casually than many other languages. It follows EAFP. Exceptions don't have to be very exceptional. Doing it like that would be out of place in many languages with different sensibilities, but it fits ok in Python. It also helps that you rarely deal with StopIteration exceptions directly or even have to remember they're used under the hood.