斐波那契数列上的 U 组合器:如何将此代码转换为 python?
我正在尝试了解组合器,但无法理解 (Y overriding自行申请)。我想我已经开始理解这个概念了,但距离理解还很远。
我想将以下代码翻译为 Python:
(define (U f) (f f))
(define (fib-nr f)
(lambda (n)
(if (< n 2) 1 (+ ((f f) (- n 1)) ((f f) (- n 2))))))
# Usage:
((U fib-nr) 35) ;==> 14930352
我尝试通过编写进行“字面”翻译:
U = lambda u: u(u)
def fibnr(f):
return lambda n: 1 if (n<2) else (f (f (n-1))) + (f (f (n-2)))
但这不起作用(我认为这与 lambda 内评估函数的顺序有关)。
所以我尝试将函数组合用作:
# http://code.activestate.com/recipes/52902-function-composition/
class compose:
'''compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))'''
def __init__(self, f, g, *args, **kwargs):
self.f = f
self.g = g
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs)
U = lambda u: compose(u, u)
def fibnr(f):
ff = compose(f, f)
return lambda n: 1 if (n<2) else (ff (n-1)) + (ff (n-2))
但仍然不起作用,当调用我的最后一段代码时,我得到了一个 lambda:
>>> U(fibnr)(35)
<function <lambda> at 0x01A1B6B0>
那么,是否有可能在 Python 中编写给定示例的“字面”翻译?我怎样才能做到呢?
I am trying to learn about combinators and I am having trouble understand the example given at (Y overriding self-application). I think I am beginning to grasp the concept but I am still far from understanding.
I would like to translate the following code to Python:
(define (U f) (f f))
(define (fib-nr f)
(lambda (n)
(if (< n 2) 1 (+ ((f f) (- n 1)) ((f f) (- n 2))))))
# Usage:
((U fib-nr) 35) ;==> 14930352
I tried a 'literal' translation by writing:
U = lambda u: u(u)
def fibnr(f):
return lambda n: 1 if (n<2) else (f (f (n-1))) + (f (f (n-2)))
But this doesnt work (I think it has to do with the order the functions are evaluated inside the lambda).
So I tried to use function composition as:
# http://code.activestate.com/recipes/52902-function-composition/
class compose:
'''compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))'''
def __init__(self, f, g, *args, **kwargs):
self.f = f
self.g = g
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs)
U = lambda u: compose(u, u)
def fibnr(f):
ff = compose(f, f)
return lambda n: 1 if (n<2) else (ff (n-1)) + (ff (n-2))
But still didn't work, when calling my last snippet of code I get a lambda back:
>>> U(fibnr)(35)
<function <lambda> at 0x01A1B6B0>
So, is it possible to write a 'literal' translation of the given example in Python? How could I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我写了一个简单的翻译,似乎产生了正确的结果:
或者如果你真的喜欢 lambdas:
我认为你最初的问题是将 Lisp
((ff) x)
翻译成 Pythonf(f(x ))
而不是f(f)(x)
。祝你好运理解组合器:)
I wrote a simple translation that seems to produce correct results:
Or if you really like lambdas:
I think your initial problem was translating Lisp
((f f) x)
into Pythonf(f(x))
instead off(f)(x)
.Good luck understanding combinators :)