2018-10-11 05:26:00 +00:00
|
|
|
from __future__ import annotations
|
2019-01-04 03:28:41 +00:00
|
|
|
import functools
|
2019-01-23 04:44:21 +00:00
|
|
|
from typing import (
|
|
|
|
Any,
|
|
|
|
Awaitable,
|
|
|
|
Callable,
|
|
|
|
Generic,
|
|
|
|
Iterable,
|
|
|
|
List,
|
|
|
|
Optional,
|
|
|
|
Type,
|
|
|
|
TypeVar,
|
|
|
|
)
|
2019-02-15 18:40:45 +00:00
|
|
|
from . import result
|
2018-10-11 05:26:00 +00:00
|
|
|
from .monad import Monad
|
2018-10-12 00:44:57 +00:00
|
|
|
from .monoid import Monoid
|
2018-10-11 05:26:00 +00:00
|
|
|
|
|
|
|
T = TypeVar("T")
|
|
|
|
S = TypeVar("S")
|
|
|
|
E = TypeVar("E")
|
|
|
|
|
|
|
|
|
|
|
|
class Maybe(Monad[T]):
|
2018-10-12 18:24:03 +00:00
|
|
|
def __init__(self) -> None: # pragma: no cover
|
2018-10-11 05:26:00 +00:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
@classmethod
|
2018-10-12 01:06:23 +00:00
|
|
|
def pure(cls, value: T) -> Maybe[T]:
|
2018-10-11 05:26:00 +00:00
|
|
|
return Just(value)
|
|
|
|
|
|
|
|
def bind(self, function: Callable[[T], Maybe[S]]) -> Maybe[S]:
|
|
|
|
if isinstance(self, Just):
|
|
|
|
return function(self.value)
|
|
|
|
else:
|
|
|
|
new: Maybe[S] = Nothing()
|
|
|
|
return new
|
|
|
|
|
2018-10-12 01:06:23 +00:00
|
|
|
def map(self, function: Callable[[T], S]) -> Maybe[S]:
|
2018-10-11 05:26:00 +00:00
|
|
|
if isinstance(self, Just):
|
|
|
|
return Just(function(self.value))
|
|
|
|
else:
|
|
|
|
new: Maybe[S] = Nothing()
|
|
|
|
return new
|
|
|
|
|
2018-10-12 18:09:16 +00:00
|
|
|
def apply(self, functor: Maybe[Callable[[T], S]]) -> Maybe[S]:
|
|
|
|
if isinstance(functor, Just):
|
|
|
|
return self.map(functor.value)
|
|
|
|
else:
|
|
|
|
new: Maybe[S] = Nothing()
|
|
|
|
return new
|
|
|
|
|
2019-01-04 03:28:41 +00:00
|
|
|
@classmethod
|
|
|
|
def sequence(cls, xs: Iterable[Maybe[T]]) -> Maybe[List[T]]:
|
|
|
|
"""Evaluate monadic actions in sequence, collecting results."""
|
|
|
|
|
|
|
|
def mcons(acc: Maybe[List[T]], x: Maybe[T]) -> Maybe[List[T]]:
|
|
|
|
return acc.bind(lambda acc_: x.map(lambda x_: acc_ + [x_]))
|
|
|
|
|
|
|
|
empty: Maybe[List[T]] = cls.pure([])
|
|
|
|
return functools.reduce(mcons, xs, empty)
|
|
|
|
|
2018-10-11 05:26:00 +00:00
|
|
|
def withDefault(self, default: T) -> T:
|
|
|
|
if isinstance(self, Just):
|
|
|
|
return self.value
|
|
|
|
else:
|
|
|
|
return default
|
|
|
|
|
2018-12-06 18:14:40 +00:00
|
|
|
@classmethod
|
2019-02-15 18:40:45 +00:00
|
|
|
def fromResult(cls, m: result.Result[T, E]) -> Maybe[T]:
|
2018-12-06 18:14:40 +00:00
|
|
|
return m.map(Maybe.pure).withDefault(Nothing())
|
|
|
|
|
2019-02-15 18:40:45 +00:00
|
|
|
def toResult(self, error: E) -> result.Result[T, E]:
|
2018-12-06 18:14:40 +00:00
|
|
|
if isinstance(self, Just):
|
2019-02-15 18:40:45 +00:00
|
|
|
return result.Ok(self.value)
|
2018-12-06 18:14:40 +00:00
|
|
|
else:
|
2019-02-15 18:40:45 +00:00
|
|
|
return result.Err(error)
|
2018-12-06 18:14:40 +00:00
|
|
|
|
2018-12-03 21:16:04 +00:00
|
|
|
@classmethod
|
|
|
|
def fromList(self, xs: List[T]) -> Maybe[T]:
|
|
|
|
if xs:
|
|
|
|
return Just(xs[0])
|
|
|
|
else:
|
|
|
|
return Nothing()
|
|
|
|
|
2018-10-11 05:26:00 +00:00
|
|
|
__rshift__ = bind
|
2018-12-12 04:20:23 +00:00
|
|
|
__and__ = lambda other, self: Maybe.apply(self, other)
|
2018-10-12 01:06:23 +00:00
|
|
|
__mul__ = __rmul__ = map
|
2018-10-11 05:26:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Just(Maybe[T]):
|
|
|
|
def __init__(self, value: T) -> None:
|
|
|
|
self.value = value
|
|
|
|
|
2018-10-11 16:15:52 +00:00
|
|
|
def __eq__(self, other: object):
|
|
|
|
return isinstance(other, Just) and self.value == other.value
|
|
|
|
|
2018-10-12 18:24:03 +00:00
|
|
|
def __repr__(self) -> str: # pragma: no cover
|
2018-10-11 05:26:00 +00:00
|
|
|
return f"<Just {self.value}>"
|
|
|
|
|
|
|
|
|
|
|
|
class Nothing(Maybe[T]):
|
|
|
|
def __init__(self) -> None:
|
|
|
|
...
|
|
|
|
|
2018-10-11 16:15:52 +00:00
|
|
|
def __eq__(self, other: object):
|
|
|
|
return isinstance(other, Nothing)
|
|
|
|
|
2018-10-12 18:24:03 +00:00
|
|
|
def __repr__(self) -> str: # pragma: no cover
|
2018-10-11 05:26:00 +00:00
|
|
|
return "<Nothing>"
|
|
|
|
|
|
|
|
|
2019-01-23 04:44:21 +00:00
|
|
|
M = TypeVar("M", bound=Monad[Maybe])
|
|
|
|
|
|
|
|
|
|
|
|
class MaybeT(Monad[T], Generic[M, T]):
|
|
|
|
def __init__(self, value: Monad[Maybe[T]]) -> None:
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
def transformer(outer: Type[M]) -> Type[MaybeT[M, T]]:
|
|
|
|
M = TypeVar("M", bound=Monad[Maybe])
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
|
|
class _MaybeT(MaybeT[M, T]):
|
|
|
|
def __init__(self, value: Monad[Maybe[T]]) -> None:
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def pure(cls, value: T) -> MaybeT[M, T]:
|
|
|
|
return _MaybeT(outer.pure(Maybe.pure(value)))
|
|
|
|
|
|
|
|
def map(self, function: Callable[[T], S]) -> _MaybeT[M, S]:
|
|
|
|
return _MaybeT(self.value.map(lambda inner: inner.map(function)))
|
|
|
|
|
|
|
|
def bind(self, function: Callable[[T], _MaybeT[M, S]]) -> _MaybeT[M, S]:
|
|
|
|
def bind_inner(inner: Maybe[T]) -> Monad[Maybe[S]]:
|
|
|
|
if isinstance(inner, Just):
|
|
|
|
return function(inner.value).value
|
|
|
|
else:
|
|
|
|
empty: Maybe[S] = Nothing()
|
|
|
|
return outer.pure(empty)
|
|
|
|
|
|
|
|
return _MaybeT(self.value.bind(bind_inner))
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return f"<MaybeT {self.value}>"
|
|
|
|
|
|
|
|
if hasattr(outer, "__await__"):
|
|
|
|
|
|
|
|
def __await__(self) -> Maybe[T]:
|
|
|
|
if isinstance(self.value, Awaitable):
|
|
|
|
return self.value.__await__()
|
|
|
|
else:
|
|
|
|
raise TypeError("Not awaitable")
|
|
|
|
|
|
|
|
return _MaybeT
|
|
|
|
|
|
|
|
|
|
|
|
def transform(outer: Type[M], instance: Monad[Maybe[T]]) -> MaybeT[M, T]:
|
|
|
|
Transformer: Type[MaybeT[M, T]] = transformer(outer)
|
|
|
|
return Transformer(instance)
|
|
|
|
|
|
|
|
|
2018-10-11 05:26:00 +00:00
|
|
|
def maybe(value: T, predicate: Optional[Callable[[T], bool]] = None) -> Maybe[T]:
|
|
|
|
predicate = predicate or (lambda x: x is not None)
|
|
|
|
if predicate(value):
|
|
|
|
return Just(value)
|
|
|
|
else:
|
|
|
|
return Nothing()
|
2018-10-12 00:44:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
class First(Monoid[Maybe[T]]):
|
|
|
|
@classmethod
|
|
|
|
def mzero(cls) -> First:
|
|
|
|
return First(Nothing())
|
|
|
|
|
|
|
|
def mappend(self, other: First):
|
|
|
|
if isinstance(self.value, Just):
|
|
|
|
return self
|
|
|
|
else:
|
|
|
|
return other
|
|
|
|
|
2018-10-12 18:24:03 +00:00
|
|
|
def __repr__(self) -> str: # pragma: no cover
|
2018-10-12 00:44:57 +00:00
|
|
|
return f"<First {self.value}>"
|
|
|
|
|
|
|
|
__add__ = mappend
|
|
|
|
|
|
|
|
|
|
|
|
def first(xs: List[Maybe[T]]) -> Maybe[T]:
|
|
|
|
return First.mconcat(map(lambda x: First(x), xs)).value
|
|
|
|
|
|
|
|
|
|
|
|
class Last(Monoid[Maybe[T]]):
|
|
|
|
@classmethod
|
|
|
|
def mzero(cls) -> Last:
|
|
|
|
return Last(Nothing())
|
|
|
|
|
|
|
|
def mappend(self, other: Last):
|
|
|
|
if isinstance(other.value, Just):
|
|
|
|
return other
|
|
|
|
else:
|
|
|
|
return self
|
|
|
|
|
2018-10-12 18:24:03 +00:00
|
|
|
def __repr__(self) -> str: # pragma: no cover
|
2018-10-12 00:44:57 +00:00
|
|
|
return f"<Last {self.value}>"
|
|
|
|
|
|
|
|
__add__ = mappend
|
|
|
|
|
|
|
|
|
|
|
|
def last(xs: List[Maybe[T]]) -> Maybe[T]:
|
|
|
|
return Last.mconcat(map(lambda x: Last(x), xs)).value
|