如果有一个compose
函数,那就太好了——也许在functools
. 没有,我也不期望会有,唉。用雷蒙德·海廷格的话来说,
之前已经在其他论坛讨论过并拒绝了。问题之一是通常的数学顺序是不直观的并且不是自我记录的——即与orcompose(f,g)
相同?此外,创建自己的合成功能或直接进行合成已经很简单了: .f(g(x))
g(f(x))
h = lambda x: f(g(x))
以下是作为可调用类的两个简单实现compose
,您可能会发现它们很有用:
# Scott Daniels, http://code.activestate.com/recipes/52902-function-composition/
# Lightly edited for style.
class Compose(object):
'''Compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))'''
def __init__(self, f, g, *args, **kwargs):
self.f = f
self.g = g
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs)
class Starcompose:
'''Compose functions. Starcompose(f,g,x...)(y...) = f(*g(y...),x...))'''
TupleType = type(())
def __init__(self, f, g, *args, **kwargs):
self.f = f
self.g = g
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
mid = self.g(*args, **kwargs)
if isinstance(mid, self.TupleType):
return self.f(*(mid + self.pending), **self.kwargs)
return self.f(mid, *self.pending, **self.kwargs)
另外,请参阅functional
包,它启发compose_many
了我不久前的这个非常简单的功能:
def compose(f1, f2):
def composition(*args, **kwargs):
return f1(f2(*args, **kwargs))
return composition
def compose_many(*funcs):
return reduce(compose, funcs)