[racket] Weird continuation behavior (to me...)

From: Stephen Halter (halter73 at gmail.com)
Date: Sat Aug 6 06:28:31 EDT 2011

Hi everyone,

I was reading through the wikipedia article on call/cc, and I thought that playing around with some of the provided examples in DrRacket would give me a better understanding of the feature. The second example was how a python style generator could be created using call/cc (http://en.wikipedia.org/wiki/Call-with-current-continuation#Examples).

I was looking how set! was used to update control-state's return argument to the continuation referencing the most recent call to the generator. I figured that if I removed the set! and called the generator twice in a row, it would create an infinite loop of sorts since control-state's return argument would forever hold a continuation originating from the first call. However, this is not what happens when I remove the set!. Instead it works exactly the same way it did before. Any ideas why?

Thanks in advance for your help,
Stephen Halter

Below is the code that I where I don't (re)set! control-state's return argument: 

https://gist.github.com/1129202

#lang racket

;; Since the control-state blows itself away after the first call by
;; set!ing itself to a continuation, I would expect the return argument to
;; control-state to retain the value from it's first call. Therefore I 
;; expected that calls subsequent to the first call to control-state would
;; "return" execution back to the first call creating an infinite loop of
;; sorts, but in DrRacket 5.1 it outputs 0 1 and finishes execution.

;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end)
(define (generate-one-element-at-a-time lst)
 
  ;; Hand the next item from a-list to "return" or an end-of-list marker
  (define (control-state return)
    (for-each 
     (lambda (element)
               (call-with-current-continuation
                (lambda (resume-here)
                  ;; Grab the current continuation
                  (set! control-state resume-here)
                  (return element))))
     lst)
    (return 'you-fell-off-the-end))
 
  ;; (-> X u 'you-fell-off-the-end)
  ;; This is the actual generator, producing one item from a-list at a time
  (lambda () (call-with-current-continuation control-state)))
 
(define generate-digit
  (generate-one-element-at-a-time '(0 1 2 3 4 5 6 7 8 9)))

(generate-digit)
(generate-digit)


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20110806/e8423826/attachment.html>

Posted on the users mailing list.