【CS 61a Study notes1】- 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值