本文介绍了"更新" lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我正在尝试编写一个解析

表达式并从中构建函数树的Python函数

(递归)。


在解析过程中,术语

和子表达式的lambda函数是动态构建的。

现在我的问题是懒惰的评价。或者至少我认为它是b $ b。 :-)


我需要更新一个lambda函数,像这样:


fu = lambda x:x

...

fu = lambda x:fu (x)+ 17

...

fu = lambda x:fu(x)* 3


当然是不起作用,因为fu被解决了,当调用lambda时,
,而不是在定义时,所以

我会遇到无休止的递归。


我目前的解决方案是定义一个辅助函数

,它通过它的参数传递lambda:


def add_17(fu):

返回lambda x:fu(x)+ 17

def mul_3(fu):

return lambda x:fu(x)* 3

fu = lambda x:x

...

fu = add_17 (fu)

...

fu = mul_3(fu)


这样可行,但它让我觉得不洁净丑陋。

还有更好的办法吗?


祝你好运

奥利弗


-

Oliver Fromme,Konrad-Celtis-Str。 72,81369慕尼黑,德国


`所有我们看到或看起来只是梦中的梦想。'''

(EA Poe)

Hi,

I''m trying to write a Python function that parses
an expression and builds a function tree from it
(recursively).

During parsing, lambda functions for the the terms
and sub-expressions are constructed on the fly.
Now my problem is lazy evaluation. Or at least I
think it is. :-)

I need to "update" a lambda function, like this:

fu = lambda x: x
...
fu = lambda x: fu(x) + 17
...
fu = lambda x: fu(x) * 3

Of course that doesn''t work, because fu is resolved
when the lambda is called, not when it''s defined, so
I''ll run into an endless recursion.

My current solution is to define a helper function
which passes the lambda through its argument:

def add_17 (fu):
return lambda x: fu(x) + 17

def mul_3 (fu):
return lambda x: fu(x) * 3

fu = lambda x: x
...
fu = add_17(fu)
...
fu = mul_3(fu)

That works, but it strikes me as unclean and ugly.
Is there a better way to do it?

Best regards
Oliver

--
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''''
(E. A. Poe)

推荐答案




这表示你需要使用类,而不是lambda函数。



That says you need to use classes, not lambda functions.




60


60





你可以利用函数成为绑定方法的方式,例如,



You could exploit the way functions become bound methods, e.g.,



-3


所有这些只是为了探索python的功能,而不是推荐特定用途;-)


问候,

Bengt Richter


-3

All just to explore python''s features, not to recommend specific uses ;-)

Regards,
Bengt Richter


这篇关于"更新" lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:13