aPToP-D
126
9 Interaction
We have been describing computation according to the initial values and final values of state
variables. A state variable declaration
var x: T· S = ∃x, x′: T· S
says that a state variable is really two mathematical variables, one for the initial value and one for
the final value. Within the scope of the declaration, x and x′ are available for use in specification
S . There are intermediate values whenever there is a dependent (sequential) composition, but
these intermediate values are local to the definition of dependent composition.
P. Q = ∃x′′, y′′, ...·
(substitute x′′, y′′, ... for x′, y′, ... in P )
∧ (substitute x′′, y′′, ... for x, y, ... in Q )
Consider (P. Q) || R . The intermediate values between P and Q are hidden in the dependent
composition, and are not visible to R , so they cannot be used for process interaction.
A variable whose value is visible only initially and finally is called a boundary variable, and a
variable whose value is visible all the time is called an interactive variable. So far our variables
have all been boundary variables. Now we introduce interactive variables whose intermediate
values are visible to parallel processes. These variables can be used to describe and reason about
interactions between people and computers, and between processes, during the course of a
computation.
9.0 Interactive Variables
Let the notation ivar x: T· S declare x to be an interactive variable of type T and scope S . It is
defined as follows.
ivar x: T· S = ∃x: time→T· S
where time is the domain of time, usually either the extended integers or the extended reals. An
interactive variable is a function of time. The value of variable x at time t is x t .
Suppose a and b are boundary variables, x and y are interactive variables, and t is time. For
independent composition we partition all the state variables, boundary and interactive. Suppose a
and x belong to P , and b and y belong to Q .
P||Q = ∃tP, tQ· (substitute tP for t′ in P ) ∧ (∀t′′· tP≤t′′≤t′ ⇒ xt′′=x(tP))
∧ (substitute tQ for t′ in Q ) ∧ (∀t′′· tQ≤t′′≤t′ ⇒ yt′′=y(tQ))
∧ t′ = max tP tQ
The new part says that when the shorter process is finished, its interactive variables remain
unchanged while the longer process is finishing.
Using the same processes and variables as in the previous paragraph, the assignment
x:= a+b+x+y in process P assigns to variable x the sum of four values. Since a and x are
variables of process P , their values are the latest ones assigned to them by process P , or their
initial values if process P has not assigned to them. Since b is a boundary variable of process
Q , its value, as seen in P , is its initial value, regardless of whether Q has assigned to it. Since
y is an interactive variable of process Q , its value, as seen in P , is the latest one assigned to it by
process Q , or its initial value if Q has not assigned to it, or unknown if Q is in the middle of
assigning to it. Since x is an interactive variable, its new value can be seen in all parallel
processes. The expression a+b+x+y is an abuse of notation, since a and b are numbers and x
and y are functions from time to numbers; the value being assigned is actually a+b+xt+yt , but
we omit the argument t when the context makes it clear. We will similarly write x′ to mean xt′ ,
and x′′ to mean xt′′ .
127
9 Interaction
The definition of ok says that the boundary variables and time are unchanged. So in process P
of the previous two paragraphs,
ok = a′=a ∧ t′=t
There is no need to say x′=x , which means xt′=xt , since t′=t . We do not mention b and y
because they are not variables of process P .
Assignment to an interactive variable cannot be instantaneous because it is time that distinguishes
its values. In a process where the boundary variables are a and b , and the interactive variables
are x and y ,
x:= e =
a′=a ∧ b′=b ∧ x′=e ∧ (∀t′′· t≤t′′≤t′ ⇒ y′′=y)
∧ t′ = t+(the time required to evaluate and store e )
interactive variable y remains unchanged throughout the duration of the assignment to x .
Nothing is said about the value of x during the assignment.
Assignment to a boundary variable can be instantaneous if we wish. If we choose to account for
its time, we must say that all interactive variables remain unchanged during the assignment.
Dependent composition hides the intermediate values of the boundary and time variables, leaving
the intermediate values of the interactive variables visible. In boundary variables a and b , and
interactive variables x and y , and time t , we define
P. Q = ∃a′′, b′′, t′′·
(substitute a′′, b′′, t′′ for a′, b′, t′ in P )
∧ (substitute a′′, b′′, t′′ for a, b, t in Q )
All of the specification laws and refinement laws survive the addition of interactive variables, with
one sad exception: the Substitution Law no longer works.
If processes P and Q are in parallel, they have different variables. Suppose again that boundary
variable a and interactive variable x are the variables of process P , and that boundary variable b
and interactive variable y are the variables of process Q . In specification P , the inputs are a ,
b , xt , and yt′′ for t≤t′′<t′ . In specification P , the outputs are a′ , and xt′′ for t<t′′≤t′ .
Specification P is implementable when
∀a, b, X, y, t· ∃a′, x, t′· P ∧ t≤t′ ∧ ∀t′′· t<t′′≤t′ ∨ x t′′=X t′′
As before, P must be satisfiable with nondecreasing time; the new part says that P must not
constrain its interactive variables outside the interval from t to t′ . We do not need to know the
context of a process specification to check its implementability; variables b and y appear only in
the outside universal quantification.
Exercise 385 is an example in the same variables a , b , x , y , and t . Suppose that time is an
extended integer, and that each assignment takes time 1 .
(x:= 2. x:= x+y. x:= x+y) || (y:= 3. y:= x+y) Clearly, x is a variable in the left
process and y is a variable in the right process.
Let's put a in the left process and b in the right process.
=
(a′=a ∧ xt′=2 ∧ t′=t+1. a′=a ∧ xt′= xt+yt ∧ t′=t+1. a′=a ∧ xt′= xt+yt ∧ t′=t+1)
|| (b′=b ∧ yt′=3 ∧ t′=t+1. b′=b ∧ yt′= xt+yt ∧ t′=t+1)
=
(a′=a ∧ x(t+1)=2 ∧ x(t+2)= x(t+1)+y(t+1) ∧ x(t+3)= x(t+2)+y(t+2) ∧ t′=t+3)
|| (b′=b ∧ y(t+1)=3 ∧ y(t+2)= x(t+1)+y(t+1) ∧ t′=t+2)
=
a′=a ∧ x(t+1)=2 ∧ x(t+2)= x(t+1)+y(t+1) ∧ x(t+3)= x(t+2)+y(t+2)
∧ b′=b ∧ y(t+1)=3 ∧ y(t+2)= x(t+1)+y(t+1) ∧ y(t+3)=y(t+2) ∧ t′=t+3
=
a′=a ∧ x(t+1)=2 ∧ x(t+2)=5 ∧ x(t+3)=10
∧ b′=b ∧ y(t+1)=3 ∧ y(t+2)=y(t+3)=5 ∧ t′=t+3
9 Interaction
128
The example gives the appearance of lock-step synchrony only because we took each assignment
time to be 1 . More realistically, different assignments take different times, perhaps specified
nondeterministically with lower and upper bounds. Whatever timing policy we decide on, whether
deterministic or nondeterministic, whether discrete or continuous, the definitions and theory remain
unchanged. Of course, complicated timing leads quickly to very complicated expressions that
describe all possible interactions. If we want to know only something, not everything, about the
possible behaviors, we can proceed by implications instead of equations, weakening for the
purpose of simplifying. Programming goes the other way: we start with a specification of desired
behavior, and strengthen as necessary to obtain a program.
9.0.0
Thermostat
Exercise 388: specify a thermostat for a gas burner. The thermostat operates in parallel with other
processes
thermometer || control || thermostat || burner
The thermometer and the control are typically located together, but they are logically distinct. The
inputs to the thermostat are:
•
real temperature , which comes from the thermometer and indicates the actual temperature.
•
real desired , which comes from the control and indicates the desired temperature.
•
boolean flame , which comes from a flame sensor in the burner and indicates whether there
is a flame.
These three variables must be interactive variables because their values may be changed at any time
by another process and the thermostat must react to their current values. These three variables do
not belong to the thermostat, and cannot be assigned values by the thermostat. The outputs of the
thermostat are:
•
boolean gas ; assigning it
turns the gas on and
turns the gas off.
•
boolean spark ; assigning it
causes sparks for the purpose of igniting the gas.
Variables gas and spark belong to the thermostat process. They must also be interactive
variables; the burner needs all their intermediate values, not just their final values.
Heat is wanted when the actual temperature falls ε below the desired temperature, and not wanted
when the actual temperature rises ε above the desired temperature, where ε is small enough to be
unnoticeable, but large enough to prevent rapid oscillation. To obtain heat, the spark should be
applied to the gas for at least 1 second to give it a chance to ignite and to allow the flame to
become stable. But a safety regulation states that the gas must not remain on and unlit for more
than 3 seconds. Another regulation says that when the gas is shut off, it must not be turned on
again for at least 20 seconds to allow any accumulated gas to clear. And finally, the gas burner
must respond to its inputs within 1 second.
Here is a specification:
thermostat = if gas then GasIsOn else GasIsOff
GasIsOn
=
if temperature < desired + ε ∧ flame
then (t ≤ t′ ≤ t+1 ∧ (∀t′′· t≤t′′≤t′ ⇒ gas′′ ∧ ¬spark′′). GasIsOn)
else (t+20 ≤ t′ ≤ t+21 ∧ (∀t′′· t≤t′′≤t′ ⇒ ¬gas′′ ∧ ¬spark′′). GasIsOff)
GasIsOff
=
if temperature < desired – ε
then (t+1 ≤ t′ ≤ t+3 ∧ (∀t′′· t≤t′′≤t′ ⇒ gas′′ ∧ spark′′). GasIsOn)
else (t ≤ t′ ≤ t+1 ∧ (∀t′′· t≤t′′≤t′ ⇒ ¬gas′′ ∧ ¬spark′′). GasIsOff)
129
9 Interaction
We are using the time variable to represent real time in seconds. The specification t+1 ≤ t′ ≤ t+3
represents the passage of at least 1 second but not more than 3 seconds. The specification
t+20 ≤ t′ ≤ t+21 is similar. A specification that a computation be slow enough is always easy to
satisfy. A specification that it be fast enough requires us to build fast enough hardware; in this
case it is easy since instruction times are microseconds and the time bounds are seconds.
One can always argue about whether a formal specification captures the intent of an informal
specification. For example, if the gas is off, and heat becomes wanted, and the ignition sequence
begins, and then heat is no longer wanted, this last input may not be noticed for up to 3 seconds.
It may be argued that this is not responding to an input within 1 second, or it may be argued that
the entire ignition sequence is the response to the first input, and until its completion no response to
further inputs is required. At least the formal specification is unambiguous.
End of Thermostat
9.0.1
Space
The main purpose of interactive variables is to provide a means for processes to interact. In this
subsection, we show another use. We make the space variable s into an interactive variable in
order to look at the space occupied during the course of a computation. As an example, Exercise
389 is contrived to be as simple as possible while including time and space calculations in an
infinite computation.
Suppose alloc allocates 1 unit of memory space and takes time 1 to do so. Then the following
computation slowly allocates memory.
GrowSlow ⇐ if t=2×x then (alloc || x:= t) else t:= t+1. GrowSlow
If the time is equal to 2×x , then one space is allocated, and in parallel x becomes the time stamp
of the allocation; otherwise the clock ticks. The process is repeated forever. Prove that if the
space is initially less than the logarithm of the time, and x is suitably initialized, then at all times
the space is less than the logarithm of the time.
It is not clear what initialization is suitable for x , so leaving that aside for a moment, we define
GrowSlow to be the desired specification.
GrowSlow = s < log t ⇒ (∀t′′· t′′≥t ⇒ s′′ < log t′′)
where s is an interactive variable, so s is really s t and s′′ is really s t′′ . We are just interested
in the space calculation and not in actually allocating space, so we can take alloc to be s:= s+1 .
There is no need for x to be interactive, so let's make it a boundary variable. To make the proof
easier, we let all variables be extended naturals, although the result we are proving holds also for
real time.
Now we have to prove the refinement, and to do that it helps to break it into pieces. The body of
the loop can be written as a disjunction.
if t=2×x then (s:= s+1 || x:= t) else t:= t+1
= t=2×x ∧ s′=s+1 ∧ x′=t ∧ t′=t+1 ∨ t 2×x ∧ s′=s ∧ x′=x ∧ t′=t+1
Now the refinement has the form
(A⇒B ⇐ C∨D. A⇒B)
. distributes over ∨
= (A⇒B ⇐ (C. A⇒B) ∨ (D. A⇒B))
antidistributive law
= (A⇒B ⇐ (C. A⇒B)) ∧ (A⇒B ⇐ (D. A⇒B))
portation twice
= (B ⇐ A ∧ (C. A⇒B)) ∧ (B ⇐ A ∧ (D. A⇒B))
So we can break the proof into two cases:
9 Interaction
130
B ⇐ A ∧ (C. A⇒B)
B ⇐ A ∧ (D. A⇒B)
starting each time with the right side (antecedent) and working toward the left side (consequent).
First case:
s < log t ∧ ( t=2×x ∧ s′=s+1 ∧ x′=t ∧ t′=t+1.
s < log t ⇒ ∀t′′· t′′≥t ⇒ s′′ < log t′′)
remove dependent composition, remembering that s is interactive
= s < log t ∧ ( ∃x′′, t′′′· t=2×x ∧ s′′′=s+1 ∧ x′′=t ∧ t′′′=t+1
∧ (s′′′ < log t′′′ ⇒ ∀t′′· t′′≥t′′′ ⇒ s′′ < log t′′))
Use s′′′=s+1 and drop it. Use one-point to eliminate ∃x′′, t′′′ .
⇒ s < log t ∧ t=2×x ∧ (s+1 < log(t+1) ⇒ ∀t′′· t′′≥t+1 ⇒ s′′ < log t′′)
The next step should be discharge. We need
s < log t ∧ t=2×x ⇒ s+1 < log(t+1)
= 2s < t = 2×x ⇒ 2s+1 < t+1
= 2s < t = 2×x ⇒ 2s+1 ≤ t
= 2s < t = 2×x ⇒ 2s+1 ≤ 2×x
= 2 s < t = 2 × x ⇒ 2s ≤ x
⇐ 2s ≤ x
This is the missing initialization of x . So we go back and redefine GrowSlow .
GrowSlow = s < log t ∧ x≥2s ⇒ (∀t′′· t′′≥t ⇒ s′′ < log t′′)
Now we redo the proof. First case:
s < log t ∧ x≥2s ∧ ( t=2×x ∧ s′=s+1 ∧ x′=t ∧ t′=t+1.
s < log t ∧ x≥2s ⇒ ∀t′′· t′′≥t ⇒ s′′ < log t′′)
remove dependent composition, remembering that s is interactive
=
s < log t ∧ x≥2s
∧ (∃x′′, t′′′· t=2×x ∧ s′′′=s+1 ∧ x′′=t ∧ t′′′=t+1
∧ (s′′′ < log t′′′ ∧ x′′≥2s′′′ ⇒ ∀t′′· t′′≥t′′′ ⇒ s′′ < log t′′))
Use s′′′=s+1 and drop it. Use one-point to eliminate ∃x′′, t′′′ .
⇒
s < log t ∧ x≥2s ∧ t=2×x
∧ (s+1 < log(t+1) ∧ t≥2s+1 ⇒ ∀t′′· t′′≥t+1 ⇒ s′′ < log t′′)
discharge, as calculated earlier
s
= s < log t ∧ x≥2 ∧ t=2×x ∧ ∀t′′· t′′≥t+1 ⇒ s′′ < log t′′
when t′′=t , then s′′=s and since s < log t , the domain of t′′ can be increased
⇒ ∀t′′· t′′≥t ⇒ s′′ < log t′′
The second case is easier than the first.
s < log t ∧ x≥2s ∧ ( t 2×x ∧ s′=s ∧ x′=x ∧ t′=t+1.
s < log t ∧ x≥2s ⇒ ∀t′′· t′′≥t ⇒ s′′ < log t′′)
remove dependent composition, remembering that s is interactive
=
s < log t ∧ x≥2s
∧ (∃x′′, t′′′· t 2×x ∧ s′′′=s ∧ x′′=x ∧ t′′′=t+1
∧ (s′′′ < log t′′′ ∧ x′′≥2s′′′ ⇒ ∀t′′· t′′≥t′′′ ⇒ s′′ < log t′′))
Use s′′′=s and drop it. Use one-point to eliminate ∃x′′, t′′′ .
s
⇒
s < log t ∧ x≥2 ∧ t 2×x
∧ (s < log t ∧ x≥2s ⇒ ∀t′′· t′′≥t+1 ⇒ s′′ < log t′′)
discharge
s
= s < log t ∧ x≥2 ∧ t 2×x ∧ ∀t′′· t′′≥t+1 ⇒ s′′ < log t′′
when t′′=t , then s′′=s and since s < log t , the domain of t′′ can be increased
⇒ ∀t′′· t′′≥t ⇒ s′′ < log t′′
End of Space
End of Interactive Variables
131
9 Interaction
A shared variable is a variable that can be written and read by any process. Shared variables are
popular for process interaction, but they present enormous problems for people who wish to
reason about their programs, and for those who must build the hardware and software to
implement them. For their trouble, there is no benefit. Interactive variables are not fully shared;
all processes can read an interactive variable, but only one process can write it. Interactive
variables are easier to reason about and implement than fully shared variables. Even boundary
variables are shared a little: their initial values are visible to all processes. They are easiest to
reason about and implement, but they provide the least interaction.
Although interactive variables are tamer than shared variables, there are still two problems with
them. The first is that they provide too much information. Usually, a process does not need the
values of all interactive variables at all times; each process needs only something about the values
(an expression in interactive variables), and only at certain times. The other problem is that
processes may be executed on different processors, and the rates of execution may not be identical.
This makes it hard to know exactly when to read the value of an interactive variable; it certainly
should not be read while its owner process is in the middle of writing to it.
We now turn to a form of communication between processes that does not have these problems: it
provides just the right information, and mediates the timing between the processes. And,
paradoxically, it provides the means for fully sharing variables safely.
9.1 Communication
This section introduces named communication channels through which a computation
communicates with its environment, which may be people or other computations running in
parallel. For each channel, only one process (person or computation) writes to it, but all processes
can read all the messages, each at its own speed. For two-way communication, use two channels.
We start the section by considering only one reading process, which may be the same process that
writes, or may be a different process. We consider multiple reading processes later when we come
to the subsection on broadcast.
Communication on channel c is described by two infinite lists Mc and Tc called the message
script and the time script, and two extended natural variables rc and wc called the read cursor and
the write cursor. The message script is the list of all messages, past, present, and future, that pass
along the channel. The time script is the corresponding list of times that the messages were or are
or will be sent. The scripts are state constants, not state variables. The read cursor is a state
variable saying how many messages have been read, or input, on the channel. The write cursor is
a state variable saying how many messages have been written, or output, on the channel. If there
is only one channel, or if the channel is known from context, we may omit the subscripts on M ,
T , w , and r .
During execution, the read and write cursors increase as inputs and outputs occur; more and more
of the script items are seen, but the scripts do not vary. At any time, the future messages and the
times they are sent on a channel may be unknown, but they can be referred to as items in the
scripts. For example, after 2 more reads the next input on channel c will be Mc (rc+2) , and
after 5 more writes the next output will be M c (w c+5) and it will occur at time T c (w c+5) .
Omitting subscripts, after 2 more reads the next input will be M (r+2) , and after 5 more writes
the next output will be M (w+5) at time T (w+5) .
9 Interaction
M
T
=
=
132
[ 6 ; 4 ; 7 ; 1 ; 0 ; 3 ; 8 ; 9 ; 2 ; 5 ; ... ]
[ 3 ; 5 ; 5 ; 20 ; 25 ; 28 ; 31 ; 31 ; 45 ; 48 ; ... ]
r
w
The scripts and the cursors are not programming notations, but they allow us to specify any
desired communications. Here is an example specification. It says that if the next input on channel
c is even, then the next output on channel d will be
, and otherwise it will be
. Formally,
we may write
if even (M crc) then M dwd = else M dwd =
or, more briefly,
Mdwd = even (Mcrc)
If there are only a finite number of communications on a channel, then after the last message, the
time script items are all ∞ , and the message script items are of no interest.
9.1.0
Implementability
Consider computations involving two memory variables x and y , a time variable t , and
communications on a single channel (no subscripts needed). The state of a computation consists of
the values of the memory variables, the time variable, and the cursor variables. During a
computation, the memory variables can change value in any direction, but time and the cursors can
only increase. Once an input has been read, it cannot be unread; once an output has been written,
it cannot be unwritten. Every computation satisfies
t′ ≥ t ∧ r′ ≥ r ∧ w′ ≥ w
An implementable specification can say what the scripts are in the segment written by a
computation, that is the segment M [w;..w′] and T [w;..w′] between the initial and final values
of the write cursor, but it cannot specify the scripts outside this segment. Furthermore, the time
script must be monotonic, and all its values in this segment must be in the range from t to t′ .
A specification S (in initial state σ , final state σ′ , message script M , and time script T ) is
implementable if and only if
∀σ, M′′, T′′· ∃σ′, M, T·
S ∧ t′ ≥ t ∧ r′ ≥ r ∧ w′ ≥ w
∧ M [(0;..w); (w′;..∞)] = M′′ [(0;..w); (w′;..∞)]
∧ T [(0;..w); (w′;..∞)] = T′′ [(0;..w); (w′;..∞)]
∧ ∀i, j: w,..w′· i≤j ⇒ t ≤ T i ≤ T j ≤ t′
If we have many channels, we need similar conjuncts for each, appropriately subscripted. If we
have no channels, implementability reduces to the definition given in Chapter 4.
To implement communication channels, it is not necessary to build two infinite lists. At any given
time, only those messages that have been written and not yet read need to be stored. The time
script is only for specification and proof, and does not need to be stored at all.
End of Implementability
133
9 Interaction
9.1.1 Input and Output
Here are five programming notations for communication. Let c be a channel. The notation c! e
describes a computation that writes the output message e on channel c . The notation c!
describes a computation that sends a signal on channel c (no message; the act of signalling is the
only information). The notation c? describes a computation that reads one input on channel c .
We use the channel name c to denote the message that was last previously read on the channel.
And √c is a boolean expression meaning “there is unread input available on channel c ”. Here are
the formal definitions (omitting the obvious subscripts).
c! e = M w = e ∧ T w = t ∧ (w:= w+1)
“ c output e ”
c! = T w = t ∧ (w:= w+1)
“ c signal”
c? = r:= r+1
“ c input”
c
= M (r–1)
√c = T r ≤ t
“check c ”
Suppose the input channel from a keyboard is named key , and the output channel to a screen is
named screen . Then execution of the program
if √key
then (key?. if key=`y then screen! "If you wish." else screen! "Not if you don't want.")
else screen! "Well?"
tests if a character of input is available, and if so, reads it and prints some output, which depends
on the character read, and if not, prints other output.
Let us refine the specification Mdwd = even (Mcrc) given earlier.
Mdwd = even (Mcrc) ⇐ c?. d! even c
To prove the refinement, we can rewrite the solution as follows:
c?. d! even c
= rc:= rc+1. Mdwd = even (Mc(rc–1)) ∧ Tdwd = t ∧ (wd:= wd+1)
= Mdwd = even (Mcrc) ∧ Tdwd=t ∧ rc′=rc+1 ∧ wc′=wc ∧ rd′=rd ∧ wd′=wd+1
which implies the problem.
A problem specification should be written as clearly, as understandably, as possible. A
programmer refines the problem specification to obtain a solution program, which a computer can
execute. In our example, the solution seems more understandable than the problem! Whenever
that is the case, we should consider using the program as the problem specification, and then there
is no need for refinement.
Our next problem is to read numbers from channel c , and write their doubles on channel d .
Ignoring time, the specification can be written
S = ∀n: nat· Md (wd+n) = 2 × Mc (rc+n)
We cannot assume that the input and output are the first input and output ever on channels c and
d . We can only ask that from now on, starting at the initial read cursor rc and initial write cursor
wd , the outputs will be double the inputs. This specification can be refined as follows.
S ⇐ c?. d! 2×c. S
The proof is:
c?. d! 2×c. S
= rc:= rc+1. Mdwd = 2 × Mc (rc–1) ∧ (wd:= wd+1). S
= Mdwd = 2 × Mcrc ∧ ∀n: nat· Md (wd+1+n) = 2 × Mc (rc+1+n)
= ∀n: nat· Md (wd+n) = 2 × Mc (rc+n)
= S
End of Input and Output
9 Interaction
9.1.2
134
Communication Timing
In the real time measure, we need to know how long output takes, how long communication transit
takes, and how long input takes, and we place time increments appropriately. To be independent
of these implementation details, we can use the transit time measure, in which we suppose that the
acts of input and output take no time at all, and that communication transit takes 1 time unit.
The message to be read next on channel c is Mcrc . This message was or is or will be sent at time
Tcrc . Its arrival time, according to the transit time measure, is Tcrc + 1 . So input becomes
t:= max t (Tcrc + 1). c?
If the input has already arrived, Tcrc + 1 ≤ t , and no time is spent waiting for input; otherwise
execution of c? is delayed until the input arrives. And the input check √c becomes
√c = Tcrc + 1 ≤ t
In some applications (called “batch processing”), all inputs are available at the start of execution;
for these applications, we may as well leave out the time assignments for input, and we have no
need for the input check. In other applications (called “process control”), inputs are provided at
regular intervals by a physical sampling device; the time script (but not the message script) is
known in advance. In still other applications (called “interactive computing”), a human provides
inputs at irregular intervals, and we have no way of saying what the time script is. In this case, we
have to leave out the waiting times, and just attach a note to our calculation saying that execution
time will be increased by any time spent waiting for input.
Exercise 407(a): Let W be “wait for input on channel c and then read it”. Formally,
W = t:= max t (T r + 1). c?
Prove W ⇐ if √c then c? else (t:= t+1. W) assuming time is an extended integer. The
significance of this exercise is that input is often implemented in just this way, with a test to see if
input is available, and a loop if it is not. Proof:
if √c then r:= r+1 else (t:= t+1. W)
= if T r + 1 ≤ t then r:= r+1 else (t:= t+1. t:= max t (T r + 1). r:= r+1)
= if T r + 1 ≤ t then (t:= t. r:= r+1) else (t:= max (t+1) (T r + 1). r:= r+1)
If T r + 1 ≤ t , then t = max t (T r + 1) .
If T r + 1 > t then max (t+1) (T r + 1) = T r + 1 = max t (T r + 1) .
= if T r + 1 ≤ t then (t:= max t (T r + 1). r:= r+1) else (t:= max t (T r + 1). r:= r+1)
= W
End of Communication Timing
9.1.3
Recursive Communication
optional; requires Chapter 6
Define dbl by the fixed-point construction (including recursive time but ignoring input waits)
dbl = c?. d! 2×c. t:= t+1. dbl
Regarding dbl as the unknown, this equation has several solutions. The weakest is
∀n: nat· Md (wd+n) = 2 × Mc (rc+n) ∧ Td (wd+n) = t+n
A strongest implementable solution is
(∀n: nat· Md (wd+n) = 2 × Mc (rc+n) ∧ Td (wd+n) = t+n)
∧ rc′=wd′=t′=∞ ∧ wc′=wc ∧ rd′=rd
The strongest solution is
. If this fixed-point construction is all we know about dbl , then we
cannot say that it is equal to a particular one of the solutions. But we can say this: it refines the
weakest solution
∀n: nat· Md (wd+n) = 2 × Mc (rc+n) ∧ Td (wd+n) = t+n ⇐ dbl
135
9 Interaction
and it is refined by the right side of the fixed-point construction
dbl ⇐ c?. d! 2×c. t:= t+1. dbl
Thus we can use it to solve problems, and we can execute it.
If we begin recursive construction with
dbl0 =
we find
dbl1 = c?. d! 2×c. t:= t+1. dbl0
= rc:= rc+1. Mdwd = 2×Mc(rc–1) ∧ Tdwd = t ∧ (wd:= wd+1). t:= t+1.
= M d w d = 2× M c r c ∧ T d w d = t
dbl2 = c?. d! 2×c. t:= t+1. dbl1
= rc:= rc+1. Mdwd = 2×Mc(rc–1) ∧ Tdwd = t ∧ (wd:= wd+1).
t:= t+1. Mdwd = 2×Mcrc ∧ Tdwd = t
= Mdwd = 2×Mcrc ∧ Tdwd = t ∧ Md(wd+1) = 2×Mc(rc+1) ∧ Td(wd+1) = t+1
and so on. The result of the construction
dbl∞ = ∀n: nat· Md (wd+n) = 2 × Mc (rc+n) ∧ Td (wd+n) = t+n
is the weakest solution of the dbl fixed-point construction. If we begin recursive construction
with t′≥t ∧ rc′≥rc ∧ wc′≥wc ∧ rd′≥rd ∧ wd′≥wd we get a strongest implementable solution.
End of Recursive Communication
9.1.4
Merge
Merging means reading repeatedly from two or more input channels and writing those inputs onto
another channel. The output is an interleaving of the messages from the input channels. The
output must be all and only the messages read from the inputs, and it must preserve the order in
which they were read on each channel. Infinite merging can be specified formally as follows. Let
the input channels be c and d , and the output channel be e . Then
merge = (c?. e! c) ∨ (d?. e! d). merge
This specification does not state any criterion for choosing between the input channels at each step.
To write a merge program, we must decide on a criterion for choosing. We might choose between
the input channels based on the value of the inputs or on their arrival times.
Exercise 411(a) (time merge) asks us to choose the first available input at each step. If input is
already available on both channels c and d , take either one; if input is available on just one
channel, take that one; if input is available on neither channel, wait for the first one and take it (in
case of a tie, take either one). Here is the specification.
timemerge =
(√c ∨ Tcrc ≤ Tdrd) ∧ (c?. e! c)
∨ (√d ∨ Tcrc ≥ Tdrd) ∧ (d?. e! d).
timemerge
To account for the time spent waiting for input, we should insert t:= max t (Tr + 1) just before
each input operation, and for recursive time we should insert t:= t+1 before the recursive call.
In Subsection 9.1.2 on Communication Timing we proved that waiting for input can be
implemented recursively. Using the same reasoning, we implement timemerge as follows.
timemerge ⇐ if √c then (c?. e! c) else ok.
if √d then (d?. e! d) else ok.
t:= t+1. timemerge
assuming time is an extended integer.
End of Merge
9 Interaction
9.1.5
136
Monitor
To obtain the effect of a fully shared variable, we create a process called a monitor that resolves
conflicting uses of the variable. A monitor for variable x receives on channels x0in , x1in , ...
data from other processes to be written to the variable, whereupon it sends an acknowledgement
back to the writing process on one of the channels x0ack , x1ack , ... . It receives on channels
x0req , x1req , ... requests from other processes to read the variable, whereupon it sends the
value of the variable back to the requesting process on one of the channels x0out , x1out , ... .
x0in
x0ack
x
x1in
x1ack
x0req
x0out
x1req
x1out
A monitor for variable x with two writing processes and two reading processes can be defined as
follows. Let m be the minimum of the times of the next input on each of the input channels
Tx0inrx0in , Tx1inrx1in , Tx0reqrx0req , and Tx1reqrx1req . Then
monitor
=
(√x0in ∨ Tx0inrx0in = m) ∧
∨ (√x1in ∨ Tx1inrx1in = m) ∧
∨ (√x0req ∨ Tx0reqrx0req = m)
∨ (√x1req ∨ Tx1reqrx1req = m)
monitor
(x0in?. x:= x0in. x0ack!)
(x1in?. x:= x1in. x1ack!)
∧ (x0req?. x0out! x)
∧ (x1req?. x1out! x).
Just like timemerge , a monitor takes the first available input and responds to it. A monitor for
several variables, for several writing processes, and for several reading processes, is similar.
When more than one input is available, an implementation must make a choice. Here's one way to
implement a monitor, assuming time is an extended integer:
monitor ⇐
if √x0in then (x0in?. x:= x0in. x0ack!) else ok.
if √x1in then (x1in?. x:= x1in. x1ack!) else ok.
if √x0req then (x0req?. x0out! x) else ok.
if √x1req then (x1req?. x1out! x) else ok.
t:= t+1. monitor
We earlier solved Exercise 388 to specify a thermostat for a gas burner using interactive variables
gas , temperature , desired , flame , and spark , as follows.
thermostat
=
if gas then GasIsOn else GasIsOff
GasIsOn
=
if temperature < desired + ε ∧ flame
then (t ≤ t′ ≤ t+1 ∧ (∀t′′· t≤t′′≤t′ ⇒ gas′′ ∧ ¬spark′′). GasIsOn)
else (t+20 ≤ t′ ≤ t+21 ∧ (∀t′′· t≤t′′≤t′ ⇒ ¬gas′′ ∧ ¬spark′′). GasIsOff)
GasIsOff
=
if temperature < desired – ε
then (t+1 ≤ t′ ≤ t+3 ∧ (∀t′′· t≤t′′≤t′ ⇒ gas′′ ∧ spark′′). GasIsOn)
else (t ≤ t′ ≤ t+1 ∧ (∀t′′· t≤t′′≤t′ ⇒ ¬gas′′ ∧ ¬spark′′). GasIsOff)
If we use communication channels instead of interactive variables, we have to build a monitor for
these variables, and rewrite our thermostat specification. Here is the result.
137
9 Interaction
thermostat
=
gasreq!. gas?. if gas then GasIsOn else GasIsOff
GasIsOn
=
temperaturereq!. temperature?. desiredreq!. desired?.
flamereq!. flame?.
if temperature < desired + ε ∧ flame
then (t ≤ t′ ≤ t+1. GasIsOn)
else (gasin! . gasack?. t+20 ≤ t′ ≤ t+21. GasIsOff)
GasIsOff
=
temperaturereq!. temperature?. desiredreq!. desired?.
if temperature < desired – ε
then ( gasin! . gasack?. sparkin! . sparkack?. t+1 ≤ t′ ≤ t+3.
sparkin! . sparkack?. GasIsOn)
else (t ≤ t′ ≤ t+1. GasIsOff)
End of Monitor
9.1.6
Reaction Controller
Many kinds of reactions are controlled by a feedback loop, as shown in the following picture.
sensors
analog
data
plant
motors
digitizer
digital data
control
signals
controller
The “plant” could be a chemical reactor, or a nuclear reactor, or even just an assembly plant. The
sensors detect concentrations or temperatures or positions in the form of analog data, and feed
them to a digitizer. The digitizer converts these data to digital form suitable for the controller. The
controller computes what should happen next to control the plant; perhaps some rods should be
pushed in farther, or some valves should be opened, or a robot arm should move in some
direction. The controller sends signals to the plant to cause the appropriate change.
Here's the problem. The sensors send their data continuously to the digitizer. The digitizer is fast
and uniform, sending digital data rapidly to the controller. The time required by the controller to
compute its output signals varies according to the input messages; sometimes the computation is
trivial and it can keep up with the input; sometimes the computation is more complex and it falls
behind. When several inputs have piled up, the controller should not continue to read them and
compute outputs in the hope of catching up. Instead, we want all but the latest input to be
discarded. It is not essential that control signals be produced as rapidly as digital data. But it is
essential that each control signal be based on the latest available data. How can we achieve this?
The solution is to place a synchronizer between the digitizer and controller, as in the following
picture.
9 Interaction
analog
data
sensors
138
digitizer
digital data
plant
synchronizer
request
control
signals
motors
reply
controller
The synchronizer's job is as simple and uniform as the digitizer's; it can easily keep up. It
repeatedly reads the data from the digitizer, always keeping only the latest. Whenever the
controller requests some data, the synchronizer sends the latest. This is exactly the function of a
monitor, and we could implement the synchronizer that way. But a synchronizer is simpler than a
monitor in two respects: first, there is only one writing process and one reading process; second,
the writing process is uniformly faster than the reading process. Here is its definition.
synchronizer
=
digitaldata?.
if √request then (request? || reply! digitaldata) else ok.
synchronizer
If we were using interactive variables instead of channels, there would be no problem of reading
old data; reading an interactive variable always reads its latest value, even if the variable is written
more often than it is read. But there would be the problem of how to make sure that the interactive
variable is not read while it is being written.
End of Reaction Controller
9.1.7
Channel Declaration
The next input on a channel is not necessarily the one that was last previously written on that
channel. In one variable x and one channel c (ignoring time),
c! 2. c?. x:= c
= Mw = 2 ∧ w′ = w+1 ∧ r′ = r+1 ∧ x′ = M r
We do not know that initially w=r , so we cannot conclude that finally x′=2 . That's because
there may have been a previous write that hasn't been read yet. For example,
c! 1. c! 2. c?. x:= c
The next input on a channel is always the first one on that channel that has not yet been read. The
same is true in a parallel composition.
c! 2 || (c?. x:= c)
= Mw = 2 ∧ w′ = w+1 ∧ r′ = r+1 ∧ x′ = M r
Again we cannot say x′=2 because there may be a previous unread output
c! 1. (c! 2 || (c?. x:= c)). c?
and the final value of x may be the 1 from the earlier output, with the 2 going to the later input.
In order to achieve useful communication between processes, we have to introduce a local channel.
Channel declaration is similar to variable declaration; it defines a new channel within some local
portion of a program or specification. A channel declaration applies to what follows it, according
to the precedence table on the final page of this book. Here is a syntax and equivalent
specification.
chan c: T· P = ∃Mc: [∞*T]· ∃Tc: [∞*xreal]· var rc , wc: xnat := 0· P
The type T says what communications are possible on this new channel. The declaration
139
9 Interaction
introduces two scripts, which are infinite lists; they are not state variables, but state constants of
unknown value (mathematical variables). We have let time be extended real, but we could let it be
extended integer. The channel declaration also introduces a read cursor rc with initial value 0 to
say that initially there has been no input on this channel, and a write cursor wc with initial value 0
to say that initially there has been no output on this channel.
A local channel can be used without concurrency as a queue, or buffer. For example,
chan c: int· c! 3. c! 4. c?. x:= c. c?. x:= x+c
assigns 7 to x . Here is the proof, including time.
chan c: int· c! 3. c! 4. t:= max t (Tr + 1). c?. x:= c. t:= max t (Tr + 1). c?. x:= x+c
=
=
=
∃M: [∞*int]· ∃T: [∞*xint]· var r, w: xnat := 0·
Mw = 3 ∧ Tw = t ∧ (w:= w+1).
Mw = 4 ∧ Tw = t ∧ (w:= w+1).
t:= max t (Tr + 1). r:= r+1.
x:= M (r–1).
t:= max t (Tr + 1). r:= r+1.
x:= x + M (r–1)
now use the Substitution Law several times
∃M: [∞*int]· ∃T: [∞*xint]· ∃r, r′, w, w′: xnat·
M0 = 3 ∧ T0 = t ∧ M1 = 4 ∧ T1 = t ∧ r′ = 2 ∧ w′ = 2 ∧ x′ = M0 + M1
∧ t′ = max (max t (T0 + 1)) (T1 + 1) ∧ (other variables unchanged)
x′=7 ∧ t′ = t+1 ∧ (other variables unchanged)
Here are two processes with a communication between them. Ignoring time,
chan c: int· c! 2 || (c?. x:= c)
Use the definition of local channel declaration,
and use the previous result for the independent composition
= ∃M: [∞*int]· var r, w: xnat := 0·
Mw = 2 ∧ w′ = w+1 ∧ r′:= r+1 ∧ x′ = M r ∧ (other variables unchanged)
Now apply the initialization r:= 0 and w:= 0 using the Substitution Law
= ∃M: [∞*int]· var r, w: xnat·
M 0 = 2 ∧ w′=1 ∧ r′=1 ∧ x′ = M 0 ∧ (other variables unchanged)
= x′=2 ∧ (other variables unchanged)
= x:= 2
Replacing 2 by an arbitrary expression, we have a general theorem equating communication on a
local channel with assignment. If we had included time, the result would have been
x′=2 ∧ t′ = t+1 ∧ (other variables unchanged)
= x:= 2. t:= t+1
End of Channel Declaration
9.1.8
Deadlock
In the previous subsection we saw that a local channel can be used as a buffer. Let's see what
happens if we try to read first and write after. Inserting the input wait into
chan c: int· c?. c! 5
gives us
9 Interaction
140
chan c: int· t:= max t (T r + 1). c?. c! 5
=
∃M: [∞*int]· ∃T: [∞*xint]· var r, w: xnat := 0·
t:= max t (T r + 1). r:= r+1. M w = 5 ∧ T w = t ∧ (w:= w+1)
We'll do this one slowly. First, expand var and w:= w+1 ,
taking r , w , x , and t as the state variables.
= ∃M: [∞*int]· ∃T: [∞*xint]· ∃r, r′, w, w′: xnat·
r:= 0. w:= 0. t:= max t (T r + 1). r:= r+1.
M w = 5 ∧ T w = t ∧ r′=r ∧ w′ = w+1 ∧ x′=x ∧ t′=t
Now use the Substitution Law four times.
= ∃M: [∞*int]· ∃T: [∞*xint]· ∃r, r′, w, w′: xnat·
M 0 = 5 ∧ T 0 = max t (T 0 + 1) ∧ r′=1 ∧ w′=1 ∧ x′=x ∧ t′ = max t (T 0 + 1)
Look at the conjunct T 0 = max t (T 0 + 1) . For any start time t > –∞ it says T 0 = ∞ .
= x′=x ∧ t′=∞
The theory tells us that execution takes forever because the wait for input is infinite.
The word “deadlock” is usually used to mean that several processes are waiting on each other, as
in the dining philosophers example of Chapter 8. But it might also be used to mean that a single
sequential computation is waiting on itself, as in the previous paragraph. Here's the more
traditional example with two processes.
chan c, d: int· (c?. d! 6) || (d?. c! 7)
Inserting the input waits, we get
chan c, d: int· (t:= max t (Tcrc + 1). c?. d! 6) || (t:= max t (Tdrd + 1). d?. c! 7)
after a little work, we obtain
= ∃Mc, Md: [∞*int]· ∃Tc, Td: [∞*xint]· ∃rc, rc′, wc, wc′, rd, rd′, wd, wd′: xnat·
Md0 = 6 ∧ Td0 = max t (Tc0 + 1) ∧ Mc0 = 7 ∧ Tc0 = max t (Td0 + 1)
∧ rc′ = wc′ = rd′ = wd′ = 1 ∧ x′=x ∧ t′ = max (max t (Tc0 + 1)) (max t (Td0 + 1))
Once again, for start time t>–∞ , the conjuncts
Td0 = max t (Tc0 + 1) ∧ Tc0 = max t (Td0 + 1) tell us that Td0 = Tc0 = ∞ .
= x′=x ∧ t′=∞
To prove that a computation is free from deadlock, prove that all message times are finite.
End of Deadlock
9.1.9
Broadcast
A channel consists of a message script, a time script, a read cursor, and a write cursor. Whenever
a computation splits into parallel processes, the state variables must be partitioned among the
processes. The scripts are not state variables; they do not belong to any process. The cursors are
state variables, so one of the processes can write to the channel, and one (perhaps the same one,
perhaps a different one) can read from the channel. Suppose the structure is
P. (Q || R || S). T
and suppose Q writes to channel c and R reads from channel c . The messages written by Q
follow those written by P , and those written by T follow those written by Q . The messages
read by R follow those read by P , and those read by T follow those read by R . There is no
problem of two processes attempting to write at the same time, and the timing discipline makes
sure that reading a message waits until after it is written.
Although communication on a channel, as defined so far, is one-way from a single writer to a
single reader, we can have as many channels as we want. So we can have two-way conversations
141
9 Interaction
between all pairs of processes. But sometimes it is convenient to have a broadcast from one
process to more than one of the parallel processes. In the program structure of the previous
paragraph, we might want Q to write and both of R and S to read on the same channel.
Broadcast is achieved by several read cursors, one for each reading process. Then all reading
processes read the same messages, each at its own rate. There is no harm in two processes reading
the same message, even at the same time. But there is a problem with broadcast: which of the read
cursors becomes the read cursor for T ? All of the read cursors start with the same value, but they
may not end with the same value. There is no sensible way to continue reading from that channel.
So we allow broadcast on a channel only when the parallel composition is not followed
sequentially by a program that reads from that channel.
We next present a broadcast example that combines communicating processes, local channel
declaration, and dynamic process generation, in one beautiful little program. It is also a striking
example of the importance of good notation and good theory. It has been “solved” before without
them, but the “solutions” required many pages, intricate synchronization arguments, lacked proof,
and were sometimes wrong.
Exercise 415 is multiplication of power series: Write a program to read from channel a an infinite
sequence of coefficients a0 a1 a2 a3 ... of a power series a0 + a1×x + a2×x2 + a3×x3 + ... and in
parallel to read from channel b an infinite sequence of coefficients b0 b1 b2 b3 ... of a power
series b0 + b1×x + b2×x2 + b3×x3 + ... and in parallel to write on channel c the infinite sequence
of coefficients c0 c1 c2 c3 ... of the power series c 0 + c 1× x + c 2× x 2 + c 3× x 3 + ... equal to the
product of the two input series. Assume that all inputs are already available; there are no input
delays. Produce the outputs one per time unit.
The question provides us with a notation for the coefficients: an = M a(ra+n) , bn = M b(rb+n) ,
and cn = M c (w c +n) . Let us use A , B , and C for the power series, so we can express our
desired result as
C = A ×B
= (a0 + a1×x + a2×x2 + a3×x3 + ... ) × (b0 + b1×x + b2×x2 + b3×x3 + ... )
=
a0×b0 + (a0×b1 + a1×b0)×x + (a0×b2 + a1×b1 + a2×b0)×x2
+ (a0×b3 + a1×b2 + a2×b1 + a3×b0)×x3 + ...
from which we see cn = Σi: 0,..n+1· ai×bn–i . The question relieves us from concern with input
times, but we are still concerned with output times. The complete specification is
C = A×B ∧ ∀n· Tc(wc+n) = t+n
Consider the problem: output coefficient n requires n+1 multiplications and n additions from
2×(n+1) input coefficients, and it must be produced 1 time unit after the previous coefficient. To
accomplish this requires more and more data storage, and more and more parallelism, as execution
progresses.
As usual, let us concentrate on the result first, and leave the time for later. Let
A1 = a1 + a2×x + a3×x2 + a4×x3 + ...
B 1 = b 1 + b 2× x + b 3× x 2 + b 4× x 3 + ...
be the power series from channels a and b beginning with coefficient 1 . Then
A ×B
=
(a0 + A1×x) × (b0 + B1×x)
=
a0×b0 + (a0×B 1 + A 1×b0)×x + A 1×B 1×x2
9 Interaction
142
In place of the problem A×B we have five new problems. The first is to read one coefficient from
each input channel and output their product; that's easy. The next two, a0×B 1 and A 1×b0 , are
multiplying a power series by a constant; that's easier than multiplying two power series,
requiring only a loop. The next, A 1 × B 1 , is exactly the problem we started with, but one
coefficient farther along; it can be solved by recursion. Finally, we have to add three power series
together. Unfortunately, these three power series are not synchronized properly. We must add the
leading coefficients of a0×B1 and A1×b0 without any coefficient from A1×B1 , and thereafter
add coefficient n+1 of a 0× B 1 and A1×b0 to coefficient n of A 1×B 1 . To synchronize, we
move a0×B1 and A1×b0 one coefficient farther along. Let
A2 = a2 + a3×x + a4×x2 + a5×x3 + ...
B 2 = b 2 + b 3× x + b 4× x 2 + b 5× x 3 + ...
be the power series from channels a and b beginning with coefficient 2 . Continuing the earlier
equation for A×B ,
=
a0×b0 + (a0×(b1 + B2×x) + (a1 + A2×x)×b0)×x + A1×B1×x2
=
a0×b0 + (a0×b1 + a1×b0)×x + (a0×B2 + A1×B1 + A2×b0)×x2
From this expansion of the desired product we can almost write a solution directly.
One problem remains. A recursive call will be used to obtain a sequence of coefficients of the
product A1×B1 in order to produce the coefficients of A×B . But the output channel for A 1 × B 1
cannot be channel c , the output channel for the main computation A×B . Instead, a local channel
must be used for output from A1×B1 . We need a channel parameter, for which we invent the
notation λ! . A channel parameter is really four parameters: one for the message script, one for
the time script, one for the write cursor, and one for the read cursor. (The cursors are variables, so
their parameters are reference parameters; see Section 5.5.2.)
Now we are ready. Define P (for product) to be our specification (ignoring time for a moment)
parameterized by output channel.
P = λ!c: rat· C = A×B
We refine P c as follows.
Pc ⇐
a?. b?. c! a×b.
var a0: rat := a· var b0: rat := b· chan d: rat·
P d || (a?. b?. c! a0×b + a×b0. C = a0×B + D + A×b0)
C = a0×B + D + A×b0
⇐
a?. b?. d?. c! a0×b + d + a×b0. C = a0×B + D + A×b0
That is the whole program: 4 lines! First, an input is read from each of channels a and b and
their product is output on channel c ; that takes care of a0×b0 . We will need these values again,
so we declare local variables (really constants) a0 and b0 to retain their values. Now that we
have read one message from each input channel, before we read another, we call P d to provide
the coefficients of A 1× B 1 on local channel d , in parallel with the remainder of the program.
Both P d and its parallel process will be reading from channels a and b using separate read
cursors; there is no computation sequentially following them. In parallel with P d we read the
next inputs a1 and b1 and output the coefficient a0×b1 + a1×b0 . Finally we execute the loop
specified as C = a0 ×B + D + A ×b0 , where D is the power series whose coefficients are read
from channel d .
The proof is completely straightforward. Here it is in detail.
143
9 Interaction
a?. b?. c! a×b.
var a0: rat := a· var b0: rat := b· chan d: rat·
P d || (a?. b?. c! a0×b + a×b0. C = a0×B + D + A×b0)
=
=
⇒
=
=
ra:= ra+1. rb:= rb+1. Mcwc = Ma(ra–1) × Mb(rb–1) ∧ (wc:= wc+1).
∃a0, a0′, b0, b0′, M d, rd, rd′, wd, wd′·
a0:= Ma(ra–1). b0:= Mb(rb–1). rd:= 0. wd:= 0.
(∀n· Md(wd+n) = (Σi: 0,..n+1· Ma(ra+i) × Mb(rb+n–i)))
∧ (ra:= ra+1. rb:= rb+1. Mcwc = a0×Mb(rb–1) + Ma(ra–1)×b0 ∧ (wc:= wc+1).
∀n· Mc(wc+n) = a0 × Mb(rb+n) + Md(rd+n) + Ma(ra+n) × b0)
Make all substitutions indicated by assignments.
M c w c = M a r a × Mb r b
∧ ∃a0, a0′, b0, b0′, M d, rd, rd′, wd, wd′·
(∀n· Mdn = Σi: 0,..n+1· Ma(ra+1+i) × Mb(rb+1+n–i))
∧ Mc(wc+1) = Mara × Mb(rb+1) + Ma(ra+1) × Mbrb
∧ (∀n· Mc(wc+2+n) = Mara × Mb(rb+2+n) + Mdn + Ma(ra+2+n) × Mbrb)
Use the first universal quantification to replace Mdn in the second.
Then throw away the first universal quantification (weakening our expression).
Now all existential quantifications are unused, and can be thrown away.
M c w c = M a r a × Mb r b
∧ Mc(wc+1) = Mara × Mb(rb+1) + Ma(ra+1) × Mbrb
∧ ∀n· M c(w c+2+n) =
Mara × Mb(rb+2+n)
+ (Σi: 0,..n+1· Ma(ra+1+i) × Mb(rb+1+n–i))
+ Ma(ra+2+n) × Mbrb
Now put the three conjuncts together.
∀n· M c(wc+n) = Σi: 0,..n+1· M a(ra+i) × Mb(rb+n–i)
Pc
We still have to prove the loop refinement.
a?. b?. d?. c! a0×b + d + a×b0. C = a0×B + D + A×b0
=
=
=
=
ra:= ra+1. rb:= rb+1. rd:= rd+1.
Mcwc = a0 × Mb(rb–1) + Md(rd–1) + Ma(ra–1) × b0 ∧ (wc:= wc+1).
∀n· Mc(wc+n) = a0 × Mb(rb+n) + Md(rd+n) + Ma(ra+n) × b0
Make all substitutions indicated by assignments.
Mcwc = a0 × Mbrb + Mdrd + Mara × b0
∧ ∀n· Mc(wc+1+n) = a0 × Mb(rb+1+n) + Md(rd+1+n) + Ma(ra+1+n) × b0
Put the two conjuncts together.
∀n· Mc(wc+n) = a0 × Mb(rb+n) + Md(rd+n) + Ma(ra+n) × b0
C = a0×B + D + A×b0
According to the recursive measure of time, we must place a time increment before the recursive
call P d and before the recursive call C = a0×B + D + A×b0 . We do not need a time increment
before inputs on channels a and b according to information given in the question. We do need a
time increment before the input on channel d . Placing only these necessary time increments,
output c0 = a0×b0 will occur at time t+0 as desired, but output c1 = a0×b1 + a1×b0 will also
occur at time t+0 , which is too soon. In order to make output c1 occur at time t+1 as desired,
we must place a time increment between the first two outputs. We can consider this time increment
to account for actual computing time, or as a delay (see Chapter 5, “Time and Space Dependence”).
Here is the program with time.
9 Interaction
Pc
⇐
144
a?. b?. c! a×b.
var a0: rat := a· var b0: rat := b· chan d: rat·
(t:= t+1. P d) || (a?. b?. t:= t+1. c! a0×b + a×b0. Q)
Q ⇐ a?. b?. t:= max t (Tdrd+1). d?. c! a0×b + d + a×b0. t:= t+1. Q
where P is redefined, and Q is defined, as follows:
P c = ∀n· Tc(wc+n) = t+n
P d = ∀n· Td(wd+n) = t+n
Q = (∀n· Td(rd+n) = t+n) ⇒ (∀n· Tc(wc+n) = t+1+n)
We could factor the first two occurrences of t:= t+1 out of the independent composition, but it
doesn't really matter. There is one change we can make to the placement of time increments that
matters greatly. Within loop Q , the assignment t:= max t (Tdrd+1) represents a delay of 1 time
unit the first iteration (because t = Tdrd ), and a delay of 0 time units each subsequent iteration
(because t = T d r d +1 ). This makes the proof very ugly. To make the proof pretty, we can
replace t:= max t (Tdrd+1) by t:= max (t+1) (Tdrd+1) and delete t:= t+1 just before the call to
Q . These changes together do not change the timing at all; they just make the proof easier. The
assignment t:= max (t+1) (Tdrd+1) increases the time by at least 1 , so the loop includes a time
increase without the t:= t+1 . The program with time is now
P c ⇐ a?. b?. c! a×b.
var a0: rat := a· var b0: rat := b· chan d: rat·
(t:= t+1. P d) || (a?. b?. t:= t+1. c! a0×b + a×b0. Q)
Q
⇐
a?. b?. t:= max (t+1) (Tdrd+1). d?. c! a0×b + d + a×b0. Q
In the main part of the timing proof, we accept Q as defined, without looking at its refinement.
a?. b?. c! a×b.
var a0: rat := a· var b0: rat := b· chan d: rat·
(t:= t+1. P d) || (a?. b?. t:= t+1. c! a0×b + a×b0. Q)
We can ignore a? and b? because they have no effect on timing (they are substitutions for
variables that do not appear in P d and L ). We also ignore what messages are output,
looking only at their times. We can therefore also ignore variables a0 and b0 .
⇒ Tcwc = t ∧ (wc:= wc+1).
∃Td, rd, rd′, wd, wd′· rd:= 0. wd:= 0.
(t:= t+1. ∀n· Td(wd+n) = t+n)
∧ ( t:= t+1. Tcwc = t ∧ (wc:= wc+1).
(∀n· Td(rd+n) = t+n) ⇒ (∀n· Tc(wc+n) = t+1+n) )
Make all substitutions indicated by assignments.
=
T cw c = t
∧ ∃Td, rd, rd′, w d, w d′·
(∀n· Tdn = t+1+n)
∧ Tc(wc+1) = t+1
∧ ((∀n· Tdn = t+1+n) ⇒ (∀n· Tc(wc+2+n) = t+2+n))
Use the first universal quantification to discharge the antecedent.
Then throw away the first universal quantification (weakening our expression).
Now all existential quantifications are unused, and can be thrown away.
⇒ Tcwc = t ∧ Tc(wc+1) = t+1 ∧ ∀n· Tc(wc+2+n) = t+2+n
Now put the three conjuncts together.
= ∀n· Tc(wc+n) = t+n
= Pc
145
9 Interaction
We still have to prove the loop refinement.
(Q ⇐ a?. b?. t:= max (t+1) (Tdrd+1). d?. c! a0×b + d + a×b0. Q)
Ignore a? and b? and the output message.
⇐
((∀n· Td(rd+n) = t+n) ⇒ (∀n· Tc(wc+n) = t+1+n))
⇐ ( t:= max (t+1) (Tdrd+1). rd:= rd+1. Tcwc = t ∧ (wc:= wc+1).
(∀n· Td(rd+n) = t+n) ⇒ (∀n· Tc(wc+n) = t+1+n) )
Use the Law of Portation to move the first antecedent
to the right side, where it becomes a conjunct.
=
(∀n· Tc(wc+n) = t+1+n)
⇐
(∀n· Td(rd+n) = t+n)
∧ ( t:= max (t+1) (Tdrd+1). rd:= rd+1. Tcwc = t ∧ (wc:= wc+1).
(∀n· Td(rd+n) = t+n) ⇒ (∀n· Tc(wc+n) = t+1+n) )
Specializing ∀n· Td(rd+n) = t+n to the case n=0,
we use Tdrd = t to simplify max (t+1) (Tdrd+1).
=
(∀n· Tc(wc+n) = t+1+n)
⇐
(∀n· Td(rd+n) = t+n)
∧ ( t:= t+1. rd:= rd+1. Tcwc = t ∧ (wc:= wc+1).
(∀n· Td(rd+n) = t+n) ⇒ (∀n· Tc(wc+n) = t+1+n) )
Make all substitutions indicated by assignments.
=
(∀n· Tc(wc+n) = t+1+n)
⇐
(∀n· Td(rd+n) = t+n)
∧ Tcwc = t+1
∧ ((∀n· Td(rd+1+n) = t+1+n) ⇒ (∀n· Tc(wc+1+n) = t+2+n))
The conjunct ∀n· Td(rd+n) = t+n discharges the antecedent
∀n· Td(rd+1+n) = t+1+n which can be dropped.
⇐
(∀n· Tc(wc+n) = t+1+n)
⇐ Tcwc = t+1 ∧ (∀n· Tc(wc+1+n) = t+2+n)
=
End of Broadcast
End of Communication
End of Interaction
For many students, the first understanding of programs they are taught is how programs are
executed. And for many students, that is the only understanding they are given. With that
understanding, the only method available for checking whether a program is correct is to test it by
executing it with a variety of inputs to see if the resulting outputs are right. All programs should be
tested, but there are two problems with testing.
One problem with testing is: how do you know if the outputs are right? With some programs, for
example graphics programs for producing pretty pictures, the only way to know if the output is
right is to test the program and judge the result. But other programs give answers to questions
whose answers you do not already know (that is why you wrote the program), and you cannot test
them to see if they are right. In that case, you should test to see at least if the answers are
reasonable. The other problem with testing is: you cannot try all inputs. Even if all the test cases
you try give reasonable answers, there may be problems with untried cases.
If you have read and understood this book to here, you now have an understanding of programs
that is completely different from execution. When you prove that a program refines a specification,
you are considering all inputs at once, and you are proving that the outputs have the properties
9 Interaction
146
stated in the specification. That is far more than can ever be accomplished by testing. But it is also
more work than trying some inputs and looking at the outputs. That raises the question: when is
the extra assurance of correctness worth the extra work?
If the program you are writing is easy enough that you can probably get it right without any theory,
and it does not really matter if there are some errors in it, then the extra assurance of correctness
provided by the theory may not be worth the trouble. If you are writing a pacemaker controller for
a heart, or the software that controls a subway system, or an air traffic control program, or nuclear
power plant software, or any other programs that people's lives will depend on, then the extra
assurance is definitely worth the trouble, and you would be negligent if you did not use the theory.
To prove that a program refines a specification after the program is finished is a very difficult task.
It is much easier to perform the proof while the program is being written. The information needed
to make one step in programming is exactly the same information that is needed to prove that step
is correct. The extra work is mainly to write down that information formally. It is also the same
information that will be needed later for program modification, so writing it explicitly at each step
will save effort later. And if you find, by trying to prove a step, that the step is incorrect, you save
the effort of building the rest of your program on a wrong step. As a further bonus, after you
become practiced and skillful at using the theory, you find that it helps in the program design; it
suggests programming steps. In the end, it may not be any extra effort at all.
In this book we have looked only at small programs, but we have done so without any automated
support. For a theory of programming to be in widespread use for industrial program design, it
must be supported by tools. Ideally, an automated prover checks each refinement, remaining silent
if the refinement is correct, complaining whenever there is a mistake, and saying exactly what is
wrong. At present there are a few tools that provide some assistance, but they are far from ideal.
There is plenty of opportunity for tool builders, and they need a thorough knowledge of a practical
theory of programming.
147
10 Exercises
Exercises marked with √ have been done in previous chapters.
10.0 Basic Theories
0
There are four cards on a table. On the cards you see D, E, 2, and 3 (one symbol per
card). You are told that each card has a letter on one side and a digit on the other. You are
asked whether every card with a D on one side has a 3 on the other. Which card(s) do you
need to turn over to answer the question? Why? (Explain in English; no proof needed.)
1
(a)
(b)
(c)
(d)
(e)
(f)
Simplify each of the following boolean expressions.
x ∧ ¬x
x ∨ ¬x
x ⇒ ¬x
x ⇐ ¬x
x = ¬x
x ¬x
2
Prove each of the following laws of Boolean Theory using the proof format given in
Subsection 1.0.1, and any laws listed in Section 11.4. Do not use the Completion Rule.
a∧b ⇒ a∨b
(a∧b) ∨ (b∧c) ∨ (a∧c) = (a∨b) ∧ (b∨c) ∧ (a∨c)
¬a ⇒ (a ⇒ b)
a = (b ⇒ a) = a ∨ b
a = (a ⇒ b) = a ∧ b
(a⇒c) ∧ (b⇒¬c) ⇒ ¬(a∧b)
a ∧ ¬b ⇒ a ∨ b
(a⇒b) ∧ (c⇒d) ∧ (a∨c) ⇒ (b∨d)
a ∧ ¬a ⇒ b
(a⇒b) ∨ (b⇒a)
¬(a ∧ ¬(a∨b))
(¬a⇒¬b) ∧ (a b) ∨ (a∧c ⇒ b∧c)
(a⇒¬a) ⇒ ¬a
(a⇒b) ∧ (¬a⇒b) = b
(a⇒b)⇒a = a
a=b ∨ a=c ∨ b=c
a∧b ∨ a∧¬b = a
a⇒(b⇒a)
a⇒a∧b = a⇒b = a∨b⇒b
if a then a else ¬a
if b∧c then P else Q = if b then if c then P else Q else Q
if b∨c then P else Q = if b then P else if c then P else Q
if b then P else if b then Q else R = if b then P else R
if if b then c else d then P else Q
= if b then if c then P else Q else if d then P else Q
if b then if c then P else R else if c then Q else R
= if c then if b then P else Q else R
if b then if c then P else R else if d then Q else R
= if if b then c else d then if b then P else Q else R
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
(k)√
(l)
(m)
(n)
(o)
(p)
(q)
(r)
(s)
(t)
(u)
(v)
(w)
(x)
(y)
(z)
10 Exercises
3
(a)
(b)
(c)
(d)
(e)
(f)
148
(dual) One operator is the dual of another operator if it negates the result when applied to
the negated operands. The nullary operators
and
are each other's duals. If
op 0 (¬a) = ¬(op1 a) then op0 and op1 are duals. If (¬a) op0 (¬b) = ¬(a op1 b)
then op0 and op1 are duals. And so on for more operands.
Of the 4 unary boolean operators, there is 1 pair of duals, and 2 operators that are their own
duals. Find them.
Of the 16 binary boolean operators, there are 6 pairs of duals, and 4 operators that are their
own duals. Find them.
What is the dual of the ternary operator if then else ? Express it using only the operator
if then else .
The dual of a boolean expression without variables is formed as follows: replace each
operator with its dual, adding parentheses if necessary to maintain the precedence. Explain
why the dual of a theorem is an antitheorem, and vice versa.
Let P be a boolean expression without variables. From part (d) we know that every
boolean expression without variables of the form
(dual of P ) = ¬P
is a theorem. Therefore, to find the dual of a boolean expression with variables, we must
replace each operator by its dual and negate each variable. For example, if a and b are
boolean variables, then the dual of a∧b is ¬a ∨ ¬b . And since
(dual of a∧b ) = ¬(a∧b)
we have one of the Duality Laws:
¬a ∨ ¬b = ¬(a ∧ b)
The other of the Duality Laws is obtained by equating the dual and negation of a∨b .
Obtain five laws that do not appear in this book by equating a dual with a negation.
Dual operators have truth tables that are each other's vertical mirror reflections. For
example, the truth table for ∧ (below left) is the vertical mirror reflection of the truth table
for ∨ (below right).
∧:




∨:




Design symbols (you may redesign existing symbols where necessary) for the 4 unary and
16 binary boolean operators according to the following criteria.
(i) Dual operators should have symbols that are vertical mirror reflections (like ∧ and ∨ ).
This implies that self-dual operators have vertically symmetric symbols, and all others have
vertically asymmetric symbols.
(ii) If a op0 b = b op1 a then op0 and op1 should have symbols that are horizontal
mirror reflections (like ⇒ and ⇐ ). This implies that symmetric operators have
horizontally symmetric symbols, and all others have horizontally asymmetric symbols.
4
Truth tables and the Evaluation Rule can be replaced by a new proof rule and some new
axioms. The new proof rule says: “A boolean expression does not gain, lose, or change
classification when a theorem within it is replaced by another theorem. Similarly, a
boolean expression does not gain, lose, or change classification when an antitheorem
within it is replaced by another antitheorem.”. The truth tables become new axioms; for
example, one truth table entry becomes the axiom ∨ and another becomes the axiom
∨ . These two axioms can be reduced to one axiom by the introduction of a variable,
giving ∨x . Write the truth tables as axioms and antiaxioms as succinctly as possible.
149
5
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(ii)
(iii)
(iv)
(v)
6
(a)
(b)
(c)
(d)
10 Exercises
Complete the following laws of Boolean Theory
=
=
¬a =
a∧b =
a∨b =
a=b =
a b =
a⇒b =
by adding a right side using only the following symbols (in any quantity)
¬∧ab()
¬∨ab()
¬⇒ab()
⇒ab()
¬ if then else a b ( )
(BDD) A BDD (Binary Decision Diagram) is a boolean expression that has one of the
following 3 forms:
,
, if variable then BDD else BDD . For example,
if x then if a then else else if y then if b then else else
is a BDD. An OBDD (Ordered BDD) is a BDD with an ordering on the variables, and in
each if then else , the variable in the if-part must come before any of the variables in its
then- and else-parts (“before” means according to the ordering). For example, using
alphabetic ordering for the variables, the previous example is not an OBDD, but
if a then if c then else else if b then if c then else else
is an OBDD. An LBDD (Labeled BDD) is a set of definitions of the following 3 forms:
label =
label =
label = if variable then label else label
The labels are separate from the variables; each label used in a then-part or else-part must
be defined by one of the definitions. The following is an LBDD.
true =
false =
alice = if b then true else false
bob = if a then alice else false
An LOBDD is an LBDD that becomes an OBDD when the labels are expanded. The
ordering prevents any recursive use of the labels. The previous example is an LOBDD.
An RBDD (Reduced BDD) is a BDD such that, in each if then else , the then- and elseparts differ. An ROBDD is both reduced and ordered; an RLBDD is both reduced and
labeled; an RLOBDD is reduced, labeled, and ordered. The previous example is an
RLOBDD.
Express ¬a , a∧b , a∨b , a⇒b , a=b , a b , and if a then b else c as BDDs.
How can you conjoin two OBDDs and get an OBDD?
How can you determine if two RLOBDDs are equal?
How can we represent an RLOBDD in order to determine efficiently if an assignment of
values to variables satisfies it (solves it, gives it value )?
7
Express formally and succinctly that exactly one of three statements is true.
8
Design symbols for the 10 binary boolean operators that are not presented in Chapter 1,
and find laws about these operators.
10 Exercises
150
9
The Case Analysis Laws equate the ternary operator if a then b else c to expressions
using only binary and unary operators. In each, the variable a appears twice. Find an
equal expression using only binary and unary operators in which the variable a appears
only once. Hint: use continuing operators.
10
Consider a fully parenthesized expression containing only the symbols
= ( ) in any
quantity and any syntactically acceptable order.
Show that all syntactically acceptable rearrangements are equivalent.
Show that it is equivalent to any expression obtained from it by making an even number of
the following substitutions:
for
,
for
, = for
,
for = .
(a)
(b)
11
(a)
(b)
12
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
(k)
(l)
(m)
13
(a)
(b)
(c)
(d)
(e)
14
Let p and q be boolean expressions. Suppose p is both a theorem and an antitheorem
(the theory is inconsistent).
Prove, using the rules of proof presented, that q is both a theorem and an antitheorem.
Is q=q a theorem or an antitheorem?
Formalize each of the following statements as a boolean expression. Start by staying as
close as possible to the English, then simplify as much as possible (sometimes no
simplification is possible). You will have to introduce new basic boolean expressions like
(the door can be opened) for the parts that cannot make use of boolean operators, but for
words like “only if” you should use boolean operators. You translate meanings from
words to boolean symbols; the meaning of the words may depend on their context and
even on facts not explicitly stated. Formalization is not a simple substitution of symbols
for words.
The door can only be opened if the elevator is stopped.
Neither the elevator door nor the floor door will open unless both of them do.
Either the motor is jammed or the control is broken.
Either the light is on or it is off.
If you press the button, the elevator will come.
If the power switch is on, the system is operating.
Where there's smoke, there's fire; and there's no smoke; so there's no fire.
Where there's smoke, there's fire; and there's no fire; so there's no smoke.
You can't score if you don't shoot.
If you have a key, only then can you open the door.
No pain, no gain.
No shirt? No shoes? No service!
If it happens, it happens.
Formalize each of the following statements. For each pair, either prove they are equivalent
or prove they differ.
Don't drink and drive.
If you drink, don't drive.
If you drive, don't drink.
Don't drink and don't drive.
Don't drink or don't drive.
Formalize and prove the following argument. If it is raining and Jane does not have her
umbrella with her, then she is getting wet. It is raining. Jane is not getting wet. Therefore
Jane has her umbrella with her.
151
10 Exercises
15
NO PARKING
7-9am
4-6pm
Mon-Fri
Using variable t for time of day and d for day, write a boolean expression that says when
there is no parking.
16
(tennis) An advertisement for a tennis magazine says “If I'm not playing tennis, I'm
watching tennis. And if I'm not watching tennis, I'm reading about tennis.”. Assuming
the speaker cannot do more than one of these activities at a time,
prove that the speaker is not reading about tennis.
what is the speaker doing?
(a)
(b)
A sign says:
17
(maid and butler) The maid said she saw the butler in the living room. The living room
adjoins the kitchen. The shot was fired in the kitchen, and could be heard in all nearby
rooms. The butler, who had good hearing, said he did not hear the shot. Given these
facts, prove that someone lied. Use the following abbreviations.
mtt = (the maid told the truth)
btt = (the butler told the truth)
blr = (the butler was in the living room)
bnk = (the butler was near the kitchen)
bhs = (the butler heard the shot)
18
(knights and knaves) There are three inhabitants of an island, named P, Q, and R. Each is
either a knight or a knave. Knights always tell the truth. Knaves always lie. For each of
the following, write the given information formally, and then answer the questions, with
proof.
You ask P: “Are you a knight?”. P replies: “If I am a knight, I'll eat my hat.”. Does P eat
his hat?
P says: “If Q is a knight, then I am a knave.”. What are P and Q?
P says: “There is gold on this island if and only if I am a knight.”. Can it be determined
whether P is a knight or a knave? Can it be determined whether there is gold on the island?
P, Q, and R are standing together. You ask P: “Are you a knight or a knave?”. P mumbles
his reply, and you don't hear it. So you ask Q: “What did P say?”. Q replies: “P said that
he is a knave.”. Then R says: “Don't believe Q, he's lying.”. What are Q and R?
You ask P: “How many of you are knights?”. P mumbles. So Q says: “P said there is
exactly one knight among us.”. R says: “Don't believe Q, he's lying.”. What are Q and
R?
P says: “We're all knaves.”. Q says: “No, exactly one of us is a knight.”. What are P, Q,
and R?
(a)
(b)
(c)
(d)
(e)
(f)
19
Islands X and Y contain knights who always tell the truth, knaves who always lie, and
possibly also some normal people who sometimes tell the truth and sometimes lie. There is
gold on at least one of the islands, and the people know which island(s) it is on. You find
a message from the pirate who buried the gold, with the following clue (which we take as
an axiom): “If there are any normal people on Island X, then there is gold on both
islands.”. You are allowed to dig on only one island, and you are allowed to ask one
question of one random person. What should you ask in order to find out which island to
dig on?
10 Exercises
152
20
(caskets) The princess had two caskets, one gold and one silver. Into one she placed her
portrait and into the other she placed a dagger. On the gold casket she wrote the
inscription: the portrait is not in here. On the silver casket she wrote the inscription:
exactly one of these inscriptions is true. She explained to her suitor that each inscription is
either true or false (not both), but on the basis of the inscriptions he must choose a casket.
If he chooses the one with the portrait, he can marry her; if he chooses the one with the
dagger, he must kill himself. Assuming marriage is preferable to death, which casket
should he choose?
21
(the unexpected egg) There are two boxes, one red and one blue. One box has an egg in it;
the other is empty. You are to look first in the red box, then if necessary in the blue box, to
find the egg. But you will not know which box the egg is in until you open the box and
see the egg. You reason as follows: “If I look in the red box and find it empty, I'll know
that the egg is in the blue box without opening it. But I was told that I would not know
which box the egg is in until I open the box and see the egg. So it can't be in the blue box.
Now I know it must be in the red box without opening the red box. But again, that's ruled
out, so it isn't in either box.”. Having ruled out both boxes, you open them and find the
egg in one unexpectedly, as originally stated. Formalize the given statements and the
reasoning, and thus explain the paradox.
22
A number can be written as a sequence of decimal digits. For the sake of generality, let us
consider using the sequence notation with arbitrary expressions, not just digits. For
example, 1(2+3)4 could be allowed, and be equal to 154 . What changes are needed to
the number axioms?
23
(scale) There is a tradition in programming languages to use a scale operator, e , in the
limited context of digit sequences. Thus 12e3 is equal to 12× 10 3 . For the sake of
generality, let us consider using the scale notation with arbitrary expressions, not just
digits. For example, (6+6)e(5–2) could be allowed, and be equal to 12e3 . What
changes are needed to the number axioms?
24
When we defined number expressions, we included complex numbers such as (–1) 1/2 ,
not because we particularly wanted them, but because it was easier than excluding them. If
we were interested in complex numbers, we would find that the number axioms given in
Subsection 11.4.2 do not allow us to prove many things we might like to prove. For
example, we cannot prove (–1)1/2 × 0 = 0 . How can the axioms be made strong enough
to prove things about complex numbers, but weak enough to leave room for ∞ ?
25
(a)
(b)
Express formally
the absolute value of a real number x .
the sign of a real number x , which is –1 , 0 , or +1 depending on whether x is
negative, zero, or positive.
26
Prove –∞<y<∞ ∧ y 0 ⇒ (x/y=z
27
Show that the number axioms become inconsistent when we add the axiom
–∞<y<∞ ⇒ x/y×y = x
28
(circular numbers) Redesign the axioms for the extended number system to make it
circular, so that +∞ = –∞ . Be careful with the transitivity of < .
=
x=z×y) .
153
10 Exercises
29
Is there any harm in adding the axiom 0/0=5 to Number Theory?
30
(bracket algebra) Here is a new way to write boolean expressions. An expression can be
empty; in other words, nothing is already an expression. If you put a pair of parentheses
around an expression, you get another expression. If you put two expressions next to each
other, you get another expression. For example,
()(())((())())
is an expression. The empty expression is bracket algebra's way of writing
; putting
parentheses around an expression is bracket algebra's way of negating it, and putting
expressions next to each other is bracket algebra's way of conjoining them. So the
example expression is bracket algebra's way of saying
¬ ∧¬¬ ∧¬(¬¬ ∧¬ )
We can also have variables anywhere in a bracket expression. There are three rules of
bracket algebra. If x , y , and z are any bracket expressions, then
((x))
can replace or be replaced by
x
double negation rule
x()y
can replace or be replaced by
()
base rule
xyz
can replace or be replaced by
x′ y z′
context rule
where x′ is x with occurrences of y added or deleted, and similarly z′ is z with
occurrences of y added or deleted. The context rule does not say how many occurrences
of y are added or deleted; it could be any number from none to all of them. To prove,
you just follow the rules until the expression disappears. For example,
((a)b((a)b))
context rule: empty for x , (a)b for y , ((a)b) for z
becomes
((a)b())
base rule: (a)b for x and empty for y
becomes
(())
double negation rule
becomes
Since the last expression is empty, all the expressions are proven.
Rewrite the boolean expression
¬(¬(a∧b)∧¬(¬a∧b)∧¬(a∧¬b)∧¬(¬a∧¬b))
as a bracket expression, and then prove it following the rules of bracket algebra.
As directly as possible, rewrite the boolean expression
(¬a⇒¬b) ∧ (a b) ∨ (a∧c ⇒ b∧c)
as a bracket expression, and then prove it following the rules of bracket algebra.
Can all boolean expressions be rewritten reasonably directly as bracket expressions?
Can x y become y x using the rules of bracket algebra?
Can all theorems of boolean algebra, rewritten reasonably directly as bracket expressions,
be proven using the rules of bracket algebra?
We interpret empty as
, parentheses as negation, and juxtaposition as conjunction. Is
there any other consistent way to interpret the symbols and rules of bracket algebra?
(a)
(b)
(c)
(d)
(e)
(f)
31
(a)
(b)
(c)
(d)
(e)
(f)
(g)
Let • be a binary infix operator (precedence 3) whose operands and result are of some type
T . Let ◊ be a binary infix operator (precedence 7) whose operands are of type T and
whose result is boolean, defined by the axiom
a◊b = a•b=a
Prove if • is idempotent then ◊ is reflexive.
Prove if • is associative then ◊ is transitive.
Prove if • is symmetric then ◊ is antisymmetric.
If T is the booleans and • is ∧ , what is ◊ ?
If T is the booleans and • is ∨ , what is ◊ ?
If T is the natural numbers and ◊ is ≤ , what is • ?
The axiom defines ◊ in terms of • . Invert it, so that • is defined in terms of ◊ .
10 Exercises
32
154
(family theory) Design a theory of personal relationships. Invent person expressions such
as Jack , Jill , father of p , mother of p . Invent boolean expressions that use person
expressions, such as p is male , p is female , p is a parent of q , p is a son of q , p is a
daughter of q , p is a child of q , p is married to q , p=q . Invent axioms such as (p is
male) (p is female) . Formulate and prove an interesting theorem.
End of Basic Theories
10.1 Basic Data Structures
33
(a)
(b)
(c)
(d)
Simplify
(1, 7–3) + 4 – (2, 6, 8)
nat×nat
nat–nat
(nat+1)×(nat+1)
34
Prove ¬ 7: null .
35
We defined bunch null with the axiom null: A . Is there any harm in defining bunch all
with the axiom A: all ?
36
Let A be a bunch of booleans such that A = ¬A . What is A ?
37
Show that some of the axioms of Bunch Theory listed in Section 2.0 are provable from the
other axioms. How many of the axioms can you remove without losing any theorems?
38
(hyperbunch) A hyperbunch is like a bunch except that each element can occur a number of
times other than just zero times (absent) or one time (present). The order of elements
remains insignificant. (A hyperbunch does not have a characteristic predicate, but a
characteristic function with numeric result.) Design notations and axioms for each of the
following kinds of hyperbunch.
multibunch: an element can occur any natural number of times. For example, a multibunch
can consist of one 2, two 7s, three 5s, and zero of everything else. (Note: the equivalent
for sets is called either a multiset or a bag.)
wholebunch: an element can occur any integer number of times.
fuzzybunch: an element can occur any real number of times from 0 to 1 inclusive.
(a)
(b)
(c)
39
A composite number is a natural number with 2 or more (not necessarily distinct) prime
factors. Express the composite numbers as simply as you can.
40
For this question only, let # be a binary infix operator (precedence 3) with natural
operands and an extended natural result. Informally, n#m means “the number of times
that n is a factor of m ”. It is defined by the following two axioms.
m: n×nat ∨ n#m = 0
n 0 ⇒ n#(m×n) = n#m + 1
Make a 3×3 chart of the values of (0,..3)#(0,..3) .
Show that the axioms become inconsistent if the antecedent of the second axiom is
removed.
How should we change the axioms to allow # to have extended natural operands?
(a)
(b)
(c)
155
41
10 Exercises
(a)
(b)
(c)
(d)
For naturals n and m , we can express the statement “ n is a factor of m ” formally as
follows:
m: n×nat
What are the factors of 0 ?
What is 0 a factor of?
What are the factors of 1 ?
What is 1 a factor of?
42
(a)
(b)
(c)
(d)
Let B = 1, 3, 5 . What is
¢(B + B)
¢(B × 2)
¢(B × B)
¢(B2)
43
The compound axiom says
x: A, B = x: A ∨ x: B
There are sixteen binary boolean operators that could sit where ∨ sits in this axiom if we
just replace bunch union (,) by a corresponding bunch operator. Which of the sixteen
boolean binary operators correspond to useful bunch operators?
44
(a)
(von Neumann numbers)
Is there any harm in adding the axioms
0 = {null}
the empty set
n+1 = {n, ~n}
for each natural n
What correspondence is induced by these axioms between the arithmetic operations and the
set operations?
Is there any harm in adding the axioms
0 = {null}
the empty set
i+1 = {i, ~i}
for each integer i
(b)
(c)
45
(Cantor's heaven) Show that $ 2S > $S is neither a theorem nor an antitheorem.
46
The strings defined in Section 2.2 are “natural strings” because their lengths and indexes
are natural numbers. Invent suitable axioms for
“extended strings”, including both “natural strings” and “infinite strings”.
“integer strings”, including both “natural strings” and “negative strings”.
(a)
(b)
47
Prove the trichotomy for strings of numbers. For strings S and T , prove that exactly one
of S<T , S=T , S>T is a theorem.
48
In Section 2.3 there is a self-describing expression. Make it into a self-printing program.
To do so, you need to know that c!e outputs the value of expression e on channel c .
49
(a)
(b)
(c)
(d)
(e)
Simplify (no proof)
null, nil
null; nil
*nil
[null]
[*null]
10 Exercises
156
50
What is the difference between [0, 1, 2] and [0; 1; 2] ?
51
(prefix order) Give axioms to define the prefix partial order on strings. String S comes
before string T in this order if and only if S is an initial segment of T .
52
(a)
(b)
Simplify, assuming i: 0,..#L
i→Li | L
L [0;..i] + [x] + L [i+1;..#L]
53
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
(k)
(l)
Simplify (no proof)
0→1 | 1→2 | 2→3 | 3→4 | 4→5 | [0;..5]
(4→2 | [–3;..3]) 3
((3;2)→[10;..15] | 3→[5;..10] | [0;..5]) 3
([0;..5] [3; 4]) 1
(2;2)→`j | ["abc"; "de"; "fghi"]
#[nat]
#[*3]
[3; 4]: [3*4*int]
[3; 4]: [3; int]
[3, 4; 5]: [2*int]
[(3, 4); 5]: [2*int]
[3; (4, 5); 6; (7, 8, 9)] ‘ [3; 4; (5, 6); (7, 8)]
54
Let i and j be indexes of list L . Express i→Lj | j→Li | L without using | .
End of Basic Data Structures
10.2 Function Theory
55
(a)
(b)
(c)
In each of the following, replace p by
λx: int· λy: int· λz: int· x≥0 ∧ x2≤y ∧ ∀z: int· z2≤y ⇒ z≤x
and simplify, assuming x, y, z, u, w: int .
p (x+y) (2×u + w) z
p (x+y) (2×u + w)
p (x+z) (y+y) (2+z)
56
Some mathematicians like to use a notation like ∃!x: D· Px to mean “there is a unique x
in D such that Px holds”. Define ∃! formally.
57
(a)
(b)
(c)
Write each of the following without using § .
¢(§x: D· Px) = 0
¢(§x: D· Px) = 1
¢(§x: D· Px) = 2
58
(cat) Define function cat so that it applies to a list of lists and produces their catenation.
For example,
cat [[0; 1; 2]; [nil]; [[3]]; [4; 5]] = [0; 1; 2; [3]; 4; 5]
59
Express formally that L is a sublist (not necessarily consecutive items) of list M . For
example, [0; 2; 1] is a sublist of [0; 1; 2; 2; 1; 0] , but [0; 2; 1] is not a sublist of
[0; 1; 2; 3] .
157
10 Exercises
60
(a)
(b)
(c)
Express formally that L is a longest sorted sublist of M where
the sublist must be consecutive items (a segment).
the sublist must be consecutive (a segment) and nonempty.
the sublist contains items in their order of appearance in M , but not necessarily
consecutively (not necessarily a segment).
61
Express formally that natural n is the length of a longest palindromic segment in list L .
A palindrome is a list that equals its reverse.
62
(a)
(b)
(c)
Using the syntax x can fool y at time t formalize the statements
You can fool some of the people all of the time.
You can fool all of the people some of the time.
You can't fool all of the people all of the time.
for each of the following interpretations of the word “You”:
Someone
Anyone
The person I am talking to
(i)
(ii)
(iii)
63
(i)
(ii)
(iii)
(iv)
(v)
(vi)
(vii)
(viii)
(ix)
(x)
(a)
(b)
(whodunit) Here are ten statements.
Some criminal robbed the Russell mansion.
Whoever robbed the Russell mansion either had an accomplice among the servants or had
to break in.
To break in one would have to either smash the door or pick the lock.
Only an expert locksmith could pick the lock.
Anyone smashing the door would have been heard.
Nobody was heard.
No one could rob the Russell mansion without fooling the guard.
To fool the guard one must be a convincing actor.
No criminal could be both an expert locksmith and a convincing actor.
Some criminal had an accomplice among the servants.
Choosing good abbreviations, translate each of these statements into formal logic.
Taking the first nine statements as axioms, prove the tenth.
64
(arity) The arity of a function is the number of variables (parameters) it introduces, and the
number of arguments it can be applied to. Write axioms to define αf (arity of f ).
65
There are some people, some keys, and some doors. Let p holds k mean that person p
holds key k . Let k unlocks d mean that key k unlocks door d . Let p opens d mean
that person p can open door d . Formalize
Anyone can open any door if they have the appropriate key.
At least one door can be opened without a key (by anyone).
The locksmith can open any door even without a key.
(a)
(b)
(c)
66
Prove that if variables i and j do not appear in predicates P and Q , then
(∀i· Pi) ⇒ (∃i· Qi) = (∃i, j· Pi ⇒ Qj)
67
There are four boolean binary associative symmetric operators with an identity. We used
two of them to define quantifiers. What happened to the other two?
68
Which binary operator can be used to define a quantifier to give the range of a function?
10 Exercises
158
69
We have defined several quantifiers by starting with an associative symmetric operator with
an identity. Bunch union is also such an operator. Does it yield a quantifier?
70
Exercise 13 talks about drinking and driving, but not about time. It's not all right to drink
first and then drive soon after, but it is all right to drive first and then drink soon after. It is
also all right to drink first and then drive 6 hours after. Let drink and drive be predicates
of time, and formalize the rule that you can't drive for 6 hours after drinking. What does
your rule say about drinking and driving at the same time?
71
(a)
(b)
(c)
(d)
(e)
(f)
Formalize each of the following statements as a boolean expression.
Everybody loves somebody sometime.
Every 10 minutes someone in New York City gets mugged.
Every 10 minutes someone keeps trying to reach you.
Whenever the altititude is below 1000 feet, the landing gear must be down.
I'll see you on Tuesday, if not before.
No news is good news.
72
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
Express formally that
natural n is the largest proper (neither 1 nor m ) factor of natural m .
g is the greatest common divisor of naturals a and b .
m is the lowest common multiple of naturals a and b .
p is a prime number.
n and m are relatively prime numbers.
there is at least one and at most a finite number of naturals satisfying predicate p .
there is no smallest integer.
between every two rational numbers there is another rational number.
list L is a longest segment of list M that does not contain item x .
the segment of list L from (including) index i to (excluding) index j is a segment whose
sum is smallest.
a and b are items of lists A and B (respectively) whose absolute difference is least.
p is the length of a longest plateau (segment of equal items) in a nonempty sorted list L .
all items that occur in list L occur in a segment of length 10 .
all items of list L are different (no two items are equal).
at most one item in list L occurs more than once.
the maximum item in list L occurs m times.
list L is a permutation of list M .
(k)
(l)
(m)
(n)
(o)
(p)
(q)
73
(bitonic list) A list is bitonic if it is monotonic up to some index, and antimonotonic after
that. For example, [1; 3; 4; 5; 5; 6; 4; 4; 3] is bitonic. Express formally that L is bitonic.
74
Formalize and disprove the statement “There is a natural number that is not equal to any
natural number.”.
75
(friends) Formalize and prove the statement “The people you know are those known by all
who know all whom you know.”.
76
(swapping partners) There is a finite bunch of couples. Each couple consists of a man and
a woman. The oldest man and the oldest woman have the same age. If any two couples
swap partners, forming two new couples, the younger partners of the two new couples
have the same age. Prove that in each couple, the partners have the same age.
159
10 Exercises
77
Express ∀ and ∃ in terms of ¢ and § .
78
(a)
(b)
(c)
(d)
Simplify
Σ (0,..n) → m
Π (0,..n) → m
∀ (0,..n) → b
∃ (0,..n) → b
79
Are the boolean expressions
nil→x = x
(S;T) → x = S→T→x
consistent with the theory in Chapters 2 and 3?
theorems according to the theory in Chapters 2 and 3?
(a)
(b)
80
(unicorns) The following statements are made.
All unicorns are white.
All unicorns are black.
No unicorn is both white and black.
Are these statements consistent? What, if anything, can we conclude about unicorns?
81
(Russell's barber) Bertrand Russell stated: “In a small town there is a barber who shaves
all and only the people in the town who do not shave themselves.”. Then Russell asked:
“Does the barber shave himself?”. If we say yes, then we can conclude from the statement
that he does not, and if we say no, then we can conclude from the statement that he does.
Formalize this paradox, and thus explain it.
82
(a)
(b)
(c)
(Russell's paradox) Define rus = λf: null→bool· ¬ f f .
Can we prove rus rus = ¬ rus rus ?
Is this an inconsistency?
Can we add the axiom ¬ f: ∆f ? Would it help?
83
Prove that the square of an odd natural number is odd, and the square of an even natural
number is even.
84
(Gödel/Turing incompleteness) Prove that we cannot consistently and completely define an
interpreter. An interpreter is a predicate
that applies to texts; when applied to a text
representing a boolean expression, its result is equal to the represented expression. For
example,
"∀s: [*char]· #s ≥ 0" = ∀s: [*char]· #s ≥ 0
85
Let f and g be functions from nat to nat . For what f do we have the theorem g f = g ?
For what f do we have the theorem f g = g ?
86
What is the difference between #[n* ] and ¢§[n* ] ?
87
(a)
(b)
Without using the Bounding Laws, prove
∀i· Li≤m = (MAX L) ≤ m
∃i· Li≤m = (MIN L) ≤ m
88
(pigeon-hole) Prove (ΣL) > n×#L ⇒ ∃i: ∆L· Li>n .
10 Exercises
160
89
(a)
(b)
If f: A→B and p: B→bool , prove
∃b: fA· pb = ∃a: A· pfa
∀b: fA· pb = ∀a: A· pfa
90
This question explores a simpler, more elegant function theory than the one presented in
Chapter 3. We separate the notion of local variable introduction from the notion of domain,
and we generalize the latter to become local axiom introduction. Variable introduction has
the form λv· b where v is a variable and b is any expression (the body; no domain).
There is a Renaming Axiom
λv· b = λw· (substitute w for v in b )
and an Application Axiom
(λv· b) x = (substitute x for v in b )
Let a be boolean, and let b be any expression. Then a b is an expression of the same
type as b . The
operator has precedence level 12 and is right-associating. Its axioms
include:
b = b
a b c = a∧b c
The expression a b is a “one-tailed if-expression”, or “asserted expression”; it
introduces a as a local axiom within b . A function is a variable introduction whose body
is an asserted expression in which the assertion has the form v: D . In this case, we allow
an abbreviation: for example, the function λ n · n : nat
n+1 can be abbreviated
λn: nat· n+1 . Applying this function to 3 , we find
(λn· n: nat n+1) 3
= 3: nat 3+1
=
4
= 4
Applying it to –3 we find
(λn· n: nat n+1) (–3)
= –3: nat –3+1
=
–2
and then we are stuck; no further axiom applies. In the example, we have used variable
introduction and axiom introduction together to give us back the kind of function we had;
but in general, they are independently useful.
Show how function-valued variables can be introduced in this new theory.
What expressions in the old theory have no equivalent in the new? How closely can they
be approximated?
What expressions in the new theory have no equivalent in the old? How closely can they
be approximated?
(a)
(b)
(c)
91
Is there any harm in defining relation R with the following axioms?
∀x· ∃y· Rxy
totality
∀x· ¬ Rxx
irreflexivity
∀x, y, z· Rxy ∧ Ryz ⇒ Rxz
transitivity
∃u· ∀x· x=u ∨ Rxu
unity
92
Let n be a natural number, and let R be a relation on 0,..n . In other words,
R: (0,..n) → (0,..n) → bool
We say that from x we can reach x in zero steps. If Rxy we say that from x we can
reach y in one step. If Rxy and Ryz we say that from x we can reach z in two steps.
And so on. Express formally that from x we can reach y in some number of steps.
161
93
10 Exercises
Relation R is transitive if ∀x, y, z· Rxy ∧ Ryz ⇒ Rxz . Express formally that relation R
is the transitive closure of relation Q ( R is the strongest transitive relation that is implied
by Q ).
End of Function Theory
10.3 Program Theory
94
Prove specification S is satisfiable for prestate σ if and only if S.
“true” boolean).
95
Let x be an integer state variable.
implementable?
x ≥ 0 ⇒ x′ 2 = x
x′ ≥ 0 ⇒ x = 0
¬(x ≥ 0 ∧ x′ = 0)
¬(x ≥ 0 ∨ x′ = 0)
(a)
(b)
(c)
(d)
(note:
is the
Which of the following specifications are
96
A specification is transitive if, for all states a , b , and c , if it allows the state to change
from a to b , and it allows the state to change from b to c , then it allows the state to
change from a to c . Prove S is transitive if and only if S is refined by S.S .
97√
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
(k)
Simplify each of the following (in integer variables x and y ).
x:= y+1. y′>x′
x:= x+1. y′>x ∧ x′>x
x:= y+1. y′=2x
x:= 1. x≥1 ⇒ ∃x· y′=2x
x:= y. x≥1 ⇒ ∃y· y′=x × y
x:= 1. ok
x:= 1. y:= 2
x:= 1. P where P = y:= 2
x:= 1. y:= 2. x:= x+y
x:= 1. if y>x then x:= x+1 else x:= y
x:= 1. x′>x. x′=x+1
98
(a)
(b)
Prove
99
(a)
(b)
(c)
Prove or disprove
R. if b then P else Q = if b then (R. P) else (R. Q)
if b then P⇒Q else R⇒S = (if b then P else R) ⇒ (if b then Q else S)
if b then (P. Q) else (R. S) = if b then P else R. if b then Q else S
100
(a)
(b)
Prove
P and Q are each refined by R if and only if their conjunction is refined by R .
P⇒Q is refined by R if and only if Q is refined by P∧R .
101
(roll up) Suppose S
always roll up a loop?
x:= x = ok
x:= e. x:= f x
=
⇐
x:= f e
A. A. S. Z. Z . Can we conclude S
⇐ A. S. Z ?
Can we
10 Exercises
102
What is wrong with the following proof:
(R ⇐ R. S)
=
(R ⇐
. S)
=
(R ⇐
)
=
162
use context rule
is base for .
base law for ⇐
103
(a)
(b)
(c)
For which kinds of specifications P and Q is the following a theorem:
¬(P. ¬Q) ⇐ P. Q
P. Q ⇐ ¬(P. ¬Q)
P. Q = ¬(P. ¬Q)
104
Write a formal specification of the following problem: “Change the value of list variable L
so that each item is repeated. For example, if L is [6; 3; 5; 5; 7] then it should be
changed to [6; 6; 3; 3; 5; 5; 5; 5; 7; 7] .”.
105
Let P and Q be specifications. Let C be a precondition and let C′ be the corresponding
postcondition. Prove the condition law
P. Q ⇐ P∧C′. C⇒Q
106
Let P and Q be specifications. Let C be a precondition and let C′ be the corresponding
postcondition. Which three of the following condition laws can be turned around,
switching the problem and the solution?
C ∧ (P. Q) ⇐ C∧P. Q
C ⇒ (P.Q) ⇐ C⇒P. Q
(P.Q) ∧ C′ ⇐ P. Q∧C′
(P.Q) ⇐ C′ ⇐ P. Q⇐C′
P. C∧Q ⇐ P∧C′. Q
P. Q ⇐ P∧C′. C⇒Q
107
Let S be a specification. Let C be a precondition and let C′ be the corresponding
postcondition. How does the exact precondition for C′ to be refined by S differ from
(S. C) ? Hint: consider prestates in which S is unsatisfiable, then deterministic, then
nondeterministic.
108
We have Refinement by Steps, Refinement by Parts, and Refinement by Cases. In this
question we propose Refinement by Alternatives:
If A ⇐ if b then C else D and E ⇐ if b then F else G are theorems,
then A∨E ⇐ if b then C∨F else D∨G is a theorem.
If A ⇐ B.C and D ⇐ E.F are theorems, then A∨D ⇐ B∨E. C∨F is a theorem.
If A ⇐ B and C ⇐ D are theorems, then A∨C ⇐ B∨D is a theorem.
Discuss the merits and demerits of this proposed law.
109
Let x and y be real variables. Prove that if y=x2 is true before
x:= x+1. y:= y + 2×x – 1
then it is still true after.
110√ In one integer variable x ,
(a)
find the exact precondition A for x′>5 to be refined by x:= x+1 .
(b)
find the exact postcondition for A to be refined by x:= x+1 , where A is your answer
from part (a).
163
10 Exercises
111
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
(k)
(l)
(m)
(n)
(o)
(p)
Let all variables be natural except L is a list of naturals. What is the exact precondition for
x′+y′ > 8 to be refined by x:= 1
x′=1 to be refined by x:= 1
x′=2 to be refined by x:= 1
x′=y to be refined by y:= 1
x′ ≥ y′ to be refined by x:= y+z
y′+z′ ≥ 0 to be refined by x:= y+z
x′≤1 ∨ x′≥5 to be refined by x:= x+1
x′<y′ ∧ ∃x· Lx<y′ to be refined by x:= 1
∃y· Ly<x′ to be refined by x:= y+1
L′ 3 = 4 to be refined by L:= i→4 | L
x′=a to be refined by if a > b then x:= a else ok
x′=y ∧ y′=x to be refined by (z:= x. x:= y. y:= z)
a×x′ 2 + b×x′ + c = 0 to be refined by (x:= a×x + b. x:= –x/a)
f ′ = n′! to be refined by (n:= n+1. f:= f×n) where ! means factorial.
7 ≤ c′ < 28 ∧ odd c′ to be refined by (a:= b–1. b:= a+3. c:= a+b)
s′ = Σ L [0;..i′] to be refined by (s:= s + Li. i:= i+1)
112
For what exact precondition and postcondition does the following assignment move integer
variable x farther from zero?
x:= x+1
x:= abs (x+1)
x:= x2
(a)
(b)
(c)√
113
(a)
(b)
(c)
114
(a)
(b)
115
For what exact precondition and postcondition does the following assignment move integer
variable x farther from zero staying on the same side of zero?
x:= x+1
x:= abs (x+1)
x:= x2
Prove
the Precondition Law: C is a sufficient precondition for P to be refined by S if and only
if C⇒P is refined by S .
the Postcondition Law: C′ is a sufficient postcondition for P to be refined by S if and
only if C′⇒P is refined by S .
(a)
(b)
(weakest prespecification, weakest postspecification) Given specifications P and Q , find
the weakest specification S (in terms of P and Q ) such that P is refined by
S. Q
Q. S
116
(a)
(b)
(c)
Let a , b , and c be integer variables. Simplify
b:= a–b. b:= a–b
a:= a+b. b:= a–b. a:= a–b
c:= a–b–c. b:= a–b–c. a:= a–b–c. c:= a+b+c
117
(a)
(b)
Let x and y be boolean variables. Simplify
x:= x=y. x:= x=y
x:= x y. y:= x y. x:= x y
10 Exercises
164
118
(a)√
(b)
Let x be an integer variable. Prove the refinement
x′=0 ⇐ if x=0 then ok else (x:= x–1. x′=0)
P ⇐ if x=0 then ok else (x:= x–1. t:= t+1. P)
where P = x′=0 ∧ if x≥0 then t′ = t+x else t′=∞
119
(a)
(b)√
Let x be an integer variable. Prove the refinement
x′=1 ⇐ if x=1 then ok else (x:= div x 2. x′=1)
R ⇐ if x=1 then ok else (x:= div x 2. t:= t+1. R)
where R = x′=1 ∧ if x≥1 then t′ ≤ t + log x else t′=∞
120
In natural variables s and n prove
P ⇐ if n=0 then ok else (n:= n–1. s:= s+2n–n. t:= t+1. P)
where P = s′ = s + 2n – n×(n–1)/2 – 1 ∧ n′=0 ∧ t′ = t+n .
121
Is the refinement
P ⇐ if x=0 then ok else (x:= x–1. t:= t+1. P)
a theorem when
P = x<0 ⇒ x′=1 ∧ t′=∞
Is this reasonable? Explain.
122
(factorial) In natural variables n and f prove
f:= n! ⇐ if n=0 then f:= 1 else (n:= n–1. f:= n!. n:= n+1. f:= f×n)
where n! = 1×2×3×...×n .
123
In natural variables n and m prove
P ⇐ n:= n+1.
if n=10 then ok
else (m:= m–1. P)
where P = m:= m+n–9. n:= 10 .
124
Let x and n be natural variables. Find a specification P such that both the following
hold:
x = x′×2n′ ⇐ n:= 0. P
P ⇐ if even x then (x:= x/2. n:= n+1. P) else ok
125
(square) Let s and n be natural variables. Find a specification P such that both the
following hold:
s′ = n2 ⇐ s:= n. P
P ⇐ if n=0 then ok else (n:= n–1. s:= s+n+n. P)
This program squares using only addition, subtraction, and test for zero.
126
Let a and b be positive integers. Let x , u , and v be integer variables. Let
P = u≥0 ∧ v≥0 ∧ x = u×a – v×b ⇒ x′=0
Prove
P ⇐ if x>0 then (x:= x–a. u:= u–1. P)
else if x<0 then (x:= x+b. v:= v–1. P)
else o k
Find an upper bound for the execution time of the program in part (a).
(a)
(b)
165
127
(a)
(b)
10 Exercises
Let i be an integer variable. Add time according to the recursive measure, and then find
the strongest P you can such that
P ⇐ if even i then i:= i/2 else i:= i+1.
if i=1 then ok else P
P ⇐ if even i then i:= i/2 else i:= i–3.
if i=0 then ok else P
128
Find a finite function f of natural variables i and j to serve as an upper bound on the
execution time of the following program, and prove
t′ ≤ t + fij ⇐
if i=0 ∧ j=0 then ok
else if i=0 then (i:= j×j. j:= j–1. t:= t+1. t′ ≤ t + fij)
else (i:= i–1. t:= t+1. t′ ≤ t + fij)
129
Let P mean that the final values of natural variables a and b are the largest exponents of
2 and 3 respectively such that both powers divide evenly into the initial value of positive
integer x .
Define P formally.
Define Q suitably and prove
P ⇐ a:= 0. b:= 0. Q
Q ⇐ if x: 2×nat then (x:= x/2. a:= a+1. Q)
else if x: 3×nat then (x:= x/3. b:= b+1. Q)
else o k
Find an upper bound for the execution time of the program in part (b).
(a)
(b)
(c)
130
Express formally that specification R is satisfied by any number (including 0 ) of
repetitions of behavior satisfying specification S .
131
(Zeno) Here is a loop.
R ⇐ x:= x+1. R
Suppose we charge time 2–x for the recursive call, so that each iteration takes half as long
as the one before. Prove that the execution time is finite.
132
Can we prove the refinement
P ⇐ t:= t+1. P
for P = t′=5 ? Does this mean that execution will terminate at time 5 ? What is wrong?
133
Let n and r be natural variables in the refinement
P ⇐ if n=1 then r:= 0 else (n:= div n 2. P. r:= r+1)
Suppose the operations div and + each take time 1 and all else is free (even the call is
free). Insert appropriate time increments, and find an appropriate P to express the
execution time in terms of
the initial values of the memory variables. Prove the refinement for your choice of P .
the final values of the memory variables. Prove the refinement for your choice of P .
(a)
(b)
134
(a)
(b)
(running total) Given list variable L and any other variables you need, write a program to
convert L into a list of cumulative sums. Formally,
∀n: 0,..#L· L′n = Σ L [0;..n]
∀n: 0,..#L· L′n = Σ L [0;..n+1]
135
(cube) Write a program that cubes using only addition, subtraction, and test for zero.
10 Exercises
166
136
(cube test) Write a program to determine if a given natural number is a cube without using
exponentiation.
137
( mod 2 ) Let n be a natural variable. The problem to reduce n modulo 2 can be solved
as follows:
n′ = mod n 2 ⇐ if n<2 then ok else (n:= n–2. n′ = mod n 2)
Using the recursive time measure, find and prove an upper time bound. Make it as small as
you can.
138
(fast mod 2 ) Let n and p be natural variables. The problem to reduce n modulo 2 can
be solved as follows:
n′ = mod n 2 ⇐ if n<2 then ok else (even n′ = even n. n′ = mod n 2)
even n′ = even n ⇐ p:= 2. even p ⇒ even p′ ∧ even n′ = even n
even p ⇒ even p′ ∧ even n′ = even n ⇐
n:= n–p. p:= p+p.
if n<p then ok else even p ⇒ even p′ ∧ even n′ = even n
Prove these refinements.
Using the recursive time measure, find and prove a sublinear upper time bound.
(a)
(b)
139
(a)
(b)
(c)
Given a specification P and a prestate σ with t as time variable, we might define “the
exact precondition for termination” as follows:
∃n: nat· ∀σ′· t′ ≤ t+n ⇐ P
Letting x be an integer variable, find the exact precondition for termination of the
following, and comment on whether it is reasonable.
x ≥ 0 ⇒ t′ ≤ t+x
∃n: nat· t′ ≤ t+n
∃f: int→nat· t′ ≤ t + fx
140√ (maximum item) Write a program to find the maximum item in a list.
141
(list comparison) Using item comparison but not list comparison, write a program to
determine whether one list comes before another in the list order.
142√ (list summation) Write a program to find the sum of a list of numbers.
143
(alternating sum) Write a program to find the alternating sum L0 – L1 + L2 – L3 + L4 –
... of a list L of numbers.
144
(combinations) Write a program to find the number of ways to partition a+b things into a
things and b things. Include recursive time.
145
(earliest meeting time) Write a program to find the earliest meeting time acceptable to three
people. Each person is willing to state their possible meeting times by means of a function
that tells, for each time t , the earliest time at or after t that they are available for a meeting.
(Do not confuse this t with the execution time variable. You may ignore execution time
for this problem.)
146
(polynomial) You are given n: nat , c: [n*rat] , x: rat and variable y: rat . c is a list of
coefficients of a polynomial (“of degree n–1”) to be evaluated at x . Write a program for
y′ = Σi: 0,..n· ci× x i
167
10 Exercises
147
(multiplication table) Given n: nat and variable M: [*[*nat]] , write a program to assign
to M a multiplication table of size n without using multiplication. For example, if
n = 4 , then
M′ = [ [0];
[0; 1];
[0; 2; 4];
[0; 3; 6; 9] ]
148
(Pascal's triangle) Given n: nat and variable P: [*[*nat]] , write a program to assign to P
a Pascal's triangle of size n . For example, if n = 4 , then
P′ = [ [1];
[1; 1];
[1; 2; 1];
[1; 3; 3; 1] ]
The left side and diagonal are all 1s; each interior item is the sum of the item above it and
the item diagonally above and left.
149√ (binary exponentiation) Given natural variables x and y , write a program for y′ = 2 x
without using exponentiation.
150
Write a program to find the smallest power of 2 that is bigger than or equal to a given
positive integer without using exponentiation.
151√ (fast exponentiation) Given rational variables x and z and natural variable y , write a
program for z′ = xy that runs fast without using exponentiation.
152
(sort test) Write a program to assign a boolean variable to indicate whether a given list is
sorted.
153√ (linear search) Write a program to find the first occurrence of a given item in a given list.
The execution time must be linear in the length of the list.
154√ (binary search) Write a program to find a given item in a given nonempty sorted list. The
execution time must be logarithmic in the length of the list. The strategy is to identify
which half of the list contains the item if it occurs at all, then which quarter, then which
eighth, and so on.
155
(a)
(b)
(c)
(d)
156
(binary search with test for equality) The problem is binary search (Exercise 154), but each
iteration tests to see if the item in the middle of the remaining segment is the item we seek.
Write the program, with specifications and proofs.
Find the execution time according to the recursive measure.
Find the execution time according to a measure that charges time 1 for each test.
Compare the execution time to binary search without the test for equality each iteration.
(ternary search) The problem is the same as binary search (Exercise 154). The strategy
this time is to identify which third of the list contains the item if it occurs at all, then which
ninth, then which twenty-seventh, and so on.
157√ (two-dimensional search) Write a program to find a given item in a given 2-dimensional
array. The execution time must be linear in the product of the dimensions.
10 Exercises
168
158
(sorted two-dimensional search) Write a program to find a given item in a given 2dimensional array in which each row is sorted and each column is sorted. The execution
time must be linear in the sum of the dimensions.
159
(sorted two-dimensional count) Write a program to count the number of occurrences of a
given item in a given 2-dimensional array in which each row is sorted and each column is
sorted. The execution time must be linear in the sum of the dimensions.
160
(pattern search) Let subject and pattern be two texts. Write a program to do the
following. If pattern occurs somewhere within subject , natural variable h is assigned to
indicate the beginning of its first occurrence
using any list operators given in Section 2.3.
using list indexing, but no other list operators.
(a)
(b)
161
(fixed point) Let L be a nonempty sorted list of n different integers. Write a program to
find a fixed-point of L , that is an index i such that Li = i , or to report that no such index
exists. Execution time should be at most log n where n is the length of the list.
162
(all present) Given a natural number and a list, write a program to determine if every
natural number up to the given number is an item in the list.
163
(missing number) You are given a list of length n whose items are the numbers 0,..n+1
in some order, but with one number missing. Write a program to find the missing number.
164
(text length) You are given a text (list of characters) that begins with zero or more
“ordinary” characters, and then ends with zero or more “padding” characters. A padding
character is not an ordinary character. Write a program to find the number of ordinary
characters in the text. Execution time should be logarithmic in the text length.
165
(ordered pair search) Given a list of at least two items whose first item is less than or equal
to its last item, write a program to find an adjacent pair of items such that the first of the
pair is less than or equal to the second of the pair. Execution time should be logarithmic in
the length of the list.
166
(convex equal pair) A list of numbers is convex if its length is at least 2 , and every item
(except the first and last) is less than or equal to the average of its two neighbors. Given a
convex list, write a program to determine if it has a pair of consecutive equal items.
Execution should be logarithmic in the length of the list.
167
Define a partial order « on pairs of integers as follows:
[a; b] « [c; d] = a<c ∧ b<d
Given n: nat+1 and L: [n*[int; int]] write a program to find the index of a minimal item in
L . That is, find j: 0,..#L such that ¬∃i· Li « Lj . The execution time should be at most
n × log n .
168
( n sort) Given a list L such that L (0,..#L) = 0,..#L , write a program to sort L in
linear time and constant space. The only change permitted to L is to swap two items.
169√ ( n2 sort) Write a program to sort a list. Execution time should be at most n2 where n is
the length of the list.
169
10 Exercises
170
( n × log n sort) Write a program to sort a list. Execution time should be at most n × log n
where n is the length of the list.
171
(reverse) Write a program to reverse the order of the items of a list.
172
(next sorted list) Given a sorted list of naturals, write a program to find the next (in list
order) sorted list having the same sum.
173
(next combination) You are given a sorted list of m different numbers, all in the range
0,..n . Write a program to find the lexicographically next sorted list of m different
numbers, all in the range 0,..n .
174
(next permutation) You are given a list of the numbers 0,..n in some order. Write a
program to find the lexicographically next list of the numbers 0,..n .
175
(permutation inverse) You are given a list variable P of different items in 0,..#P . Write
a program for P P′ = [0;..#P] .
176
(idempotent permutation) You are given a list variable L of items in 0,..#L (not
necessarily all different). Write a program to permute the list so that finally L′ L′ = L′ .
177
(local minimum) You are given a list L of at least 3 numbers such that L0 ≥ L1 and
L(#L–2) ≤ L(#L–1) . A local minimum is an interior index i: 1,..#L–1 such that
L(i–1) ≥ Li ≤ L(i+1)
Write a program to find a local minimum of L .
178
(natural division) The natural quotient of natural n and positive integer p is the natural
number q satisfying
q ≤ n/p < q+1
Write a program to find the natural quotient of n and p in log n time without using any
functions ( div , mod , floor , ceil , ... ).
179
(remainder) Write a program to find the remainder after natural division (Exercise 178),
using only comparison, addition, and subtraction (not multiplication or division or mod ).
180
(natural binary logarithm) The natural binary logarithm of a positive integer p is the
natural number b satisfying
2b ≤ p < 2b+1
Write a program to find the natural binary logarithm of a given positive integer p in log p
time.
181
(natural square root) The natural square root of a natural number n is the natural number
s satisfying
s2 ≤ n < (s+1)2
Write a program to find the natural square root of a given natural number n in log n time.
Write a program to find the natural square root of a given natural number n in log n time
using only addition, subtraction, doubling, halving, and comparisons (no multiplication or
division).
(a)
(b)
10 Exercises
170
182
(factor count) Write a program to find the number of factors (not necessarily prime) of a
given natural number.
183
(Fermat's last program) Given natural c , write a program to find the number of unordered
pairs of naturals a and b such that a 2 + b 2 = c 2 in time proportional to c . (An
unordered pair is really a bunch of size 1 or 2 . If we have counted the pair a and b ,
we don't want to count the pair b and a .) Your program may use addition, subtraction,
multiplication, division, and comparisons, but not exponentiation or square root.
184
(flatten) Write a program to flatten a list. The result is a new list just like the old one but
without the internal structure. For example,
L = [ [3; 5]; 2; [5; [7]; [nil] ] ]
L′ = [3; 5; 2; 5; 7]
Your program may employ a test Li: int to see if an item is an integer or a list.
185
(diagonal) Some points are arranged around the perimeter of a circle. The distance from
each point to the next point going clockwise around the perimeter is given by a list. Write a
program to find two points that are farthest apart.
186
(minimum sum segment) Given a list of integers, possibly including negatives, write a
program to find
the minimum sum of any segment (sublist of consecutive items).
the segment (sublist of consecutive items) whose sum is minimum.
(a)√
(b)
187
(a)
(b)
188
(a)
(b)
189
(a)
(b)
(maximum product segment) Given a list of integers, possibly including negatives, write a
program to find
the maximum product of any segment (sublist of consecutive items).
the segment (sublist of consecutive items) whose product is maximum.
(segment sum count)
Write a program to find, in a given list of naturals, the number of segments whose sum is a
given natural.
Write a program to find, in a given list of positive naturals, the number of segments whose
sum is a given natural.
(longest plateau) You are given a nonempty sorted list of numbers. A plateau is a segment
(sublist of consecutive items) of equal items. Write a program to find
the length of a longest plateau.
the number of longest plateaus.
190
(longest smooth segment) In a list of integers, a smooth segment is a sublist of consecutive
items in which no two adjacent items differ by more than 1 . Write a program to find a
longest smooth segment.
191
(longest balanced segment) Given a list of booleans, write a program to find a longest
segment (sublist of consecutive items) having an equal number of
and
items.
192
(longest palindrome) A palindrome is a list that equals its reverse. Write a program to find
a longest palindromic segment in a given list.
171
10 Exercises
193
(greatest subsequence) Given a list, write a program to find the sublist that is largest
according to list order. (A sublist contains items drawn from the list, in the same order of
appearance, but not necessarily consecutive items.)
194
(a)
Given a list whose items are all 0 , 1 , or 2 , write a program
to find the length of a shortest segment (consecutive items) that contains all three numbers
in any order.
to count the number of sublists (not necessarily consecutive items) that are 0 then 1 then
2 in that order.
(b)
195
Let L and M be sorted lists of numbers. Write a program to find the number of pairs of
indexes i: 0,..#L and j: 0,..#M such that Li ≤ Mj .
196
(heads and tails) Let L be a list of positive integers. Write a program to find the number
of pairs of indexes i and j such that
Σ L [0;..i] = Σ L [j;..#L]
197
(pivot) You are given a nonempty list of positive numbers. Write a program to find the
balance point, or pivot. Each item contributes its value (weight) times its distance from the
pivot to its side of the balance. Item i is considered to be located at point i + 1/2 , and the
pivot point may likewise be noninteger.
198
(inversion count) Given a list, write a program to find how many pairs of items (not
necessarily consecutive items) are out of order, with the larger item before the smaller item.
199
(minimum difference) Given two nonempty sorted lists of numbers, write a program to
find a pair of items, one from each list, whose absolute difference is smallest.
200
(earliest quitter) In a nonempty list find the first item that is not repeated later. In list
[13; 14; 15; 14; 15; 13] the earliest quitter is 14 because the other items 13 and 15 both
occur after the last occurrence of 14 .
201
(interval union) A collection of intervals along a real number line is given by the list of left
ends L and the corresponding list of right ends R . List L is sorted. The intervals might
sometimes overlap, and sometimes leave gaps. Write a program to find the total length of
the number line that is covered by these intervals.
202
(bit sum) Write a program to find the number of ones in the binary representation of a
given natural number.
203
(digit sum) Write a program to find the sum of the digits in the decimal representation of a
given natural number.
204
(parity check) Write a program to find whether the number of ones in the binary
representation of a given natural number is even or odd.
205
(approximate search) Given a nonempty sorted list of numbers and a number, write a
program to determine the index of an item in the list that is closest in value to the given
number.
10 Exercises
172
206
Given two natural numbers s and p , write a program to find four natural numbers a ,
b , c , and d whose sum is s and product p , in time s2 , if such numbers exist.
207
Given three natural numbers n , s , and p , write a program to find a list of length n of
natural numbers whose sum is s and product p , if such a list exists.
208
(transitive closure) A relation R: (0,..n)→(0,..n)→bool can be represented by a square
boolean array of size n . Given a relation in the form of a square boolean array, write a
program to find
its transitive closure (the strongest transitive relation that is implied by the given relation).
its reflexive transitive closure (the strongest reflexive and transitive relation that is implied
by the given relation).
(a)
(b)
209
(reachability) You are given a finite bunch of places; and a successor function S on
places that tells, for each place, those places that are directly reachable from it; and a
special place named h (for home). Write a program to find all places that are reachable
(reflexively, directly, or indirectly) from h .
210
(shortest path) You are given a square extended rational array in which item i j represents
the direct distance from place i to place j . If it is not possible to go directly from i to j ,
then item i j is ∞ . Write a program to find the square extended rational array in which
item i j represents the shortest, possibly indirect, distance from place i to place j .
211
(McCarthy's 91 problem) Let i be an integer variable. Let
M = if i>100 then i:= i–10 else i:= 91
Prove M ⇐ if i>100 then i:= i–10 else (i:= i+11. M. M) .
Find the execution time of M as refined in part (a).
(a)
(b)
212
(a)√
(b)√
(c)
(d)√
(e)√
(f)
(Towers of Hanoi) There are 3 towers and n disks. The disks are graduated in size;
disk 0 is the smallest and disk n–1 is the largest. Initially tower A holds all n disks,
with the largest disk on the bottom, proceding upwards in order of size to the smallest disk
on top. The task is to move all the disks from tower A to tower B, but you can move only
one disk at a time, and you must never put a larger disk on top of a smaller one. In the
process, you can make use of tower C as intermediate storage.
Using the command MoveDisk from to to cause a robot arm to move the top disk from
tower from to tower to , write a program to move all the disks from tower A to tower B.
Find the execution time, counting MoveDisk as time 1 , and all else free.
Suppose that the posts where the disks are placed are arranged in an equilateral triangle, so
that the distance the arm moves each time is constant (one side of the triangle to get into
position plus one side to move the disk), and not dependent on the disk being moved.
Suppose the time to move a disk varies with the weight of the disk being moved, which
varies with its area, which varies with the square of its radius, which varies with the disk
number. For even more realism, suppose there is an uncertainty of ε in the time to move
each disk. Find the execution time.
Find the maximum memory space required by the program, counting a recursive call as 1
location (for the return address) and all else free.
Find the average memory space required by the program, counting a recursive call as 1
location (for the return address) and all else free.
Find a simple upper bound on the average memory space required by the program,
counting a recursive call as 1 location (for the return address) and all else free.
173
213
(a)
(b)
(c)
214
(a)
(b)
(c)
215
10 Exercises
(Ackermann) Function ack of two natural variables is defined as follows.
ack 0 0 = 2
ack 1 0 = 0
ack (m+2) 0 = 1
ack 0 (n+1) = ack 0 n + 1
ack (m+1) (n+1) = ack m (ack (m+1) n)
Suppose that functions and function application are not implemented expressions; in that
case n:= ack m n is not a program. Refine n:= ack m n to obtain a program.
Find a time bound. Hint: you may use function ack in your time bound.
Find a space bound.
(alternate Ackermann) For each of the following functions f , refine n:= f m n , find a
time bound (possibly involving f ), and find a space bound.
f 0 n = n+2
f10 = 0
f (m+2) 0 = 1
f (m+1) (n+1) = f m (f (m+1) n)
f 0 n = n×2
f (m+1) 0 = 1
f (m+1) (n+1) = f m (f (m+1) n)
f 0 n = n+1
f10 = 2
f20 = 0
f (m+3) 0 = 1
f (m+1) (n+1) = f m (f (m+1) n)
Let n be a natural variable. Add time according to the recursive measure, and find a finite
upper bound on the execution time of
P ⇐ if n ≥ 2 then (n:= n–2. P. n:= n+1. P. n:= n+1) else ok
216√ (roller-coaster) Let n be a natural variable. It is easy to prove
n′=1 ⇐ if n=1 then ok
else if even n then (n:= n/2. n′=1)
else (n:= 3×n + 1. n′=1)
The problem is to find the execution time. Warning: this problem has never been solved.
217√ (Fibonacci) The Fibonacci numbers fn are defined as follows.
f0=0
f1=1
f (n+2) = f n + f (n+1)
Write a program to find fn in time log n . Hint: see Exercise 301.
218
(Fibolucci) Let a and b be integers. Then the Fibolucci numbers for a and b are
f0=0
f1=1
f (n+2) = a × f n + b × f (n+1)
(The Fibonacci numbers are Fibolucci numbers for 1 and 1 .) Given natural k , without
using any list variables, write a program to compute
Σn: 0,..k· fn × f(k–n)
10 Exercises
174
219
(item count) Write a program to find the number of occurrences of a given item in a given
list.
220
(duplicate count) Write a program to find how many items are duplicates (repeats) of
earlier items
in a given sorted list.
in a given list.
(a)
(b)
221
(z-free subtext) Given a text, write a program to find the longest subtext that does not
contain the letter `z .
222
(merge) Given two sorted lists, write a program to merge them into one sorted list.
223
(arithmetic) Let us represent a natural number as a list of naturals, each in the range 0,..b
for some natural base b>1 , in reverse order. For example, if b=10 , then [9; 2; 7]
represents 729 . Write programs for each of the following.
Find the list representing a given natural in a given base.
Given a base and two lists representing natural numbers, find the list representing their
sum.
Given a base and two lists representing natural numbers, find the list representing their
difference. You may assume the first list represents a number greater than or equal to the
number represented by the second list. What is the result if this is not so?
Given a base and two lists representing natural numbers, find the list representing their
product.
Given a base and two lists representing natural numbers, find the lists representing their
quotient and remainder.
(a)
(b)
(c)
(d)
(e)
224
(machine multiplication) Given two natural numbers, write a program to find their product
using only addition, subtraction, doubling, halving, test for even, and test for zero.
225
(machine division) Given two natural numbers, write a program to find their quotient
using only addition, subtraction, doubling, halving, test for even, and test for zero.
226
(machine squaring) Given a natural number, write a program to find its square using only
addition, subtraction, doubling, halving, test for even, and test for zero.
227
Given a list of roots of a polynomial, write a program to find the list of coefficients.
228
(longest sorted sublist) Write a program to find the length of a longest sorted sublist of a
given list, where
the sublist must be consecutive items (a segment).
the sublist consists of items in their order of appearance in the given list, but not necessarily
consecutively.
(a)
(b)
229
(almost sorted segment) An almost sorted list is a list in which at most one adjacent pair of
elements is out of order. Write a program to find the length of a longest almost sorted
segment of a given list.
230
(edit distance) Given two lists, write a program to find the minimum number of item
insertions, item deletions, and item replacements to change one list into the other.
175
10 Exercises
231
(ultimately periodic sequence) Let f: int→int be such that the sequence
x0 = 0
xn+1 = f (xn)
is ultimately periodic:
∃p: nat+1· ∃n: nat· xn = xn+p
The smallest positive p such that ∃n: nat· xn = xn+p is called the period. Write a program
to find the period. Your program should use an amount of storage that is bounded by a
constant, and not dependent on f .
232
(partitions) A list of positive integers is called a partition of natural number n if the sum of
its items is n . Write a program to find
a list of all partitions of a given natural n . For example, if n=3 then an acceptable answer
is [[3]; [1; 2]; [2; 1]; [1; 1; 1]] .
a list of all sorted partitions of a given natural n . For example, if n=3 then an acceptable
answer is [[3]; [1; 2]; [1; 1; 1]] .
the sorted list of all partitions of a given natural n . For example, if n=3 then the answer
is [[1; 1; 1]; [1; 2]; [2; 1]; [3]] .
the sorted list of all sorted partitions of a given natural n . For example, if n=3 then the
answer is [[1; 1; 1]; [1; 2]; [3]] .
(a)
(b)
(c)
(d)
233
(largest true square) Write a program to find, within a boolean array, a largest square
subarray consisting entirely of items with value .
234
(P-list) Given a nonempty list S of natural numbers, define a P-list as a nonempty list P
of natural numbers such that each item of P is an index of S , and
∀i: 1,..#P· P (i–1) < P i ≤ S (P (i–1))
Write a program to find the length of a longest P-list for a given list S .
235
(J-list) For natural number n , a J-list of order n is a list of 2×n naturals in which each
m: 0,..n occurs twice, and between the two occurrences of m there are m items.
Write a program that creates a J-list of order n if there is one, for given n .
For which n do J-lists exist?
(a)
(b)
236
(a)
(b)
(diminished J-list) For positive integer n , a diminished J-list of order n is a list of
2×n–1 naturals in which 0 occurs once and each m: 1,..n occurs twice, and between the
two occurrences of m there are m items.
Write a program that creates a diminished J-list of order n if there is one, for given n .
For which n do diminished J-lists exist?
237
(greatest common divisor) Given two positive integers, write a program to find their
greatest common divisor.
238
(least common multiple) Given two positive integers, write a program to find their least
common multiple.
239
Given two integers (not necessarily positive ones) that are not both zero, write a program to
find their greatest common divisor.
240
(common items) Let A be a sorted list of different integers. Let B be another such list.
Write a program to find the number of integers that occur in both lists.
10 Exercises
176
241
(unique items) Let A be a sorted list of different integers. Let B be another such list.
Write a program to find the sorted list of integers that occur in exactly one of A or B .
242
(smallest common item) Given two sorted lists having at least one item in common, write a
program to find the smallest item occurring in both lists.
243
Given three sorted lists having at least one item common to all three, write a program to
find the smallest item occurring in all three lists.
244
Given three positive integers, write a program to find their greatest common divisor. One
method is to find the greatest common divisor of two of them, and then find the greatest
common divisor of that and the third, but there is a better way.
245
(longest common prefix) A positive integer can be written as a sequence of decimal digits
without leading zeros. Given two positive integers, write a program to find the number
that is written as their longest common prefix of digits. For example, given 25621 and
2547 , the result is 25 . Hint: this question is about numbers, not about strings or lists.
246
(museum) You are given natural n , rationals s and f (start and finish), and lists A, D:
[n*rat] (arrive and depart) such that
∀i· s ≤ Ai ≤ Di ≤ f
They represent a museum that opens at time s , is visited by n people with person i
arriving at time Ai and departing at time Di and closes at time f . Write a program to find
the total amount of time during which at least one person is inside the museum, and the
average number of people in the museum during the time it is open, in time linear in n , if
list A is sorted.
list D is sorted.
(a)
(b)
247
(rotation test) Given two lists, write a program to determine if one list is a rotation of the
other. You may use item comparisons, but not list comparisons. Execution time should be
linear in the length of the lists.
248
(smallest rotation) Given a text variable t , write a program to reassign t its alphabetically
(lexicographically) smallest rotation. You may use character comparisons, but not text
comparisons.
249
You are given a list variable L assigned a nonempty list. All changes to L must be via
procedure swap , defined as
swap = λi, j: 0,..#L· L:= i→Lj | j→Li | L
Write a program to reassign L a new list obtained by rotating the old list one place to the
right (the last item of the old list is the first item of the new).
(rotate) Given an integer r , write a program to reassign L a new list obtained by rotating
the old list r places to the right. (If r<0 , rotation is to the left –r places.) Recursive
execution time must be at most #L .
(segment swap) Given an index p , swap the initial segment up to p with the final
segment beginning at p .
(a)
(b)
(c)
250
(squash) Let L be a list variable assigned a nonempty list. Reassign it so that any run of
two or more identical items is collapsed to a single item.
177
10 Exercises
251
Let n and p be natural variables. Write a program to solve
n≥2 ⇒ p′: 22nat ∧ n≤p′<n2
Include a finite upper bound on the execution time, but it doesn't matter how small.
252
(greatest square under a histogram) You are given a histogram in the form of a list H of
natural numbers. Write a program to find the longest segment of H in which the height
(each item) is at least as large as the segment length.
253
(long texts) A particular computer has a hardware representation for texts less than n
characters long, for some constant n . Longer texts must be represented in software as a
list of short texts. (The long text represented is the catenation of the short texts.) A list of
short texts is called “packed” if all items except possibly the last have maximum length.
Write a program to pack a list of short texts without changing the long text represented.
254
(a)
(Knuth, Morris, Pratt)
Given list P , find list L such that for every index n of list P , Ln is the length of the
longest list that is both a proper prefix and a proper suffix of P [0;..n+1] . Here is a
program to find L .
A ⇐ i:= 0. L:= [#P*0]. j:= 1. B
B ⇐ if j≥#P then ok else (C. L:= j→i | L. j:= j+1. B)
C ⇐ if Pi=Pj then i:= i+1
else if i=0 then ok
else (i:= L (i–1). C)
Find specifications A , B , and C so that A is the problem and the three refinements are
theorems.
Given list S (subject), list P (pattern), and list L (as in part (a)), determine if P is a
segment of S , and if so, where it occurs. Here is a program.
D ⇐ m:= 0. n:= 0. E
E ⇐ if m=#P then h:= n–#P else F
F ⇐ if n=#S then h:= ∞
else if Pm=Sn then (m:= m+1. n:= n+1. E)
else G
G ⇐ if m=0 then (n:= n+1. F) else (m:= L (m–1). G)
Find specifications D , E , F , and G so that D is the problem and the four refinements
are theorems.
(b)
End of Program Theory
10.4 Programming Language
255
(nondeterministic assignment) Generalize the assignment notation x:= e to allow the
expression e to be a bunch, with the meaning that x is assigned an arbitrary element of
the bunch. For example, x:= nat assigns x an arbitrary natural number. Show the
standard boolean notation for this form of assignment. Show what happens to the
Substitution Law.
256
Suppose variable declaration is defined as
var x: T· P = ∃x: undefined· ∃x′: T· P
What are the characteristics of this kind of declaration? Look at the example
var x: int· ok
10 Exercises
178
257
What is wrong with defining local variable declaration as follows:
var x: T· P = ∀x: T· ∃x′: T· P
258
Suppose variable declaration with initialization is defined as
var x: T := e = var x: T· x:= e
In what way does this differ from the definition given in Subsection 5.0.0?
259
Here are two different definitions of variable declaration with initialization.
var x: T := e· P = ∃x, x′: T· x=e ∧ P
var x: T := e· P = ∃x′: T· (substitute e for x in P )
Show how they differ with an example.
260
The program
var x: nat· x:= –1
introduces a local variable and then assigns it a value that is out of bounds. Is this program
implementable? (Proof required.)
261
(frame problem) Suppose there is one nonlocal variable x , and we define P = x′=0 .
Can we prove
P ⇐ var y: nat· y:= 0. P. x:= y
The problem is that y was not part of the state space where P was defined, so does P
leave y unchanged? Hint: consider the definition of dependent composition. Is it being
used properly?
262
Let the state variables be x , y , and z . Rewrite frame x·
Say in words what the final value of x is.
263
In a language with array element assignment, the program
x:= i. i:= A i. A i:= x
was written with the intention to swap the values of i and A i . Assume that all variables
and array elements are of type nat , and that i has a value that is an index of A .
In variables x , i , and A , specify that i and Ai should be swapped, the rest of A
should be unchanged, but x might change.
Find the exact precondition for which the program refines the specification of part (a).
Find the exact postcondition for which the program refines the specification of part (a).
(a)
(b)
(c)
264
without using frame .
In a language with array element assignment, what is the exact precondition for A′ i′ = 1
to be refined by (A(A i):= 0. A i:= 1. i:= 2) ?
265√ (unbounded bound) Find a time bound for the following program in natural variables x
and y .
while ¬ x=y=0 do
if y>0 then y:= y–1
else (x:= x–1. var n: nat· y:= n)
266
Let W ⇐ while b do P be an abbreviation of W ⇐ if b then (P. W) else ok . Let
R ⇐ repeat P until b be an abbreviation of R ⇐ P. if b then ok else R . Now
prove
(R ⇐ repeat P until b) ∧ (W ⇐ while ¬b do P)
⇐ (R ⇐ P. W) ∧ (W ⇐ if b then ok else R)
179
267
(a)
(b)
10 Exercises
(guarded command) In “Dijkstra's little language” there is a conditional program with the
syntax
if b → P [] c → Q fi
where b and c are boolean and P and Q are programs. It can be executed as follows.
If exactly one of b and c is true initially, then the corresponding program is executed; if
both b and c are true initially, then either one of P or Q (arbitrary choice) is executed;
if neither b nor c is true initially, then execution is completely arbitrary.
Express this program in the notations of this book as succinctly as possible.
Refine this program using only the programming notations introduced in Chapter 4.
268√ Using a for-loop, write a program to add 1 to every item of a list.
269
(a)
(b)
270
(a)
(b)
Here is one way that we might consider defining the for-loop. Let j , n , k and m be
integer expressions, and let i be a fresh name.
for i:= nil do P = ok
for i:= j do P = (substitute j for i in P )
for i:= n;..k ; k;..m do P = for i:= n;..k do P. for i:= k;..m do P
From this definition, what can we prove about for i:= 0;..n do n:= n+1 where n is an
integer variable?
What kinds of for-loop are in the programming languages you know?
(majority vote) The problem is to find, in a given list, the majority item (the item that
occurs in more than half the places) if there is one. Letting L be the list and m be a
variable whose final value is the majority item, prove that the following program solves the
problem.
var e: nat := 0·
for i:= 0;..#L do
if m = L i then e:= e+1
else if i = 2×e then (m:= L i. e:= e+1)
else o k
var s: nat := 0·
for i:= 0;..#L do
if m = L i then ok
else if i = 2×s then m:= L i
else s:= s+1
271
We defined the programmed expression P result e with the axiom
x′ = (P result e) = P. x′=e
Why don't we define it instead with the axiom
x′ = (P result e) = P ⇒ x′=e′
272
Let a and b be rational variables. Define procedure P as
P = λx, y: rat· if x=0 then a:= x else (a:= x×y. a:= a×y)
What is the exact precondition for a′=b′ to be refined by P a (1/b) ?
Discuss the difference between “eager” and “lazy” evaluation of arguments as they affect
both the theory of programming and programming language implementation.
(a)
(b)
273
“Call-by-value-result” describes a parameter that gets its initial value from an argument, is
then a local variable, and gives its final value back to the argument, which therefore must
be a variable. Define “call-by-value-result” formally. Discuss its merits and demerits.
10 Exercises
180
274
Here is a procedure applied to an argument.
(λx: int· a:= x. b:= x) (a+1)
Suppose, by mistake, we replace both occurrences of x in the body with the argument.
What do we get? What should we get? (This mistake is known as “call-by-name”.)
275
We defined wait until w = t:= max t w where t is an extended integer time variable,
and w is an integer expression.
Prove wait until w ⇐ if t≥w then ok else (t:= t+1. wait until w)
Now suppose that t is an extended real time variable, and w is an extended real
expression. Redefine wait until w appropriately, and refine it using the recursive time
measure.
(a)√
(b)
276
(a)
(b)
The specification wait w where w is a length of time, not an instant of time, describes a
delay in execution of time w . Formalize and implement it using the recursive time
measure and
an extended integer time variable.
an extended real time variable.
277
We propose to define a new programming connective P ♦ Q . What properties of ♦ are
essential? Why?
278
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(i)
(ii)
(Boole's booleans) If =1 and =0 , express
¬a
a∧b
a∨b
a⇒b
a⇐b
a=b
a b
using only the following symbols (in any quantity)
01ab()+–×
0 1 a b ( ) – max min
279
(a)
(b)
Prove that the average value of
n2 as n varies over nat+1 according to probability 2–n is 6 .
n as it varies over nat according to probability (5/6)n × 1/6 is 5 .
280
(coin) Repeatedly flip a coin until you get a head. Prove that it takes n flips with
probability 2–n . With an appropriate definition of R , the program is
R ⇐ t:= t+1. if rand 2 then ok else R
281√ (blackjack) You are dealt a card from a deck; its value is in the range 1 through 13
inclusive. You may stop with just one card, or have a second card if you want. Your
object is to get a total as near as possible to 14 , but not over 14 . Your strategy is to take
a second card if the first is under 7 . Assuming each card value has equal probability, find
the probability and average value of your total.
282√ (dice) If you repeatedly throw a pair of six-sided dice until they are equal, how long does it
take?
181
283
(a)
(b)
(c)
284
10 Exercises
(drunk) A drunkard is trying to walk home. At each time unit, the drunkard may go
forward one distance unit, stay in the same position, or go back one distance unit. After n
time units, where is the drunkard?
At each time unit, there is a 2/3 probability of going forward, and a 1/3 probability of
staying in the same position. The drunkard does not go back.
At each time unit, there is a 1/4 probability of going forward, a 1/2 probability of staying
in the same position, and a 1/4 probability of going back.
At each time unit, there is a 1/2 probability of going forward, a 1/4 probability of staying
in the same position, and a 1/4 probability of going back.
(Mr.Bean's socks) Mr.Bean is trying to get a matching pair of socks from a drawer
containing an inexhaustible supply of red and blue socks. He begins by withdrawing two
socks at random. If they match, he is done. Otherwise, he throws away one of them at
random, withdraws another sock at random, and repeats. How long will it take him to get
a matching pair? Assume that a sock withdrawn from the drawer has 1/2 probability of
being each color, and that a sock that is thrown away also has a 1/2 probability of being
each color.
End of Programming Language
10.5 Recursive Definition
285
Prove ¬ –1: nat . Hint: You will need induction.
286
(Cantor's diagonal) Prove ¬∃f: nat→nat→nat· ∀g: nat→nat· ∃n: nat· fn = g .
287
Prove ∀n: nat· Pn
=
∀n: nat· ∀m: 0,..n· Pm
288√ Prove that the square of an odd natural number is 8×m + 1 for some natural m .
289
Prove that every positive integer is a product of primes. By “product” we mean the result
of multiplying together any natural number of (not necessarily distinct) numbers. By
“prime” we mean a natural number with exactly two factors.
290
Here is an argument to “prove” that in any group of people, all the people are the same age.
The “proof” is by induction on the size of groups. The induction base is that in any group
of size 1 , clearly all the people are the same age. Or we could equally well use groups of
size 0 as the induction base. The induction hypothesis is, of course, to assume that in any
group of size n , all the people are the same age. Now consider a group of size n+1 . Let
its people be p 0 , p 1 , ..., pn . By the induction hypothesis, in the subgroup p0, p1, ...,
pn–1 of size n , all the people are the same age; to be specific, they are all the same age as
p 1 . And in the subgroup p 1 , p 2 , ..., p n of size n , all the people are the same age;
again, they are the same age as p1 . Hence all n+1 people are the same age. Formalize
this argument and find the flaw.
291
Here is a possible alternative construction axiom for nat .
0, 1, nat+nat: nat
What induction axiom goes with it?
Are the construction axiom given and your induction axiom of part (a) satisfactory as a
definition if nat?
(a)
(b)
10 Exercises
182
292
Chapter 6 gives four predicate versions of nat induction. Prove that they are equivalent.
293
Prove nat = 0,..∞ .
294
Here are a construction axiom and an induction axiom for bunch bad .
(§n: nat· ¬ n: bad) : bad
(§n: nat· ¬ n: B) : B ⇒ bad: B
Are these axioms consistent?
Can the fixed-point equation
bad = §n: nat· ¬ n: bad
be proven from them?
(a)
(b)
295
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
(k)
Prove the following; quantifications are over nat .
¬∃i, j· j 0 ∧ 21/2 = i/j The square root of 2 is irrational.
∀n· (Σi: 0,..n· 1) = n
∀n· (Σi: 0,..n· i) = n × (n–1) / 2
∀n· (Σi: 0,..n· i3) = (Σi: 0,..n· i)2
∀n· (Σi: 0,..n· 2i) + 1 = 2n
∀n· (Σi: 0,..n· (–2)i) = (1 – (–2)n) / 3
∀n· n≥10 ⇒ 2n > n3
∀n· n≥4 ⇒ 3n > n3
∀n· n≥3 ⇒ 2×n3 > 3×n2 + 3×n
∀a, d· ∃q, r· d 0 ⇒ r<d ∧ a = q×d + r
∀a, b· a≤b ⇒ (Σi: a,..b· 3i) = (3b–3a)/2
296
(a)
(b)
Show that we can define nat by fixed-point construction together with
∀n: nat· 0 ≤ n < n+1
∃m: nat· ∀n: nat· m ≤ n < n+1
297√ Suppose we define nat by ordinary construction and induction.
0, nat+1: nat
0, B+1: B ⇒ nat: B
Prove that fixed-point construction and induction
nat = 0, nat+1
B = 0, B+1 ⇒ nat: B
are theorems.
298
(fixed-point theorem) Suppose we define nat by fixed-point construction and induction.
nat = 0, nat+1
B = 0, B+1 ⇒ nat: B
Prove that ordinary construction and induction
0, nat+1: nat
0, B+1: B ⇒ nat: B
are theorems. Warning: this is hard, and requires the use of limits.
299
(rulers) Rulers are formed as follows. A vertical stroke | is a ruler. If you append a
horizontal stroke — and then a vertical stroke | to a ruler you get another ruler. Thus the
first few rulers are | , |—| , |—|—| , |—|—|—| , and so on. No two rulers formed this
way are equal. There are no other rulers. What axioms are needed to define bunch ruler
consisting of all and only the rulers?
183
10 Exercises
300
(a)
(b)
(c)
Function f is called monotonic if i ≤ j ⇒ fi ≤ fj .
Prove f is monotonic if and only if fi < fj ⇒ i < j .
Let f: int→int . Prove f is monotonic if and only if fi ≤ f(i+1) .
Let f: nat→nat be such that ∀n· ffn < f(n+1) . Prove f is the identity function. Hints:
First prove ∀n· n ≤ fn . Then prove f is monotonic. Then prove ∀n· fn ≤ n .
301
The Fibonacci numbers f n are defined as follows.
f0 = 0
f1 = 1
f (n+2) = f n + f (n+1)
Prove
f (gcd n m) = gcd (f n) (f m)
where gcd is the greatest common divisor.
f n × f (n+2) = f (n+1) 2 – (–1)n
f (n+m+1) = f n × f m + f (n+1) × f (m+1)
f (n+m+2) = f n × f (m+1) + f (n+1) × f m + f (n+1) × f (m+1)
f (2×n+1) = f n 2 + f (n+1) 2
f (2×n+2) = 2 × f n × f (n+1) + f (n+1) 2
(a)
(b)
(c)
(d)
(e)
(f)
302
Let R be a relation of naturals R: nat→nat→bool that is monotonic in its second
parameter
∀i, j· R i j ⇒ R i (j+1)
Prove
∃i· ∀j· R i j = ∀j· ∃i· R i j
303
(a)
(b)
What is the smallest bunch satisfying
B = 0, 2×B + 1
B = 2, B ×B
304
What elements can be proven in P from the axiom P = 1, x, –P, P+P, P×P ? Prove
2×x2–1: P
305
Bunch this is defined by the construction and induction axioms
2, 2×this: this
2, 2×B: B ⇒ this: B
Bunch that is defined by the construction and induction axioms
2, that×that: that
2, B×B: B ⇒ that: B
Prove this = that .
306
Express 2int without using exponentiation. You may introduce auxiliary names.
307
Let n be a natural number. From the fixed-point equation
ply = n, ply+ply
we obtain a sequence of bunches plyi by recursive construction.
State plyi formally (no proof needed).
State plyi in English.
What is ply∞ ?
Is ply∞ a solution? If so, is it the only solution?
(a)
(b)
(c)
(d)
10 Exercises
308
(a)
(b)
(c)
309
(a)
(b)
(c)
(d)
310
(a)
(b)
311
(a)
(b)
184
For each of the following fixed-point equations, what does recursive construction yield?
Does it satisfy the fixed-point equation?
M = [*int], [*M]
T = [nil], [T; int; T]
A = bool, rat, char, [*A]
Let A B be the difference between bunch A and bunch B . The operator
has
precedence level 4, and is defined by the axiom
x: A B = x: A ∧ ¬ x: B
For each of the following fixed-point equations, what does recursive construction yield?
Does it satisfy the fixed-point equation?
Q = nat (Q+3)
D = 0, (D+1) (D–1)
E = nat (E+1)
F = 0, (nat F)+1
For each of the following fixed-point equations, what does recursive construction yield?
Does it satisfy the fixed-point equation?
P = §n: nat· n=0 ∧ P=null ∨ n: P+1
Q = §x: xnat· x=0 ∧ Q=null ∨ x: Q+1
Here is a pair of mutually recursive equations.
even = 0, odd+1
odd = even+1
What does recursive construction yield? Show the construction.
Are further axioms needed to ensure that even consists of only the even naturals, and odd
consists of only the odd naturals? If so, what axioms?
312(a) Considering E as the unknown, find three solutions of E, E+1 = nat .
(b)
Now add the induction axiom B, B+1 = nat ⇒ E: B . What is E ?
313
(a)
(b)
(c)
(d)
From the construction axiom 0, 1–few: few
what elements are constructed?
give three solutions (considering few as the unknown).
give the corresponding induction axiom.
state which solution is specified by construction and induction.
314
Investigate the fixed-point equation
strange = §n: nat· ∀m: strange· ¬ m+1: n×nat
315
Let truer be a bunch of strings of booleans defined by the construction and induction
axioms
, ;truer;truer: truer
, ;B;B: B ⇒ truer: B
Given a string of booleans, write a program to determine if the string is in truer .
316
(strings) If S is a bunch of strings, then *S is the bunch of all strings formed by
catenating together any number of any strings in S in any order. Without using * , define
*S by construction and induction.
185
10 Exercises
317
Here are the construction and induction axioms for lists of items of type T .
[nil], [T], list+list: list
[nil], [T], L+L: L ⇒ list: L
Prove list = [*T] .
318
(decimal-point numbers) Using recursive data definition, define the bunch of all decimalpoint numbers. These are the rationals that can be expressed as a finite string of decimal
digits containing a decimal point. Note: you are defining a bunch of numbers, not a
bunch of texts.
319
(Backus-Naur Form) Backus-Naur Form is a grammatical formalism in which grammatical
rules are written as in the following example.
〈exp〉::= 〈exp〉 + 〈exp〉 | 〈exp〉 × 〈exp〉 | 0 | 1
In our formalism, it would be written
exp = exp; "+"; exp, exp; "×"; exp, "0", "1"
In a similar fashion, write axioms to define each of the following.
palindromes: texts that read the same forward and backward. Use a two-symbol alphabet.
palindromes of odd length.
all texts consisting of “a”s followed by the same number of “b”s.
all texts consisting of “a”s followed by at least as many “b”s.
(a)
(b)
(c)
(d)
320
(a)
(b)
(c)
(d)
(e)
321
(a)
(b)
(c)
(d)
(e)
Section 6.1 defines program zap by the fixed-point equation
zap = if x=0 then y:= 0 else (x:= x–1. t:= t+1. zap)
Prove zap ⇒ x≥0 ⇒ x′=y′=0 ∧ t′ = t+x .
Prove x≥0 ∧ x′=y′=0 ∧ t′ = t+x ⇒ zap .
What axiom is needed to make zap the weakest fixed-point?
What axiom is needed to make zap the strongest fixed-point?
Section 6.1 gives six solutions to this equation. Find more solutions. Hint: strange things
can happen at time ∞ .
Let all variables be integer. Add recursive time. Using recursive construction, find a
fixed-point of
skip = if i≥0 then (i:= i–1. skip. i:= i+1) else ok
inc
= ok ∨ (i:= i+1. inc)
sqr
= if i=0 then ok else (s:= s + 2×i – 1. i:= i–1. sqr)
fac
= if i=0 then f:= 1 else (i:= i–1. fac. i:= i+1. f:= f×i)
chs
= if a=b then c:= 1 else (a:= a–1. chs. a:= a+1. c:= c×a/(a–b) )
322
(a)
(b)
(c)
Let all variables be integer. Add recursive time. Any way you can, find a fixed-point of
walk = if i≥0 then (i:= i–2. walk. i:= i+1. walk. i:= i+1) else ok
crawl = if i≥0 then (i:= i–1. crawl. i:= i+2. crawl. i:= i–1) else ok
run
= if even i then i:= i/2 else i:= i+1.
if i=1 then ok else run
323
(a)
(b)
Investigate how recursive construction is affected when we start with
t′ = ∞
t:= ∞
10 Exercises
186
324
Let x be an integer variable. Using the recursive time measure, add time and then find the
strongest implementable specifications P and Q that you can find for which
P ⇐ x′ ≥ 0. Q
Q ⇐ if x=0 then ok else (x:= x–1. Q)
Assume that x′ ≥ 0 takes no time.
325
(a)
Let x be an integer variable.
Using the recursive time measure, add time and then find the strongest implementable
specification S that you can find for which
S ⇐ if x=0 then ok
else if x>0 then (x:= x–1. S)
else (x′ ≥ 0. S)
Assume that x′ ≥ 0 takes no time.
What do we get from recursive construction starting with t′ ≥ t ?
(b)
326
Prove that the following three ways of defining R are equivalent.
R = ok ∨ (R. S)
R = ok ∨ (S. R)
R = ok ∨ S ∨ (R. R)
327
Prove the laws of Refinement by Steps and Refinement by Parts for while-loops.
328
Prove that
∀σ, σ′· (t′≥t ∧ (if b then (P. t:= t+inc. W) else ok) ⇐ W)
⇐ ∀σ, σ′· (while b do P ⇐ W)
is equivalent to the while construction axioms, and hence that construction and induction
can be expressed together as
∀σ, σ′· (t′≥t ∧ (if b then (P. t:= t+inc. W) else ok) ⇐ W)
= ∀σ, σ′· (while b do P ⇐ W)
329
The notation repeat P until b has been used as a loop construct that is executed as
follows. First P is executed; then b is evaluated, and if
execution is finished, and if
execution is repeated. Define repeat P until b by construction and induction axioms.
330
(a)
(b)
(c)
Using the definition of Exercise 329, prove
repeat P until b = P. t:= t+inc. while ¬b do P
while b do P = if b then repeat P until ¬b else ok
(∀σ, σ′·(R = repeat P until b)) ∧ (∀σ, σ′·(W = while ¬b do P))
= (∀σ, σ′·(R = P. t:= t+inc. W)) ∧ (∀σ, σ′·(W = if b then ok else R))
331
(a)
Let P: nat→bool .
Define quantifier FIRST so that FIRST m: nat· Pm is the smallest natural m such that
Pm , and ∞ if there is none.
Prove n:= FIRST m: nat· Pm ⇐ n:= 0. while ¬Pn do n:= n+1 .
(b)
332
(a)
(b)
Let the state consist of boolean variables b and c . Let
W = if b then (P. W) else ok
X = if b∨c then (P. X) else ok
Find a counterexample to W. X = X .
Now let W and X be the weakest solutions of those equations, and prove W. X
=
X.
187
333
(a)
(b)
(c)
(d)
10 Exercises
In real variable x , consider the equation
P = P. x:= x2
Find 7 distinct solutions for P .
Which solution does recursive construction give starting from
? Is it the weakest
solution?
If we add a time variable, which solution does recursive construction give starting from
t′≥t ? Is it a strongest implementable solution?
Now let x be an integer variable, and redo the question.
334
Suppose we define while b do P by ordinary construction and induction, ignoring time.
if b then (P. while b do P) else ok ⇐ while b do P
∀σ, σ′·(if b then (P. W) else ok ⇐ W) ⇒ ∀σ, σ′·(while b do P ⇐ W)
Prove that fixed-point construction and induction
while b do P = if b then (P. while b do P) else ok
∀σ, σ′· (W = if b then (P. W) else ok) ⇒ ∀σ, σ′· (while b do P ⇐ W)
are theorems.
335
Suppose we define while b do P by fixed-point construction and induction, ignoring
time.
while b do P = if b then (P. while b do P) else ok
∀σ, σ′· (W = if b then (P. W) else ok) ⇒ ∀σ, σ′· (while b do P ⇐ W)
Prove that ordinary construction and induction
if b then (P. while b do P) else ok ⇐ while b do P
∀σ, σ′·(if b then (P. W) else ok ⇐ W) ⇒ ∀σ, σ′·(while b do P ⇐ W)
are theorems. Warning: this is hard, and requires the use of limits.
End of Recursive Definition
10.6 Theory Design and Implementation
336
(a)
(b)
(c)
(widgets) A theory of widgets is presented in the form of some new syntax and some
axioms. An implementation of widgets is written.
How do we know if the theory of widgets is consistent?
How do we know if the theory of widgets is incomplete?
How can we prove that the implementation of widgets is correct?
337√ Implement data-stack theory to make the two boolean expressions
pop empty = empty
top empty = 0
antitheorems.
338
Prove that the following definitions implement the simple data-stack theory.
stack = [nil], [stack; X]
push = λs: stack· λx: X· [s; x]
pop = λs: stack· s 0
top = λs: stack· s 1
339
(weak data-stack) In Subsection 7.1.3 we designed a program-stack theory so weak that
we could add axioms to count pushes and pops without inconsistency. Design a similarly
weak data-stack theory.
10 Exercises
188
340
(data-queue implementation) Implement the data-queue theory presented in Section 7.0.
341
(slip) The slip data structure introduces the name slip with the following axioms:
slip = [X; slip]
B = [X; B] ⇒ B: slip
where X is some given type. Can you implement it?
342
Prove that the program-stack implementation given in Subsection 7.1.1 satisfies the
program-stack axioms of Subsection 7.1.0.
343
Implement weak program-stack theory as follows: the implementer's variable is a list that
grows and never shrinks. A popped item must be marked as garbage.
344
You are given a program-stack. Can you write a program composed from the programs
push `A push `B push `C push `D push `E
in that order, with the programs print top and pop interspersed wherever needed as many
times as needed, to obtain the following output?
BDECA
BCDEA
CADEB
ABECD
ABCDE
(a)
(b)
(c)
(d)
(e)
345
(brackets) You are given a text t of characters drawn from the alphabet `x, `(, `), `[, `] .
Write a program to determine if t has its brackets properly paired and nested.
346
(limited-stack) A stack, according to our axioms, has an unlimited capacity to have items
pushed onto it. A limited-stack is a similar data structure but with a limited capacity to have
items pushed onto it.
Design axioms for a limited-data-stack.
Design axioms for a limited-program-stack.
Can the limit be 0 ?
(a)
(b)
(c)
347
(a)
(b)
(c)
348
(a)
(b)
(c)
(d)
(e)
(limited-queue) A queue, according to our axioms, has an unlimited capacity to have items
joined onto it. A limited-queue is a similar data structure but with a limited capacity to have
items joined onto it.
Design axioms for a limited-data-queue.
Design axioms for a limited-program-queue.
Can the limit be 0 ?
You are given a program-queue. Can you write a program composed from the programs
join `A join `B join `C join `D join `E
in that order, with the programs print front and leave interspersed wherever needed as
many times as needed, to obtain the following output?
BDECA
BCDEA
CADEB
ABECD
ABCDE
189
10 Exercises
349
Each of the program theories provides a single, anonymous instance of a data structure.
How can a program theory be made to provide many instances of a data structure, like data
theories do?
350
(circular list) Design axioms for a circular list. There should be operations to create an
empty list, to move along one position in the list (the first item comes after the last, in
circular fashion), to insert an item at the current position, to delete the current item, and to
give the current item.
351
(resettable variable) A resettable variable is defined as follows. There are three new
names: value (of type X ), set (a procedure with one parameter of type X ), and reset
(a program). Here are the axioms:
value′=x ⇐ set x
value′=value ⇐ set x. reset
reset. reset = reset
Implement this data structure, with proof.
352
A particular program-list has the following operations:
•
the operation mkempty makes the list empty
•
the operation extend x catenates item x to the end of the list
•
the operation swap i j swaps the items at indexes i and j
•
the expression length tells the length of the list
•
the expression item i tells the item at index i
Write axioms to define this program-list.
Implement this program-list, with proof.
(a)
(b)
353
(linear algebra) Design a theory of linear algebra. It should include scalar, vector, and
matrix sums, products, and inner products. Implement the theory, with proof.
354
(leafy tree) A leafy tree is a tree with information residing only at the leaves. Design
appropriate axioms for a binary leafy data-tree.
355
(a)
A tree can be implemented by listing its items in breadth order.
Implement a binary tree by a list of its items such that the root is at index 0 and the left and
right subtrees of an item at index n are rooted at indexes 2×n+1 and 2×n+2 .
Prove your implementation.
Generalize this implementation to trees in which each item can have at most k branches for
arbitrary (but constant) k .
(b)
(c)
356
(hybrid-tree) Chapter 7 presented data-tree theory and program-tree theory. Design a
hybrid-tree theory in which there is only one tree structure, so it can be an implementer's
variable with program operations on it, but there can be many pointers into the tree, so they
are data-pointers (they may be data-stacks).
357
(heap) A heap is a tree with the property that the root is the largest item and the subtrees are
heaps.
Specify the heap property formally.
Write a function heapgraft that makes a heap from two given heaps and a new item. It
may make use of graft , and may rearrange the items as necessary to produce a heap.
(a)
(b)
10 Exercises
190
358
(leaf count) Write a program to count the number of leaves in a tree.
359
(binary search tree) A binary search tree is a binary tree with the property that all items in
the left subtree are less than the root item, all items in the right subtree are greater than the
root item, and the subtrees are also binary search trees.
Specify the binary search tree property formally.
How many binary search trees are there with three items?
How many binary search trees are there with three distinct items?
Write a program to find an item in a binary search tree.
Write a program to add an item to a binary search tree as a new leaf.
Write a program to make a list of the items in a binary search tree in order.
Write a program to determine whether two binary search trees have the same items.
(a)
(b)
(c)
(d)
(e)
(f)
(g)
360
(party) A company is structured as a tree, with employees at the nodes. Each employee,
except the one at the root, has a boss represented by their parent in the tree. Each employee
has a conviviality rating (a number) representing how much fun they are at a party. But noone will be at a party with their boss. Write a program to find the bunch of employees to
invite to a party so that the total convivialty is maximized.
361
(insertion list) An insertion list is a data structure similar to a list, but with an associated
insertion point.
[ ...; 4 ; 7 ; 1 ; 0 ; 3 ; 8 ; 9 ; 2 ; 5 ; ... ]
(a)
(b)
(c)
(d)
insertion point
insert puts an item at the insertion point (between two existing items), leaving the insertion
point at its right. erase removes the item to the left of the insertion point, closing up the
list. item gives the item to the left of the insertion point. forward moves the insertion
point one item to the right. back moves the insertion point one item to the left.
Design axioms for a doubly-infinite data-insertion list.
Design axioms for a doubly-infinite program-insertion list.
Design axioms for a finite data-insertion list.
Design axioms for a finite program-insertion list.
362√ (parsing) Define E as a bunch of strings of texts satisfying the fixed-point equation
E = "x", "if"; E; "then"; E; "else"; E
Given a string s of texts, write a program to determine if s: E .
363
(a)√
(b)
(c)
A theory provides three names: zero , increase , and inquire . It is presented by an
implementation. Let u: bool be the user's variable, and let v: nat be the implementer's
variable. The axioms are
zero = v:= 0
increase = v:= v+1
inquire = u:= even v
Use data transformation to replace v with w: bool according to the transformer
w = even v
(this isn't a data transformer, since ∀w· ∃v·
anyway to see what happens)
isn't a theorem, but apply it
191
364
(a)√
(b)
(c)
365
(a)
(b)
(c)
(d)
366
10 Exercises
A theory provides three names: set , flip , and ask . It is presented by an implementation.
Let u: bool be the user's variable, and let v: bool be the implementer's variable. The
axioms are
set = v:=
flip = v:= ¬v
ask = u:= v
Replace v with w: nat according to the data transformer v = even w .
Replace v with w: nat according to the data transformer (w=0 ⇒ v) ∧ (w=1 ⇒ ¬v) . Is
anything wrong?
Replace v with w: nat according to (v ⇒ w=0) ∧ (¬v ⇒ w=1) . Is anything wrong?
Let a , b and c be boolean variables. Variables a and b are implementer's variables,
and c is a user's variable for the operations
seta = a:=
reseta = a:=
flipa = a:= ¬a
setb = b:=
resetb = b:=
flipb = b:= ¬b
and = c:= a∧b
or = c:= a∨b
This theory must be reimplemented using integer variables, with 0 for
and all other
integers for .
What is the data transformer?
Transform seta .
Transform flipa .
Transform and .
Find a data transformer to transform the program of Exercise 270(a) into the program of
Exercise 270(b).
367√ (security switch) A security switch has three boolean user's variables a , b , and c . The
users assign values to a and b as input to the switch. The switch's output is assigned to
c . The output changes when both inputs have changed. More precisely, the output
changes when both inputs differ from what they were the previous time the output
changed. The idea is that one user might flip their switch indicating a desire for the output
to change, but the output does not change until the other user flips their switch indicating
agreement that the output should change. If the first user changes back before the second
user changes, the output does not change.
(a)
Implement a security switch to correspond as directly as possible to the informal
description.
(b)
Transform the implementation of part (a) to obtain an efficient implementation.
368
The user's variable is boolean b . The implementer's variables are natural x and y . The
operations are:
done = b:= x=y=0
step = if y>0 then y:= y–1 else (x:= x–1. var n: nat· y:= n)
Replace the two implementer's variables x and y with a single new implementer's
variable: natural z . Hint: Look at Exercise 265, which is solved in Chapter 5.
10 Exercises
369
192
Maintain a natural variable on which the following requests are made:
• make it equal to a given natural n
• assign to boolean variable p to say whether it is prime
If we let m be the natural variable, we can specify the two problems, and solve them, very
easily as follows:
m:= n
p:= prime m
assuming prime is suitably defined. If prime is an expensive operation and requests to
know whether m is prime are more frequent than requests to change the value of m , we
can improve the solution. Using data transformation, find a better solution.
370√ (take a number) Maintain a list of natural numbers standing for those that are “in use”. The
three operations are:
• make the list empty (for initialization)
• assign to variable n a number not currently in use, and add this number to the list (it is
now in use)
• given a number n that is currently in use, remove it from the list (it is now no longer in
use, and it can be reused later)
(a)
Implement the operations in terms of bunches.
(b)
Use a data transformer to replace all bunch variables with natural variables.
(c)
Use a data transformer to obtain a distributed solution.
371√ A limited queue is a queue with a limited number of places for items. Let the limit be
positive natural n , and let Q: [n*X] and p: nat be implementer's variables. Here is an
implementation.
mkemptyq = p:= 0
isemptyq = p=0
isfullq = p=n
join x = Qp:= x. p:= p+1
leave = for i:= 1;..p do Q(i–1):= Qi. p:= p–1
front = Q0
Removing the front item from the queue takes time p–1 to shift all remaining items down
one index. Transform the queue so that all operations are instant.
372
A binary tree can be stored as a list of nodes in breadth order. Traditionally, the root is at
index 1 , the node at index n has its left child at index 2×n and its right child at index
2×n+1 . Suppose the user's variable is x: X , and the implementer's variables are s: [*X]
and p: nat+1 , and the operations are
goHome =
p:= 1
goLeft
= p:= 2×p
goRight =
p:= 2×p + 1
goUp
= p:= div p 2
put
= s:= p→x | s
get
= x:= s p
Now suppose we decide to move the entire list down one index so that we do not waste
index 0 . The root is at index 0 , its children are at indexes 1 and 2 , and so on.
Develop the necessary data transform, and use it to transform the operations.
193
373
(a)
(b)
(c)
374
(a)
(b)
10 Exercises
(sparse array) An array A: [*[*rat]] is said to be sparse if many of its items are 0 . We
can represent such an array compactly as a list of triples [i; j; x] of all nonzero items
A i j = x 0. Using this idea, find a data transformer and transform the programs
A:= [100*[100*0]]
x:= A i j
A:= (i;j)→x | A
(transformation incompleteness) The user's variable is i and the implementer's variable is
j , both of type nat . The operations are:
initialize = i′ = 0 ≤ j′ < 3
step = if j>0 then (i:= i+1. j:= j–1) else ok
The user can look at i but not at j . The user can initialize , which starts i at 0 and
starts j at any of 3 values. The user can then repeatedly step and observe that i
increases 0 or 1 or 2 times and then stops increasing, which effectively tells the user
what value j started with.
Show that there is no data transformer to replace j with boolean variable b so that
initialize
is transformed to
i′=0
step
is transformed to
if b ∧ i<2 then i′ = i+1 else ok
The transformed initialize starts b either at
, meaning that i will be increased, or at
, meaning that i will not be increased. Each use of the transformed step tests b to
see if we might increase i , and checks i<2 to ensure that i will remain below 3 . If i is
increased, b is again assigned either of its two values. The user will see i start at 0 and
increase 0 or 1 or 2 times and then stop increasing, exactly as in the original
specification.
Use the data transformer b=(j>0) to transform initialize and i+j=k ⇒ step where
k : 0, 1, 2 .
End of Theory Design and Implementation
10.7 Concurrency
375
(a)
(b)
376
Let x and y be natural variables. Rewrite the following program as a program that does
not use || .
x:= x+1 || if x=0 then y:= 1 else ok
if x>0 then y:= x–1 else ok || if x=0 then x:= y+1 else ok
If we ignore time, then
x:= 3. y:= 4 = x:= 3 || y:= 4
Some dependent compositions could be executed in parallel if we ignore time. But the time
for P.Q is the sum of the times for P and Q , and that forces the execution to be
sequential.
t:= t+1. t:= t+2 = t:= t+3
Likewise some independent compositions could be executed sequentially, ignoring time.
But the time for P||Q is the maximum of the times for P and Q , and that forces the
execution to be parallel.
t:= t+1 || t:= t+2 = t:= t+2
Invent another form of composition, intermediate between dependent and independent
composition, whose execution is sequential to the extent necessary, and parallel to the
extent possible. Warning: this is a research question.
10 Exercises
377
(a)
(b)
378
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
194
(disjoint composition) Independent composition P||Q requires that P and Q have no
variables in common, although each can make use of the initial values of the other's
variables by making a private copy. An alternative, let's say disjoint composition, is to
allow both P and Q to use all the variables with no restrictions, and then to choose
disjoint sets of variables v and w and define
P |v|w| Q = (P. v′=v) ∧ (Q. w′=w)
Describe how P |v|w| Q can be executed.
Prove that if P and Q are implementable specifications, then P |v|w| Q is implementable.
(semi-dependent composition) Independent composition P||Q requires that P and Q
have no variables in common, although each can make use of the initial values of the
other's variables by making a private copy. In this question we explore another kind of
composition, let's say semi-dependent composition P Q . Like dependent composition, it
requires P and Q to have the same variables. Like independent composition, it can be
executed by executing the processes in parallel, but each process makes its assignments to
local copies of variables. Then, when both processes are finished, the final value of a
variable is determined as follows: if both processes left it unchanged, it is unchanged; if
one process changed it and the other left it unchanged, its final value is the changed one; if
both processes changed it, its final value is arbitrary. This final rewriting of variables does
not require coordination or communication between the processes; each process rewrites
those variables it has changed. In the case when both processes have changed a variable,
we do not even require that the final value be one of the two changed values; the rewriting
may mix the bits.
Formally define semi-dependent composition, including time.
What laws apply to semi-dependent composition?
Under what circumstances is it unnecessary for a process to make private copies of
variables?
In variables x , y , and z , without using
, express
x:= z y:= z
In variables x , y , and z , without using
, express
x:= y y:= x
In variables x , y , and z , without using
, express
x:= y x:= z
In variables x , y , and z , prove
x:= y x:= z = if x=y then x:= z else if x=z then x:= y else (x:= y x:= z)
In boolean variables x , y and z , without using
, express
x:= x∧z
y:= y∧¬z
x:= x∧¬z
y:= y∧z
Let w: 0,..4 and z: 0, 1 be variables. Without using
, express
w:= 2 × max (div w 2) z + max (mod w 2) (1–z)
w:= 2 × max (div w 2) (1–z) + max (mod w 2) z
379
Extend the definition of semi-dependent composition P Q (Exercise 378) from variables
to list items.
380
Redefine semi-dependent composition P Q (Exercise 378) so that if P and Q agree on
a changed value for a variable, then it has that final value, and if they disagree on a changed
value for a variable, then its final value is
arbitrary.
either one of the two changed values.
(a)
(b)
195
10 Exercises
381
We want to find the smallest number in 0,..n with property p . Linear search solves the
problem. But evaluating p is expensive; let us say it takes time 1 , and all else is free.
The fastest solution is to evaluate p on all n numbers concurrently, and then find the
smallest number that has the property. Write a program without concurrency for which the
sequential to parallel transformation gives the desired computation.
382
Exercise 134 asks for a program to compute cumulative sums (running total). Write a
program that can be transformed from sequential to parallel execution with log n time
where n is the length of the list.
383
(sieve) Given variable p: [n*bool] := [ ; ; (n–2)* ] , the following program is the sieve
of Eratosthenes for determining if a number is prime.
for i:= 2;..ceil (n1/2) do
if p i then for j:= i;..ceil (n/i) do p:= (j×i)→ | p
else ok
Show how the program can be transformed for concurrency. State your answer by
drawing the execution pattern.
What is the execution time, as a function of n , with maximum concurrency?
(a)
(b)
384√ (dining philosophers) Five philosophers are sitting around a round table. At the center of
the table is an infinite bowl of noodles. Between each pair of neighboring philosophers is a
chopstick. Whenever a philosopher gets hungry, the hungry philosopher reaches for the
two chopsticks on the left and right, because it takes two chopsticks to eat. If either
chopstick is unavailable because the neighboring philosopher is using it, then this hungry
philosopher will have to wait until it is available again. When both chopsticks are
available, the philosopher eats for a while, then puts down the chopsticks, and goes back to
thinking, until the philosopher gets hungry again. The problem is to write a program
whose execution simulates the life of these philosophers with the maximum concurrency
that does not lead to deadlock.
End of Concurrency
10.8 Interaction
385√ Suppose a and b are integer boundary variables, x and y are integer interactive
variables, and t is an extended integer time variable. Suppose that each assignment takes
time 1 . Express the following using ordinary boolean operators, without using any
programming notations.
(x:= 2. x:= x+y. x:= x+y) || (y:= 3. y:= x+y)
386
Let a and b be boolean interactive variables. Define
loop = if b then loop else ok
Add a time variable according to any reasonable measure, and then without using || ,
express
b:= || loop
387
(a)
(b)
The Substitution Law does not work for interactive variables.
Show an example of the failure of the law.
Develop a new Substitution Law for interactive variables.
10 Exercises
196
388√ (thermostat) Specify a thermostat for a gas burner. The thermostat operates in parallel with
other processes
thermometer || control || thermostat || burner
The thermometer and the control are typically located together, but they are logically
distinct. The inputs to the thermostat are:
•
real temperature , which comes from the thermometer and indicates the actual
temperature.
•
real desired , which comes from the control and indicates the desired temperature.
•
boolean flame , which comes from a flame sensor in the burner and indicates
whether there is a flame.
The outputs of the thermostat are:
•
boolean gas ; assigning it
turns the gas on and
turns the gas off.
•
boolean spark ; assigning it
causes sparks for the purpose of igniting the gas.
Heat is wanted when the desired temperature falls ε below the actual temperature, and not
wanted when the desired temperature rises ε above the actual temperature, where ε is
small enough to be unnoticeable, but large enough to prevent rapid oscillation. To obtain
heat, the spark should be applied to the gas for at least 1 second to give it a chance to
ignite and to allow the flame to become stable. But a safety regulation states that the gas
must not remain on and unlit for more than 3 seconds. Another regulation says that when
the gas is shut off, it must not be turned on again for at least 20 seconds to allow any
accumulated gas to clear. And finally, the gas burner must respond to its inputs within 1
second.
389√ (grow slow) Suppose alloc allocates 1 unit of memory space and takes time 1 to do so.
Then the following computation slowly allocates memory.
GrowSlow ⇐ if t=2×x then (alloc || x:= t) else t:= t+1. GrowSlow
If the time is equal to 2 ×x , then one space is allocated, and in parallel x becomes the time
stamp of the allocation; otherwise the clock ticks. The process is repeated forever. Prove
that if the space is initially less than the logarithm of the time, and x is suitably initialized,
then at all times the space is less than the logarithm of the time.
390
(a)
(b)
According to the definition of assignment to an interactive variable, writing to the variable
takes some time during which the value of the variable is unknown. But any variables in
the expression being assigned are read instantaneously at the start of the assignment.
Modify the definition of assignment to an interactive variable so that
writing takes place instantaneously at the end of the assignment.
reading the variables in the expression being assigned takes the entire time of the
assignment, just as writing does.
391
(interactive data transformation) Section 7.2 presented data transformation for boundary
variables. How do we do data transformation when there are interactive variables?
Warning: this is a research question.
392
(telephone) Specify the control of a simple telephone. Its inputs are those actions you can
perform: picking up the phone, dialing a digit, and putting down (hanging up) the phone.
Its output is a list of digits (the number dialed). The end of dialing is indicated by 5
seconds during which no further digit is dialed. If the phone is put down without waiting
5 seconds, then there is no output. But, if the phone is put down and then picked up again
within 2 seconds, this is considered to be an accident, and it does not affect the output.
197
10 Exercises
393
(consensus) Some parallel processes are connected in a ring. Each process has a local
integer variable with an initial value. These initial values may differ, but otherwise the
processes are identical. Execution of all processes must terminate in time linear in the
number of processes, and in the end the values of these local variables must all be the
same, and equal to one of the initial values. Write the processes.
394
Many programming languages require a variable for input, with a syntax such as read x .
Define this form of input formally. When is it more convenient than the input described in
Section 9.1? When is it less convenient?
395
Write a program to print the sequence of natural numbers, one per time unit.
396
Write a program to repeatedly print the current time, up until some given time.
397
Given a finite list L of different characters sorted in increasing order, write a program to
print the strings *(L(0,..#L)) in the following order: shorter strings come before longer
strings; strings of equal length are in string (alphabetical, lexicographic) order.
398
(T-lists) Let us call a list L: [*(`a, `b, `c)] a T-list if no two adjacent nonempty segments
are identical:
¬∃i, j, k· 0≤i<j<k≤#L ∧ L [i;..j] = L [j;..k]
Write a program to output all T-lists in alphabetical order. (The mathematician Thue proved
that there are infinitely many T-lists.)
399
(reformat) Write a program to read, reformat, and write a sequence of characters. The
input includes a line-break character at arbitrary places; the output should include a linebreak character just after each semicolon. Whenever the input includes two consecutive
stars, or two stars separated only by line-breaks, the output should replace the two stars by
an up-arrow. Other than that, the output should be identical to the input. Both input and
output end with a special end-character.
400
According to the definition of result expression given in Subsection 5.5.0, what happens
to any output that occurs in the program part of programmed data? Can input be read and
used? What happens to it?
401
(Huffman code) You are given a finite set of messages, and for each message, the
probability of its occurrence.
Write a program to find a binary code for each message. It must be possible to
unambiguously decode any sequence of 0s and 1s into a sequence of messages, and the
average code length (according to message frequency) must be minimum.
Write the accompanying program to produce the decoder for the codes produced in part (a).
(a)
(b)
402
(matrix multiplication) Write a program to multiply two n × n matrices that uses n 2
processes, with 2×n2 local channels, with execution time n .
403
(coin weights) You are given some coins, all of which have a standard weight except
possibly for one of them, which may be lighter or heavier than the standard. You are also
given a balance scale, and as many more standard coins as you need. Write a program to
determine whether there is a nonstandard coin, and if so which, and whether it is light or
heavy, in the minimum number of weighings.
10 Exercises
198
404
How should “deterministic” and “nondeterministic” be defined in the presence of channels?
405
From the fixed-point equation
twos = c! 2. t:= t+1. twos
use recursive construction to find
the weakest fixed-point.
a strongest implementable fixed-point.
the strongest fixed-point.
(a)
(b)
(c)
406
Here are two definitions.
A = if √c ∧ √d then c? ∨ d?
else if √c then c?
else if √d then d?
else if Tcrc < Tdrd then (t:= Tcrc + 1. c?)
else if Tdrd < Tcrc then (t:= Tdrd + 1. d?)
else (t:= Tcrc + 1. c? ∨ d?)
B = if √c ∧ √d then c? ∨ d?
else if √c then c?
else if √d then d?
else (t:= t+1. B)
Letting time be an extended integer, prove A = B .
407
(a)√
(input implementation) Let W be “wait for input on channel c and then read it”.
W = t:= max t (T r + 1). c?
Prove W ⇐ if √c then c? else (t:= t+1. W) assuming time is an extended integer.
Now let time be an extended real, redefine W appropriately, and reprove the refinement.
(b)
408
(input with timeout) As in Exercise 407, let W be “wait for input on channel c and then
read it”, except that if input is still not available by a deadline, an alarm should be raised.
W ⇐ if t ≤ deadline then if√c then c? else (t:= t+1. W) else alarm
Define W appropriately, and prove the refinement.
409
Define relation partmerge: nat→nat→bool as follows:
partmerge 0 0
partmerge (m+1) 0 = partmerge m 0 ∧ Mc(wc+m) = Ma(ra+m)
partmerge 0 (n+1) = partmerge 0 n ∧ Mc(wc+n) = Mb(rb+n)
partmerge (m+1) (n+1) = partmerge m (n+1) ∧ Mc(wc+m+n+1)=Ma(ra+m)
∨ partmerge (m+1) n ∧ Mc(wc+m+n+1)=Mb(rb+n)
Now partmerge m n says that the first m+n outputs on channel c are a merge of m
inputs from channel a and n inputs from channel b . Define merge as
merge = (a?. c! a) ∨ (b?. c! b). merge
Prove merge = (∀m· ∃n· partmerge m n) ∨ (∀n· ∃m· partmerge m n)
410
(perfect shuffle) Write a specification for a computation that repeatedly reads an input on
either channel c or d . The specification says that the computation might begin with either
channel, and after that it alternates.
199
411
(a)√
(b)
10 Exercises
(time merge) We want to repeatedly read an input on either channel c or channel d ,
whichever comes first, and write it on channel e . At each reading, if input is available on
both channels, read either one; if it is available on just one channel, read that one; if it is
available on neither channel, wait for the first one and read that one (in case of a tie, read
either one).
Write the specification formally, and then write a program.
Prove
Tewe = max t (min (Tcrc) (Tdrd) + 1)
∀m, n· Te(we+m+n+1) ≤ max (max (Tc(rc+m)) (Td(rd+n))) (Te(we+m+n)) + 1
412
(fairer time merge) This question is the same as the time merge (Exercise 411), but if input
is available on both channels, the choice must be made the opposite way from the previous
read. If, after waiting for an input, inputs arrive on both channels at the same time, the
choice must be made the opposite way from the previous read.
413
In the reaction controller in Subsection 9.1.6, it is supposed that the synchronizer receives
digital data from the digitizer faster than requests from the controller. Now suppose that
the controller is sometimes faster than the digitizer. Modify the synchronizer so that if two
or more requests arrive in a row (before new digital data arrives), the same digital data will
be sent in reply to each request.
414
(Brock-Ackermann) The following picture shows a network of communicating processes.
a! 0
b
a
choose
c?. b! c
d
c
(a)
(b)
The formal description of this network is
chan a, b, c· a! 0 || choose || (c?. b! c)
Formally define choose , add transit time, and state the output message and time if
choose either reads from a and outputs a 0 on c and d , or reads from b and outputs a
1 on c and d . The choice is made freely.
As in part (a), choose either reads from a and outputs a 0 on c and d , or reads from
b and outputs a 1 on c and d . But this time the choice is not made freely; choose
reads from the channel whose input is available first (if there's a tie, then take either one).
415√ (power series multiplication) Write a program to read from channel a an infinite sequence
of coefficients a0 a1 a2 a 3 ... of a power series a 0 + a 1× x + a 2× x2 + a 3× x3 + ... and in
parallel to read from channel b an infinite sequence of coefficients b0 b1 b2 b 3 ... of a
power series b0 + b1×x + b2×x2 + b3×x3 + ... and in parallel to write on channel c the
infinite sequence of coefficients c0 c1 c2 c3 ... of the power series c0 + c 1× x + c 2 × x 2 +
c3×x3 + ... equal to the product of the two input series. Assume that all inputs are already
available; there are no input delays. Produce the outputs one per time unit.
416
(repetition) Write a program to read an infinite sequence, and after every even number of
inputs, to output a boolean saying whether the second half of the input sequence is a
repetition of the first half.
10 Exercises
200
417
(file update) A master file of records and a transaction file of records are to be read, one
record at a time, and a new file of records is to be written, one record at a time. A record
consists of two text fields: a "key" field and an "info" field. The master file is kept in
order of its keys, without duplicate keys, and with a final record having a sentinel key
"zzzzz" guaranteed to be larger than all other keys. The transaction file is also sorted in
order of its keys, with the same final sentinel key, but it may have duplicate keys. The new
file is like the master file, but with changes as signified by the transaction file. If the
transaction file contains a record with a key that does not appear in the master file, that
record is to be added. If the transaction file contains a record with a key that does appear in
the master file, that record is a change of the "info" field, unless the "info" text is the
empty text, in which case it signifies record deletion. Whenever the transaction file
contains a repeated key, the last record for each key determines the result.
418
(mutual exclusion) Process P is an endless repetition of a “non-critical section” NP and a
“critical section” CP . Process Q is similar.
P = N P . CP . P
Q = NQ. CQ. Q
They are executed in parallel (P || Q) . Specify formally that the two critical sections are
never executed at the same time. Hint: You may insert into P and Q outputs on channels
that are never read, but help to specify the mutual exclusion of the critical sections.
419
(synchronous communication) A synchronous communication happens when the sender is
ready to send and the receiver(s) is(are) ready to receive. Those that are ready must wait
for those that are not.
Design a theory of synchronous communication. For each channel, you will need only one
cursor, but two (or more) time scripts. An output, as well as an input, increases the time to
the maximum of the time scripts for the current message.
Show how it works in some examples, including a deadlock example.
Show an example that is not a deadlock with asynchronous communication, but becomes a
deadlock with synchronous communication.
(a)
(b)
(c)
End of Interaction
End of Exercises
201
11 Reference
11.0 Justifications
This section explains some of the decisions made in choosing and presenting the material in this
book. It is probably not of interest to a student whose concern is to learn the material, but it may
be of interest to a teacher or researcher.
11.0.0
Notation
Whenever I had to choose between a standard notation that will do and a new notation that's
perfect, I chose the standard notation. For example, to express the maximum of two numbers x
and y , a function max is applied: max x y . Since maximum is symmetric and associative, it
would be better to introduce a symmetric symbol like ↑ as an infix operator: x↑y . I always do
so privately, but in this book I have chosen to keep the symbols few in number and reasonably
traditional. Most people seeing max x y will know what is meant without prior explanation; most
people seeing x↑y would not.
A precedence scheme is chosen on two criteria: to minimize the need for parentheses, and to be
easily remembered. The latter is helped by sticking to tradition, by placing related symbols
together, and by having as few levels as possible. The two criteria are sometimes conflicting,
traditions are sometimes conflicting, and the three suggestions for helping memory are sometimes
conflicting. In the end, one makes a decision and lives with it. Extra parentheses can always be
used, and should be used whenever structural similarities would be obscured by the precedence
scheme. For the sake of structure, it would be better to give ∧ and ∨ the same precedence, but I
have stayed with tradition. The scheme in this book has more levels than I would like. I could
place ¬ with unary – , ∧ with × , ∨ with binary + , and ⇒ and ⇐ with = and
. This
saves four levels, but is against mathematical tradition and costs a lot of parentheses. The use of
large symbols = ⇐ ⇒ with large precedence level is a novelty; I hope it is both readable
and writable. Do not judge it until you have used it awhile; it saves an enormous number of
parentheses. One can immediately see generalizations of this convention to all symbols and many
sizes (a slippery slope).
End of Notation
11.0.1
Boolean Theory
Boolean Theory sometimes goes by other names: Boolean Algebra, Propositional Calculus,
Sentential Logic. Its expressions are sometimes called “propositions” or “sentences”. Sometimes
a distinction is made between “terms”, which are said to denote values, and “propositions”, which
are said not to denote values but instead to be true or false. A similar distinction is made between
“functions”, which apply to arguments to produce values, and “predicates”, which are instantiated
to become true or false. But slowly, the subject of logic is emerging from its confused,
philosophical past. I consider that propositions are just boolean expressions and treat them on a
par with number expressions and expressions of other types. I consider that predicates are just
boolean functions. I use the same equal sign for booleans as for numbers, characters, sets, and
functions. Perhaps in the future we won't feel the need to imagine abstract objects for expressions
to denote; we will justify them by their practical applications. We will explain our formalisms by
the rules for their use, not by their philosophy.
11 Reference
202
Why bother with “antiaxioms” and “antitheorems”? They are not traditional (in fact, I made up the
words). As stated in Chapter 1, thanks to the negation operator and the Consistency Rule, we
don't need to bother with them. Instead of saying that expression is an antitheorem, we can say
that ¬expression is a theorem. Why bother with ? We could instead write ¬ . One reason
is just that it is shorter to say “antitheorem” than to say “negation of a theorem”. Another reason is
to help make clear the important difference between “disprovable” and “not provable”. Another
reason is that some logics do not use the negation operator and the Consistency Rule. The logic in
this book is “classical logic”; “constructive logic” omits the Completion Rule; “evaluation logic”
omits both the Consistency Rule and the Completion Rule.
Some books present proof rules (and axioms) with the aid of a formal notation. In this book, there
is no formal metalanguage; the metalanguage is English. A formal metalanguage is helpful for the
presentation and comparison of a variety of competing formalisms, and necessary for proving
theorems about formalisms. But in this book, only one formalism is presented. The burden of
learning another formalism first, for the purpose of presenting the main formalism, is unnecessary.
A formal metanotation for substitution would allow me to write the function application rule as
(λv· b) a = b[a/v]
but then I would have to explain that b[a/v] means “substitute a for v in b ”. I may as well say
directly
(λv· b) a = (substitute a for v in b )
A proof syntax (formalizing the “hints”) would be necessary if we were using an automated
prover, but in this book it is unnecessary and I have not introduced one.
Some authors may distinguish “axiom” from “axiom schema”, the latter having variables which
can be instantiated to produce axioms; I have used the term “axiom” for both. I have also used the
term “law” as a synonym for “theorem” (I would prefer to reduce my vocabulary, but both words
are well established). Other books may distinguish them by the presence or absence of variables,
or they may use “law” to mean “we would like it to be a theorem but we haven't yet designed an
appropriate theory”.
I have taken a few liberties with the names of some axioms and laws. What I have called
“transparency” is often called “substitution of equals for equals”, which is longer and doesn't quite
make sense. Each of my Laws of Portation is historically two laws, one an implication in one
direction, and the other an implication in the other direction. One was called “Importation”, and the
other “Exportation”, but I can never remember which was which.
End of Boolean Theory
11.0.2
Bunch Theory
Why bother with bunches? Don't sets work just as well? Aren't bunches really just sets but using
a peculiar notation and terminology? The answer is no, but let's take it slowly. Suppose we just
present sets. We want to be able to write {1, 3, 7} and similar expressions, and we might
describe these set expressions with a little grammar like this:
set = “{” contents “}”
contents = number
| set
| contents “,” contents
We will want to say that the order of elements in a set is irrelevant so that {1, 2} = {2, 1} ; the
best way to say it is formally: A,B = B,A (comma is symmetric, or commutative). Next, we
want to say that repetitions of elements in a set are irrelevant so that {3, 3} = {3} ; the best way to
203
11 Reference
say that is A,A = A (comma is idempotent). What we are doing here is inventing bunches, but
calling them “contents” of a set. And note that the grammar is equating bunches; the catenations
(denoted by juxtaposition) distribute over the elements of their operands, and the alternations (the
vertical bars) are bunch unions.
When a child first learns about sets, there is often an initial hurdle: that a set with one element is
not the same as the element. How much easier it would be if a set were presented as packaging: a
bag with an apple in it is obviously not the same as the apple. Just as {2} and 2 differ, so
{2,7} and 2,7 differ. Bunch Theory tells us about aggregation; Set Theory tells us about
packaging. The two are independent.
We could define sets without relying on bunches (as has been done for many years), and we could
use sets wherever I have used bunches. In that sense, bunches are unnecessary. Similarly we
could define lists without relying on sets (as I did in this book), and we could always use lists in
place of sets. In that sense, sets are unnecessary. But sets are a beautiful data structure that
introduces one idea (packaging), and I prefer to keep them. Similarly bunches are a beautiful data
structure that introduces one idea (aggregation), and I prefer to keep them. I always prefer to use
the simplest structure that is adequate for its purpose.
The subject of functional programming has suffered from an inability to express nondeterminism
conveniently. To say something about a value, but not pin it down completely, one can express
the set of possible values. Unfortunately, sets do not reduce properly to the deterministic case; in
this context it is again a problem that a set containing one element is not equal to the element. What
is wanted is bunches. One can always regard a bunch as a “nondeterministic value”.
Bunches have also been used in this book as a “type theory”. Surely it is discouraging to others,
as it is to me, to see type theory duplicating all the operators of its value space: for each operation
on values, there is a corresponding operation on type spaces. By using bunches, this duplication
is eliminated.
Many mathematicians consider that curly brackets and commas are just syntax, and syntax is
annoying and unimportant, though necessary. I have treated them as operators, with algebraic
properties (in Section 2.1 on Set Theory, we see that curly brackets have an inverse). This
continues a very long, historical trend. For example, = was at first just a syntax for the statement
that two things are (in some way) the same, but now it is an operator with algebraic properties.
End of Bunch Theory
11.0.3
String Theory
In many papers there is a little apology as the author explains that the notation for catenation of lists
will be abused by sometimes catenating a list and an item. Or perhaps there are three catenation
notations: one to catenate two lists, one to prepend an item to a list, and one to append an item to a
list. The poor author has to fight with unwanted packaging provided by lists in order to get the
sequencing. I offer these authors strings: sequencing without packaging. (Of course, they can be
packaged into lists whenever wanted. I am not taking away lists.)
End of String Theory
11 Reference
11.0.4
204
Function Theory
I have used the words “local” and “nonlocal” where others might use the words “bound” and
“free”, or “local” and “global”, or “hidden” and “visible”, or “private” and “public”. The tradition
in logic, which I have not followed, is to begin with all possible variables (infinitely many of them)
already “existing”. The function notation (λ) is said to “bind” variables, and any variable that is
not bound remains “free”. For example,
(λx: int· x+3) y
has bound variable x , free variable y , and infinitely many other free variables. In this book,
variables do not automatically “exist”; they are introduced (rather than bound) either formally
using the function notation, or informally by saying in English what they are.
The quantifier formed from max is called MAX even though its result may not be any result of
the function it is applied to; the name “least upper bound” is traditional. Similarly for MIN ,
which is traditionally called “greatest lower bound”.
I have ignored the traditional question of the “existence” of limits; in cases where traditionally a
limit does not “exist”, the Limit Axiom does not tell us exactly what the limit is, but it might still
tell us something useful.
End of Function Theory
11.0.5
Program Theory
Assignment could have been defined as
x:= e = defined “e” ∧ e: T ⇒ x′=e ∧ y′=y ∧ ...
where defined rules out expressions like 1/0 , and T is the type of variable x . I left out
defined because a complete definition of it is impossible, a reasonably complete definition is as
complicated as all of program theory, and it serves no purpose. The antecedent e: T would be
useful, making the assignment n:= n–1 implementable when n is a natural variable. But its
benefit does not pay for its trouble, since the same check is made at every dependent composition.
Since the design of Algol-60, sequential execution has often been represented by a semi-colon.
The semi-colon is unavailable to me for this purpose because I used it for string catenation.
Dependent composition is a kind of product, so I hope a period will be an acceptable symbol. I
considered switching the two, using semi-colon for dependent composition and a period for string
catenation, but the latter did not work well.
In English, the word “precondition” means “something that is necessary beforehand”. In many
programming books, the word “precondition” is used to mean “something that is sufficient
beforehand”. In those books, “weakest precondition” means “necessary and sufficient
precondition”, which I have called “exact precondition”.
In the earliest and still best-known theory of programming, we specify that variable x is to be
increased as follows:
{x = X} S {x > X}
We are supposed to know that x is a state variable, that X is a local variable to this specification
whose purpose is to relate the initial and final value of x , and that S is also local to the
specification and is a place-holder for a program. Neither X nor S will appear in a program that
refines this specification. Formally, X and S are quantified as follows:
§S· ∀X· {x = X} S {x > X}
205
11 Reference
In the theory of weakest preconditions, the equivalent specification looks similar:
§S· ∀X· x=X ⇒ wp S (x>X)
There are two problems with these notations. One is that they do not provide any way of referring
to both the prestate and the poststate, hence the introduction of X . This is solved in the Vienna
Development Method, in which the same specification is
§S· { } S {x′ > x}
The other problem is that the programming language and specification language are disjoint, hence
the introduction of S . In my theory, the programming language is a sublanguage of the
specification language. The specification that x is to be increased is
x′ > x
The same single-expression double-state specifications are used in Z, but refinement is rather
complicated. In Z, P is refined by S if and only if
∀σ· (∃σ′· P) ⇒ (∃σ′· S) ∧ (∀σ′· P ⇐ S)
In the early theory, §S· {P} S {Q} is refined by §S· {R} S {U} if and only if
∀σ· P ⇒ R ∧ (Q ⇐ U)
In my theory, P is refined by S if and only if
∀σ, σ′· P ⇐ S
Since refinement is what we must prove when programming, it is best to make refinement as
simple as possible.
One might suppose that any type of mathematical expression can be used as a specification:
whatever works. A specification of something, whether cars or computations, distinguishes those
things that satisfy it from those that don't. Observation of something provides values for certain
variables, and on the basis of those values we must be able to determine whether the something
satisfies the specification. Thus we have a specification, some values for variables, and two
possible outcomes. That is exactly the job of a boolean expression: a specification (of anything)
really is a boolean expression. If instead we use a pair of predicates, or a function from predicates
to predicates, or anything else, we make our specifications in an indirect way, and we make the
task of determining satisfaction more difficult.
One might suppose that any boolean expression can be used to specify any computer behavior:
whatever correspondence works. In Z, the expression
is used to specify (describe) terminating
computations, and
is used to specify (describe) nonterminating computations. The reasoning is
something like this:
is the specification for which there is no satisfactory final state; an infinite
computation is behavior for which there is no final state; hence
represents infinite computation.
Although we cannot observe a “final” state of an infinite computation, we can observe, simply by
waiting 10 time units, that it satisfies t′ > t+10 , and it does not satisfy t′ ≤ t+10 . Thus it ought to
satisfy any specification implied by t′ > t+10 , including
, and it ought not to satisfy any
specification that implies t′ ≤ t+10 , including
. Since
is not true of anything, it does not
describe anything. A specification is a description, and
is not satisfiable, not even by
nonterminating computations. Since
is true of everything, it describes everything, even
nonterminating computations. To say that P refines Q is to say that all behavior satisfying P
also satisfies Q , which is just implication. The correspondence between specifications and
computer behavior is not arbitrary.
As pointed out in Chapter 4, specifications such as x′=2 ∧ t′=∞ that talk about the “final” values
of variables at time infinity are strange. I could change the theory to prevent any mention of results
at time infinity, but I do not for two reasons: it would make the theory more complicated, and I
need to distinguish among infinite loops when I introduce interactions (Chapter 9).
End of Program Theory
11 Reference
11.0.6
206
Programming Language
The form of variable declaration given in Chapter 5 assigns the new local variable an arbitrary
value of its type. Thus, for example, if y and z are integer variables, then
var x: nat· y:= x = y′: nat ∧ z′=z
For ease of implementation and speed of execution, this is much better than initialization with “the
undefined value”. For error detection, it is no worse, assuming that we prove all our refinements.
Furthermore, there are circumstances in which arbitrary initialization is exactly what's wanted (see
Exercise 270 (majority vote)). However, if we do not prove all our refinements, initialization with
undefined provides a measure of protection. If we allow the generic operators ( = ,
, if then
else ) to apply to undefined , then we can prove trivialities like undefined = undefined . If not,
then we can prove nothing at all about undefined . Some programming languages seek to
eliminate the error of using an uninitialized variable by initializing each variable to a standard value
of its type. Such languages achieve the worst of all worlds: they are not as efficient as arbitrary
initialization; and they eliminate only the error detection, not the error.
The most widely known and used rule for while-loops is the Method of Invariants and Variants.
Let I be a precondition (called the “invariant”) and let I′ be the corresponding postcondition. Let
v be an integer expression (called the “variant” or “bound function”) and let v ′ be the
corresponding expression with primes on all the variables. The Rule of Invariants and Variants
says:
I ⇒ I′ ∧ ¬b′ ⇐ while b do I ∧ b ⇒ I′ ∧ 0≤v′<v
The rule says, very roughly, that if the body of the loop maintains the invariant and decreases the
variant but not below zero, then the loop maintains the invariant and negates the loop condition.
For example, to prove
s′ = s + Σ L [n;..#L] ⇐ while n #L do (s:= s + Ln. n:= n+1)
we must invent an invariant
s + Σ L [n;..#L] = ΣL
and a variant
#L – n
and prove both
s′ = s + Σ L [n;..#L]
⇐ s + Σ L [n;..#L] = ΣL ⇒ s′ + Σ L [n′;..#L] = ΣL ∧ n′=#L
and
s + Σ L [n;..#L] = ΣL ∧ n #L ⇒ s′ + Σ L [n′;..#L] = ΣL ∧ 0 ≤ #L – n′ < v
⇐ s:= s + Ln. n:= n+1
The proof method given in Chapter 5 is easier and more information (time) is obtained.
For probabilistic programming, my first approach was to reinterpret the types of variables as
probability distributions expressed as functions. If x was a variable of type T , it becomes a
variable of type T→prob such that Σx = Σx′ = 1 . All operators then need to be extended to
distributions expressed as functions. Although this approach works, it was too low-level; a
distribution expressed as a function tells us about the probability of its variables by their positions
in an argument list, rather than by their names.
207
11 Reference
The subject of programming has often been mistaken for the learning of a large number of
programming language “features”. This mistake has been made of both imperative and functional
programming. Of course, each fancy operator provided in a programming language makes the
solution of some problems easy. In functional programming, an operator called “fold” or “reduce”
is often presented; it is a useful generalization of some quantifiers. Its symbol might be / and it
takes as left operand a binary operator and as right operand a list. The list summation problem is
solved as +/L . The search problem could similarly be solved by the use of an appropriate search
operator, and it would be a most useful exercise to design and implement such an operator. This
exercise cannot be undertaken by someone whose only programming ability is to find an already
implemented operator and apply it. The purpose of this book is to teach the necessary
programming skills.
As our examples illustrate, functional programming and imperative programming are essentially the
same: the same problem in the two styles requires the same steps in its solution. They have been
thought to be different for the following reasons: imperative programmers adhere to clumsy loop
notations, complicating proofs; functional programmers adhere to equality, rather than refinement,
making nondeterminism difficult.
End of Programming Language
11.0.7
Recursive Definition
The combination of construction and induction is so beautiful and useful that it has a name
(generation) and a notation ( ::= ). To keep terminology and notation to a minimum, I have not
used them.
Recursive construction has always been done by taking the limit of a sequence of approximations.
My innovation is to substitute ∞ for the index in the sequence; this is a lot easier than finding a
limit. Substituting ∞ is not guaranteed to produce the desired fixed-point, but neither is finding
the limit. Substituting ∞ works well except in examples contrived to show its limitation.
End of Recursive Definition
11.0.8
Theory Design and Implementation
I used the term “data transformation” instead of the term “data refinement” used by others. I don't
see any reason to consider one space more “abstract” and another more “concrete”. What I call a
“data transformer” is sometimes called “abstraction relation”, “linking invariant”, “gluing relation”,
“retrieve function”, or “data invariant”.
The incompleteness of data transformation is demonstrated with an example carefully crafted to
show the incompleteness, not one that would ever arise in practice. I prefer to stay with the simple
rule that is adequate for all transformations that will ever arise in any problem other than a
demonstration of theoretical incompleteness, rather than to switch to a more complicated rule, or
combination of rules, that are complete. To regain completeness, all we need is the normal
mathematical practice of introducing local variables. Variables for this purpose have been called
“bound variables”, “logical constants”, “specification variables”, “ghost variables”, “abstract
variables”, and “prophesy variables”, by different authors.
End of Theory Design and Implementation
11 Reference
11.0.9
208
Concurrency
In FORTRAN (prior to 1977) we could have a sequential composition of if-statements, but we
could not have an if-statement containing a sequential composition. In ALGOL the syntax was
fully recursive; sequential and conditional compositions could be nested, each within the other.
Did we learn a lesson? Apparently we did not learn a very general one: we now seem happy to
have a parallel composition of sequential compositions, but very reluctant to have a sequential
composition of parallel compositions. So in currently popular languages, a parallel composition
can occur only as the outermost construct.
As we saw in Chapter 8, the execution pattern
A
C
B
D
can be expressed as ((A || B). (C || D)) without any synchronization primitives. But the pattern
A
C
B
D
cannot be expressed using only parallel and sequential composition. This pattern occurs in the
buffer program.
In the first edition of this book, parallel composition was defined for processes having the same
state space (semi-dependent composition). That definition was more complicated than the present
one (see Exercise 378), but in theory, it eliminated the need to partition the variables. In practice,
however, the variables were always partitioned, so in the present edition the simpler definition
(independent composition) is used.
nd of Concurrency
11.0.10
Interaction
In the formula for implementability, there is no conjunct r′ ≤ w′ saying that the read cursor must
not get ahead of the write cursor. In Subsection 9.1.8 on deadlock we see that it can indeed
happen. Of course, it takes infinite time to do so. In the deadlock examples, we can prove that the
time is infinite. But there is a mild weakness in the theory. Consider this example.
chan c· t:= max t (Tr + 1). c?
= ∃M, T, r, r′, w, w′· t′ = max t (Tr + 1) ∧ r′=1 ∧ w′=0
= t′ ≥ t
We might like to prove t′=∞ . To get this answer, we must strengthen the definition of local
channel declaration by adding the conjunct T w′ ≥ t′ . I prefer the simpler, weaker theory.
End of Interaction
We could talk about a structure of channels, and about indexed processes. We could talk about a
parallel for-loop. There is always something more to say, but we have to stop somewhere.
End of Justifications
209
11 Reference
11.1 Sources
Ideas do not come out of nowhere. They are the result of one's education, one's culture, and
one's interactions with acquaintances. I would like to acknowledge all those people who have
influenced me and enabled me to write this book. I will probably fail to mention people who have
influenced me indirectly, even though the influence may be strong. I may fail to thank people who
gave me good ideas on a bad day, when I was not ready to understand. I will fail to give credit to
people who worked independently, whose ideas may be the same as or better than those that
happened to reach my eyes and ears. To all such people, I apologize. I do not believe anyone can
really take credit for an idea. Ideally, our research should be done for the good of everyone,
perhaps also for the pleasure of it, but not for the personal glory. Still, it is disappointing to be
missed. Here then is the best accounting of my sources that I can provide.
The early work in this subject is due to Alan Turing (1949), Peter Naur (1966), Robert Floyd
(1967), Tony Hoare (1969), Rod Burstall (1969), and Dana Scott and Christopher Strachey
(1970). (See the Bibliography, which follows.) My own introduction to the subject was a book
by Edsger Dijkstra (1976); after reading it I took my first steps toward formalizing refinement
(1976). Further steps in that same direction were taken by Ralph Back (1978), though I did not
learn of them until 1984. The first textbooks on the subject began to appear, including one by me
(1984). That work was based on Dijkstra's weakest precondition predicate transformer, and work
continues today on that same basis. I highly recommend the book Refinement Calculus by Ralph
Back and Joachim vonWright (1998).
In the meantime, Tony Hoare (1978, 1981) was developing communicating sequential processes.
During a term at Oxford in 1981 I realized that they could be described as predicates, and published
a predicate model (1981, 1983). It soon became apparent that the same sort of description, a single
boolean expression, could be used for any kind of computation, and indeed for anything else; in
retrospect, it should have been obvious from the start. The result was a series of papers (1984,
1986, 1988, 1989, 1990, 1994, 1998, 1999) leading to the present book.
The importance of format in expressions and proofs was made clear to me by Netty van Gasteren
(1990). The symbols ¢ and $ for bunch and set cardinality were suggested by Chris Lengauer.
The word “conflation” was suggested by Doug McIlroy. The value of indexing from 0 was
taught to me by Edsger Dijkstra. Joe Morris and Alex Bunkenburg (2001) found and fixed a
problem with bunch theory. The word “apposition” and the idea to which it applies come from
Lambert Meertens (1986). Alan Rosenthal suggested that I stop worrying about when limits
“exist”, and just write the axioms describing them; I hope that removes the last vestige of
Platonism from the mathematics, though some remains in the English. My Refinement by Parts
law was made more general by Theo Norvell. I learned the use of a timing variable from Chris
Lengauer (1981), who credits Mary Shaw; we were using weakest preconditions then, so our time
variables ran down instead of up. The recursive measure of time is inspired by the work of Paul
Caspi, Nicolas Halbwachs, Daniel Pilaud, and John Plaice (1987); in their language LUSTRE,
each iteration of a loop takes time 1 , and all else is free. I learned to discount termination by
itself, with no time bound, in discussions with Andrew Malton, and from an example of Hendrik
Boom (1982). I was told the logarithmic solution to the Fibonacci number problem by Wlad
Turski, who learned it while visiting the University of Guelph. My incorrect version of local
variable declaration was corrected by Andrew Malton. Local variable suspension is adapted from
Carroll Morgan (1990). The for-loop rule was influenced by Victor Kwan and Emil Sekerinski.
The backtracking implementation of unimplementable specifications comes from Greg Nelson
(1989). Carroll Morgan and Annabelle McIver (1996) suggested probabilities as observable
11 Reference
210
quantities, and Exercise 284 (Mr.Bean's socks) comes from them. The use of bunches for
nondeterminism in functional programming and for function refinement is joint work with Theo
Norvell (1992). Theo also added the timing to the recursive definition of while-loops (1997).
The style of data-type theories (data-stack, data-queue, data-tree) comes from John Guttag and Jim
Horning (1978). The implementation of data-trees was influenced by Tony Hoare (1975). Some
details of the program-tree theory are due to Theo Norvell. I learned about data transformation
from He Jifeng and Carroll Morgan, based on earlier work by Tony Hoare (1972); the formulation
here is my own, but I checked it for equivalence with those in Wei Chen and Jan Tijmen Udding
(1989). Theo Norvell provided the criterion for data transformers. The second data
transformation example (take a number) is adapted from a resource allocation example of Carroll
Morgan (1990). The final data transformation example showing incompleteness was invented by
Paul Gardiner and Carroll Morgan (1993). For an encyclopedic treatment of data transformers, see
the book by Willem-Paul deRoever and Kai Engelhardt (1998). I published various formulations
of independent (parallel) composition (1981, 1984, 1990, 1994); the one in the first edition of this
book is due to Theo Norvell and appears in this edition as Exercise 378 (semi-dependent
composition), and is used in recent work by Hoare and He (1998); for this edition I was
persuaded by Leslie Lamport to return to my earlier (1990) version: simple conjunction. Section
8.1 on sequential to parallel transformation is joint work with Chris Lengauer (1981); he has since
made great advances in the automatic production of highly parallel, systolic computations from
ordinary sequential, imperative programs. The thermostat example is a simplification and
adaptation of a similar example due to Anders Ravn, Erling Sørensen, and Hans Rischel (1990).
The form of communication was influenced by Gilles Kahn (1974). Time scripts were suggested
by Theo Norvell. The input check is an invention of Alain Martin (1985), which he called the
“probe”. Monitors were invented by Per Brinch Hansen (1973) and Tony Hoare (1974). The
power series multiplication is from Doug McIlroy (1990), who credits Gilles Kahn. Many of the
exercises were given to me by Wim Feijen for my earlier book (1984); they were developed by
Edsger Dijkstra, Wim Feijen, Netty van Gasteren, and Martin Rem for examinations at the
Technical University of Eindhoven; they have since appeared in a book by Edsger Dijkstra and
Wim Feijen (1988). Some exercises come from a series of journal articles by Martin Rem
(1983,..1991). Other exercises were taken from a great variety of sources too numerous to
mention.
End of Sources
211
11 Reference
11.2 Bibliography
R.-J.R.Back: “on the Correctness of Refinement Steps in Program Development”, University of
Helsinki, Department of Computer Science, Report A-1978-4, 1978
R.-J.R.Back: “a Calculus of Refinement for Program Derivations”, Acta Informatica, volume 25,
pages 593,..625, 1988
R.-J.R.Back, J.vonWright: Refinement Calculus: a Systematic Introduction, Springer, 1998
H.J.Boom: “a Weaker Precondition for Loops”, ACM Transactions on Programming Languages
and Systems, volume 4, number 4, pages 668,..678, 1982
P.BrinchHansen: “Concurrent Programming Concepts”, ACM Computing Surveys, volume 5,
pages 223,..246, 1973 December
R.Burstall: “Proving Properties of Programs by Structural Induction”, University of Edinburgh,
Report 17 DMIP, 1968; also Computer Journal, volume 12, number 1, pages 41,..49, 1969
P.Caspi, N.Halbwachs, D.Pilaud, J.A.Plaice: “LUSTRE: a Declarative Language for
Programming Synchronous Systems”, fourteenth annual ACM Symposium on Principles of
Programming Languages, pages 178,..189, Munich, 1987
K.M.Chandy, J.Misra: Parallel Program Design: a Foundation, Addison-Wesley, 1988
W.Chen, J.T.Udding: “Toward a Calculus of Data Refinement”, J.L.A.van de Snepscheut
(editor): Mathematics of Program Construction, Springer-Verlag, Lecture Notes in Computer
Science, volume 375, pages 197,..219, 1989
E.W.Dijkstra: “Guarded Commands, Nondeterminacy, and Formal Derivation of Programs”,
Communications ACM, volume 18, number 8, pages 453,..458, 1975 August
E.W.Dijkstra: a Discipline of Programming, Prentice-Hall, 1976
E.W.Dijkstra, W.H.J.Feijen: a Method of Programming, Addison-Wesley, 1988
R.W.Floyd: “Assigning Meanings to Programs”, Proceedings of the American Society,
Symposium on Applied Mathematics, volume 19, pages 19,..32, 1967
P.H.B.Gardiner, C.C.Morgan: “a Single Complete Rule for Data Refinement”, Formal Aspects of
Computing, volume 5, number 4, pages 367,..383, 1993
A.J.M.vanGasteren: “on the Shape of Mathematical Arguments”, Springer-Verlag Lecture Notes in
Computer Science, 1990
J.V.Guttag, J.J.Horning: “the Algebraic Specification of Abstract Data Types”, Acta Informatica,
volume 10, pages 27,..53, 1978
11 Reference
212
E.C.R.Hehner: “do considered od: a Contribution to the Programming Calculus”, University of
Toronto, Technical Report CSRG-75, 1976 November; also Acta Informatica, volume 11, pages
287,..305, 1979
E.C.R.Hehner: “Bunch Theory: a Simple Set Theory for Computer Science”, University of
Toronto, Technical Report CSRG-102, 1979 July; also Information Processing Letters, volume
12, number 1, pages 26,..31, 1981 February
E.C.R.Hehner, C.A.R.Hoare: “a More Complete Model of Communicating Processes”,
University of Toronto, Technical Report CSRG-134, 1981 September; also Theoretical Computer
Science, volume 26, numbers 1 and 2, pages 105,..121, 1983 September
E.C.R.Hehner: “Predicative Programming”, Communications ACM, volume 27, number 2, pages
134,..152, 1984 February
E.C.R.Hehner: the Logic of Programming, Prentice-Hall International, 1984
E.C.R.Hehner, L.E.Gupta, A.J.Malton: “Predicative Methodology”, Acta Informatica, volume
23, number 5, pages 487,..506, 1986
E.C.R.Hehner, A.J.Malton: “Termination Conventions and Comparative Semantics”, Acta
Informatica, volume 25, number 1, pages 1,..15, 1988 January
E.C.R.Hehner: “Termination is Timing”, International Conference on Mathematics of Program
Construction, The Netherlands, Enschede, 1989 June; also J.L.A.van de Snepscheut (editor):
Mathematics of Program Construction, Springer-Verlag, Lecture Notes in Computer Science
volume 375, pages 36,..48, 1989
E.C.R.Hehner: “a Practical Theory of Programming”, Science of Computer Programming, volume
14, numbers 2 and 3, pages 133,..159, 1990
E.C.R.Hehner: “Abstractions of Time”, a Classical Mind, chapter 12, Prentice-Hall, 1994
E.C.R.Hehner: “Formalization of Time and Space”, Formal Aspects of Computing, volume 10,
pages 290,..307, 1998
E.C.R.Hehner, A.M.Gravell: “Refinement Semantics and Loop Rules”, FM'99 World Congress
on Formal Methods, pages 20,..25, Toulouse France, 1999 September
E.C.R.Hehner: “Specifications, Programs, and Total Correctness”, Science of Computer
Programming volume 34, pages 191,..206, 1999
C.A.R.Hoare: “an Axiomatic Basis for Computer Programming”, Communications ACM, volume
12, number 10, pages 576,..581, 583, 1969 October
C.A.R.Hoare: “Proof of Correctness of Data Representations”, Acta Informatica, volume 1,
number 4, pages 271,..282, 1972
C.A.R.Hoare: “Monitors: an Operating System Structuring Concept”, Communications ACM,
volume 17, number 10, pages 549,..558, 1974 October
213
11 Reference
C.A.R.Hoare: “Recursive Data Structures”, International Journal of Computer and Information
Sciences, volume 4, number 2, pages 105,..133, 1975 June
C.A.R.Hoare: “Communicating Sequential Processes”, Communications ACM, volume 21,
number 8, pages 666,..678, 1978 August
C.A.R.Hoare: “a Calculus of Total Correctness for Communicating Processes”, Science of
Computer Programming, volume 1, numbers 1 and 2, pages 49,..73, 1981 October
C.A.R.Hoare: “Programs are Predicates”, in C.A.R.Hoare, J.C.Shepherdson (editors):
Mathematical Logic and Programming Languages, Prentice-Hall Intenational, pages 141,..155,
1985
C.A.R.Hoare, I.J.Hayes, J.He, C.C.Morgan, A.W.Roscoe, J.W.Sanders, I.H.Sørensen,
J.M.Spivey, B.A.Sufrin: “the Laws of Programming”, Communications ACM, volume 30,
number 8, pages 672,..688, 1987 August
C.A.R.Hoare, J.He: Unifying Theories of Programming, Prentice-Hall, 1998
C.B.Jones: Software Development: a Rigorous Approach, Prentice-Hall International, 1980
C.B.Jones: Systematic Software Development using VDM, Prentice-Hall International, 1990
G.Kahn: “the Semantics of a Simple Language for Parallel Programming, Information Processing
74, North-Holland, Proceeding of IFIP Congress, 1974
C.Lengauer, E.C.R.Hehner: “a Methodology for Programming with Concurrency”, CONPAR 81,
Nürnberg, 1981 June 10,..13; also Springer-Verlag, Lecture Notes in Computer Science volume
111, pages 259,..271, 1981 June; also Science of Computer Programming, volume 2, pages
1,..53 , 1982
A.J.Martin: “the Probe: an Addition to Communication Primitives”, Information Processing
Letters, volume 20, number 3, pages 125,..131, 1985
J.McCarthy: “a Basis for a Mathematical Theory of Computation”, Proceedings of the Western
Joint Computer Conference, pages 225,..239, Los Angeles, 1961 May; also Computer
Programming and Formal Systems, North-Holland, pages 33,..71, 1963
M.D.McIlroy: “Squinting at Power Series”, Software Practice and Experience, volume 20, number
7, pages 661,..684, 1990 July
L.G.L.T.Meertens: “Algorithmics — towards Programming as a Mathematical Activity”,
Proceedings of CWI Symposium on Mathematics and Computer Science, North-Holland, CWI
Monographs, volume 1, pages 289,..335, 1986
C.C.Morgan: “the Specification Statement”, ACM Transactions on Programming Languages and
Systems, volume 10, number 3, pages 403,..420, 1988 July
C.C.Morgan: Programming from Specifications, Prentice-Hall International, 1990
11 Reference
214
C.C.Morgan, A.K.McIver, K,Seidel, J.W.Sanders: “Probabilistic Predicate Transformers”, ACM
Transactions on Programming Languages and Systems, volume 18, number 3, pages 325,..354,
1996 May
J.M.Morris: “a Theoretical Basis for Stepwise Refinement and the Programming Calculus”,
Science of Computer Programming, volume 9, pages 287,..307, 1987
J.M.Morris, A.Bunkenburg: “a Theory of Bunches”, Acta Informatica, volume 37, number 8,
pages 541,..563, 2001 May
P.Naur: “Proof of Algorithms by General Snapshots”, BIT, volume 6, number 4, pages
310,..317, 1966
G.Nelson: “a Generalization of Dijkstra's Calculus”, ACM Transactions on Programming
Languages and Systems, volume 11, number 4, pages 517,..562, 1989 October
T.S.Norvell: “Predicative Semantics of Loops”, Algorithmic Languages and Calculi, ChapmanHall, 1997
T.S.Norvell, E.C.R.Hehner: “Logical Specifications for Functional Programs”, International
Conference on Mathematics of Program Construction, Oxford, 1992 June
A.P.Ravn, E.V.Sørensen, H.Rischel: “Control Program for a Gas Burner”, Technical University
of Denmark, Department of Computer Scence, 1990 March
M.Rem: “Small Programming Exercises”, articles in Science of Computer Programming,
1983,..1991
W.-P.deRoever, K.Engelhardt: Data Refinement: Model-Oriented Proof Methods and their
Comparisons, tracts in Theoretical Computer Science volume 47, Cambridge University Press,
1998
D.S.Scott, C.Strachey: “Outline of a Mathematical Theory of Computation”, technical report PRG2, Oxford University, 1970; also Proceedings of the fourth annual Princeton Conference on
Information Sciences and Systems, pages 169,..177, 1970
K.Seidel, C.Morgan, A.K.McIver: “an Introduction to Probabilistic Predicate Transformers”,
technical report PRG-TR-6-96, Oxford University, 1996
J.M.Spivey: the Z Notation – a Reference Manual, Prentice-Hall International, 1989
A.M.Turing: “Checking a Large Routine”, Cambridge University, Report on a Conference on
High Speed Automatic Calculating Machines, pages 67,..70, 1949
End of Bibliography
215
11 Reference
11.3 Index
abstract space 207
variable 207
abstraction relation 207
Ackermann 173
algebra, bracket 153
linear 189
alias 81
all present 168
almost sorted segment 174
alternating sum 166
antecedent 3
antiaxiom 6, 202
antimonotonic 9
antitheorem 3, 202
application 24
apposition 31
approximate search 171
argument 24, 80
arithmetic 12, 174
arity 157
array 22, 68
element assignment 68
sparse 193
assertion 77
assignment 36
array element 68
initializing 67
nondeterministic 177
average 83
space 64
axiom 6
rule 5
schema 202
backtracking 77
Backus-Naur Form 185
batch processing 134
binary 3
decision diagram 149
exponentiation 167, 45
logarithm natural 169
search 53, 167
tree 192
bit sum 171
bitonic list 158
blackjack 85, 180
body 23
Boole's booleans 180
boolean 3
booleans, Boole's 180
bound function 206
greatest lower 204
least upper 204
time 47, 61
unbounded 178
variable 204, 207
boundary variable 126, 131
bracket algebra 153
brackets 188
break 71
broadcast 141
Brock-Ackermann 199
buffer 122
bunch 14, 202
elementary 14
empty 15
busy-wait loop 76
call-by-value-result 179
Cantor's diagonal 181
heaven 155
cardinality 14
cases, refinement by 43
caskets 152
catenation 17, 156
list 20
channel 131
declaration 138
character 13, 15
check, input 133
parity 171
circular list 189
numbers 152
classical logic 202
clock 76
closure, transitive 172
code, Huffman 197
coin 180
weights 197
combination 166
next 169
command, guarded 179
common divisor, greatest 175
item, smallest 175
items 175
multiple, least 175
prefix, longest 176
11 Reference
communication 131
synchronous 200
comparison list 166
compiler 45
complete 5, 101
completeness 51, 117
completion rule 5, 6
composite number 154
composition conditional 4
dependent 36, 127
disjoint 194
function 31
independent 118, 119, 126
list 20
semi-dependent 194
computing constant 36
interactive 134
variable 36
concrete space 207
concurrency 118
list 120
condition 40
final 40
initial 40
conditional composition 4
conjunct 3
conjunction 3
consensus 197
consequent 3
consistency rule 5, 6
consistent 5, 101
constant 23
computing 36
logical 207
mathematical 36
state 36
construction 16, 91
fixed-point 94
recursive data 95
recursive program 98
constructive logic 202
constructors 91
context 10
continuing 7, 9
contradiction 10
control process 134
controlled iteration 74
controller, reaction 137
convex equal pair 168
216
count, duplicate 174
inversion 171
item 174
segment sum 170
two-dimensional sorted 168
cube 165
test 166
cursor, read 131
write 131
data construction, recursive 95
invariant 207
refinement 207
structure 14
structures 100
transformation 111
transformation, interactive 196
transformer 111
deadlock 124, 139
decimal-point numbers 185
declaration, channel 138
variable 66
dependent composition 35, 127
detachment 6
deterministic 89
function 29
specification 35
diagonal 170
Cantor's 181
dice 86, 180
difference, minimum 171
digit sum 171
digitizer 137
diminished J-list 175
dining philosophers 124, 195
disjoint composition 194
disjunct 3
disjunction 3
distribute 15
distribution, probability 82
division, machine 174
natural 169
divisor, greatest common 175
domain 23
drunk 181
dual 148
duplicate count 174
earliest meeting time 166
quitter 171
edit distance 174
217
element 14
assignment, array 68
elementary bunch 14
empty bunch 15
set 17
string 17
entropy 87
equation 4
evaluation logic 202
rule 5, 6
exact postcondition 40
precondition 40
precondition for termination 166
exclusion, mutual 200
execution, sequential 36
time 60
existence 204
existential quantification 26
exit 71
exponentiation, binary 45, 167
fast 57, 167
expression 13
extended integers 15
naturals 15
rationals 15
reals 15
factor 155
count 169
factorial 164
family theory 154
fast exponentiation 57. 167
Fermat's last program 170
Fibolucci 173
Fibonacci 59, 173, 183
file update 200
final condition 40
state 34
fixed-point 94, 168
construction 94
induction 94
least 94
theorem 182
flatten 170
follows from 3
formal 12
format, proof 7
frame 67
problem 178
free 204
friends 158
11 Reference
function 23, 79, 80
bound 206
composition 31
deterministic 29
higher-order 30
inclusion 30
nondeterministic 29
partial 29
refinement 89
retrieve 207
total 29
functional programming 88, 90
fuzzybunch 154
gas burner 128, 136, 196
general recursion 76
generation 207
generator, random number 84
generic 13
ghost variables 207
gluing relation 207
go to 45, 71, 76
Gödel/Turing incompleteness 159
grammar 94
greatest common divisor 175
lower bound 204
square under a histogram 177
subsequence 171
grow slow 196
guarded command 179
heads and tails 171
heap 189
hidden variable 204
higher-order function 30
Huffman code 197
hyperbunch 154
idempotent permutation 169
imperative programming 88, 90
implementable 34, 35, 89, 132, 127
implementation, input 198
implemented specification 41
implementer's variables 106
implication 3
inclusion 14
function 30
incomplete 5
incompleteness, Gödel/Turing 159
transformation 193
inconsistent 5
independent composition 118, 119, 126
probability 82
11 Reference
index 18
list 20
induction 16, 91
fixed-point 94
proof by 93
infinity 12
infix 3
information 87
initial condition 40
state 34
initializing assignment 67
input 133
check 133
implementation 198
insertion list 190
sort 123
instance rule 5
instantiation 4
integer numbers 15
integers, extended 15
interactive computing 134
data transformation 196
variable 126, 131
intersection 14
interval union 171
invariant 75, 206
data 207
linking 207
inverse permutation 169
inversion count 171
item 17
count 174
maximum 120
smallest common 175
items, common 175
unique 175
iteration, controlled 74
J-list 175
knights and knaves 151
Knuth, Morris, Pratt 177
largest true square 175
law 7
substitution 38
least common multiple 175
fixed-point 94
upper bound 204
left side 4
length list 20
string 17
text 168
218
lexicographic order 18
limit 32
limited queue 115, 192
linear algebra 189
search 51, 167
linking invariant 207
list 14, 20
bitonic 158
catenation 20
circular 189
comparison 166
composition 20
concurrency 120
diminished J- 175
index 20
insertion 190
J- 175
length 20
next sorted 169
P- 175
summation 43, 67, 88, 166
T- 197
Thue 197
local 25
minimum 169
logarithm natural binary 169
logic 3
classical 202
constructive 202
evaluation 202
logical constants 207
long texts 177
longest balanced segment 170
common prefix 176
palindrome 170
plateau 170
smooth segment170
sorted sublist 174
loop 48, 69
busy-wait 76
lower bound, greatest 204
machine division 174
multiplication 174
squaring 174
maid and butler 151
majority vote 179
mathematical constant 36
variable 36
matrix multiplication 197
219
maximum item 120, 166
product segment 170
space 63
McCarthy's 91 problem 172
memory variables 46
merge 135, 174
time 199
message script 131
metalanguage 202
minimum difference 171
local 169
sum segment 170
missing number 168
model-checking 1
modification, program 57
modus ponens 6
monitor 136, 138
monotonic 9
Mr.Bean's socks 181
multibunch 154
multidimensional 22
multiple, least common 175
multiplication, machine 174
matrix 197
table 167
museum 176
mutual exclusion 200
natural binary logarithm 169
division 169
numbers 15
square root 169
naturals, extended 15
necessary postcondition 40
precondition 40
negation 3
next combination 169
permutation 169
sorted list 169
nondeterministic 89
assignment 177
function 29
specification 35
nonlocal 25
notation 201
nullary 3
number 12
composite 154
generator, random 84
missing 168
11 Reference
numbers, circular 152
decimal-point 185
Fibonacci 59
integer 15
natural 15
rational 15
real 15
von Neumann 155
one-point 28
operand 3
operator 3
order lexicographic 18
prefix 156
ordered pair search 168
output 133
P-list 175
package 14
pair search, ordered 168
palindrome, longest 170
parallelism 118
parameter 24, 79, 80
reference 80, 81
parity check 171
parking 151
parsing 108, 190
partial function 29
partition 118
partitions 175
parts, refinement by 43
party 190
Pascal's triangle 167
path, shortest 172
pattern search 168
perfect shuffle 198
periodic sequence, ultimately 175
permutation, idempotent 169
inverse 169
next 169
pigeon-hole 159
pivot 171
pointer 22, 81, 105
polynomial 166
postcondition 40
exact 40
necessary 40
sufficient 40
postspecification, weakest 163
poststate 34
power series 141, 199
powerset 17
11 Reference
precedence 4, 5
precondition 40, 204
exact 40
necessary 40
sufficient 40
weakest 204
predecessor 13
predicate 24
prefix 3
longest common 176
order 156
prespecification, weakest 163
prestate 34
private variable 204
probability 82
distribution 82
independent 82
uniform 84
problem, frame 178
process 118
control 134
processing, batch 134
program 41
construction, recursive 98
modification 57
programming, functional 88, 90
programming, imperative 88, 90
proof 7
by induction 93
format 7
rule 5
prophesy variable 207
proposition 201
public variable 204
quantification, existential 26
universal 26
quantifier 26
queue 103, 108, 188
limited 115, 192
quitter, earliest 171
random number generator 84
range 23
rational numbers 15
rationals, extended 15
reachability 172
reaction controller 137
read cursor 131
real 33
numbers 15
time 46
220
reals, extended 15
record 69
recursion 42
general 76
tail 76
recursive data construction 95
program construction 98
time 48
reference parameter 80, 81
refinement 39
by cases 43
by parts 43
by steps 43
data 207
function 89
stepwise 43
reformat 197
reification 204
relation 24
abstraction 207
gluing 207
transitive 161
remainder 169
renaming 24
repetition 199
resettable variable 189
retrieve function 207
reverse 169
right side 4
roll up 161
roller coaster 60, 173
root, natural square 169
rotation, smallest 176
test 176
rule, completion 5, 6
consistency 5, 6
evaluation 5, 6
instance 5
proof 5
rulers 182
running total 165, 195
Russell's barber 159
paradox 159
satisfiable 35, 89
scale 152
schema, axiom 202
scope 23, 66
script, message 131
time 131
221
search, approximate 171
binary 167, 53
linear 167, 51
ordered pair 168
pattern 168
sorted two-dimensional 168
ternary 167
two-dimensional 167
two-dimensional 72
security switch 112, 191
segment 21
almost sorted 174
longest balanced 170
longest smooth 170
maximum product 170
minimum sum 170
sum count 170
selective union 24
self-describing 21
self-reproducing 21
semi-dependent composition 194
sentence 201
sentinel 52
sequence, ultimately periodic 175
sequential execution 36
series, power 141, 199
set 14, 17
empty 17
shared variable 131, 136
shortest path 172
shuffle, perfect 198
side-effect 79
sieve 195
signal 133
size 14
slip 188
smallest common item 175
rotation 176
socks, Mr.Bean's 181
solution 27
sort, insertion 123
test 167
sorted list, next 169
segment, almost 174
sublist, longest 174
two-dimensional count 168
two-dimensional search 168
soundness 51, 117
11 Reference
space 61, 129
abstract 207
average 64
concrete 207
maximum 63
state 34
sparse array 193
specification 34
deterministic 35
implemented 41
nondeterministic 35
transitive 161
variable 207
square 164
greatest under a histogram 177
largest true 175
root, natural 169
squaring, machine 174
stack 100, 106, 187, 188
state 34
constant 36
final 34
initial 34
space 34
variable 34, 36
steps, refinement by 43
stepwise refinement 43
string 14, 17, 184
empty 17
length 17
stronger 3, 9
structure 69
data 14, 100
sublist 21
longest sorted 174
subscript 18
substitution 4, 25
law 38
successor 13, 23
sufficient postcondition 40
precondition 40
sum, alternating 166
bit 171
digit 171
summation, list 43, 67, 88, 166
suspension, variable 67
swapping partners 158
switch, security 112, 191
synchronizer 137
synchronous communication 200
11 Reference
T-list 197
tail recursion 76
take a number 192
telephone 196
tennis 151
termination 34, 50
exact precondition for 166
term 201
ternary 4
search 167
testing 145
text 21
length 168
long 177
theorem 3
thermostat 128, 136, 196
Thue list 197
time 46
bound 47, 61
execution 60
merge 199
real 46
recursive 48
script 131
transit 134
variable 46
timeout 198
total function 29
Towers of Hanoi 61, 172
transformation, data 111
incompleteness 193
interactive data 196
transformer, data 111
transit time 134
transitive closure 172
relation 161
specification 161
tree 104, 108, 189, 190
binary 192
truth table 3, 4
two-dimensional search 72, 167
search, sorted 168
ultimately periodic sequence 175
unary 3
unbounded bound 178
undefined value 66
unequation 4
unexpected egg 152
unicorn 159
222
uniform probability 84
union 14
interval 171
selective 24
unique items 175
universal quantification 26
unsatisfiable 35, 89
update, file 200
upper bound, least 204
user's variables 106
value, undefined 66
variable 4, 23
abstract 207
bound 204, 207
boundary 126, 131
computing 36
declaration 66
ghost 207
hidden 204
implementer's 106
interactive 126, 131
mathematical 36
memory 46
private 204
prophesy 207
public 204
resettable 189
shared 131, 136
specification 207
state 34, 36
suspension 67
time 46
user's 106
visible 204
variant 206
visible variable 204
von Neumann numbers 155
vote, majority 179
wait 76
weaker 3, 9
weakest postspecification 163
precondition 204
prespecification 163
whodunit 157
wholebunch 154
widget 187
write cursor 131
z-free subtext 174
Zeno 165
End of Index
223
11 Reference
11.4 Laws
11.4.0
Booleans
Let a , b , c , d , and e be boolean.
Boolean Axioms
¬
Law of Excluded Middle (Tertium non Datur)
a ∨ ¬a
Law of Contradiction
¬(a ∧ ¬a)
Base Laws
¬(a ∧ )
a∨
a⇒
⇒a
Identity Laws
∧a = a
∨a = a
⇒a = a
=a = a
Idempotent Laws
a∧a = a
a∨a = a
Reflexive Laws
a⇒a
a=a
Law of Double Negation
¬¬a = a
Duality Laws (deMorgan)
¬(a ∧ b) = ¬a ∨ ¬b
¬(a ∨ b) = ¬a ∧ ¬b
Laws of Exclusion
a ⇒ ¬b = b ⇒ ¬a
a = ¬b = b = ¬a
Laws of Inclusion
a ⇒ b = ¬a ∨ b (Material Implication)
a ⇒ b = (a ∧ b = a)
a ⇒ b = (a ∨ b = b)
Absorption Laws
a ∧ (a ∨ b)
a ∨ (a ∧ b)
=a
=a
Laws of Direct Proof
(a ⇒ b) ∧ a ⇒ b
(Modus Ponens)
(a ⇒ b) ∧ ¬b ⇒ ¬a (Modus Tollens)
(a ∨ b) ∧ ¬a ⇒ b(Disjunctive Syllogism)
Transitive Laws
(a ∧ b) ∧ (b ∧ c) ⇒ (a ∧ c)
(a ⇒ b) ∧ (b ⇒ c) ⇒ (a ⇒ c)
(a = b) ∧ (b = c) ⇒ (a = c)
(a ⇒ b) ∧ (b = c) ⇒ (a ⇒ c)
(a = b) ∧ (b ⇒ c) ⇒ (a ⇒ c)
Laws of Indirect Proof
¬a ⇒ = a (Reductio ad Absurdum)
¬a ⇒ a = a
Distributive Laws (Factoring)
a ∧ (b ∧ c) = (a ∧ b) ∧ (a ∧ c)
Law of Specialization
a ∧ (b ∨ c) = (a ∧ b) ∨ (a ∧ c)
a∧b⇒a
a ∨ (b ∧ c) = (a ∨ b) ∧ (a ∨ c)
a ∨ (b ∨ c) = (a ∨ b) ∨ (a ∨ c)
Associative Laws
a ∨ (b ⇒ c) = (a ∨ b) ⇒ (a ∨ c)
a ∧ (b ∧ c) = (a ∧ b) ∧ c
a ∨ (b = c) = (a ∨ b) = (a ∨ c)
a ∨ (b ∨ c) = (a ∨ b) ∨ c
a ⇒ (b ∧ c) = (a ⇒ b) ∧ (a ⇒ c)
a = (b = c) = (a = b) = c
a ⇒ (b ∨ c) = (a ⇒ b) ∨ (a ⇒ c)
a (b c) = (a b) c
a ⇒ (b ⇒ c) = (a ⇒ b) ⇒ (a ⇒ c)
a = (b c) = (a = b) c
a ⇒ (b = c) = (a ⇒ b) = (a ⇒ c)
11 Reference
Symmetry Laws (Commutative Laws)
a∧b = b∧a
a∨b = b∨a
a=b = b=a
a b = b a
Law of Generalization
a⇒a∨b
Antidistributive Laws
a ∧ b ⇒ c = (a ⇒ c) ∨ (b ⇒ c)
a ∨ b ⇒ c = (a ⇒ c) ∧ (b ⇒ c)
Antisymmetry Law (Double Implication)
(a ⇒ b) ∧ (b ⇒ a) = a = b
Laws of Discharge
a ∧ (a ⇒ b)
a ⇒ (a ∧ b)
= a∧b
= a⇒b
Antimonotonic Law
a ⇒ b ⇒ (b ⇒ c) ⇒ (a ⇒ c)
Law of Resolution
a ∧ c ⇒ (a ∨ b) ∧ (¬b ∨ c)
Case Base Laws
if then a else b
if then a else b
=
=
a
b
One Case Laws
if a then b else
if a then b else
=
=
a⇒b
a∧b
Case Reversal Law
if a then b else c
= if ¬a then c else b
=
=
=
=
=
=
Laws of Portation
a∧b⇒c
a∧b⇒c
=
=
a ⇒ (b ⇒ c)
a ⇒ ¬b ∨ c
Laws of Conflation
(a ⇒ b) ∧ (c ⇒ d)
(a ⇒ b) ∧ (c ⇒ d)
⇒
⇒
a∧c⇒b∧d
a∨c⇒b∨d
Monotonic Laws
a⇒b ⇒ c∧a⇒c∧b
a⇒b ⇒ c∨a⇒c∨b
a ⇒ b ⇒ (c ⇒ a) ⇒ (c ⇒ b)
Contrapositive Law
a ⇒ b = ¬b ⇒ ¬a
Case Absorption Laws
if a then b else c
if a then b else c
if a then b else c
if a then b else c
if a then b else c
if a then b else c
224
=
(a ∧ ¬b) ∨ (b ∧ c)
⇒
a∨c
Case Analysis Laws
if a then b else c = (a ∧ b) ∨ (¬a ∧ c)
if a then b else c = (a⇒b) ∧ (¬a ⇒ c)
Case Creation Laws
a = if b then b ⇒ a else ¬b ⇒ a
a = if b then b ∧ a else ¬b ∧ a
a = if b then b = a else b a
Case Idempotent Law
if a then b else b
=
b
if a then a∧b else c
if a then a ⇒ b else c
if a then a = b else c
if a then b else ¬a ∧ c
if a then b else a ∨ c
if a then b else a c
Case Distributive Laws (Case Factoring)
¬ if a then b else c = if a then ¬b else ¬c
(if a then b else c) ∧ d = if a then b ∧ d else c ∧ d
and similarly replacing ∧ by any of ∨ =
⇒ ⇐
if a then b ∧ c else d ∧ e = (if a then b else d) ∧ (if a then c else e)
and similarly replacing ∧ by any of ∨ =
⇒ ⇐
End of Booleans
225
11.4.1
11 Reference
Generic
The operators = if then else apply to every type of expression, with the axioms
x=x
reflexivity
x=y = y=x
symmetry
x=y ∧ y=z ⇒ x=z
transitivity
x=y ⇒ (···x···) = (···y···)
transparency
x y = ¬(x=y)
inequality
if then x else y = x
case destruction
if then x else y = y
case destruction
Note: in the transparency axiom, the context of x (denoted by dots around x ) must be the same
as the context of y (denoted by dots around y ).
The operators < ≤ > ≥ apply to numbers, characters, strings, and lists, with the axioms
¬ x<x
irreflexivity
¬(x<y ∧ x>y)
exclusivity
¬(x<y ∧ x=y)
exclusivity
x≤y ∧ y≤x = x=y
antisymmetry
x<y ∧ y<z ⇒ x<z
transitivity
x≤y = x<y ∨ x=y
inclusivity
x>y = y<x
mirror
x≥y = y≤x
mirror
x<y ∨ x=y ∨ x>y
totality, trichotomy
End of Generic
11.4.2
Numbers
Let d be a sequence of (zero or more) digits, let x , y , and z be numbers, and let a be boolean.
d0+1 = d1
counting
d1+1 = d2
counting
d2+1 = d3
counting
d3+1 = d4
counting
d4+1 = d5
counting
d5+1 = d6
counting
d6+1 = d7
counting
d7+1 = d8
counting
d8+1 = d9
counting
d9+1 = (d+1)0
counting (see Exercise 22)
+x = x
identity
x+0 = x
identity
x+y = y+x
symmetry
x+(y+z) = (x+y)+z
associativity
–∞<x<∞ ⇒ (x+y = x+z = y=z)
cancellation
–∞<x ⇒ ∞+x = ∞
absorption
x<∞ ⇒ –∞ + x = –∞
absorption
–x = 0 – x
negation
– –x = x
self-inverse
–(x+y) = –x + –y
distributivity
–(x–y) = –x – –y
distributivity
–(x×y) = –x × y
semi-distributivity
11 Reference
–(x/y) = (–x)/y
x–y = –(y–x)
x–y = x + –y
x + (y – z) = (x + y) – z
–∞<x<∞ ⇒ (x–y = x–z = y=z)
–∞<x<∞ ⇒ x–x = 0
x<∞ ⇒ ∞–x = ∞
–∞<x ⇒ –∞ – x = –∞
–∞<x<∞ ⇒ x×0 = 0
x×1 = x
x×y = y×x
x × (y+z) = x × y + x × z
x × (y × z) = (x × y)× z
–∞<x<∞ ∧ x 0 ⇒ (x×y = x×z = y=z)
0<x ⇒ x×∞ = ∞
0<x ⇒ x × –∞ = –∞
x/1 = x
–∞<x<∞ ∧ x 0 ⇒ x/x = 1
x×(y/z) = (x×y)/z
–∞<x<∞ ⇒ x/∞ = 0 = x/–∞
–∞<x<∞ ⇒ x0 = 1
x1 = x
x y+z = x y × x z
x y × z = (x y ) z
–∞<0<1<∞
x<y = –y<–x
–∞<x<∞ ⇒ (x+y < x+z = y<z)
0<x<∞ ⇒ (x×y < x×z = y<z)
x<y ∨ x=y ∨ x>y
–∞ ≤ x ≤∞
226
associativity
antisymmetry
subtraction
associativity
cancellation
inverse
absorption
absorption
base
identity
symmetry
distributivity
associativity
cancellation
absorption
absorption
identity
inverse
associativity
anihilation
base
identity
exponents
exponents
direction
reflection
cancellation, translation
cancellation, scale
trichotomy
extremes
End of Numbers
11.4.3
Bunches
Let x and y be elements (booleans, numbers, characters, sets, strings and lists of elements).
x: y = x=y
elementary axiom
x: A,B = x: A ∨ x: B
compound axiom
A,A = A
idempotence
A,B = B,A
symmetry
A,(B,C) = (A,B),C
associativity
A‘A = A
idempotence
A‘B = B‘A
symmetry
A‘(B‘C) = (A‘B)‘C
associativity
A,B: C = A: C ∧ B: C
antidistributivity
A: B‘C = A: B ∧ A: C
distributivity
A: A,B
generalization
A‘B: A
specialization
A: A
reflexivity
A: B ∧ B: A = A=B
antisymmetry
A: B ∧ B: C ⇒ A: C
transitivity
227
11 Reference
¢ null = 0
size
¢x = 1
size
¢(A, B) + ¢(A‘B) = ¢A + ¢B
size
¬ x: A ⇒ ¢(A‘x) = 0
size
A: B ⇒ ¢A ≤ ¢B
size
A,(A‘B) = A
absorption
A‘(A,B) = A
absorption
A: B = A,B = B = A = A‘B
inclusion
A,(B,C) = (A,B),(A,C)
distributivity
A,(B‘C) = (A,B)‘(A,C)
distributivity
A‘(B,C) = (A‘B), (A‘C)
distributivity
A‘(B‘C) = (A‘B)‘(A‘C)
distributivity
A: B ∧ C: D ⇒ A,C: B,D
conflation, monotonicity
A: B ∧ C: D ⇒ A‘C: B‘D
conflation, monotonicity
null: A
induction
A, null = A
identity
A ‘ null = null
base
¢A = 0 = A = null
size
i: x,..y = x≤i<y
(for extended integers i , x , y , x≤y )
¢(x,..y) = y–x
(for extended integers x , y , x≤y )
–null = null
distribution
–(A, B) = –A, –B
distribution
A+null = null+A = null
distribution
(A, B)+(C, D) = A+C, A+D, B+C, B+D
distribution
and similarly for many other operators (see the final page of the book)
End of Bunches
11.4.4
Sets
{A}
A
~{A} = A
A {B} = A: B
{A} {B} = A: B
{A} 2{B} = A: B
${A} = ¢A
{A} {B} = {A, B}
{A} {B} = {A ‘ B}
{A} = {B} = A = B
{A} {B} = A B
End of Sets
11.4.5
Strings
Let S , T , and U be strings; let i and j be items (booleans, numbers, characters, bunch of
items, sets, lists, functions); let n be natural; let x , y , and z be integers.
nil; S = S; nil = S
S; (T; U) = (S; T); U
nil = 0
i = 1
(S; T) = S + T
Snil = nil
(S; i; T) S = i
ST; U = ST; SU
S(TU) = (ST)U
0*S = nil
(n+1)*S = n*S; S
i=j = S; i; T = S; j; T
i<j ⇒ S; i; T < S; j; U
nil ≤ S < S; i; T
x;..x = nil
x;..x+1 = x
(x;..y) ; (y;..z) = x;..z
(x;..y) = y–x
End of Strings
11 Reference
11.4.6
228
Lists
Let S and T be strings; let n be a natural number; let i and j be items (booleans, numbers,
characters, bunch of items, sets, lists, functions); let L , M , and N be lists.
[S] n = Sn
#[S] = S
( S) → i | [S; j; T] = [S; i; T]
[S]+[T] = [S; T]
[S] = [T] = S = T
[S] [T] = [ST]
[S] < [T] = S < T
(L M) n = L (M n)
L null = null
(L M) N = L (M N)
L (A, B) = L A, L B
[email protected] = L
L {A} = {L A}
[email protected] = L i
L nil = nil
[email protected](S; T) = [email protected]@T
L (S; T) = L S; L T
nil→i | L = i
L [S] = [L S]
(S;T) → i | L = S→(T→i | [email protected]) | L
L (M+N) = L M + L N
End of Lists
11.4.7
Functions
Renaming Axiom — if v and w do not appear in D and w does not appear in b
λv: D· b = λw: D· (substitute w for v in b)
Application Axiom: if element x: D
Law of Extension
(λv: D· b) x = (substitute x for v in b )
f = λv: ∆f· f v
Domain Axiom
∆ λv: D· b
=
D
Function Inclusion Law
f: g = ∆g: ∆f ∧ ∀x: ∆g· fx: gx
Function Equality Law
f = g = ∆f = ∆g ∧ ∀x: ∆f· fx = gx
Axioms of Functional Union
∆(f, g) = ∆f ‘ ∆g
(f, g) x = f x, g x
Function Composition Axioms: If ¬ f: ∆g
∆(g f) = §x: ∆f· fx: ∆g
(g f) x = g (f x)
f (g h) = (f g) h
Cardinality Axiom
¢A = Σ A→1
Axioms of Functional Intersection
∆(f ‘ g) = ∆f, ∆g
(f ‘ g) x = f x ‘ g x
Axioms and Law of Selective Union
Laws of Selective Union
∆(f | g) = ∆f, ∆g
f|f = f
(f | g) x = if x: ∆f then f x else g x
(g | h) f = g f | h f
f | (g | h) = (f | g) | h
(λv: A· x) | (λv: B· y) = λv: A, B· if v: A then x else y
Distributive Axioms
Arrow Laws
f null = null
f: null→A
f (A, B) = f A, f B
A→B: (A‘C) → (B,D)
f (§g) = §y: f (∆g)· ∃x: ∆g· fx=y ∧ gx
f: A→B = A: ∆f ∧ ∀a: A· fa: B
f (if b then x else y) = if b then f x else f y
(if b then f else g) x = if b then f x else g x
End of Functions
229
11.4.8
11 Reference
Quantifiers
Let x be an element, let a , b and c be boolean, let n and m be numeric, let f and g be
functions, and let P be a predicate.
∀v: null· b =
∀v: A,B· b = (∀v: A· b) ∧ (∀v: B· b)
∀v: x· b = (λv: x· b) x
∀v: (§v: D· b)· c = ∀v: D· b ⇒ c
∃v: null· b =
∃v: x· b = (λv: x· b) x
∃v: A,B· b = (∃v: A· b) ∨ (∃v: B· b)
∃v: (§v: D· b)· c = ∃v: D· b ∧ c
Σv: null· n = 0
Σv: x· n = (λv: x· n) x
(Σv: A,B· n) + (Σv: A‘B· n) = (Σv: A· n) + (Σv: B· n)
Σv: (§v: D· b)· n = Σv: D· if b then n else 0
Πv: null· n = 1
Πv: x· n = (λv: x· n) x
(Πv: A,B· n) × (Πv: A‘B· n) = (Πv: A· n) × (Πv: B· n)
Πv: (§v: D· b)· n = Πv: D· if b then n else 1
MIN v: null· n = ∞
MIN v: x· n = (λv: x· n) x
MIN v: A,B· n = min (MIN v: A· n) (MIN v: B· n)
MIN v: (§v: D· b)· n = MIN v: D· if b then n else ∞
MAX v: null· n = –∞
MAX v: x· n = (λv: x· n) x
MAX v: A,B· n = max (MAX v: A· n) (MAX v: B· n)
MAX v: (§v: D· b)· n = MAX v: D· if b then n else –∞
§v: null· b = null
§v: x· b = if (λv: x· b) x then x else null
§v: A,B· b = (§v: A· b), (§v: B· b)
§v: A‘B· b = (§v: A· b) ‘ (§v: B· b)
§v: (§v: D· b)· c = §v: D· b ∧ c
Change of Variable Laws — if d does not appear in b
∀r: fD· b = ∀d: D· (substitute fd for r in b )
∃r: fD· b = ∃d: D· (substitute fd for r in b )
Σr: fD· n = Σd: D· (substitute fd for r in n )
Πr: fD· n = Πd: D· (substitute fd for r in n )
MIN r: fD· n = MIN d: D· (substitute fd for r in n )
MAX r: fD· n = MAX d: D· (substitute fd for r in n )
Bunch-Element Conversion Laws
V: W = ∀v: V· ∃w: W· v=w
fV: gW = ∀v: V· ∃w: W· fv=gw
Idempotent Laws — if D null
and v does not appear in b
∀v: D· b = b
∃v: D· b = b
Absorption Laws — if x: D
(λv: D· b) x ∧ ∃v: D· b
(λv: D· b) x ∨ ∀v: D· b
(λv: D· b) x ∧ ∀v: D· b
(λv: D· b) x ∨ ∃v: D· b
Identity Axioms
∀v·
¬∃v·
Distributive Axioms and Laws — if D null
and v does not appear in a
a ∧ ∀v: D· b = ∀v: D· a ∧ b
a ∧ ∃v: D· b = ∃v: D· a ∧ b
a ∨ ∀v: D· b = ∀v: D· a ∨ b
a ∨ ∃v: D· b = ∃v: D· a ∨ b
= (λv: D· b) x
a ⇒ ∀v: D· b = ∀v: D· a ⇒ b
= (λv: D· b) x
a ⇒ ∃v: D· b = ∃v: D· a ⇒ b
= ∀v: D· b
a ⇐ ∃v: D· b = ∀v: D· a ⇐ b
= ∃v: D· b
a ⇐ ∀v: D· b = ∃v: D· a ⇐ b
11 Reference
230
Specialization Law — if x: D
∀v: D· b ⇒ (λv: D· b) x
Generalization Law — if x: D
(λv: D· b) x ⇒ ∃v: D· b
One-Point Laws — if x: D
and v does not appear in x
∀v: D· v=x ⇒ b = (λv: D· b) x
∃v: D· v=x ∧ b = (λv: D· b) x
Splitting Laws — for any fixed domain
∀v· a ∧ b = (∀v· a) ∧ (∀v· b)
∃v· a ∧ b ⇒ (∃v· a) ∧ (∃v· b)
∀v· a ∨ b ⇐ (∀v· a) ∨ (∀v· b)
∃v· a ∨ b = (∃v· a) ∨ (∃v· b)
∀v· a ⇒ b ⇒ (∀v· a) ⇒ (∀v· b)
∀v· a ⇒ b ⇒ (∃v· a) ⇒ (∃v· b)
∀v· a = b ⇒ (∀v· a) = (∀v· b)
∀v· a = b ⇒ (∃v· a) = (∃v· b)
Duality Laws
¬∀v· b = ∃v· ¬b (deMorgan)
¬∃v· b = ∀v· ¬b (deMorgan)
– MAX v· n = MIN v· –n
– MIN v· n = MAX v· –n
Solution Laws
§v: D·
=D
(§v: D· b): D
§v: D·
= null
(§v· b): (§v· c) = ∀v· b⇒c
(§v· b), (§v· c) = §v· b ∨ c
(§v· b) ‘ (§v· c) = §v· b ∧ c
x: §p = x: ∆p ∧ px
∀f = (§f)=(∆f)
∃f = (§f) null
Bounding Axioms and Laws
if v does not appear in
n > (MAX v: D· m) ⇒
n < (MIN v: D· m) ⇒
n ≥ (MAX v: D· m) =
n ≤ (MIN v: D· m) =
n ≥ (MIN v: D· m) ⇐
n ≤ (MAX v: D· m) ⇐
n > (MIN v: D· m) =
n < (MAX v: D· m) =
Commutative Laws
∀v· ∀w· b = ∀w· ∀v· b
∃v· ∃w· b = ∃w· ∃v· b
Semicommutative Laws (Skolem)
∃v· ∀w· b ⇒ ∀w· ∃v· b
∀x· ∃y· Pxy = ∃f· ∀x· Px(fx)
Domain Change Laws
A: B ⇒ (∀v: A· b) ⇐ (∀v: B· b)
A: B ⇒ (∃v: A· b) ⇒ (∃v: B· b)
∀v: A· v: B ⇒ p = ∀v: A‘B· p
∃v: A· v: B ∧ p = ∃v: A‘B· p
n
(∀v: D· n>m) Extreme Law
(∀v: D· n<m)
∀v· (MIN v· n) ≤ n ≤ (MAX v· n)
(∀v: D· n≥m)
(∀v: D· n≤m) Connection Laws (Galois)
(∃v: D· n≥m)
n≤m = ∀k· k≤n ⇒ k≤m
(∃v: D· n≤m)
n≤m = ∀k· k<n ⇒ k<m
(∃v: D· n>m)
n≤m = ∀k· m≤k ⇒ n≤k
(∃v: D· n<m)
n≤m = ∀k· m<k ⇒ n<k
Distributive Laws — if D null and v does not appear in n
max n (MAX v: D· m) = (MAX v: D· max n m)
max n (MIN v: D· m) = (MIN v: D· max n m)
min n (MAX v: D· m) = (MAX v: D· min n m)
min n (MIN v: D· m) = (MIN v: D· min n m)
n + (MAX v: D· m) = (MAX v: D· n+m)
n + (MIN v: D· m) = (MIN v: D· n+m)
n – (MAX v: D· m) = (MIN v: D· n–m)
n – (MIN v: D· m) = (MAX v: D· n–m)
(MAX v: D· m) – n = (MAX v: D· m–n)
(MIN v: D· m) – n = (MIN v: D· m–n)
n≥0 ⇒ n × (MAX v: D· m) = (MAX v: D· n×m)
n≥0 ⇒ n × (MIN v: D· m) = (MIN v: D· n×m)
n≤0 ⇒ n × (MAX v: D· m) = (MIN v: D· n×m)
n≤0 ⇒ n × (MIN v: D· m) = (MAX v: D· n×m)
n × (Σv: D· m) = (Σv: D· n×m)
(Πv: D· m)n = (Πv: D· mn)
End of Quantifiers
231
11 Reference
11.4.9
Limits
(MAX m· MIN n· f(m+n)) ≤ (LIM f) ≤ (MIN m· MAX n· f(m+n))
∃m· ∀n· p(m+n) ⇒ LIM p ⇒ ∀m· ∃n· p(m+n)
End of Limits
11.4.10
Specifications and Programs
For specifications P , Q , R , and S , and boolean b ,
ok = x′=x ∧ y′=y ∧ ...
x:= e = x′=e ∧ y′=y ∧ ...
P. Q = ∃x′′, y′′, ...· (substitute x′′ for x′ , y′′ for y′ , ... in P )
∧ (substitute x′′ for x , y′′ for y , ... in Q )
P||Q = ∃tP, tQ· (substitute tP for t′ in P )
∧ (substitute tQ for t′ in Q )
∧ t′ = max tP tQ
if b then P else Q = b ∧ P ∨ ¬b ∧ Q
var x: T· P = ∃x, x′: T· P
while b do P = t′≥t ∧ (if b then (P. t:= t+inc. while b do P) else ok)
(Fmn ⇐ m=n ∧ ok) ∧ (Fik ⇐ m≤i<j<k≤n ∧ (Fij. Fjk))
⇒
(Fmn ⇐ for i:= m;..n do m≤i<n ⇒ Fi(i+1))
Im⇒I′n ⇐ for i:= m;..n do m≤i<n ∧ Ii ⇒ I′(i+1)
wait until w = t:= max t w
assert b = if b then ok else (print "error". wait until ∞)
ensure b = b ∧ ok
x′ = (P result e) = P. x′ = e
c? = r:= r+1
c = M (r–1)
c! e = M w = e ∧ T w = t ∧ (w:= w+1)
√c = T r + (transit time) ≤ t
ivar x: T· S = ∃x: time→T· S
chan c: T· P = ∃Mc: [∞*T]· ∃Tc: [∞*xreal]· var rc , wc: xnat := 0· P
ok. P = P. ok = P
identity
P. (Q. R) = (P. Q). R
associativity
if b then P else P = P
idempotence
if b then P else Q = if ¬b then Q else P
case reversal
P = if b then b ⇒ P else ¬b ⇒ P
case creation
P∨Q. R∨S = (P. R) ∨ (P. S) ∨ (Q. R) ∨ (Q. S)
distributivity
(if b then P else Q). R = if b then (P. R) else (Q. R) distributivity (unprimed b )
ok || P = P || ok = P
identity
P || Q = Q || P
symmetry
P || (Q || R) = (P || Q) || R
associativity
P || Q∨R = (P || Q) ∨ (P || R)
distributivity
P || if b then Q else R = if b then (P || Q) else (P || R) distributivity
if b then (P||Q) else (R||S) = if b then P else R || if b then Q else S distributivity
x:= if b then e else f = if b then x:= e else x:= f
functional-imperative
∀σ, σ′· (if b then (P. W) else ok ⇐ W) ⇒ ∀σ, σ′· (while b do P ⇐ W)
End of Specifications and Programs
11 Reference
11.4.11
232
Substitution
Let x and y be different boundary state variables, let e and f be expressions of the prestate,
and let P be a specification.
x:= e. P = (for x substitute e in P )
(x:= e || y:= f). P = (for x substitute e and independently for y substitute f in P )
End of Substitution
11.4.12
Conditions
Let P and Q be any specifications, and let C be a precondition, and let C′ be the corresponding
postcondition (in other words, C′ is the same as C but with primes on all the state variables).
C ∧ (P. Q) ⇐ C∧P. Q
C ⇒ (P.Q) ⇐ C⇒P. Q
(P.Q) ∧ C′ ⇐ P. Q∧C′
(P.Q) ⇐ C′ ⇐ P. Q⇐C′
P. C∧Q ⇐ P∧C′. Q
P. Q ⇐ P∧C′. C⇒Q
C is a sufficient precondition for P to be refined by S
if and only if C⇒P is refined by S .
C′ is a sufficient postcondition for P to be refined by S
if and only if C′⇒P is refined by S .
End of Conditions
11.4.13
Refinement
Refinement by Steps (Stepwise Refinement) (monotonicity, transitivity)
If A ⇐ if b then C else D and C ⇐ E and D ⇐ F are theorems,
then A ⇐ if b then E else F is a theorem.
If A ⇐ B.C and B ⇐ D and C ⇐ E are theorems, then A ⇐ D.E is a theorem.
If A ⇐ B||C and B ⇐ D and C ⇐ E are theorems, then A ⇐ D||E is a theorem.
If A ⇐ B and B ⇐ C are theorems, then A ⇐ C is a theorem.
Refinement by Parts (monotonicity, conflation)
If A ⇐ if b then C else D and E ⇐ if b then F else G are theorems,
then A∧E ⇐ if b then C∧F else D∧G is a theorem.
If A ⇐ B.C and D ⇐ E.F are theorems, then A∧D ⇐ B∧E. C∧F is a theorem.
If A ⇐ B||C and D ⇐ E||F are theorems, then A∧D ⇐ B∧E || C∧F is a theorem.
If A ⇐ B and C ⇐ D are theorems, then A∧C ⇐ B∧D is a theorem.
Refinement by Cases
P ⇐ if b then Q else R is a theorem if and only if
P ⇐ b ∧ Q and P ⇐ ¬b ∧ R are theorems.
End of Refinement
End of Laws
233
11 Reference
11.5 Names
abs: xreal→§r: xreal· r≥0
bool (the booleans)
ceil: real→int
char (the characters)
div: real→(§r: real· r>0)→int
divides: (nat+1)→int→bool
entro: prob→§r: xreal· r≥0
even: int→bool
floor: real→int
info: prob→§r: xreal· r≥0
int (the integers)
LIM (limit quantifier)
log: (§r: xreal· r≥0)→xreal
max: xrat→xrat→xrat
MAX (maximum quantifier)
min: xrat→xrat→xrat
MIN (minimum quantifier)
mod: real→(§r: real· r>0)→real
nat (the naturals)
nil (the empty string)
null (the empty bunch)
odd: int→bool
ok (the empty program)
prob (probability)
rand (random number)
rat (the rationals)
real (the reals)
suc: nat→(nat+1)
xint (the extended integers)
xnat (the extended naturals)
xrat (the extended rationals)
xreal (the extended reals)
abs r = if r≥0 then r else –r
bool = ,
r ≤ ceil r < r+1
char = ..., `a, `A, ...
div x y = floor (x/y)
divides n i = i/n: int
entro p = p × info p + (1–p) × info (1–p)
even i = i/2: int
even = divides 2
floor r ≤ r < floor r + 1
info p = – log p
int = nat, –nat
see Axioms and Laws
log (2x) = x
log (x×y) = log x + log y
max x y = if x≥y then x else y
– max a b = min (–a) (–b)
see Axioms and Laws
min x y = if x≤y then x else y
– min a b = max (–a) (–b)
see Axioms and Laws
0 ≤ mod a d < d
a = div a d × d + mod a d
0, nat+1: nat
0, B+1: B ⇒ nat: B
nil = 0
nil; S = S = S; nil
nil ≤ S
¢null = 0
null, A = A = A, null
null: A
odd i = ¬ i/2: int
odd = ¬even
ok = σ′=σ
ok.P = P.ok = ok || P = P || ok = P
prob = §r: real· 0≤r≤1
rand n: 0,..n
rat = int/(nat+1)
r: real = r: xreal ∧ –∞<r<∞
suc n = n+1
xint = –∞, int, ∞
xnat = nat, ∞
xrat = –∞, rat, ∞
x: xreal = ∃f: nat→rat· x = LIM f
End of Names
11 Reference
234
11.6 Symbols
¬
∧
∨
⇒
⇒
⇐
⇐
=
=
<
>
≤
≥
+
+
–
×
/
,
,..
‘
;
;..
:
::
:=
.
·
!
?
3
3
3
3
3
3
3
3
3
3
3
3
13
13
13
13
12
20
12
12
12
14
16
14
17
19
14
90
36
36
23
133
133
true
false
not
and
or
implies
implies
follows from, is implied by
follows from, is implied by
equals, if and only if
equals, if and only if
differs from, is unequal to
less than
greater than
less than or equal to
greater than or equal to
plus
list catenation
minus
times, multiplication
divided by
bunch union
union from (incl) to (excl)
bunch intersection
string catenation
catenation from (incl) to (excl)
is in, bunch inclusion
includes
assignment
dep't (sequential) composition
variable introduction
output
input
assert
77
chan
138
ensure
77
exit when
71
for do
74
frame
67
go to
76
if then else
4
()
{}
[]
2
¢
$
#
|
||
~
*
∆
→
@
λ
∀
∃
Σ
Π
§
′
`
"
ab
ab
ab
√
∞
4
17
20
17
14
17
18
20
20,24
118
17
18
23
25
17
17
17
17
22
23
26
26
26
26
27
34
13
21
12
18
20,31
133
12
ivar
loop end
or
result
var
wait until
while do
parentheses for grouping
set brackets
list brackets
powerset
bunch size, cardinality
set size, cardinality
string size, length
list size, length
selective union, otherwise
indep't (parallel) composition
contents of a set
repetition of a string
domain of a function
function arrow
element of a set
subset
set union
set intersection
index with a pointer
function, variable introduction
for all, universal quantifier
there exists, existential quantifier
sum of, summation quantifier
product of, product quantifier
those, solution quantifier
x′ is final value of state var x
`A is a character
"hello" is a text or list of chars
exponentiation
string indexing
indexing,application,composition
input check
infinity
126
71
77
78
66
76
69
End of Symbols
235
11 Reference
11.7 Precedence
0.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
( ) { } [ ] loop end numbers characters texts names
juxtaposition
+prefix –prefix
× /
@
¢ $
# * ~
2
∆ → superscript subscript
+ – +
; ;.. ‘
, ,.. |
=
< > ≤ ≥ : ::
¬
∧
∨
⇒ ⇐
:= ! ? √
if then else while do exit when for do go to
wait until assert ensure or
. || result
λ· ∀· ∃· Σ· Π· §· LIM· MAX· MIN· var· ivar· chan· frame·
= ⇒ ⇐
On level 2, superscripting and subscripting serve to bracket all operations within them.
Juxtaposition associates from left to right, so a b c means (a b) c . The infix operators @ / –
associate from left to right. The infix operators * → associate from right to left. The infix
operators ×
+ +
; ‘ , | ∧ ∨ . || are associative (they associate in both directions).
On levels 7, 11, and 16 the operators are continuing. For example, a = b = c neither associates to
the left nor associates to the right, but means a = b ∧ b = c . On any one of these levels, a
mixture of continuing operators can be used. For example, a ≤ b < c means a ≤ b ∧ b < c .
On levels 13 and 15, the precedence applies to the final operand (and initial operand of or ), not to
operands that are surrounded by the operator.
The operators
= ⇒ ⇐
are identical to = ⇒ ⇐ except for precedence.
End of Precedence
The following operators distribute over bunch union:
[ ] @ juxtaposition +prefix –prefix $
# *(left operand only)
~ superscript subscript × /
+ – +
; ‘ ¬ ∧ ∨
End of Reference
End of a Practical Theory of Programming
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement