Skip to content

Instantly share code, notes, and snippets.

@dwickstrom
Last active September 28, 2016 13:28
Show Gist options
  • Save dwickstrom/2b32c31b8f77359c557914146bef81b1 to your computer and use it in GitHub Desktop.
Save dwickstrom/2b32c31b8f77359c557914146bef81b1 to your computer and use it in GitHub Desktop.
import functools
def compose(*functions):
return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
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
# prop :: String -> Object -> Any
@curry
def prop(x, obj):
if isinstance(obj, dict):
return obj[x]
return getattr(obj, x)
# upper :: String -> String
upper = lambda x: x.upper()
# lower :: String -> String
lower = lambda x: x.lower()
# has :: String -> Object -> Boolean
@curry
def has(x, obj):
if isinstance(obj, dict):
return x in obj
return hasattr(obj, x)
# identity :: a -> a
identity = curry(lambda x: x)
# add :: Number -> Number -> Number
add = curry(lambda x, y: x + y)
# inc :: Number -> Number
inc = lambda x: x + 1
# modulo :: Number -> Number -> Number
modulo = curry(lambda x, y: x % y)
# product :: [Number] -> Number
def product(ns):
return reduce(lambda x, y: x + y, ns)
# head :: [a] -> a
head = lambda xs: xs[0]
# tail :: [a] -> [a]
tail = lambda xs: xs[1:]
# last :: [a] -> a
last = lambda xs: xs[-1:]
# reverse :: [a] -> [a]
reverse = lambda xs: xs[::-1]
# inc :: Number -> Number
inc = lambda x: x + 1
# dec :: Number -> Number
dec = lambda x: x - 1
# take :: Number -> [a] -> [a]
take = curry(lambda n, xs: xs[:n])
# take_last :: Number -> [a] -> [a]
take_last = curry(lambda n, xs: xs[n:])
# take_until :: (a -> Boolean) -> [a] -> [a]
@curry
def take_until(predicate, xs):
idx = 0
things = []
while not (predicate(xs[idx])):
things.append(xs[idx])
idx += 1
return things
# concat :: [a] -> [a] -> [a] | String -> String -> String
concat = curry(lambda x, y: x + y)
# contains :: a -> [a] -> Boolean
contains = curry(lambda x, xs: x in xs)
# default_to :: a -> b -> a | b
default_to = curry(lambda x, y: y or x)
# multiply :: Number -> Number -> Number
multiply = curry(lambda x, y: x * y)
flip = lambda f: lambda *a: f(*reversed(a))
__ = {'__placeholder__': True}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment