Search code examples
pythonfunctioncomposition

Execute functions in a list as a chain


In Python I defined these functions:

def foo_1(p): return p + 1
def foo_2(p): return p + 1
def foo_3(p): return p + 1
def foo_4(p): return p + 1
def foo_5(p): return p + 1

I want to execute these functions in a chain like this:

foo_1(foo_2(foo_3(foo_4(foo_5(1)))))

I'd like to specify these functions as a list, executing those functions in a chain with a precise sequence. This is what I've tried:

lf = [Null,foo_1,foo_2,foo_3,foo_4,foo_5]  # Null is for +1 issue here

def execu(lst, seq, raw_para):
    # in some way

execu(lf,(1,2,3,4,5), 1)   # = foo_1(foo_2(foo_3(foo_4(foo_5(1)))))
execu(lf,(1,2,3), 1)       # = foo_1(foo_2(foo_3(1)))
execu(lf,(3,3,3), 1)       # = foo_3(foo_3(foo_3(1)))

Solution

  • def execu(lst, seq, raw_para):
      return reduce(lambda x, y: y(x), reversed(operator.itemgetter(*seq)(lst)), raw_para)