diff --git a/emis_funky_funktions.py b/emis_funky_funktions.py index 53e0401..7b666f8 100644 --- a/emis_funky_funktions.py +++ b/emis_funky_funktions.py @@ -1,6 +1,7 @@ from dataclasses import dataclass from functools import partial, wraps -from typing import Any, Callable, Concatenate, Generic, ParamSpec, Sequence, Tuple, TypeVar +from operator import not_ +from typing import Any, Callable, Concatenate, Generic, Iterator, ParamSpec, Sequence, Tuple, TypeVar A = TypeVar('A') B = TypeVar('B') @@ -28,6 +29,10 @@ def flip(f: Callable[P1, Callable[P2, C]]) -> Callable[P2, Callable[P1, C]]: return inner2 return inner1 +# Identity function! +def ident(x: A) -> A: + return x + # Partial Appliaction shorthand p = partial @@ -198,6 +203,8 @@ class Ok(Generic[A]): @dataclass(frozen=True) class Err(Generic[B]): err: B + def __bool__(self): + return False Result = Ok[A] | Err[B] def map_res(f: Callable[[A], C], r: Result[A, B]) -> Result[C, B]: match r: @@ -222,4 +229,25 @@ def hush(r: Result[A, Any]) -> Option[A]: case Ok(val): return Some(val) case not_okay: - return None \ No newline at end of file + return None +def try_(handle: Callable[[Exception], B], f: Callable[P, A], *args: P.args, **kwargs: P.kwargs) -> Result[A, B]: + try: + return Ok(f(*args, **kwargs)) + except Exception as e: + return Err(handle(e)) +def unwrap_r(r: Result[A, Any]) -> A: + match r: + case Ok(val): + return val + case Err(e): + raise Exception(f'Tried to unwrap an error: {e}') +def sequence(s: Sequence[Result[A, B]]) -> Result[Iterator[A], B]: + if all(s): + return Ok(( + unwrap_r(r) + for r in s + )) + else: + o = next(filter(not_, s)) + assert isinstance(o, Err) + return o \ No newline at end of file