Jump to content

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.
In this implementation, a <code>Maybe</code> type's 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."""
"""A Maybe monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
 
from typing import Any
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[AnyU]]) -> Maybe[U]:
return self.bind(func)
 
def bind(self, func: Callable[[Optional[T]], Maybe[AnyU]]) -> Maybe[AnyU]:
return func(self.value)
 
Line 1,631 ⟶ 1,629:
def plus_one(value: Optional[int]) -> Maybe[int]:
if value is not None:
return Maybe[int](value + 1)
return Maybe[int](None)
 
 
def currency(value: Optional[int]) -> Maybe[str]:
if value is not None:
return Maybe[str](f"${value}.00")
return Maybe[str](None)
 
 
Line 1,645 ⟶ 1,643:
 
for case in test_cases:
m_intresult = Maybe[int](case) >> plus_one >> currency
 
result = m_int >> plus_one >> currency
# or..
# result = m_intMaybe(case).bind(plus_one).bind(currency)
 
print(f"{str(case):<4} -> {result}")
</syntaxhighlight>
140

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.