Python 递归错误组合lambdas

Python 递归错误组合lambdas,python,python-3.x,recursion,lambda,Python,Python 3.x,Recursion,Lambda,我正在尝试编写一个由任意数量的lambda函数组成的函数 我有两个简单的lambda函数 f = lambda x: x + 1 g = lambda x: x**2 我对合成函数的尝试如下: def compose(*functions): composed = lambda x: x # Function that returns input for function in reversed(functions): composed = lambda x:

我正在尝试编写一个由任意数量的lambda函数组成的函数

我有两个简单的lambda函数

f = lambda x: x + 1
g = lambda x: x**2
我对合成函数的尝试如下:

def compose(*functions):
    composed = lambda x: x  # Function that returns input
    for function in reversed(functions):
        composed = lambda x: function(composed(x))
    return composed
我的想法是循环使用数量可变的函数,每次都使组合的函数包含一个新函数

然后我可以制作一个由
f
g
组成的函数

c = compose(f, g)
因此调用
c(5)
应该返回
f(g(5))
,即26。但是相反,我得到了

RecursionError: maximum recursion depth exceeded
我认为引入一个中间变量可能会解决这个问题

def compose(*functions):
    composed = lambda x: x  # Function that returns input
    for function in reversed(functions):
        intermediate = lambda x: function(composed(x))
        composed = intermediate
    return composed
但也出现了同样的错误


有办法解决这个问题吗?

首先,我认为您的方法会受到后期闭包绑定的影响,因为lambda中的
函数
只会在迭代结束时获取函数的最后一个值。其次,由于第一个原因,
composed
最终只会递归地调用自己
composed
-lambda-调用
composed
-自身的最后一个值

一种可能的修复方法是在每次迭代时将
组合
函数
绑定到
lambda

def compose(*functions):
    composed = lambda x: x
    for function in reversed(functions):
        composed = lambda x, function=function, composed=composed: function(composed(x))
    return composed

print(compose(f, g)(5))
# 26
但您的总体问题看起来是一个很好的用例:


很好的解决方案,但是你能在OP的尝试中发现错误吗?@juanpa.arrivillaga正在查看是的,刚刚发现是由于后期绑定。
from functools import reduce

def compose(*functions):
    def inner(v):
        return reduce(lambda x, y: y(x),  reversed(functions), v)
    return inner

print(compose(f, g)(5))
# 26