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