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, Third Edition or the Revised5 Report on Scheme for a description of standard control structures.

Section 6.1. Quasiquotation


syntax: (quasiquote obj ...)
syntax: `obj
syntax: (unquote obj ...)
syntax: ,obj
syntax: (unquote-splicing obj ...)
syntax: ,@obj
returns: see explanation

`obj is equivalent to (quasiquote obj), ,obj is equivalent to (unquote obj), and ,@obj is equivalent to (unquote-splicing obj). The abbreviated forms are converted into the longer forms by the Scheme reader (see read).

quasiquote is similar to quote, but it allows parts of the quoted text to be "unquoted." Within a quasiquote expression, unquote and unquote-splicing subforms are evaluated, and everything else is quoted, i.e., left unevaluated. The value of each unquote subform is inserted into the output in place of the unquote form, while the value of each unquote-splicing subform is spliced into the surrounding list or vector structure. unquote and unquote-splicing are valid only within quasiquote expressions.

quasiquote expressions may be nested, with each quasiquote introducing a new level of quotation and each unquote or unquote-splicing taking away a level of quotation. An expression nested within n quasiquote expressions must be within n unquote or unquote-splicing expressions to be evaluated.

New structures are allocated as necessary, and only as necessary, to rebuild quasiquoted structure that contains any nonempty unquote or unquote-splicing form. For example, while `(a . b) is equivalent to '(a . b) and returns a constant pair (the same one each time the quasiquote expression is evaluated, e.g., in a loop or procedure called multiple times) `(',a . ',b) is equivalent to (cons 'a 'b) so that a new pair is allocated each time the quasiquote expression is evaluated.

`(+ 2 3) <graphic> (+ 2 3)

`(+ 2 ,(* 3 4)) <graphic> (+ 2 12)
`(a b (,(+ 2 3) c) d) <graphic> (a b (5 c) d)
`(a b ,(reverse '(c d e)) f g) <graphic> (a b (e d c) f g)
(let ((a 1) (b 2))
  `(,a . ,b)) <graphic> (1 . 2)

`(+ ,@(cdr '(* 2 3))) <graphic> (+ 2 3)
`(a b ,@(reverse '(c d e)) f g) <graphic> (a b e d c f g)
(let ((a 1) (b 2))
  `(,a ,@b)) <graphic> (1 . 2)
`#(,@(list 1 2 3)) <graphic> #(1 2 3)

'`,(cons 'a 'b) <graphic> `,(cons 'a 'b)
`',(cons 'a 'b) <graphic> '(a . b)

unquote and unquote-splicing with zero or more than one subform are valid only in splicing (list or vector) contexts. (unquote obj ...) is equivalent to (unquote obj) ..., and (unquote-splicing obj ...) is equivalent to (unquote-splicing obj) .... These forms are primarily useful as intermediate forms in the output of the quasiquote expander. They support certain useful nested quasiquotation idioms [2], such as ,@,@, which has the effect of a doubly indirect splicing when used within a doubly nested and doubly evaluated quasiquote expression.

`(a (unquote) b) <graphic> (a b)
`(a (unquote (+ 3 3)) b) <graphic> (a 6 b)
`(a (unquote (+ 3 3) (* 3 3)) b) <graphic> (a 6 9 b)

(define x '(m n))
(define m '(b c))
(define n '(d e))
``(a ,@,@x f) <graphic> `(a (unquote-splicing m n) f)
(eval ``(a ,@,@x f)) <graphic> (a b c d e f)

Section 6.2. 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)) <graphic> 7
(calc '(div 3 4)) <graphic> 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)) <graphic> (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)) <graphic> (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 ...))))

Section 6.3. Mapping and Folding


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

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

exists and ormap are identical. The former is the Revised6 Report name.

(exists symbol? '(1.0 #\a "hi" '())) <graphic> #f

(exists member
        '(a b c)
        '((c b) (b a) (a c))) <graphic> (b a)

(exists (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)) <graphic> #t

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

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


procedure: (for-all proc list1 list2 ...)
procedure: (andmap proc list1 list2 ...)
returns: see explanation

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

for-all and andmap are identical. The former is the Revised6 Report name.

(for-all symbol? '(a b c d)) <graphic> #t

(for-all =
         '(1 2 3 4)
         '(1.0 2.0 3.0 4.0)) <graphic> #t

(for-all (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)) <graphic> #f

for-all may be defined (somewhat inefficiently and without error checks) as follows:

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


procedure: (vector-map proc vector1 vector1 ...)
returns: vector of results

vector-map applies proc to corresponding elements of the vectors vector1 vector2 ... and returns a vector of the resulting values. The vectors vector1 vector2 ... must be of the same length, and proc should accept as many arguments as there are vectors and return a single value.

(vector-map abs '#(1 -2 3 -4 5 -6)) <graphic> #(1 2 3 4 5 6)
(vector-map (lambda (x y) (* x y))
  '#(1 2 3 4)
  '#(8 7 6 5)) <graphic> #(8 14 18 20)

While the order in which the applications themselves occur is not specified, the order of the values in the output vector is the same as that of the corresponding values in the input vectors.


procedure: (vector-for-each proc vector1 vector2 ...)
returns: unspecified

for-each is similar to vector-map except that vector-for-each does not create and return a vector of the resulting values, and vector-for-each guarantees to perform the applications in sequence over the vectors from left to right.

(let ((same-count 0))
  (vector-for-each
    (lambda (x y)
      (if (= x y)
          (set! same-count (+ same-count 1))))
    '#(1 2 3 4 5 6)
    '#(2 3 3 4 7 6))
  same-count) <graphic> 3


procedure: (fold-left proc obj list1 list2 ...)
returns: unspecified

The list arguments should all have the same length. proc must be a procedure. It should accept one more argument than the number of list arguments and return a single value. It should not mutate the list arguments.

fold-left returns obj if the list arguments are empty. If they are not empty, fold-left applies proc to obj and the cars of list1 list2 ..., then recurs with the value returned by proc in place of obj and the cdr of each list in place of the list.

(fold-left cons '() '(1 2 3 4)) <graphic> ((((() . 1) . 2) . 3) . 4)
(fold-left
  (lambda (a x) (+ a (* x x)))
  0 '(1 2 3 4 5)) <graphic> 55
(fold-left
  (lambda (a . args) (append args a))
  '(question)
  '(that not to)
  '(is to be)
  '(the be: or)) <graphic> (to be or not to be: that is the question)


procedure: (fold-right proc obj list1 list2 ...)
returns: unspecified

The list arguments should all have the same length. proc must be a procedure. It should accept one more argument than the number of list arguments and return a single value. It should not mutate the list arguments.

fold-right returns obj if the list arguments are empty. If they are not empty, fold-right recurs with the cdr of each list replacing the list, then applies proc to the cars of list1 list2 ... and the result returned by the recursion.

(fold-right cons '() '(1 2 3 4)) <graphic> (1 2 3 4)
(fold-right
  (lambda (x a) (+ a (* x x)))
  0 '(1 2 3 4 5)) <graphic> 55

(fold-right
  (lambda (x y a) (cons* x y a))
  '((with apologies))
  '(parting such sorrow go ya)
  '(is sweet gotta see tomorrow)) <graphic> (parting is such sweet sorrow
                                       gotta go see ya tomorrow
                                       (with apologies))

Section 6.4. 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.


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

call/cc is an abbreviation for call-with-current-continuation.


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

call/1cc obtains its continuation and passes it to proc, 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 proc 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> error


procedure: (dynamic-wind in body out)
procedure: (dynamic-wind critical? in body out)
returns: result of applying body

dynamic-wind offers "protection" from continuation invocation. It is useful for performing tasks that must be performed whenever control enters or leaves body, either normally or by continuation application.

The arguments in, body, and out must be procedures of no arguments, i.e., thunks. Before applying body, and each time body is entered subsequently by the application of a continuation created within body, the in thunk is applied. Upon normal exit from body and each time body is exited by the application of a continuation created outside body, the out thunk is applied.

Thus, it is guaranteed that in is invoked at least once. In addition, if body ever returns, out is invoked at least once.

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 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.

The standard Scheme dynamic-wind does not support the critical? option.

Section 6.5. Engines

Engines are a high-level process abstraction supporting timed preemption [15,19]. 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 (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 246.) 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, Third 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

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

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)

R. Kent Dybvig / Chez Scheme Version 7 User's Guide
Copyright © 2005 R. Kent Dybvig
Revised July 2007 for Chez Scheme Version 7.4
Cadence Research Systems / www.scheme.com
Cover illustration © 1998 Jean-Pierre Hébert
ISBN: 0-9667139-1-5
to order this book / about this book