
% 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}{5}}{} % Chapter 6

\newcommand{\pred}[1]{\subscriptIt{pred}{#1}}
\newcommand{\expr}[1]{\subscriptIt{expression}{#1}}

% *********************************************************************
\head{chapter}{User-Defined Functions, Macros and Rules}{ugUser}
% *********************************************************************

In this chapter we show you how to write functions and macros,
and we explain how \Language{} looks for and applies them.
We show some simple one-line examples of functions, together
with larger ones that are defined piece-by-piece or through the use of
piles.

% *********************************************************************
\head{section}{Functions vs. Macros}{ugUserFunMac}
% *********************************************************************

A function is a program to perform some
\index{function!vs. macro}
computation.
\index{macro!vs. function}
Most functions have names so that it is easy to refer to them.
A simple example of a function is one named
\spadfunFrom{abs}{Integer} which
computes the absolute value of an integer.
%
\xtc{
This is a use of the ``absolute value'' library function for integers.
}{
\spadcommand{abs(-8)}
}
\xtc{
This is an unnamed function that does the same thing, using the
``maps-to'' syntax \spadSyntax{+->} that we discuss in
\spadref{ugUserAnon}.
}{
\spadcommand{(x +-> if x < 0 then -x else x)(-8)}
}
%
Functions can be used alone or serve as the building blocks for larger
programs.
Usually they return a value that you might want to use in the next stage
of a computation, but not always (for example, see
\xmpref{Exit} and \xmpref{Void}).
They may also read data from your keyboard, move information from one
place to another, or format and display results on your screen.

In \Language{}, as in mathematics, functions
\index{function!parameters}
are usually \spadglossSee{parameterized}{parameterized form}.
Each time you {\it call} (some people say \spadgloss{apply} or
\spadglossSee{invoke}{invocation}) a function, you give
\index{parameters to a function}
values to the parameters (variables).
Such a value is called an \spadgloss{argument} of
\index{function!arguments}
the function.
\Language{} uses the arguments for the computation.
In this way you get different results depending on what you ``feed'' the
function.

Functions can have local variables or refer to global variables in the
workspace.
\Language{} can often \spadglossSee{compile}{compiler} functions so that
they execute very efficiently.
Functions can be passed as arguments to other functions.

Macros are textual substitutions.
They are used to clarify the meaning of constants or expressions and to be
templates for frequently used expressions.
Macros can be parameterized but they are not objects that can be passed as
arguments to functions.
In effect, macros are extensions to the \Language{} expression parser.

% *********************************************************************
\head{section}{Macros}{ugUserMacros}
% *********************************************************************

A \spadgloss{macro} provides general textual substitution of
\index{macro}
an \Language{} expression for a name.
You can think of a macro as being a generalized abbreviation.
You can only have one macro in your workspace with
a given name, no matter how many arguments it has.

% ----------------------------------------------------------------------
\beginImportant
The two general forms for macros are
\begin{center}
{\tt macro} {\it name} {\tt ==} {\it body} \\
{\tt macro} {\it name(arg1,...)} {\tt ==} {\it body}
\end{center}
where the body of the macro can be any \Language{} expression.
\endImportant
% ----------------------------------------------------------------------

%
\xtc{
For example, suppose you decided that you
like to use \spad{df} for \spadfun{D}.
You define the macro \spad{df} like this.
}{
\spadcommand{macro df == D \bound{df}}
}
\xtc{
Whenever you type \spad{df}, the system expands it to
\spadfun{D}.
}{
\spadcommand{df(x^2 + x + 1,x) \free{df}}
}
\xtc{
Macros can be parameterized and so can be used for many different
kinds of objects.
}{
\spadcommand{macro ff(x) == x^2 + 1 \bound{ff}}
}
\xtc{
Apply it to a number, a symbol, or an expression.
}{
\spadcommand{ff z \free{ff}}
}
\xtc{
Macros can also be nested, but you get an error message if you
run out of space because of an infinite nesting loop.
}{
\spadcommand{macro gg(x) == ff(2*x - 2/3) \bound{gg}\free{ff}}
}
\xtc{
This new macro is fine as it does not produce a loop.
}{
\spadcommand{gg(1/w) \free{gg}}
}
%
\xtc{
This, however, loops since \spad{gg} is
defined in terms of \spad{ff}.
}{
\spadcommand{macro ff(x) == gg(-x) \free{gg}}
}
\xtc{
The body of a macro can be a block.
}{
\spadcommand{macro next == (past := present; present := future; future := past + present) \bound{next}}
}
\xtc{
Before entering \spad{next}, we need
values for \spad{present} and \spad{future}.
}{
\spadcommand{present : Integer := 0 \bound{present}}
}
\xtc{
}{
\spadcommand{future : Integer := 1 \bound{future}}
}
\xtc{
Repeatedly evaluating \spad{next} produces the next Fibonacci number.
}{
\spadcommand{next \free{future}\free{present}}
}
\xtc{
And the next one.
}{
\spadcommand{next \free{future}\free{present}}
}
\xtc{
Here is the infinite stream of the rest of the Fibonacci numbers.
}{
\spadcommand{[next for i in 1..] \free{future}\free{present}}
}
\xtc{
Bundle all the above lines into a single macro.
}{
\begin{spadsrc}[\bound{fibstr}]
macro fibStream ==
  present : Integer := 1
  future : Integer := 1
  [next for i in 1..] where
    macro next ==
      past := present
      present := future
      future := past + present
\end{spadsrc}
}
\xtc{
Use \spadfunFrom{concat}{Stream} to start with the first two
\index{Fibonacci numbers}
Fibonacci numbers.
}{
\spadcommand{concat([0,1],fibStream) \free{fibstr}}
}
\xtc{
An easier way to compute these numbers is to
use the library operation \spadfun{fibonacci}.
}{
\spadcommand{[fibonacci i for i in 1..]}
}

% *********************************************************************
\head{section}{Introduction to Functions}{ugUserIntro}
% *********************************************************************

Each name in your workspace can refer to a single object.
This may be any kind of object including a function.
You can use interactively any function from the library or any that you
define in the workspace.
In the library the same name can have very many functions, but you
can have only one function with a given name, although it can have any
number of arguments that you choose.

If you define a function in the workspace that has the same name and number
of arguments as one in the library, then your definition takes precedence.
In fact, to get the library function you must
\spadglossSee{package-call}{package call} it (see \spadref{ugTypesPkgCall}).

To use a function in \Language{}, you apply it to its arguments.
Most functions are applied by entering the name of the function followed by
its argument or arguments.
\xtc{
}{
\spadcommand{factor(12)}
}
%
\xtc{
Some functions like \spadop{+} have {\it infix} \spadgloss{operators} as names.
}{
\spadcommand{3 + 4}
}
\xtc{
The function \spadop{+} has two arguments.
When you give it more than two arguments,
\Language{} groups the arguments to the left.
This expression is equivalent to \spad{(1 + 2) + 7}.
}{
\spadcommand{1 + 2 + 7}
}

All operations, including infix operators, can be written in prefix form,
that is, with the operation name followed by the arguments
in parentheses.
For example, \spad{2 + 3} can alternatively be written as \spad{+(2,3)}.
But \spad{+(2,3,4)} is an error since \spadop{+}
takes only two arguments.

Prefix operations are generally applied before the infix operation.
Thus \spad{factorial 3 + 1} means \spad{factorial(3) + 1} producing
\spad{7}, and
\spad{- 2 + 5} means \spad{(-2) + 5} producing \spad{3}.
An example of a prefix operator is prefix \spadop{-}.
For example, \spad{- 2 + 5} converts to \spad{(- 2) + 5} producing
the value \spad{3}.
Any prefix function taking two arguments can be written in
an infix manner by putting an
ampersand (\spadSyntax{\&}) before the name.
Thus \spad{D(2*x,x)} can be written as
\spad{2*x \&D x} returning \spad{2}.

Every function in \Language{} is identified by
a \spadgloss{name} and \spadgloss{type}.\footnote{An exception is
an ``anonymous function''
discussed in
\spadref{ugUserAnon}.}
The type of a function is always a mapping of the form
\spadsig{Source}{Target}
where \spad{Source} and \spad{Target} are types.
To enter a type from the keyboard, enter the arrow by using
a hyphen \spadSyntax{-} followed by a greater-than sign
\spadSyntax{>}, e.g. {\tt Integer -> Integer}.

Let's go back to \spadop{+}.
There are many \spadop{+} functions in the
\Language{} library: one for integers, one for floats, another for
rational numbers, and so on.
These \spadop{+} functions have different types and thus are
different functions.
You've seen examples of this \spadgloss{overloading}
before---using the same name for different functions.
Overloading is the rule rather than the exception.
You can add two integers, two polynomials, two matrices or
two power series.
These are all done with the same function name
but with different functions.

% *********************************************************************
\head{section}{Declaring the Type of Functions}{ugUserDeclare}
% *********************************************************************

In \spadref{ugTypesDeclare} we discussed how to declare a variable
to restrict the kind of values that can be assigned to it.
In this section we show how to declare a variable that refers to
function objects.

% ----------------------------------------------------------------------
\beginImportant
A function is an object of type
\begin{center}
\spadsig{Source}{Type}
\end{center}
where \spad{Source} and \spad{Target} can be any type.
A common type for \spad{Source} is
\spadtype{Tuple}(\subscriptIt{T}{1}, \ldots, \subscriptIt{T}{n}),
usually written
(\subscriptIt{T}{1}, \ldots, \subscriptIt{T}{n}),
to indicate a function of \spad{n} arguments.
\endImportant
% ----------------------------------------------------------------------

\xtc{
If \spad{g} takes an \spadtype{Integer}, a \spadtype{Float} and
another \spadtype{Integer}, and returns a
\spadtype{String}, the declaration is written this way.
}{
\spadcommand{g: (Integer,Float,Integer) -> String}
}
\xtc{
The types need not be written fully; using abbreviations, the above
declaration is:
}{
\spadcommand{g: (INT,FLOAT,INT) -> STRING}
}
\xtc{
It is possible for a function to take no arguments.
If \spad{ h} takes no arguments
but returns a \spadtype{Polynomial} \spadtype{Integer}, any
of the following declarations is acceptable.
}{
\spadcommand{h: () -> POLY INT}
}
\xtc{
}{
\spadcommand{h: () -> Polynomial INT}
}
\xtc{
}{
\spadcommand{h: () -> POLY Integer}
}


\beginImportant
Functions can also be declared when they are being defined.
The syntax for combined declaration/definition is:
\begin{center}
\frenchspacing{\tt {\it functionName}(\subscriptIt{parm}{1}: \subscriptIt{parmType}{1}, \ldots, \subscriptIt{parm}{N}: \subscriptIt{parmType}{N}): {\it functionReturnType}}
\end{center}
\endImportant

The following definition fragments show how this can be done for
the functions \spad{g} and \spad{h} above.
\begin{verbatim}
g(arg1: INT, arg2: FLOAT, arg3: INT): STRING == ...

h(): POLY INT == ...
\end{verbatim}

A current restriction on function declarations is that they must
involve fully specified types (that is, cannot include modes involving
explicit or implicit \spadSyntax{?}).
For more information on declaring things in general, see
\spadref{ugTypesDeclare}.

% *********************************************************************
\head{section}{One-Line Functions}{ugUserOne}
% *********************************************************************

As you use \Language{}, you will find that you will write many short functions
\index{function!one-line definition}
to codify sequences of operations that you often perform.
In this section we write some simple one-line functions.

\xtc{
This is a simple recursive factorial function for positive integers.
}{
\spadcommand{fac n == if n < 3 then n else n * fac(n-1) \bound{fac}}
}
\xtc{
}{
\spadcommand{fac 10 \free{fac}}
}
%>> Thankfully, the $ is no longer needed in the next example.
\xtc{
This function computes \spad{1 + 1/2 + 1/3 + ... + 1/n}.
}{
\spadcommand{s n == reduce(+,[1/i for i in 1..n]) \bound{s}}
}
\xtc{
}{
\spadcommand{s 50 \free{s}}
}
\xtc{
This function computes a Mersenne number, several of which are prime.
\index{Mersenne number}
}{
\spadcommand{mersenne i == 2^i - 1 \bound{mersenne}}
}
\xtc{
If you type \spad{mersenne}, \Language{} shows you
the function definition.
}{
\spadcommand{mersenne \free{mersenne}}
}
\xtc{
Generate a stream of Mersenne numbers.
}{
\spadcommand{[mersenne i for i in 1..] \free{mersenne}}
}
\xtc{
Create a stream of those values of \spad{i} such that
\spad{mersenne(i)} is prime.
}{
\spadcommand{mersenneIndex := [n for n in 1.. | prime?(mersenne(n))] \bound{mersenneIndex}\free{mersenne}}
}
\xtc{
Finally, write a function that returns the \eth{\spad{n}} Mersenne
prime.
}{
\spadcommand{mersennePrime n == mersenne mersenneIndex(n) \free{mersenne mersenneIndex}\bound{mersennePrime}}
}
\xtc{
}{
\spadcommand{mersennePrime 5 \free{mersennePrime}}
}

% *********************************************************************
\head{section}{Declared vs. Undeclared Functions}{ugUserDecUndec}
% *********************************************************************

If you declare the type of a function, you can apply
it to any data that can be converted to the source type
of the function.

\labelSpace{2pc}
\xtc{
Define \userfun{f} with type \spadsig{Integer}{Integer}.
}{
\spadcommand{f(x: Integer): Integer == x + 1 \bound{f}}
}
\xtc{
The function
\userfun{f} can be applied to integers, \ldots
}{
\spadcommand{f 9 \free{f}}
}
\xtc{
and to values that convert to integers, \ldots
}{
\spadcommand{f(-2.0) \free{f}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
but not to values that cannot be converted to integers.
}{
\spadcommand{f(2/3) \free{f}}
}
\begin{inputonly}
)set message test on
\end{inputonly}

To make the function over a wide range of types, do not
declare its type.
\xtc{
Give the same definition with no declaration.
}{
\spadcommand{g x == x + 1 \bound{g}}
}
\xtc{
If \spad{x + 1} makes sense, you can apply \userfun{g} to \spad{x}.
}{
\spadcommand{g 9 \free{g}}
}
\xtc{
A version of \userfun{g} with different argument types
get compiled for each new kind of argument used.
}{
\spadcommand{g(2/3)  \free{g}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
Here \spad{x+1} for \spad{x = "axiom"} makes no sense.
}{
\spadcommand{g("axiom")\free{g}}
}
\begin{inputonly}
)set message test on
\end{inputonly}

As you will see in \chapref{ugCategories},
\Language{} has a formal idea of categories for what ``makes sense.''

% *********************************************************************
\head{section}{Functions vs. Operations}{ugUserDecOpers}
% *********************************************************************

A function is an object that you can create, manipulate, pass to,
and return from functions (for some interesting examples of
library functions that manipulate functions, see
\xmpref{MappingPackage1}).
Yet, we often seem to use the term \spadgloss{operation} and
function interchangeably in \Language{}.
What is the distinction?

First consider values and types associated with some variable \spad{n} in
your workspace.
You can make the declaration \spad{n : Integer}, then assign \spad{n} an
integer value.
You then speak of the integer \spad{n}.
However, note that the integer is not the name \spad{n} itself, but
the value that you assign to \spad{n}.

Similarly, you can declare a variable \spad{f} in your workspace to have
type \spadsig{Integer}{Integer}, then assign \spad{f}, through a definition
or an assignment of an anonymous function.
You then speak of the function \spad{f}.
However, the function is not \spad{f}, but the value that you
assign to \spad{f}.

A function is a value, in fact, some machine code for doing something.
Doing what?
Well, performing some \spadgloss{operation}.
Formally, an operation consists of the constituent parts of \spad{f} in your
workspace, excluding the value; thus an operation has a name and a type.
An operation is what domains and packages export.
Thus \spadtype{Ring} exports one operation \spadop{+}.
Every ring also exports this operation.
Also, the author of every ring in the system is obliged under contract
(see \spadref{ugPackagesAbstract})
to provide an implementation for this operation.

This chapter is all about functions---how you create them interactively and
how you apply them to meet your needs.
In \chapref{ugPackages} you will learn how to create them for the
\Language{} library.
Then in \chapref{ugCategories}, you will learn about categories and
exported operations.

% *********************************************************************
\head{section}{Delayed Assignments vs. Functions with No Arguments}{ugUserDelay}
% *********************************************************************

In \spadref{ugLangAssign} we discussed the difference between immediate and
\index{function!with no arguments}
delayed assignments.
In this section we show the difference between delayed
assignments and functions of no arguments.

\labelSpace{2pc}
\xtc{
A function of no arguments is sometimes called a {\it nullary function.}
}{
\spadcommand{sin24() == sin(24.0) \bound{sin24}}
}
\xtc{
You must use the parentheses (\spadSyntax{()}) to evaluate it.
Like a delayed assignment, the right-hand-side of a function evaluation
is not evaluated until the left-hand-side is used.
}{
\spadcommand{sin24() \free{sin24}}
}
\xtc{
If you omit the parentheses, you just get the function definition.
%(Note how the explicit floating point number in the definition
%has been translated into a function call involving a mantissa,
%exponent and radix.)
}{
\spadcommand{sin24 \free{sin24}}
}
\xtc{
You do not use the parentheses \spadSyntax{()} in a delayed assignment\ldots
}{
\spadcommand{cos24 == cos(24.0) \bound{cos24}}
}
\xtc{
nor in the evaluation.
}{
\spadcommand{cos24 \free{cos24}}
}
The only syntactic difference between delayed assignments
and nullary functions is that you use \spadSyntax{()} in the latter case.

% *********************************************************************
\head{section}{How \Language{} Determines What Function to Use}{ugUserUse}
% *********************************************************************

What happens if you define a function that has the same name as a library
function?
Well, if your function has the same name and number of arguments (we
sometimes say \spadgloss{arity}) as another function
in the library, then your function covers up the library function.
If you want then to call the library function, you will have to package-call
it.
\Language{} can use both the functions you write and those that come
from the library.
Let's do a simple example to illustrate this.
\xtc{
Suppose you (wrongly!) define \userfun{sin} in this way.
}{
\spadcommand{sin x == 1.0 \bound{sin}}
}
\xtc{
The value \spad{1.0} is returned for any argument.
}{
\spadcommand{sin 4.3 \free{sin}}
}
\xtc{
If you want the library operation, we have to package-call it
(see \spadref{ugTypesPkgCall}
for more information).
}{
\spadcommand{sin(4.3)\$Float}
}
\xtc{
}{
\spadcommand{sin(34.6)\$Float}
}
\xtc{
Even worse, say we accidentally used the same name as a library
function in the function.
}{
\spadcommand{sin x == sin x \bound{sin1}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
Then \Language{} definitely does not understand us.
}{
\spadcommand{sin 4.3 \free{sin1}}
}
\begin{inputonly}
)set message test on
\end{inputonly}
\xtc{
Again, we could package-call the inside function.
}{
\spadcommand{sin x == sin(x)\$Float \bound{sin2}}
}
\xtc{
}{
\spadcommand{sin 4.3 \free{sin2}}
}
Of course, you are unlikely to make such obvious errors.
It is more probable that you would write a function and in the body use a
function that you think is a library function.
If you had also written a function by that same name, the library function
would be invisible.

How does \Language{} determine what library function to call?
It very much depends on the particular example, but the simple case of
creating the polynomial
\spad{x + 2/3} will give you an idea.
\begin{enumerate}
\item The \spad{x} is analyzed and its default type is
\spadtype{Variable(x)}.
\item The \spad{2} is analyzed and its default type is
\spadtype{PositiveInteger}.
\item The \spad{3} is analyzed and its default type is
\spadtype{PositiveInteger}.
\item Because the arguments to \spadop{/} are integers, \Language{}
gives the expression \spad{2/3} a default target type of
\spadtype{Fraction(Integer)}.
\item \Language{} looks in \spadtype{PositiveInteger} for \spadop{/}.
It is not found.
\item \Language{} looks in \spadtype{Fraction(Integer)} for \spadop{/}.
It is found for arguments of type \spadtype{Integer}.
\item The \spad{2} and \spad{3} are converted to objects of type
\spadtype{Integer} (this is trivial) and \spadop{/} is applied,
creating an object of type \spadtype{Fraction(Integer)}.
\item No \spadop{+} for arguments of types \spadtype{Variable(x)} and
\spadtype{Fraction(Integer)} are found in either domain.
\item \Language{} resolves
\index{resolve}
(see \spadref{ugTypesResolve})
the types and gets \spadtype{Polynomial (Fraction (Integer))}.
\item The \spad{x} and the \spad{2/3} are converted to objects of this
type and \spadop{+} is applied, yielding the answer, an object of type
\spadtype{Polynomial (Fraction (Integer))}.
\end{enumerate}

% *********************************************************************
\head{section}{Compiling vs. Interpreting}{ugUserCompInt}
% *********************************************************************

When possible, \Language{} completely determines the type of every object in
a function, then translates the function definition to \Lisp{} or
to machine code (see next section).
This translation,
\index{function!compiler}
called \spadglossSee{compilation}{compiler}, happens the first time you call
the function and results in a computational delay.
Subsequent function calls with the same argument types use the compiled
version of the code without delay.

If \Language{} cannot determine the type of everything, the
function may still be executed
\index{function!interpretation}
but
\index{interpret-code mode}
in \spadglossSee{interpret-code mode}{interpreter} :
each statement in the function is analyzed and executed as the control
flow indicates.
This process is slower than executing a compiled function, but it
allows the execution of code that may involve objects whose types
change.

% ----------------------------------------------------------------------
\beginImportant
If \Language{} decides that it cannot compile the code, it
issues a message stating the problem and then the following
message:
%
\begin{center}
{\bf We will attempt to step through and interpret the code.}
\end{center}
%
This is not a time to panic.
\index{panic!avoiding}
Rather, it just means that what you gave to \Language{}
is somehow ambiguous: either it is not specific enough to be analyzed
completely, or it is beyond \Language{}'s present interactive
compilation abilities.
\endImportant
% ----------------------------------------------------------------------

\xtc{
This function runs in interpret-code mode, but it does not compile.
}{
\begin{spadsrc}[\bound{varPolys}]
varPolys(vars) ==
  for var in vars repeat
    output(1 :: UnivariatePolynomial(var,Integer))
\end{spadsrc}
}
\xtc{
For \spad{vars} equal to \spad{['x, 'y, 'z]}, this function displays
\spad{1} three times.
}{
\spadcommand{varPolys ['x,'y,'z] \free{varPolys}}
}
\xtc{
The type of the argument to \spadfun{output} changes in each iteration,
so \Language{} cannot compile the function.
In this case, even the inner loop by itself would have a problem:
}{
\begin{spadsrc}
for var in ['x,'y,'z] repeat
  output(1 :: UnivariatePolynomial(var,Integer))
\end{spadsrc}
}

Sometimes you can help a function to compile by using an extra conversion
or by using \spad{pretend}.
\spadkey{pretend}
See \spadref{ugTypesSubdomains} for details.

When a function is compilable, you have the choice of whether it is
compiled to \Lisp{} and then interpreted by the \Lisp{}
interpreter or then further compiled from \Lisp{} to machine code.
\index{machine code}
The option is controlled via \spadcmd{)set functions compile}.
\syscmdindex{set function compile}
Issue \spadcmd{)set functions compile on} to compile all the way to
machine code.
With
the default setting \spadcmd{)set functions compile off},
\Language{} has its \Lisp{} code interpreted
because the overhead of further compilation is larger than the run-time
of most of the functions our users have defined.
You may find that selectively turning this option on and off will
\index{performance}
give you the best performance in your particular application.
For example, if you are writing functions for graphics applications
where hundreds of points are being computed, it is almost certainly true
that you will get the best performance by issuing
\spadcmd{)set functions compile on}.

% *********************************************************************
\head{section}{Piece-Wise Function Definitions}{ugUserPiece}
% *********************************************************************

To move beyond functions defined in one line, we introduce in this section
functions that are defined piece-by-piece.
That is, we say ``use this definition when the argument is such-and-such and
use this other definition when the argument is that-and-that.''

% *********************************************************************
\head{subsection}{A Basic Example}{ugUserPieceBasic}
% *********************************************************************

There are many other ways to define a factorial function for nonnegative
integers.
You might
\index{function!piece-wise definition}
say
\index{piece-wise function definition}
factorial of \spad{0} is \spad{1,} otherwise factorial of \spad{n} is
\spad{n} times factorial of \spad{n-1}.
Here is one way to do this in \Language{}.
%
\xtc{
Here is the value for \spad{n = 0}.
}{
\spadcommand{fact(0) == 1 \bound{fact0}}
}
\xtc{
Here is the value for \spad{n > 0}.
The vertical bar \spadSyntax{|} means
``such that''.
}{
\spadcommand{fact(n | n > 0) == n * fact(n - 1) \free{fact0}\bound{factn}}
}
\index{such that}
%>> am moving this back
%The vertical bar \spadSyntax{|} is read as ``such that'' and so
%\index{such that}
%the second line means that that part of the definition for \userfun{fact}
%is for any \spad{n} such that \spad{n} is greater than 0.
%In fact, the first line is really just a shorthand expression for
%\spad{fact(n | n = 0) == 1}.
%>> prefer scratching next 4 lines
%We are implicitly using a \spadgloss{predicate} with a \spadSyntax{|} in
%this line (see \spadref{ugUserPiecePred} for more on predicates).
%So this piece of the function is applicable to all (the not so many!)
%values of \spad{n} that are equal to zero.
\xtc{
What is the value for \spad{n = 3}?
}{
\spadcommand{fact(3) \free{factn}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
What is the value for \spad{n = -3}?
}{
\spadcommand{fact(-3) \free{factn}}
}
\begin{inputonly}
)set message test on
\end{inputonly}
\xtc{
Now for a second definition.
Here is the value for \spad{n = 0}.
}{
\spadcommand{facto(0) == 1 \bound{facto0}}
}
\xtc{
Give an error message if \spad{n < 0}.
}{
\spadcommand{facto(n | n < 0) == error "arguments to facto must be non-negative" \free{facto0}\bound{factop}}
}
\xtc{
Here is the value otherwise.
}{
\spadcommand{facto(n) == n * facto(n - 1) \free{factop}\bound{facton}}
}
\xtc{
What is the value for \spad{n = 7}?
}{
\spadcommand{facto(3) \free{facton}}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
What is the value for \spad{n = -7}?
}{
\spadcommand{facto(-7) \free{facton}}
}
\begin{inputonly}
)set message test on
\end{inputonly}
\xtc{
To see the current piece-wise definition of a function,
use \spadsys{)display value}.
}{
\spadcommand{)display value facto \free{facton}}
}

In general a {\it piece-wise definition} of a function consists of two or
more parts.
Each part gives a ``piece'' of the entire definition.
\Language{} collects the pieces of a function as you enter them.
When you ask for a value of the function, it then ``glues''
the pieces together to form a function.

The two piece-wise definitions for the factorial function
are examples of recursive functions, that is, functions that
are defined in terms of themselves.
Here is an interesting doubly-recursive function.
This function returns the value \spad{11} for all positive integer arguments.
\xtc{
Here is the first of two pieces.
}{
\spadcommand{eleven(n | n < 1) == n + 11\bound{ff0}}
}
\xtc{
And the general case.
}{
\spadcommand{eleven(m) == eleven(eleven(m - 12))\bound{ff1}\free{ff0}}
}
\xtc{
Compute \spad{elevens}, the infinite stream
of values of \spad{eleven}.
}{
\spadcommand{elevens := [eleven(i) for i in 0..]\bound{ff2}\free{ff1}}
}
\xtc{
What is the value at \spad{n = 200}?
}{
\spadcommand{elevens 200\free{ff2}}
}
\xtc{
What is the \Language{}'s definition of \spad{eleven}?
}{
\spadcommand{)display value eleven\free{ff2}}
}
% *********************************************************************
\head{subsection}{Picking Up the Pieces}{ugUserPiecePicking}
% *********************************************************************

Here are the details about how \Language{} creates a function from its
pieces.
\Language{} converts the \eth{\spad{i}} piece of a function definition into a
conditional expression of the form: \spad{if} \pred{i} \spad{then}
\expr{i}.
If any new piece has a \pred{i} that is identical\footnote{after all
variables are uniformly named} to an earlier \pred{j}, the earlier piece is
removed.
Otherwise, the new piece is always added at the end.

% ----------------------------------------------------------------------
\beginImportant
If there are \spad{n} pieces to a function definition for \spad{f},
the function defined \spad{f} is: \newline
%
\texht{\hspace*{3pc}}{\tab{6}}
{\tt if} \pred{1} {\tt then} \expr{1} {\tt else}\newline
\texht{\hspace*{6pc}}{\tab{12}}. . . \newline
\texht{\hspace*{3pc}}{\tab{6}}
{\tt if} \pred{n} {\tt then} \expr{n} {\tt else}\newline
\texht{\hspace*{3pc}}{\tab{6}}
{\tt  error "You did not define f for argument <arg>."}
%
\endImportant
% ----------------------------------------------------------------------

You can give definitions of any number of mutually recursive function
definitions, piece-wise or otherwise.
No computation is done until you ask for a value.
When you do ask for a value, all the relevant definitions are gathered,
analyzed, and translated into separate functions and compiled.

\xtc{
Let's recall the definition of \userfun{eleven} from
\texht{the previous section}{\spadref{ugUserPieceBasic}}.
}{
\spadcommand{eleven(n | n < 1) == n + 11\bound{ff0}}
}
\xtc{
}{
\spadcommand{eleven(m) == eleven(eleven(m - 12))\bound{ff1}\free{ff0}}
}

A similar doubly-recursive function below produces \spad{-11} for all
negative positive integers.
If you haven't worked out why or how \userfun{eleven} works,
the structure of this definition gives a clue.
\xtc{
This definition we write as a block.
}{
\begin{spadsrc}[\bound{rf1}]
minusEleven(n) ==
  n >= 0 => n - 11
  minusEleven (5 + minusEleven(n + 7))
\end{spadsrc}
}
\xtc{
Define \spad{s(n)} to be the
sum of plus and minus ``eleven'' functions divided by \spad{n}.
Since \spad{11 - 11 = 0}, we define \spad{s(0)} to be \spad{1}.
}{
\spadcommand{s(0) == 1\bound{rf2}}
}
\xtc{
And the general term.
}{
\spadcommand{s(n) == (eleven(n) + minusEleven(n))/n\bound{rf3}\free{rf2 rf1 ff1}}
}
\xtc{
What are the first ten values of \spad{s}?
}{
\spadcommand{[s(n) for n in 0..]\free{rf3}}
}
%% interpreter puts the rule at the end - should fix
% \xtc{
% Oops! Evidently \spad{s(0)} should be \spad{1}.
% Let's check the current definition of \userfun{s} using \spadsys{)display}.
% }{
% \spadcommand{)display value s\free{rf3}}
% }
% \xtc{
% Change the value at \spad{n = 0}.
% }{
% \spadcommand{s(0) == 1\free{rf3}\bound{rf4}}
% }
% \xtc{
% Now, what is the definition of \userfun{s}?
% Note: {\it you can only replace a given piece if you give exactly the same
% predicate!}
% }{
% \spadcommand{)display value s\free{rf4}}
% }
\Language{} can create infinite streams in the positive direction (for
example, for index values \spad{0,1, \ldots}) or negative direction (for
example, for index values \spad{0,-1,-2, \ldots}).
Here we would like a stream of values of \spad{s(n)} that is infinite in
both directions.
The function \spad{t(n)} below returns the \eth{\spad{n}} term of the infinite
stream \spad{[s(0), s(1), s(-1), s(2), s(-2), \ldots].}
Its definition has three pieces.
\xtc{
Define the initial term.
}{
\spadcommand{t(1) == s(0)\bound{t1}\free{rf4}}
}
\xtc{
The even numbered terms are the \spad{s(i)} for positive \spad{i}.
We use \spadop{quo} rather than \spadop{/}
since we want the result to be an integer.
}{
\spadcommand{t(n | even?(n)) == s(n quo 2)\free{t1}\bound{t2}}
}
\xtc{
Finally, the odd numbered terms are the
\spad{s(i)} for negative \spad{i}.
In piece-wise definitions, you can use different variables
to define different pieces. \Language{} will not get confused.
}{
\spadcommand{t(p) == s(- p quo 2)\free{t2}\bound{t3}}
}
\xtc{
Look at the definition of \spad{t}.
In the first piece, the variable \spad{n}
was used; in the second piece, \spad{p}.
\Language{} always uses
your last variable to display your definitions
back to you.
}{
\spadcommand{)display value t\free{t2}}
}
\xtc{
Create a series of values of \spad{s} applied to
alternating positive and negative arguments.
}{
\spadcommand{[t(i) for i in 1..]\free{t3}\bound{t4}}
}
\xtc{
Evidently \spad{t(n) = 1} for all \spad{i.}
Check it at \spad{n= 100}.
}{
\spadcommand{t(100)\free{t4}}
}

% *********************************************************************
\head{subsection}{Predicates}{ugUserPiecePred}
% *********************************************************************

We have already seen some examples of
\index{function!predicate}
predicates
\index{predicate!in function definition}
(\spadref{ugUserPieceBasic}).
Predicates are \spadtype{Boolean}-valued expressions and \Language{} uses them
for filtering collections
(see \spadref{ugLangIts})
and for placing
constraints on function arguments.
In this section we discuss their latter usage.

\xtc{
The simplest use of a predicate is one you don't see at all.
}{
\spadcommand{opposite 'right == 'left}
}
\xtc{
Here is a longer way to give the ``opposite definition.''
}{
\spadcommand{opposite (x | x = 'left) == 'right}
}
\xtc{
Try it out.
}{
\spadcommand{for x in ['right, 'left] repeat output opposite x}
}
\begin{inputonly}
)set message test off
\end{inputonly}
\xtc{
We get an error if there is no definition for given argument.
}{
\spadcommand{opposite('inbetween)}
}
\begin{inputonly}
)set message test on
\end{inputonly}

Explicit predicates tell \Language{} that the given function definition
piece is to be applied if the predicate evaluates to {\tt true} for the
arguments to the function.
You can use such ``constant'' arguments for integers,
\index{function!constant argument}
strings, and quoted symbols.
\index{constant function argument}
The \spadtype{Boolean} values \spad{true} and \spad{false} can also be used
if qualified with ``\spad{@}'' or ``\spad{\$}'' and \spadtype{Boolean}.
The following are all valid function definition fragments using
constant arguments.
\begin{verbatim}
a(1) == ...
b("unramified") == ...
c('untested) == ...
d(true@Boolean) == ...
\end{verbatim}

If a function has more than one argument,
each argument can have its own predicate.
However, if a predicate involves two or more arguments, it must be given
{\it after} all the arguments mentioned in the predicate have been given.
You are always safe to give
a single predicate at the end of the argument list.
\xtc{
A function involving predicates on two arguments.
}{
\spadcommand{inFirstHalfQuadrant(x | x > 0,y | y < x) == true}
}
\xtc{
This is incorrect as it gives a predicate on \spad{y}
before the argument \spad{y} is given.
}{
\spadcommand{inFirstHalfQuadrant(x | x > 0 and y < x,y) == true}
}
\xtc{
It is always correct to write the predicate at the end.
}{
\spadcommand{inFirstHalfQuadrant(x,y | x > 0 and y < x) == true \bound{ifq1a}}
}
\xtc{
Here is the rest of the definition.
}{
\spadcommand{inFirstHalfQuadrant(x,y) == false \bound{ifq1b}}
}
\xtc{
Try it out.
}{
\spadcommand{[inFirstHalfQuadrant(i,3) for i in 1..5]\bound{ifq1b}}
}

{\bf Remark:} Very old versions of \Language{} allowed predicates
to be given after a {\tt when} keyword as in
{\tt inFirstHalfQuadrant(x ,y) == true when x >0 and y < x}.
This is no longer supported, is WRONG, and will cause a syntax
error or strange behavior.

% *********************************************************************
\head{section}{Caching Previously Computed Results}{ugUserCache}
% *********************************************************************

By default, \Language{} does not save the values of any function.
\index{function!caching values}
You can cause it to save values and not to recompute unnecessarily
\index{remembering function values}
by using \spadcmd{)set functions cache}.
\syscmdindex{set functions cache}
This should be used before the functions are defined or, at least, before
they are executed.
The word following ``cache'' should be \spad{0} to turn off
caching, a positive integer \spad{n} to save the last \spad{n}
computed values or ``all'' to save all computed values.
If you then give a list of names of functions, the caching
only affects those functions.
Use no list of names or ``all'' when you want to define the default
behavior for functions not specifically mentioned in other
\spadcmd{)set functions cache} statements.
If you give no list of names, all functions will have the caching behavior.
If you explicitly turn on caching for one or more names, you must
explicitly turn off caching for those names when you want to stop
saving their values.

\xtc{
This causes the functions \userfun{f} and \userfun{g} to have
the last three computed values saved.
}{
\spadcommand{)set functions cache 3 f g \bound{cache}}
}
\xtc{
This is a sample definition for \userfun{f}.
}{
\spadcommand{f x == factorial(2^x) \bound{fdef}\free{cache}}
}
\xtc{
A message is displayed stating what \userfun{f} will cache.
}{
\spadcommand{f(4) \free{}\free{cache}}
}
\xtc{
This causes all other functions to have all computed values saved by
default.
}{
\spadcommand{)set functions cache all}
}
\xtc{
This causes all functions that have not been specifically cached in some way
to have no computed values saved.
}{
\spadcommand{)set functions cache 0}
}
\xtc{
We also make \userfun{f} and \userfun{g} uncached.
}{
\spadcommand{)set functions cache 0 f g}
}

\beginImportant
Be careful about caching functions that have
\spadglossSee{side effects}{side effect}.
Such a function might destructively modify the elements of an array or
issue a \spadfun{draw} command, for example.
A function that you expect to execute every time it is called should
not be cached.
Also, it is highly unlikely that a function with no arguments should
be cached.
\endImportant

You should also be careful about caching functions that depend on
free variables.
See \spadref{ugUserFreeLocal}
for an example.

% *********************************************************************
\head{section}{Recurrence Relations}{ugUserRecur}
% *********************************************************************

One of the most useful classes of function are those defined via a
``recurrence relation.''
A {\it recurrence relation} makes each successive
\index{recurrence relation}
value depend on some or all of the previous values.
A simple example is the ordinary ``factorial'' function:
\begin{verbatim}
fact(0) == 1
fact(n | n > 0) == n * fact(n-1)
\end{verbatim}

The value of
\spad{fact(10)} depends on the value of \spad{fact(9)}, \spad{fact(9)}
on \spad{fact(8)}, and so on.
Because it depends on only one previous value, it is usually called a
{\it first order recurrence relation.}
You can easily imagine a function based on two, three or more previous
values.
The Fibonacci numbers are probably the most famous function defined by a
\index{Fibonacci numbers}
second order recurrence relation.
\xtc{
The library function \spadfun{fibonacci} computes Fibonacci numbers.
It is obviously optimized for speed.
}{
\spadcommand{[fibonacci(i) for i in 0..]}
}
\xtc{
Define the
Fibonacci numbers ourselves using a piece-wise definition.
}{
\spadcommand{fib(1) == 1 \bound{fib0}}
}
\xtc{
}{
\spadcommand{fib(2) == 1 \bound{fib1}\free{fib0}}
}
\xtc{
}{
\spadcommand{fib(n) == fib(n-1) + fib(n-2) \bound{fibn}\free{fib1}}
}

As defined, this recurrence relation is obviously doubly-recursive.
To compute \spad{fib(10)}, we need to compute \spad{fib(9)} and
\spad{fib(8)}.
And to  \spad{fib(9)}, we need to compute \spad{fib(8)} and
\spad{fib(7)}.
And so on.
It seems that to compute \spad{fib(10)} we need to compute
\spad{fib(9)} once, \spad{fib(8)} twice, \spad{fib(7)} three times.
Look familiar?
The number of function calls needed to compute {\it any} second order
recurrence relation in the obvious way is exactly \spad{fib(n)}.
These numbers grow!
For example, if \Language{} actually did this, then \spad{fib(500)}
requires more than \texht{$10^{104}$}{\spad{10^104}} function calls.
And, given all this, our definition of \userfun{fib} obviously could not be
used to calculate the five-hundredth Fibonacci number.
\xtc{
Let's try it anyway.
}{
\spadcommand{fib(500) \free{fibn}}
}

Since this takes a short time to compute, it obviously didn't do
as many as \texht{$10^{104}$}{\spad{10^104}} operations!
By default, \Language{} transforms any recurrence relation it recognizes
into an iteration.
Iterations are efficient.
To compute the value of the \eth{\spad{n}}
term of a recurrence relation using an iteration requires only
\spad{n} function calls.\footnote{If
you compare the speed of our \userfun{fib} function
to the library function, our version is still slower.
This is because the library
\spadfunFrom{fibonacci}{IntegerNumberTheoryFunctions}
uses a ``powering algorithm'' with a computing time
proportional to \texht{$\log^3(n)$}{\spad{log(n)^3}} to compute
\spad{fibonacci(n).}}

To turn off this special recurrence relation compilation, issue
\syscmdindex{set function recurrence}
\begin{verbatim}
)set functions recurrence off
\end{verbatim}
To turn it back on, substitute ``{\tt on}'' for ``{\tt off}''.

The transformations that \Language{} uses for \userfun{fib} caches the
last two values.\footnote{For a more general \eth{\spad{k}} order recurrence
relation, \Language{} caches the last \spad{k} values.}
If, after computing a value for \userfun{fib}, you ask
for some larger value, \Language{} picks up the cached values
and continues computing from there.
See \spadref{ugUserFreeLocal}
for an example of a function definition that has this same behavior.
Also see \spadref{ugUserCache}
for a more general discussion of how you can cache function values.

Recurrence relations can be used for defining recurrence relations
involving polynomials, rational functions, or anything you like.
Here we compute the infinite stream of Legendre polynomials.
\xtc{
The Legendre polynomial of degree \spad{0.}
}{
\spadcommand{p(0) == 1\bound{p0}}
}
\xtc{
The Legendre polynomial of degree \spad{1.}
}{
\spadcommand{p(1) == x\bound{p1}}
}

\xtc{
The Legendre polynomial of degree \spad{n}.
}{
\spadcommand{p(n) == ((2*n-1)*x*p(n-1) - (n-1)*p(n-2))/n\bound{pn}\free{p1}}
}
\xtc{
Compute the Legendre polynomial of degree \spad{6.}
}{
\spadcommand{p(6)\free{pn}}
}

% *********************************************************************
\head{section}{Making Functions from Objects}{ugUserMake}
% *********************************************************************

There are many times when you compute a complicated expression
and then wish to use that expression as the body of a function.
\Language{} provides an operation called \spadfun{function} to do
\index{function!from an object}
this.
\index{function!made by function @{made by {\bf function}}}
It creates a function object and places it into the workspace.
There are several versions, depending on how many arguments the function
has.
The first argument to \spadfun{function} is always the expression to be
converted into the function body, and the second is always the name to be
used for the function.
For more information, see \xmpref{MakeFunction}.

\xtc{
Start with a simple example of a polynomial in three variables.
}{
\spadcommand{p := -x + y^2 - z^3 \bound{p}}
}
\xtc{
To make this into a function of no arguments that
simply returns the polynomial, use the two argument form of
\spadfun{function}.
}{
\spadcommand{function(p,'f0) \free{p}\bound{f0}}
}
\xtc{
To avoid possible conflicts (see below), it is a good idea to
quote always this second argument.
}{
\spadcommand{f0 \free{f0}}
}
\xtc{
This is what you get when you evaluate the function.
}{
\spadcommand{f0() \free{f0}}
}
\xtc{
To make a function in \spad{x}, use a version of
\spadfun{function} that takes three arguments.
The last argument is the name of the variable to use as the parameter.
Typically, this variable occurs in the expression and, like the function
name, you should quote it to avoid possible confusion.
}{
\spadcommand{function(p,'f1,'x) \free{p}\bound{f1}}
}
\xtc{
This is what the new function looks like.
}{
\spadcommand{f1 \free{f1}}
}
\xtc{
This is the value of \userfun{f1} at \spad{x = 3}.
Notice that the return type of the function is
\spadtype{Polynomial (Integer)}, the same as \spad{p}.
}{
\spadcommand{f1(3) \free{f1}}
}
\xtc{
To use \spad{x} and \spad{y} as parameters, use the
four argument form of \spadfun{function}.
}{
\spadcommand{function(p,'f2,'x,'y) \free{p}\bound{f2}}
}
\xtc{
}{
\spadcommand{f2 \free{f2}}
}
\xtc{
Evaluate \spad{f2} at \spad{x = 3} and \spad{y = 0}.
The return type of \userfun{f2} is still
\spadtype{Polynomial(Integer)} because the variable \spad{z}
is still present and not one of the parameters.
}{
\spadcommand{f2(3,0) \free{f2}}
}
\xtc{
Finally, use all three variables as parameters.
There is no five argument form of \spadfun{function}, so use the one with
three arguments, the third argument being a list of the parameters.
}{
\spadcommand{function(p,'f3,['x,'y,'z]) \free{p}\bound{f3}}
}
\xtc{
Evaluate this using the same values for \spad{x} and \spad{y}
as above, but let \spad{z} be \spad{-6}.
The result type of \userfun{f3} is \spadtype{Integer}.
}{
\spadcommand{f3 \free{f3}}
}
\xtc{
}{
\spadcommand{f3(3,0,-6) \free{f3}}
}

The four functions we have defined via \spad{p} have been undeclared.
To declare a function whose body is to be generated by
\index{function!declaring}
\spadfun{function}, issue the declaration {\it before} the function is created.
\xtc{
}{
\spadcommand{g: (Integer, Integer) -> Float \bound{g}}
}
\xtc{
}{
\spadcommand{D(sin(x-y)/cos(x+y),x) \bound{prev}}
}
\xtc{
}{
\spadcommand{function(\%,'g,'x,'y) \free{g}\free{prev}}
}
\xtc{
}{
\spadcommand{g \free{g}}
}
It is an error to use \spad{g} without the quote in the
penultimate expression since \spad{g} had been declared but did not have
a value.
Similarly, since it is common to overuse variable names like \spad{x},
\spad{y}, and so on,
you avoid problems if you always quote the variable names
for \spadfun{function}.
In general,
if \spad{x} has a value and you use \spad{x} without a quote in a call to
\spadfun{function}, then
\Language{} does not know what you are trying to do.

What kind of object is allowable as the first argument to \spadfun{function}?
Let's use the \Browse{} facility of \HyperName{} to find out.
\index{Browse@\Browse{}}
At the main \Browse{} menu, enter the string {\tt function} and then
click on {\bf Operations.}
The exposed operations called \spadfun{function} all take an object
whose type belongs to category \spadtype{ConvertibleTo InputForm}.
What domains are those?
Go back to the main \Browse{} menu, erase {\tt function},
enter {\tt ConvertibleTo} in the
input area, and click on {\bf categories} on the {\bf Constructors} line.
At the bottom of the page, enter {\tt InputForm} in the input area
following {\bf S =}.
Click on {\bf Cross Reference} and then on {\bf Domains}.
The list you see contains over forty domains that belong to the
category \spadtype{ConvertibleTo InputForm}.
Thus you can use \spadfun{function} for \spadtype{Integer},
\spadtype{Float},
\spadtype{String},
\spadtype{Complex},
\spadtype{Expression}, and so on.

% *********************************************************************
\head{section}{Functions Defined with Blocks}{ugUserBlocks}
% *********************************************************************
% return, local and free variables

You need not restrict yourself to functions that only fit on one line
or are written in a piece-wise manner.
The body of the function can be a block, as discussed in
\spadref{ugLangBlocks}.

\labelSpace{1pc}
\xtc{
Here is a short function that swaps two elements of a list,
array or vector.
}{
\begin{spadsrc}[\bound{swap}]
swap(m,i,j) ==
  temp := m.i
  m.i := m.j
  m.j := temp
\end{spadsrc}
}
\xtc{
The significance of \userfun{swap} is that it has a destructive
effect on its first argument.
}{
\spadcommand{k := [1,2,3,4,5] \bound{k}}
}
\xtc{
}{
\spadcommand{swap(k,2,4) \free{l swap}\bound{swapk}}
}
\xtc{
You see that the second and fourth elements are interchanged.
}{
\spadcommand{k \free{swapk}}
}

\xtc{
Using this, we write a couple of different sort functions.
First, a simple bubble sort.
\index{sort!bubble}
The operation \spadopFrom{\#}{List} returns the number of elements in
an aggregate.
}{
\begin{spadsrc}[\bound{bubbleSort}]
bubbleSort(m) ==
  n := \#m
  for i in 1..(n-1) repeat
    for j in n..(i+1) by -1 repeat
      if m.j < m.(j-1) then swap(m,j,j-1)
  m
\end{spadsrc}
}
\xtc{
Let this be the list we want to sort.
}{
\spadcommand{m := [8,4,-3,9] \bound{m}}
}
\xtc{
This is the result of sorting.
}{
\spadcommand{bubbleSort(m) \free{m swap bubbleSort}\bound{sortm}}
}
\xtc{
Moreover, \spad{m} is destructively changed to be the sorted version.
}{
\spadcommand{m \free{sortm}}
}

\xtc{
This function implements an insertion sort.
\index{sort!insertion}
The basic idea is to traverse the list and insert the \eth{\spad{i}}
element in its correct position among the \spad{i-1} previous
elements.
Since we start at the beginning of the list, the list elements before the
\eth{\spad{i}} element have already been placed in ascending order.
}{
\begin{spadsrc}[\bound{insertionSort}]
insertionSort(m) ==
  for i in 2..\#m repeat
    j := i
    while j > 1 and m.j < m.(j-1) repeat
      swap(m,j,j-1)
      j := j - 1
  m
\end{spadsrc}
}
\xtc{
As with our bubble sort, this is a destructive function.
}{
\spadcommand{m := [8,4,-3,9] \bound{m1}}
}
\xtc{
}{
\spadcommand{insertionSort(m) \free{m1 swap insertionSort}\bound{sortm1}}
}
\xtc{
}{
\spadcommand{m \free{sortm1}}
}

Neither of the above functions is efficient for sorting large lists since
they reference elements by asking for the \eth{\spad{j}} element of the
structure \spad{m}.
%For lists, compute \spad{m.(j+1) = rest(m,j).first}, and thus, starting at
%the first node of \spad{m}, walk down to the \eth{\spad{j}} node, then call
%\spadfun{first}.

\xtc{
Here is a more efficient bubble sort for lists.
}{
\begin{spadsrc}[\bound{bubbleSort2}]
bubbleSort2(m: List Integer): List Integer ==
  null m => m
  l := m
  while not null (r := l.rest) repeat
     r := bubbleSort2 r
     x := l.first
     if x < r.first then
       l.first := r.first
       r.first := x
     l.rest := r
     l := l.rest
  m
\end{spadsrc}
}
\xtc{
Try it out.
}{
\spadcommand{bubbleSort2 [3,7,2]\free{bubbleSort2}}
}

This definition is both recursive and iterative, and is tricky!
Unless you are {\it really} curious about this definition,
we suggest you skip immediately to the next section.

Here are the key points in the definition.
First notice that if you are sorting a list with less than two elements,
there is nothing to do: just return the list.
This definition returns immediately if there are zero elements, and skips
the entire \spad{while} loop if there is just one element.

The second point to realize is that on each outer iteration, the bubble sort
ensures that the minimum element is propagated leftmost.
Each iteration of the \spad{while} loop calls \userfun{bubbleSort2}
recursively to sort all but the first element.
When finished, the minimum element is either in the first or second position.
The conditional expression ensures that it comes first.
If it is in the second, then a swap occurs.
In any case, the \spadfun{rest} of the original list must be updated to hold
the result of the recursive call.

% *********************************************************************
\head{section}{Free and Local Variables}{ugUserFreeLocal}
% *********************************************************************

When you want to refer to a variable that is not local to your
function, use a ``\spad{free}'' declaration.
\spadkey{free}
Variables declared to be \spad{free}
\index{free variable}
are assumed to be defined globally
\index{variable!free}
in the
\index{variable!global}
workspace.
\index{global variable}

\labelSpace{1pc}
\xtc{
This is a global workspace variable.
}{
\spadcommand{counter := 0 \bound{counter}}
}
\xtc{
This function refers to the global \spad{counter}.
}{
\begin{spadsrc}[\free{counter}\bound{f}]
f() ==
  free counter
  counter := counter + 1
\end{spadsrc}
}
\xtc{
The global \spad{counter} is incremented by \spad{1}.
}{
\spadcommand{f() \free{f}\bound{f1}}
}
\xtc{
}{
\spadcommand{counter \free{f1}}
}

Usually \Language{} can tell that you mean to refer to a global
variable and so \spad{free} isn't always necessary.
However, for clarity and the sake of self-documentation, we encourage
you to use it.

Declare a variable to be ``\spad{local}'' when you do not want to refer to
\index{variable!local}
a global variable by the same name.
\index{local variable}

\xtc{
This function uses \spad{counter} as a local variable.
}{
\begin{spadsrc}[\bound{g}]
g() ==
  local counter
  counter := 7
\end{spadsrc}
}
\xtc{
Apply the function.
}{
\spadcommand{g() \free{g}}
}
\xtc{
Check that the global value of \spad{counter} is unchanged.
}{
\spadcommand{counter\free{g f1}}
}

Parameters to a function are local variables in the function.
Even if you issue a \spad{free} declaration for a parameter, it is
still local.

What happens if you do not declare that a variable \spad{x} in
the body of your function is \spad{local} or \spad{free}?
Well, \Language{} decides on this basis:

\begin{enumerate}
\item \Language{} scans your function line-by-line, from top-to-bottom.
The right-hand side of an assignment is looked at before the left-hand
side.
\item If \spad{x} is referenced before it is assigned a value, it is a
\spad{free} (global) variable.
\item If \spad{x} is assigned a value before it is referenced, it is a
\spad{local} variable.
\end{enumerate}

\xtc{
Set two global variables to 1.
}{
\spadcommand{a := b := 1\bound{ab1}}
}
\xtc{
Refer to \spad{a} before it is assigned a value, but
assign a value to \spad{b} before it is referenced.
}{
\begin{spadsrc}[\bound{hh}]
h() ==
  b := a + 1
  a := b + a
\end{spadsrc}
}
\xtc{
Can you predict this result?
}{
\spadcommand{h() \free{ab1 hh}\bound{hhh}}
}
\xtc{
How about this one?
}{
\spadcommand{[a, b] \free{hhh}}
}

What happened?
In the first line of the function body for \spad{h}, \spad{a} is
referenced on the right-hand side of the assignment.
Thus \spad{a} is a free variable.
The variable \spad{b} is not referenced in that line, but it is
assigned a value.
Thus \spad{b} is a local variable and is given the value
\spad{a + 1 = 2}.
In the second line, the free variable \spad{a} is assigned the value
\spad{b + a} which equals \spad{2 + 1 = 3.}
This is the value returned by the function.
Since \spad{a} was free in \userfun{h}, the global variable \spad{a}
has value \spad{3.}
Since \spad{b} was local in \userfun{h}, the global variable \spad{b}
is unchanged---it still has the value \spad{1.}

It is good programming practice always to declare global variables.
However, by far the most common situation is to have local variables in
your functions.
No declaration is needed for this situation, but be sure to
initialize their values.

Be careful if you use free variables and you cache the value of
your function (see \spadref{ugUserCache}).
Caching {\it only} checks if the values of the function arguments
are the same as in a function call previously seen.
It does not check if any of the free variables on which the
function depends have changed between function calls.
\xtc{
Turn on caching for \userfun{p}.
}{
\spadcommand{)set fun cache all p \bound{pcache}}
}
\xtc{
Define \userfun{p} to depend on the free variable \spad{N}.
}{
\spadcommand{p(i,x) == ( free N; reduce( + , [ (x-i)^n for n in 1..N ] ) ) \free{pcache}\bound{pdef}}
}
\xtc{
Set the value of \spad{N}.
}{
\spadcommand{N := 1 \bound{Nass}}
}
\xtc{
Evaluate \userfun{p} the first time.
}{
\spadcommand{p(0, x) \free{pdef Nass}\bound{pfirst}}
}
\xtc{
Change the value of \spad{N}.
}{
\spadcommand{N := 2 \bound{Nass2}}
}
\xtc{
Evaluate \userfun{p} the second time.
}{
\spadcommand{p(0, x) \free{pfirst Nass2}}
}
If caching had been turned off, the second evaluation would have
reflected the changed value of \spad{N}.
\xtc{
Turn off caching for \userfun{p}.
}{
\spadcommand{)set fun cache 0 p}
}

\Language{} does not allow {\it fluid variables}, that is, variables
\index{variable!fluid}
\spadglossSee{bound}{binding} by a function \spad{f} that can be referenced by
functions called by \spad{f}.
\index{fluid variable}

Values are passed to functions by \spadgloss{reference}: a pointer
to the value is passed rather than a copy of the value or a pointer to
a copy.

\xtc{
This is a global variable that is bound to a record object.
}{
\spadcommand{r : Record(i : Integer) := [1] \free{r}}
}
\xtc{
This function first modifies the one component of its
record argument and then rebinds the parameter to another
record.
}{
\begin{spadsrc}[\bound{resetRecord}]
resetRecord rr ==
  rr.i := 2
  rr := [10]
\end{spadsrc}
}
\xtc{
Pass \spad{r} as an argument to \userfun{resetRecord}.
}{
\spadcommand{resetRecord r \free{r resetRecord}\bound{rr}}
}
\xtc{
The value of \spad{r} was changed by the expression
\spad{rr.i := 2} but not by \spad{rr := [10]}.
}{
\spadcommand{r \free{rr}}
}

To conclude this section, we give an iterative definition of
\index{Fibonacci numbers}
a function that computes Fibonacci numbers.
This definition approximates the definition into which \Language{}
transforms the recurrence relation definition of \userfun{fib} in
\spadref{ugUserRecur}.

\xtc{
Global variables
\spad{past} and \spad{present} are used
to hold the last computed Fibonacci numbers.
}{
\spadcommand{past := present := 1\bound{f0}}
}
\xtc{
Global variable \spad{index} gives the
current index of \spad{present}.
}{
\spadcommand{index := 2\bound{f1}\free{f0}}
}
\xtc{
Here is a recurrence relation defined in terms
of these three global variables.
}{
\begin{spadsrc}[\bound{f3}\free{f2}]
fib(n) ==
  free past, present, index
  n < 3 => 1
  n = index - 1 => past
  if n < index-1 then
    (past,present) := (1,1)
    index := 2
  while (index < n) repeat
    (past,present) := (present, past+present)
    index := index + 1
  present
\end{spadsrc}
}
\xtc{
Compute the infinite stream of Fibonacci numbers.
}{
\spadcommand{fibs := [fib(n) for n in 1..] \bound{fibs}\free{f3}}
}
\xtc{
What is the 1000th Fibonacci number?
}{
\spadcommand{fibs 1000 \free{fibs}}
}

As an exercise, we suggest you write a function in an iterative
style that computes the value of the recurrence relation
\texht{$p(n) = p(n-1) - 2 \, p(n-2) + 4 \, p(n-3)$}{\spad{p(n) = p(n-1) - 2*p(n-2) + 4*p(n-3)}}
having the initial values
\texht{$p(1) = 1,\, p(2) = 3 \hbox{ and } p(3) = 9.$}{\spad{p(1) = 1, p(2) = 3 {\rm and} p(3) = 9.}}
How would you write the function using an element
\spadtype{OneDimensionalArray} or \spadtype{Vector}
to hold the previously computed values?

% *********************************************************************
\head{section}{Anonymous Functions}{ugUserAnon}
% *********************************************************************

% ----------------------------------------------------------------------
\beginImportant
An {\it anonymous function} is a function that is
\index{function!anonymous}
defined
\index{anonymous function}
by giving a list of parameters, the ``maps-to'' compound
\index{+-> @{\tt +->}}
symbol \spadSyntax{+->} \texht{(from the mathematical symbol
$\mapsto$)}{},
and by an expression involving the parameters, the evaluation of
which determines the return value of the function.

\begin{center}
{\tt ( \subscriptIt{parm}{1}, \subscriptIt{parm}{2}, \ldots, \subscriptIt{parm}{N} ) +-> {\it expression}}
\end{center}
\endImportant
% ----------------------------------------------------------------------

You can apply an anonymous function in several ways.
\begin{enumerate}
\item Place the anonymous function definition in parentheses
directly followed by a list of arguments.
\item Assign the anonymous function to a variable and then
use the variable name when you would normally use a function name.
\item Use \spadSyntax{==} to use the anonymous function definition as
the arguments and body of a regular function definition.
\item Have a named function contain a declared anonymous function and
use the result returned by the named function.
\end{enumerate}

% *********************************************************************
\head{subsection}{Some Examples}{ugUserAnonExamp}
% *********************************************************************

Anonymous functions are particularly useful for defining functions
``on the fly.'' That is, they are handy for simple functions that
are used only in one place.
In the following examples, we show how to write some simple
anonymous functions.

\xtc{
This is a simple absolute value function.
}{
\spadcommand{x +-> if x < 0 then -x else x \bound{anon0}}
}
\xtc{
}{
\spadcommand{abs1 := \% \free{anon0}\bound{abs1}}
}
\xtc{
This function returns {\tt true} if the absolute value of
the first argument is greater than the absolute value of the
second, {\tt false} otherwise.
}{
\spadcommand{(x,y) +-> abs1(x) > abs1(y) \bound{anon1}\free{abs1}}
}
\xtc{
We use the above function to ``sort'' a list of integers.
}{
\spadcommand{sort(\%,[3,9,-4,10,-3,-1,-9,5]) \free{anon1}}
}

\xtc{
This function returns \spad{1} if \spad{i + j} is even, \spad{-1} otherwise.
}{
\spadcommand{ev := ( (i,j) +-> if even?(i+j) then 1 else -1) \bound{ev}}
}
\xtc{
We create a four-by-four matrix containing \spad{1} or \spad{-1}
depending on whether the row plus the column index is even or not.
}{
\spadcommand{matrix([[ev(row,col) for row in 1..4] for col in 1..4]) \free{ev}}
}

\xtc{
This function returns {\tt true} if a polynomial in \spad{x} has multiple
roots, {\tt false} otherwise.
It is defined and applied in the same expression.
}{
\spadcommand{( p +-> not one?(gcd(p,D(p,x))) )(x^2+4*x+4)}
}

\xtc{
This and the next expression are equivalent.
}{
\spadcommand{g(x,y,z) == cos(x + sin(y + tan(z)))}
}
\xtc{
The one you use is a matter of taste.
}{
\spadcommand{g == (x,y,z) +-> cos(x + sin(y + tan(z)))}
}

% *********************************************************************
\head{subsection}{Declaring Anonymous Functions}{ugUserAnonDeclare}
% *********************************************************************

If you declare any of the arguments you must declare all of them.
Thus,
\begin{verbatim}
(x: INT,y): FRAC INT +-> (x + 2*y)/(y - 1)
\end{verbatim}
is not legal.

\xtc{
This is an example of a fully declared anonymous
\index{function!declaring}
function.
\index{function!anonymous!declaring}
The output shown just indicates that the object you created is a
particular kind of map, that is, function.
}{
\spadcommand{(x: INT,y: INT): FRAC INT +-> (x + 2*y)/(y - 1)}
}
\xtc{
\Language{} allows you to declare the arguments and not declare
the return type.
}{
\spadcommand{(x: INT,y: INT) +-> (x + 2*y)/(y - 1)}
}
The return type is computed from the types of the arguments and the
body of the function.
You cannot declare the return type if you do not declare the arguments.
Therefore,
\begin{verbatim}
(x,y): FRAC INT +-> (x + 2*y)/(y - 1)
\end{verbatim}
is not legal.

\xtc{
This and the next expression are equivalent.
}{
\spadcommand{h(x: INT,y: INT): FRAC INT == (x + 2*y)/(y - 1)}
}
\xtc{
The one you use is a matter of taste.
}{
\spadcommand{h == (x: INT,y: INT): FRAC INT +-> (x + 2*y)/(y - 1)}
}

When should you declare an anonymous function?
\begin{enumerate}
\item If you use an anonymous function and \Language{} can't figure
out what you are trying to do, declare the function.
\item If the function has nontrivial argument types or a
nontrivial return type that
\Language{} may be able to determine eventually, but you are not
willing to wait that long, declare the function.
\item If the function will only be used for arguments of specific
types and it is not too much trouble to declare the function, do so.
\item If you are using the anonymous function as an argument to
another function (such as \spadfun{map} or \spadfun{sort}),
consider declaring the function.
\item If you define an anonymous function inside a named function,
you {\it must} declare the anonymous function.
\end{enumerate}

\xtc{
This is an example of a named function for integers that returns a
function.
}{
\spadcommand{addx x == ((y: Integer): Integer +-> x + y) \bound{addx}}
}
\xtc{
We define \userfun{g} to be a function that adds \spad{10} to its
argument.
}{
\spadcommand{g := addx 10 \free{addx}\bound{g}}
}
\xtc{
Try it out.
}{
\spadcommand{g 3 \free{g}}
}
\xtc{
}{
\spadcommand{g(-4) \free{g}}
}

\index{function!anonymous!restrictions}
An anonymous function cannot be recursive: since it does not have a
name, you cannot even call it within itself!
If you place an anonymous function inside a named function, the
anonymous function must be declared.

% *********************************************************************
\head{section}{Example: A Database}{ugUserDatabase}
% *********************************************************************

This example shows how you can use \Language{} to organize a database of
lineage data and then query the database for relationships.

\labelSpace{1.5pc}
\xtc{
The database is entered as ``assertions'' that are really
pieces of a function definition.
}{
\spadcommand{children("albert") == ["albertJr","richard","diane"]\bound{d1}}
}
\xtc{
Each piece
\spad{children(x) == y} means
``the children of \spad{x} are \spad{y}''.
}{
\spadcommand{children("richard") == ["douglas","daniel","susan"]\free{d1}\bound{d2}}
}
\xtc{
This family tree thus spans four generations.
}{
\spadcommand{children("douglas") == ["dougie","valerie"]\free{d2}\bound{d3}}
}
\xtc{
Say ``no one else has children.''
}{
\spadcommand{children(x) == []\free{d3}\bound{d4}}
}

\xtc{
We need some functions for computing lineage.
Start with \spad{childOf}.
}{
\spadcommand{childOf(x,y) == member?(x,children(y))\bound{d9}\free{d10}}
}
\xtc{
To find the \spad{parentOf} someone,
you have to scan the database of
people applying \spad{children}.
}{
\begin{spadsrc}[\bound{d8a}\free{d9}]
parentOf(x) ==
  for y in people repeat
    (if childOf(x,y) then return y)
  "unknown"
\end{spadsrc}
}
\xtc{
And a grandparent of \spad{x} is just a parent of a parent of \spad{x}.
}{
\spadcommand{grandParentOf(x) == parentOf parentOf x\bound{d8}\free{d8a}}
}
\xtc{
The grandchildren of \spad{x}
are the people \spad{y} such that
\spad{x} is a grandparent of \spad{y}.
}{
\spadcommand{grandchildren(x) == [y for y in people | grandParentOf(y) = x]\free{d7}\bound{d8}}
}
\xtc{
Suppose you want to make a list of all great-grandparents.
Well, a great-grandparent is a grandparent of a person who has children.
}{
\begin{spadsrc}[\free{d6}\bound{d7}]
greatGrandParents == [x for x in people |
  reduce(\_or,[not empty? children(y) for y in grandchildren(x)],false)]
\end{spadsrc}
}
\xtc{
Define \spad{descendants} to include the parent as well.
}{
\begin{spadsrc}[\free{d5}\bound{d6}]
descendants(x) ==
  kids := children(x)
  null kids => [x]
  concat(x,reduce(concat,[descendants(y)
    for y in kids],[]))
\end{spadsrc}
}
\xtc{
Finally, we need a list of people.
Since all people are descendants of ``albert'', let's say so.
}{
\spadcommand{people == descendants "albert"\free{d4}\bound{d5}}
}

We have used \spadSyntax{==} to define the database and some functions to
query the database.
But no computation is done until we ask for some information.
Then, once and for all, the functions are analyzed and compiled to machine
code for run-time efficiency.
Notice that no types are given anywhere in this example.
They are not needed.

\xtc{
Who are the grandchildren of ``richard''?
}{
\spadcommand{grandchildren "richard"\bound{d10}\free{d11}}
}
\xtc{
Who are the great-grandparents?
}{
\spadcommand{greatGrandParents\bound{d11}\free{d12}}
}

% *********************************************************************
\head{section}{Example: A Famous Triangle}{ugUserTriangle}
% *********************************************************************

In this example we write some functions that display
Pascal's triangle.
\index{Pascal's triangle}
It demonstrates the use of piece-wise definitions and some output
operations you probably haven't seen before.

\labelSpace{1pc}
\xtc{
To make these output operations
available, we have to \spadgloss{expose} the domain
\spadtype{OutputForm}.
\exptypeindex{OutputForm}
See \spadref{ugTypesExpose} for more information about exposing domains
and packages.
}{
\spadcommand{)set expose add constructor OutputForm \bound{expose}}
}
\xtc{
Define the values along the first
row and any column \spad{i}.
}{
\spadcommand{pascal(1,i) == 1 \bound{pas1}}
}
\xtc{
Define the values for when the row
and column index \spad{i} are equal.
Repeating the argument name indicates that
the two index values are equal.
}{
\spadcommand{pascal(n,n) == 1 \bound{pas2}\free{pas1}}
}
\xtc{
}{
\begin{spadsrc}[\bound{pas3}\free{pas1 pas2}]
pascal(i,j | 1 < i and i < j) ==
   pascal(i-1,j-1)+pascal(i,j-1)
\end{spadsrc}
}
Now that we have defined the coefficients in Pascal's triangle,
let's write a couple of one-liners to display it.
\xtc{
First, define a function that gives the \eth{\spad{n}} row.
}{
\spadcommand{pascalRow(n) == [pascal(i,n) for i in 1..n] \bound{pascalRow}\free{pas3}}
}
\xtc{
Next, we write the function \userfun{displayRow}
to display the row, separating entries by blanks and centering.
}{
\spadcommand{displayRow(n) == output center blankSeparate pascalRow(n) \free{pascalRow}\bound{displayRow}\free{expose}}
}
%
Here we have used three output operations.
Operation \spadfunFrom{output}{OutputForm}
displays the printable form of objects on the screen,
\spadfunFrom{center}{OutputForm} centers a printable form in the
width of the screen, and \spadfunFrom{blankSeparate}{OutputForm} takes a list of
printable forms and inserts a blank between successive elements.
\xtc{
Look at the result.
}{
\spadcommand{for i in 1..7 repeat displayRow i \free{displayRow}}
}
Being purists, we find this less than satisfactory.
Traditionally, elements of Pascal's triangle are centered between
the left and right elements on the line above.
%
\xtc{
To fix this misalignment, we go back and
redefine \userfun{pascalRow} to right adjust the entries within the
triangle within a width of four characters.
}{
\spadcommand{pascalRow(n) == [right(pascal(i,n),4) for i in 1..n] \bound{pascalRow2}}
}
%
\xtc{
Finally let's look at our purely reformatted triangle.
}{
\spadcommand{for i in 1..7 repeat displayRow i \free{pascalRow2}\free{displayRow}}
}
\xtc{
Unexpose \spadtype{OutputForm} so we don't get unexpected
results later.
}{
\spadcommand{)set expose drop constructor OutputForm}
}

% *********************************************************************
\head{section}{Example: Testing for Palindromes}{ugUserPal}
% *********************************************************************

\begin{inputonly}
)set expose drop constructor OutputForm
\end{inputonly}

In this section we define a function \userfun{pal?} that tests whether its
\index{palindrome}
argument is a {\it palindrome}, that is, something that reads the same
backwards and forwards.
For example, the string ``Madam I'm Adam'' is a palindrome (excluding blanks
and punctuation) and so is the number \spad{123454321.}
The definition works for any datatype that has \spad{n} components that
are accessed by the indices \spad{1\ldots n}.

\xtc{
Here is the definition for \userfun{pal?}.
It is simply a call to an auxiliary function called
\userfun{palAux?}.
We are following the convention of ending a function's name with
\spadSyntax{?} if the function returns a \spadtype{Boolean} value.
}{
\spadcommand{pal? s ==  palAux?(s,1,\#s) \bound{pal}}
}
\xtc{
Here is \userfun{palAux?}.
It works by comparing elements that are equidistant from the start and end
of the object.
}{
\begin{spadsrc}[\bound{palAux}]
palAux?(s,i,j) ==
  j > i =>
    (s.i = s.j) and palAux?(s,i+1,i-1)
  true
\end{spadsrc}
}
\xtc{
Try \userfun{pal?} on some examples.
First, a string.
}{
\spadcommand{pal? "Oxford"  \free{pal palAux}}
}
\xtc{
A list of polynomials.
}{
\spadcommand{pal? [4,a,x-1,0,x-1,a,4]  \free{pal palAux}}
}
\xtc{
A list of integers from the example in
\texht{the last section.}{\spadref{ugUserTriangle}.}
}{
\spadcommand{pal? [1,6,15,20,15,6,1] \free{pal palAux}}
}
\xtc{
To use \userfun{pal?} on an integer, first convert it to a string.
}{
\spadcommand{pal?(1441::String)\free{pal palAux}}
}
\xtc{
Compute an infinite stream of decimal numbers,
each of which is an obvious palindrome.
}{
\spadcommand{ones := [reduce(+,[10^j for j in 0..i]) for i in 1..]\free{pal palAux}\bound{pal5}}
}
\begin{texonly}
\begin{discard}
\noOutputXtc{
}{
\spadcommand{)set streams calculate 9}
}
\end{discard}
\end{texonly}
\xtc{
How about their squares?
}{
\spadcommand{squares := [x^2 for x in ones]\free{pal5}\bound{pal6}}
}
\xtc{
Well, let's test them all!
}{
\spadcommand{[pal?(x::String) for x in squares]\free{pal6}}
}
\begin{texonly}
\begin{discard}
\noOutputXtc{
}{
\spadcommand{)set streams calculate 7}
}
\end{discard}
\end{texonly}

% *********************************************************************
\head{section}{Rules and Pattern Matching}{ugUserRules}
% *********************************************************************

A common mathematical formula is
\texht{\narrowDisplay{%
\log(x) + \log(y) = \log(x y) \quad\forall \, x \hbox{\ and\ } y.}}{
\spad{log(x) + log(y) == log(x * y)} for any \spad{x} and \spad{y}.}
The presence of
\texht{``$\forall$''}{the word ``any''}
indicates that \spad{x} and \spad{y} can stand for arbitrary mathematical
expressions in the above formula.
You can use such mathematical formulas in \Language{} to specify ``rewrite
rules''.
Rewrite rules are objects in \Language{} that can be assigned to variables for
later use, often for the purpose of simplification.
Rewrite rules look like ordinary function definitions except that they are
preceded by the reserved word \spad{rule}.
\spadkey{rule}
For example, a rewrite rule for the above formula is:
\begin{verbatim}
rule log(x) + log(y) == log(x * y)
\end{verbatim}
Like function definitions, no action is taken when a rewrite rule is issued.
Think of rewrite rules as functions that take one argument.
When a rewrite rule \spad{A = B} is applied to an argument \spad{f}, its
meaning is: ``rewrite every subexpression of \spad{f} that {\it matches}
\spad{A} by \spad{B.}''
The left-hand side of a rewrite rule is called a \spadgloss{pattern}; its
right-side side is called its \spadgloss{substitution}.

\xtc{
Create a rewrite rule named \userfun{logrule}.
The generated symbol beginning with a \spadSyntax{\%} is a place-holder
for any other terms that might occur in the sum.
}{
\spadcommand{logrule := rule log(x) + log(y) == log(x * y) \bound{logrule}}
}
\xtc{
Create an expression with logarithms.
}{
\spadcommand{f := log sin x + log x \bound{f}}
}
\xtc{
Apply \userfun{logrule} to \spad{f}.
}{
\spadcommand{logrule f \free{f}\free{logrule}}
}

The meaning of our example rewrite rule is:
``for all expressions \spad{x} and \spad{y}, rewrite
\spad{log(x) + log(y)} by \spad{log(x * y)}.''
Patterns generally have both operation names
(here, \spadfun{log} and \spadop{+})
and variables (here, \spad{x} and \spad{y}).
By default, every operation name stands for itself.
Thus \spadfun{log}  matches only ``\spad{log}'' and not any
other operation such as \spadfun{sin}.
On the other hand, variables do not stand for themselves.
Rather, a variable denotes a
{\it pattern variable} that is free to match any expression whatsoever.
\index{pattern!variables}

When a rewrite rule is applied, a process called
\spadgloss{pattern matching} goes to work by systematically
scanning
\index{pattern!matching}
the subexpressions of the argument.
When a subexpression is found that ``matches'' the pattern, the subexpression
is replaced by the right-hand side of the rule.
The details of what happens will be covered later.

The customary \Language{} notation for patterns is actually a shorthand for a
longer, more general notation.
Pattern variables can be made explicit by using a percent
(\spadSyntax{\%}) as the first character of the variable name.
To say that a name stands for itself, you can prefix that name with a quote
operator (\spadSyntax{'}).
Although the current \Language{} parser does not let you quote an operation
name, this more general notation gives you an alternate way of giving the same
rewrite rule:
\begin{verbatim}
rule log(%x) + log(%y) == log(x * y)
\end{verbatim}
This longer notation gives you patterns that the
standard notation won't handle.
For example, the rule
\texht{\typeout{check this example}}{}
\begin{verbatim}
rule %f(c * 'x) ==  c*%f(x)
\end{verbatim}
means ``for all \spad{f} and \spad{c}, replace \spad{f(y)} by
\spad{c * f(x)} when \spad{y} is the product of \spad{c}
and the explicit variable \spad{x}.''

Thus the pattern can have several adornments on the names that appear there.
Normally, all these adornments are dropped in the substitution on the
right-hand side.

To summarize:

% ----------------------------------------------------------------------
\beginImportant
To enter a single rule in \Language{}, use the following syntax:
\spadkey{rule}
\begin{center}
{\tt rule {\it leftHandSide} == {\it rightHandSide}}
\end{center}
The {\it leftHandSide} is a pattern to be matched and
the {\it rightHandSide} is its substitution.
The rule is an object of type \spadtype{RewriteRule} that can be
assigned to a variable and applied to expressions to transform them.
\endImportant
% ----------------------------------------------------------------------

Rewrite rules can be collected
into rulesets so that a set of rules can be applied at once.
Here is another simplification rule for logarithms.
\texht{\narrowDisplay{y \log(x) = \log(x^y) \quad\forall \, x \hbox{\ and\ } y.}}{
\spad{y * log(x) == log(x ^ y)} for any \spad{x} and \spad{y}.}
If instead of giving a single rule following the reserved word \spad{rule}
you give a ``pile'' of rules, you create
what is called a {\it ruleset.}
\index{ruleset}
Like rules, rulesets are objects in \Language{} and
can be assigned to variables.
You will find it useful to group commonly used rules into input files, and read
them in as needed.
\xtc{
Create a ruleset named \spad{logrules}.
}{
\begin{spadsrc}[\bound{logrules}]
logrules := rule
  log(x) + log(y) == log(x * y)
  y * log x       == log(x ^ y)
\end{spadsrc}
}
\xtc{
Again, create an expression \spad{f} containing logarithms.
}{
\spadcommand{f := a * log(sin x) - 2 * log x \bound{f1}}
}
\xtc{
Apply the ruleset \userfun{logrules} to \spad{f}.
}{
\spadcommand{logrules f \free{f1}\free{logrules}}
}

We have allowed pattern variables to match arbitrary expressions in the
above examples.
Often you want a variable only to match expressions
satisfying some predicate.
For example, we may want to apply the transformation
\texht{\narrowDisplay{y \log(x) = \log(x^y)}}{\spad{y * log(x) == log(x ^ y)}}
only when \spad{y} is an integer.
%
The way to restrict a pattern variable \spad{y} by a predicate \spad{f(y)}
\index{pattern!variable!predicate}
is by using a vertical bar \spadSyntax{|}, which means ``such that,'' in
\index{such that}
much the same way it is used in function definitions.
\index{predicate!on a pattern variable}
You do this only once, but at the earliest
(meaning deepest and leftmost) part of the pattern.
\xtc{
This restricts the logarithmic rule to create integer exponents only.
}{
\begin{spadsrc}[\bound{logrules2}]
logrules2 := rule
  log(x) + log(y)          == log(x * y)
  (y | integer? y) * log x == log(x ^ y)
\end{spadsrc}
}
\xtc{
Compare this with the result of applying the previous set of rules.
}{
\spadcommand{f \free{f1}}
}
\xtc{
}{
\spadcommand{logrules2 f \free{f1}\free{logrules2}}
}
You should be aware that you might need to apply a function like
\spadfun{integer} within your predicate expression to actually apply
the test function.
\xtc{
Here we use \spadfun{integer} because \spad{n} has
type \spadtype{Expression Integer} but \spadfun{even?} is an operation
defined on integers.
}{
\spadcommand{evenRule := rule cos(x)^(n | integer? n and even? integer n)==(1-sin(x)^2)^(n/2) \bound{evenRule}}
}
\xtc{
Here is the application of the rule.
}{
\spadcommand{evenRule( cos(x)^2 ) \free{evenRule}}
}
\xtc{
This is an example of some of the usual identities involving products of
sines and cosines.
}{
\begin{spadsrc}[\bound{sinCosProducts}]
sinCosProducts == rule
  sin(x) * sin(y) == (cos(x-y) - cos(x + y))/2
  cos(x) * cos(y) == (cos(x-y) + cos(x+y))/2
  sin(x) * cos(y) == (sin(x-y) + sin(x + y))/2
\end{spadsrc}
}
\xtc{
}{
\spadcommand{g := sin(a)*sin(b) + cos(b)*cos(a) + sin(2*a)*cos(2*a) \bound{g}}
}
\xtc{
}{
\spadcommand{sinCosProducts g \free{sinCosProducts g}}
}

Another qualification you will often want to use is to allow a pattern to
match an identity element.
Using the pattern \spad{x + y}, for example, neither \spad{x} nor \spad{y}
matches the expression \spad{0}.
Similarly, if a pattern contains a product \spad{x*y} or an exponentiation
\spad{x^y}, then neither \spad{x} or \spad{y} matches \spad{1}.
%
\xtc{
If identical elements were matched, pattern matching would generally loop.
Here is an expansion rule for exponentials.
}{
\spadcommand{exprule := rule exp(a + b) == exp(a) * exp(b)\bound{exprule}}
}
\xtc{
This rule would cause infinite rewriting on this if either \spad{a} or
\spad{b} were allowed to match \spad{0}.
}{
\spadcommand{exprule exp x \free{exprule}}
}
%
There are occasions when you do want a pattern variable in a sum or
product to match \spad{0} or \spad{1}.
If so, prefix its name
with a \spadSyntax{?} whenever it appears in a left-hand side of a rule.
For example, consider the following rule for the exponential integral:
\texht{\narrowDisplay{\int \left(\frac{y+e^x}{x}\right)\: dx = \int \frac{y}{x}\: dx + \hbox{\rm Ei}(x)
\quad\forall \, x \hbox{\ and\ } y.}}{
\spad{integral((y + exp x)/x, x) == integral(y/x, x) + Ei x}
for any \spad{x} and \spad{y}.}
This rule is valid for \spad{y = 0}.
One solution is to create a \spadtype{Ruleset} with two
rules, one with and one without \spad{y}.
A better solution is to use an ``optional'' pattern variable.
%
\xtc{
Define rule \spad{eirule} with
a pattern variable \spad{?y} to indicate
that an expression may or may not occur.
}{
\spadcommand{eirule := rule integral((?y + exp x)/x,x) == integral(y/x,x) + Ei x \bound{eirule}}
}
\xtc{
Apply rule \spad{eirule} to an integral without this term.
}{
\spadcommand{eirule integral(exp u/u, u) \free{eirule}}
}
\xtc{
Apply rule \spad{eirule} to an integral with this term.
}{
\spadcommand{eirule integral(sin u + exp u/u, u) \free{eirule}}
}

Here is one final adornment you will find useful.
When matching a pattern of the form \spad{x + y} to an expression containing a
long sum of the form \spad{a +\ldots+ b}, there is no way to predict in
advance which subset of the sum  matches \spad{x} and which matches
\spad{y}.
Aside from efficiency, this is generally unimportant since the rule holds for
any possible combination of matches for \spad{x} and \spad{y}.
In some situations, however, you may want to say which pattern variable is a sum
(or product) of several terms, and which should match only a single term.
To do this, put a prefix colon \spadSyntax{:} before the pattern variable
that you want to match multiple terms.
\index{pattern!variable!matching several terms}
%
\xtc{
The remaining rules involve operators \spad{u} and \spad{v}.
\index{operator}
}{
\spadcommand{u := operator 'u \bound{u}}
}
\xtc{
These definitions tell \Language{} that
\spad{u} and \spad{v} are formal operators to be used in expressions.
}{
\spadcommand{v := operator 'v \bound{v}}
}
\xtc{
First define \spad{myRule}
with no restrictions on the pattern variables
\spad{x} and \spad{y}.
}{
\spadcommand{myRule := rule u(x + y) == u x + v y \free{u v}\bound{m}}
}
\xtc{
Apply \spad{myRule} to an expression.
}{
\spadcommand{myRule u(a + b + c + d) \free{m}}
}
\xtc{
Define \spad{myOtherRule} to match several terms
so that the rule gets applied recursively.
}{
\spadcommand{myOtherRule := rule u(:x + y) == u x + v y \free{u v}\bound{m2}}
}
\xtc{
Apply \spad{myOtherRule} to the same expression.
}{
\spadcommand{myOtherRule u(a + b + c + d) \free{m2}}
}

% ----------------------------------------------------------------------
\begin{texonly}
\beginImportant
Summary of pattern variable adornments:

\vskip .5\baselineskip
\begin{tabular}{@{}ll}
{\tt (x | predicate?(x))} &
  means that the substutution \spad{s} for \spad{x}\\ &
  must satisfy \spad{predicate?(s) = true.} \\
{\tt ?x} &
  means that \spad{x} can match an identity \\ & element (0 or 1). \\
{\tt :x} &
  means that \spad{x} can match several terms \\ & in a sum.
\end{tabular}
\endImportant
\end{texonly}
% ----------------------------------------------------------------------

Here are some final remarks on pattern matching.
Pattern matching provides a very useful paradigm for solving
certain classes of problems, namely, those that involve
transformations of one form to another and back.
However, it is important to recognize its limitations.
\index{pattern!matching!caveats}

First, pattern matching slows down as the number of rules you have to apply
increases.
Thus it is good practice to organize the sets of rules you use optimally so
that irrelevant rules are never included.

Second, careless use of pattern matching can lead to wrong answers.
You should avoid using pattern matching to handle hidden algebraic
relationships that can go undetected by other programs.
As a simple example, a symbol such as ``J'' can easily be used to represent
the square root of \spad{-1} or some other important algebraic quantity.
Many algorithms branch on whether an expression is zero or not, then divide by
that expression if it is not.
If you fail to simplify an expression involving powers of
\spad{J} to \spad{-1,}
algorithms may incorrectly assume an expression is non-zero, take a wrong
branch, and produce a meaningless result.

Pattern matching should also not be used as a substitute for a domain.
In \Language{}, objects of one domain are transformed to objects of other
domains using well-defined \spadfun{coerce} operations.
Pattern matching should be used on objects that are all the same type.
Thus if your application can be handled by type \spadtype{Expression} in
\Language{} and you think you need pattern matching, consider this choice
carefully.
\exptypeindex{Expression}
You may well be better served by extending an existing domain
or by building a new domain of objects for your application.
