
% Copyright (c) 1991-2002, The Numerical ALgorithms Group Ltd.
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
%     - Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%
%     - Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the
%       distribution.
%
%     - Neither the name of The Numerical ALgorithms Group Ltd. nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
% IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
% OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES-- LOSS OF USE, DATA, OR
% PROFITS-- OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


\texht{\setcounter{chapter}{4}}{} % Chapter 5

% *********************************************************************
\head{chapter}{Introduction to the \Language{} Interactive Language}{ugLang}
% *********************************************************************

In this chapter we look at some of the basic components of the
\Language{} language that you can use interactively.
We show how to create a \spadgloss{block} of expressions,
how to form loops and list iterations, how to modify the sequential
evaluation of a block and how to use {\tt if-then-else} to
evaluate parts of your program conditionally.
We suggest you first read the boxed material in each section and then
proceed to a more thorough reading of the chapter.

% *********************************************************************
\head{section}{Immediate and Delayed Assignments}{ugLangAssign}
% *********************************************************************

A \spadgloss{variable} in \Language{} refers to a value.
A variable has a name beginning with an uppercase or lowercase alphabetic
character, \axiomSyntax{\%}, or \axiomSyntax{!}.
Successive characters (if any) can be any of the above, digits, or
\axiomSyntax{?}.
Case is distinguished.
The following are all examples of valid, distinct variable names:
\begin{verbatim}
a             tooBig?    a1B2c3%!?
A             %j         numberOfPoints
beta6         %J         numberofpoints
\end{verbatim}

The \axiomSyntax{:=} operator is the immediate \spadgloss{assignment}
operator.
\index{assignment!immediate}
Use it to associate a value with a variable.
\index{immediate assignment}

\beginImportant
The syntax for immediate assignment for a single variable is
\begin{center}
{\it variable} \axiom{:=} {\it expression}
\end{center}
The value returned by an immediate assignment is the value of {\it expression}.
\endImportant

\xtc{
The right-hand side of the expression is evaluated,
yielding \axiom{1}.  This value is then assigned to \axiom{a}.
}{
\spadcommand{a := 1 \bound{a}}
}
\xtc{
The right-hand side of the expression is evaluated,
yielding \axiom{1}.  This value is then assigned to \axiom{b}.
Thus \axiom{a} and \axiom{b} both have the value \axiom{1} after the sequence
of assignments.
}{
\spadcommand{b := a \free{a}\bound{b}}
}
\xtc{
What is the value of \axiom{b} if \axiom{a} is
assigned the value \axiom{2}?
}{
\spadcommand{a := 2 \bound{a2}}
}
\xtc{
As you see, the value of \axiom{b} is left unchanged.
}{
\spadcommand{b \free{b}}
}
This is what we mean when we say this kind of assignment is
{\it immediate};
\axiom{b} has no dependency on \axiom{a} after the initial assignment.
This is the usual notion of assignment found in programming
languages such as C,
\index{C language!assignment}
PASCAL
\index{PASCAL!assignment}
and FORTRAN.
\index{FORTRAN!assignment}

\Language{} provides delayed assignment with \axiomSyntax{==}.
\index{assignment!delayed}
This implements a
\index{delayed assignment}
delayed evaluation of the right-hand side and dependency
checking.

\beginImportant
The syntax for delayed assignment is
\begin{center}
{\it variable} \axiom{==} {\it expression}
\end{center}
The value returned by a delayed assignment is \void{}.
\endImportant

\xtc{
Using \axiom{a} and \axiom{b} as above, these are the corresponding delayed
assignments.
}{
\spadcommand{a == 1 \bound{ad}}
}
\xtc{
}{
\spadcommand{b == a \free{ad}\bound{bd}}
}
\xtc{
The right-hand side of each delayed assignment
is left unevaluated until the
variables on the left-hand sides are evaluated.
Therefore this evaluation and \ldots
}{
\spadcommand{a \free{ad}}
}
\xtc{
this evaluation seem the same as before.
}{
\spadcommand{b \free{bd}}
}
\xtc{
If we change \axiom{a} to \axiom{2}
}{
\spadcommand{a == 2 \bound{ad2}}
}
\xtc{
then
\axiom{a} evaluates to \axiom{2}, as expected, but
}{
\spadcommand{a \free{ad2}}
}
\xtc{
the value of \axiom{b} reflects the change to \axiom{a}.
}{
\spadcommand{b \free{bd ad2}}
}

It is possible to set several variables at the same time
\index{assignment!multiple immediate}
by using
\index{multiple immediate assignment}
a \spadgloss{tuple} of variables and a tuple of expressions.\footnote{A
\spadgloss{tuple} is a collection of things separated by commas, often
surrounded by parentheses.}

% ----------------------------------------------------------------------
\beginImportant
The syntax for multiple immediate assignments is
\begin{center}
{\tt ( \subscriptIt{var}{1}, \subscriptIt{var}{2}, \ldots, \subscriptIt{var}{N} ) := ( \subscriptIt{expr}{1}, \subscriptIt{expr}{2}, \ldots, \subscriptIt{expr}{N} ) }
\end{center}
The value returned by an immediate assignment is the value of
\subscriptIt{expr}{N}.
\endImportant
% ----------------------------------------------------------------------

\xtc{
This sets \axiom{x} to \axiom{1} and \axiom{y} to \axiom{2}.
}{
\spadcommand{(x,y) := (1,2) \bound{x}\bound{y}}
}
Multiple immediate assigments are parallel in the sense that the
expressions on the right are all evaluated before any assignments
on the left are made.
However, the order of evaluation of these expressions is undefined.
\xtc{
You can use multiple immediate assignment to swap the
values held by variables.
}{
\spadcommand{(x,y) := (y,x) \free{x y}\bound{swap}}
}
\xtc{
\axiom{x} has the previous value of \axiom{y}.
}{
\spadcommand{x \free{swap}}
}
\xtc{
\axiom{y} has the previous value of \axiom{x}.
}{
\spadcommand{y \free{swap}}
}

There is no syntactic form for multiple delayed assignments.
See the discussion in
\spadref{ugUserDelay}
about how \Language{} differentiates between delayed assignments and
user functions of no arguments.

% *********************************************************************
\head{section}{Blocks}{ugLangBlocks}
% *********************************************************************

%%
%% We should handle tabs in pile correctly but so far we do not.
%%

A \spadgloss{block} is a sequence of expressions evaluated
in the order that they appear, except as modified by control expressions
such as \axiom{break},
\spadkey{break}
\axiom{return},
\spadkey{return}
\axiom{iterate} and
\spadkey{iterate}
\axiom{if-then-else} constructions.
The value of a block is the value of the expression last evaluated
in the block.

To leave a block early, use \axiomSyntax{=>}.
For example, \axiom{i < 0 => x}.
The expression before the \axiomSyntax{=>} must evaluate to
\axiom{true} or \axiom{false}.
The expression following the \axiomSyntax{=>} is the return value
for the block.

A block can be constructed in two ways:
\begin{enumerate}
\item the expressions can be separated by semicolons
and the resulting expression surrounded by parentheses, and
\item the expressions can be written on succeeding lines with each line
indented the same number of spaces (which must be greater than zero).
\index{indentation}
A block entered in this form is
called a \spadgloss{pile}.
\end{enumerate}
Only the first form is available if you are entering expressions
directly to \Language{}.
Both forms are available in {\bf .input} files.

\beginImportant
The syntax for a simple block of expressions entered interactively is
\begin{center}
{\tt ( \subscriptIt{expression}{1}; \subscriptIt{expression}{2}; \ldots; \subscriptIt{expression}{N} )}
\end{center}
The value returned by a block is the value of an
\axiomSyntax{=>} expression, or \subscriptIt{expression}{N}
if no \axiomSyntax{=>} is encountered.
\endImportant

In {\bf .input} files, blocks can also be written using
\spadglossSee{piles}{pile}.
The examples throughout this book are assumed to come from {\bf .input} files.

\xtc{
In this example, we assign a rational number to \axiom{a} using a block
consisting of three expressions.
This block is written as a pile.
Each expression in the pile has the same indentation, in this case two
spaces to the right of the first line.
}{
\begin{spadsrc}
a :=
  i := gcd(234,672)
  i := 3*i^5 - i + 1
  1 / i
\end{spadsrc}
}
\xtc{
Here is the same block written on one line.
This is how you are required to enter it at the input prompt.
}{
\spadcommand{a := (i := gcd(234,672); i := 3*i^5 - i + 1; 1 / i)}
}
\xtc{
Blocks can be used to put several expressions on one line.
The value returned is that of the last expression.
}{
\spadcommand{(a := 1; b := 2; c := 3; [a,b,c]) \bound{a b c}}
}

\Language{} gives you two ways of writing a block and the
preferred way in an {\bf .input} file is to use a pile.
\index{file!input}
Roughly speaking, a pile is
a block whose constituent expressions are indented the same amount.
You begin a pile by starting a new line for the first expression,
indenting it to the right of the previous line.
You then enter the second expression on a new line, vertically aligning
it with the first line. And so on.
If you need to enter an inner pile, further indent its lines to the right
of the outer pile.
\Language{} knows where a pile ends.
It ends when a subsequent line is indented to the left of the pile or
the end of the file.

\xtc{
Blocks can be used to perform several steps before an assignment
(immediate or delayed) is made.
}{
\begin{spadsrc}[\free{a b}]
d :=
   c := a^2 + b^2
   sqrt(c * 1.3)
\end{spadsrc}
}
\xtc{
Blocks can be used in the arguments to functions.
(Here \axiom{h} is assigned \axiom{2.1 + 3.5}.)
}{
\begin{spadsrc}[\bound{h}]
h := 2.1 +
   1.0
   3.5
\end{spadsrc}
}
\xtc{
Here the second argument to \axiomFun{eval} is \axiom{x = z}, where
the value of \axiom{z} is computed in the first line of the block
starting on the second line.
}{
\begin{spadsrc}
eval(x^2 - x*y^2,
     z := %pi/2.0 - exp(4.1)
     x = z
   )
\end{spadsrc}
}
\xtc{
Blocks can be used in the clauses of \axiom{if-then-else}
expressions (see \spadref{ugLangIf}).
}{
\spadcommand{if h > 3.1 then 1.0 else (z := cos(h); max(z,0.5)) \free{h}}
}
\xtc{
This is the pile version of the last block.
}{
\begin{spadsrc}[\free{h}]
if h > 3.1 then
    1.0
  else
    z := cos(h)
    max(z,0.5)
\end{spadsrc}
}
\xtc{
Blocks can be nested.
}{
\spadcommand{a := (b := factorial(12); c := (d := eulerPhi(22); factorial(d));b+c)}
}
\xtc{
This is the pile version of the last block.
}{
\begin{spadsrc}
a :=
  b := factorial(12)
  c :=
    d := eulerPhi(22)
    factorial(d)
  b+c
\end{spadsrc}
}

\xtc{
Since \axiom{c + d} does equal \axiom{3628855}, \axiom{a} has the value
of \axiom{c} and the last line is never evaluated.
}{
\begin{spadsrc}
a :=
  c := factorial 10
  d := fibonacci 10
  c + d = 3628855 => c
  d
\end{spadsrc}
}

% *********************************************************************
\head{section}{if-then-else}{ugLangIf}
% *********************************************************************

Like many other programming languages, \Language{} uses the three
% Remark: following strangeness with \spadkey is because \spadkey
% only creates an index term. Multiple sequential index macros without
% intervening text cause starnge spaces in the text.
keywords \spadkey{if} \axiom{if, then} \spadkey{then} and \axiom{else}
\spadkey{else} to form
\index{conditional}
conditional expressions.
The \axiom{else} part of the conditional is optional.
The expression between the \axiom{if} and \axiom{then} keywords
is a
\spadgloss{predicate}: an expression that evaluates to or is convertible to
either {\tt true} or {\tt false}, that is,
a \axiomType{Boolean}.
\exptypeindex{Boolean}

% ----------------------------------------------------------------------
\beginImportant
The syntax for conditional expressions is
\begin{center}
{\tt if {\it predicate} then \subscriptIt{expression}{1} else \subscriptIt{expression}{2}}
\end{center}
where the \axiom{else} \subscriptIt{\it expression}{2} part is optional.
The value returned from a conditional expression is
\subscriptIt{\it expression}{1} if the predicate evaluates to \axiom{true}
and \subscriptIt{\it expression}{2} otherwise.
If no \axiom{else} clause is given, the value is always \void{}.
\endImportant
% ----------------------------------------------------------------------

An \axiom{if-then-else} expression always returns a value.
If the
\axiom{else} clause is missing then the entire expression returns
\void{}.
If both clauses are present, the type of the value returned by \axiom{if}
is obtained by resolving the types of the values of the two clauses.
See \spadref{ugTypesResolve}
for more information.

The predicate must evaluate to, or be convertible to, an object of type
\axiomType{Boolean}: {\tt true} or {\tt false}.
By default, the equal sign \spadopFrom{=}{Equation} creates
\index{equation}
an equation.
\xtc{
This is an equation.
\exptypeindex{Equation}
In particular, it is an object of type \axiomType{Equation Polynomial Integer}.
}{
\spadcommand{x + 1 = y}
}
However, for predicates in \axiom{if} expressions, \Language{}
\index{equality testing}
places a default target type of \axiomType{Boolean} on the
predicate and equality testing is performed.
\exptypeindex{Boolean}
Thus you need not qualify the \axiomSyntax{=} in any way.
In other contexts you may need to tell \Language{} that you want
to test for equality rather than create an equation.
In those cases, use \axiomSyntax{@} and a target type of
\axiomType{Boolean}.
See \spadref{ugTypesPkgCall} for more information.

The compound symbol meaning ``not equal'' in \Language{} is
\index{inequality testing}
``\texht{$\sim =$}{\axiom{~=}}''.
\index{\_notequal@$\sim =$}
This can be used directly without a package call or a target specification.
The expression
\axiom{a} \texht{$\sim =$}{\axiom{~=}} \axiom{b} is directly translated into
\axiom{not (a = b)}.

Many other functions have return values of type \axiomType{Boolean}.
These include \axiom{<}, \axiom{<=}, \axiom{>},
\axiom{>=}, \texht{$\sim =$}{\axiom{~=}} and \axiom{member?}.
By convention, operations with names ending in \axiomSyntax{?}
return \axiomType{Boolean} values.

The usual rules for piles are suspended for conditional expressions.
In {\bf .input} files, the \axiom{then} and
\axiom{else} keywords can begin in the same column as the corresponding
\axiom{if} but may also appear to the right.
Each of the following styles of writing \axiom{if-then-else}
expressions is acceptable:
\begin{verbatim}
if i>0 then output("positive") else output("nonpositive")

if i > 0 then output("positive")
  else output("nonpositive")

if i > 0 then output("positive")
else output("nonpositive")

if i > 0
then output("positive")
else output("nonpositive")

if i > 0
  then output("positive")
  else output("nonpositive")
\end{verbatim}

A block can follow the \axiom{then} or \axiom{else} keywords.
In the following two assignments to \axiom{a}, the \axiom{then} and \axiom{else}
clauses each are followed by two-line piles.
The value returned in each is the value of the second line.

\begin{verbatim}
a :=
  if i > 0 then
    j := sin(i * pi())
    exp(j + 1/j)
  else
    j := cos(i * 0.5 * pi())
    log(abs(j)^5 + 1)

a :=
  if i > 0
    then
      j := sin(i * pi())
      exp(j + 1/j)
    else
      j := cos(i * 0.5 * pi())
      log(abs(j)^5 + 1)
\end{verbatim}
These are both equivalent to the following:
\begin{verbatim}
a :=
  if i > 0 then (j := sin(i * pi()); exp(j + 1/j))
  else (j := cos(i * 0.5 * pi()); log(abs(j)^5 + 1))
\end{verbatim}

% *********************************************************************
\head{section}{Loops}{ugLangLoops}
% *********************************************************************

A \spadgloss{loop} is an expression that contains another expression,
\index{loop}
called the {\it loop body}, which is to be evaluated zero or more
\index{loop!body}
times.
All loops contain the \axiom{repeat} keyword and return \void{}.
Loops can contain inner loops to any depth.

\beginImportant
The most basic loop is of the form
\begin{center}
\axiom{repeat} {\it loopBody}
\end{center}
Unless {\it loopBody} contains a \axiom{break} or \axiom{return} expression,
the loop repeats forever.
The value returned by the loop is \void{}.
\endImportant

% *********************************************************************
\head{subsection}{Compiling vs. Interpreting Loops}{ugLangLoopsCompInt}
% *********************************************************************

\Language{} tries to determine completely the type of every
object in a loop and then to translate the loop body to LISP or even to
machine code.
This translation is called \spadglossSee{compilation}{compiler}.

If \Language{} decides that it cannot compile the loop, it issues a
\index{loop!compilation}
message stating the problem and then the following message:
%
\begin{center}
{\bf We will attempt to step through and interpret the code.}
\end{center}
%
It is still possible that \Language{} can evaluate the loop but in
\spadgloss{interpret-code mode}.
See \spadref{ugUserCompInt} where this is discussed in terms
\index{panic!avoiding}
of compiling versus interpreting functions.

% *********************************************************************
\head{subsection}{return in Loops}{ugLangLoopsReturn}
% *********************************************************************

A \axiom{return} expression is used to exit a function with
\index{loop!leaving via return}
a particular value.
In particular, if a \axiom{return} is in a loop within the
\spadkey{return}
function, the loop is terminated whenever the \axiom{return}
is evaluated.
%> This is a bug! The compiler should never accept allow
%> Void to be the return type of a function when it has to use
%> resolve to determine it.
\xtc{
Suppose we start with this.
}{
\begin{spadsrc}[\bound{f}]
f() ==
  i := 1
  repeat
    if factorial(i) > 1000 then return i
    i := i + 1
\end{spadsrc}
}
\xtc{
When \axiom{factorial(i)} is big enough, control passes from
inside the loop all the way outside the function, returning the
value of \axiom{i} (or so we think).
}{
\spadcommand{f() \free{f}}
}

What went wrong?
Isn't it obvious that this function should return an integer?
Well, \Language{} makes no attempt to analyze the structure of a
loop to determine if it always returns a value because, in
general, this is impossible.
So \Language{} has this simple rule: the type of the function is
determined by the type of its body, in this case a block.
The normal value of a block is the value of its last expression,
in this case, a loop.
And the value of every loop is \void{}!
So the return type of \userfun{f} is \axiomType{Void}.

There are two ways to fix this.
The best way is for you to tell \Language{} what the return type
of \axiom{f} is.
You do this by giving \axiom{f} a declaration \axiom{f: () ->
Integer} prior to calling for its value.
This tells \Language{}: ``trust me---an integer is returned.''
We'll explain more about this in the next chapter.
Another clumsy way is to add a dummy expression as follows.

\xtc{
Since we want an integer, let's stick in a dummy final expression that is
an integer and will never be evaluated.
}{
\begin{spadsrc}[\bound{f1}]
f() ==
  i := 1
  repeat
    if factorial(i) > 1000 then return i
    i := i + 1
  0
\end{spadsrc}
}
\xtc{
When we try \userfun{f} again we get what we wanted.
See
\spadref{ugUserBlocks}
for more information.
}{
\spadcommand{f() \free{f1}}
}

% *********************************************************************
\head{subsection}{break in Loops}{ugLangLoopsBreak}
% *********************************************************************

The \axiom{break} keyword is often more useful
\spadkey{break}
in terminating
\index{loop!leaving via break}
a loop.
%>  and more in keeping with the ideas of structured programming.
A \axiom{break} causes control to transfer to the expression
immediately following the loop.
As loops always return \void{},
you cannot return a value with \axiom{break}.
That is, \axiom{break} takes no argument.

\xtc{
This example is a modification of the last example in
\texht{the previous section}{\spadref{ugLangLoopsReturn}}.
Instead of using \axiom{return}, we'll use \axiom{break}.
}{
\begin{spadsrc}[\bound{f1}]
f() ==
  i := 1
  repeat
    if factorial(i) > 1000 then break
    i := i + 1
  i
\end{spadsrc}
}
\xtc{
The loop terminates when \axiom{factorial(i)} gets big enough,
the last line of the function evaluates to the corresponding ``good''
value of \axiom{i}, and the function terminates, returning that value.
}{
\spadcommand{f() \free{f1}}
}
\xtc{
You can only use \axiom{break} to terminate the evaluation of one loop.
Let's consider a loop within a loop, that is, a loop with a nested loop.
First, we initialize two counter variables.
}{
\spadcommand{(i,j) := (1, 1) \bound{i}\bound{j}}
}
\xtc{
Nested loops must have multiple \axiom{break}
\index{loop!nested}
expressions at the appropriate nesting level.
How would you rewrite this so \axiom{(i + j) > 10} is only evaluated once?
}{
\begin{spadsrc}[\free{i j}]
repeat
  repeat
    if (i + j) > 10 then break
    j := j + 1
  if (i + j) > 10 then break
  i := i + 1
\end{spadsrc}
}

% *********************************************************************
\head{subsection}{break vs. {\tt =>} in Loop Bodies}{ugLangLoopsBreakVs}
% *********************************************************************

Compare the following two loops:

\begin{verbatim}
i := 1                            i := 1
repeat                            repeat
  i := i + 1                        i := i + 1
  i > 3 => i                        if i > 3 then break
  output(i)                         output(i)
\end{verbatim}

In the example on the left, the values
\mathOrSpad{2} and \mathOrSpad{3} for \axiom{i} are displayed
but then the \axiomSyntax{=>} does not allow control to reach the call to
\axiomFunFrom{output}{OutputForm} again.
The loop will not terminate
until you run out of space or interrupt the execution.
The variable \axiom{i} will continue to be incremented because
the \axiomSyntax{=>} only means to leave the {\it block,} not the loop.

In the example on the right,
upon reaching \mathOrSpad{4}, the \axiom{break} will be
executed, and both the block and the loop will terminate.
This is one of the reasons why both \axiomSyntax{=>} and \axiom{break} are
provided.
Using a \axiom{while} clause (see below) with the \axiomSyntax{=>}
\spadkey{while}
lets you simulate the action of \axiom{break}.

% *********************************************************************
\head{subsection}{More Examples of break}{ugLangLoopsBreakMore}
% *********************************************************************

Here we give four examples of \axiom{repeat} loops that
terminate when a value exceeds a given bound.

\texht{\vskip 1pc}{}
\xtc{
First, initialize \axiom{i} as the loop counter.
}{
\spadcommand{i := 0 \bound{i}}
}
\xtc{
Here is the first loop.
When the square of \axiom{i} exceeds \axiom{100}, the loop terminates.
}{
\begin{spadsrc}[\free{i}\bound{i1}]
repeat
  i := i + 1
  if i^2 > 100 then break
\end{spadsrc}
}
\xtc{
Upon completion, \axiom{i} should have the value \axiom{11}.
}{
\spadcommand{i \free{i1}}
}
%
%
\xtc{
Do the same thing except use \axiomSyntax{=>} instead
an \axiom{if-then} expression.
}{
\spadcommand{i := 0 \bound{i2}}
}
\xtc{
}{
\begin{spadsrc}[\free{i2}\bound{i3}]
repeat
  i := i + 1
  i^2 > 100 => break
\end{spadsrc}
}
\xtc{
}{
\spadcommand{i \free{i3}}
}
%
%
\xtc{
As a third example, we use a simple loop to compute \axiom{n!}.
}{
\spadcommand{(n, i, f) := (100, 1, 1) \bound{n}\bound{i4}\bound{f}}
}
\xtc{
Use \axiom{i} as the iteration variable and \axiom{f}
to compute the factorial.
}{
\begin{spadsrc}[\bound{f1}\bound{i5}\free{f i4 n}]
repeat
  if i > n then break
  f := f * i
  i := i + 1
\end{spadsrc}
}
\xtc{
Look at the value of \axiom{f}.
}{
\spadcommand{f \free{f1}}
}
%
%
\xtc{
Finally, we show an example of nested loops.
First define a four by four matrix.
}{
\spadcommand{m := matrix [[21,37,53,14], [8,-24,22,-16], [2,10,15,14], [26,33,55,-13]] \bound{m2}}
}
\xtc{
Next, set row counter \axiom{r} and column counter \axiom{c} to
\mathOrSpad{1}.
Note: if we were writing a function, these would all be local
variables rather than global workspace variables.
}{
\spadcommand{(r, c) := (1, 1) \bound{r}\bound{c}}
}
\xtc{
Also, let \axiom{lastrow} and
\axiom{lastcol} be the final row and column index.
}{
\spadcommand{(lastrow, lastcol) := (nrows(m), ncols(m)) \bound{lastrow}\bound{lastcol}\free{m2}}
}
%
\xtc{
Scan the rows looking for the first negative element.
We remark that you can reformulate this example in a better, more
concise form by using a \axiom{for} clause with \axiom{repeat}.
See
\spadref{ugLangLoopsForIn}
for more information.
}{
\begin{spadsrc}[\free{m2 r c lastrow lastcol}]
repeat
  if r > lastrow then break
  c := 1
  repeat
    if c > lastcol then break
    if elt(m,r,c) < 0 then
      output [r, c, elt(m,r,c)]
      r := lastrow
      break     -- don't look any further
    c := c + 1
  r := r + 1
\end{spadsrc}
}

% *********************************************************************
\head{subsection}{iterate in Loops}{ugLangLoopsIterate}
% *********************************************************************

\Language{} provides an \axiom{iterate} expression that
\spadkey{iterate}
skips over the remainder of a loop body and starts the next loop iteration.
\xtc{
We first initialize a counter.
}{
\spadcommand{i := 0 \bound{i}}
}
\xtc{
Display the even integers from \axiom{2} to \axiom{5}.
}{
\begin{spadsrc}[\free{i}]
repeat
  i := i + 1
  if i > 5 then break
  if odd?(i) then iterate
  output(i)
\end{spadsrc}
}

% *********************************************************************
\head{subsection}{while Loops}{ugLangLoopsWhile}
% *********************************************************************

The \axiom{repeat} in a loop can be modified by adding one or
more \axiom{while} clauses.
\spadkey{while}
Each clause contains a \spadgloss{predicate}
immediately following the \axiom{while} keyword.
The predicate is tested {\it before}
the evaluation of the body of the loop.
The loop body is evaluated whenever the predicates in a \axiom{while}
clause are all \axiom{true}.

\beginImportant
The syntax for a simple loop using \axiom{while} is
\begin{center}
\axiom{while} {\it predicate} \axiom{repeat} {\it loopBody}
\end{center}
The {\it predicate} is evaluated before {\it loopBody} is evaluated.
A \axiom{while} loop terminates immediately when {\it predicate}
evaluates to \axiom{false} or when a \axiom{break} or \axiom{return}
expression is evaluated in {\it loopBody}.
The value returned by the loop is \void{}.
\endImportant

\xtc{
Here is a simple example of using \axiom{while} in a loop.
We first initialize the counter.
}{
\spadcommand{i := 1 \bound{i}}
}
\xtc{
The steps involved in computing this example are
(1) set \axiom{i} to \axiom{1}, (2) test the condition \axiom{i < 1} and
determine that it is not true, and (3) do not evaluate the
loop body and therefore do not display \axiom{"hello"}.
}{
\begin{spadsrc}[\free{i}]
while i < 1 repeat
  output "hello"
  i := i + 1
\end{spadsrc}
}
\xtc{
If you have multiple predicates to be tested use the
logical \axiom{and} operation to separate them.
\Language{} evaluates these predicates from left to right.
}{
\spadcommand{(x, y) := (1, 1) \bound{x}\bound{y}}
}
\xtc{
}{
\begin{spadsrc}[\free{x y}]
while x < 4 and y < 10 repeat
  output [x,y]
  x := x + 1
  y := y + 2
\end{spadsrc}
}
\xtc{
A \axiom{break} expression can be included in a loop body to terminate a
loop even if the predicate in any \axiom{while} clauses are not \axiom{false}.
}{
\spadcommand{(x, y) := (1, 1) \bound{x1}\bound{y1}}
}
\xtc{
This loop has multiple \axiom{while} clauses and the loop terminates
before any one of their conditions evaluates to \axiom{false}.
}{
\begin{spadsrc}[\free{x1 y1}]
while x < 4 while y < 10 repeat
  if x + y > 7 then break
  output [x,y]
  x := x + 1
  y := y + 2
\end{spadsrc}
}
\xtc{
Here's a different version of the nested loops that looked
for the first negative element in a matrix.
}{
\spadcommand{m := matrix [[21,37,53,14], [8,-24,22,-16], [2,10,15,14], [26,33,55,-13]] \bound{m2}}
}
\xtc{
Initialized the row index to \axiom{1} and
get the number of rows and columns.
If we were writing a function, these would all be
local variables.
}{
\spadcommand{r := 1 \bound{r}}
}
\xtc{
}{
\spadcommand{(lastrow, lastcol) := (nrows(m), ncols(m)) \bound{lastrow}\bound{lastcol}\free{m2}}
}
%
\xtc{
Scan the rows looking for the first negative element.
}{
\begin{spadsrc}[\free{m2 r lastrow lastcol}]
while r <= lastrow repeat
  c := 1  -- index of first column
  while c <= lastcol repeat
    if elt(m,r,c) < 0 then
      output [r, c, elt(m,r,c)]
      r := lastrow
      break     -- don't look any further
    c := c + 1
  r := r + 1
\end{spadsrc}
}

% *********************************************************************
\head{subsection}{for Loops}{ugLangLoopsForIn}
% *********************************************************************

\Language{} provides the \axiom{for}
\spadkey{for}
and \axiom{in}
\spadkey{in}
keywords in \axiom{repeat} loops,
allowing you to iterate across all
\index{iteration}
elements of a list, or to have a variable take on integral values
from a lower bound to an upper bound.
We shall refer to these modifying clauses of \axiom{repeat} loops as
\axiom{for} clauses.
These clauses can be present in addition to \axiom{while} clauses.
As with all other types of \axiom{repeat} loops, \axiom{break} can
\spadkey{break}
be used to prematurely terminate the evaluation of the loop.

\beginImportant
The syntax for a simple loop using \axiom{for} is
\begin{center}
\axiom{for} {\it iterator} \axiom{repeat} {\it loopBody}
\end{center}
The {\it iterator} has several forms.
Each form has an end test which is evaluated
before {\it loopBody} is evaluated.
A \axiom{for} loop terminates immediately when the end test
succeeds (evaluates to \axiom{true}) or when a \axiom{break} or \axiom{return}
expression is evaluated in {\it loopBody}.
The value returned by the loop is \void{}.
\endImportant

% *********************************************************************
\head{subsection}{for i in n..m repeat}{ugLangLoopsForInNM}
% *********************************************************************

If \axiom{for}
\spadkey{for}
is followed by a variable name, the \axiom{in}
\spadkey{in}
keyword and then an integer segment of the form \axiom{n..m},
\index{segment}
the end test for this loop is the predicate \axiom{i > m}.
The body of the loop is evaluated \axiom{m-n+1} times if this
number is greater than 0.
If this number is less than or equal to 0, the loop body is not evaluated
at all.

The variable \axiom{i} has the value
\axiom{n, n+1, ..., m} for successive iterations
of the loop body.
The loop variable is a \spadgloss{local variable}
within the loop body: its value is not available outside the loop body
and its value and type within the loop body completely mask any outer
definition of a variable with the same name.

%
\xtc{
This loop prints the values of
\texht{${10}^3$, ${11}^3$, and $12^3$}{\axiom{10^3, 11^3, and 12^3}}:
}{
\spadcommand{for i in 10..12 repeat output(i^3)}
}
%
\xtc{
Here is a sample list.
}{
\spadcommand{a := [1,2,3] \bound{a}}
}
\xtc{
Iterate across this list, using \axiomSyntax{.} to access the elements of a list and
the \axiomFun{\#} operation to count its elements.
}{
\spadcommand{for i in 1..\#a repeat output(a.i) \free{a}}
}
%
This type of iteration is applicable to anything that uses \axiomSyntax{.}.
You can also use it with functions that use indices to extract elements.
%
\xtc{
Define \axiom{m} to be a matrix.
}{
\spadcommand{m := matrix [[1,2],[4,3],[9,0]] \bound{m}}
}
\xtc{
Display the rows of \axiom{m}.
}{
\spadcommand{for i in 1..nrows(m) repeat output row(m,i) \free{m}}
}
%
You can use \axiom{iterate} with \axiom{for}-loops.
\spadkey{iterate}
\xtc{
Display the even integers in a segment.
}{
\begin{spadsrc}
for i in 1..5 repeat
  if odd?(i) then iterate
  output(i)
\end{spadsrc}
}

See \xmpref{Segment} for more information about segments.

% *********************************************************************
\head{subsection}{for i in n..m by s repeat}{ugLangLoopsForInNMS}
% *********************************************************************

By default, the difference between values taken on by a variable in loops
such as \axiom{for i in n..m repeat ...} is \mathOrSpad{1}.
It is possible to supply another, possibly negative, step value by using
the \axiom{by}
\spadkey{by}
keyword along with \axiom{for} and \axiom{in}.
Like the upper and lower bounds, the step value following the
\axiom{by} keyword must be an integer.
Note that the loop
\axiom{for i in 1..2 by 0 repeat output(i)}
will not terminate by itself, as the step value does not change the index
from its initial value of \mathOrSpad{1}.

\xtc{
This expression displays the odd integers between two bounds.
}{
\spadcommand{for i in 1..5 by 2 repeat output(i)}
}
\xtc{
Use this to display the numbers in reverse order.
}{
\spadcommand{for i in 5..1 by -2 repeat output(i)}
}

% *********************************************************************
\head{subsection}{for i in n.. repeat}{ugLangLoopsForInN}
% *********************************************************************

If the value after the \axiomSyntax{..}
is omitted, the loop has no end test.
A potentially infinite loop is thus created.
The variable is given the successive values \axiom{n, n+1, n+2, ...}
and the loop is terminated only if a \axiom{break} or \axiom{return}
expression is evaluated in the loop body.
However you may also add some other modifying clause on the
\axiom{repeat} (for example, a \axiom{while} clause) to stop the loop.

\xtc{
This loop displays the integers greater than or equal to \axiom{15}
and less than the first prime greater than \axiom{15}.
}{
\spadcommand{for i in 15.. while not prime?(i) repeat output(i)}
}

% *********************************************************************
\head{subsection}{for x in l repeat}{ugLangLoopsForInXL}
% *********************************************************************

Another variant of the \axiom{for} loop has the form:
\begin{center}
{\it \axiom{for} x \axiom{in} list \axiom{repeat} loopBody}
\end{center}
This form is used when you want to iterate directly over the
elements of a list.
In this form of the \axiom{for} loop, the variable
\axiom{x} takes on the value of each successive element in \axiom{l}.
The end test is most simply stated in English: ``are there no more
\axiom{x} in \axiom{l}?''

\xtc{
If \axiom{l} is this list,
}{
\spadcommand{l := [0,-5,3] \bound{l}}
}
\xtc{
display all elements of \axiom{l}, one per line.
}{
\spadcommand{for x in l repeat output(x) \free{l}}
}

Since the list constructing expression \axiom{expand [n..m]} creates the
list \axiom{[n, n+1, ..., m]}\footnote{This list is empty if \axiom{n >
m}.}, you might be tempted to think that the loops
\begin{verbatim}
for i in n..m repeat output(i)
\end{verbatim}
and
\begin{verbatim}
for x in expand [n..m] repeat output(x)
\end{verbatim}
are equivalent.
The second form first creates the list
\axiom{expand [n..m]} (no matter how large it might be) and
then does the iteration.
The first form potentially runs in much less space, as the index variable
\axiom{i} is simply incremented once per loop and the list is not actually
created.
Using the first form is much more efficient.
%
\xtc{
Of course, sometimes you really want to iterate across a specific list.
This displays each of the factors of \axiom{2400000}.
}{
\spadcommand{for f in factors(factor(2400000)) repeat output(f)}
}

% *********************************************************************
\head{subsection}{``Such that'' Predicates}{ugLangLoopsForInPred}
% *********************************************************************

A \axiom{for} loop can be followed by a \axiomSyntax{|} and then a
predicate.
The predicate qualifies the use of the values from the iterator following
the \axiom{for}.
Think of the vertical bar
\axiomSyntax{|} as the phrase ``such that.''
\xtc{
This loop expression
prints out the integers \axiom{n} in the given segment
such that \axiom{n} is odd.
}{
\spadcommand{for n in 0..4 | odd? n repeat output n}
}

\beginImportant
A \axiom{for} loop can also be written
\begin{center}
\axiom{for} {\it iterator} \axiom{|} {\it predicate}  \axiom{repeat} {\it loopBody}
\end{center}
which is equivalent to:
\begin{center}
\axiom{for} {\it iterator} \axiom{repeat if}
{\it predicate} \axiom{then} {\it loopBody} \axiom{else} \axiom{iterate}
\end{center}
\endImportant

The predicate need not refer only to the variable in the \axiom{for} clause:
any variable in an outer scope can be part of the predicate.
\xtc{
In this example, the predicate on the inner \axiom{for} loop uses
\axiom{i} from the outer loop and the \axiom{j} from the \axiom{for}
\index{iteration!nested}
clause that it directly modifies.
}{
\begin{spadsrc}
for i in 1..50 repeat
  for j in 1..50 | factorial(i+j) < 25 repeat
    output [i,j]
\end{spadsrc}
}

% *********************************************************************
\head{subsection}{Parallel Iteration}{ugLangLoopsPar}
% *********************************************************************

The last example of
\texht{the previous section}{\spadref{ugLangLoopsForInPred}}
gives an example of
\spadgloss{nested iteration}: a loop is contained
\index{iteration!nested}
in another loop.
\index{iteration!parallel}
Sometimes you want to iterate across two lists in parallel, or perhaps
you want to traverse a list while incrementing a variable.

\beginImportant
The general syntax of a repeat loop is
\begin{center}
{\tt \subscriptIt{iterator}{1} \subscriptIt{iterator}{2} \ldots \subscriptIt{iterator}{N} repeat {\it loopBody}}
\end{center}
where each {\it iterator} is either a \axiom{for} or a \axiom{while} clause.
The loop terminates immediately when the end test of any {\it iterator}
succeeds or when a \axiom{break} or \axiom{return} expression is evaluated
in {\it loopBody}.
The value returned by the loop is \void{}.
\endImportant

\xtc{
Here we write a loop to iterate across
two lists, computing the sum of the pairwise product
of elements. Here is the first list.
}{
\spadcommand{l := [1,3,5,7] \bound{l}}
}
\xtc{
And the second.
}{
\spadcommand{m := [100,200] \bound{m}}
}
\xtc{
The initial value of the sum counter.
}{
\spadcommand{sum := 0 \bound{sum}}
}
\xtc{
The last two elements of \axiom{l} are not used in the calculation
because \axiom{m} has two fewer elements than \axiom{l}.
}{
\begin{spadsrc}[\bound{doit}\free{sum l m}]
for x in l for y in m repeat
    sum := sum + x*y
\end{spadsrc}
}
\xtc{
Display the ``dot product.''
}{
\spadcommand{sum \free{doit}}
}

\xtc{
Next, we write a loop to compute the sum of the products of the loop elements with
their positions in the loop.
}{
\spadcommand{l := [2,3,5,7,11,13,17,19,23,29,31,37] \bound{l1}}
}
\xtc{
The initial sum.
}{
\spadcommand{sum := 0 \bound{sum1}}
}
\xtc{
Here looping stops when the list \axiom{l} is exhausted, even though
the \axiom{for i in 0..} specifies no terminating condition.
}{
\spadcommand{for i in 0.. for x in l repeat sum := i * x \bound{doit1}\free{sum1 l1}}
}
\xtc{
Display this weighted sum.
}{
\spadcommand{sum \free{doit1}}
}

When \axiomSyntax{|} is used to qualify any of the \axiom{for} clauses in a
parallel iteration, the variables in the predicates can be from an outer
scope or from a \axiom{for} clause in or to the left of a modified clause.

This is correct:
% output from following is too long to show
\begin{verbatim}
for i in 1..10 repeat
  for j in 200..300 | odd? (i+j) repeat
    output [i,j]
\end{verbatim}
This is not correct since the variable \axiom{j} has not been
defined outside the inner loop.
\begin{verbatim}
for i in 1..10 | odd? (i+j) repeat  -- wrong, j not defined
  for j in 200..300 repeat
    output [i,j]
\end{verbatim}

%>% *********************************************************************
%>\head{subsection}{Mixing Loop Modifiers}{ugLangLoopsMix}
%>% *********************************************************************

\xtc{
This example shows that it is possible to mix several of the
\index{loop!mixing modifiers}
forms of \axiom{repeat} modifying clauses on a loop.
}{
\begin{spadsrc}
for i in 1..10
    for j in 151..160 | odd? j
      while i + j < 160 repeat
        output [i,j]
\end{spadsrc}
}
%
Here are useful rules for composing loop expressions:
\begin{enumerate}
\item \axiom{while} predicates can only refer to variables that
are global (or in an outer scope)
or that are defined in \axiom{for} clauses to the left of the
predicate.
\item A ``such that'' predicate (something following \axiomSyntax{|})
must directly follow a \axiom{for} clause and can only refer to
variables that are global (or in an outer scope)
or defined in the modified \axiom{for} clause
or any \axiom{for} clause to the left.
\end{enumerate}

% *********************************************************************
\head{section}{Creating Lists and Streams with Iterators}{ugLangIts}
% *********************************************************************

All of what we did for loops in \spadref{ugLangLoops}
\index{iteration}
can be transformed into expressions that create lists
\index{list!created by iterator}
and streams.
\index{stream!created by iterator}
The \axiom{repeat,} \axiom{break} or \axiom{iterate} words are not used but
all the other ideas carry over.
Before we give you the general rule, here are some examples which
give you the idea.

\xtc{
This creates a simple list of the integers from \axiom{1} to \axiom{10}.
}{
\spadcommand{mylist := [i for i in 1..10] \bound{mylist}}
}
\xtc{
Create a stream of the integers greater than or equal to \axiom{1}.
}{
\spadcommand{mystream := [i for i in 1..] \bound{mystream}}
}
\xtc{
This is a list of the prime integers between \axiom{1} and \axiom{10},
inclusive.
}{
\spadcommand{[i for i in 1..10 | prime? i]}
}
\xtc{
This is a stream of the prime integers greater than or equal to \axiom{1}.
}{
\spadcommand{[i for i in 1..   | prime? i]}
}
\xtc{
This is a list of the integers between \axiom{1} and \axiom{10},
inclusive, whose squares are less than \axiom{700}.
}{
\spadcommand{[i for i in 1..10 while i*i < 700]}
}
\xtc{
This is a stream of the integers greater than or equal to \axiom{1}
whose squares are less than \axiom{700}.
}{
\spadcommand{[i for i in 1..   while i*i < 700]}
}

Got the idea?
Here is the general rule.
\index{collection}

\beginImportant
The general syntax of a collection is
\begin{center}
{\tt [ {\it collectExpression} \subscriptIt{iterator}{1}  \subscriptIt{iterator}{2}  \ldots  \subscriptIt{iterator}{N} ]}
\end{center}
where each \subscriptIt{iterator}{i} is either a \axiom{for} or a
\axiom{while} clause.
The loop terminates immediately when the end test of any
\subscriptIt{iterator}{i} succeeds or when a \axiom{return} expression is
evaluated in {\it collectExpression}.
The value returned by the collection is either a list or a stream of
elements, one for each iteration of the {\it collectExpression}.
\endImportant

Be careful when you use \axiom{while}
\index{stream!using while @{using {\tt while}}}
to create a stream.
By default, \Language{} tries to compute and display the first ten elements
of a stream.
If the \axiom{while} condition is not satisfied quickly, \Language{}
can spend a long (possibly infinite) time trying to compute
\index{stream!number of elements computed}
the elements.
Use \spadcmd{)set streams calculate} to change the default
to something else.
\syscmdindex{set streams calculate}
This also affects the number of terms computed and displayed for power
series.
For the purposes of this book, we have used this system
command to display fewer than ten terms.
\xtc{
Use nested iterators to create lists of
\index{iteration!nested}
lists which can then be given as an argument to \axiomFun{matrix}.
}{
\spadcommand{matrix [[x^i+j for i in 1..3] for j in 10..12]}
}
\xtc{
You can also create lists of streams, streams of lists and
streams of streams.
Here is a stream of streams.
}{
\spadcommand{[[i/j for i in j+1..] for j in 1..]}
}
\xtc{
You can use parallel iteration across lists and streams to create
\index{iteration!parallel}
new lists.
}{
\spadcommand{[i/j for i in 3.. by 10 for j in 2..]}
}
\xtc{
Iteration stops if the end of a list or stream is reached.
}{
\spadcommand{[i^j for i in 1..7 for j in 2.. ]}
}
%\xtc{
%or a while condition fails.
%}{
%\spadcommand{[i^j for i in 1..  for j in 2.. while i + j < 5 ]}
%}
\xtc{
As with loops, you can combine these modifiers to make very
complicated conditions.
}{
\spadcommand{[[[i,j] for i in 10..15 | prime? i] for j in 17..22 | j = squareFreePart j]}
}

See \xmpref{List} and \xmpref{Stream} for more information on creating and
manipulating lists and streams, respectively.

% *********************************************************************
\head{section}{An Example: Streams of Primes}{ugLangStreamsPrimes}
% *********************************************************************

We conclude this chapter with an example of the creation and manipulation
of infinite streams of prime integers.
This might be useful for experiments with numbers or other applications
where you are using sequences of primes over and over again.
As for all streams, the stream of primes is only computed as far out as you
need.
Once computed, however, all the primes up to that point are saved for
future reference.

Two useful operations provided by the \Language{} library are
\axiomFunFrom{prime?}{IntegerPrimesPackage} and
\axiomFunFrom{nextPrime}{IntegerPrimesPackage}.
A straight-forward way to create a stream of
prime numbers is to start with the stream of positive integers \axiom{[2,..]} and
filter out those that are prime.
\xtc{
Create a stream of primes.
}{
\spadcommand{primes : Stream Integer := [i for i in 2.. | prime? i]}
}
A more elegant way, however, is to use the \axiomFunFrom{stream}{Stream}
operation from \axiomType{Stream}.
Given an initial value \axiom{a} and a function \axiom{f},
\axiomFunFrom{stream}{Stream}
constructs the stream \axiom{[a, f(a), f(f(a)), ...]}.
This function gives you the quickest method of getting the stream of primes.
\xtc{
This is how you use
\axiomFunFrom{stream}{Stream} to
generate an infinite stream of primes.
}{
\spadcommand{primes := stream(nextPrime,2)}
}
% decl seems necessary
\xtc{
Once the stream is generated, you might only be interested in
primes starting at a particular value.
}{
\spadcommand{smallPrimes := [p for p in primes | p > 1000] \bound{smallPrimes}}
}
\xtc{
Here are the first 11 primes greater than 1000.
}{
\spadcommand{[p for p in smallPrimes for i in 1..11] \free{smallPrimes}}
}
\xtc{
Here is a stream of primes between 1000 and 1200.
}{
\spadcommand{[p for p in smallPrimes while p < 1200] \free{smallPrimes}}
}
\xtc{
To get these expanded into a finite stream,
you call \axiomFunFrom{complete}{Stream} on the stream.
}{
\spadcommand{complete \%}
}
\xtc{
Twin primes are consecutive odd number pairs which are prime.
Here is the stream of twin primes.
}{
\spadcommand{twinPrimes := [[p,p+2] for p in primes | prime?(p + 2)]}
}
\xtc{
Since we already have the primes computed we can
avoid the call to \axiomFunFrom{prime?}{IntegerPrimesPackage}
by using a double iteration.
This time we'll just generate a stream of the first of the twin primes.
}{
\spadcommand{firstOfTwins:= [p for p in primes for q in rest primes | q=p+2]}
}

Let's try to compute the infinite stream of triplet primes,
the set of primes \axiom{p} such that \axiom{[p,p+2,p+4]}
are primes. For example, \axiom{[3,5,7]} is a triple prime.
We could do this by a triple \axiom{for} iteration.
A more economical way is to use \userfun{firstOfTwins}.
This time however, put a semicolon at the end of the line.

\xtc{Create the stream of firstTriplets.
Put a semicolon at the end so that no
elements are computed.
}{
\spadcommand{firstTriplets := [p for p in firstOfTwins for q in rest firstOfTwins | q = p+2];}
}

What happened?
As you know, by default
\Language{} displays the first ten
elements of a stream when you first display it.
And, therefore, it needs to compute them!
If you want {\it no} elements computed, just terminate the expression by a
semicolon (\axiomSyntax{;}).\footnote{
Why does this happen? The semi-colon prevents the display of the
result of evaluating the expression.
Since no stream elements are needed for display (or anything else, so far),
none are computed.
}

\xtc{
Compute the first triplet prime.
}{
\spadcommand{firstTriplets.1}
}

If you want to compute another, just ask for it.
But wait a second!
Given three consecutive odd integers, one of them must be divisible
by 3. Thus there is only one triplet prime.
But suppose that you did not know this and wanted to know what was the
tenth triplet prime.
\begin{verbatim}
firstTriples.10
\end{verbatim}
To compute the tenth triplet prime, \Language{} first must compute the second,
the third, and so on.
But since there isn't even a second triplet prime, \Language{} will
compute forever.
Nonetheless, this effort can produce a useful result.
After waiting a bit, hit
\texht{\fbox{\bf Ctrl}--\fbox{\bf c}}{{\bf Ctrl-c}}.
The system responds as follows.
\begin{verbatim}
   >> System error:
   Console interrupt.
   You are being returned to the top level of
   the interpreter.
\end{verbatim}
Let's say that you want to know how many primes have been computed.
Issue
\begin{verbatim}
numberOfComputedEntries primes
\end{verbatim}
and, for this discussion, let's say that the result is \axiom{2045.}
\xtc{
How big is the \eth{\axiom{2045}} prime?
}{
\spadcommand{primes.2045}
}

What you have learned is that there are no triplet primes between 5 and
17837.
Although this result is well known (some might even say trivial), there
are many experiments you could make where the result is not known.
What you see here is a paradigm for testing of hypotheses.
Here our hypothesis could have been: ``there is more than one triplet
prime.''
We have tested this hypothesis for 17837 cases.
With streams, you can let your machine run, interrupt it to see how far
it has progressed,
then start it up and let it continue from where it left off.

%> RDJ note to RSS:
%> Expressions not statements or lines--
%>   By an expression I mean any syntactically correct program fragment.
%>   Everything in AXIOM is an expression since every fragment has a value and a type.
%>   In most languages including LISP, a "statement" is different from an expression:
%>   it is executed for side-effect only and an error is incurred if you assign it a value.
%>   This "gimmick" takes care of incomplete expressions such as "if x > 0 then y" in blocks.
%>   In LISP, "u := (if x > 0 then y)" is illegal but in AXIOM it is legal.
%>   Also, in AXIOM the value of a repeat loop is void even though you might be
%>   be able to prove that it always returns a valid value (you have an example of this)!
%>   This will be considered a bug not a feature. But it is how things stand.
%>   In any case---this point should be in a box somewhere since it is key
%>   to a user's understanding to the language. I am not sure where. You only
%>   gain an appreciation for it after are awhile in chapter 5.
