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)
两种写法均可
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构