6

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 ...))

user541686
  • 205,094
  • 128
  • 528
  • 886
  • 3
    Elegant weapons for a more civilized age. – corsiKa Feb 20 '11 at 18:48
  • 1
    Just ran into your question after posting a [similar one](http://stackoverflow.com/q/38611717/1488067). Good news is that the [Wikipedia article](http://en.wikipedia.org/wiki/Continuation-passing_style) has been updated in the meantime to use `*&`, `+&` and `sqrt&`, i.e. a convention where an ampersand is appended to each function which accepts a continuation as the last parameter. It took me a while nevertheless to understand that these functions are not part of Scheme's standard operators, but implemented explicitly. – Lou Jul 27 '16 at 11:36

1 Answers1

7

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).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • More specifically, for people who want to actually try this out: (define (cps-* x y k) (k (* x y)), (define (cps-+ x y k) (k (+ x y))), and (define (cps-sqrt n k) (k (sqrt n))). – jacobm Feb 20 '11 at 19:00
  • Gotcha... that asterisk in the article is **very** misleading; thanks a lot for clarifying that! :) – user541686 Feb 20 '11 at 19:02
  • 1
    In CPS every function has one (or more) extra parameter for the continuation. Multiply and add are normal functions ... – knivil Feb 20 '11 at 20:07