4 ms·
The traversal example is a bit weird. There's a simple solution to what the author wanted. Replace `print(root.value)` with `yield root.value`. Now you've got a
by viraptor 7y ago
The traversal example is a bit weird. There's a simple solution to what the author wanted. Replace `print(root.value)` with `yield root.value`. Now you've got a simple algorithm where the caller can decide what to do with the values. And it nicely resembles every kind of iterating things in python. Instead, the object idea makes the algorithm specific to one single use case.
Same with the second example: You can write this as a filter on a function which reads the data. You get a generic reader and a generic filter which can be tested separately.
Twisting the code to fit it into the strategy pattern and preserving some hidden state just to make that possible seems silly to me. Is the class really worth writing instead of composable / reusable / testable / streamable:
def data_reader(fin):
fin.readline()
for line in fin:
yield [int(val) for val in line.split()]
def fill_zero(source):
last_day = 0
for next_day, value in source:
while last_day < next_day - 1:
yield 0
last_day += 1
yield value
last_day = next_day
- edflsafoiewq 7y agoAs far as the general principle goes, an iterator object is a great example of "algorithms as objects" as opposed to "algorithms as monolithic functions".
- viraptor 7y agoFrom the code simplicity POV they're very different though. Sure, an iterator is an object here internally. But continue that way and you'll get to the "objects are closures / closures are objects" discussion.
- edflsafoiewq 7y agoI see the fact that Python has a nice syntax for writing generators as incidental to the main point of "algorithms as objects". In Rust you'd (currently) explicitly write a struct and its next() method, but its still the exact same idea.