Chapter 6. Control Structures

This chapter describes Chez Scheme extensions to the set of standard control structures. See Chapter 5 of The Scheme Programming Language, 4th Edition or the Revised6 Report on Scheme for a description of standard control structures.

Section 6.1. Conditionals

syntax: (exclusive-cond clause1 clause2 ...)
returns: see below
libraries: (chezscheme)

exclusive-cond is a version of cond (Section 5.3 of TSPLFOUR) that differs from cond in that the tests embedded within the clauses are assumed to be exclusive in the sense that if one of the tests is true, the others are not. This allows the implementation to reorder clauses when profiling information is available at expansion time (Section 12.7).

The (test) form of clause is not supported. The order chosen when profiling information is available is based on the relative numbers of times the RHS of each clause is executed, and (test) has no RHS. (test => values) is equivalent, albeit less concise.

syntax: (case expr0 clause1 clause2 ...)
returns: see below
libraries: (chezscheme)

Each clause but the last must take one of the forms:

((key ...) expr1 expr2 ...)
(key expr1 expr2 ...)

where each key is a datum distinct from the other keys. The last clause may be in the above form or it may be an else clause of the form

(else expr1 expr2 ...)

expr0 is evaluated and the result is compared (using equal?) against the keys of each clause in order. If a clause containing a matching key is found, the expressions expr1 expr2 ... are evaluated in sequence and the values of the last expression are returned.

If none of the clauses contains a matching key and an else clause is present, the expressions expr1 expr2 ... of the else clause are evaluated in sequence and the values of the last expression are returned.

If none of the clauses contains a matching key and no else clause is present, the value or values are unspecified.

The Revised6 Report version of case does not support singleton keys (the second of the first two clause forms above) and uses eqv? rather than equal? as the comparison procedure. Both versions are defined in terms of exclusive-cond so that if profiling information is available at expansion time, the clauses will be reordered to put those that are most frequently executed first.

(let ([ls '(ii iv)])
  (case (car ls)
    [i 1]
    [ii 2]
    [iii 3]
    [(iiii iv) 4]
    [else 'out-of-range])) <graphic> 2

(define p
  (lambda (x)
    (case x
      [("abc" "def") 'one]
      [((a b c)) 'two]
      [else #f])))

(p (string #\d #\e #\f)) <graphic> one
(p '(a b c)) <graphic> two

syntax: (record-case expr clause1 clause2 ...)
returns: see explanation
libraries: (chezscheme)

record-case is a restricted form of case that supports the destructuring of records, or tagged lists. A record has as its first element a tag that determines what "type" of record it is; the remaining elements are the fields of the record.

Each clause but the last must take the form

((key ...) formals body1 body2 ...)

where each key is a datum distinct from the other keys. The last clause may be in the above form or it may be an else clause of the form

(else body1 body2 ...)

expr must evaluate to a pair. expr is evaluated and the car of its value is compared (using eqv?) against the keys of each clause in order. If a clause containing a matching key is found, the variables in formals are bound to the remaining elements of the list and the expressions body1 body2 ... are evaluated in sequence. The value of the last expression is returned. The effect is identical to the application of

(lambda formals body1 body2 ...)

to the cdr of the list.

If none of the clauses contains a matching key and an else clause is present, the expressions body1 body2 ... of the else clause are evaluated in sequence and the value of the last expression is returned.

If none of the clauses contains a matching key and no else clause is present, the value is unspecified.

(define calc
  (lambda (x)
    (record-case x
      [(add) (x y) (+ x y)]
      [(sub) (x y) (- x y)]
      [(mul) (x y) (* x y)]
      [(div) (x y) (/ x y)]
      [else (assertion-violationf 'calc "invalid expression ~s" x)])))

(calc '(add 3 4)) <graphic> 7
(calc '(div 3 4)) <graphic> 3/4

Section 6.2. Mapping and Folding

procedure: (ormap procedure list1 list2 ...)
returns: see explanation
libraries: (chezscheme)

ormap is identical to the Revised6 Report exists.

procedure: (andmap procedure list1 list2 ...)
returns: see explanation
libraries: (chezscheme)

andmap is identical to the Revised6 Report for-all.

Section 6.3. Continuations

Chez Scheme supports one-shot continuations as well as the standard multi-shot continuations obtainable via call/cc. One-shot continuations are continuations that may be invoked at most once, whether explicitly or implicitly. They are obtained with call/1cc.

Continuation marks support efficient annotation of continuations and inspection of those annotations. Each continuation has a table of marks, where each mark is a key-value pair. This table is updated using the with-continuation-mark form to associate a key with a value, replacing any existing association for that key. Although each continuation has a single immediate table of marks, a continuation may extend another continuation that has its own marks. The current-continuation-marks function captures the sequence of mark tables for a continuation and all continuations that it extends. Functions such as continuation-marks-first, continuation-marks->list, and continuation-marks->iterator can be used to inspect mark sequences. When a continuation is captured with call/cc, only the marks of the rest of the continuation are captured, and continuation-next-marks returns the captured marks.

procedure: (call/1cc procedure)
returns: see below
libraries: (chezscheme)

call/1cc obtains its continuation and passes it to procedure, which should accept one argument. The continuation itself is represented by a procedure. This procedure normally takes one argument but may take an arbitrary number of arguments depending upon whether the context of the call to call/1cc expects multiple return values or not. When this procedure is applied to a value or values, it returns the values to the continuation of the call/1cc application.

The continuation obtained by call/1cc is a "one-shot continuation." A one-shot continuation should not be returned to multiple times, either by invoking the continuation or returning normally from procedure more than once. A one-shot continuation is "promoted" into a normal (multishot) continuation, however, if it is still active when a normal continuation is obtained by call/cc. After a one-shot continuation is promoted into a multishot continuation, it behaves exactly as if it had been obtained via call/cc. This allows call/cc and call/1cc to be used together transparently in many applications.

One-shot continuations may be more efficient for some applications than multishot continuations. See the paper "Representing control in the presence of one-shot continuations" [3] for more information about one-shot continuations, including how they are implemented in Chez Scheme.

The following examples highlight the similarities and differences between one-shot and normal continuations.

(define prod
 ; compute the product of the elements of ls, bugging out
 ; with no multiplications if a zero element is found
  (lambda (ls)
    (lambda (k)
      (if (null? ls)
          1
          (if (= (car ls) 0)
              (k 0)
              (* (car ls) ((prod (cdr ls)) k)))))))

(call/cc (prod '(1 2 3 4))) <graphic> 24
(call/1cc (prod '(1 2 3 4))) <graphic> 24

(call/cc (prod '(1 2 3 4 0))) <graphic> 0
(call/1cc (prod '(1 2 3 4 0))) <graphic> 0

(let ([k (call/cc (lambda (x) x))])
  (k (lambda (x) 0))) <graphic> 0

(let ([k (call/1cc (lambda (x) x))])
  (k (lambda (x) 0))) <graphic> exception

procedure: (dynamic-wind in body out)
procedure: (dynamic-wind critical? in body out)
returns: values resulting from the application of body
libraries: (chezscheme)

The first form is identical to the Revised6 Report dynamic-wind. When the optional critical? argument is present and non-false, the in thunk is invoked in a critical section along with the code that records that the body has been entered, and the out thunk is invoked in a critical section along with the code that records that the body has been exited. Extreme caution must be taken with this form of dynamic-wind, since an error or long-running computation can leave interrupts and automatic garbage collection disabled.

syntax: (with-continuation-mark key val body)
returns: the value of the body expression
libraries: (chezscheme)

with-continuation-mark updates the table of marks on the current continuation to map the result of the key expression to the result of the val expression. If the current continuation's table of marks already has a mapping for key (based on eq? comparison), then the mark's value is replaced with val, otherwise a mapping from key to val is added to the table.

(with-continuation-mark
 'key "val"
 "hello") ; => "hello"

(with-continuation-mark
 'key "val"
 (continuation-marks-first (current-continuation-marks)
                           'key)) ; => "val"

(with-continuation-mark
 'key "val"
 (continuation-marks-first (current-continuation-marks)
                           'other-key)) ; => #f

(with-continuation-mark
 'key "val"
 (with-continuation-mark
  'key "val2"
  (continuation-marks-first (current-continuation-marks)
                            'key))) ; => "val2"

(with-continuation-mark
 'key "val"
 (with-continuation-mark
  'key "val2"
  (continuation-marks->list (current-continuation-marks)
                            'key))) ; => ("val2")

(with-continuation-mark
 'key "val"
 (values
  (with-continuation-mark
   'key "val2"
   (continuation-marks->list (current-continuation-marks)
                             'key)))) ; => ("val2" "val")

procedure: (continuation-marks? obj)
returns: boolean
libraries: (chezscheme)

A predicate that recognizes a continuation mark sequence, which can be produced by the functions current-continuation-marks and continuation-next-marks.

procedure: (current-continuation-marks)
procedure: (continuation-next-marks cont)
returns: a continuation mark sequence
libraries: (chezscheme)

Returns a captured sequence of mark tables, either the current continuation's marks in the case of current-continuation-marks or the marks of the rest of cont in the case of continuation-next-marks. In the latter case, cont must be a continuation.

This function takes constant time. The size of the resulting mark sequence is proportional to the number of distinct key-value mappings in the overall mark-table sequence; that size is bounded by the length of the continuation times the number of distinct values used as keys, but since many continuations have no keys or fewer than all possible keys in their tables, the size tends to be much less than the bound.

(continuation-marks? (current-continuation-marks)) ; => #t
(continuation-marks? (continuation-next-marks
                      (call/cc (lambda (k) k)))) ; => #t

procedure: (continuation-marks-first marks key)
procedure: (continuation-marks-first marks key none-val)
returns: the value for key in marks or none-val
libraries: (chezscheme)

Extracts the first value found for key in marks, checking the mark table of a continuation before checking the table of the continuation that it extends (if any). Keys are compared using eq?. If no mark for key is found, none-val is returned; if none-val is not provided, it defaults to #f.

This function takes amortized time proportional to the number of distinct values used as keys in marks. Typically the number of keys used in an application is bounded, which makes the computation amortized constant-time for those applications.

(with-continuation-mark
 'key "val"
 (values
  (with-continuation-mark
   'key "val2"
   (continuation-marks-first (current-continuation-marks)
                             'key)))) ; => "val2"

(with-continuation-mark
 'key "val"
 (continuation-marks-first (current-continuation-marks)
                           'other
                           "nope")) ; => "nope"

procedure: (continuation-marks->list marks key)
returns: a list
libraries: (chezscheme)

Returns the list of all values associated with key in marks, with the value from a continuation's mark table appearing before the values from the mark tables of any other continuation that it extends. Keys are compared using eq?.

This function takes time proportional to the size of the captured mark sequence.

(with-continuation-mark
 'key "val"
 (values
  (with-continuation-mark
   'key "val2"
   (continuation-marks->list (current-continuation-marks)
                             'key)))) ; => ("val2" "val")

(with-continuation-mark
 'key "val"
 (continuation-marks->list (current-continuation-marks)
                           'other)) ; => ()

procedure: (continuation-marks->iterator marks key-vector)
procedure: (continuation-marks->iterator marks key-vector none-val)
returns: a procedure
libraries: (chezscheme)

Generalizes the mark sequence traversal of continuation-marks->list to a functional iterator. The marks argument must be a continuation mark sequence, and the key-vector argument must be a vector of values to be used as keys. The result is an iterator procedure of zero arguments.

Calling the result iterator procedure (with no arguments) returns two values:

Obtaining an iterator from continuation-marks->iterator takes constant time. Each call to an iterator takes time proportional to the size of continuation mark tables that are traversed to find one of the keys in key-vector.

(with-continuation-mark
 'key "val"
 (with-continuation-mark
  'other "also"
  (values
   (with-continuation-mark
    'key "val2"
    (let loop ([iter (continuation-marks->iterator
                      (current-continuation-marks)
                      '#(key other))])
      (let-values ([(vec iter) (iter)])
         (if vec
             (cons vec (loop iter))
             '()))))))) ; => (#("val2" #f) #("val" "also"))

procedure: (call-with-immediate-continuation-mark key proc)
procedure: (call-with-immediate-continuation-mark key none-val proc)
returns: the value produced by calling proc
libraries: (chezscheme)

Similar to

 (continuation-marks-first (current-continuation-marks) key none-val)

but only the immediate continuation's mark table is checked, and the result is delivered to proc instead of returned. The proc, which must be a procedure that accepts one argument, is called in tail position, so its continuation is the same as the one whose table is checked.

(with-continuation-mark
 'key "val"
 (call-with-immediate-continuation-mark 'key list)) ; => ("val")

(with-continuation-mark
 'key "val"
 (vector (call-with-immediate-continuation-mark 'key list))) ; => #((#f))
(with-continuation-mark
 'key "val"
 (vector (call-with-immediate-continuation-mark 'key 'no list))) ; => #((no))

procedure: (call-in-continuation continuation procedure)
procedure: (call-in-continuation continuation marks procedure)
returns: does not return
libraries: (chezscheme)

continuation must be a continuation, procedure must be a procedure that accepts zero arguments, and marks (if provided) must be a continuation mark sequence.

Applies procedure to zero arguments with continuation as the continuation of the call, escaping from the current continuation. This operation is similar to applying continuation to values, except that the values delivered to the continuation are the ones produced by procedure as it runs within the applied continuation.

If marks is not provided, then procedure starts with no immediate mark table. Otherwise, marks must be consistent with the result of continuation-next-marks on continuation: either the same content or one additional mark table, and the additional mark table becomes the immediate mark table when calling procedure.

Section 6.4. Engines

Engines are a high-level process abstraction supporting timed preemption [15,24]. Engines may be used to simulate multiprocessing, implement operating system kernels, and perform nondeterministic computations.

procedure: (make-engine thunk)
returns: an engine
libraries: (chezscheme)

An engine is created by passing a thunk (no argument procedure) to make-engine. The body of the thunk is the computation to be performed by the engine. An engine itself is a procedure of three arguments:

ticks:
a positive integer that specifies the amount of fuel to be given to the engine. An engine executes until this fuel runs out or until its computation finishes.

complete:
a procedure of one or more arguments that specifies what to do if the computation finishes. Its arguments are the amount of fuel left over and the values produced by the computation.

expire:
a procedure of one argument that specifies what to do if the fuel runs out before the computation finishes. Its argument is a new engine capable of continuing the computation from the point of interruption.

When an engine is applied to its arguments, it sets up a timer to fire in ticks time units. (See set-timer on page 359.) If the engine computation completes before the timer expires, the system invokes complete, passing it the number of ticks left over and the values produced by the computation. If, on the other hand, the timer goes off before the engine computation completes, the system creates a new engine from the continuation of the interrupted computation and passes this engine to expire. complete and expire are invoked in the continuation of the engine invocation.

An implementation of engines is given in Section 12.11. of The Scheme Programming Language, 4th Edition.

Do not use the timer interrupt (see set-timer) and engines at the same time, since engines are implemented in terms of the timer.

The following example creates an engine from a trivial computation, 3, and gives the engine 10 ticks.

(define eng
  (make-engine
    (lambda () 3)))

(eng 10
     (lambda (ticks value) value)
     (lambda (x) x)) <graphic> 3

It is often useful to pass list as the complete procedure to an engine, causing an engine that completes to return a list whose first element is the ticks remaining and whose remaining elements are the values returned by the computation.

(define eng
  (make-engine
    (lambda () 3)))

(eng 10
     list
     (lambda (x) x)) <graphic> (9 3)

In the example above, the value is 3 and there are 9 ticks left over, i.e., it takes one unit of fuel to evaluate 3. (The fuel amounts given here are for illustration only. Your mileage may vary.)

Typically, the engine computation does not finish in one try. The following example displays the use of an engine to compute the 10th Fibonacci number in steps.

(define fibonacci
  (lambda (n)
    (let fib ([i n])
      (cond
        [(= i 0) 0]
        [(= i 1) 1]
        [else (+ (fib (- i 1))
                 (fib (- i 2)))]))))

(define eng
  (make-engine
    (lambda ()
      (fibonacci 10))))

(eng 50
     list
     (lambda (new-eng)
       (set! eng new-eng)
       "expired")) <graphic> "expired"

(eng 50
     list
     (lambda (new-eng)
       (set! eng new-eng)
       "expired")) <graphic> "expired"

(eng 50
     list
     (lambda (new-eng)
       (set! eng new-eng)
       "expired")) <graphic> "expired"

(eng 50
     list
     (lambda (new-eng)
       (set! eng new-eng)
       "expired")) <graphic> (21 55)

Each time the engine's fuel runs out, the expire procedure assigns eng to the new engine. The entire computation requires four blocks of 50 ticks to complete; of the last 50 it uses all but 21. Thus, the total amount of fuel used is 179 ticks. This leads to the following procedure, mileage, which "times" a computation using engines:

(define mileage
  (lambda (thunk)
    (let loop ([eng (make-engine thunk)] [total-ticks 0])
      (eng 50
           (lambda (ticks . values)
             (+ total-ticks (- 50 ticks)))
           (lambda (new-eng)
             (loop new-eng
                   (+ total-ticks 50)))))))

(mileage (lambda () (fibonacci 10))) <graphic> 179

The choice of 50 for the number of ticks to use each time is arbitrary, of course. It might make more sense to pass a much larger number, say 10000, in order to reduce the number of times the computation is interrupted.

The next procedure is similar to mileage, but it returns a list of engines, one for each tick it takes to complete the computation. Each of the engines in the list represents a "snapshot" of the computation, analogous to a single frame of a moving picture. snapshot might be useful for "single stepping" a computation.

(define snapshot
  (lambda (thunk)
    (let again ([eng (make-engine thunk)])
      (cons eng
            (eng 1 (lambda (t . v) '()) again)))))

The recursion embedded in this procedure is rather strange. The complete procedure performs the base case, returning the empty list, and the expire procedure performs the recursion.

The next procedure, round-robin, could be the basis for a simple time-sharing operating system. round-robin maintains a queue of processes (a list of engines), cycling through the queue in a round-robin fashion, allowing each process to run for a set amount of time. round-robin returns a list of the values returned by the engine computations in the order that the computations complete. Each computation is assumed to produce exactly one value.

(define round-robin
  (lambda (engs)
    (if (null? engs)
        '()
        ((car engs)
         1
         (lambda (ticks value)
           (cons value (round-robin (cdr engs))))
         (lambda (eng)
           (round-robin
             (append (cdr engs) (list eng))))))))

Since the amount of fuel supplied each time, one tick, is constant, the effect of round-robin is to return a list of the values sorted from the quickest to complete to the slowest to complete. Thus, when we call round-robin on a list of engines, each computing one of the Fibonacci numbers, the output list is sorted with the earlier Fibonacci numbers first, regardless of the order of the input list.

(round-robin
  (map (lambda (x)
         (make-engine
           (lambda ()
             (fibonacci x))))
       '(4 5 2 8 3 7 6 2))) <graphic> (1 1 2 3 5 8 13 21)

More interesting things can happen if the amount of fuel varies each time through the loop. In this case, the computation would be nondeterministic, i.e., the results would vary from call to call.

The following syntactic form, por (parallel-or), returns the first of its expressions to complete with a true value. por is implemented with the procedure first-true, which is similar to round-robin but quits when any of the engines completes with a true value. If all of the engines complete, but none with a true value, first-true (and hence por) returns #f. Also, although first-true passes a fixed amount of fuel to each engine, it chooses the next engine to run at random, and is thus nondeterministic.

(define-syntax por
  (syntax-rules ()
    [(_ x ...)
     (first-true
       (list (make-engine (lambda () x)) ...))]))

(define first-true
  (let ([pick
         (lambda (ls)
           (list-ref ls (random (length ls))))])
    (lambda (engs)
      (if (null? engs)
          #f
          (let ([eng (pick engs)])
            (eng 1
                 (lambda (ticks value)
                   (or value
                       (first-true
                         (remq eng engs))))
                 (lambda (new-eng)
                   (first-true
                     (cons new-eng
                           (remq eng engs))))))))))

The list of engines is maintained with pick, which randomly chooses an element of the list, and remq, which removes the chosen engine from the list. Since por is nondeterministic, subsequent uses with the same expressions may not return the same values.

(por 1 2 3) <graphic> 2
(por 1 2 3) <graphic> 3
(por 1 2 3) <graphic> 2
(por 1 2 3) <graphic> 1

Furthermore, even if one of the expressions is an infinite loop, por still finishes as long as one of the other expressions completes and returns a true value.

(por (let loop () (loop)) 2) <graphic> 2

With engine-return and engine-block, it is possible to terminate an engine explicitly. engine-return causes the engine to complete, as if the computation had finished. Its arguments are passed to the complete procedure along with the number of ticks remaining. It is essentially a nonlocal exit from the engine. Similarly, engine-block causes the engine to expire, as if the timer had run out. A new engine is made from the continuation of the call to engine-block and passed to the expire procedure.

procedure: (engine-block)
returns: does not return
libraries: (chezscheme)

This causes a running engine to stop, create a new engine capable of continuing the computation, and pass the new engine to the original engine's third argument (the expire procedure). Any remaining fuel is forfeited.

(define eng
  (make-engine
    (lambda ()
      (engine-block)
      "completed")))

(eng 100
     (lambda (ticks value) value)
     (lambda (x)
        (set! eng x)
        "expired")) <graphic> "expired"

(eng 100
     (lambda (ticks value) value)
     (lambda (x)
        (set! eng x)
        "expired")) <graphic> "completed"

procedure: (engine-return obj ...)
returns: does not return
libraries: (chezscheme)

This causes a running engine to stop and pass control to the engine's complete argument. The first argument passed to the complete procedure is the amount of fuel remaining, as usual, and the remaining arguments are the objects obj ... passed to engine-return.

(define eng
  (make-engine
    (lambda ()
      (reverse (engine-return 'a 'b 'c)))))

(eng 100
     (lambda (ticks . values) values)
     (lambda (new-eng) "expired")) <graphic> (a b c)

Chez Scheme Version 10 User's Guide
Copyright © 2024 Cisco Systems, Inc.
Licensed under the Apache License Version 2.0 (full copyright notice.).
Revised November 2024 for Chez Scheme Version 10.1.0
about this book