功能制作 [英] function making
问题描述
>>> g = lambda x:x * 2
>>> f = g
>>> g = lambda×:f(f(x))
>>> g(9)
36
现在,它不会创建 g
作为非终结递归函数 - g(x)
被转换为一个新函数,该函数给出结果 g(g (X))
。
>>> f = g
>>> g = lambda×:f(f(x))
>>> f(8)
RuntimeError:超过最大递归深度
我预计 g
将被转换成一个函数,该函数根据g的第一个定义给出结果 g(g(g(x)))
(X)。为什么没有?是否有可能创建一个新的函数,其结果为 g(g(g(...(g(x))....)))
这种方式的迭代?
当你做 f = g
第二次,f变成 lambda x:f(x)
。关闭是通过名称而不是价值创建的。
$ b
def compose(f,g):
return lambda x:f(g(x))
square = x = x * 2
g = square
对于xrange(4)中的i:
g = compose(g,square)
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
Now, it is not creating g
as a nonterminating recursive function - g(x)
is transformed to a new function which gives the result g(g(x))
.
>>> f=g
>>> g=lambda x:f(f(x))
>>> f(8)
RuntimeError: maximum recursion depth exceeded
I expected g
to be transformed into a function which gives the result g(g(g(x)))
, according to the first definition of g(x). Why does it not? Is it possible to make a new function which results in g(g(g(...(g(x))....)))
for a certain number of iterations in this way?
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)
这篇关于功能制作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!