4 ms·
A generator function can always be implemented via an iterator class, but often the generator is more convenient. Without generators, you manually need to conve
by armchairhacker 3y ago
A generator function can always be implemented via an iterator class, but often the generator is more convenient. Without generators, you manually need to convert loops and conditionals (typical programming) into an explicit state machine (atypical programming, and more verbose)
Your example in Python:
class Pow2:
def __init__(self, n):
self.value = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.value < self.n:
ans = self.value * self.value
self.value += 1
return ans
else:
raise StopIteration
iter(Pow2(n))
is semantically equivalent to
def pow2(n):
value = 0
while value < n:
yield value * value
value += 1
pow2(n)
and
(i * i for i in range(n))
but both the generators are a lot less code.
The generator expression (last one) can actually be implemented right now in Java streams (something like `IntRange::to(n).map(i => i * i)`). But the generator functions which use `yield` are necessary for more complex expressions: the ones which have nested loops, resources, exceptions, etc. which are even more verbose when converted into generator classes