Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ecounysis
Created February 29, 2012 01:36
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 ecounysis/1936844 to your computer and use it in GitHub Desktop.
Save ecounysis/1936844 to your computer and use it in GitHub Desktop.
Function Piping in Python
# I don't know 100% what this is, but it seems interesting, so I am recording it.
class FunctionPiper:
def applyAll(self, data):
if len(self.functionList) > 0:
for func in self.functionList:
data = func(data)
return data
j=FunctionPiper()
j.functionList=[lambda x:x*2,lambda x:x-1]
j.applyAll(5)
# 9
# select the first entry of each list
j.functionList=[lambda x: map(lambda y: y[0], x)]
j.applyAll([[1,2,3],[4,5,6],[7,8,9]])
# [1, 4, 7]
# sum the first entry of each list
j.functionList=[lambda x: map(lambda y: y[0], x), lambda z: reduce(lambda x,y:x+y,z,0)]
j.applyAll([[1,2,3],[4,5,6],[7,8,9]])
# 12
@donbro
Copy link

donbro commented Feb 29, 2012

could be just:

class FP2:
... def a(self, data):
... for i in self.functionList:
... data = i(data)
... return data
...
j = FP2()
j.functionList=[lambda x:x*2,lambda x:x-1]
j.a(5)
9

Its a mapping. could be written for a list not just scalar.

@ecounysis
Copy link
Author

You're right. I originally wrote it with the intention of processing lists of lists, but demonstrated it here with just a scalar. I like the way you simplified the iteration over the functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment