anru
anru

Reputation: 1414

call/cc with Break procedure

(define RESUME "ANY THING...")
(define BREAK
  (lambda (msg)
    (call/cc
      (lambda (k)
        (set! RESUME k)
        ((lambda (x) x) msg)))))


(define addition
  (lambda (x y)
    (+ x (BREAK 7))))


(define main
  (lambda args
    (print (addition 8 5))
    (print (RESUME 1))))

Above code keep outputs 9s, like trapped in infinite loop, why is this? from my understanding, (RESUME 1) should only be called once.

Invoke above program like below: csi -ss break.scm

Upvotes: 0

Views: 69

Answers (1)

jcubic
jcubic

Reputation: 66590

What you're doing is creating a loop:

you save continuation like this:

(define addition
  (lambda (x y)
    (+ x <SLOT>)))

and when you call (RESUME 1) it replaces the slot with 1 and continue execution of the code. Next line is this:

(+ x 1)

And the rest of the code up the execution stack:

(print (addition 8 1)
(print (RESUME 1))

and when RESUME is called it jumps to the same place <SLOT> with 1, so it creates infinite loop of 9, (+ x 1) ==> (+ 8 1)

You basically have implemented GOTO. This is a simplification of your code:

(define GOTO "ANY THING...")
(define START (lambda ()
                (call/cc (lambda (k)
                           (set! GOTO k)))))

(define main
  (lambda args
    (START)
    (print "xx")
    (GOTO 'x))) ;; continuation needs argument

Upvotes: 1

Related Questions