cs61a 2_3Enviroments+lab02

完整的请看库

Enviroments

Environments for Higher-Order Functions

所谓Higher-Order function就是以函数为参数或是返回一个函数的函数,实现了函数的灵活运算
如果构造一个函数,其构造环境的过程如下:

def apply_twice(f, x):
    return f(f(x))

def square(x):
    return x * x
>>> apply_twice(square, 2)
>>> 16

首先在Global frame中声明了两个函数apply_twice()square(),在调用apply_twice()过程中在环境里产生响应的框架,由于其调用square()两次,因此随后又产生了两次对应的框架![[Pasted image 20220510212831.png]]
另一个例子,循环次数多一些,逻辑都差不多:

def repeat(f, x):
	while f(x) != x:
		x = f(x)
	return x

def g(x):
	return (x + 5) // 3

result = repeat(g, 5)

Enviroment for Nested Definitions

嵌套的函数定义需要注意函数所在的框架是怎么来的,它是建立在其定义或是调用的父级框架之上

def make_adder(n):
	def adder(k):
		return n + k
	return adder

add_three = make_adder(3)
add_three(4)

因此,在调用参数时,参数的取值是从本级框架向父级框架一直到全局框架中找的最近的那个值
![[Pasted image 20220510215626.png]]![[Pasted image 20220510215753.png]]

Local Names

局部变量不通用![[Pasted image 20220510221404.png]]

Function Composition

函数组合

def square(x):
	return x * x

def triple(x):
	return 3 * x

def compose1(f, g):
	def h(x):
		return f(g(x))
	return h

squiple = compose1(square, triple)
triquare = compose1(triple, square)

![[Pasted image 20220511000325.png]]

Self-Reference

def print_all(x):
	print(x)
	return print_all

print_all(1)(2)(3)

![[Pasted image 20220511185844.png]]

def print_sums(x):
	print(x)
	def next_sums(y):
		return print_sums(x+y)
	return next_sums

print_sums(1)(2)(3)

![[Pasted image 20220511190232.png]]

Lab 2: Higher-Order Functions, Lambda Expressions

What Would Python Display?

Q1: WWPD: Lambda the Free

For all WWPD questions, type Function if you believe the answer is <function...>, Error if it errors, and Nothing if nothing is displayed.As a reminder, the following two lines of code will not display anything in the Python interpreter when executed:

>>> x = None
>>> x

                
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值