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