Last active
August 29, 2015 14:26
-
-
Save jsanders/2385d5c04daf957478a7 to your computer and use it in GitHub Desktop.
Demonstrate how compose could be defined in python
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
def compose(*funcs): | |
return lambda x: reduce(lambda acc, f: f(acc), funcs[::-1], x) | |
def double(x): | |
return x + x | |
def square(x): | |
return x * x | |
print(compose(double, square)(2)) #=> 8 |
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
def double(x): | |
return x + x | |
def square(x): | |
return x * x | |
result = reduce(lambda acc, f: f(acc), [square, double], 2) | |
print(result) #=> 8 |
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
def reduce(func, iterable, initial): | |
acc = initial | |
for cur in iterable: | |
acc = func(acc, cur) | |
return acc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment