% Copyright The Numerical Algorithms Group Limited 1992-94. All rights reserved.
% !! DO NOT MODIFY THIS FILE BY HAND !! Created by ht.awk.

%
%
%
%
%


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

%
\newcommand{\ugLangTitle}{Introduction to the \Language{} Interactive Language}
\newcommand{\ugLangNumber}{5.}
%
% =====================================================================
\begin{page}{ugLangPage}{5. Introduction to the \Language{} Interactive Language}
% =====================================================================
\beginscroll

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.

\beginmenu
    \menudownlink{{5.1. Immediate and Delayed Assignments}}{ugLangAssignPage}
    \menudownlink{{5.2. Blocks}}{ugLangBlocksPage}
    \menudownlink{{5.3. if-then-else}}{ugLangIfPage}
    \menudownlink{{5.4. Loops}}{ugLangLoopsPage}
    \menudownlink{{5.5. Creating Lists and Streams with Iterators}}{ugLangItsPage}
    \menudownlink{{5.6. An Example: Streams of Primes}}{ugLangStreamsPrimesPage}
\endmenu
\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangAssignTitle}{Immediate and Delayed Assignments}
\newcommand{\ugLangAssignNumber}{5.1.}
%
% =====================================================================
\begin{page}{ugLangAssignPage}{5.1. Immediate and Delayed Assignments}
% =====================================================================
\beginscroll

A \spadgloss{variable} in \Language{} refers to a value.
A variable has a name beginning with an uppercase or lowercase alphabetic
character, \spadSyntax{\%}, or \spadSyntax{!}.
Successive characters (if any) can be any of the above, digits, or
\spadSyntax{?}.
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 \spadSyntax{:=} operator is the immediate \spadgloss{assignment}
operator.
%-% \HDindex{assignment!immediate}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
Use it to associate a value with a variable.
%-% \HDindex{immediate assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}

\beginImportant
The syntax for immediate assignment for a single variable is
\centerline{{{\it variable} \spad{:=} {\it expression}}}
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 \spad{1}.  This value is then assigned to \spad{a}.
}{
\spadpaste{a := 1 \bound{a}}
}
\xtc{
The right-hand side of the expression is evaluated,
yielding \spad{1}.  This value is then assigned to \spad{b}.
Thus \spad{a} and \spad{b} both have the value \spad{1} after the sequence
of assignments.
}{
\spadpaste{b := a \free{a}\bound{b}}
}
\xtc{
What is the value of \spad{b} if \spad{a} is
assigned the value \spad{2}?
}{
\spadpaste{a := 2 \bound{a2}}
}
\xtc{
As you see, the value of \spad{b} is left unchanged.
}{
\spadpaste{b \free{b}}
}
This is what we mean when we say this kind of assignment is
{\it immediate};
\spad{b} has no dependency on \spad{a} after the initial assignment.
This is the usual notion of assignment found in programming
languages such as C,
%-% \HDindex{C language!assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
PASCAL
%-% \HDindex{PASCAL!assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
and FORTRAN.
%-% \HDindex{FORTRAN!assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}

\Language{} provides delayed assignment with \spadSyntax{==}.
%-% \HDindex{assignment!delayed}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
This implements a
%-% \HDindex{delayed assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
delayed evaluation of the right-hand side and dependency
checking.

\beginImportant
The syntax for delayed assignment is
\centerline{{{\it variable} \spad{==} {\it expression}}}
The value returned by a delayed assignment is \void{}.
\endImportant

\xtc{
Using \spad{a} and \spad{b} as above, these are the corresponding delayed
assignments.
}{
\spadpaste{a == 1 \bound{ad}}
}
\xtc{
}{
\spadpaste{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
}{
\spadpaste{a \free{ad}}
}
\xtc{
this evaluation seem the same as before.
}{
\spadpaste{b \free{bd}}
}
\xtc{
If we change \spad{a} to \spad{2}
}{
\spadpaste{a == 2 \bound{ad2}}
}
\xtc{
then
\spad{a} evaluates to \spad{2}, as expected, but
}{
\spadpaste{a \free{ad2}}
}
\xtc{
the value of \spad{b} reflects the change to \spad{a}.
}{
\spadpaste{b \free{bd ad2}}
}

It is possible to set several variables at the same time
%-% \HDindex{assignment!multiple immediate}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
by using
%-% \HDindex{multiple immediate assignment}{ugLangAssignPage}{5.1.}{Immediate and Delayed Assignments}
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
\centerline{{{\tt ( \subscriptIt{var}{1}, \subscriptIt{var}{2}, \ldots, \subscriptIt{var}{N} ) := ( \subscriptIt{expr}{1}, \subscriptIt{expr}{2}, \ldots, \subscriptIt{expr}{N} ) }}}
The value returned by an immediate assignment is the value of
\subscriptIt{expr}{N}.
\endImportant

\xtc{
This sets \spad{x} to \spad{1} and \spad{y} to \spad{2}.
}{
\spadpaste{(x,y) := (1,2) \bound{x}\bound{y}}
}
Multiple immediate assignments 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.
}{
\spadpaste{(x,y) := (y,x) \free{x y}\bound{swap}}
}
\xtc{
\spad{x} has the previous value of \spad{y}.
}{
\spadpaste{x \free{swap}}
}
\xtc{
\spad{y} has the previous value of \spad{x}.
}{
\spadpaste{y \free{swap}}
}

There is no syntactic form for multiple delayed assignments.
See the discussion in
\downlink{``\ugUserDelayTitle''}{ugUserDelayPage} in Section \ugUserDelayNumber\ignore{ugUserDelay}
about how \Language{} differentiates between delayed assignments and
user functions of no arguments.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangBlocksTitle}{Blocks}
\newcommand{\ugLangBlocksNumber}{5.2.}
%
% =====================================================================
\begin{page}{ugLangBlocksPage}{5.2. Blocks}
% =====================================================================
\beginscroll

%%
%% 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 \spad{break},
\spadkey{break}
\spad{return},
\spadkey{return}
\spad{iterate} and
\spadkey{iterate}
\spad{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 \spadSyntax{=>}.
For example, \spad{i < 0 => x}.
The expression before the \spadSyntax{=>} must evaluate to
\spad{true} or \spad{false}.
The expression following the \spadSyntax{=>} is the return value
for the block.

A block can be constructed in two ways:
\indent{4}
\beginitems
\item[1. ] the expressions can be separated by semicolons
and the resulting expression surrounded by parentheses, and
\item[2. ] the expressions can be written on succeeding lines with each line
indented the same number of spaces (which must be greater than zero).
%-% \HDindex{indentation}{ugLangBlocksPage}{5.2.}{Blocks}
A block entered in this form is
called a \spadgloss{pile}.
\enditems
\indent{0}
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
\centerline{{{\tt ( \subscriptIt{expression}{1}; \subscriptIt{expression}{2}; \ldots; \subscriptIt{expression}{N} )}}}
The value returned by a block is the value of an
\spadSyntax{=>} expression, or \subscriptIt{expression}{N}
if no \spadSyntax{=>} 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 \spad{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.
}{
\spadpaste{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.
}{
\spadpaste{(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.
%-% \HDindex{file!input}{ugLangBlocksPage}{5.2.}{Blocks}
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 \spad{h} is assigned \spad{2.1 + 3.5}.)
}{
\begin{spadsrc}[\bound{h}]
h := 2.1 +
   1.0
   3.5
\end{spadsrc}
}
\xtc{
Here the second argument to \spadfun{eval} is \spad{x = z}, where
the value of \spad{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 \spad{if-then-else}
expressions (see \downlink{``\ugLangIfTitle''}{ugLangIfPage} in Section \ugLangIfNumber\ignore{ugLangIf}).
}{
\spadpaste{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.
}{
\spadpaste{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 \spad{c + d} does equal \spad{3628855}, \spad{a} has the value
of \spad{c} and the last line is never evaluated.
}{
\begin{spadsrc}
a :=
  c := factorial 10
  d := fibonacci 10
  c + d = 3628855 => c
  d
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangIfTitle}{if-then-else}
\newcommand{\ugLangIfNumber}{5.3.}
%
% =====================================================================
\begin{page}{ugLangIfPage}{5.3. if-then-else}
% =====================================================================
\beginscroll

Like many other programming languages, \Language{} uses the three
keywords \spadkey{if} \spad{if, then} \spadkey{then} and \spad{else}
\spadkey{else} to form
%-% \HDindex{conditional}{ugLangIfPage}{5.3.}{if-then-else}
conditional expressions.
The \spad{else} part of the conditional is optional.
The expression between the \spad{if} and \spad{then} keywords
is a
\spadgloss{predicate}: an expression that evaluates to or is convertible to
either {\tt true} or {\tt false}, that is,
a \spadtype{Boolean}.
%-% \HDexptypeindex{Boolean}{ugLangIfPage}{5.3.}{if-then-else}

\beginImportant
The syntax for conditional expressions is
\centerline{{{\tt if {\it predicate} then \subscriptIt{expression}{1} else \subscriptIt{expression}{2}}}}
where the \spad{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 \spad{true}
and \subscriptIt{\it expression}{2} otherwise.
If no \spad{else} clause is given, the value is always \void{}.
\endImportant

An \spad{if-then-else} expression always returns a value.
If the
\spad{else} clause is missing then the entire expression returns
\void{}.
If both clauses are present, the type of the value returned by \spad{if}
is obtained by resolving the types of the values of the two clauses.
See \downlink{``\ugTypesResolveTitle''}{ugTypesResolvePage} in Section \ugTypesResolveNumber\ignore{ugTypesResolve}
for more information.

The predicate must evaluate to, or be convertible to, an object of type
\spadtype{Boolean}: {\tt true} or {\tt false}.
By default, the equal sign \spadopFrom{=}{Equation} creates
%-% \HDindex{equation}{ugLangIfPage}{5.3.}{if-then-else}
an equation.
\xtc{
This is an equation.
%-% \HDexptypeindex{Equation}{ugLangIfPage}{5.3.}{if-then-else}
In particular, it is an object of type \spadtype{Equation Polynomial Integer}.
}{
\spadpaste{x + 1 = y}
}
However, for predicates in \spad{if} expressions, \Language{}
%-% \HDindex{equality testing}{ugLangIfPage}{5.3.}{if-then-else}
places a default target type of \spadtype{Boolean} on the
predicate and equality testing is performed.
%-% \HDexptypeindex{Boolean}{ugLangIfPage}{5.3.}{if-then-else}
Thus you need not qualify the \spadSyntax{=} 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 \spadSyntax{@} and a target type of
\spadtype{Boolean}.
See \downlink{``\ugTypesPkgCallTitle''}{ugTypesPkgCallPage} in Section \ugTypesPkgCallNumber\ignore{ugTypesPkgCall} for more information.

The compound symbol meaning ``not equal'' in \Language{} is
%-% \HDindex{inequality testing}{ugLangIfPage}{5.3.}{if-then-else}
``\texht{$\sim =$}{\spad{~=}}''.
%-% \HDindex{\_notequal@$\sim =$}{ugLangIfPage}{5.3.}{if-then-else}
This can be used directly without a package call or a target specification.
The expression
\spad{a} \texht{$\sim =$}{\spad{~=}} \spad{b} is directly translated into
\spad{not (a = b)}.

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

The usual rules for piles are suspended for conditional expressions.
In {\bf .input} files, the \spad{then} and
\spad{else} keywords can begin in the same column as the corresponding
\spad{if} but may also appear to the right.
Each of the following styles of writing \spad{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 \spad{then} or \spad{else} keywords.
In the following two assignments to \spad{a}, the \spad{then} and \spad{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}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsTitle}{Loops}
\newcommand{\ugLangLoopsNumber}{5.4.}
%
% =====================================================================
\begin{page}{ugLangLoopsPage}{5.4. Loops}
% =====================================================================
\beginscroll

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

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

\beginmenu
    \menudownlink{{5.4.1. Compiling vs. Interpreting Loops}}{ugLangLoopsCompIntPage}
    \menudownlink{{5.4.2. return in Loops}}{ugLangLoopsReturnPage}
    \menudownlink{{5.4.3. break in Loops}}{ugLangLoopsBreakPage}
    \menudownlink{{5.4.4. break vs. {\tt =>} in Loop Bodies}}{ugLangLoopsBreakVsPage}
    \menudownlink{{5.4.5. More Examples of break}}{ugLangLoopsBreakMorePage}
    \menudownlink{{5.4.6. iterate in Loops}}{ugLangLoopsIteratePage}
    \menudownlink{{5.4.7. while Loops}}{ugLangLoopsWhilePage}
    \menudownlink{{5.4.8. for Loops}}{ugLangLoopsForInPage}
    \menudownlink{{5.4.9. for i in n..m repeat}}{ugLangLoopsForInNMPage}
    \menudownlink{{5.4.10. for i in n..m by s repeat}}{ugLangLoopsForInNMSPage}
    \menudownlink{{5.4.11. for i in n.. repeat}}{ugLangLoopsForInNPage}
    \menudownlink{{5.4.12. for x in l repeat}}{ugLangLoopsForInXLPage}
    \menudownlink{{5.4.13. ``Such that'' Predicates}}{ugLangLoopsForInPredPage}
    \menudownlink{{5.4.14. Parallel Iteration}}{ugLangLoopsParPage}
\endmenu
\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsCompIntTitle}{Compiling vs. Interpreting Loops}
\newcommand{\ugLangLoopsCompIntNumber}{5.4.1.}
%
% =====================================================================
\begin{page}{ugLangLoopsCompIntPage}{5.4.1. Compiling vs. Interpreting Loops}
% =====================================================================
\beginscroll

\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
%-% \HDindex{loop!compilation}{ugLangLoopsCompIntPage}{5.4.1.}{Compiling vs. Interpreting Loops}
message stating the problem and then the following message:
%
\centerline{{{\bf We will attempt to step through and interpret the code.}}}
%
It is still possible that \Language{} can evaluate the loop but in
\spadgloss{interpret-code mode}.
See \downlink{``\ugUserCompIntTitle''}{ugUserCompIntPage} in Section \ugUserCompIntNumber\ignore{ugUserCompInt} where this is discussed in terms
%-% \HDindex{panic!avoiding}{ugLangLoopsCompIntPage}{5.4.1.}{Compiling vs. Interpreting Loops}
of compiling versus interpreting functions.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsReturnTitle}{return in Loops}
\newcommand{\ugLangLoopsReturnNumber}{5.4.2.}
%
% =====================================================================
\begin{page}{ugLangLoopsReturnPage}{5.4.2. return in Loops}
% =====================================================================
\beginscroll

A \spad{return} expression is used to exit a function with
%-% \HDindex{loop!leaving via return}{ugLangLoopsReturnPage}{5.4.2.}{return in Loops}
a particular value.
In particular, if a \spad{return} is in a loop within the
\spadkey{return}
function, the loop is terminated whenever the \spad{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 \spad{factorial(i)} is big enough, control passes from
inside the loop all the way outside the function, returning the
value of \spad{i} (or so we think).
}{
\spadpaste{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 \spadtype{Void}.

There are two ways to fix this.
The best way is for you to tell \Language{} what the return type
of \spad{f} is.
You do this by giving \spad{f} a declaration \spad{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
\downlink{``\ugUserBlocksTitle''}{ugUserBlocksPage} in Section \ugUserBlocksNumber\ignore{ugUserBlocks}
for more information.
}{
\spadpaste{f() \free{f1}}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsBreakTitle}{break in Loops}
\newcommand{\ugLangLoopsBreakNumber}{5.4.3.}
%
% =====================================================================
\begin{page}{ugLangLoopsBreakPage}{5.4.3. break in Loops}
% =====================================================================
\beginscroll

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

\xtc{
This example is a modification of the last example in
\texht{the previous section}{\downlink{``\ugLangLoopsReturnTitle''}{ugLangLoopsReturnPage} in Section \ugLangLoopsReturnNumber\ignore{ugLangLoopsReturn}}.
Instead of using \spad{return}, we'll use \spad{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 \spad{factorial(i)} gets big enough,
the last line of the function evaluates to the corresponding ``good''
value of \spad{i}, and the function terminates, returning that value.
}{
\spadpaste{f() \free{f1}}
}
\xtc{
You can only use \spad{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.
}{
\spadpaste{(i,j) := (1, 1) \bound{i}\bound{j}}
}
\xtc{
Nested loops must have multiple \spad{break}
%-% \HDindex{loop!nested}{ugLangLoopsBreakPage}{5.4.3.}{break in Loops}
expressions at the appropriate nesting level.
How would you rewrite this so \spad{(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}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsBreakVsTitle}{break vs. {\tt =>} in Loop Bodies}
\newcommand{\ugLangLoopsBreakVsNumber}{5.4.4.}
%
% =====================================================================
\begin{page}{ugLangLoopsBreakVsPage}{5.4.4. break vs. {\tt =>} in Loop Bodies}
% =====================================================================
\beginscroll

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 \spad{i} are displayed
but then the \spadSyntax{=>} does not allow control to reach the call to
\spadfunFrom{output}{OutputForm} again.
The loop will not terminate
until you run out of space or interrupt the execution.
The variable \spad{i} will continue to be incremented because
the \spadSyntax{=>} only means to leave the {\it block,} not the loop.

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

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsBreakMoreTitle}{More Examples of break}
\newcommand{\ugLangLoopsBreakMoreNumber}{5.4.5.}
%
% =====================================================================
\begin{page}{ugLangLoopsBreakMorePage}{5.4.5. More Examples of break}
% =====================================================================
\beginscroll

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

\texht{\vskip 1pc}{}
\xtc{
First, initialize \spad{i} as the loop counter.
}{
\spadpaste{i := 0 \bound{i}}
}
\xtc{
Here is the first loop.
When the square of \spad{i} exceeds \spad{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, \spad{i} should have the value \spad{11}.
}{
\spadpaste{i \free{i1}}
}
%
%
\xtc{
Do the same thing except use \spadSyntax{=>} instead
an \spad{if-then} expression.
}{
\spadpaste{i := 0 \bound{i2}}
}
\xtc{
}{
\begin{spadsrc}[\free{i2}\bound{i3}]
repeat
  i := i + 1
  i^2 > 100 => break
\end{spadsrc}
}
\xtc{
}{
\spadpaste{i \free{i3}}
}
%
%
\xtc{
As a third example, we use a simple loop to compute \spad{n!}.
}{
\spadpaste{(n, i, f) := (100, 1, 1) \bound{n}\bound{i4}\bound{f}}
}
\xtc{
Use \spad{i} as the iteration variable and \spad{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 \spad{f}.
}{
\spadpaste{f \free{f1}}
}
%
%
\xtc{
Finally, we show an example of nested loops.
First define a four by four matrix.
}{
\spadpaste{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 \spad{r} and column counter \spad{c} to
\mathOrSpad{1}.
Note: if we were writing a function, these would all be local
variables rather than global workspace variables.
}{
\spadpaste{(r, c) := (1, 1) \bound{r}\bound{c}}
}
\xtc{
Also, let \spad{lastrow} and
\spad{lastcol} be the final row and column index.
}{
\spadpaste{(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 \spad{for} clause with \spad{repeat}.
See
\downlink{``\ugLangLoopsForInTitle''}{ugLangLoopsForInPage} in Section \ugLangLoopsForInNumber\ignore{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}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsIterateTitle}{iterate in Loops}
\newcommand{\ugLangLoopsIterateNumber}{5.4.6.}
%
% =====================================================================
\begin{page}{ugLangLoopsIteratePage}{5.4.6. iterate in Loops}
% =====================================================================
\beginscroll

\Language{} provides an \spad{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.
}{
\spadpaste{i := 0 \bound{i}}
}
\xtc{
Display the even integers from \spad{2} to \spad{5}.
}{
\begin{spadsrc}[\free{i}]
repeat
  i := i + 1
  if i > 5 then break
  if odd?(i) then iterate
  output(i)
\end{spadsrc}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsWhileTitle}{while Loops}
\newcommand{\ugLangLoopsWhileNumber}{5.4.7.}
%
% =====================================================================
\begin{page}{ugLangLoopsWhilePage}{5.4.7. while Loops}
% =====================================================================
\beginscroll

The \spad{repeat} in a loop can be modified by adding one or
more \spad{while} clauses.
\spadkey{while}
Each clause contains a \spadgloss{predicate}
immediately following the \spad{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 \spad{while}
clause are all \spad{true}.

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

\xtc{
Here is a simple example of using \spad{while} in a loop.
We first initialize the counter.
}{
\spadpaste{i := 1 \bound{i}}
}
\xtc{
The steps involved in computing this example are
(1) set \spad{i} to \spad{1}, (2) test the condition \spad{i < 1} and
determine that it is not true, and (3) do not evaluate the
loop body and therefore do not display \spad{"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 \spad{and} operation to separate them.
\Language{} evaluates these predicates from left to right.
}{
\spadpaste{(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 \spad{break} expression can be included in a loop body to terminate a
loop even if the predicate in any \spad{while} clauses are not \spad{false}.
}{
\spadpaste{(x, y) := (1, 1) \bound{x1}\bound{y1}}
}
\xtc{
This loop has multiple \spad{while} clauses and the loop terminates
before any one of their conditions evaluates to \spad{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.
}{
\spadpaste{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 \spad{1} and
get the number of rows and columns.
If we were writing a function, these would all be
local variables.
}{
\spadpaste{r := 1 \bound{r}}
}
\xtc{
}{
\spadpaste{(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}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInTitle}{for Loops}
\newcommand{\ugLangLoopsForInNumber}{5.4.8.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInPage}{5.4.8. for Loops}
% =====================================================================
\beginscroll

\Language{} provides the \spad{for}
\spadkey{for}
and \spad{in}
\spadkey{in}
keywords in \spad{repeat} loops,
allowing you to iterate across all
%-% \HDindex{iteration}{ugLangLoopsForInPage}{5.4.8.}{for Loops}
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 \spad{repeat} loops as
\spad{for} clauses.
These clauses can be present in addition to \spad{while} clauses.
As with all other types of \spad{repeat} loops, \spad{break} can
\spadkey{break}
be used to prematurely terminate the evaluation of the loop.

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

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInNMTitle}{for i in n..m repeat}
\newcommand{\ugLangLoopsForInNMNumber}{5.4.9.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInNMPage}{5.4.9. for i in n..m repeat}
% =====================================================================
\beginscroll

If \spad{for}
\spadkey{for}
is followed by a variable name, the \spad{in}
\spadkey{in}
keyword and then an integer segment of the form \spad{n..m},
%-% \HDindex{segment}{ugLangLoopsForInNMPage}{5.4.9.}{for i in n..m repeat}
the end test for this loop is the predicate \spad{i > m}.
The body of the loop is evaluated \spad{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 \spad{i} has the value
\spad{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$}{\spad{10^3, 11^3, and 12^3}}:
}{
\spadpaste{for i in 10..12 repeat output(i^3)}
}
%
\xtc{
Here is a sample list.
}{
\spadpaste{a := [1,2,3] \bound{a}}
}
\xtc{
Iterate across this list, using \spadSyntax{.} to access the elements of a list and
the \spadfun{\#} operation to count its elements.
}{
\spadpaste{for i in 1..\#a repeat output(a.i) \free{a}}
}
%
This type of iteration is applicable to anything that uses \spadSyntax{.}.
You can also use it with functions that use indices to extract elements.
%
\xtc{
Define \spad{m} to be a matrix.
}{
\spadpaste{m := matrix [[1,2],[4,3],[9,0]] \bound{m}}
}
\xtc{
Display the rows of \spad{m}.
}{
\spadpaste{for i in 1..nrows(m) repeat output row(m,i) \free{m}}
}
%
You can use \spad{iterate} with \spad{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 \downlink{`Segment'}{SegmentXmpPage}\ignore{Segment} for more information about segments.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInNMSTitle}{for i in n..m by s repeat}
\newcommand{\ugLangLoopsForInNMSNumber}{5.4.10.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInNMSPage}{5.4.10. for i in n..m by s repeat}
% =====================================================================
\beginscroll

By default, the difference between values taken on by a variable in loops
such as \spad{for i in n..m repeat ...} is \mathOrSpad{1}.
It is possible to supply another, possibly negative, step value by using
the \spad{by}
\spadkey{by}
keyword along with \spad{for} and \spad{in}.
Like the upper and lower bounds, the step value following the
\spad{by} keyword must be an integer.
Note that the loop
\spad{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.
}{
\spadpaste{for i in 1..5 by 2 repeat output(i)}
}
\xtc{
Use this to display the numbers in reverse order.
}{
\spadpaste{for i in 5..1 by -2 repeat output(i)}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInNTitle}{for i in n.. repeat}
\newcommand{\ugLangLoopsForInNNumber}{5.4.11.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInNPage}{5.4.11. for i in n.. repeat}
% =====================================================================
\beginscroll

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

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

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInXLTitle}{for x in l repeat}
\newcommand{\ugLangLoopsForInXLNumber}{5.4.12.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInXLPage}{5.4.12. for x in l repeat}
% =====================================================================
\beginscroll

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

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

Since the list constructing expression \spad{expand [n..m]} creates the
list \spad{[n, n+1, ..., m]}\footnote{This list is empty if \spad{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
\spad{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
\spad{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 \spad{2400000}.
}{
\spadpaste{for f in factors(factor(2400000)) repeat output(f)}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsForInPredTitle}{``Such that'' Predicates}
\newcommand{\ugLangLoopsForInPredNumber}{5.4.13.}
%
% =====================================================================
\begin{page}{ugLangLoopsForInPredPage}{5.4.13. ``Such that'' Predicates}
% =====================================================================
\beginscroll

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

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

The predicate need not refer only to the variable in the \spad{for} clause:
any variable in an outer scope can be part of the predicate.
\xtc{
In this example, the predicate on the inner \spad{for} loop uses
\spad{i} from the outer loop and the \spad{j} from the \spad{for}
%-% \HDindex{iteration!nested}{ugLangLoopsForInPredPage}{5.4.13.}{``Such that'' Predicates}
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}
}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangLoopsParTitle}{Parallel Iteration}
\newcommand{\ugLangLoopsParNumber}{5.4.14.}
%
% =====================================================================
\begin{page}{ugLangLoopsParPage}{5.4.14. Parallel Iteration}
% =====================================================================
\beginscroll

The last example of
\texht{the previous section}{\downlink{``\ugLangLoopsForInPredTitle''}{ugLangLoopsForInPredPage} in Section \ugLangLoopsForInPredNumber\ignore{ugLangLoopsForInPred}}
gives an example of
\spadgloss{nested iteration}: a loop is contained
%-% \HDindex{iteration!nested}{ugLangLoopsParPage}{5.4.14.}{Parallel Iteration}
in another loop.
%-% \HDindex{iteration!parallel}{ugLangLoopsParPage}{5.4.14.}{Parallel Iteration}
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
\centerline{{{\tt \subscriptIt{iterator}{1} \subscriptIt{iterator}{2} \ldots \subscriptIt{iterator}{N} repeat {\it loopBody}}}}
where each {\it iterator} is either a \spad{for} or a \spad{while} clause.
The loop terminates immediately when the end test of any {\it iterator}
succeeds or when a \spad{break} or \spad{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.
}{
\spadpaste{l := [1,3,5,7] \bound{l}}
}
\xtc{
And the second.
}{
\spadpaste{m := [100,200] \bound{m}}
}
\xtc{
The initial value of the sum counter.
}{
\spadpaste{sum := 0 \bound{sum}}
}
\xtc{
The last two elements of \spad{l} are not used in the calculation
because \spad{m} has two fewer elements than \spad{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.''
}{
\spadpaste{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.
}{
\spadpaste{l := [2,3,5,7,11,13,17,19,23,29,31,37] \bound{l1}}
}
\xtc{
The initial sum.
}{
\spadpaste{sum := 0 \bound{sum1}}
}
\xtc{
Here looping stops when the list \spad{l} is exhausted, even though
the \spad{for i in 0..} specifies no terminating condition.
}{
\spadpaste{for i in 0.. for x in l repeat sum := i * x \bound{doit1}\free{sum1 l1}}
}
\xtc{
Display this weighted sum.
}{
\spadpaste{sum \free{doit1}}
}

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

This is correct:
\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 \spad{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
%-% \HDindex{loop!mixing modifiers}{ugLangLoopsParPage}{5.4.14.}{Parallel Iteration}
forms of \spad{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:
\indent{4}
\beginitems
\item[1. ] \spad{while} predicates can only refer to variables that
are global (or in an outer scope)
or that are defined in \spad{for} clauses to the left of the
predicate.
\item[2. ] A ``such that'' predicate (something following \spadSyntax{|})
must directly follow a \spad{for} clause and can only refer to
variables that are global (or in an outer scope)
or defined in the modified \spad{for} clause
or any \spad{for} clause to the left.
\enditems
\indent{0}

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangItsTitle}{Creating Lists and Streams with Iterators}
\newcommand{\ugLangItsNumber}{5.5.}
%
% =====================================================================
\begin{page}{ugLangItsPage}{5.5. Creating Lists and Streams with Iterators}
% =====================================================================
\beginscroll

All of what we did for loops in \downlink{``\ugLangLoopsTitle''}{ugLangLoopsPage} in Section \ugLangLoopsNumber\ignore{ugLangLoops}
%-% \HDindex{iteration}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
can be transformed into expressions that create lists
%-% \HDindex{list!created by iterator}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
and streams.
%-% \HDindex{stream!created by iterator}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
The \spad{repeat,} \spad{break} or \spad{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 \spad{1} to \spad{10}.
}{
\spadpaste{mylist := [i for i in 1..10] \bound{mylist}}
}
\xtc{
Create a stream of the integers greater than or equal to \spad{1}.
}{
\spadpaste{mystream := [i for i in 1..] \bound{mystream}}
}
\xtc{
This is a list of the prime integers between \spad{1} and \spad{10},
inclusive.
}{
\spadpaste{[i for i in 1..10 | prime? i]}
}
\xtc{
This is a stream of the prime integers greater than or equal to \spad{1}.
}{
\spadpaste{[i for i in 1..   | prime? i]}
}
\xtc{
This is a list of the integers between \spad{1} and \spad{10},
inclusive, whose squares are less than \spad{700}.
}{
\spadpaste{[i for i in 1..10 while i*i < 700]}
}
\xtc{
This is a stream of the integers greater than or equal to \spad{1}
whose squares are less than \spad{700}.
}{
\spadpaste{[i for i in 1..   while i*i < 700]}
}

Got the idea?
Here is the general rule.
%-% \HDindex{collection}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}

\beginImportant
The general syntax of a collection is
\centerline{{{\tt [ {\it collectExpression} \subscriptIt{iterator}{1}  \subscriptIt{iterator}{2}  \ldots  \subscriptIt{iterator}{N} ]}}}
where each \subscriptIt{iterator}{i} is either a \spad{for} or a
\spad{while} clause.
The loop terminates immediately when the end test of any
\subscriptIt{iterator}{i} succeeds or when a \spad{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 \spad{while}
%-% \HDindex{stream!using while @{using {\tt while}}}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
to create a stream.
By default, \Language{} tries to compute and display the first ten elements
of a stream.
If the \spad{while} condition is not satisfied quickly, \Language{}
can spend a long (possibly infinite) time trying to compute
%-% \HDindex{stream!number of elements computed}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
the elements.
Use \spadcmd{)set streams calculate} to change the default
to something else.
%-% \HDsyscmdindex{set streams calculate}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
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
%-% \HDindex{iteration!nested}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
lists which can then be given as an argument to \spadfun{matrix}.
}{
\spadpaste{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.
}{
\spadpaste{[[i/j for i in j+1..] for j in 1..]}
}
\xtc{
You can use parallel iteration across lists and streams to create
%-% \HDindex{iteration!parallel}{ugLangItsPage}{5.5.}{Creating Lists and Streams with Iterators}
new lists.
}{
\spadpaste{[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.
}{
\spadpaste{[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.
}{
\spadpaste{[[[i,j] for i in 10..15 | prime? i] for j in 17..22 | j = squareFreePart j]}
}

See \downlink{`List'}{ListXmpPage}\ignore{List} and \downlink{`Stream'}{StreamXmpPage}\ignore{Stream} for more information on creating and
manipulating lists and streams, respectively.

\endscroll
\autobuttons
\end{page}
%
%
\newcommand{\ugLangStreamsPrimesTitle}{An Example: Streams of Primes}
\newcommand{\ugLangStreamsPrimesNumber}{5.6.}
%
% =====================================================================
\begin{page}{ugLangStreamsPrimesPage}{5.6. An Example: Streams of Primes}
% =====================================================================
\beginscroll

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
\spadfunFrom{prime?}{IntegerPrimesPackage} and
\spadfunFrom{nextPrime}{IntegerPrimesPackage}.
A straight-forward way to create a stream of
prime numbers is to start with the stream of positive integers \spad{[2,..]} and
filter out those that are prime.
\xtc{
Create a stream of primes.
}{
\spadpaste{primes : Stream Integer := [i for i in 2.. | prime? i]}
}
A more elegant way, however, is to use the \spadfunFrom{stream}{Stream}
operation from \spadtype{Stream}.
Given an initial value \spad{a} and a function \spad{f},
\spadfunFrom{stream}{Stream}
constructs the stream \spad{[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
\spadfunFrom{stream}{Stream} to
generate an infinite stream of primes.
}{
\spadpaste{primes := stream(nextPrime,2)}
}
\xtc{
Once the stream is generated, you might only be interested in
primes starting at a particular value.
}{
\spadpaste{smallPrimes := [p for p in primes | p > 1000] \bound{smallPrimes}}
}
\xtc{
Here are the first 11 primes greater than 1000.
}{
\spadpaste{[p for p in smallPrimes for i in 1..11] \free{smallPrimes}}
}
\xtc{
Here is a stream of primes between 1000 and 1200.
}{
\spadpaste{[p for p in smallPrimes while p < 1200] \free{smallPrimes}}
}
\xtc{
To get these expanded into a finite stream,
you call \spadfunFrom{complete}{Stream} on the stream.
}{
\spadpaste{complete \%}
}
\xtc{
Twin primes are consecutive odd number pairs which are prime.
Here is the stream of twin primes.
}{
\spadpaste{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 \spadfunFrom{prime?}{IntegerPrimesPackage}
by using a double iteration.
This time we'll just generate a stream of the first of the twin primes.
}{
\spadpaste{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 \spad{p} such that \spad{[p,p+2,p+4]}
are primes. For example, \spad{[3,5,7]} is a triple prime.
We could do this by a triple \spad{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.
}{
\spadpaste{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 (\spadSyntax{;}).\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.
}{
\spadpaste{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 \spad{2045.}
\xtc{
How big is the \eth{\spad{2045}} prime?
}{
\spadpaste{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.
\endscroll
\autobuttons
\end{page}
%
