此代码如何工作?包括一个lambda

时间:2019-02-14 13:23:33

标签: python

有人可以举一个例子来说明这个程序的流程吗?

id_ = lambda x:x 
// would return the number (id_(1) would return 1)

zero=map(number,0)//should return number= lambda 0: lambda 0:f(0)

所以我无法解释:

number = lambda x: lambda f=id_: f(x)

plus = lambda x: lambda y: y + x

id_ = lambda x: x
number = lambda x: lambda f=id_: f(x)
zero, one, two, three, four, five, six, seven, eight, nine = map(number, range(10))
plus = lambda x: lambda y: y + x
minus = lambda x: lambda y: y - x
times = lambda x: lambda y: y * x
divided_by = lambda x: lambda y: y / x

使用函数进行计算:

one(plus(one()))

> 2

1 个答案:

答案 0 :(得分:3)

number():
 - expects a number "A"
 - returns a function "F" that expects a single argument function (or if not provided it uses "id_" by default)

同时提供两个参数时,将对函数number()求值并将函数F应用于数字A

# Example 1: returns only 3 (applies "id_" by default)
print(number(3)())

打印:

3

并且在提供功能时:

def inc(x):
    return x + 1

# Example 2: applies a single argument function to the number 3
print(number(3)(inc))

哪个返回:

4

所以现在您感兴趣的第二个功能是

plus():
 - expects a number
 - returns a function that accept another number

同时提供两个参数时,将对函数求值并返回其总和。

# Example:
print(plus(3)(4))

打印:

7

使用您在注释中使用的示例:

one(plus(one()))

从最里面的表达式开始,我们得到:

  1. one() == 1是因为one() == number(1)(f=id_) == _id(1)

  2. plus(1)的第二次调用将返回lambda y: y+1

应用于第一步plus(one()) == plus(1) == lambda y: y+1

的结果

因此,这意味着plus(one())本身就是一个函数(换句话说:“返回”),并且等效于:

def plus_one(y):
   return y + 1
  1. 最后一步:

one(plus(one())) == one(plus_one) == number(1)(f=plus_one) == plus_one(1) == 1 + 1 == 2

如果lambda语法困扰您,您可以将它们重写以提高清晰度(?)从而相应地进入完整功能:

def id_(x):
    return x

def number(x):
    def inner(f=id_):
        return f(x)

    return inner

def one(f=id_):
    return f(1)

def plus(x):
    def add_to_x(y):
        return y + x

    return add_to_x

add_one = plus(one())

assert one() == number(1)(f=id_) == id_(1) == 1

assert add_one(2) == plus(1)(2) == 3

assert plus(one())(4) == plus(1)(4) == 5

assert one(plus(one())) == one(add_one) == 2