Last active
November 8, 2017 22:08
-
-
Save sepulchered/73eda12d86d58eb70513211989ae04df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
class MaybeException(Exception): | |
pass | |
class Just: | |
def __init__(self, value): | |
self.value = value | |
def __repr__(self): | |
return f'Just {self.value}' | |
def maybe(fn): | |
@functools.wraps(fn) | |
def wrapper(*args, **kwargs): | |
try: | |
return Just(fn(*args, **kwargs)) | |
except Exception: | |
return None | |
return wrapper | |
@maybe | |
def divide(num, den): | |
return num / den | |
@maybe | |
def positive_division(num, den): | |
res = num / den | |
if res <= 0: | |
return None | |
return res | |
def maybe_fn(default_val, fn, maybe_val): | |
if maybe_val is None: | |
return default_val | |
return fn(maybe_val) | |
def is_just(maybe_val): | |
return isinstance(maybe_val, Just) | |
def is_nothing(maybe_val): | |
return maybe_val is None | |
def from_just(maybe_val): | |
if not isinstance(maybe_val, Just): | |
raise MaybeException('from_just: Nothing') | |
return maybe_val.value | |
def from_maybe(default_val, maybe_val): | |
if isinstance(maybe_val, Just): | |
return maybe_val.value | |
return default_val | |
def list_to_maybe(lst): | |
return maybe(lambda x: x[0])(lst) | |
def maybe_to_list(maybe_val): | |
if isinstance(maybe_val, Just): | |
return [maybe_val.value] | |
return [] | |
def cat_maybes(maybes_lst): | |
return [mv.value for mv in maybes_lst if isinstance(mv, Just)] | |
def map_maybe(map_maybe_fn, inp_lst): | |
return [mv.value for mv in map(map_maybe_fn, inp_lst) if isinstance(mv, Just)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment