Python: nested lambdas — `s_push: parser stack overflow Memory Error`

寵の児 提交于 2019-11-29 07:33:04

express the number 100 without having so many nested functions?

here you go:

>>> test = lambda f: f(lambda x: x + 1)(0)
>>> z = lambda f: lambda x: x
>>> test(z)
0
>>> succ = lambda n: lambda f: lambda x: f(n(f)(x))
>>> _1 = succ(z)
>>> test(_1)
1
>>> _2 = succ(_1)
>>> test(_2)
2
>>> plus = lambda m: lambda n: lambda f: lambda x: m(f)(n(f)(x))
>>> _3 = plus(_1)(_2)
>>> test(_3)
3
>>> mult = lambda m: lambda n: lambda f: lambda x: m(n(f))(x)
>>> _6 = mult(_2)(_3)
>>> test(_6)
6
>>> _5 = plus(_2)(_3)
>>> _25 = mult(_5)(_5)
>>> _4 = plus(_2)(_2)
>>> _100 = mult(_25)(_4)
>>> test(_100)
100
>>> 

It looks like it's not possible without recompiling Python. The parser stack size is set with the constant MAXSTACK in parser.h. You could increase this value and recompile to increase the limit. See http://bugs.python.org/issue3971 and http://mail.python.org/pipermail/python-list/2012-March/621555.html .

From the lambda-calculus standpoint, incrementing a number can be done with the following function:

succ = lambda n: lambda p: lambda x: p(n(p)(x))

Then, one = succ(zero), two = succ(one), and so forth.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!