1

If a continuation captures the rest of a computation, why doesn't the following snippet of Scheme code enter into an infinite loop?

(define cont #f)

(define (funny1)
    (print "entered funny")
    (call/cc (lambda (k) (set! cont k)))
    (print "left funny"))

(funny1)
(print "end")
(cont)

It seems like returning from the function and calling 'print' and 'cont' should be part of the rest of the computation, triggering an infinite loop. Instead, it simply prints: "entered funny", "left funny", "end", "left funny"

The following CPS transformation of the previous snippet does, indeed, enter an infinite loop as expected:

(define cont #f)

(define (funny2 ret)
    (print "entered funny")
    (let ((rest (lambda ()
                    (print "left funny")
                    (ret))))
        (set! cont rest)
        (rest)))

(funny2 (lambda ()
            (print "end")
            (cont))))

What am I missing here?

user3026691
  • 497
  • 2
  • 11
  • 1
    This has to do with the top-level. If you put the code inside a function `(define (main) (funny1) (print "end") (cont))` and then call it `(main)` it *will* loop. – uselpa Feb 23 '16 at 20:01
  • 1
    Have a look at http://stackoverflow.com/questions/25339956/scheme-continuation-whats-the-difference-between-call-call-cc-in-top-level-a – uselpa Feb 23 '16 at 20:03
  • Also consider looking at [delimited continuations](http://stackoverflow.com/q/29838344/465378), which generalize the idea of continuation capture. – Alexis King Feb 24 '16 at 04:14

0 Answers0