typesafe-monads/monads/maybe.py

120 lines
2.9 KiB
Python
Raw Permalink Normal View History

2018-10-11 05:26:00 +00:00
from __future__ import annotations
2018-10-12 00:44:57 +00:00
from typing import Any, Callable, Generic, List, Optional, TypeVar
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]):
def __init__(self) -> None: # pragma: no cover
2018-10-11 05:26:00 +00:00
raise NotImplementedError
@classmethod
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
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
2018-10-11 05:26:00 +00:00
def withDefault(self, default: T) -> T:
if isinstance(self, Just):
return self.value
else:
return default
__rshift__ = bind
__mul__ = __rmul__ = map
2018-10-11 05:26:00 +00:00
class Just(Maybe[T]):
def __init__(self, value: T) -> None:
self.value = value
def __eq__(self, other: object):
return isinstance(other, Just) and self.value == other.value
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:
...
def __eq__(self, other: object):
return isinstance(other, Nothing)
def __repr__(self) -> str: # pragma: no cover
2018-10-11 05:26:00 +00:00
return "<Nothing>"
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
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
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