方案中的连续传递风格? [英] Continuation-Passing Style in Scheme?
问题描述
(define (pyth x y k)(* x x (拉姆达 (x2)(* y y (λ (y2)(+ x2 y2 (λ (x2py2)(sqrt x2py2 k)))))))))
文章说那段代码是另一段代码的Continuation-Passing版本:
(定义(pyth x y)(sqrt (+ (* x x) (* y y))))
然而,我很困惑:这到底是怎么工作的?在这里,你如何将一个数字乘以一个 lambda?(* x x (lambda ...))
在维基百科示例中,*
与常规示例中的 *
的含义不同.
我会将维基百科的例子改写为:
(define (pyth x y k)(cps-* x x (拉姆达 (x2)(cps-* y y (λ (y2)(cps-+ x2 y2 (λ (x2py2)(cps-sqrt x2py2 k)))))))))
在这种形式中,每个 cps-xxx
函数执行指定的操作,然后将结果传递给最后一个参数.你可以这样称呼它:
(pyth 2 3 显示)
将 2 和 3 相乘,得到 6,然后将 6 传递给 display
.(实际上,您可能希望将结果传递给 cps-display
,后者显示其初始参数,然后调用指定为其最后一个参数的另一个函数).>
I ran into this code on Wikipedia:
(define (pyth x y k)
(* x x (lambda (x2)
(* y y (lambda (y2)
(+ x2 y2 (lambda (x2py2)
(sqrt x2py2 k))))))))
The article says that that code is the Continuation-Passing version of another piece of code:
(define (pyth x y)
(sqrt (+ (* x x) (* y y))))
However, I'm quite confused: How does that even work? How do you multiply a number by a lambda here? (* x x (lambda ...))
In the Wikipedia example, *
doesn't mean the same thing as *
in the conventional example.
I would rewrite the Wikipedia example as:
(define (pyth x y k)
(cps-* x x (lambda (x2)
(cps-* y y (lambda (y2)
(cps-+ x2 y2 (lambda (x2py2)
(cps-sqrt x2py2 k))))))))
In this form, each of the cps-xxx
functions perform the operation indicated and then pass the result to the last argument. You could call it like this:
(pyth 2 3 display)
which would multiply 2 and 3, giving 6, and then passing 6 to display
. (Actually you would want to pass the result to a cps-display
that displayed its initial argument(s) and then called another function specified as its last parameter).
这篇关于方案中的连续传递风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!