【问题标题】:Return function that modifies the value of the input function修改输入函数值的返回函数
【发布时间】:2014-12-01 00:04:23
【问题描述】:

如何创建一个函数,该函数将函数作为输入并返回值三倍的函数。这是我正在寻找的一些伪代码。 Python 或 Scala 中的具体示例将不胜感激。

def f(int x):
    return x ** 2

def tipleFunc(Function g)
    return 3 * g

Function newFunc = tripleFunc(f)
print newFunc(5)

【问题讨论】:

  • IMO,Python 应该支持类似的东西。 __mul__ 根本没有为函数 ATM 定义,也没有其他明显的解释。

标签: python scala functional-programming higher-order-functions


【解决方案1】:
def f(x):
    return x ** 2

def tripleFunc(g):
    return lambda *args: 3 * g(*args)

newFunc = tripleFunc(f)
print newFunc(5)

【讨论】:

  • 有什么方法可以返回一个函数以将 x 传递给它,还是我必须将函数和它可能需要的任何参数传递给它?
【解决方案2】:

在 Scala 中:

def foo(x: Int) = x * x
def quadruple(f: Int => Int) = (x: Int) => 4 * f(x)
val quadfoo = quadruple(foo)
scala> quadfoo(3)
res0: Int = 36

【讨论】:

    【解决方案3】:

    您可以使用 Python @decorator 语法来执行此操作; @decorator 等价于分配somefunc = decorator(somefunc),允许应用任意包装函数:

    >>> from functools import wraps
    >>> def multiplier(n):
        """Create a decorator to multiply a wrapped function's output by n."""
        def wrapper(f):
            @wraps(f) # retain the wrapped function's docstring
            def func(*args, **kwargs):
                return n * f(*args, **kwargs)
            return func
        return wrapper
    
    >>> @multiplier(3) # apply a multiplier of 3 to the outputs of f
    def f(x):
        """Return x squared."""
        return x ** 2
    
    >>> f(5)
    75
    

    注意*args, **kwargs 语法来处理任意参数(分别是位置和关键字)。您也可以直接创建triple_func 装饰器,例如:

    >>> triple_func = multiplier(3)
    >>> @triple_func
    def f(x):
        """Return x squared."""
        return x ** 2
    
    >>> f(5)
    75
    

    甚至可以在没有装饰器语法的情况下应用它:

    >>> def f(x):
        """Return x squared."""
        return x ** 2
    
    >>> new_func = triple_func(f) # or 'new_func = multiplier(3)(f)'
    >>> new_func(5)
    75
    

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多