- 2
How can functions be parameters for other functions?
all I can say is "wow"! functions calling functions; cats and dogs sleeping together; "wow"!
5 ответов
+ 6
If a function returns a value, you can use it like a value. Here's an example:
value = sum(double(5), double(3))
First, double(5) is run, which returns 10. Then, double(3) is run, and returns 6. So then sum() works with those returned numbers:
sum(10, 6)
and returns 16. Pretty neat!
+ 6
you can also return a function as value:
def f1(x):
return x*5
def f2(x):
return x+2
c = 0
def test():
global c
c = (c+1)&1
return f1 if c else f2
for i in range(5):
f = test()
print(f(i))
+ 2
One more common instance of a function calling a function is a recursive function, which repeatedly calls the function over and over until the function calls the base case and ends. I have seen recursive functions where the programmer either had no base case or wrote a base case that would never be called, resulting in an outcome that would be considered bad.
+ 1
A function can be input to a higher order function. For instance, you want to know if an element x of an iterable I verifies the function F(x) == True, you can do it in the following way:
def exists(F, I):
for x in I:
if F(x):
return True
return False
0
Thanks for your insights!