Add an infix operator for Applicative.apply

This commit is contained in:
Correl Roush 2018-12-11 23:20:23 -05:00
parent 58c8d6841b
commit 8a25d3904f
5 changed files with 12 additions and 0 deletions

View file

@ -18,3 +18,5 @@ class Applicative(Functor[T]):
# https://github.com/python/mypy/issues/1317
def apply(self, functor: Any) -> Functor[S]: # pragma: no cover
raise NotImplementedError
__and__ = lambda other, self: Applicative.apply(self, other)

View file

@ -34,5 +34,6 @@ class List(Monad[T], Monoidal[list]):
return List(self.value + other.value)
__add__ = mappend
__and__ = lambda other, self: List.apply(self, other)
__mul__ = __rmul__ = map
__rshift__ = bind

View file

@ -61,6 +61,7 @@ class Maybe(Monad[T]):
return Nothing()
__rshift__ = bind
__and__ = lambda other, self: Maybe.apply(self, other)
__mul__ = __rmul__ = map

View file

@ -65,6 +65,7 @@ class Result(Monad[T], Generic[T, E]):
return self.map(Maybe.pure).withDefault(Nothing())
__rshift__ = bind
__and__ = lambda other, self: Result.apply(self, other)
__mul__ = __rmul__ = map

View file

@ -12,3 +12,10 @@ def test_fmap_using_ap(monad) -> None:
f: Callable[[int], int] = lambda x: x + 1
m: Applicative[int] = monad.pure(3)
assert m.map(f) == m.apply(monad.pure(f))
def test_apply_and_operator(monad) -> None:
subtract: Callable[[int], Callable[[int], int]] = lambda x: lambda y: x - y
ten = monad.pure(10)
six = monad.pure(6)
assert six.apply(ten.map(subtract)) == subtract * ten & six