Added option and result types
This commit is contained in:
parent
b11f2fa8ea
commit
bdca0186da
|
@ -166,3 +166,42 @@ def tco_rec(f: Callable[P, Recur[P] | Return[B]]) -> Callable[P, B]:
|
|||
case Return(val=val)|val:
|
||||
return val #type:ignore
|
||||
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
|
Loading…
Reference in a new issue