function making

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

    When you do f = g for the second time, f becomes lambda x: f(x). Closures are created by name, not by value.


    This becomes easy with a helper function:

    def compose(f, g):
        return lambda x: f(g(x))
    
    square = lambda x:x*2
    g = square
    for i in xrange(4):
        g = compose(g, square)
    

提交回复
热议问题