mirror of
https://github.com/correl/typesafe-monads.git
synced 2024-11-21 19:18:42 +00:00
Add Maybe analogues to Result's to/from Maybe methods
This commit is contained in:
parent
c85f5537ec
commit
50a26a7b7a
3 changed files with 35 additions and 1 deletions
|
@ -43,6 +43,16 @@ class Maybe(Monad[T]):
|
|||
else:
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def fromResult(cls, m: Result[T, E]) -> Maybe[T]:
|
||||
return m.map(Maybe.pure).withDefault(Nothing())
|
||||
|
||||
def toResult(self, error: E) -> Result[T, E]:
|
||||
if isinstance(self, Just):
|
||||
return Ok(self.value)
|
||||
else:
|
||||
return Err(error)
|
||||
|
||||
@classmethod
|
||||
def fromList(self, xs: List[T]) -> Maybe[T]:
|
||||
if xs:
|
||||
|
@ -124,3 +134,7 @@ class Last(Monoid[Maybe[T]]):
|
|||
|
||||
def last(xs: List[Maybe[T]]) -> Maybe[T]:
|
||||
return Last.mconcat(map(lambda x: Last(x), xs)).value
|
||||
|
||||
|
||||
# Import Result last to avoid a circular import error
|
||||
from .result import Result, Ok, Err
|
||||
|
|
|
@ -2,7 +2,6 @@ from __future__ import annotations
|
|||
from typing import Any, Callable, Generic, TypeVar
|
||||
|
||||
from .monad import Monad
|
||||
from .maybe import Maybe, Nothing
|
||||
|
||||
T = TypeVar("T")
|
||||
S = TypeVar("S")
|
||||
|
@ -100,3 +99,7 @@ def safe(function: Callable[..., T]) -> Callable[..., Result[T, Exception]]:
|
|||
return Err(e)
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
# Import Maybe last to avoid a circular import error
|
||||
from .maybe import Maybe, Nothing
|
||||
|
|
|
@ -2,6 +2,7 @@ import pytest # type: ignore
|
|||
from typing import Callable, List
|
||||
|
||||
from monads.maybe import Maybe, Just, Nothing, maybe, first, last
|
||||
from monads.result import Ok, Err
|
||||
|
||||
|
||||
def test_bind_just() -> None:
|
||||
|
@ -82,3 +83,19 @@ def test_from_empty_list() -> None:
|
|||
|
||||
def test_from_nonempty_list() -> None:
|
||||
assert Just(2) == Maybe.fromList([2, 4, 6])
|
||||
|
||||
|
||||
def test_from_ok() -> None:
|
||||
assert Just(3) == Maybe.fromResult(Ok(3))
|
||||
|
||||
|
||||
def test_from_err() -> None:
|
||||
assert Nothing() == Maybe.fromResult(Err("oops"))
|
||||
|
||||
|
||||
def test_just_to_result() -> None:
|
||||
assert Ok(3) == Just(3).toResult("oops")
|
||||
|
||||
|
||||
def test_nothing_to_result() -> None:
|
||||
assert Err("oops") == Nothing().toResult("oops")
|
||||
|
|
Loading…
Reference in a new issue