function making

后端 未结 3 696
长发绾君心
长发绾君心 2021-01-19 09:42

Hi I am new to functional programming. What i did is

>>> g=lambda x:x*2
>>> f=g
>>> g=lambda x:f(f(x))
>>> g(9)
36
         


        
3条回答
  •  没有蜡笔的小新
    2021-01-19 10:34

    This

    g=lambda x:x*2
    f=g
    g=lambda x:f(x)
    

    is equivalent to:

    f=lambda x:x*2
    g=lambda x:f(x)
    

    When you call g, you get whatever f happens to be defined in the global (or enclosing) scope.

    what you're expecting is something like:

    f=lambda x:x*2
    g=lambda x, f=f:f(x)
    

    That captures the value of f in the outer scope at the time the lambda expression is evaluated.

提交回复
热议问题