It's fairly straightforward to write a function that composes two other functions. (For simplicity, assume they are one parameter each.)
def compose(f, g):
fg = lambda x: f(g(x))
return fg
def add1(x):
return x + 1
def add2(x):
return x + 2
print(compose(add1, add2)(5)) # => 8
I would like to do composition using an operator, e.g., (add1 . add2)(5)
.
Is there a way to do that?
I tried various decorator formulations, but I couldn't get any of them to work.
def composable(f):
"""
Nothing I tried worked. I won't clutter up the question
with my failed attempts.
"""
@composable
def add1(x):
return x + 1
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…