CS61A pyhton----高阶函数
A function that either:
- Takes another function as an argument
- Returns a function as its result
All other functions are considered first-order functions.
可以直接将函数名当成参数传入函数
def cube(k): return k ** 3 def summation(n, term): """Sum the first N terms of a sequence. >>> summation(5, cube) 225 """ total = 0 k = 1 while k <= n: total = total + term(k) k = k + 1 return total
可以在函数中直接定义函数,此时子函数的域绑定在母函数下
人话:母函数中的变量子函数也可以用
def f (x): def g (y): return x+y return g f (1)(2) # 3
lambda
lambda <parameters>: <expression>
sq = lambda x : x * x # sq(3) 9
条件表达式
<consequent> if <predicate> else <alternative>
lambda x: x if x > 0 else 0
多环境
环境指的是一系列的 frame
当一个name被提及时,python会找当前环境下最近的frame
frame之间是调用的关系,或者父子关系
curry化
把一个带多参数的函数改成单参数的高阶函数
def curry2(f): def g(x): def h(y): return f(x, y) return h return g
from operator import add make_adder = curry2(add) make_adder(2)(3)
curry2 = lambda f: lambda x: lambda y: f(x, y)
两种写法均可