Chapter 5. Control Structures

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


Section 5.1. Conditionals


syntax: (record-case exp0 clause1 clause2 ...)
returns: see explanation

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 exp1 exp2 ...)

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 exp1 exp2 ...)

exp0 must evaluate to a pair. exp0 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 exp1 exp2 ... are evaluated in sequence. The value of the last expression is returned. The effect is identical to the application of

(lambda formals exp1 exp2 ...)

to the cdr of the list.

If none of the clauses contains a matching key and an else clause is present, the expressions exp1 exp2 ... 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 (error 'calc "invalid expression ~s" x)])))

(calc '(add 3 4))  7
(calc '(div 3 4))  3/4


syntax: (when test-exp exp1 exp2 ...)
syntax: (unless test-exp exp1 exp2 ...)
returns: unspecified

For when, if test-exp evaluates to a true value, the expressions exp1 exp2 ... are evaluated in sequence. If test-exp evaluates to false, none of the other expressions are evaluated.

For unless, if test-exp evaluates to false, the expressions exp1 exp2 ... are evaluated in sequence. If test-exp evaluates to a true value, none of the other expressions are evaluated.

A when or unless expression is usually clearer than the corresponding "one-armed" if expression.

(let ([x -4] [sign 'plus])
  (when (< x 0)
    (set! x (- 0 x))
    (set! sign 'minus))
  (list sign x))  (minus 4)

(define check-pair
  (lambda (x)
    (unless (pair? x)
      (error 'check-pair "~s is not a pair" x))
    x))

(check-pair '(a b c))  (a b c)

when may be defined as follows:

(define-syntax when
  (syntax-rules ()
    ((_ e0 e1 e2 ...)
     (if e0 (begin e1 e2 ...)))))

unless may be defined as follows:

(define-syntax unless
  (syntax-rules ()
    ((_ e0 e1 e2 ...)
     (if (not e0) (begin e1 e2 ...)))))

or in terms of when as follows:

(define-syntax unless
  (syntax-rules ()
    ((_ e0 e1 e2 ...)
     (when (not e0) e1 e2 ...))))


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

ormap applies procedure to corresponding elements of the lists list1 list2 ... in sequence until either the lists run out or procedure returns a true value. The value of the last application of procedure is returned. The lists list1 list2 ... must be of the same length, and procedure must accept as many arguments as there are lists.

(ormap symbol? '(1.0 #\a "hi" '()))  #f

(ormap member
       '(a b c)
       '((c b) (b a) (a c)))  (b a)

(ormap (lambda (x y z) (= (+ x y) z))
       '(1 2 3 4)
       '(1.2 2.3 3.4 4.5)
       '(2.3 4.4 6.4 8.6))  #t

ormap may be defined (somewhat inefficiently and without error checks) as follows:

(define ormap
  (lambda (f ls . more)
    (let ormap ([f f] [ls ls] [more more])
      (and (not (null? ls))
           (or (apply f (car ls) (map car more))
               (ormap f (cdr ls) (map cdr more)))))))


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

andmap applies procedure to corresponding elements of the lists list1 list2 ... in sequence until either the lists run out or procedure returns a false value. The value of the last application of procedure is returned. The lists list1 list2 ... must be of the same length, and procedure must accept as many arguments as there are lists.

(andmap symbol? '(a b c d))  #t

(andmap =
        '(1 2 3 4)
        '(1.0 2.0 3.0 4.0))  #t

(andmap (lambda (x y z) (= (+ x y) z))
        '(1 2 3 4)
        '(1.2 2.3 3.4 4.5)
        '(2.2 4.3 6.5 8.5))  #f

andmap may be defined (somewhat inefficiently and without error checks) as follows:

(define andmap
  (lambda (f ls . more)
    (let andmap ([ls ls] [more more] [a #t])
      (if (null? ls)
          a
          (let ([a (apply f (car ls) (map car more))])
            (and a (andmap (cdr ls) (map cdr more) a)))))))


Section 5.2. One-Shot Continuations

One-shot continuations are continuations that may be invoked at most once, whether explicitly or implicitly. They are obtained with call/1cc.


procedure: (call/1cc procedure)
returns: the result of applying procedure to the current continuation

call/1cc obtains its continuation and passes it to procedure, which must 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." It is an error to return to a one-shot continuation, 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" [2] 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)))  24
(call/1cc (prod '(1 2 3 4)))  24

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

(let ((k (call/cc (lambda (x) x))))
  (k (lambda (x) 0)))  0

(let ((k (call/1cc (lambda (x) x))))
  (k (lambda (x) 0)))  error


Section 5.3. Engines

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


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

An engine is created by passing a thunk (procedure of no arguments) 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 188.) 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 9.11. of The Scheme Programming Language, Second 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))  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))  (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"))  "expired"

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

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

(eng 50
     list
     (lambda (new-eng)
       (set! eng new-eng)
       "expired"))  (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)))  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)))  (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)  2
(por 1 2 3)  3
(por 1 2 3)  2
(por 1 2 3)  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)  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

This causes a running engine to stop, create a new engine capable of continuing the computation, and pass it to its own 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"))  "expired"

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


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

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"))  (a b c)


Chez Scheme User's Guide
© 1998 R. Kent Dybvig
Cadence Research Systems
http://www.scheme.com
Illustrations © 1998 Jean-Pierre Hébert
about this book