|
| 1 | +from typing import Iterable, Any, Generic, TypeVar, Callable, List, Iterator, Generator |
| 2 | + |
| 3 | +T = TypeVar('T') |
| 4 | +S = TypeVar('S') |
| 5 | +R = TypeVar('R') |
| 6 | + |
| 7 | + |
| 8 | +class Filter(Generic[T]): |
| 9 | + def __init__(self, fn: Callable[[T], bool]): |
| 10 | + self._fn = fn |
| 11 | + |
| 12 | + def __call__(self, t: T): |
| 13 | + return self._fn(t) |
| 14 | + |
| 15 | + |
| 16 | +class Map(Generic[S, R]): |
| 17 | + def __init__(self, fn: Callable[[S], R]): |
| 18 | + self._fn = fn |
| 19 | + |
| 20 | + def __call__(self, s: S) -> R: |
| 21 | + return self._fn(s) |
| 22 | + |
| 23 | + |
| 24 | +class FlatMap(Generic[S, R]): |
| 25 | + """ |
| 26 | + Flat map an iterable object |
| 27 | +
|
| 28 | + While code is identical to Map, how it is used is different. |
| 29 | + """ |
| 30 | + def __init__(self, fn: Callable[[S], R]): |
| 31 | + self._fn = fn |
| 32 | + |
| 33 | + def __call__(self, s: S) -> Generator[R, Any, None]: |
| 34 | + yield self._fn(s) |
| 35 | + |
| 36 | + |
| 37 | +class Stream(Generic[T, S]): |
| 38 | + def __init__(self, source: Iterator[T]): |
| 39 | + self._source = source |
| 40 | + self._chain: List[Filter | Map | FlatMap] = [] |
| 41 | + |
| 42 | + def observe(self): |
| 43 | + for item in self._source: |
| 44 | + included = True |
| 45 | + iterated_value = item |
| 46 | + |
| 47 | + for act in self._chain: |
| 48 | + if isinstance(act, Filter) and not act(iterated_value): |
| 49 | + included = False |
| 50 | + break |
| 51 | + |
| 52 | + if isinstance(act, Map): |
| 53 | + iterated_value = act(iterated_value) |
| 54 | + |
| 55 | + if isinstance(act, FlatMap): |
| 56 | + raise NotImplementedError('To be implemented') |
| 57 | + |
| 58 | + if not included: |
| 59 | + continue |
| 60 | + |
| 61 | + yield iterated_value |
0 commit comments