|
| 1 | +from typing import ( |
| 2 | + Any, |
| 3 | + Callable, |
| 4 | + Generic, |
| 5 | + Iterable, |
| 6 | + Optional, |
| 7 | + TypeVar, |
| 8 | + final, |
| 9 | + overload, |
| 10 | +) |
| 11 | + |
| 12 | +from returns.primitives.types import Immutable |
| 13 | + |
| 14 | +_ValueType = TypeVar('_ValueType') |
| 15 | +_NewValueType = TypeVar('_NewValueType') |
| 16 | + |
| 17 | +_AccValueType = TypeVar('_AccValueType') |
| 18 | + |
| 19 | + |
| 20 | +@final |
| 21 | +class Reduced(Immutable, Generic[_ValueType]): |
| 22 | + """ |
| 23 | + Sentinel for early termination inside transducer. |
| 24 | +
|
| 25 | + .. code:: python |
| 26 | +
|
| 27 | + >>> from returns.transducers import tmap, transduce, Reduced |
| 28 | +
|
| 29 | + >>> def add_one(number: int) -> int: |
| 30 | + ... return number + 1 |
| 31 | +
|
| 32 | + >>> def add(acc: int, number: int) -> int: |
| 33 | + ... if acc == 3: |
| 34 | + ... return Reduced(acc) |
| 35 | + ... return acc + number |
| 36 | +
|
| 37 | + >>> my_list = [0, 1, 2] |
| 38 | + >>> assert transduce(tmap(add_one), add, 0, my_list) == 3 |
| 39 | +
|
| 40 | + """ |
| 41 | + |
| 42 | + __slots__ = ('_inner_value',) |
| 43 | + |
| 44 | + _inner_value: _ValueType |
| 45 | + |
| 46 | + def __init__(self, inner_value: _ValueType) -> None: |
| 47 | + """Encapsulates the value from early reduce termination.""" |
| 48 | + object.__setattr__(self, '_inner_value', inner_value) # noqa: WPS609 |
| 49 | + |
| 50 | + @property |
| 51 | + def value(self) -> _ValueType: # noqa: WPS110 |
| 52 | + """Returns the value from early reduce termination.""" |
| 53 | + return self._inner_value |
| 54 | + |
| 55 | + |
| 56 | +@final |
| 57 | +class _Missing(Immutable): |
| 58 | + """Represents a missing value for reducers.""" |
| 59 | + |
| 60 | + __slots__ = ('_instance',) |
| 61 | + |
| 62 | + _instance: Optional['_Missing'] = None |
| 63 | + |
| 64 | + def __new__(cls, *args: Any, **kwargs: Any) -> '_Missing': |
| 65 | + if cls._instance is None: |
| 66 | + cls._instance = object.__new__(cls) # noqa: WPS609 |
| 67 | + return cls._instance |
| 68 | + |
| 69 | + |
| 70 | +#: A singleton representing any missing value |
| 71 | +Missing = _Missing() |
| 72 | + |
| 73 | + |
| 74 | +def transduce( |
| 75 | + xform: Callable[ |
| 76 | + [Callable[[_AccValueType, _ValueType], _AccValueType]], |
| 77 | + Callable[[_AccValueType, _ValueType], _AccValueType], |
| 78 | + ], |
| 79 | + reducing_function: Callable[[_AccValueType, _ValueType], _AccValueType], |
| 80 | + initial: _AccValueType, |
| 81 | + iterable: Iterable[_ValueType], |
| 82 | +) -> _AccValueType: |
| 83 | + """ |
| 84 | + Process information with transducers. |
| 85 | +
|
| 86 | + .. code:: python |
| 87 | +
|
| 88 | + >>> from returns.transducers import tmap, transduce |
| 89 | +
|
| 90 | + >>> def add_one(number: int) -> int: |
| 91 | + ... return number + 1 |
| 92 | +
|
| 93 | + >>> def add(acc: int, number: int) -> int: |
| 94 | + ... return acc + number |
| 95 | +
|
| 96 | + >>> my_list = [0, 1, 2] |
| 97 | + >>> assert transduce(tmap(add_one), add, 0, my_list) == 6 |
| 98 | + """ |
| 99 | + reducer = xform(reducing_function) |
| 100 | + return treduce(reducer, iterable, initial) |
| 101 | + |
| 102 | + |
| 103 | +@overload |
| 104 | +def treduce( |
| 105 | + function: Callable[[_ValueType, _ValueType], _ValueType], |
| 106 | + iterable: Iterable[_ValueType], |
| 107 | + initial: _Missing = Missing, |
| 108 | +) -> _ValueType: |
| 109 | + """Reduce without an initial value.""" |
| 110 | + |
| 111 | + |
| 112 | +@overload |
| 113 | +def treduce( |
| 114 | + function: Callable[[_AccValueType, _ValueType], _AccValueType], |
| 115 | + iterable: Iterable[_ValueType], |
| 116 | + initial: _AccValueType, |
| 117 | +) -> _AccValueType: |
| 118 | + """Reduce with an initial value.""" |
| 119 | + |
| 120 | + |
| 121 | +def treduce(function, iterable, initial=Missing): |
| 122 | + """ |
| 123 | + A rewritten version of :func:`reduce <functools.reduce>`. |
| 124 | +
|
| 125 | + This version considers some features borrowed from Clojure: |
| 126 | +
|
| 127 | + - Early termination |
| 128 | + - Function initializer [TODO] |
| 129 | +
|
| 130 | + You can use it as a normal reduce if you want: |
| 131 | +
|
| 132 | + .. code:: python |
| 133 | +
|
| 134 | + >>> from returns.transducers import treduce |
| 135 | +
|
| 136 | + >>> def add(acc: int, value: int) -> int: |
| 137 | + ... return acc + value |
| 138 | +
|
| 139 | + >>> assert treduce(add, [1, 2, 3]) == 6 |
| 140 | +
|
| 141 | + """ |
| 142 | + it = iter(iterable) |
| 143 | + |
| 144 | + if initial is Missing: |
| 145 | + try: |
| 146 | + acc_value = next(it) |
| 147 | + except StopIteration: |
| 148 | + raise TypeError( |
| 149 | + 'reduce() of empty iterable with no initial value', |
| 150 | + ) from None |
| 151 | + else: |
| 152 | + acc_value = initial |
| 153 | + |
| 154 | + for value in it: # noqa: WPS110 |
| 155 | + acc_value = function(acc_value, value) |
| 156 | + if isinstance(acc_value, Reduced): |
| 157 | + return acc_value.value |
| 158 | + return acc_value |
0 commit comments