CS61A pyhton----高阶函数/lambda

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)

两种写法均可

 

posted @   liankewei123456  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示