From bdca0186da37786f9e7d645bb322ed3488fd7ccc Mon Sep 17 00:00:00 2001 From: Emi Simpson Date: Wed, 8 Feb 2023 21:32:24 -0500 Subject: [PATCH] Added option and result types --- emis_funky_funktions.py | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/emis_funky_funktions.py b/emis_funky_funktions.py index c707a26..d37eb78 100644 --- a/emis_funky_funktions.py +++ b/emis_funky_funktions.py @@ -165,4 +165,43 @@ def tco_rec(f: Callable[P, Recur[P] | Return[B]]) -> Callable[P, B]: pass case Return(val=val)|val: return val #type:ignore - return tco_loop \ No newline at end of file + return tco_loop + +# Options! +@dataclass(frozen=True) +class Some(Generic[A]): + val: A +Option = Some[A] | None +def map_opt(f: Callable[[A], B], o: Option[A]) -> Option[B]: + match o: + case Some(val): + return Some(f(val)) + case none: + return none +def bind_opt(f: Callable[[A], Option[B]], o: Option[A]) -> Option[B]: + match o: + case Some(val): + return f(val) + case none: + return none + +# Results! +@dataclass(frozen=True) +class Ok(Generic[A]): + val: A +@dataclass(frozen=True) +class Err(Generic[B]): + err: B +Result = Ok[A] | Err[B] +def map_res(f: Callable[[A], C], r: Result[A, B]) -> Result[C, B]: + match r: + case Ok(val): + return Ok(f(val)) + case not_okay: + return not_okay +def bind_res(f: Callable[[A], Result[C, B]], r: Result[A, B]) -> Result[C, B]: + match r: + case Ok(val): + return f(val) + case not_okay: + return not_okay \ No newline at end of file