Problem k: Problem 1: Lambdas and Currying (100pts)
Problem
We can transform multiple-argument functions into a chain of single-argument, higher order functions by taking advantage of lambda expressions. This is useful when dealing with functions that take only single-argument functions. We will see some examples of these later on.
Write a function
lambda_curry2that will curry any two argument function using lambdas. See the doctest or refer to Section 1.6.6 in the textbook if you're not sure what this means.Your solution to this problem should fit entirely on the return line. You can try writing it first without this restriction, but rewrite it after in one line to test your understanding of this topic.
我们可以利用 lambda 表达式,将多参数函数转换为单参数、高阶函数的链式调用。这在处理只接受单参数函数的场景中非常有用。稍后我们会看到一些相关示例。
编写一个函数 lambda_curry2,它可以使用 lambda 表达式柯里化(curry)任何两个参数的函数。如果您不确定柯里化是什么意思,请参阅文档测试或查阅 教材 的 1.6.6 节。
您的解决方案必须完全写在 return 这一行上。 您可以先尝试在没有此限制的情况下编写它,但之后需要将其重写为一行,以检验您对该主题的理解。
def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add, mul, mod
>>> curried_add = lambda_curry2(add)
>>> add_three = curried_add(3)
>>> add_three(5)
8
>>> curried_mul = lambda_curry2(mul)
>>> mul_5 = curried_mul(5)
>>> mul_5(42)
210
>>> lambda_curry2(mod)(123)(10)
3
>>> # You aren't expected to understand the code of this test.
>>> # It's just here to check that definition of lambda_curry2 is just a return statement.
>>> import inspect, ast
>>> [type(x).__name__ for x in ast.parse(inspect.getsource(lambda_curry2)).body[0].body]
['Expr', 'Return']
"""
return ______
Hints
-
lambda_curry2(func)(a)(b)应该与func(a, b)是等价的。 -
考虑连用两个
lambda
Solutions
如果难以思考的话,可以先写出不用 lambda 的形式
def curry2(func):
def g(x):
def h(y):
return func(x, y)
return h
return g
然后一步步转为 lambda 形式。
def lambda_curry2(func):
return lambda x: lambda y: func(x, y)