问题
How can I make a function that is given a function as input and returns a function with the value tripled. Here is some pseudo code for what I'm looking for. Concrete examples in Python or Scala would be appreciated.
def f(int x):
return x ** 2
def tipleFunc(Function g)
return 3 * g
Function newFunc = tripleFunc(f)
print newFunc(5)
回答1:
def f(x):
return x ** 2
def tripleFunc(g):
return lambda *args: 3 * g(*args)
newFunc = tripleFunc(f)
print newFunc(5)
回答2:
In 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:
You can use the Python @decorator
syntax to do this; @decorator
is equivalent to assigning somefunc = decorator(somefunc)
, allowing an arbitrary wrapper function to be applied:
>>> 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
Note the *args, **kwargs
syntax to handle arbitrary arguments (positional and keyword, respectively). You can also create the triple_func
decorator directly, e.g.:
>>> triple_func = multiplier(3)
>>> @triple_func
def f(x):
"""Return x squared."""
return x ** 2
>>> f(5)
75
or even apply it without the decorator syntax at all:
>>> def f(x):
"""Return x squared."""
return x ** 2
>>> new_func = triple_func(f) # or 'new_func = multiplier(3)(f)'
>>> new_func(5)
75
来源:https://stackoverflow.com/questions/26221148/return-function-that-modifies-the-value-of-the-input-function