yas*_*sar 9 python functional-programming
如今,我开始学习haskell,而当我这样做时,我尝试实现我在Python中从中学到的一些想法.但是,我发现这个具有挑战性.你可以在Haskell中编写一个函数,它接受另一个函数作为参数,并返回相同的函数,并且它的参数的顺序被翻转.可以用Python做类似的事吗?例如,
def divide(a,b):
return a / b
new_divide = flip(divide)
# new_divide is now a function that returns second argument divided by first argument
Run Code Online (Sandbox Code Playgroud)
你能用Python做到这一点吗?
Ray*_*ger 16
您可以使用嵌套函数定义在Python中创建闭包.这使您可以创建一个反转参数顺序的新函数,然后调用原始函数:
>>> from functools import wraps
>>> def flip(func):
'Create a new function from the original with the arguments reversed'
@wraps(func)
def newfunc(*args):
return func(*args[::-1])
return newfunc
>>> def divide(a, b):
return a / b
>>> new_divide = flip(divide)
>>> new_divide(30.0, 10.0)
0.3333333333333333
Run Code Online (Sandbox Code Playgroud)
geo*_*org 14
纯粹的功能风格:
flip = lambda f: lambda *a: f(*reversed(a))
def divide(a, b):
return a / b
print flip(divide)(3.0, 1.0)
Run Code Online (Sandbox Code Playgroud)
更有趣的例子:
unreplace = lambda s: flip(s.replace)
replacements = ['abc', 'XYZ']
a = 'abc123'
b = a.replace(*replacements)
print b
print unreplace(b)(*replacements) # or just flip(b.replace)(*replacements)
Run Code Online (Sandbox Code Playgroud)