Scheme call/cc iterator step by step

 
#lang scheme

(define (consume)
  (call/cc control))

(define (control ret)
  (call/cc (lambda (resume)
             (set! control resume)
             (ret 1)))
  (call/cc (lambda (resume)
             (set! control resume)
             (ret 2)))
  (call/cc (lambda (resume)
             (set! control resume)
             (ret 3))))

(consume)
(consume)

Every time control is called, it resets itself to “resume”, which is next expression to be executed.

Next step, we rewrite control function to take numbers from a list. It is done by adding for-each and a lambda function to consume every number in the list:

#lang scheme
(define (consume)
  (call/cc control))

(define (control ret)
  (for-each
   (lambda (elem)
     (call/cc (lambda (resume)
                (set! control resume)
                (ret elem))))
   '(1 2 3)))

Finally, we put both consume and control functions inside a function itor. We take a list as parameter, instead of hard coded input.

#lang scheme
(define (itor lst)
  (define (consume)
    (call/cc control))
  
  (define (control ret)
    (for-each
     (lambda (elem)
       (call/cc (lambda (resume)
                  (set! control resume)
                  (ret elem))))
     lst))

  consume)

(define consume (itor '(a b c)))
(consume)
(consume)

Advertisements
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s