mirror of
https://github.com/correl/typesafe-monads.git
synced 2024-11-21 19:18:42 +00:00
Add some useful conversion functions
This commit is contained in:
parent
23f53d422a
commit
c7a5020d89
4 changed files with 46 additions and 0 deletions
|
@ -43,6 +43,13 @@ class Maybe(Monad[T]):
|
|||
else:
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def fromList(self, xs: List[T]) -> Maybe[T]:
|
||||
if xs:
|
||||
return Just(xs[0])
|
||||
else:
|
||||
return Nothing()
|
||||
|
||||
__rshift__ = bind
|
||||
__mul__ = __rmul__ = map
|
||||
|
||||
|
|
|
@ -2,6 +2,7 @@ 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")
|
||||
|
@ -49,6 +50,13 @@ class Result(Monad[T], Generic[T, E]):
|
|||
else:
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def fromMaybe(self, m: Maybe[T], error: E) -> Result[T, E]:
|
||||
return m.map(Result.pure).withDefault(Err(error))
|
||||
|
||||
def toMaybe(self) -> Maybe[T]:
|
||||
return self.map(Maybe.pure).withDefault(Nothing())
|
||||
|
||||
__rshift__ = bind
|
||||
__mul__ = __rmul__ = map
|
||||
|
||||
|
|
|
@ -74,3 +74,11 @@ def test_first() -> None:
|
|||
def test_last() -> None:
|
||||
maybes: List[Maybe[int]] = [Just(1), Just(2), Nothing()]
|
||||
assert Just(2) == last(maybes)
|
||||
|
||||
|
||||
def test_from_empty_list() -> None:
|
||||
assert Nothing() == Maybe.fromList([])
|
||||
|
||||
|
||||
def test_from_nonempty_list() -> None:
|
||||
assert Just(2) == Maybe.fromList([2, 4, 6])
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
from __future__ import annotations
|
||||
from typing import Callable
|
||||
|
||||
from monads.maybe import Maybe, Just, Nothing
|
||||
from monads.result import Result, Ok, Err, safe
|
||||
|
||||
|
||||
|
@ -121,3 +122,25 @@ def test_safe_wrapped_function_returns_ok() -> None:
|
|||
|
||||
result: Result[int, Exception] = unsafe(5)
|
||||
assert Ok(6) == result
|
||||
|
||||
|
||||
def test_from_just() -> None:
|
||||
m: Maybe[int] = Just(6)
|
||||
result: Result[int, str] = Result.fromMaybe(m, "error")
|
||||
assert Ok(6) == result
|
||||
|
||||
|
||||
def test_from_nothing() -> None:
|
||||
m: Maybe[int] = Nothing()
|
||||
result: Result[int, str] = Result.fromMaybe(m, "error")
|
||||
assert Err("error") == result
|
||||
|
||||
|
||||
def test_ok_to_maybe() -> None:
|
||||
result: Result[int, str] = Ok(6)
|
||||
assert Just(6) == result.toMaybe()
|
||||
|
||||
|
||||
def test_err_to_maybe() -> None:
|
||||
result: Result[int, str] = Err("error")
|
||||
assert Nothing() == result.toMaybe()
|
||||
|
|
Loading…
Reference in a new issue