Created
November 7, 2017 21:34
-
-
Save sepulchered/b25bd52f2337918c4da70ab1463e4c10 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 | |
def maybe(fn): | |
@functools.wraps(fn) | |
def wrapper(*args, **kwargs): | |
try: | |
return fn(*args, **kwargs) | |
except Exception: | |
return None | |
return wrapper | |
@maybe | |
def divide(num, den): | |
return num / den | |
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 maybe_val is not None | |
def is_nothing(maybe_val): | |
return maybe_val is None | |
def from_just(maybe_val): | |
if maybe_val is None: | |
raise MaybeException('from_just: Nothing') | |
return maybe_val | |
def from_maybe(default_val, maybe_val): | |
return maybe_val or default_val | |
def list_to_maybe(lst): | |
return maybe(lambda x: x[0])(lst) | |
def maybe_to_list(maybe_val): | |
if maybe_val is None: | |
return [] | |
return [maybe_val] | |
def cat_maybes(maybes_lst): | |
return [mv for mv in maybes_lst if mv] | |
def map_maybe(map_maybe_fn, inp_lst): | |
return [mv for mv in map(map_maybe_fn, inp_lst) if mv] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment