Scatter in some more functions

This commit is contained in:
Emi Simpson 2023-02-09 20:46:55 -05:00
parent 179198e59d
commit a018831a49
Signed by: Emi
GPG Key ID: A12F2C2FFDC3D847
1 changed files with 30 additions and 2 deletions

View File

@ -1,6 +1,7 @@
from dataclasses import dataclass from dataclasses import dataclass
from functools import partial, wraps 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') A = TypeVar('A')
B = TypeVar('B') B = TypeVar('B')
@ -28,6 +29,10 @@ def flip(f: Callable[P1, Callable[P2, C]]) -> Callable[P2, Callable[P1, C]]:
return inner2 return inner2
return inner1 return inner1
# Identity function!
def ident(x: A) -> A:
return x
# Partial Appliaction shorthand # Partial Appliaction shorthand
p = partial p = partial
@ -198,6 +203,8 @@ class Ok(Generic[A]):
@dataclass(frozen=True) @dataclass(frozen=True)
class Err(Generic[B]): class Err(Generic[B]):
err: B err: B
def __bool__(self):
return False
Result = Ok[A] | Err[B] Result = Ok[A] | Err[B]
def map_res(f: Callable[[A], C], r: Result[A, B]) -> Result[C, B]: def map_res(f: Callable[[A], C], r: Result[A, B]) -> Result[C, B]:
match r: match r:
@ -222,4 +229,25 @@ def hush(r: Result[A, Any]) -> Option[A]:
case Ok(val): case Ok(val):
return Some(val) return Some(val)
case not_okay: case not_okay:
return None 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