mirror of
https://github.com/correl/typesafe-monads.git
synced 2024-11-14 11:09:36 +00:00
Add Result.mapError
This commit is contained in:
parent
77bf6b4735
commit
58c8d6841b
2 changed files with 13 additions and 0 deletions
|
@ -34,6 +34,14 @@ class Result(Monad[T], Generic[T, E]):
|
|||
else: # pragma: no cover
|
||||
raise TypeError
|
||||
|
||||
def mapError(self, function: Callable[[E], S]) -> Result[T, S]:
|
||||
if isinstance(self, Err):
|
||||
return Err(function(self.err))
|
||||
elif isinstance(self, Ok):
|
||||
return Ok(self.value)
|
||||
else: # pragma: no cover
|
||||
raise TypeError
|
||||
|
||||
def apply(self, functor: Result[Callable[[T], S], E]) -> Result[S, E]:
|
||||
if isinstance(functor, Ok):
|
||||
return self.map(functor.value)
|
||||
|
|
|
@ -63,6 +63,11 @@ def test_map_infix() -> None:
|
|||
assert "5" == mapped.withDefault("0")
|
||||
|
||||
|
||||
def test_map_error() -> None:
|
||||
m: Result[int, str] = Err("oops")
|
||||
assert Err(4) == m.mapError(len)
|
||||
|
||||
|
||||
def test_bind() -> None:
|
||||
result: Result[int, str] = Ok(5)
|
||||
incremented: Result[int, str] = result.bind(lambda x: Ok(x + 1))
|
||||
|
|
Loading…
Reference in a new issue