Skip to content

Commit

Permalink
Add dedicated __rshift__ (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
katunilya committed Apr 23, 2022
1 parent 72a9e40 commit 310add5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
21 changes: 18 additions & 3 deletions mona/maybe.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ class Maybe(state.State[T], abc.ABC):
Strict types help ignore
"""

def __rshift__(self, func: typing.Callable[[T], "Maybe[V]"]) -> "Maybe[V]":
"""Dunder method for `>>` bind syntax.
>>> maybe.bind(function, cnt)
>>> # exactly the same as
>>> cnt >> function
Args:
func (typing.Callable[[T], "Maybe[V]"]): _description_
Returns:
Maybe[V]: _description_
"""
return bind(func, self)


@dataclasses.dataclass(frozen=True)
class Some(Maybe[T]):
Expand Down Expand Up @@ -51,7 +66,7 @@ def __init__(self) -> None:


@toolz.curry
def bind(function: typing.Callable[[Maybe[T]], Maybe[V]], cnt: Maybe[T]) -> Maybe[V]:
def bind(func: typing.Callable[[T], Maybe[V]], cnt: Maybe[T]) -> Maybe[V]:
"""Bind function for `Maybe` monad.
`function` is executed only in case `cnt` is `Some` and not `Nothing` as it does not
Expand All @@ -65,7 +80,7 @@ def bind(function: typing.Callable[[Maybe[T]], Maybe[V]], cnt: Maybe[T]) -> Mayb
Maybe[V]: result of running `function` on `cnt` value.
"""
match cnt:
case Some():
return function(cnt)
case Some(value):
return func(value)
case _:
return cnt
6 changes: 3 additions & 3 deletions tests/test_maybe.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ def test_nothing_is_singleton():
@pytest.mark.parametrize(
"arrange_function,arrange_cnt,assert_cnt",
[
(lambda x: x, maybe.Some(1), maybe.Some(1)),
(lambda x: x, maybe.Some(2), maybe.Some(2)),
(lambda x: x, maybe.Nothing, maybe.Nothing),
(lambda x: maybe.Some(x), maybe.Some(1), maybe.Some(1)),
(lambda x: maybe.Some(x), maybe.Some(2), maybe.Some(2)),
(lambda x: maybe.Some(x), maybe.Nothing, maybe.Nothing),
(lambda x: maybe.Nothing, maybe.Nothing, maybe.Nothing),
(lambda x: maybe.Nothing, maybe.Some(1), maybe.Nothing),
],
Expand Down

0 comments on commit 310add5

Please sign in to comment.