Monads/List monad: Difference between revisions
Content added Content deleted
(New post.) |
m (→{{header|Python}}: Improve type hints) |
||
Line 1,136: | Line 1,136: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
<syntaxhighlight lang="python"> |
<syntaxhighlight lang="python"> |
||
"""A List Monad. Requires Python >= 3.7 for type hints.""" |
|||
from __future__ import annotations |
from __future__ import annotations |
||
from itertools import chain |
from itertools import chain |
||
from typing import Any |
|||
from typing import Callable |
from typing import Callable |
||
from typing import Iterable |
from typing import Iterable |
||
Line 1,148: | Line 1,148: | ||
T = TypeVar("T") |
T = TypeVar("T") |
||
U = TypeVar("U") |
|||
Line 1,155: | Line 1,156: | ||
return cls(value) |
return cls(value) |
||
def bind(self, func: Callable[[T], MList[ |
def bind(self, func: Callable[[T], MList[U]]) -> MList[U]: |
||
return MList(chain.from_iterable(map(func, self))) |
return MList(chain.from_iterable(map(func, self))) |
||
def __rshift__(self, func: Callable[[T], MList[ |
def __rshift__(self, func: Callable[[T], MList[U]]) -> MList[U]: |
||
return self.bind(func) |
return self.bind(func) |
||
if __name__ == "__main__": |
if __name__ == "__main__": |
||
# Chained int and string functions |
# Chained int and string functions. |
||
print( |
print( |
||
MList([1, 99, 4]) |
MList([1, 99, 4]) |
||
Line 1,177: | Line 1,178: | ||
) |
) |
||
# Cartesian product of [1..5] and [6..10] |
# Cartesian product of [1..5] and [6..10]. |
||
print( |
print( |
||
MList(range(1, 6)).bind( |
MList(range(1, 6)).bind( |
||
Line 1,184: | Line 1,185: | ||
) |
) |
||
# Pythagorean triples with elements between 1 and 25 |
# Pythagorean triples with elements between 1 and 25. |
||
print( |
print( |
||
MList(range(1, 26)).bind( |
MList(range(1, 26)).bind( |