Monads/Maybe monad: Difference between revisions
m
→{{header|Python}}: Improve type hints
m (Rewrote a comment/) |
m (→{{header|Python}}: Improve type hints) |
||
Line 1,593:
=={{header|Python}}==
The <code>Maybe</code> class constructor is effectively the <code>unit</code> function. Note that I've used <code>>></code> as the bind operator. Trying to chain <code>__irshift__</code> (<code>>>=</code>) would be a syntax error.
<syntaxhighlight lang="python">
"""A Maybe monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
from typing import Callable
from typing import Generic
Line 1,610 ⟶ 1,607:
T = TypeVar("T")
U = TypeVar("U")
Line 1,619 ⟶ 1,617:
self.value = value
def __rshift__(self, func: Callable[[Optional[T]], Maybe[
return self.bind(func)
def bind(self, func: Callable[[Optional[T]], Maybe[
return func(self.value)
Line 1,631 ⟶ 1,629:
def plus_one(value: Optional[int]) -> Maybe[int]:
if value is not None:
return Maybe
return Maybe
def currency(value: Optional[int]) -> Maybe[str]:
if value is not None:
return Maybe
return Maybe
Line 1,645 ⟶ 1,643:
for case in test_cases:
# or..
# result =
print(f"{str(case):<4} -> {result}")
</syntaxhighlight>
|