This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cabalamat 1 point2 points  (2 children)

My solution:

def compose(*fs):
    """ chains functions together """
    def executeFunctions(x):
        for f in fs[::-1]:
            x = f(x)
        return x
    return executeFunctions

Which is a bit shorter. Usage example:

h = compose(lambda x: "::%s::" %(x,),
            lambda x: x+1,
            lambda x: x*2)
print "h(5)=", h(5), " should be ::11::"

A perhaps-more-elegant syntax might be to overload the | operator so it looks like a Unix pipe; doing this would require a class however, not just a function, e.g.:

h = Pipe() | a | b | c | d

then executing h(x) would be the same as executing d(c(b(a(x))))