Created
August 16, 2012 20:59
-
-
Save SegFaultAX/3373635 to your computer and use it in GitHub Desktop.
Function composition and threading in Python
This file contains hidden or 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
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