
% 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}{0}}{} % Chapter 1

\begin{texonly}
\hyphenation{
Uni-var-iate-Poly-nomial
Mul-ti-var-iate-Poly-nomial
Distributed-Mul-ti-var-iate-Poly-nomial
Homo-gen-eous-Distributed-Mul-ti-var-iate-Poly-nomial
New-Distributed-Mul-ti-var-iate-Poly-nomial
General-Distributed-Mul-ti-var-iate-Poly-nomial
}
\end{texonly}

% *********************************************************************
\head{chapter}{An Overview of \Language{}}{ugIntro}
% *********************************************************************

Welcome to the \Language{} environment for interactive computation
and problem solving.
Consider this chapter a brief, whirlwind tour of the \Language{}
world.
We introduce you to \Language{}'s graphics and the \Language{}
language.
Then we give a sampling of the large variety of facilities
in the \Language{} system, ranging from the various kinds of
numbers, to data types (like lists, arrays, and sets) and
mathematical objects (like matrices, integrals, and differential
equations).
We conclude with the discussion of system commands and an
interactive ``undo.''

Before embarking on the tour, we need to brief those readers
working interactively with \Language{} on some details.
Others can skip right immediately to
\spadref{ugIntroTypo}.

% *********************************************************************
\head{section}{Starting Up and Winding Down}{ugIntroStart}
% *********************************************************************
%

You need to know how to start the \Language{} system and how to stop it.
We assume that \Language{} has been correctly installed on your
machine (as described in another \Language{} document).

To begin using \Language{}, issue the command {\bf axiom} to the
\index{starting @{starting \Language{}}}
operating system shell.
\index{axiom @{\bf axiom}}
There is a brief pause, some start-up messages, and then one
or more windows appear.

If you are not running \Language{} under the X Window System, there is
only one window (the console).
At the lower left of the screen there is a prompt that
\index{prompt}
looks like
\begin{verbatim}
(1) ->
\end{verbatim}
%%--> do you want to talk about equation numbers on the right, etc.
When you want to enter input to \Language{}, you do so on the same line
after the prompt.
The ``1'' in ``(1)'' is the computation step number and is incremented
\index{step number}
after you enter \Language{} statements.
Note, however, that a system command
such as \spadsys{)clear all}
may change the step number in other ways.
We talk about step numbers more when we discuss system commands
and the workspace history facility.

If you are running \Language{} under the X Window System, there may be two
\index{X Window System}
windows: the console window (as just described) and the \HyperName{}
main menu.
\index{Hyper @{\HyperName{}}}
\HyperName{} is a multiple-window hypertext system that lets you
\index{window}
view \Language{} documentation and examples on-line,
execute \Language{} expressions, and generate graphics.
If you are in a graphical windowing environment,
it is usually started automatically when \Language{} begins.
If it is not running, issue \spadsys{)hd} to start it.
We discuss the basics of \HyperName{} in \chapref{ugHyper}.
\syscmdindex{hd}

To interrupt an \Language{} computation, hold down the
\index{interrupt}
\texht{\fbox{\bf Ctrl}}{{\bf Ctrl}} (control) key and press
\texht{\fbox{\bf c}}{{\bf c}}.
This  brings you back to the \Language{} prompt.

\beginImportant
To exit from \Language{},  move to the console window,
\index{stopping @{stopping \Language{}}}
type \spadsys{)quit}
\index{exiting @{exiting \Language{}}}
at the input prompt and press the \texht{\fbox{\bf Enter}}{{\bf Enter}} key.
\syscmdindex{quit}
You will probably be prompted with the following message:
\begin{center}
Please enter {\bf y} or {\bf yes} if you really want to leave the \\
interactive environment and return to the operating system
\end{center}
You should respond {\bf yes}, for example, to exit \Language{}.
\endImportant

We are purposely vague in describing exactly what your screen
looks like or what messages \Language{} displays.
\Language{} runs on a number of different machines, operating
systems and window environments, and these differences all affect
the physical look of the system.
You can also change the way that \Language{} behaves via
\spadgloss{system commands} described later in this chapter and in
\appxref{ugSysCmd}.
System commands are special commands, like \spadcmd{)set}, that begin
with a closing parenthesis and are used to change your
environment.
For example, you can set a system variable so that you are not
prompted for confirmation when you want to leave \Language{}.

% *********************************************************************
\head{subsection}{\Clef{}}{ugAvailCLEF}
% *********************************************************************
%
If you are using \Language{} under the X Window System, the
\index{Clef@{\Clef{}}}
\index{command line editor}
\Clef{} command line editor is probably available and installed.
With this editor you can recall previous lines with the up and
down arrow keys\texht{ (\fbox{$\uparrow$} and
\fbox{$\downarrow$})}{}.
To move forward and backward on a line, use the right and
left arrows\texht{ (\fbox{$\rightarrow$} and
\fbox{$\leftarrow$})}{}.
You can use the
\texht{\fbox{\bf Insert}}{{\bf Insert}}
key to toggle insert mode on or off.
When you are in insert mode,
the cursor appears as a large block and if you type
anything, the characters are inserted into the line without
deleting the previous ones.

If you press the
\texht{\fbox{\bf Home}}{{\bf Home}}
key, the cursor moves to the beginning of the line and if you press the
\texht{\fbox{\bf End}}{{\bf End}}
key, the cursor moves to the end of the line.
Pressing
\texht{\fbox{\bf Ctrl}--\fbox{\bf End}}{{\bf Ctrl-End}}
deletes all the text from the cursor to the end of the line.

\Clef{} also provides \Language{} operation name completion for
\index{operation name completion}
a limited set of operations.
If you enter a few letters and then press the
\texht{\fbox{\bf Tab}}{{\bf Tab}} key,
\Clef{} tries to use those letters as the prefix of an \Language{}
operation name.
If a name appears and it is not what you want, press
\texht{\fbox{\bf Tab}}{{\bf Tab}} again
to see another name.

You are ready to begin your journey into the world of \Language{}.
Proceed to the first stop.

% *********************************************************************
\head{section}{Typographic Conventions}{ugIntroTypo}
% *********************************************************************

In this book we have followed these typographical conventions:
\begin{itemize}
%
\item Categories, domains and packages are displayed in
\texht{a sans-serif typeface:}{this font:}
\spadtype{Ring}, \spadtype{Integer}, \spadtype{DiophantineSolutionPackage}.
%
\item Prefix operators, infix operators, and punctuation symbols in the \Language{}
language are displayed in the text like this:
\spadop{+}, \spadSyntax{\$}, \spadSyntax{+->}.
%
\item \Language{} expressions or expression fragments are displayed in
\texht{a mon\-o\-space typeface:}{this font:}
\spad{inc(x) == x + 1}.
%
\item For clarity of presentation, \TeX{} is often
used to format expressions\texht{: $g(x)=x^2+1.$}{.}
%
\item Function names and \HyperName{} button names
are displayed in the text in
\texht{a bold typeface:}{this font:}
\spadfun{factor}, \spadfun{integrate},  {\bf Lighting}.
%
\item Italics are used for emphasis and for words defined in the
glossary: \spadgloss{category}.
\end{itemize}

This book contains over 2500 examples of \Language{} input and output.
All examples were run though \Language{} and their output was
created in \texht{\TeX{}}{TeX} form for this book by the \Language{}
\spadtype{TexFormat} package.
\exptypeindex{TexFormat}
We have deleted system messages from the example output if those
messages are not important for the discussions in which the examples
appear.

% *********************************************************************
\head{section}{The \Language{} Language}{ugIntroExpressions}
% *********************************************************************
%

The \Language{} language is a rich language for performing
interactive computations and for building components of the
\Language{} library.
Here we present only some basic aspects of the language that you
need to know for the rest of this chapter.
Our discussion here is intentionally informal, with details
unveiled on an ``as needed'' basis.
For more information on a particular construct, we suggest you
consult the index at the back of the book.

% *********************************************************************
\head{subsection}{Arithmetic Expressions}{ugIntroArithmetic}
% *********************************************************************

For arithmetic expressions, use the \spadop{+} and \spadop{-}
\spadglossSee{operators}{operator} as in mathematics.
Use \spadop{*} for multiplication, and \spadop{^} for
exponentiation.
To create a fraction, use \spadop{/}.
When an expression contains several operators, those of highest
\spadgloss{precedence} are evaluated first.
For arithmetic operators, \spadop{^} has highest precedence,
\spadop{*} and \spadop{/} have the next highest
precedence, and \spadop{+} and \spadop{-} have the lowest
precedence.

\xtc{
\Language{} puts implicit parentheses around operations of higher
precedence, and groups those of equal precedence from left to right.
}{
\spadcommand{1 + 2 - 3 / 4 * 3 ^ 2 - 1}
}
\xtc{
The above expression is equivalent to this.
}{
\spadcommand{((1 + 2) - ((3 / 4) * (3 ^ 2))) - 1}
}
\xtc{
If an expression contains subexpressions enclosed in parentheses,
the parenthesized subexpressions are evaluated first (from left to
right, from inside out).
}{
\spadcommand{1 + 2 - 3/ (4 * 3 ^ (2 - 1))}
}

% *********************************************************************
\head{subsection}{Previous Results}{ugIntroPrevious}
% *********************************************************************

Use the percent sign (\spadSyntax{\%}) to refer to the last
result.
\index{result!previous}
Also, use \spadSyntax{\%\%} to refer to previous results.
\index{percentpercent@{\%\%}}
\spad{\%\%(-1)} is equivalent to \spadSyntax{\%},
\spad{\%\%(-2)} returns the next to the last result, and so on.
\spad{\%\%(1)} returns the result from step number 1,
\spad{\%\%(2)} returns the result from step number 2, and so on.
\spad{\%\%(0)} is not defined.

\xtc{
This is ten to the tenth power.
}{
\spadcommand{10 ^ 10 \bound{prev}}
}
\xtc{
This is the last result minus one.
}{
\spadcommand{\% - 1 \free{prev}\bound{prev1}}
}
\xtc{
This is the last result.
}{
\spadcommand{\%\%(-1) \free{prev1}\bound{prev2}}
}
\xtc{
This is the result from step number 1.
}{
\spadcommand{\%\%(1) \free{prev2}}
}

% *********************************************************************
\head{subsection}{Some Types}{ugIntroTypes}
% *********************************************************************

Everything in \Language{} has a type.
The type determines what operations you can perform on an object and
how the object can be used.
An entire chapter of this book (\chapref{ugTypes}) is dedicated to
the interactive use of types.
Several of the final chapters discuss how types are built and how
they are organized in the \Language{} library.

\xtc{
Positive integers are given type \spadtype{PositiveInteger}.
}{
\spadcommand{8}
}
\xtc{
Negative ones are given type \spadtype{Integer}.
This fine distinction is helpful to the
\Language{} interpreter.
}{
\spadcommand{-8}
}
\xtc{
Here a positive integer exponent gives a polynomial result.
}{
\spadcommand{x^8}
}
\xtc{
Here a negative integer exponent produces a fraction.
}{
\spadcommand{x^(-8)}
}

% *********************************************************************
\head{subsection}{Symbols, Variables, Assignments, and Declarations}{ugIntroAssign}
% *********************************************************************

A \spadgloss{symbol} is a literal used for the input of things like
the ``variables'' in polynomials and power series.

\labelSpace{2pc}
\xtc{
We use the three symbols \spad{x}, \spad{y}, and \spad{z} in
entering this polynomial.
}{
\spadcommand{(x - y*z)^2}
}
A symbol has a name beginning with an uppercase or lowercase alphabetic
\index{symbol!naming}
character, \spadSyntax{\%}, or \spadSyntax{!}.
Successive characters (if any) can be any of the above, digits, or
\spadSyntax{?}.
Case is distinguished: the symbol \spad{points} is different
from the symbol \spad{Points}.

A symbol can also be used in \Language{} as a \spadgloss{variable}.
A variable refers to a value.
To \spadglossSee{assign}{assignment}
a value to a variable,
\index{variable!naming}
the operator \spadSyntax{:=}
\index{assignment}
is used.\footnote{\Language{} actually has two forms of assignment:
{\it immediate} assignment, as discussed here,
and {\it delayed assignment}. See \spadref{ugLangAssign} for details.}
A variable initially has no restrictions on the kinds of
\index{declaration}
values to which it can refer.

\xtc{
This assignment gives the value \spad{4} (an integer) to
a variable named \spad{x}.
}{
\spadcommand{x := 4}
}
\xtc{
This gives the value \spad{z + 3/5} (a polynomial)  to \spad{x}.
}{
\spadcommand{x := z + 3/5}
}
\xtc{
To restrict the types of objects that can be assigned to a variable,
use a \spadgloss{declaration}
}{
\spadcommand{y : Integer \bound{y}}
}
\xtc{
After a variable is declared to be of some type, only values
of that type can be assigned to that variable.
}{
\spadcommand{y := 89\bound{y1}\free{y}}
}
\xtc{
The declaration for \spad{y} forces values assigned to \spad{y} to
be converted to integer values.
}{
\spadcommand{y := sin \%pi}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
If no such conversion is possible,
\Language{} refuses to assign a value to \spad{y}.
}{
\spadcommand{y := 2/3}
}
\begin{inputonly}
)set message test on
\end{inputonly}
\xtc{
A type declaration can also be given together with an assignment.
The declaration can assist \Language{} in choosing the correct
operations to apply.
}{
\spadcommand{f : Float := 2/3}
}

Any number of expressions can be given on input line.
Just separate them by semicolons.
Only the result of evaluating the last expression is displayed.

\xtc{
These two expressions have the same effect as
the previous single expression.
}{
\spadcommand{f : Float; f := 2/3 \bound{fff}}
}

The type of a symbol is either \spadtype{Symbol}
\exptypeindex{Symbol}
or \spadtype{Variable({\it name})} where {\it name} is the name
of the symbol.

\xtc{
By default, the interpreter
\exptypeindex{Variable}
gives this symbol the type \spadtype{Variable(q)}.
}{
\spadcommand{q}
}
\xtc{
When multiple symbols are involved, \spadtype{Symbol} is used.
}{
\spadcommand{[q, r]}
}

\xtc{
What happens when you try to use a symbol that is the name of a variable?
}{
\spadcommand{f \free{fff}}
}
\xtc{
Use a single quote (\spadSyntax{'}) before
\index{quote}
the name to get the symbol.
}{
\spadcommand{'f}
}

Quoting a name creates a symbol by
preventing evaluation of the name as a variable.
Experience will teach you when you are most likely going to need to use
a quote.
We try to point out the location of such trouble spots.

% *********************************************************************
\head{subsection}{Conversion}{ugIntroConversion}
% *********************************************************************

Objects of one type can usually be ``converted'' to objects of several
other types.
To \spadglossSee{convert}{conversion}
an object to a new type, use the \spadSyntax{::} infix
operator.\footnote{Conversion is discussed in detail in \spadref{ugTypesConvert}.}
For example, to display an object, it is necessary to
convert the object to type \spadtype{OutputForm}.

\xtc{
This produces a polynomial with rational number coefficients.
}{
\spadcommand{p := r^2 + 2/3 \bound{p}}
}
\xtc{
Create a quotient of polynomials with integer coefficients
by using \spadSyntax{::}.
}{
\spadcommand{p :: Fraction Polynomial Integer \free{p}}
}

Some conversions can be performed automatically when
\Language{} tries to evaluate your input.
Others conversions must be explicitly requested.

% *********************************************************************
\head{subsection}{Calling Functions}{ugIntroCallFun}
% *********************************************************************

As we saw earlier, when you want to add or subtract two values,
you place the arithmetic operator \spadop{+}
or \spadop{-} between the two
\spadglossSee{arguments}{argument} denoting the values.
To use most other \Language{} operations, however, you use another syntax:
\index{function!calling}
write the name
of the operation first, then an open parenthesis, then each of the
arguments separated by commas, and, finally, a closing parenthesis.
If the operation takes only one argument and the argument is a number
or a symbol, you can omit the parentheses.

\xtc{
This calls the operation \spadfun{factor} with the single
integer argument \spad{120}.
}{
\spadcommand{factor(120)}
}
\xtc{
This is a call to \spadfun{divide} with the two integer arguments
\spad{125} and \spad{7}.
}{
\spadcommand{divide(125,7)}
}
\xtc{
This calls \spadfun{quatern} with four floating-point arguments.
}{
\spadcommand{quatern(3.4,5.6,2.9,0.1)}
}
\xtc{
This is the same as \spad{factorial(10)}.
}{
\spadcommand{factorial 10}
}

An operations that returns a \spadtype{Boolean} value (that is,
\spad{true} or \spad{false}) frequently has a name suffixed with
a question mark (``?'').  For example, the \spadfun{even?}
operation returns \spad{true} if its integer argument is an even
number, \spad{false} otherwise.

An operation that can be destructive on one or more arguments
usually has a name ending in a exclamation point (``!'').
This actually means that it is {\it allowed} to update its
arguments but it is not {\it required} to do so. For example,
the underlying representation of a collection type may not allow
the very last element to removed and so an empty object may be
returned instead. Therefore, it is important that you use the
object returned by the operation and not rely on a physical
change having occurred within the object. Usually, destructive
operations are provided for efficiency reasons.

% *********************************************************************
\head{subsection}{Some Predefined Macros}{ugIntroMacros}
% *********************************************************************

\Language{} provides several \spadglossSee{macros}{macro}
for your convenience.\footnote{See \spadref{ugUserMacros}
for a discussion on how to write your own macros.}
Macros are names
\index{macro!predefined}
(or forms) that expand to larger expressions for commonly used values.

\texht{
\begin{center}
\begin{tabular}{ll}
\spadgloss{\%i}             &  The square root of -1. \\
\spadgloss{\%e}             &  The base of the natural logarithm. \\
\spadgloss{\%pi}            &  $\pi$. \\
\spadgloss{\%infinity}      &  $\infty$. \\
\spadgloss{\%plusInfinity}  &  $+\infty$. \\
\spadgloss{\%minusInfinity} &  $-\infty$.
\end{tabular}
\end{center}
\index{\%i}
\index{\%e}
\index{\%pi}
\index{pi@{$\pi$ (= \%pi)}}
\index{\%infinity}
\index{infinity@{$\infty$ (= \%infinity)}}
\index{\%plusInfinity}
\index{\%minusInfinity}
}{
\begin{description}
\item[\spadSyntax{\%i}]             \tab{17} The square root of -1.
\item[\spadSyntax{\%e}]             \tab{17} The base of the natural logarithm.
\item[\spadSyntax{\%pi}]            \tab{17} Pi.
\item[\spadSyntax{\%infinity}]      \tab{17} Infinity.
\item[\spadSyntax{\%plusInfinity}]  \tab{17} Plus infinity.
\item[\spadSyntax{\%minusInfinity}] \tab{17} Minus infinity.
\end{description}
}

%To display all the macros (along with anything you have
%defined in the workspace), issue the system command \spadsys{)display all}.

% *********************************************************************
\head{subsection}{Long Lines}{ugIntroLong}
% *********************************************************************

When you enter \Language{} expressions from your keyboard, there
will be times when they are too long to fit on one line.
\Language{} does not care how long your lines are, so you can let
them continue from the right margin to the left side of the
next line.

Alternatively, you may want to enter several shorter lines and
have \Language{} glue them together.
To get this glue, put an underscore (\_) at the end of
each line you wish to continue.
\begin{verbatim}
2_
+_
3
\end{verbatim}
is the same as if you had entered
\begin{verbatim}
2+3
\end{verbatim}

If you are putting your \Language{} statements in an input file
(see \spadref{ugInOutIn}),
you can use indentation to indicate the structure of your program.
(see \spadref{ugLangBlocks}).

% *********************************************************************
\head{subsection}{Comments}{ugIntroComments}
% *********************************************************************

Comment statements begin with two consecutive hyphens or two
consecutive plus signs and continue until the end of the line.

\xtc{
The comment beginning with {\tt --} is ignored by \Language{}.
}{
\spadcommand{2 + 3   -- this is rather simple, no?}
}

There is no way to write long multi-line comments
other than starting each line with \spadSyntax{--} or
\spadSyntax{++}.

% *********************************************************************
\head{section}{Graphics}{ugIntroGraphics}
% *********************************************************************
%

\Language{} has a two- and three-dimensional drawing and rendering
\index{graphics}
package that allows you to draw, shade, color, rotate, translate, map,
clip, scale and combine graphic output of \Language{} computations.
The graphics interface is capable of plotting functions of one or more
variables and plotting parametric surfaces.
Once the graphics figure appears in a window,
move your mouse to the window and click.
A control panel appears immediately  and allows you to
interactively transform the object.

\psXtc{
This is an example of \Language{}'s two-dimensional plotting.
From the 2D Control Panel you can rescale the plot, turn axes and units
on and off and save the image, among other things.
This PostScript image was produced by clicking on the
\texht{\fbox{\bf PS}}{{\bf PS}} 2D Control Panel button.
}{
\spadgraph{draw(cos(5*t/8), t=0..16*\%pi, coordinates==polar)}
}{
% window was 256 x 256
\epsffile[72 72 300 300]{../ps/rose-1.ps}
}

\psXtc{
This is an example of \Language{}'s three-dimensional plotting.
It is a monochrome graph of the complex arctangent
function.
The image displayed was rotated and had the ``shade'' and ``outline''
display options set from the 3D Control Panel.
The PostScript output was produced by clicking on the
\texht{\fbox{\bf save}}{{\bf save}} 3D Control Panel button and then
clicking on the \texht{\fbox{\bf PS}}{{\bf PS}} button.
See \spadref{ugProblemNumeric} for more details and examples
of \Language{}'s numeric and graphics capabilities.
}{
\spadgraph{draw((x,y) +-> real atan complex(x,y), -\%pi..\%pi, -\%pi..\%pi, colorFunction == (x,y) +-> argument atan complex(x,y))}
}{
% window was 256 x 256
\epsffile[72 72 285 285]{../ps/atan-1.ps}
}

An exhibit of \Gallery{} is given in the
center section of this book.
For a description of the commands and programs that
produced these figures, see \appxref{ugAppGraphics}.
PostScript
\index{PostScript}
output is available so that \Language{} images can be
printed.\footnote{PostScript is a trademark of Adobe Systems Incorporated,
registered in the United States.}
See \chapref{ugGraph} for more examples and details about using
\Language{}'s graphics facilities.

% *********************************************************************
\head{section}{Numbers}{ugIntroNumbers}
% *********************************************************************
%

\Language{} distinguishes very carefully between different kinds
of numbers, how they are represented and what their properties
are.
Here are a sampling of some of these kinds of numbers and some
things you can do with them.

\xtc{
Integer arithmetic is always exact.
}{
\spadcommand{11^13 * 13^11 * 17^7 - 19^5 * 23^3}
}
\xtc{
Integers can be represented in factored form.
}{
\spadcommand{factor 643238070748569023720594412551704344145570763243 \bound{ex1}}
}
\xtc{
Results stay factored when you do arithmetic.
Note that the \spad{12} is automatically factored for you.
}{
\spadcommand{\% * 12 \free{ex1}}
}
\index{radix}
\xtc{
Integers can also be displayed to bases other than 10.
This is an integer in base 11.
}{
\spadcommand{radix(25937424601,11)}
}
\xtc{
Roman numerals are also available for those special occasions.
\index{Roman numerals}
}{
\spadcommand{roman(1992)}
}
\xtc{
Rational number arithmetic is also exact.
}{
\spadcommand{r := 10 + 9/2 + 8/3 + 7/4 + 6/5 + 5/6 + 4/7 + 3/8 + 2/9\bound{r}}
}
\xtc{
To factor fractions, you have to
map \spadfun{factor} onto the numerator and denominator.
}{
\spadcommand{map(factor,r) \free{r}}
}
\xtc{
Type \spadtype{SingleInteger} refers to machine word-length
integers.
\exptypeindex{SingleInteger}
In English, this expression means ``\spad{11} as a small
integer''.
}{
\spadcommand{11@SingleInteger}
}
\xtc{
Machine double-precision floating-point numbers are also
available for numeric and graphical
applications.
\exptypeindex{DoubleFloat}
}{
\spadcommand{123.21@DoubleFloat}
}

The normal floating-point type in \Language{}, \spadtype{Float},
is a software implementation of floating-point numbers in which
the exponent and the mantissa may have any number of
digits.\footnote{See \xmpref{Float} and \xmpref{DoubleFloat} for
additional information on floating-point types.}
The types \spadtype{Complex(Float)} and
\spadtype{Complex(DoubleFloat)} are the corresponding software
implementations of complex floating-point numbers.

\xtc{
This is a floating-point approximation to about twenty digits.
\index{floating point}
The \spadSyntax{::}
is used here to change from one kind of object
(here, a rational number) to another (a floating-point number).
}{
\spadcommand{r :: Float \free{r}}
}
\xtc{
Use \spadfunFrom{digits}{Float} to change the number of digits in
the representation.
This operation returns the previous value so you can reset it
later.
}{
\spadcommand{digits(22) \bound{fewerdigits}}
}
\xtc{
To \spad{22} digits of precision, the number
\texht{$e^{\pi {\sqrt {163.0}}}$}{\spad{exp(\%pi * sqrt 163.0)}}
appears to be an integer.
}{
\spadcommand{exp(\%pi * sqrt 163.0) \free{fewerdigits}}
}
\xtc{
Increase the precision to forty digits and try again.
}{
\spadcommand{digits(40);  exp(\%pi * sqrt 163.0) \free{moredigits}}
}
\xtc{
Here are complex numbers with rational numbers as real and
\index{complex numbers}
imaginary parts.
}{
\spadcommand{(2/3 + \%i)^3 \bound{gaussint}}
}
\xtc{
The standard operations on complex numbers are available.
}{
\spadcommand{conjugate \% \free{gaussint}}
}
\xtc{
You can factor complex integers.
}{
\spadcommand{factor(89 - 23 * \%i)}
}
\xtc{
Complex numbers with floating point parts are also available.
}{
\spadcommand{exp(\%pi/4.0 * \%i)}
}
%%--> These are not numbers:
%\xtc{
%The real and imaginary parts can be symbolic.
%}{
%\spadcommand{complex(u,v) \bound{cuv}}
%}
%\xtc{
%Of course, you can do complex arithmetic with these also.
%See \xmpref{Complex} for more information.
%}{
%\spadcommand{\% ^ 2 \free{cuv}}
%}
\xtc{
Every rational number has an exact representation as a
repeating decimal expansion
(see \xmpref{DecimalExpansion}).
}{
\spadcommand{decimal(1/352)}
}
\xtc{
A rational number can also be expressed as a continued fraction (see
\index{continued fraction}
\xmpref{ContinuedFraction}).
\index{fraction!continued}
}{
\spadcommand{continuedFraction(6543/210)}
}
\xtc{
Also, partial fractions can be used and can be displayed in a
\index{partial fraction}
compact \ldots
\index{fraction!partial}
}{
\spadcommand{partialFraction(1,factorial(10)) \bound{partfrac}}
}
\xtc{
or expanded format (see \xmpref{PartialFraction}).
}{
\spadcommand{padicFraction(\%) \free{partfrac}}
}
\xtc{
Like integers, bases (radices) other than ten can be used for rational
numbers (see \xmpref{RadixExpansion}).
Here we use base eight.
}{
\spadcommand{radix(4/7, 8)\bound{rad}}
}
\xtc{
Of course, there are complex versions of these as well.
\Language{} decides to make the result a complex rational number.
}{
\spadcommand{\% + 2/3*\%i\free{rad}}
}
\xtc{
You can also use \Language{} to manipulate fractional powers.
\index{radical}
}{
\spadcommand{(5 + sqrt 63 + sqrt 847)^(1/3)}
}
\xtc{
You can also compute with integers modulo a prime.
}{
\spadcommand{x : PrimeField 7 := 5 \bound{x}}
}
\xtc{
Arithmetic is then done modulo \mathOrSpad{7}.
}{
\spadcommand{x^3 \free{x}}
}
\xtc{
Since \mathOrSpad{7} is prime, you can invert nonzero values.
}{
\spadcommand{1/x \free{x}}
}
\xtc{
You can also compute modulo an integer that is not a prime.
}{
\spadcommand{y : IntegerMod 6 := 5 \bound{y}}
}
\xtc{
All of the usual arithmetic operations are available.
}{
\spadcommand{y^3 \free{y}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
Inversion is not available if the modulus is not a prime
number.
Modular arithmetic and prime fields are discussed in
\spadref{ugxProblemFinitePrime}.
}{
\spadcommand{1/y \free{y}}
}
\begin{inputonly}
)set message test on
\end{inputonly}
\xtc{
This defines \spad{a} to be an algebraic number, that is,
a root of a polynomial equation.
}{
\spadcommand{a := rootOf(a^5 + a^3 + a^2 + 3,a) \bound{a}}
}
\xtc{
Computations with \spad{a} are reduced according
to the polynomial equation.
}{
\spadcommand{(a + 1)^10\free{a}}
}
\xtc{
Define \spad{b} to be an algebraic number involving \spad{a}.
}{
\spadcommand{b := rootOf(b^4 + a,b) \bound{b}\free{a}}
}
\xtc{
Do some arithmetic.
}{
\spadcommand{2/(b - 1) \free{b}\bound{check}}
}
\xtc{
To expand and simplify this, call \spadfun{ratDenom}
to rationalize the denominator.
}{
\spadcommand{ratDenom(\%) \free{check}\bound{check1}}
}
\xtc{
If we do this, we should get \spad{b}.
}{
\spadcommand{2/\%+1 \free{check1}\bound{check2}}
}
\xtc{
But we need to rationalize the denominator again.
}{
\spadcommand{ratDenom(\%) \free{check2}}
}
\xtc{
Types \spadtype{Quaternion} and \spadtype{Octonion} are also available.
Multiplication of quaternions is non-commutative, as expected.
}{
\spadcommand{q:=quatern(1,2,3,4)*quatern(5,6,7,8) - quatern(5,6,7,8)*quatern(1,2,3,4)}
}

% *********************************************************************
\head{section}{Data Structures}{ugIntroCollect}
% *********************************************************************
%

\Language{} has a large variety of data structures available.
Many data structures are particularly useful for interactive
computation and others are useful for building applications.
The data structures of \Language{} are organized into
\spadglossSee{category hierarchies}{hierarchy} as shown on
the inside back cover.

A \spadgloss{list} is the most commonly used data structure in
\Language{} for holding objects all of the same
type.\footnote{Lists are discussed in \xmpref{List} and in
\spadref{ugLangIts}.}
The name {\it list} is short for ``linked-list of nodes.'' Each
node consists of a value (\spadfunFrom{first}{List}) and a link
(\spadfunFrom{rest}{List}) that
\spadglossSee{points}{pointer} to the next node, or to a
distinguished value denoting the empty list.
To get to, say, the third element, \Language{} starts at the front
of the list, then traverses across two links to the third node.

\xtc{
Write a list of elements using
square brackets with commas separating the elements.
}{
\spadcommand{u := [1,-7,11] \bound{u}}
}
\xtc{
This is the value at the third node.
Alternatively, you can say \spad{u.3}.
}{
\spadcommand{first rest rest u\free{u}}
}

Many operations are defined on lists, such as:
\spadfun{empty?}, to test that a list has no elements;
\spadfun{cons}\spad{(x,l)}, to create a new list with
\spadfun{first} element \spad{x} and \spadfun{rest} \spad{l};
\spadfun{reverse}, to create a new list with elements in reverse
order; and \spadfun{sort}, to arrange elements in order.

An important point about lists is that they are ``mutable'': their
constituent elements and links can be changed ``in place.''
To do this, use any of the operations whose names end with the
character \spadSyntax{!}.

\xtc{
The operation \spadfunFromX{concat}{List}\spad{(u,v)}
replaces the last link of the list
\spad{u} to point to some other list \spad{v}.
Since \spad{u} refers to the original list,
this change is seen by \spad{u}.
}{
\spadcommand{concat!(u,[9,1,3,-4]); u\free{u}\bound{u1}}
}
\xtc{
A {\it cyclic list} is a list with a ``cycle'':
\index{list!cyclic}
a link pointing back to an earlier node of the list.
\index{cyclic list}
To create a cycle, first get a node somewhere down
the list.
}{
\spadcommand{lastnode := rest(u,3)\free{u1}\bound{u2}}
}
\xtc{
Use \spadfunFromX{setrest}{List} to
change the link emanating from that node to point back to an
earlier part of the list.
}{
\spadcommand{setrest!(lastnode,rest(u,2)); u\free{u2}}
}

A \spadgloss{stream}
is a structure that (potentially) has an infinite number of
distinct elements.\footnote{Streams are discussed in
\xmpref{Stream} and in \spadref{ugLangIts}.}
Think of a stream as an ``infinite list'' where elements are
computed successively.

\xtc{
Create an infinite stream of factored integers.
Only a certain number of initial elements are computed
and displayed.
}{
\spadcommand{[factor(i) for i in 2.. by 2] \bound{stream1}}
}
\xtc{
\Language{} represents streams by a collection of already-computed
elements together with a function to compute the next element
``on demand.''
Asking for the \eth{\spad{n}} element causes elements \spad{1} through
\spad{n} to be evaluated.
}{
\spadcommand{\%.36 \free{stream1}}
}

Streams can also be finite or cyclic.
They are implemented by a linked list structure similar to lists
and have many of the same operations.
For example, \spadfun{first} and \spadfun{rest} are used to access
elements and successive nodes of a stream.
%%> reverse and sort do not exist for streams
%%Don't try to reverse or sort a stream: the
%%operation will generally run forever!

A \spadgloss{one-dimensional array} is another data structure used
to hold objects of the same type.\footnote{See \xmpref{OneDimensionalArray} for
details.}
Unlike lists, one-dimensional arrays are inflexible---they are
\index{array!one-dimensional}
implemented using a fixed block of storage.
Their advantage is that they give quick and equal access time to
any element.

\xtc{
A simple way to create a one-dimensional array is to apply the
operation \spadfun{oneDimensionalArray} to a list of elements.
}{
\spadcommand{a := oneDimensionalArray [1, -7, 3, 3/2]\bound{a}}
}
\xtc{
One-dimensional arrays are also mutable:
you can change their constituent elements ``in place.''
}{
\spadcommand{a.3 := 11; a\bound{a1}\free{a}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
However, one-dimensional arrays are not flexible structures.
You cannot destructively \spadfunX{concat} them together.
}{
\spadcommand{concat!(a,oneDimensionalArray [1,-2])\free{a1}}
}
\begin{inputonly}
)set message test on
\end{inputonly}

Examples of datatypes similar to \spadtype{OneDimensionalArray}
are: \spadtype{Vector} (vectors are mathematical structures
implemented by one-dimensional arrays), \spadtype{String} (arrays
of ``characters,'' represented by byte vectors), and
\spadtype{Bits} (represented by ``bit vectors'').

\xtc{
A vector of 32 bits, each representing the \spadtype{Boolean} value \spad{true}.
}{
\spadcommand{bits(32,true)}
}

A \spadgloss{flexible array} is a cross between a list
\index{array!flexible}
and a one-dimensional array.\footnote{See \xmpref{FlexibleArray} for
details.}
Like a one-dimensional array, a flexible array occupies a fixed
block of storage.
Its block of storage, however, has room to expand!
When it gets full, it grows (a new, larger block of storage is
allocated); when it has too much room, it contracts.

\xtc{
Create a flexible array of three elements.
}{
\spadcommand{f := flexibleArray [2, 7, -5]\bound{f}}
}
\xtc{
Insert some elements between the second and third elements.
}{
\spadcommand{insert!(flexibleArray [11, -3],f,2)\free{f}}
}

Flexible arrays are used to implement ``heaps.'' A
\spadgloss{heap} is an example of a data structure called a
\spadgloss{priority queue}, where elements are ordered with
respect to one another.\footnote{See \xmpref{Heap} for more details.
Heaps are also examples of data structures called
\spadglossSee{bags}{bag}.
Other bag data structures are \spadtype{Stack}, \spadtype{Queue},
and \spadtype{Dequeue}.}
A heap is organized
so as to optimize insertion and extraction of maximum elements.
The \spadfunX{extract} operation
returns the maximum element of the heap, after destructively
removing that element and
reorganizing the heap
so that the next maximum element is ready to be delivered.

\xtc{
An easy way to create a heap is to apply the
operation \spadfun{heap} to a list of values.
}{
\spadcommand{h := heap [-4,7,11,3,4,-7]\bound{h}}
}
\xtc{
This loop extracts elements one-at-a-time from \spad{h}
until the heap is exhausted, returning the elements
as a list in the order they were extracted.
}{
\spadcommand{[extract!(h) while not empty?(h)]\free{h}}
}

A \spadgloss{binary tree} is a ``tree'' with at most two branches
\index{tree}
per node: it is either empty, or else is a node consisting of a
value, and a left and right subtree (again, binary trees).\footnote{Example of binary tree types are
\spadtype{BinarySearchTree} (see \xmpref{BinarySearchTree},
\spadtype{PendantTree}, \spadtype{TournamentTree},
and \spadtype{BalancedBinaryTree} (see \xmpref{BalancedBinaryTree}).}

\xtc{
A {\it binary search tree} is a binary tree such that,
\index{tree!binary search}
for each node, the value of the node is
\index{binary search tree}
greater than all values (if any) in the left subtree,
and less than or equal all values (if any) in the right subtree.
}{
\spadcommand{binarySearchTree [5,3,2,9,4,7,11]}
}

\xtc{
A {\it balanced binary tree} is useful for doing modular computations.
\index{balanced binary tree}
Given a list \spad{lm} of moduli,
\index{tree!balanced binary}
\spadfun{modTree}\spad{(a,lm)} produces a balanced binary
tree with the values \texht{$a \bmod m$}{a {\tt mod} m}
at its leaves.
}{
\spadcommand{modTree(8,[2,3,5,7])}
}

A \spadgloss{set} is a collection of elements where duplication
and order is irrelevant.\footnote{See \xmpref{Set} for more
details.}
Sets are always finite and have no corresponding
structure like streams for infinite collections.

\xtc{
%Create sets using braces (\spadSyntax{\{} and \spadSyntax{\}})
%rather than brackets.
}{
\spadcommand{fs := set[1/3,4/5,-1/3,4/5] \bound{fs}}
}

A \spadgloss{multiset}
is a set that keeps track of the number
of duplicate values.\footnote{See \xmpref{Multiset} for details.}
\xtc{
For all the primes \spad{p} between 2 and 1000, find the
distribution of \texht{$p \bmod 5$}{p mod 5}.
}{
\spadcommand{multiset [x rem 5 for x in primes(2,1000)]}
}

A \spadgloss{table}
is conceptually a set of ``key--value'' pairs and
is a generalization of a multiset.\footnote{For examples of tables, see
\spadtype{AssociationList} (\xmpref{AssociationList}),
\spadtype{HashTable},
\spadtype{KeyedAccessFile} (\xmpref{KeyedAccessFile}),
\spadtype{Library} (\xmpref{Library}),
\spadtype{SparseTable} (\xmpref{SparseTable}),
\spadtype{StringTable} (\xmpref{StringTable}),
and \spadtype{Table} (\xmpref{Table}).}
The domain \spadtype{Table(Key, Entry)} provides a general-purpose
type for tables with {\it values} of type \spad{Entry} indexed
by {\it keys} of type \spad{Key}.

\xtc{
Compute the above distribution of primes using tables.
First, let \spad{t} denote an empty table of keys and values,
each of type \spadtype{Integer}.
}{
\spadcommand{t : Table(Integer,Integer) := empty()\bound{t}}
}

We define a function \userfun{howMany} to return the number
of values of a given modulus \spad{k} seen so far.
It calls \spadfun{search}\spad{(k,t)} which returns the number of
values stored under the key \spad{k} in table \spad{t}, or
\spad{"failed"} if no such value is yet stored in \spad{t} under
\spad{k}.

\xtc{
In English, this says ``Define \spad{howMany(k)} as follows.
First, let \smath{n} be the value of \spadfun{search}\smath{(k,t)}.
Then, if \smath{n} has the value \smath{"failed"}, return the value
\smath{1}; otherwise return \smath{n + 1}.''
}{
\spadcommand{howMany(k) == (n:=search(k,t); n case "failed" => 1; n+1)\bound{how}}
}
\xtc{
Run through the primes to create the table, then print the table.
The expression \spad{t.m := howMany(m)} updates the value in table \spad{t}
stored under key \spad{m}.
}{
\spadcommand{for p in primes(2,1000) repeat (m:= p rem 5; t.m:= howMany(m)); t\free{how t}}
}

A {\it record}
is an example of an inhomogeneous collection
of objects.\footnote{See \spadref{ugTypesRecords} for details.}
A record consists of a set of named {\it selectors} that
can be used to access its components.
\index{Record@{\sf Record}}

\xtc{
Declare that \spad{daniel} can only be
assigned a record with two prescribed fields.
}{
\spadcommand{daniel : Record(age : Integer, salary : Float) \bound{danieldec}}
}
\xtc{
Give \spad{daniel} a value, using square brackets to enclose the values of
the fields.
}{
\spadcommand{daniel := [28, 32005.12] \free{danieldec}\bound{daniel}}
}
\xtc{
Give \spad{daniel} a raise.
}{
\spadcommand{daniel.salary := 35000; daniel \free{daniel}}
}

A {\it union}
is a data structure used when objects
have multiple types.\footnote{See \spadref{ugTypesUnions} for details.}
\index{Union@{\sf Union}}

\xtc{
Let \spad{dog} be either an integer or a string value.
}{
\spadcommand{dog: Union(licenseNumber: Integer, name: String)\bound{xint}}
}
\xtc{
Give \spad{dog} a name.
}{
\spadcommand{dog := "Whisper"\free{xint}}
}

All told, there are over forty different data structures in
\Language{}.
Using the domain constructors described in \chapref{ugDomains}, you
can add your own data structure or extend an existing one.
Choosing the right data structure for your application may be the key
to obtaining good performance.

% *********************************************************************
\head{section}{Expanding to Higher Dimensions}{ugIntroTwoDim}
% *********************************************************************
%

To get higher dimensional aggregates, you can create one-dimensional
aggregates with elements that are themselves
aggregates, for example, lists of lists, one-dimensional arrays of
lists of multisets, and so on.
For applications requiring two-dimensional homogeneous aggregates,
you will likely find {\it two-dimensional arrays}
\index{matrix}
and {\it matrices} most useful.
\index{array!two-dimensional}

The entries in \spadtype{TwoDimensionalArray} and
\spadtype{Matrix} objects
are all the same type, except that those for
\spadtype{Matrix} must belong to a \spadtype{Ring}.
You create and access elements in roughly the same way.
Since matrices have an understood algebraic structure, certain algebraic
operations are available for matrices but not for arrays.
Because of this, we limit our discussion here to
\spadtype{Matrix}, that can be regarded as an extension of
\spadtype{TwoDimensionalArray}.\footnote{See
\xmpref{TwoDimensionalArray} for more information about arrays.
For more information about \Language{}'s linear algebra
facilities, see \xmpref{Matrix}, \xmpref{Permanent},
\xmpref{SquareMatrix}, \xmpref{Vector},
\spadref{ugProblemEigen}\texht{(computation of eigenvalues and
eigenvectors)}{}, and
\spadref{ugProblemLinPolEqn}\texht{(solution of linear and
polynomial equations)}{}.}

\xtc{
You can create a matrix from a list of lists,
\index{matrix!creating}
where each of the inner lists represents a row of the matrix.
}{
\spadcommand{m := matrix([[1,2], [3,4]]) \bound{m}}
}
\xtc{
The ``collections'' construct (see \spadref{ugLangIts}) is
useful for creating matrices whose entries are given by formulas.
\index{matrix!Hilbert}
}{
\spadcommand{matrix([[1/(i + j - x) for i in 1..4] for j in 1..4]) \bound{hilb}}
}
\xtc{
Let \spad{vm} denote the three by three Vandermonde matrix.
}{
\spadcommand{vm := matrix [[1,1,1], [x,y,z], [x*x,y*y,z*z]] \bound{vm}}
}
\xtc{
Use this syntax to extract an entry in the matrix.
}{
\spadcommand{vm(3,3) \free{vm}}
}
\xtc{
You can also pull out a \spadfun{row} or a \spad{column}.
}{
\spadcommand{column(vm,2) \free{vm}}
}
\xtc{
You can do arithmetic.
}{
\spadcommand{vm * vm \free{vm}}
}
\xtc{
You can perform operations such as
\spadfun{transpose}, \spadfun{trace}, and \spadfun{determinant}.
}{
\spadcommand{factor determinant vm \free{vm}\bound{d}}
}

% *********************************************************************
\head{section}{Writing Your Own Functions}{ugIntroYou}
% *********************************************************************
%

\Language{} provides you with a very large library of predefined
operations and objects to compute with.
You can use the \Language{} library of constructors to create new
objects dynamically of quite arbitrary complexity.
For example, you can make lists of matrices of fractions of
polynomials with complex floating point numbers as coefficients.
Moreover, the library provides a wealth of operations that allow
you to create and manipulate these objects.

For many applications,
you need to interact with the interpreter and write some
\Language{} programs to tackle your application.
\Language{} allows you to write functions interactively,
\index{function}
thereby effectively extending the system library.
Here we give a few simple examples, leaving the details to \chapref{ugUser}.

We begin by looking at several ways that you can define the
``factorial'' function in \Language{}.
The first way is to give a
\index{function!piece-wise definition}
piece-wise definition of the function.
\index{piece-wise function definition}
This method is best for a general recurrence
relation since the pieces are gathered together and compiled into
an efficient iterative function.
Furthermore, enough previously computed values are automatically
saved so that a subsequent call to the function can pick up from
where it left off.

\xtc{
Define the value of \userfun{fact} at \spad{0}.
}{
\spadcommand{fact(0) == 1 \bound{fact}}
}
\xtc{
Define the value of \spad{fact(n)} for general \spad{n}.
}{
\spadcommand{fact(n) == n*fact(n-1)\bound{facta}\free{fact}}
}
\xtc{
Ask for the value at \spad{50}.
The resulting function created by \Language{}
computes the value by iteration.
}{
\spadcommand{fact(50) \free{facta}}
}
\xtc{
A second definition uses an \spad{if-then-else} and recursion.
}{
\spadcommand{fac(n) == if n < 3 then n else n * fac(n - 1) \bound{fac}}
}
\xtc{
This function is less efficient than the previous version since
each iteration involves a recursive function call.
}{
\spadcommand{fac(50) \free{fac}}
}
\xtc{
A third version directly uses iteration.
}{
\spadcommand{fa(n) == (a := 1; for i in 2..n repeat a := a*i; a) \bound{fa}}
}
\xtc{
This is the least space-consumptive version.
}{
\spadcommand{fa(50) \free{fa}}
}
\xtc{
A final version appears to construct a large list and then reduces over
it with multiplication.
}{
\spadcommand{f(n) == reduce(*,[i for i in 2..n]) \bound{f}}
}
\xtc{
In fact, the resulting computation is optimized into an efficient
iteration loop equivalent to that of the third version.
}{
\spadcommand{f(50) \free{f}}
}
\xtc{
The library version uses an algorithm that is different from the four
above because it highly optimizes the recurrence relation definition of
\spadfun{factorial}.
}{
\spadcommand{factorial(50)}
}

You are not limited to one-line functions in \Language{}.
If you place your function definitions in {\bf .input} files
\index{file!input}
(see \spadref{ugInOutIn}), you can have
multi-line functions that use indentation for grouping.

Given \spad{n} elements, \spadfun{diagonalMatrix} creates an
\spad{n} by \spad{n} matrix with those elements down the diagonal.
This function uses a permutation matrix
that interchanges the \spad{i}th and \spad{j}th rows of a matrix
by which it is right-multiplied.

\xtc{
This function definition shows a style of definition that can be used
in {\bf .input} files.
Indentation is used to create \spadglossSee{blocks}{block}\texht{\/}{}:
sequences of expressions that are evaluated in sequence except as
modified by control statements such as \spad{if-then-else} and \spad{return}.
}{
\begin{spadsrc}[\bound{permMat}]
permMat(n, i, j) ==
  m := diagonalMatrix
    [(if i = k or j = k then 0 else 1)
      for k in 1..n]
  m(i,j) := 1
  m(j,i) := 1
  m
\end{spadsrc}
}
\xtc{
This creates a four by four matrix that interchanges the second and third
rows.
}{
\spadcommand{p := permMat(4,2,3) \free{permMat}\bound{p}}
}
\xtc{
Create an example matrix to permute.
}{
\spadcommand{m := matrix [[4*i + j for j in 1..4] for i in 0..3]\bound{m}}
}
\xtc{
Interchange the second and third rows of m.
}{
\spadcommand{permMat(4,2,3) * m \free{p m}}
}

A function can also be passed as an argument to another function,
which then applies the function or passes it off to some other
function that does.
You often have to declare the type of a function that has
functional arguments.

\xtc{
This declares \userfun{t} to be a two-argument function that
returns a \spadtype{Float}.
The first argument is a function that takes one \spadtype{Float}
argument and returns a \spadtype{Float}.
}{
\spadcommand{t : (Float -> Float, Float) -> Float \bound{tdecl}}
}
\xtc{
This is the definition of \userfun{t}.
}{
\spadcommand{t(fun, x) == fun(x)^2 + sin(x)^2 \free{tdecl}\bound{t}}
}
\xtc{
We have not defined a \spadfun{cos} in the workspace. The one from the
\Language{} library will do.
}{
\spadcommand{t(cos, 5.2058) \free{t}}
}
\xtc{
Here we define our own (user-defined) function.
}{
\spadcommand{cosinv(y) == cos(1/y) \bound{cosinv}}
}
\xtc{
Pass this function as an argument to \userfun{t}.
}{
\spadcommand{t(cosinv, 5.2058) \free{t}\free{cosinv}}
}

\Language{} also has pattern matching capabilities for
\index{simplification}
simplification
\index{pattern matching}
of expressions and for defining new functions by rules.
For example, suppose that you want to apply regularly a transformation
that groups together products of radicals:
\texht{$$\sqrt{a}\:\sqrt{b} \mapsto \sqrt{ab}, \quad
(\forall a)(\forall b)$$}{\spad{sqrt(a) * sqrt(b) by sqrt(a*b)} for any \spad{a} and \spad{b}}
Note that such a transformation is not generally correct.
\Language{} never uses it automatically.

\xtc{
Give this rule the name \userfun{groupSqrt}.
}{
\spadcommand{groupSqrt := rule(sqrt(a) * sqrt(b) == sqrt(a*b)) \bound{g}}
}
\xtc{
Here is a test expression.
}{
\spadcommand{a := (sqrt(x) + sqrt(y) + sqrt(z))^4 \bound{sxy}}
}
\xtc{
The rule
\userfun{groupSqrt} successfully simplifies the expression.
}{
\spadcommand{groupSqrt a \free{sxy} \free{g}}
}

% *********************************************************************
\head{section}{Polynomials}{ugIntroVariables}
% *********************************************************************
%

Polynomials are the commonly used algebraic types in symbolic
computation.
\index{polynomial}
Interactive users of \Language{} generally only see one type
of polynomial: \spadtype{Polynomial(R)}.
This type represents polynomials in any number of unspecified
variables over a particular coefficient domain \spad{R}.
This type represents its coefficients
\spadglossSee{sparsely}{sparse}: only terms with non-zero
coefficients are represented.
\exptypeindex{Polynomial}

In building applications, many other kinds of polynomial
representations are useful.
Polynomials may have one variable or multiple variables, the
variables can be named or unnamed, the coefficients can be stored
sparsely or densely.
So-called ``distributed multivariate polynomials'' store
polynomials as coefficients paired with vectors of exponents.
This type is particularly efficient for use in algorithms for
solving systems of non-linear polynomial equations.

\xtc{
The polynomial constructor most familiar to the interactive user
is \spadtype{Polynomial}.
}{
\spadcommand{(x^2 - x*y^3 +3*y)^2}
}
\xtc{
If you wish to restrict the variables used,
\spadtype{UnivariatePolynomial}
provides polynomials in one variable.
\exptypeindex{UnivariatePolynomial}
}{
\spadcommand{p: UP(x,INT) := (3*x-1)^2 * (2*x + 8)}
}
\xtc{
The constructor
\spadtype{MultivariatePolynomial} provides polynomials in one or more
specified variables.
\exptypeindex{MultivariatePolynomial}
}{
\spadcommand{m: MPOLY([x,y],INT) := (x^2-x*y^3+3*y)^2 \bound{m}}
}
\xtc{
You can change the way the polynomial appears by modifying the variable
ordering in the explicit list.
}{
\spadcommand{m :: MPOLY([y,x],INT) \free{m}}
}
\xtc{
The constructor
\spadtype{DistributedMultivariatePolynomial} provides
polynomials in one or more specified variables with the monomials
ordered lexicographically.
\exptypeindex{DistributedMultivariatePolynomial}
}{
\spadcommand{m :: DMP([y,x],INT) \free{m}}
}
\xtc{
The constructor
\spadtype{HomogeneousDistributedMultivariatePolynomial} is similar except that
the monomials are ordered by total order refined by reverse
lexicographic order.
\exptypeindex{HomogeneousDistributedMultivariatePolynomial}
}{
\spadcommand{m :: HDMP([y,x],INT) \free{m}}
}

More generally, the domain constructor
\spadtype{GeneralDistributedMultivariatePolynomial} allows the
user to provide an arbitrary predicate to define his own term ordering.
\exptypeindex{GeneralDistributedMultivariatePolynomial}
These last three constructors are typically used in
\texht{Gr\"{o}bner}{Groebner} basis
\index{Groebner basis@{Gr\protect\"{o}bner basis}}
applications and when a flat (that is, non-recursive) display is
wanted and the term ordering is critical for controlling the computation.

% *********************************************************************
\head{section}{Limits}{ugIntroCalcLimits}
% *********************************************************************
%

\Language{}'s \spadfun{limit} function is usually used to
evaluate limits of quotients where the numerator and denominator
\index{limit}
both tend to zero or both tend to infinity.
To find the limit of an expression \spad{f} as a real variable
\spad{x} tends to a limit value \spad{a}, enter \spad{limit(f, x=a)}.
Use \spadfun{complexLimit} if the variable is complex.
Additional information and examples of limits are in
\spadref{ugProblemLimits}.

\xtc{
You can take limits of functions with parameters.
\index{limit!of function with parameters}
}{
\spadcommand{g := csc(a*x) / csch(b*x) \bound{g}}
}
\xtc{
As you can see, the limit is expressed in terms of the parameters.
}{
\spadcommand{limit(g,x=0) \free{g}}
}
%
\xtc{
A variable may also approach plus or minus infinity:
}{
\spadcommand{h := (1 + k/x)^x \bound{h}}
}
\xtc{
\texht{Use \spad{\%plusInfinity} and \spad{\%minusInfinity} to
denote $\infty$ and $-\infty$.}{}
}{
\spadcommand{limit(h,x=\%plusInfinity) \free{h}}
}
\xtc{
A function can be defined on both sides of a particular value, but
may tend to different limits as its variable approaches that value from the
left and from the right.
}{
\spadcommand{limit(sqrt(y^2)/y,y = 0)}
}
\xtc{
As \spad{x} approaches \spad{0} along the real axis, \spad{exp(-1/x^2)}
tends to \spad{0}.
}{
\spadcommand{limit(exp(-1/x^2),x = 0)}
}
\xtc{
However, if \spad{x} is allowed to approach \spad{0} along any path in the
complex plane, the limiting value of \spad{exp(-1/x^2)} depends on the
path taken because the function has an essential singularity at \spad{x=0}.
This is reflected in the error message returned by the function.
}{
\spadcommand{complexLimit(exp(-1/x^2),x = 0)}
}

% *********************************************************************
\head{section}{Series}{ugIntroSeries}
% *********************************************************************
%

\Language{} also provides power series.
\index{series!power}
By default, \Language{} tries to compute and display the first ten elements
of a series.
Use \spadsys{)set streams calculate} to change the default value
to something else.
\syscmdindex{set streams calculate}
For the purposes of this book, we have used this system command to display
fewer than ten terms.
For more information about working with series, see
\spadref{ugProblemSeries}.

\xtc{
You can convert a functional expression to a power series by using the
operation \spadfun{series}.
In this example,
\spad{sin(a*x)} is expanded in powers of \spad{(x - 0)},
that is, in powers of \spad{x}.
}{
\spadcommand{series(sin(a*x),x = 0)}
}
\xtc{
This expression expands
\spad{sin(a*x)} in powers of \spad{(x - \%pi/4)}.
}{
\spadcommand{series(sin(a*x),x = \%pi/4)}
}
\xtc{
\Language{} provides
\index{series!Puiseux}
{\it Puiseux series:}
\index{Puiseux series}
series with rational number exponents.
The first argument to \spadfun{series} is an in-place function that
computes the \eth{\spad{n}} coefficient.
(Recall that
the \spadSyntax{+->} is an infix operator meaning ``maps to.'')
}{
\spadcommand{series(n +-> (-1)^((3*n - 4)/6)/factorial(n - 1/3),x = 0,4/3..,2)}
}
\xtc{
Once you have created a power series, you can perform arithmetic operations
on that series.
We compute the Taylor expansion of \spad{1/(1-x)}.
\index{series!Taylor}
}{
\spadcommand{f := series(1/(1-x),x = 0) \bound{f}}
}
\xtc{
Compute the square of the series.
}{
\spadcommand{f ^ 2 \free{f}}
}
\xtc{
The usual elementary functions
(\spadfun{log}, \spadfun{exp}, trigonometric functions, and so on)
are defined for power series.
}{
\spadcommand{f := series(1/(1-x),x = 0) \bound{f1}}
}
\xtc{
}{
\spadcommand{g := log(f) \free{f1}\bound{g}}
}
\xtc{
}{
\spadcommand{exp(g) \free{g}}
}
% Warning: currently there are (interpreter) problems with converting
% rational functions and polynomials to power series.
\xtc{
Here is a way to obtain numerical approximations of
\spad{e} from the Taylor series expansion of \spad{exp(x)}.
First create the desired Taylor expansion.
}{
\spadcommand{f := taylor(exp(x)) \bound{f2}}
}
\xtc{
Evaluate the series at the value \spad{1.0}.
% Warning: syntax for evaluating power series may change.
As you see, you get a sequence of partial sums.
}{
\spadcommand{eval(f,1.0) \free{f2}}
}

% *********************************************************************
\head{section}{Derivatives}{ugIntroCalcDeriv}
% *********************************************************************
%
Use the \Language{} function \spadfun{D} to differentiate an
\index{derivative}
expression.
\index{differentiation}

\texht{\vskip 2pc}{}
\xtc{
To find the derivative of an expression \spad{f} with respect to a
variable \spad{x}, enter \spad{D(f, x)}.
}{
\spadcommand{f := exp exp x \bound{f}}
}
\xtc{
}{
\spadcommand{D(f, x) \free{f}}
}
\xtc{
An optional third argument \spad{n} in \spadfun{D} asks
\Language{} for the \eth{\spad{n}} derivative of \spad{f}.
This finds the fourth derivative of \spad{f} with respect to \spad{x}.
}{
\spadcommand{D(f, x, 4) \free{f}}
}
\xtc{
You can also compute partial derivatives by specifying the order of
\index{differentiation!partial}
differentiation.
}{
\spadcommand{g := sin(x^2 + y) \bound{g}}
}
\xtc{
}{
\spadcommand{D(g, y) \free{g}}
}
\xtc{
}{
\spadcommand{D(g, [y, y, x, x]) \free{g}}
}

\Language{} can manipulate the derivatives (partial and iterated) of
\index{differentiation!formal}
expressions involving formal operators.
All the dependencies must be explicit.
\xtc{
This returns \spad{0} since \spad{F} (so far)
does not explicitly depend on \spad{x}.
}{
\spadcommand{D(F,x)}
}
Suppose that we have \spad{F} a function of \spad{x},
\spad{y}, and \spad{z}, where \spad{x} and \spad{y} are themselves
functions of \spad{z}.
\xtc{
Start by declaring that \spad{F}, \spad{x}, and \spad{y}
are operators.
\index{operator}
}{
\spadcommand{F := operator 'F; x := operator 'x; y := operator 'y\bound{F x y}}
}
\xtc{
You can use \spad{F}, \spad{x}, and \spad{y} in expressions.
}{
\spadcommand{a := F(x z, y z, z^2) + x y(z+1) \bound{a}\free{F}\free{x}\free{y}}
}
\xtc{
Differentiate formally with respect to \spad{z}.
The formal derivatives appearing in \spad{dadz} are not just formal symbols,
but do represent the derivatives of \spad{x}, \spad{y}, and \spad{F}.
}{
\spadcommand{dadz := D(a, z)\bound{da}\free{a}}
}
\xtc{
You can evaluate the above for particular functional
values of \spad{F}, \spad{x}, and \spad{y}.
If \spad{x(z)} is \spad{exp(z)} and \spad{y(z)} is \spad{log(z+1)}, then
this evaluates \spad{dadz}.
}{
\spadcommand{eval(eval(dadz, 'x, z +-> exp z), 'y, z +-> log(z+1))\free{da}}
}
\xtc{
You obtain the same result by first evaluating \spad{a} and
then differentiating.
}{
\spadcommand{eval(eval(a, 'x, z +-> exp z), 'y, z +-> log(z+1)) \free{a}\bound{eva}}
}
\xtc{
}{
\spadcommand{D(\%, z)\free{eva}}
}

% *********************************************************************
\head{section}{Integration}{ugIntroIntegrate}
% *********************************************************************
%

\Language{} has extensive library facilities for integration.
\index{integration}

The first example is the integration of a fraction with
denominator that factors into a quadratic and a quartic
irreducible polynomial.
The usual partial fraction approach used by most other computer
algebra systems either fails or introduces expensive unneeded
algebraic numbers.

\xtc{
We use a factorization-free algorithm.
}{
\spadcommand{integrate((x^2+2*x+1)/((x+1)^6+1),x)}
}

When real parameters are present, the form of the integral can depend on
the signs of some expressions.

\xtc{
Rather than query the user or make sign assumptions, \Language{} returns
all possible answers.
}{
\spadcommand{integrate(1/(x^2 + a),x)}
}

The \spadfun{integrate} operation generally assumes that all
parameters are real.
The only exception is when the integrand has complex valued
quantities.

\xtc{
If the parameter is complex instead of real, then the notion of sign is
undefined and there is a unique answer.
You can request this answer by ``prepending'' the word ``complex'' to the
command name:
}{
\spadcommand{complexIntegrate(1/(x^2 + a),x)}
}

The following two examples illustrate the limitations of
table-based approaches.
The two integrands are very similar, but the answer to one of them
requires the addition of two new algebraic numbers.

\xtc{
This one is the easy one.
The next one looks very similar
but the answer is much more complicated.
}{
\spadcommand{integrate(x^3 / (a+b*x)^(1/3),x)}
}
\xtc{
Only an algorithmic approach
is guaranteed to find what new constants must be added in order to
find a solution.
}{
\spadcommand{integrate(1 / (x^3 * (a+b*x)^(1/3)),x)}
}

Some computer algebra systems use heuristics or table-driven
approaches to integration.
When these systems cannot determine the answer to an integration
problem, they reply ``I don't know.'' \Language{} uses a
algorithm for integration.
that conclusively proves that an integral cannot be expressed in
terms of elementary functions.

\xtc{
When \Language{} returns an integral sign, it has proved
that no answer exists as an elementary function.
}{
\spadcommand{integrate(log(1 + sqrt(a*x + b)) / x,x)}
}
\Language{} can handle complicated mixed functions much beyond what you
can find in tables.
\xtc{
Whenever possible, \Language{} tries to express the answer using the functions
present in the integrand.
}{
\spadcommand{integrate((sinh(1+sqrt(x+b))+2*sqrt(x+b)) / (sqrt(x+b) * (x + cosh(1+sqrt(x + b)))), x)}
}
\xtc{
A strong structure-checking algorithm in \Language{} finds hidden algebraic
relationships between functions.
}{
\spadcommand{integrate(tan(atan(x)/3),x)}
}
\noindent
%%--> Bob---> please make these formulas in this section smaller.
The discovery of this algebraic relationship is necessary for correct
integration of this function.
Here are the details:
\begin{enumerate}
\item
If \texht{$x=\tan t$}{\spad{x=tan(t)}} and
\texht{$g=\tan (t/3)$}{\spad{g=tan(t/3)}} then the following
algebraic relation is true:
\texht{$${g^3-3xg^2-3g+x=0}$$}{\centerline{\spad{g^3 - 3*x*g^2 - 3*g + x = 0}}}
\item
Integrate \spad{g} using this algebraic relation; this produces:
\texht{$${%
{(24g^2 - 8)\log(3g^2 - 1) + (81x^2 + 24)g^2 + 72xg - 27x^2 - 16}
\over{54g^2 - 18}}$$}{\centerline{\spad{(24g^2 - 8)log(3g^2 - 1) +
(81x^2 + 24)g^2 + 72xg - 27x^2 - 16/ (54g^2 - 18)}}}
\item
Rationalize the denominator, producing:
\texht{\narrowDisplay{{8\log(3g^2-1) - 3g^2 + 18xg + 16} \over
{18}}}{\centerline{\spad{(8*log(3*g^2-1) - 3*g^2 + 18*x*g + 16)/18}}}
Replace \spad{g} by the initial definition
\texht{$g = \tan(\arctan(x)/3)$}{\spad{g = tan(arctan(x)/3)}}
to produce the final result.
\end{enumerate}

\xtc{
This is an example of a mixed function where
the algebraic layer is over the transcendental one.
}{
\spadcommand{integrate((x + 1) / (x*(x + log x) ^ (3/2)), x)}
}
\xtc{
While incomplete for non-elementary functions, \Language{} can
handle some of them.
}{
\spadcommand{integrate(exp(-x^2) * erf(x) / (erf(x)^3 - erf(x)^2 - erf(x) + 1),x)}
}

More examples of \Language{}'s integration capabilities are discussed in
\spadref{ugProblemIntegration}.

% *********************************************************************
\head{section}{Differential Equations}{ugIntroDiffEqns}
% *********************************************************************
%
The general approach used in integration also carries over to the
solution of linear differential equations.

\labelSpace{2pc}
\xtc{
Let's solve some differential equations.
Let \spad{y} be the unknown function in terms of \spad{x}.
}{
\spadcommand{y := operator 'y \bound{y}}
}
\xtc{
Here we solve a third order equation with polynomial coefficients.
}{
\spadcommand{deq := x^3 * D(y x, x, 3) + x^2 * D(y x, x, 2) - 2 * x * D(y x, x) + 2 * y x = 2 * x^4 \bound{e3}\free{y}}
}
\xtc{
}{
\spadcommand{solve(deq, y, x) \free{e3}\free{y}}
}
\xtc{
Here we find all the algebraic function solutions of the equation.
}{
\spadcommand{deq := (x^2 + 1) * D(y x, x, 2) + 3 * x * D(y x, x) + y x = 0 \bound{e5}\free{y}}
}
\xtc{
}{
\spadcommand{solve(deq, y, x) \free{e5}\free{y}}
}

Coefficients of differential equations can come from arbitrary
constant fields.
For example, coefficients can contain algebraic numbers.

\xtc{
This example has solutions
whose logarithmic derivative is an algebraic function of
degree two.
}{
\spadcommand{eq := 2*x^3 * D(y x,x,2) + 3*x^2 * D(y x,x) - 2 * y x\bound{eq}\free{y}}
}
\xtc{
}{
\spadcommand{solve(eq,y,x).basis\free{eq}}
}

\xtc{
Here's another differential equation to solve.
}{
\spadcommand{deq := D(y x, x) = y(x) / (x + y(x) * log y x) \bound{deqi}\free{y}}
}
\xtc{
}{
\spadcommand{solve(deq, y, x) \free{deqi y}}
}

Rather than attempting to get a closed form solution of
a differential equation, you instead might want to find an
approximate solution in the form of a series.

\xtc{
Let's solve a system of nonlinear first order equations and get a
solution in power series.
Tell \Language{} that \spad{x} is also an operator.
}{
\spadcommand{x := operator 'x\bound{x}}
}
\xtc{
Here are the two equations forming our system.
}{
\spadcommand{eq1 := D(x(t), t) = 1 + x(t)^2\free{x}\free{y}\bound{eq1}}
}
\xtc{
}{
\spadcommand{eq2 := D(y(t), t) = x(t) * y(t)\free{x}\free{y}\bound{eq2}}
}
\xtc{
We can solve the system around \spad{t = 0} with the initial conditions
\spad{x(0) = 0} and \spad{y(0) = 1}.
Notice that since we give the unknowns in the
order \spad{[x, y]}, the answer is a list of two series in the order
\spad{[series for x(t), series for y(t)]}.
}{
\spadcommand{seriesSolve([eq2, eq1], [x, y], t = 0, [y(0) = 1, x(0) = 0])\free{x}\free{y}\free{eq1}\free{eq2}}
}

% *********************************************************************
\head{section}{Solution of Equations}{ugIntroSolution}
% *********************************************************************
%

\Language{} also has state-of-the-art algorithms for the solution
of systems of polynomial equations.
When the number of equations and unknowns is the same, and you
have no symbolic coefficients, you can use \spadfun{solve} for
real roots and \spadfun{complexSolve} for complex roots.
In each case, you tell \Language{} how accurate you want your
result to be.
All operations in the \spadfun{solve} family return answers in
the form of a list of solution sets, where each solution set is a
list of equations.

\xtc{
A system of two equations involving a symbolic
parameter \spad{t}.
}{
\spadcommand{S(t) == [x^2-2*y^2 - t,x*y-y-5*x + 5]\bound{S1}}
}
\xtc{
Find the real roots of \spad{S(19)} with
rational arithmetic, correct to within \smath{1/10^{20}}.
}{
\spadcommand{solve(S(19),1/10^20)\free{S1}}
}
\xtc{
Find the complex roots of \spad{S(19)} with floating
point coefficients to \spad{20} digits accuracy in the mantissa.
}{
\spadcommand{complexSolve(S(19),10.e-20)\free{S1}}
}
\xtc{
If a system of equations has symbolic coefficients and you want
a solution in radicals, try \spadfun{radicalSolve}.
}{
\spadcommand{radicalSolve(S(a),[x,y])\free{S1}}
}
For systems of equations with symbolic coefficients, you can
apply \spadfun{solve}, listing the variables that you want
\Language{} to solve for.
For polynomial equations, a solution cannot usually be expressed
solely in terms of the other variables.
Instead, the solution is presented as a ``triangular'' system of
equations, where each polynomial has coefficients involving
only the succeeding variables. This is analogous to converting  a linear system
of equations to ``triangular form''.
\xtc{
A system of three equations in five variables.
}{
\spadcommand{eqns := [x^2 - y + z,x^2*z + x^4 - b*y, y^2 *z - a - b*x]\bound{e}}
}
\xtc{
Solve the system for unknowns \smath{[x,y,z]},
reducing the solution to triangular form.
}{
\spadcommand{solve(eqns,[x,y,z])\free{e}}
}
% *********************************************************************
\head{section}{System Commands}{ugIntroSysCmmands}
% *********************************************************************
%

We conclude our tour of \Language{} with a brief discussion
of \spadgloss{system commands}.
System commands are special statements that start with a
closing parenthesis (\spadSyntax{)}). They are used to control or
display your \Language{} environment, start the \HyperName{}
system, issue operating system commands and leave \Language{}.
For example, \spadsys{)system} is used
to issue commands to the operating system from \Language{}.
\syscmdindex{system}
Here is a brief description of some of these commands.
For more information on specific commands, see
\appxref{ugSysCmd}.

Perhaps the most important user command is the \spadsys{)clear all}
command that initializes your environment.
Every section and subsection in this book has an invisible
\spadsys{)clear all} that is read prior to the examples given in
the section.
\spadsys{)clear all} gives you a fresh, empty environment with no
user variables defined and the step number reset to \spad{1}.
The \spadsys{)clear} command can also be used to selectively clear
values and properties of system variables.

Another useful system command is \spadsys{)read}.
A preferred way to develop an application in \Language{} is to put
your interactive commands into a file, say {\bf my.input} file.
To get \Language{} to read this file, you use the system command
\spadsys{)read my.input}.
If you need to make changes to your approach or definitions, go
into your favorite editor, change {\bf my.input}, then
\spadsys{)read my.input} again.

Other system commands include: \spadsys{)history}, to display
previous input and/or output lines; \spadsys{)display}, to display
properties and values of workspace variables; and \spadsys{)what}.

\xtc{
Issue \spadsys{)what} to get a list of \Language{} objects that
contain a given substring in their name.
}{
\spadcommand{)what operations integrate}
}

% *********************************************************************
%\head{subsection}{Undo}{ugIntroUndo}
% *********************************************************************

A useful system command is \spadcmd{)undo}.
Sometimes while computing interactively with \Language{}, you make
a mistake and enter an incorrect definition or assignment.
Or perhaps you
need to try one of several alternative approaches, one after
another, to find the best way to approach an application.
For this, you will find the \spadgloss{undo} facility of
\Language{} helpful.

System command \spadsys{)undo n} means ``undo back to step \spad{n}''; it
restores the values of user variables to those that existed
immediately after input expression \spad{n} was evaluated.
Similarly, \spadsys{)undo -n} undoes changes caused by the last
\spad{n} input expressions.
Once you have done an \spadsys{)undo},
you can continue on from there, or make a change and
{\bf redo} all your input expressions from the point
of the \spadsys{)undo} forward.
The \spadsys{)undo} is completely general: it changes the environment
like any user expression.
Thus you can \spadsys{)undo} any previous undo.

Here is a sample dialogue between user and \Language{}.
\xtc{
``Let me define
two mutually dependent functions \spad{f} and \spad{g} piece-wise.''
}{
\spadcommand{f(0) == 1; g(0) == 1\bound{u1}}
}
\xtc{
``Here is the general term for \spad{f}.''
}{
\spadcommand{f(n) == e/2*f(n-1) - x*g(n-1)\bound{u2}\free{u1}}
}
\xtc{
``And here is the general term for \spad{g}.''
}{
\spadcommand{g(n) == -x*f(n-1) + d/3*g(n-1)\bound{u3}\free{u2}}
}
\xtc{
``What is value of \spad{f(3)}?''
}{
\spadcommand{f(3)\bound{u4}\free{u3}}
}
\noOutputXtc{
``Hmm, I think I want to define \spad{f} differently.
Undo to the environment right after I defined \spad{f}.''
}{
\spadcommand{)undo 2\bound{u5}\free{u4}}
}
\xtc{
``Here is how I think I want \spad{f} to be defined instead.''
}{
\spadcommand{f(n) == d/3*f(n-1) - x*g(n-1)\bound{u6}\free{u5}}
}
\noOutputXtc{
Redo the computation from expression \spad{3} forward.
}{
\spadcommand{)undo )redo\bound{u7}\free{u6}}
}
\noOutputXtc{
``I want my old definition of
\spad{f} after all. Undo the undo and restore
the environment to that immediately after \spad{(4)}.''
}{
\spadcommand{)undo 4\bound{u8}\free{u7}}
}
\xtc{
``Check that the value of \spad{f(3)} is restored.''
}{
\spadcommand{f(3)\bound{u9}\free{u8}}
}

After you have gone off on several tangents, then backtracked to
previous points in your conversation using \spadsys{)undo}, you
might want to save all the ``correct'' input commands you issued,
disregarding those undone.
The system command \spadsys{)history )write mynew.input} writes a
clean straight-line program onto the file {\bf mynew.input} on
your disk.

This concludes your tour of \Language{}.
To disembark, issue the system command \spadsys{)quit} to leave \Language{}
and return to the operating system.
