Skip to content

Instantly share code, notes, and snippets.

@jsanders
Last active August 29, 2015 14:26
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 jsanders/2385d5c04daf957478a7 to your computer and use it in GitHub Desktop.
Save jsanders/2385d5c04daf957478a7 to your computer and use it in GitHub Desktop.
Demonstrate how compose could be defined in python
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
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
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