我使用 Python 是因为它通常很容易阅读,但这不是一个特定于 Python 的问题。
采用以下 Python 函数 strip_argument
:
def strip_argument(func_with_no_args):
return lambda unused: func_with_no_args()
在使用中,我可以将一个无参数函数传递给 strip_argument
,它将返回一个接受一个从未使用过的参数的函数。例如:
# some API I want to use
def set_click_event_listener(listener):
"""Args:
listener: function which will be passed the view that was clicked.
"""
# ...implementation...
# my code
def my_click_listener():
# I don't care about the view, so I don't want to make that an arg.
print "some view was clicked"
set_click_event_listener(strip_argument(my_click_listener))
函数strip_argument
有标准名称吗?我对标准库中具有此类功能的任何语言都感兴趣。
最佳答案
大多数函数式编程语言都提供 const
函数,该函数始终会忽略第一个参数并返回第二个参数。如果您将函数传递给 const,这正是您所描述的行为。
在 Haskell 中你可以这样使用它:
f x = x + 1
g = const f
g 2 3 == 4 --2 is ignored and 3 is incremented
我在 python 中快速搜索了这样的函数,但没有找到任何东西。看来标准是像您一样使用 lambda 函数。
关于functional-programming - 修改函数以忽略参数的函数的标准名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28864907/