Continuation style intermediate and return values

I come from OOP, a non-functional background, so I had problems fully rendering several online examples regarding the continuation of the transfer . In addition, functional languages ​​such as Scheme should not indicate argument types or return values, so I'm not sure if I got this idea correctly.

Since C # supports lambdas, I took the first example from a Wikipedia article and tried to port it to C # with strong typing to see how the template would apply:

// (Scheme)

// direct function
(define (pyth x y)
 (sqrt (+ (* x x) (* y y))))

// rewriten with CPS 
(define (pyth& x y k)
 (*& x x (lambda (x2)
          (*& y y (lambda (y2)
                   (+& x2 y2 (lambda (x2py2)
                              (sqrt& x2py2 k))))))))

// where *&, +& and sqrt& are defined to 
// calculate *, + and sqrt respectively and pass the result to k
(define (*& x y k)
 (k (* x y)))

So, rewriting the CPS version pyth&in C # led to:

// (C#6)

// continuation function signature
delegate double Cont(double a);

// *&, +& and sqrt& functions
static double MulCont(double a, double b, Cont k) => k(a * b);
static double AddCont(double a, double b, Cont k) => k(a + b);
static double SqrtCont(double a, Cont k) => k(Math.Sqrt(a));

// sqrt(x*x + y*y), cps style
static double PythCont(double x, double y, Cont k) =>
    MulCont(x, x, x2 =>
        MulCont(y, y, y2 =>
            AddCont(x2, y2, x2py2 =>
                SqrtCont(x2py2, k))));

I could use generics instead double, but the signatures will be longer. Anyway, I'm not sure:

  • Cont (.. Func<double, double>)? fn. , , ?

  • , , , sqrt&, , "" . k(Math.Sqrt(x * x + y * y)), , "" ?

+2
1
  • , - , . "Cont", , .

    (define (foo x) (if (= x 0) 1 0))

(, ):

(define (foo& x k)
  (=& x 0 (lambda (r1)
            (if r1 (k 1) (k 0)))))

- ( , int) , , "= &" bool- > int.

  1. ( ) - . , cps - ( , call/cc), , . cps, ( -).

, , - , cps . , , , (, ) , , , , . , - , [, , - ]. , , ? , , - stdout, . . , , gambit-C, , - ;). cps [ , cps!]. , "+" . :

(define (pyth& x y k)
 (*& y y (lambda (y2)
          (*& x x (lambda (x2)
                   (+& x2 y2 (lambda (x2py2)
                              (sqrt& x2py2 k))))))))

.

, , CPS , lambdas, , , , , - , , , C - . ! , mumbo-jumbo, , , , CPS , , " -" ( ) "", "" ( -). , , , , - cps , cps.

, .

+3

All Articles