Add Result.mapError

This commit is contained in:
Correl Roush 2018-12-11 22:19:13 -05:00
parent 77bf6b4735
commit 58c8d6841b
2 changed files with 13 additions and 0 deletions

View file

@ -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)

View file

@ -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))