HIGHER-ORDER FUNCTION
Higher-order function
Def : A funtion returns a function or takes a function as an argument
Why higher-order function
High-order functions separate the functions into different parts to reduce the repetition
Higher-order func example
We wanna to get the inverse of the square function by using the search func
def search(f):
x = 0
while True:
if f(x):
return x
x += 1
def square(x):
return x*x
def inverse(f):
""" return g(y) such that g(f(x))=x """
return lambda y : search(lambda x : f(x)==y)
The return part of the inverse function seems difficult to figure out , so now we can use nesting structure to rewrite it to make it clearer.
# ref: lambda function : lambda x : f(x)==y
def anonymous_func(x):
return f(x)==y
# let's begin:
def inverse(f):
def inverse_of_f(y):
def is_inverse_of_y(x):
return f(x