[英]a function composition VS a function that acts on another function
我有許多可重用的函數,所有函數都具有相同的簽名(它們record
並返回float
)。 我經常需要將功能合並為新功能。
假設我要創建一個接受record
的函數,將f
應用於record
,如果結果為負,則將其轉換為零。 我有兩種方法:組合和函數修改。 每種方法的優缺點是什么?
組成:
def non_negative(value):
return max(0, value)
g = compose(non_negative, f)
# from functional module by Collin Winter
def compose(func_1, func_2, unpack=False):
"""
compose(func_1, func_2, unpack=False) -> function
The function returned by compose is a composition of func_1 and func_2.
That is, compose(func_1, func_2)(5) == func_1(func_2(5))
"""
if not callable(func_1):
raise TypeError("First argument to compose must be callable")
if not callable(func_2):
raise TypeError("Second argument to compose must be callable")
if unpack:
def composition(*args, **kwargs):
return func_1(*func_2(*args, **kwargs))
else:
def composition(*args, **kwargs):
return func_1(func_2(*args, **kwargs))
return composition
修改:
def non_negative(func):
def new_func(record):
return max(0, func(record))
return new_func
g = non_negative(f)
假設compose
在庫中可用,那么在此示例中,我希望使用這種樣式。
主要原因是,它消除了將一個值鉗位為非負值並將一個函數的結果提供給另一個函數的擔憂。 在“修改”樣式中,如果您發現自己想對一個值而不是對一個函數的結果運行non_negative
,那么您最終會得到諸如non_negative(lambda x: x)(value)
類的扭曲。 而且,您需要為可能要組成的每個事物函數編寫一個單獨的函數,每個函數都包含與該函數的代碼混合的組成邏輯。
在此示例中,無論采用哪種方式,負擔都是微不足道的。 但是通常,如果您很容易制作獨立的小片段,然后將它們粘合在一起以創建復合代碼,那么這就是個好方法。
您的兩個示例完全一樣,只是在一種情況下使用無點樣式,而在另一種情況下則不使用無點樣式。
唯一的考慮是您(以及閱讀您的代碼的人)最容易閱讀。 在某些情況下,我發現無點樣式最自然; 這是其中一種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.