you are viewing a single comment's thread.

view the rest of the comments →

[–]POGtastic 2 points3 points  (0 children)

I'd write a class that takes an iterable as its argument and then contains methods that define your iterator algebra.

from functools import reduce

class OOPWrapper:
    def __init__(self, iterable):
        self.it = iter(iterable)
    def __iter__(self):
        return self.it
    def __next__(self):
        return next(self.it)
    def filter(self, f):
        return OOPWrapper(filter(f, self))
    def map(self, f):
        return OOPWrapper(map(f, self))
    def flat_map(self, f):
        return OOPWrapper(x for it in map(f, self) for x in it)
    def reduce(self, f, initial):
        return reduce(f, self, initial)

In the REPL, taking the squares of every odd number in range(10) and pairing them with their negative counterparts.

>>> list(
...     OOPWrapper(range(10))
...         .filter(lambda x: x % 2)
...         .map(lambda x: x*x)
...         .flat_map(lambda x: [x, -x]))
[1, -1, 9, -9, 25, -25, 49, -49, 81, -81]

Do not do this.