Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created August 16, 2012 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SegFaultAX/3373635 to your computer and use it in GitHub Desktop.
Save SegFaultAX/3373635 to your computer and use it in GitHub Desktop.
Function composition and threading in Python
def compose(f, g):
def inner(*args, **kwargs):
return f(g(*args, **kwargs))
return inner
# Clojure: (comp #(+ 1 %) #(* 2 %))
times2plus1 = compose(lambda n: n + 1, lambda n: n * 2)
print times2plus1(4)
# OUT: 9
def compose_many(*funs):
return reduce(compose, funs)
def thread(x, *funs):
return (compose_many(*funs[::-1]))(x)
add1 = lambda n: n + 1
times2 = lambda n: n * 2
sqr = lambda n: n * n
# Clojure:
# (defn add1 [n] (+ 1 n))
# (defn times2 [n] (* 2 n))
# (defn sqr [n] (* n n))
# (-> 10 sqr times2 add1)
print thread(10, sqr, times2, add1)
# OUT: 201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment