Home > Software design >  Function as argument for another function
Function as argument for another function

Time:12-06

The first function adds two numbers, the second function adds them twice. What is the purpose of Z? I get that x and y are the numbers you're adding together. But what is Z?

    def add(x, y):
return x   y

    def twice(z, x, y):
return z(z(x, y), z(x, y))

    a = 5
    b = 10
    print(twice(add, a, b)) 

CodePudding user response:

z represents the function that you want to execute twice. In your example:

twice(add, a, b)

twice received three arguments, add, a, and b. add is a reference to the add function, and becomes z instead the twice function. You might imagine a scenario in which you pass a different hypothetical function subtract to twice.

CodePudding user response:

In twice(z, x, y), z is a function. So when you call twice(add, a, b), z is the function add. Therefore return z(z(x, y), z(x, y)) would be

return add(add(a, b), add(a, b))

So it calculates (a b) (a b).

If you pass, for example, a function sub = lambda x, y: x - y, then twice(sub, a, b) will return sub(sub(a, b), sub(a, b)) instead, i.e., (a - b) - (a - b).

Another example:

print(twice(lambda x, y: x   ' '   y, 'hello', 'world'))
# hello world hello world
  • Related