function making

后端 未结 3 672
长发绾君心
长发绾君心 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:36

    In python, variables are names mapped to values, not values themselves (everything is a reference). Also, you can think of lambda as storing text that can be evaluated. The following will illustrate

    a = 2
    f = lambda x: a*x
    f(2) # This gives 4
    a = 3
    f(2) # This gives 6
    

    This should clear up why you are getting infinite recursion.

    In answer to your question about recursing, here is a little hack that might do

    g = lambda x, n: n > 0 and g(x, n-1)**2 or x
    

    Then g(2,3) would be (((2)^2)^2)^2 = 256.

提交回复
热议问题