【问题标题】:Standard name for a function that modifies a function to ignore an argument修改函数以忽略参数的函数的标准名称
【发布时间】:2015-03-04 21:05:10
【问题描述】:

我使用 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 有标准名称吗?我对标准库中具有此类功能的任何语言都感兴趣。

【问题讨论】:

    标签: functional-programming


    【解决方案1】:

    大多数函数式编程语言都提供const 函数,该函数将始终忽略它的第一个参数并返回它的第二个参数。如果你将一个函数传递给 const,那正是你所描述的行为。

    在 Haskell 中你可以这样使用它:

    f x = x + 1
    g = const f
    g 2 3 == 4 --2 is ignored and 3 is incremented
    

    我已经在 python 中快速搜索过这样的函数,但没有找到任何东西。似乎标准是像您一样使用 lambda 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      相关资源
      最近更新 更多