Add << as an alias for binding a result

This commit is contained in:
Emi Simpson 2023-03-05 19:13:15 -05:00
parent ad31d63450
commit 642225b285
Signed by: Emi
GPG Key ID: A12F2C2FFDC3D847
1 changed files with 17 additions and 3 deletions

View File

@ -577,7 +577,7 @@ def unwrap_opt(r: Option[A]) -> A:
# Results!
@dataclass(frozen=True)
class Ok(Generic[A]):
class Ok(Generic[A, B]):
"""
The positive part of a result (either) datatype
@ -586,8 +586,12 @@ class Ok(Generic[A]):
val: A
def __repr__(self) -> str:
return f'Ok({self.val!r})'
def __lshift__(self, other: 'Callable[[A], Result[C, B]]') -> 'Result[C, B]':
"Alias for bind"
return other(self.val)
@dataclass(frozen=True)
class Err(Generic[B]):
class Err(Generic[A, B]):
"""
The error part of a result (either) datatype
@ -598,7 +602,17 @@ class Err(Generic[B]):
return f'Err({self.err!r})'
def __bool__(self):
return False
Result = Ok[A] | Err[B]
def __lshift__(self, other: 'Callable[[A], Result[C, B]]') -> 'Result[C, B]':
"Alias for bind"
"""
Alias for bind
>>> my_result = Err('oh noes!')
>>> my_result <<(lambda x: Ok(x + 1))
Err('oh noes!')
"""
return self
Result = Ok[A, B] | Err[A, B]
"A Result datatype, aka Either"
def map_res(f: Callable[[A], C], r: Result[A, B]) -> Result[C, B]:
"""