-1

如何創建一個函數作爲輸入並返回一個函數,其值爲三倍。這裏是我正在尋找的一些僞代碼。 Python或Scala中的具體示例值得讚賞。返回函數,修改輸入函數的值

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

def tipleFunc(Function g) 
    return 3 * g 

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

IMO,巨蟒* *應該支持這樣的事情。函數ATM沒有定義'__mul__',並且沒有其他明顯的解釋。 – chepner 2014-10-06 19:01:45

回答

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

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

newFunc = tripleFunc(f) 
print newFunc(5) 
+0

有沒有什麼辦法可以返回一個函數來傳入x或者是否必須傳遞函數以及它可能需要的任何參數? – 2014-10-06 17:08:19

+0

請參閱我的更新。 – uselpa 2014-10-06 17:09:34

2

在斯卡拉:

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 
0

您可以使用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