-2

Create a function that takes any number of functions as positional arguments. The function returns execution of function-arguments one by one. See example for better understanding (Let's call this function chain).

my_func = chain(lambda x: x + 2, lambda x: (x/4, x//4))
my_func(37)

It should return

(9.75, 9)

I tried to do something like:

def chain(x,*args):
    for arg in args:
        arg(x)

It is not working. Can't understand how to take a non function argument to this function (in example above 37).

Keyreall
  • 97
  • 1
  • 5
  • `chain` _shouldn't_ take a non-function argument - it _returns_ a function that does. – jonrsharpe Dec 07 '21 at 15:06
  • 1
    Does this answer your question? [Composing functions in python](https://stackoverflow.com/questions/16739290/composing-functions-in-python) – Pedro Maia Dec 07 '21 at 15:25

1 Answers1

2

Are you looking for something like this:

def chain(*funcs):
    def chained(*args, **kwargs):
        return tuple(func(*args, **kwargs) for func in funcs)
    return chained

my_func = chain(lambda x: x + 2, lambda x: (x/4, x//4))
print(my_func(37))

Output:

(39, (9.25, 9))
Timus
  • 10,974
  • 5
  • 14
  • 28