在python中的lambda
我在python中重新考慮一些方案練習(如果有意義的話),找出py可以在FP方面做什麼.我的問題在python中涉及lambda:
我可以在python中定義一個函式作為引數之一嗎?
想想:
def f (op,x,y): #return some lambda function that combines x and y in the appropriate way #i.e if op is +, then return x+y, if op is -, then return x-y etc #Edit : added usage #this should be called like this: f(+, 1,2) #should return 3
我知道這是可能的方案,但有什麼等同於python?我得到的印象是,在python中的lambda只是定義一個方法的一種較短的方式,我沒有找到任何方法來定義python中的一般組合函式.
我可以在你的問題中看到一些點,讓我們按順序通過它們:
我可以把一個函式作為引數傳遞給某人嗎?
是:
def f(op, x, y): return op(x, y) def add(x, y): return x + y f(add, 10, 7) #gives 17
2.那麼呢呢呢?
與方案不同,Python操作符不是函式,因此您不能直接作為引數傳遞它們.您可以自己建立包裝器功能,也可以從標準庫匯入ofollow,noindex" target="_blank">operator 模組.
import operator operator.add(1, 2) (lambda x,y : x+y)(1, 2)
在大多數情況下,運算子不是真正的功能是有點難過,但至少Python給我們連結的比較,如10<= x<100交換... 那麼Python和Scheme之間有什麼區別呢? 在一般意義上,Python中的函式與Scheme中的函式一樣強大,但有一些注意事項: lambda關鍵字有限 您只能具有單個表示式作為函式體
f = lambda x, y: x + y
由於Python中有一些是語句而不是表示式(賦值,2.x列印,…)的東西,往往需要回到命名函式.
有關閉
def make_printer(msg): def printer(): print msg return printer printer('a message')()
但它們中變異的變數是一種痛苦
這不行.它嘗試繫結內部函式的新n,而不是使用外部函式
def make_counter(n): def inc(): n = n + 1 return n return inc
新的3.x非本地關鍵字
def make_counter(n): def inc(): nonlocal n n = n + 1 return n return inc
解決方案w /可變物件
def make_counter(n): nw = [n] def inc(): nw[0] = nw[0] + 1 return nw[0] return inc
物件而不是關閉.使用魔術__call__方法假裝其功能
class Counter: def __init__(self, n): self.n = n def __call__(self): self.n += 1 return self.n
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/7974442/lambda-in-python