Skip to content

Instantly share code, notes, and snippets.

@dwickstrom
Last active January 1, 2018 12:36
Show Gist options
  • Save dwickstrom/eacf22aa78f78e29de5a08cdab190e1d to your computer and use it in GitHub Desktop.
Save dwickstrom/eacf22aa78f78e29de5a08cdab190e1d to your computer and use it in GitHub Desktop.
from itertools import chain, imap
def curry(fn):
def curried(*args, **kwargs):
if len(args) + len(kwargs) >= fn.__code__.co_argcount:
return fn(*args, **kwargs)
return (lambda *args2, **kwargs2:
curried(*(args + args2), **dict(kwargs, **kwargs2)))
return curried
@curry
def flatmap(f, xs):
return chain.from_iterable(imap(f, xs))
@curry
def from_noneable(callable, arg):
try:
result = callable(arg)
return [result] if result is not None else []
except Exception:
return []
def flip(f):
return lambda *y: f(*reversed(y))
maybe = from_noneable
head = lambda x: x[0]
safe_head = from_noneable(head)
div = curry(lambda x, y: x / y)
flatmap(from_noneable(flip(div)(10)), [10, 5, 0, 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment