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 Revised^{6} Report
on Scheme for a description of standard control structures.

**syntax**: `(record-case expr clause_{1} clause_{2} ...)`

`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 body_{1} body_{2} ...)`

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 body_{1} body_{2} ...)`

` expr` must evaluate to a pair.

`(lambda formals body_{1} body_{2} ...)`

to the cdr of the list.

If none of the clauses contains a matching key and an `else` clause
is present, the expressions ` body_{1} body_{2} ...` of the

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)) 7
(calc '(div 3 4)) 3/4`

**procedure**: `(ormap procedure list_{1} list_{2} ...)`

`ormap` is identical to the Revised^{6} Report `exists`.

**procedure**: `(andmap procedure list_{1} list_{2} ...)`

`andmap` is identical to the Revised^{6} Report `for-all`.

*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/1cc procedure)`

`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

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

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))) 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))) `

**procedure**: `(dynamic-wind in body out)`

The first form is identical to the Revised^{6} Report `dynamic-wind`.
When the optional ` critical?` argument is present and non-false,
the

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

**procedure**: `(make-engine thunk)`

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

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

`(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,

**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")) "expired"
(eng 100
(lambda (ticks value) value)
(lambda (x)
(set! eng x)
"expired")) "completed"`

**procedure**: `(engine-return obj ...)`

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

`(define eng
(make-engine
(lambda ()
(reverse (engine-return 'a 'b 'c)))))
(eng 100
(lambda (ticks . values) values)
(lambda (new-eng) "expired")) (a b c)`

R. Kent Dybvig /

Copyright © 2009 R. Kent Dybvig

Revised October 2011 for Chez Scheme Version 8.4

Cadence Research Systems / www.scheme.com

Cover illustration © 2010 Jean-Pierre Hébert

ISBN: 978-0-966-71392-3

about this book /
purchase this book in print form