control, resumed

Since at least some people helped me re-re-invent prompt after my last post, I thought I would remind people that PLT Scheme is the only production system in the world that provides delimited and (truly) composable continuations directly (and w/o loss of TCO properties). So here is the same fragment again:

(require (lib "control.ss"))

(define (generate-one-element-at-a-time a-list)
  (define (control-state)
    (for-each (lambda (an-element-from-a-list)
  (control resume-here
    (set! control-state resume-here)
  (define (generator) (prompt (control-state)))
Take a look, compare and contrast with the previous post. Time permitting, I will continue to show you another control poem soon. P.S. See Adding Delimited and Composable Control to a Production Programming Environment for details.


call/cc and self-modifying code

Today I wrote this short illustration of call/cc and posted it on wikipedia:

;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end-off-the-list)
(define (generate-one-element-at-a-time a-list)
  ;; (-> X u 'you-fell-off-the-end-off-the-list)
  ;; this is the actual generator, producing one item from a-list at a time
  (define (generator)
     (call/cc control-state)) 
  ;; hand the next item from a-list to "return" (or an end-of-list marker)'
  (define (control-state return)
        (lambda (an-element-from-a-list)
           (set! return ;; fixed
               (lambda (resume-here)
                 (set! control-state resume-here)
                 (return an-element-from-a-list)))))
     (return 'you-fell-off-the-end-off-the-list))
  ;; time to return the generator
It reminded of all the talk in the 1980s and 1990s that self-modifying code is bad. But look at the elegant assignment to control-state within its body. It's such a poem, I thought I'd share it with people since nobody else blogs here anywya.