1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
|
from abc import abstractmethod
from collections.abc import Callable, Iterable
from typing import TypeVar, final
from returns.interfaces.applicative import ApplicativeN
from returns.interfaces.failable import FailableN
from returns.primitives.hkt import KindN, kinded
_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')
_ThirdType = TypeVar('_ThirdType')
_UpdatedType = TypeVar('_UpdatedType')
_ApplicativeKind = TypeVar('_ApplicativeKind', bound=ApplicativeN)
_FailableKind = TypeVar('_FailableKind', bound=FailableN)
class AbstractFold:
"""
A collection of different helpers to write declarative ``Iterable`` actions.
Allows to work with iterables.
.. rubric:: Implementation
``AbstractFold`` and ``Fold`` types are special.
They have double definition for each method: public and protected ones.
Why?
Because you cannot override ``@kinded`` method due to a ``mypy`` bug.
So, there are two opportunities for us here:
1. Declare all method as ``@final`` and do not allow to change anything
2. Use delegation to protected unkinded methods
We have chosen the second way! Here's how it works:
1. Public methods are ``@kinded`` for better typing and cannot be overridden
2. Protected methods are unkinded and can be overridden in subtyping
Now, if you need to make a change into our implementation,
then you can subclass ``Fold`` or ``AbstractFold`` and then
change an implementation of any unkinded protected method.
"""
__slots__ = ()
@final
@kinded
@classmethod
def loop(
cls,
iterable: Iterable[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
function: Callable[
[_FirstType],
Callable[[_UpdatedType], _UpdatedType],
],
) -> KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType]:
"""
Allows to make declarative loops for any ``ApplicativeN`` subtypes.
Quick example:
.. code:: python
>>> from typing import Callable
>>> from returns.maybe import Some
>>> from returns.iterables import Fold
>>> def sum_two(first: int) -> Callable[[int], int]:
... return lambda second: first + second
>>> assert Fold.loop(
... [Some(1), Some(2), Some(3)],
... Some(10),
... sum_two,
... ) == Some(16)
Looks like ``foldl`` in some other languages with some more specifics.
See: https://philipschwarz.dev/fpilluminated/?page_id=348#bwg3/137
.. image:: https://i.imgur.com/Tza1isS.jpg
Is also quite similar to ``reduce``.
Public interface for ``_loop`` method. Cannot be modified directly.
"""
return cls._loop(iterable, acc, function, _concat_applicative)
@final
@kinded
@classmethod
def collect(
cls,
iterable: Iterable[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[
_ApplicativeKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
],
) -> KindN[
_ApplicativeKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
]:
"""
Transforms an iterable of containers into a single container.
Quick example for regular containers:
.. code:: python
>>> from returns.io import IO
>>> from returns.iterables import Fold
>>> items = [IO(1), IO(2)]
>>> assert Fold.collect(items, IO(())) == IO((1, 2))
If container can have failed values,
then this strategy fails on any existing failed like type.
It is enough to have even a single failed value in iterable
for this type to convert the whole operation result to be a failure.
Let's see how it works:
.. code:: python
>>> from returns.result import Success, Failure
>>> from returns.iterables import Fold
>>> empty = []
>>> all_success = [Success(1), Success(2), Success(3)]
>>> has_failure = [Success(1), Failure('a'), Success(3)]
>>> all_failures = [Failure('a'), Failure('b')]
>>> acc = Success(()) # empty tuple
>>> assert Fold.collect(empty, acc) == Success(())
>>> assert Fold.collect(all_success, acc) == Success((1, 2, 3))
>>> assert Fold.collect(has_failure, acc) == Failure('a')
>>> assert Fold.collect(all_failures, acc) == Failure('a')
If that's now what you need, check out
:meth:`~AbstractFold.collect_all`
to force collect all non-failed values.
Public interface for ``_collect`` method. Cannot be modified directly.
"""
return cls._collect(iterable, acc)
@final
@kinded
@classmethod
def collect_all(
cls,
iterable: Iterable[
KindN[_FailableKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[
_FailableKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
],
) -> KindN[
_FailableKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
]:
"""
Transforms an iterable of containers into a single container.
This method only works with ``FailableN`` subtypes,
not just any ``ApplicativeN`` like :meth:`~AbstractFold.collect`.
Strategy to extract all successful values
even if there are failed values.
If there's at least one successful value
and any amount of failed values,
we will still return all collected successful values.
We can return failed value for this strategy only in a single case:
when default element is a failed value.
Let's see how it works:
.. code:: python
>>> from returns.result import Success, Failure
>>> from returns.iterables import Fold
>>> empty = []
>>> all_success = [Success(1), Success(2), Success(3)]
>>> has_failure = [Success(1), Failure('a'), Success(3)]
>>> all_failures = [Failure('a'), Failure('b')]
>>> acc = Success(()) # empty tuple
>>> assert Fold.collect_all(empty, acc) == Success(())
>>> assert Fold.collect_all(all_success, acc) == Success((1, 2, 3))
>>> assert Fold.collect_all(has_failure, acc) == Success((1, 3))
>>> assert Fold.collect_all(all_failures, acc) == Success(())
>>> assert Fold.collect_all(empty, Failure('c')) == Failure('c')
If that's now what you need, check out :meth:`~AbstractFold.collect`
to collect only successful values and fail on any failed ones.
Public interface for ``_collect_all`` method.
Cannot be modified directly.
"""
return cls._collect_all(iterable, acc)
# Protected part
# ==============
@classmethod
@abstractmethod
def _loop(
cls,
iterable: Iterable[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
function: Callable[
[_FirstType],
Callable[[_UpdatedType], _UpdatedType],
],
concat: Callable[
[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
KindN[
_ApplicativeKind,
Callable[
[_FirstType],
Callable[[_UpdatedType], _UpdatedType],
],
_SecondType,
_ThirdType,
],
],
KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
],
) -> KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType]:
"""
Protected part of ``loop`` method.
Can be replaced in subclasses for better performance, etc.
"""
@classmethod
def _collect(
cls,
iterable: Iterable[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[
_ApplicativeKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
],
) -> KindN[
_ApplicativeKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
]:
return cls._loop(
iterable,
acc,
_concat_sequence,
_concat_applicative,
)
@classmethod
def _collect_all(
cls,
iterable: Iterable[
KindN[_FailableKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[
_FailableKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
],
) -> KindN[
_FailableKind,
'tuple[_FirstType, ...]',
_SecondType,
_ThirdType,
]:
return cls._loop(
iterable,
acc,
_concat_sequence,
_concat_failable_safely,
)
class Fold(AbstractFold):
"""
Concrete implementation of ``AbstractFold`` of end users.
Use it by default.
"""
__slots__ = ()
@classmethod
def _loop(
cls,
iterable: Iterable[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
],
acc: KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
function: Callable[
[_FirstType],
Callable[[_UpdatedType], _UpdatedType],
],
concat: Callable[
[
KindN[_ApplicativeKind, _FirstType, _SecondType, _ThirdType],
KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
KindN[
_ApplicativeKind,
Callable[
[_FirstType],
Callable[[_UpdatedType], _UpdatedType],
],
_SecondType,
_ThirdType,
],
],
KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType],
],
) -> KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType]:
"""
Protected part of ``loop`` method.
Can be replaced in subclasses for better performance, etc.
"""
wrapped = acc.from_value(function)
for current in iterable:
acc = concat(current, acc, wrapped)
return acc
# Helper functions
# ================
def _concat_sequence(
first: _FirstType,
) -> Callable[
['tuple[_FirstType, ...]'],
'tuple[_FirstType, ...]',
]:
"""
Concats a given item to an existing sequence.
We use explicit curring with ``lambda`` function because,
``@curry`` decorator is way slower. And we don't need its features here.
But, your functions can use ``@curry`` if you need it.
"""
return lambda second: (*second, first)
def _concat_applicative(
current: KindN[
_ApplicativeKind,
_FirstType,
_SecondType,
_ThirdType,
],
acc: KindN[
_ApplicativeKind,
_UpdatedType,
_SecondType,
_ThirdType,
],
function: KindN[
_ApplicativeKind,
Callable[[_FirstType], Callable[[_UpdatedType], _UpdatedType]],
_SecondType,
_ThirdType,
],
) -> KindN[_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType]:
"""Concats two applicatives using a curried-like function."""
return acc.apply(current.apply(function))
def _concat_failable_safely(
current: KindN[
_FailableKind,
_FirstType,
_SecondType,
_ThirdType,
],
acc: KindN[
_FailableKind,
_UpdatedType,
_SecondType,
_ThirdType,
],
function: KindN[
_FailableKind,
Callable[[_FirstType], Callable[[_UpdatedType], _UpdatedType]],
_SecondType,
_ThirdType,
],
) -> KindN[_FailableKind, _UpdatedType, _SecondType, _ThirdType]:
"""
Concats two ``FailableN`` using a curried-like function and a fallback.
We need both ``.apply`` and ``.lash`` methods here.
"""
return _concat_applicative(current, acc, function).lash(lambda _: acc)
|