From 642225b28562775b06c220f772c3b8de125e1fde Mon Sep 17 00:00:00 2001 From: Emi Simpson Date: Sun, 5 Mar 2023 19:13:15 -0500 Subject: [PATCH] Add << as an alias for binding a result --- emis_funky_funktions.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/emis_funky_funktions.py b/emis_funky_funktions.py index cac943a..a4fa345 100644 --- a/emis_funky_funktions.py +++ b/emis_funky_funktions.py @@ -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]: """