Last active
March 14, 2016 07:41
-
-
Save ydm/dcdfa19e77eddd87e8ae to your computer and use it in GitHub Desktop.
Chain functions in Python. It's like Haskell's dot operator, but better. ^_^
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 | |
def chain(*fs, reverse=True): | |
def dec(g): | |
@functools.wraps(g) | |
def wrapper(*args, **kwargs): | |
functions = reversed(fs) if reverse else fs | |
a = lambda m, f: f(m) | |
return functools.reduce(a, functions, g(*args, **kwargs)) | |
return wrapper | |
return dec | |
# Exmaple | |
# | |
# def ts(t): | |
# t2 = t * t | |
# t3 = t2 * t | |
# return [t3, t2, t, 1] | |
# | |
# tsrev = chain(list, reversed)(ts) | |
# OR | |
# @chain(list, reversed) | |
# def tsrev(t): | |
# return ts(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment