\chapter{Statements}
This section discusses the various possibilities to write statements and the
features offered by \setlx\ to steer the control flow in a program.
Besides the assignment statement, \setlx\ supports the following means to control the order of statement execution:
\begin{enumerate}
\item branching statements like \texttt{if-then-else}, \texttt{switch}, and \texttt{match},
\item the looping statements \texttt{for} and \texttt{while} together with \texttt{break} and
      \texttt{continue},
\item the \texttt{try-catch} statement to deal with exceptions,
\item the \texttt{backtrack} statement to support a limited form of backtracking.
\end{enumerate}

\section{Assignment Statements}
The most basic command is the assignment statement.  In contrast to the programming languages \texttt{C}
and \textsl{Java}, \setlx\ uses the operator ``\texttt{:=}'' to assign a value to a variable.  For example, the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{x := 2/3;}
\\[0.2cm]
binds the variable \texttt{x} to the fraction $\frac{2}{3}$.  \setlx\ supports simultaneous
assignments to multiple variables via lists.  For example, the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[x, y, z] := [1, 2, 3];}
\\[0.2cm]
simultaneously binds the variables \texttt{x} to $1$, \texttt{y} to $2$, and \texttt{z} to $3$.
This feature can be used to swap the values of two variables. For example,  the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[x, y] := [y, x];}
\\[0.2cm]
swaps the values of $x$ and $y$.  If we do not need to assign all the values of a list, we
can use the underscore ``\texttt{\_}'' as a so called \emph{anonymous variable}.  For example, if
the list \texttt{l} happens to have the value \texttt{[1,2,3]}, then the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[x, \_, z] := l;}
\\[0.2cm]
assigns the number \texttt{1} to the variable \texttt{x} and the variable \texttt{z} is
is set to \texttt{3}.

The assignment operator can be combined with any of the operators
``\texttt{+}'',
``\texttt{-}'',
``\texttt{*}'',
``\texttt{/}'',
``\texttt{\symbol{37}}'', and
``\texttt{\symbol{92}}''.
For example, the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{x += 1;}
\\[0.2cm]
increments the value of the variable \texttt{x} by one,  while the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{x *= 2;}
\\[0.2cm]
doubles the value of \texttt{x}.   Finally,
assignment statements can be chained.  For example, the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{a := b := 3;}
\\[0.2cm]
assigns the value \texttt{3} to both  \texttt{a} and \texttt{b}.

\section{Functions}
The code shown in figure
\ref{fig:primes-slim.stlx} on page \pageref{fig:primes-slim.stlx} shows a simple program
to compute \href{http://en.wikipedia.org/wiki/Prime_number}{\emph{prime numbers}}.
It defines two functions.  The function \texttt{factors} takes a
natural number \texttt{p} as its first argument and computes the set of all \emph{factors} of \texttt{p}.  Here, a number
\texttt{f} is a factor of \texttt{p} iff dividing \texttt{p} by \texttt{f} leaves no remainder, that is
the expression \texttt{p \symbol{37} f} is equal to \texttt{0}.
The second function \texttt{primes} takes a natural number \texttt{n} as its sole argument and computes the
set of all those numbers \texttt{p} less or equal to \texttt{n} that have only the trivial factors
\texttt{1} and \texttt{p}.  These numbers are, by definition, prime numbers.

Note that, as \setlx\ is a functional language, the functions that are defined by the
keyword \texttt{procedure} are assigned to variables.  As already mentioned in the previous chapter,
these functions can be used like any other values.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    factors := procedure(p) {
        return { f : f in { 1 .. p } | p % f == 0 };
    };
    primes := procedure(n) {
        return { p : p in { 2 .. n } | factors(p) == { 1, p } };
    };
    print(primes(100));
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A naive program to compute prime numbers.}
\label{fig:primes-slim.stlx}
\end{figure}

\noindent
A simplified grammar rule for the definition of a function can be given as follows:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{fctDef} \;\rightarrow\; \mathtt{VAR}\; \quoted{:=} \quoted{procedure} \quoted{(} \textsl{paramList}
 \quoted{)} \quoted{\{} \textsl{block} \quoted{\}} \quoted{;}$
\\[0.2cm]
The meaning of the symbols used in this grammar rule are as follows:
\begin{enumerate}
\item \texttt{VAR} identifies a variable.  This variable is bound to the definition of the function.
\item \textsl{paramList} is a list of the formal parameters of the function.  In
      \textsc{Ebnf}-notation the grammar rule for \textsl{paramList} is given as
      \\[0.2cm]
      \hspace*{1.3cm}
      $
      \begin{array}[t]{lcl}
        \textsl{paramList} & \rightarrow &
        \bigl(\textsl{paramSpec}\;\; (\squoted{,}\; \textsl{paramSpec})^* \;\; (\squoted{,} \;\; \squoted{*} \;\mathtt{VAR})?\bigr)? \\[0.1cm]
        & \mid & \squoted{*} \;\mathtt{VAR} \\
      \end{array}
      $
      \\[0.2cm]
      Therefore, a \textsl{paramList} is a possibly empty list of parameter specifications that are
      separated by a comma ``\texttt{,}''.  Optionally, as the last element, a parameter list can
      contain a variable that is prefixed with the operator ``\texttt{*}''.  This is used when
      a function takes a variable number of arguments and will be explained later.  Furthermore,
      a parameter list can consist of a single variable prefixed with the operator ``\texttt{*}''.

      A parameter specification is either just a variable,
      or it is a variable with the assignment of a default value,
      or it is a variable preceded by the token ``\texttt{rw}'':
      \\[0.2cm]
      \hspace*{1.3cm}
      $
      \begin{array}[b]{lcl}
        \textsl{paramSpec} & \rightarrow & \mathtt{VAR}                                \\[0.1cm]
                           & \mid        & \mathtt{VAR} \;\squoted{:=}\; \textsl{expr} \\[0.1cm]
                           & \mid        & \squoted{rw}\; \mathtt{VAR}
      \end{array}
      $
      \\[0.2cm]
      If the parameter is preceded by the keyword \texttt{rw}, then this parameter is a
      \emph{read-write parameter}, which means that the function can change the value of the
      variable given as argument and this change will then be visible
      outside of the function.  Therefore, parameters prefixed with
      the keyword \texttt{rw} have a
      \href{http://en.wikipedia.org/wiki/Call_by_name#Call_by_name}{\emph{call by name}}
      semantics.  Parameters not specified as read-write parameters have a strict
      \href{http://en.wikipedia.org/wiki/Call_by_value#Call_by_value}{\emph{call by value}}
      semantics, and hence changes to those parameters will not be
      visible outside the function.
\item \textsl{block} is a sequence of statements.
\end{enumerate}
Note that the definition of a function has to be terminated by the symbol ``\texttt{;}''.  The
reason is that the function is part of an assignment and every assignment is terminated with a semicolon.
Let us inspect a few examples of function definitions.  Figure \ref{fig:functions.stlx} shows
several functions definition.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    f := procedure(a, b, c) {
        return a + b + c;
    };
    print(f(1,2,3));

    g := procedure(a, b := 2, c := 3) {
        return a + b + c;
    };
    print(g);
    print(g(1));
    print(g(1, 3));
    print(g(1, 3, 5));

    h := procedure(a := 1, b := 2, c := 3, *rest) {
        s := a + b + c;
        for (x in rest) {
            s += x;
        }
        return s;
    };
    print(h);
    print(h(1));
    print(h(2, 4));
    print(h(2, 4, 6));
    print(h(1, 2, 3, 4, 5, 6));
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Functions with and without default arguments.}
\label{fig:functions.stlx}
\end{figure}

\begin{enumerate}
\item The function $f$ takes three arguments.  It adds these arguments and returns the resulting
      sum.  As none of the arguments has a default assigned, $f$ can only be called with three arguments.
\item The function $g$ also takes three arguments, but this time both the second and the third
      argument have a default value.  Therefore, $g$ can be called with either one argument, two
      arguments, or three arguments.
\item The function $h$ takes four arguments.  The first three arguments are regular arguments and
      each of them has a default value.  The remaining argument \texttt{rest} is prefixed with a
      \squoted{*}.  Therefore, this argument is a list that collects all arguments beyond the third
      argument.  Hence, the function $h$ can be called with any number of arguments.  For example,
      if we call $h$ as
      \\[0.2cm]
      \hspace*{1.3cm}
      \texttt{h(1, 2, 3, 4, 5, 6)}
      \\[0.2cm]
      then \texttt{a} is set to \texttt{1}, \texttt{b} is set to \texttt{2}, \texttt{c} is set to
      \texttt{3}, and \texttt{rest} is set to the list \texttt{[4, 5, 6]}.  Later, when we discuss
      \emph{closures} we will see that having an argument prefixed with the \squoted{*}-operator
      enables us to build so called
      \href{http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators}{\emph{decorator functions}}.
      This is a very powerful idea that has been borrowed from the programming language \textsl{Python}.
\end{enumerate}
There is a variant syntax for defining a function which is appropriate if the definition of the
function is just a single expression.  For example, the function mapping $x$ to the square
$x*x$ can be defined as
\\[0.2cm]
\hspace*{1.3cm}
\texttt{f := x |-> x * x;}
\\[0.2cm]
A definition of this form is called a \emph{lambda definition}.  The example given above is
equivalent to defining \texttt{f} as follows:
\\[0.2cm]
\hspace*{1.3cm}
\texttt{f := procedure(x) \{ return x * x; \};}
\\[0.2cm]
We see that using a lambda definition is shorter as we do not have to use the keywords ``\texttt{procedure}''
and ``\texttt{return}''.
If the function takes more than one arguments and we want to use a lambda definition, the argument
list has to be enclosed in square brackets.  For example, the function \texttt{hyp} that computes
the length of the hypotenuse of a rectangular triangle can be defined as follows:
\\[0.2cm]
\hspace*{1.3cm}
\texttt{hyp := [x, y] |-> sqrt(x*x + y*y);}
\\[0.2cm]
The syntax for a lambda definition is given by the follwing grammar rule:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{fctDef} \;\rightarrow\; \mathtt{VAR} \quoted{:=} \textsl{lambdaParams} \quoted{|->} \textsl{expr} \quoted{;}$
\\[0.2cm]
Here, \textsl{lambdaParams} is either just a single parameter or a list of parameters, where the
parameters are enclosed in square brackets and are separated by commas, while
\textsl{expr} denotes an expression.

Lambda definitions are handy if we don't bother to give a name to a function.
For example, the code in figure \ref{fig:lambda.stlx} defines a function map.  This function takes
two arguments: The first argument $l$ is a list and the second argument $f$ is a function that is to
be applied to all arguments of this list.  In line 4, the function map is called with a function
that squares its argument.  Therefore, the assignment in line 4 computes the list of the first 10
square numbers.  Note that we did not had to name the function that did the squaring.  Instead, we
have  used a lambda definition.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    map := procedure(l, f) {
        return [ f(x) : x in l ];
    };
    t := map([1 .. 10], x |-> x * x);
\end{Verbatim}
\vspace*{-0.3cm}
\caption{An example of a lambda definition in use.}
\label{fig:lambda.stlx}
\end{figure}

\noindent
Of course, it would be much easier to build the list of the first 10 squares using the following statement:
\\[0.2cm]
\hspace*{1.3cm}
\texttt{t := [x*x : $\hspace*{-0.3cm}$x in [1..10]];}

\subsection{Calling a Procedure}
There are two ways to call a procedure.  If a procedure has $n$ arguments, then one way to call $f$ is
to write
\\[0.2cm]
\hspace*{1.3cm}
$f(a_1, \cdots, a_n)$
\\[0.2cm]
where $a_1$, $\cdots$, $a_n$ are the arguments.  However, there is another way to call a procedure:
If $l$ is a list of the form
\\[0.2cm]
\hspace*{1.3cm}
$l = [a_1, \cdots, a_n]$,
\\[0.2cm]
then the expression
\\[0.2cm]
\hspace*{1.3cm}
$f(\mathtt{*}\,l)$
\\[0.2cm]
is equivalent to the expression
\\[0.2cm]
\hspace*{1.3cm}
$f(a_1, \cdots, a_n)$.
\\[0.2cm]
Later, when we discuss functional programming in Chapter \ref{chapter:closures}, we will see that
this can be very convenient.  The reason is that this technique permits us to write second order functions
that take procedures as inputs and that then modify these procedures.  Even though we will not know the number
of parameters that the procedures given as input take, we will still be able to modify the procedure
given as argument.

\subsection{Memoization}
The function $\textsl{fib}: \mathbb{N} \rightarrow
\mathbb{N}$ computing the
\href{http://en.wikipedia.org/wiki/Fibonacci_numbers}{\emph{Fibonacci numbers}}
is defined recursively by the following set of recurrence equations:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{fib}(0) = 0$, \quad
$\textsl{fib}(1) = 1$, \quad and \quad
$\textsl{fib}(n+2) = \textsl{fib}(n+1) + \textsl{fib}(n)$.
\\[0.2cm]
These equations are readily implemented as shown in Figure \ref{fig:fibonacci.stlx}.
However, this implementation has a performance problem which can be easily seen when tracing the
computation of $\textsl{fib}(4)$.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    fibonacci := procedure(n) {
        if (n in [0,1]) {
            return n;
        }
        return fibonacci(n-1) + fibonacci(n-2);
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A naive implementation of the Fibonacci function.}
\label{fig:fibonacci.stlx}
\end{figure}

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    fibonacci := procedure(n) {
        if (n in [0,1]) {
            result := n;
        } else {
            result := fibonacci(n-1) + fibonacci(n-2);
        }
        print("fibonacci($n$) = $result$");
        return result;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Tracing the computation of the Fibonacci function.}
\label{fig:fibonacci-trace.stlx}
\end{figure}

In order to trace the computation, we change the program as shown in Figure
\ref{fig:fibonacci-trace.stlx}.
If we evaluate the expression \texttt{fibonacci(4)}, we get the output shown in Figure
\ref{fig:fibonacci.trace}.  This output shows that the expression \texttt{fibonacci(2)} is
evaluated twice.  The reason is that the value of \texttt{fibonacci(2)} is needed in the equation
\\[0.2cm]
\hspace*{1.3cm}
\texttt{fibonacci(4)} := \texttt{fibonacci(3)} + \texttt{fibonacci(2)}
\\[0.2cm]
to compute \texttt{fibonacci(4)}, but then in order to compute \texttt{fibonacci(3)}, we
have to compute \texttt{fibonacci(2)} again.  The trace also shows that the problem gets
aggravated the longer the computation runs.  For example, the value of
\texttt{fibonacci(1)} has to be computed three times.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = none,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    => fibonacci(4);

    fibonacci(1) = 1
    fibonacci(0) = 0
    fibonacci(2) = 1
    fibonacci(1) = 1
    fibonacci(3) = 2
    fibonacci(1) = 1
    fibonacci(0) = 0
    fibonacci(2) = 1
    fibonacci(4) = 3
    ~< Result: 3 >~

    =>
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Output of evaluating the expression \texttt{fibonacci(4)}.}
\label{fig:fibonacci.trace}
\end{figure}

In order to have a more efficient computation, it is necessary to memorize the values of
the function \texttt{fibonacci} once they are computed.  Fortunately, \setlx\ offers
\emph{cached functions}.  If a function $f$ is declared as a cached function, then every
time the function $f$ is evaluated for an argument $x$, the computed value $f(x)$ is
memorized and stored in a table.  The next time the function $f$ is used to compute
$f(x)$, the interpreter first checks whether the value of $f(x)$ has already been
computed.  In this case, instead of computing $f(x)$ again,  the function returns the
value stored in the table.  This technique is known as
\href{http://en.wikipedia.org/wiki/Memoization}{\emph{memoization}}.
Memoization is directly supported in \setlx\ via cached functions.
Figure
\ref{fig:fibonacci-cached.stlx} shows an implementation of the Fibonacci function as a
cached function.  If we compare the program in Figure
\ref{fig:fibonacci-cached.stlx} with our first attempt shown in Figure
\ref{fig:fibonacci.stlx}, then we see that the only difference is that instead of the
keyword ``\texttt{procedure}'' we have used the keyword ``\texttt{cachedProcedure}'' instead.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    fibonacci := cachedProcedure(n) {
        if (n in [0,1]) {
            return n;
        }
        return fibonacci(n-1) + fibonacci(n-2);
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A cached implementation of the Fibonacci function.}
\label{fig:fibonacci-cached.stlx}
\end{figure}

\vspace*{0.3cm}

\noindent
\textbf{Warning}:  A function should only be declared as a \texttt{cachedProcedure} if it is
guaranteed to always produce the same result when called with the same argument.
Therefore, a function should not be declared as a \texttt{cachedProcedure} if it does one
of the following things:
\begin{enumerate}
\item The function makes use of random numbers.
\item The function reads input either from a file or from the command line.
\end{enumerate}
To further support cached procedures,  \setlx\ provides the function \texttt{cacheStats},
which is called with a single argument that must be a cached function.  For example, if
we define the function \texttt{fibonacci} as shown in Figure
\ref{fig:fibonacci-cached.stlx} and evaluate the expression \texttt{fibonacci(100)}, then
the expression \texttt{cacheStats(fib)} gives the following result:
\\[0.2cm]
\hspace*{1.3cm}
\texttt{\symbol{126}< Result: {["cache hits", 98], ["cached items", 101]} >\symbol{126}}
\\[0.2cm]
This tells us that the cache contains 101 different argument/value pairs, as the cache
now stores the values
\\[0.2cm]
\hspace*{1.3cm}
\texttt{fibonacci($n$)} \quad for all $n \in \{0,\cdots,100\}$.
\\[0.2cm]
Furthermore, we see that 98 of these 101 argument/value pairs have
been used more than once in order to
compute the values of \texttt{fibonacci} for different arguments.

In order to prevent memory leaks, \setlx\ provides the function \texttt{clearCache}.  This
function is invoked with one argument which must be a cached function.  Writing
\\[0.2cm]
\hspace*{1.3cm}
\texttt{clearCache(f)}
\\[0.2cm]
clears the cache for the function $f$, that is all argument/value pairs stored for $f$
will be removed from the cache.

\section{Branching Statements}
Like most modern languages, \setlx\ supports \texttt{if-then-else} statements and
\texttt{switch} statements.  A generalization of \texttt{switch} statements, the so called
\texttt{match} statements, are also supported. We begin our discussion with
\texttt{if-then-else} statements.

\subsection{\texttt{if-then-else} Statements}
In order to support branching, \setlx\ supports \texttt{if-then-else} statements.  The syntax is
similar to the corresponding syntax in the programming language \texttt{C}.  However, braces are
required.  For example, figure \ref{fig:toBin.stlx} on page \pageref{fig:toBin.stlx} shows a
recursive function that computes the binary representation of a
natural number.  Here, the function \texttt{str} is a predefined function that converts its argument
into a string.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    toBin := procedure(n) {
        if (n < 2) {
            return str(n);
        }
        [r, n] := [n % 2, n \ 2];
        return toBin(n) + str(r);
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function to compute the binary representation of a natural number.}
\label{fig:toBin.stlx}
\end{figure}

As in the programming languages \texttt{C} and \textsl{Java}, the
\texttt{else} clause is optional.

\subsection{\texttt{switch} Statements}
Figure \ref{fig:sort3.stlx} shows a function that takes a list of length 3.  The function sorts
the resulting list.  In effect, the function \texttt{sort3} implements a
\href{http://en.wikipedia.org/wiki/Decision_tree}{\emph{decision tree}}.
This example shows how \texttt{if-then-else} statements can be cascaded.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    sort3 := procedure(l) {
        [ x, y, z ] := l;
        if (x <= y) {
            if (y <= z) {
                return [ x, y, z ];
            } else if (x <= z) {
                return [ x, z, y ];
            } else {
                return [ z, x, y ];
            }
        } else if (z <= y) {
            return [z, y, x];
        } else if (x <= z) {
            return [ y, x, z ];
        } else {
            return [ y, z, x ];
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function to sort a list of three elements.}
\label{fig:sort3.stlx}
\end{figure}

Figure \ref{fig:sort3switch.stlx} on page \pageref{fig:sort3switch.stlx}
shows an equivalent program that uses a \texttt{switch} statement instead of an
\texttt{if-then-else} statement to sort a list of three elements.  Note that this implementation is
much easier to understand than the program using \texttt{if-then-else} statements.
\footnote{
However, we should also mention that the version using \texttt{switch} is less efficient than the
version using \texttt{if-then-else}.  The reason is that some of the tests are redundant.  This is most obvious for the
last case in line 9 since at the time when control arrives in line 9 it is already known that $z$ must be
less or equal than $y$ and that, furthermore, $y$ must be less or equal than $x$, since all other
cases have already been covered.}

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    sort3 := procedure(l) {
        [ x, y, z ] := l;
        switch {
            case x <= y && y <= z: return [ x, y, z ];
            case x <= z && z <= y: return [ x, z, y ];
            case y <= x && x <= z: return [ y, x, z ];
            case y <= z && z <= x: return [ y, z, x ];
            case z <= x && x <= y: return [ z, x, y ];
            case z <= y && y <= x: return [ z, y, x ];
            default: print("Impossible error occurred!");
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Sorting a list of 3 elements using a \texttt{switch} statement.}
\label{fig:sort3switch.stlx}
\end{figure}
\noindent
The grammar rule describing the syntax of \texttt{switch} statements is as follows:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{stmnt} \;\rightarrow\; \quoted{switch} \quoted{\{} \textsl{caseList} \quoted{\}}$
\\[0.2cm]
where the syntactical variable \textsl{caseList} is defined via the rule:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{caseList} \;\rightarrow\; (\squoted{case}\; \textsl{boolExpr} \quoted{:} \textsl{block})^*
 (\squoted{default} \quoted{:} \textsl{block})?$
\\[0.2cm]
Here, \textsl{boolExpr} is a Boolean expression and \textsl{block} represents a sequence of statements.

In contrast to the programming languages \texttt{C} and \textsl{Java}, the \texttt{switch}
statement in \setlx\ doesn't have a fall through.  Therefore, we don't need a \texttt{break} statement in the
block of statements following the Boolean expression.
There are two other important distinction between the \texttt{switch} statement in
\textsl{Java} and the \texttt{switch} statement in \setlx:
\begin{enumerate}
\item In \textsc{SetlX}, the keyword switch is not followed by a value.
\item The expressions following the keyword \texttt{case} have to produce Boolean values when evaluated.
\end{enumerate}
There is a another type of a branching statement that is much more powerful than the \texttt{switch}
statement.  This branching statement is the \emph{matching statement} and is discussed in the next section.

\section{Matching}
The most powerful branching construct is \emph{matching}.  Although the syntax for the
matching statement is always the same, there are really four different variants of matching.  The
reason is that there four different data types that support matching.  Matching has been implemented for
 \emph{strings}, \emph{lists}, \emph{sets}, and \emph{terms}.  We discuss \emph{string matching} first.

\subsection{String Matching}
Many algorithms that deal with a given string $s$ have to deal with two cases:  Either the string $s$ is
empty or it is nonempty and in that case has to be split into its first character $c$ and the
remaining characters $r$, that is we have
\\[0.2cm]
\hspace*{1.3cm}
$s = c + r$ \quad where $c = s[1]$ and $r = s[2..]$.
\\[0.2cm]
In order to facilitate algorithms that perform this kind of case distinction, \setlx\ provides the
\texttt{match} statement.  Consider the function\footnote{
There is also a predefined version of the function \texttt{reverse} which does exactly the
same thing as the function in Figure \ref{fig:reverse.stlx}.  However, once we define the
function \texttt{reverse} as in Figure \ref{fig:reverse.stlx}, the predefined function
gets overwritten and is no longer accessible.}
 \texttt{reverse} shown in Figure \ref{fig:reverse.stlx}.
This function reverses its input argument, so the expression
\\[0.2cm]
\hspace*{1.3cm}
\texttt{reverse("abc")}
\\[0.2cm]
yields the result \texttt{"cba"}.  In order to reverse a string $s$, the function has to deal with two
cases:
\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    reverse := procedure(s) {
        match (s) {
            case []   : return s;
            case [c|r]: return reverse(r) + c;
            default   : abort("type error in reverse($s$)");
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function that reverses a string.}
\label{fig:reverse.stlx}
\end{figure}
\begin{enumerate}
\item The string $s$ is empty.  In this case, we can just return the string $s$ as it is.
      This case is dealt with in line 3.  There, we have used the pattern ``\texttt{[]}'' to match
      the empty string.  Instead, we could have used the empty string itself.  Using the pattern
      ``\texttt{[]}'' will prove beneficial when dealing with lists because it turns out that the
      function
      \texttt{reverse} as given in Figure \ref{fig:reverse.stlx} can also be used to reverse a list.
\item If the string $s$ is not empty, then it can be split up into a first character $c$ and the remaining
      characters $r$.  In this case, we reverse the string $r$ and append the character $c$ to the end of
      this string.  This case is dealt with in line 4.
\end{enumerate}
The \texttt{match} statement in the function \texttt{reverse}  has a default case in line 5 to deal with
those cases where $s$ is neither a string nor a list.  In those cases, the function is aborted with
an error message.

The previous example shows that the syntax for the match statement  is similar to the syntax for the switch
statement.  The main difference is that the keyword is now ``\texttt{match}'' instead of
``\texttt{switch}'' and that the cases no longer contain Boolean values but instead contain
\emph{patterns} that can be used
\begin{itemize}
\item to check whether a string has a given form and
\item to extract certain components (like the first character or everything but the first character).
\end{itemize}
Basically, for strings the function \texttt{reverse} given above is interpreted as if it
had been written in the way shown in Figure \ref{fig:reverse-long.stlx} on page \pageref{fig:reverse-long.stlx}.
This example shows that the use of the \texttt{match} statement can make programs more compact while
increasing their legibility.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    reverse := procedure(s) {
        if (s == "") {
            return s;
        } else if (isString(s)) {
            c := s[1];
            r := s[2..];
            return reverse(r) + c;
        } else {
            abort("type error in reverse($s$)");
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function to reverse a string that does not use matching.}
\label{fig:reverse-long.stlx}
\end{figure}

To explore string matching further, consider a function \texttt{reversePairs} that interchanges all pairs
of characters, so for example we have
\\[0.2cm]
\hspace*{1.3cm}
\texttt{reversePairs("abcd") = "badc"} \quad and \quad
\texttt{reversePairs("abcde") = "badce"}.
\\[0.2cm]
This function can be implemented as shown in Figure \ref{fig:reverse-pairs.stlx} on page
\pageref{fig:reverse-pairs.stlx}.  Notice that we can match the empty string with the pattern
``\texttt{[]}'' in line 3.  The pattern ``\texttt{[c]}'' matches a string consisting of a single
character $c$.  In line 5 the pattern \texttt{[a,b|r]} extracts the first two
characters from the string $s$ and binds them to the variables $a$ and $b$.  The rest of the string is
bound to $r$.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    reversePairs := procedure(s) {
        match (s) {
            case []     : return s;
            case [c]    : return c;
            case [a,b|r]: return b + a + reversePairs(r);

        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function to exchange pairs of characters.}
\label{fig:reverse-pairs.stlx}
\end{figure}

\subsubsection{String Decomposition via Assignment}
Assignment can be used to decompose a string into its constituent characters.  For
example, if $s$ is defined as
\\[0.2cm]
\hspace*{1.3cm}
\texttt{s := }\verb|"abc";|
\\[0.2cm]
then after the assignment
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[u, v, w] := s;}
\\[0.2cm]
the variables $u$, $v$, and $w$ have the values
\\[0.2cm]
\hspace*{1.3cm}
\texttt{$u$ =} \verb|"a"|, \quad
\texttt{$v$ =} \verb|"b"|, \quad and \quad
\texttt{$w$ =} \verb|"c"|.
\\[0.2cm]
Therefore, for strings, list assignment can be seen as a lightweight alternative to matching.
However, string decomposition via assignment only works if the list on the left hand side has the
same length as the string.

\subsection{List Matching}
As strings can be regarded as lists of characters, the matching of lists is very similar to the matching of
strings.  The function \texttt{reverse} shown in Figure \ref{fig:reverse.stlx} on page
\pageref{fig:reverse.stlx} can also be used to reverse a list.
 If the argument $s$ of \texttt{reverse} is a list instead of a string, we match the empty list with
 the pattern ``\texttt{[]}'', while the pattern ``\texttt{[c|r]}'' matches a non-empty list:
The variable $c$  matches the first element  of the list, while the variable $r$ matches the remaining elements.

List assignment is another way to decompose a list that is akin to matching.  If the list
$l$ is defined via
\\[0.2cm]
\hspace*{1.3cm}
\texttt{l := [1..3];}
\\[0.2cm]
then after the assignment
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[x, y, z] := l;}
\\[0.2cm]
the variables $x$, $y$, and $y$ have the values $x = 1$, $y = 2$, and $z = 3$.  Of course, this only
works if the number of variables on the left hand side of the assignment is equal to the length of
the list on the right hand side.

\subsection{Set Matching}
As sets are quite similar to lists, the matching of sets is closely related to the matching of
lists.  Figure \ref{fig:set-sort.stlx}  shows the function \texttt{setSort} that takes a
set of numbers as its  argument and returns a sorted list containing the numbers appearing
in the set.  In the \texttt{match} statement, we match the empty set with the pattern
``\texttt{\{\}}'', while the pattern ``\texttt{\{x|r\}}'' matches a non-empty set:
The variable $x$ matches the first element of the set, while the variable $r$ matches the
set of all the remaining elements.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    setSort := procedure(s) {
        match (s) {
            case {}   : return [];
            case {x|r}: return [x] + setSort(r);
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function to sort a set of numbers.}
\label{fig:set-sort.stlx}
\end{figure}

Of course, in \setlx\ sorting a set into a list is trivial, as a
set is represented as an ordered binary tree and therefore is already sorted.
For this reason, we could also transform a set $s$ into a sorted list by using the expression
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[] + s}.
\\[0.2cm]
The reason is that in this case the set \texttt{s} is first transformed into a list and this list is then appended
to the empty list.  In general, for a list $l$ and a set $s$ the expression \texttt{$l$ + $s$} creates a new
list containing all elements of $l$.  Then, the elements of $s$ are appended to this
list.  Similarly, for a set $s$ and a list $l$ the expression \texttt{$s$ + $l$} creates a new set
containing the elements of the set $s$ and the list $l$.

\subsection{Term Matching}
The most elaborate form of matching is the matching of terms.  This kind of matching is similar to
the kind of matching provided in the programming languages
\href{http://en.wikipedia.org/wiki/Prolog}{\textsl{Prolog}} and
\href{http://en.wikipedia.org/wiki/ML_(programming_language)}{\textsc{Ml}} \cite{milner:90}.
Figure \ref{fig:binary-tree.stlx} shows an implementation of the function \texttt{insert} to insert
a number into an ordered binary tree.  This implementation uses
term matching instead of the functions ``\texttt{fct}'' and ``\texttt{args}'' that had been used in
the previous implementation shown in Figure \ref{fig:binary-tree-no-matching.stlx} on page
\pageref{fig:binary-tree-no-matching.stlx}.  In line 3 of Figure \ref{fig:binary-tree.stlx}, the
\texttt{case} statement checks whether the term $m$ is identical to the empty binary tree, which is
represented by the term \texttt{@Nil()}.  This is more straightforward than
testing that the functor of $m$ is ``\texttt{Nil}'', as it was done in line 3 of Figure
\ref{fig:binary-tree-no-matching.stlx}.  However, the real benefit of matching shows in line 5 of
Figure \ref{fig:binary-tree.stlx} since the case statement in this line does not only check whether
the functor of the term $m$ is ``\texttt{Node}'' but also assigns the subterms of $m$ to the
variables \texttt{k2}, \texttt{l}, and \texttt{r}, respectively.  Compare this with line 5 and line 6 of Figure
\ref{fig:binary-tree-no-matching.stlx} where we had to use a separate statement in line 6 to extract
the arguments of the term $m$.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    insert := procedure(m, k1) {
        match (m) {
            case @Nil() :
                 return @Node(k1, @Nil(), @Nil());
            case @Node(k2, l, r) | k1 == k2:
                 return @Node(k1, l, r);
            case @Node(k2, l, r) | compare(k1, k2) < 0:
                 return @Node(k2, insert(l, k1), r);
            case @Node(k2, l, r):
                 return @Node(k2, l, insert(r, k1));
            default: abort("Error in insert($m$, $k1$)");
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Inserting an element into a binary tree using matching.}
\label{fig:binary-tree.stlx}
\end{figure}
\noindent
In general, a \texttt{case} statement that is part of a \texttt{match} statement has the form
\\[0.2cm]
\hspace*{1.3cm}
\texttt{case }\textsl{pattern}\texttt{ | }\textsl{condition}\texttt{: }\textsl{stmnt}
\\[0.2cm]
Here, \textsl{pattern} is a term, \textsl{condition} is a Boolean condition, and \textsl{stmnt} is a
statement.  When this \texttt{case} statement is processed, the term $t$ in the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{match ($t$) \{ $\cdots$ \}}
\\[0.2cm]
is \emph{matched} against  \textsl{pattern}.  This will be explained in more detail in the next
paragraph.  If this \emph{matching} succeeds, the variables in \textsl{pattern} are
bound to the corresponding subterms in $t$.  Next, it is checked whether \textsl{condition} is true.
If it is, the \emph{match} succeeds and the statement \textsl{stmnt} is executed.  Otherwise, the statement
is skipped and control proceeds to the next case.

Let us now explain the details how a term $t$ is matched against a pattern $p$.  The pattern $p$ is either
a variable or it is a term.  If $p$ is a variable, the match succeeds and the term $t$ is assigned
to the variable $p$, i.e.~the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{$p$ := $t$;}
\\[0.2cm]
is executed.  If $p$ is a term, then $t$ and $p$ can be written as
\\[0.2cm]
\hspace*{1.3cm}
$t = f(t_1, \cdots, t_n)$ \quad and \quad $p = g(p_1, \cdots, p_m)$.
\\[0.2cm]
Then, matching $t$ against $p$ proceeds as follows:
\begin{enumerate}
\item If the function symbols $f$ and $g$ are different, the match fails.
\item If the numbers $n$ and $m$ are different, the match fails.
\item If the match hasn't failed yet, the subterms $t_1$, $\cdots$, $t_n$ are matched recursively against
      the patterns $p_1$, $\cdots$, $p_n$.  The match only succeeds if all of the
      recursive matches succeed.  If it does not succeed, then the assignments that have been
      made during the recursive matching are undone.
\end{enumerate}

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    loadLibrary("termUtilities");

    diff := procedure(t, x) {
        match (t) {
            case t1 + t2:
                 return diff(t1, x) + diff(t2, x);
            case t1 - t2:
                 return diff(t1, x) - diff(t2, x);
            case t1 * t2:
                 return diff(t1, x) * t2 + t1 * diff(t2, x);
            case t1 / t2:
                 return ( diff(t1, x) * t2 - t1 * diff(t2, x) ) / (t2 * t2);
            case f ** 0:
                 return 0;
            case f ** n | isNumber(n):
                 return n * diff(f, x) * f ** (n-1);
            case f ** g:
                 return diff(@exp(g * @ln(f)), x);
            case @ln(a):
                 return diff(a, x) / a;
            case @exp(a):
                 return diff(a, x) * @exp(a);
            case var | var == x :
                 return 1;
            case var | isVariable(var) :
                 return 0;
            case t | isNumber(t):
                 return 0;
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A function to perform symbolic differentiation.}
\label{fig:diff.stlx}
\end{figure}

\noindent
The following more complex example will serve to elucidate matching further.  The function
\texttt{diff} shown in Figure \ref{fig:diff.stlx} on page \pageref{fig:diff.stlx} is supposed to be
called with two arguments:
\begin{enumerate}
\item The first argument $t$ is a term that is interpreted as an arithmetic expression.
\item The second argument $x$ is a term that is interpreted as  the name of a variable.
\end{enumerate}
The function \texttt{diff} interprets the term $t$ as a mathematical function and takes the
\href{https://en.wikipedia.org/wiki/Derivative}{\emph{derivative}} of this function with respect to the
variable $x$.  For example, in order to compute the derivative of the function
\\[0.2cm]
\hspace*{1.3cm}
$x \mapsto x^x$
\\[0.2cm]
we can invoke \texttt{diff} as follows:
\\[0.2cm]
\hspace*{1.3cm}
\texttt{diff(parseTerm("x ** x"), parseTerm("x"));}
\\[0.2cm]
Here the function \texttt{parseTerm} transforms the string ``\texttt{x ** x}'' into a term.
The form of this term will be discussed in more detail later.  This function is a part of the
package \texttt{termUtilities}.  Therefore, to use this function we have to load the corresponding
library first using the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{loadLibrary("termUtilities");}
\\[0.2cm]
For the moment, let us focus on the
\texttt{match} statement in Figure
\ref{fig:diff.stlx}.  Consider line 5: If the term that is to be differentiated has the form
\texttt{t1 + t2}, then both \texttt{t1} and \texttt{t2} have to be differentiated separately and the
resulting terms have to be added.  For a more interesting example, consider line 9.  This line
implements the product rule:
\\[0.2cm]
\hspace*{1.3cm}
$\displaystyle\frac{\mathrm{d}\;}{\mathrm{d}x} \bigl(t_1 \cdot t_2\bigr) =
 \frac{\mathrm{d}\, t_1}{\mathrm{d}x} \cdot t_2 + t_1 \cdot \frac{\mathrm{d}\,t_2}{\mathrm{d}x}
$.
\\[0.2cm]
Note how the pattern
\\[0.2cm]
\hspace*{1.3cm}
\texttt{t1 * t2}
\\[0.2cm]
in line 9 extracts the two factors $t_1$ and $t_2$ from a term that happens to be a product.
Further, note that in line 18, 19, 21, and 22 we had to prefix the function symbols ``\texttt{exp}'' and
``\texttt{ln}'' with the character ``\texttt{\symbol{64}}'' in order to convert these function
symbols into functors.

Note that the example makes extensive use of the fact that terms are \emph{viral} when used with
the arithmetic operators
``\texttt{+}'', ``\texttt{-}'', ``\texttt{*}'', ``\texttt{/}'', ``\texttt{\symbol{92}}'', and
``\texttt{\%}'':
If one operand of these operators is a term, the operator automatically yields a term.
For example, if \texttt{x} is a term, then
\\[0.2cm]
\hspace*{1.3cm}
\texttt{x + 2}
\\[0.2cm]
is also a term.
Note also that terms are not viral inside function symbols like ``\texttt{exp}''.  Therefore, this
function symbol has to be prefixed by the operator ``\texttt{\symbol{64}}'' to turn it
into a functor.

Line 27 shows how a condition can be attached to a pattern:  The pattern
\\[0.2cm]
\hspace*{1.3cm}
\texttt{case t:}
\\[0.2cm]
would match anything.  However, we want to match only numbers here.  Therefore, we have attached
the condition \texttt{isNumber(t)} via the condition operator ``\texttt{|}'' to this pattern and
hence have written
\\[0.2cm]
\hspace*{1.3cm}
\texttt{case t | isNumber(t):}
\\[0.2cm]
in order to ensure that \texttt{t} is indeed a number.

\subsection{Term Decomposition via List Assignment}
As a syntactical convenience, terms can be decomposed via list assignment.  For example, after the assignment
\\[0.2cm]
\hspace*{1.3cm}
\texttt{[x,y,z] := @f(1, @g(2), \{2,3\});}
\\[0.2cm]
the variables $x$, $y$, and $z$ have the values
\\[0.2cm]
\hspace*{1.3cm}
$x = 1$, \quad $y = \mathtt{@g(2)}$, \quad and \quad $z = \{2,3\}$.
\\[0.2cm]
Of course, the function \texttt{args} achieves a similar effect.  We have that
\\[0.2cm]
\hspace*{1.3cm}
\texttt{args(@f(1, @g(2), \{2,3\})) = [1, @g(2), \{2, 3\}]}.

\section{Loops}
\setlx\ offers three different kinds of loops: \texttt{for} loops, \texttt{while} loops, and
\texttt{do-while} loops.  The \texttt{while} loops are the most general loops.  Therefore, we discuss them first.

\subsection{\texttt{while} Loops}
The syntax of \texttt{while} loops in \setlx\ is similar to the syntax of
\texttt{while} loops in the programming language \texttt{C}.  The only difference is that in \setlx,
the body of a \texttt{while} loop has to be enclosed in curly braces even if it only consists of a single line.
To demonstrate a \texttt{while} loop,
let us implement a function testing the
\href{http://en.wikipedia.org/wiki/Collatz_conjecture}{\emph{Collatz conjecture}}:  Define the function
\\[0.2cm]
\hspace*{1.3cm}
$f: \mathbb{N} \rightarrow \mathbb{N}$
\\[0.2cm]
recursively as follows:
\begin{enumerate}
\item $f(n) := 1$ \hspace*{2.13cm} if $n = 1$,
\item $f(n) := \left\{
       \begin{array}[c]{ll}
         f(n/2)           & \mbox{if $n \,\texttt{\symbol{37}}\, 2 = 0$;} \\[0.2cm]
         f(3 \cdot n + 1) & \mbox{otherwise.}
       \end{array}
       \right.
      $
\end{enumerate}
The Collatz conjecture claims that $f(n) = 1$  for all $n \in \mathbb{N}$.
If we assume the Collatz conjecture is true, then $f$ is well-defined.
Otherwise, if the Collatz conjecture is not true, for certain values of $n$ the function $f(n)$ is undefined.
Figure \ref{fig:ulam.stlx} shows an implementation of the function $f$ in \setlx.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    f := procedure(n) {
        if (n == 1) {
            return 1;
        }
        while (n != 1) {
            if (n % 2 == 0) {
                n /= 2;
            } else {
                n := 3 * n + 1;
            }
        }
        return n;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A program to test the Collatz conjecture.}
\label{fig:ulam.stlx}
\end{figure}

The function $f$ is implemented via a \texttt{while} loop.  This loop runs as long as $n$
is different from the number one.  Therefore, if the Collatz conjecture is true, the \texttt{while}
loop will eventually terminate for all values of $n$.

The syntax of a \texttt{while} loop is given by the following
grammar rule:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{statement} \;\rightarrow\; \quoted{while} \quoted{(} \textsl{boolExpr} \quoted{)}
 \quoted{\{}  \textsl{block} \quoted{\}}
$.
\\[0.2cm]
Here, \textsl{boolExpr} is a Boolean expression returning either \texttt{true} or
\texttt{false}.  This condition is called the \emph{guard} of the \texttt{while} loop.
The syntactical variable \textsl{block} denotes a sequence of statements.  Note that,
in contrast to the programming languages \texttt{C} and \textsl{Java}, the
block of statements always has to be enclosed in curly braces, even if it consists only of a
single statement.  The semantics of a \texttt{while} loop is the same as in \texttt{C}:
The loop is executed as long as the guard is true.  In order to abort an iteration
prematurely, \setlx\ provides the command \texttt{continue}.  This command aborts the
current iteration of the loop and proceeds with the next iteration.  In order to abort the
loop itself, the command \texttt{break} can be used.  Figure \ref{fig:break-and-continue.stlx} shows
a function that uses both a \texttt{break} statement and a \texttt{continue} statement.  This
function will print the number 1.  Then, when $n$ is incremented to 2, the \texttt{continue}
statement in line 6 is executed so that the number 2 is not printed.  In the next iteration of the
loop, the number $n$ is incremented to 3 and printed.  In the final iteration of the loop, $n$ is
incremented to 4 and the \texttt{break} statement in line 9 terminates the loop.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    testBreakAndContinue := procedure() {
        n := 0;
        while (n < 10) {
            n := n + 1;
            if (n == 2) { continue; }
            if (n == 4) { break;    }
            print(n);
        }
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{This function demonstrates the semantics of \texttt{break} and \texttt{continue}.}
\label{fig:break-and-continue.stlx}
\end{figure}

\subsection{\texttt{do-while} Loops}
Similar to the language \texttt{C}, \setlx\ supports the \texttt{do-while} loop.  The difference
between a \texttt{do-while} loop and an ordinary \texttt{while} loop is that
sometimes the body of a loop needs to execute at least once, regardless of the condition
controlling the loop.  For example, imagine you want to implement the following guessing game:  The computer
generates a random natural number between 0 and 100 inclusive and the player has to guess it.  Every time the
player enters some number, the computer informs the player whether the number was too big, too
small, or whether the player has correctly guessed the secret number.  In this guessing game, the
player always has to enter at least one number.  Therefore, the most natural way to implement this
game is to use a \texttt{do-while} loop.  Figure \ref{fig:guessNumber.stlx} shows an implementation
of the guessing game.  The implementation works as follows:

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    guessNumber := procedure() {
        secret := rnd(100);
        count  := 0;
        do {
            count += 1;
            x := read("input a number between 0 and 100 inclusively: ");
            if (x < secret) {
                print("sorry, too small");
            } else if (x > secret) {
                print("sorry, too big");
            } else {
                print("correct!");
            }
        } while (x != secret);
        print("number of guesses: $count$");
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Implementing the guessing game in \setlx.}
\label{fig:guessNumber.stlx}
\end{figure}

\begin{enumerate}
\item In line 2, the secret number is generated using the function \texttt{rnd} which picks a random
      element from the set given as argument.  This number has to be guessed by the player.
\item The variable \texttt{count} is used to count the number of guessing attempts.
      This variable is initialized in line 3.
\item Since the user has to enter at least one number, we use a \texttt{do-while} loop that loops as
      long as the user has not yet guessed the secret number.

      In line 6, the user is asked to guess the secret number.  If this number is either too small
      or too big, an appropriate message is printed.  The loop terminates in line 14 if the number
      that has been guessed is identical to the secret number.
\end{enumerate}

\noindent
The syntax of a \texttt{do-while} loop is given by the following grammar rule:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{statement} \;\rightarrow\; \quoted{do} \quoted{\{}  \textsl{block} \quoted{\}} \quoted{while}
  \quoted{(} \textsl{boolExpr} \quoted{)} \quoted{;}
$.
\\[0.2cm]
Here, \textsl{boolExpr} is a Boolean expression returning either \texttt{true} or
\texttt{false}.  This expression is called the \emph{guard} of the \texttt{do-while} loop.
The syntactical variable \textsl{block} denotes a sequence of statements.  Note that,
in contrast to the programming languages \texttt{C} and \textsl{Java}, the
block of statements always has to be enclosed in curly braces, even if it consists only of a
single statement.  Furthermore, note that a \texttt{do-while} loop has to be terminated with a
semicolon.  This is a notable difference to \texttt{while} loops and \texttt{for} loops, which are
not terminated by a semicolon.

The semantics of a \texttt{do-while} loop is the same as in \texttt{C}:
The body of the loop is executed once.  Then, if the guard is false, execution terminates.  Otherwise,
the body is executed again and again as long as the guard is true.  In order
to abort an iteration of the loop prematurely, the commands \texttt{continue} and
\texttt{break} can be used.  These commands work in the same way as in a \texttt{while} loop.

\subsection{\texttt{for} Loops}
In order to either perform a group of commands a predefined number of times, or to iterate over a
set, list or string, a \texttt{for} loop should  be
used.  Figure \ref{fig:multiplication-table.stlx} on page \pageref{fig:multiplication-table.stlx}
shows some \setlx\ code that prints a multiplication table.  The output of this program is
shown in Figure \ref{fig:multiplication-table} on page \pageref{fig:multiplication-table}.

In the program in Figure \ref{fig:multiplication-table.stlx}, the printing is done in the two nested
\texttt{for} loops that start in line 8 and line 9, respectively.  In line 8, the counting variable
\texttt{i} iterates over all values
from $1$ to $10$.  Similarly, the counting variable \texttt{j} in line 9 iterates over the same values.
The product \texttt{i * j} is computed in line 10 and printed without a newline using the
function \texttt{nPrint}.
The function $\texttt{rightAdjust}(n)$ turns the number $n$ into a string by padding the
number with blanks from the left so that the resulting string always has a length of 4
characters.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    rightAdjust := procedure(n) {
        switch {
            case n < 10 : return "   " + n;
            case n < 100: return  "  " + n;
            default:      return   " " + n;
        }
    };
    for (i in [1 .. 10]) {
        for (j in [1 .. 10]) {
            nPrint(rightAdjust(i * j));
        }
        print();
    }
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A simple program to generate a multiplication table.}
\label{fig:multiplication-table.stlx}
\end{figure}

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = none,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
       1   2   3   4   5   6   7   8   9  10
       2   4   6   8  10  12  14  16  18  20
       3   6   9  12  15  18  21  24  27  30
       4   8  12  16  20  24  28  32  36  40
       5  10  15  20  25  30  35  40  45  50
       6  12  18  24  30  36  42  48  54  60
       7  14  21  28  35  42  49  56  63  70
       8  16  24  32  40  48  56  64  72  80
       9  18  27  36  45  54  63  72  81  90
      10  20  30  40  50  60  70  80  90 100
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Output of the program in Figure \ref{fig:multiplication-table.stlx}.}
\label{fig:multiplication-table}
\end{figure}

The general syntax of a \texttt{for} loop is given by the following \textsc{Ebnf} rule:
\\[0.2cm]
\hspace*{1.3cm}
$\textsl{statement} \rightarrow \quoted{for} \quoted{(} \textsl{iterator} \;(\squoted{,}\;
\textsl{iterator})^* \;(\squoted{|}\; \textsl{condition})? \quoted{)}
  \quoted{\{} \textsl{block} \;\squoted{\}}
$.
\\[0.2cm]
Here an iterator is either a \emph{simple iterator} or a \emph{tuple iterator}.  A
\emph{simple iterator} has the form
\\[0.2cm]
\hspace*{1.3cm}
$x \quoted{in} s$
\\[0.2cm]
where $s$ is either a set, a list, or a string and $x$ is the name of a variable.
This variable is bound to the elements of $s$ in turn.  For example,  the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{for (x in [1..10]) \{ print(x); \}}
\\[0.2cm]
will print the numbers from 1 to 10.  If $s$ is a string, then the variable $x$ iterates over the
characters of $s$.  For example, the statement
\\[0.2cm]
\hspace*{1.3cm}
\texttt{for (c in \symbol{34}abc\symbol{34}) \{ print(c); \}}
\\[0.2cm]
prints the characters \texttt{\symbol{34}a\symbol{34}}, \texttt{\symbol{34}b\symbol{34}},
and \texttt{\symbol{34}c\symbol{34}}.

The iterator of a \texttt{for} loop can also be a \emph{tuple iterator}.  The simplest form of
a tuple is
\\[0.2cm]
\hspace*{1.3cm}
 $[x_1, \cdots, x_n] \quoted{in} s$.
\\[0.2cm]
Here, $s$ must be either a set or a list whose elements are lists of length $n$.
Figure \ref{fig:relational-product-for.stlx} on page \pageref{fig:relational-product-for.stlx}
shows a procedure that computes the relational product
of two binary relations $r_1$ and $r_2$.  In set theory, the relational product $r_1 \circ r_2$
is defined as
\\[0.2cm]
\hspace*{1.3cm}
$r_1 \circ r_2 := \{ \pair(x,z) \mid \pair(x,y) \in r_1 \wedge \pair(y,z) \in r_2 \}$.
\\[0.2cm]
The \texttt{for} loop in line 3 iterates over the two relations \texttt{r1} and \texttt{r2}.
The condition ``\texttt{y1 == y2}'' selects those pairs of numbers such that the second
component of the first pair is identical to the first component of the second pair.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    product := procedure(r1, r2) {
        r := {};
        for ([x, y1] in r1, [y2, z] in r2 | y1 == y2) {
            r += { [x, z] };
        }
        return r;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A program to compute the relational product of two binary relations.}
\label{fig:relational-product-for.stlx}
\end{figure}

The \texttt{for} loop in line 3 can be simplified as shown in Figure
\ref{fig:relational-product-for-1.stlx} on page \pageref{fig:relational-product-for-1.stlx}.  Here,
we have forced the second component of the pair \texttt{[x,y]} to be equal to the first component of
the pair \texttt{[y,z]} by using the same variable name for both components.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    product := procedure(r1, r2) {
        r := {};
        for ([x, y] in r1, [y, z] in r2) {
            r += { [x, z] };
        }
        return r;
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A program to compute the relational product of two binary relations.}
\label{fig:relational-product-for-1.stlx}
\end{figure}

Of course, in \setlx\ the relational product can be computed more easily via set comprehension.
Figure \ref{fig:relational-product.stlx} on page \pageref{fig:relational-product.stlx} shows
an implementation of the function \texttt{product} that is based on set comprehension.
In general, most occurrences of \texttt{for} loops can be replaced by equivalent set
comprehensions. Our experience shows that the resulting code is often both shorter as well as easier to
understand.

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    product := procedure(r1, r2) {
        return { [x, z] : [x, y] in r1, [y, z] in r2 };
    };
\end{Verbatim}
\vspace*{-0.3cm}
\caption{Computing the relational product via set comprehension.}
\label{fig:relational-product.stlx}
\end{figure}

Iterators can be even more complex, since the tuples can be nested, so a \texttt{for} loop of the form
\\[0.2cm]
\hspace*{1.3cm}
\texttt{for ([[x,y],z] in s) \{ $\cdots$ \}}
\\[0.2cm]
is possible.  However, as this feature is rarely needed, we won't discuss it in more detail.

A \texttt{for} loop creates a
\href{http://en.wikipedia.org/wiki/Variable_scope}{\emph{local scope} }
for its iteration variables.  This means that changes to an iteration variable that occur in the
\texttt{for} loop are not visible outside of the \texttt{for} loop.
Therefore, the last line of the program shown in Figure \ref{fig:scope-for-loop.stlx} prints the
message
\\[0.2cm]
\hspace*{1.3cm}
\texttt{x = 1.}

\begin{figure}[!ht]
\centering
\begin{Verbatim}[ frame         = lines,
                  framesep      = 0.3cm,
                  firstnumber   = 1,
                  labelposition = bottomline,
                  numbers       = left,
                  numbersep     = -0.2cm,
                  xleftmargin   = 0.8cm,
                  xrightmargin  = 0.8cm,
                ]
    x := 1;
    for (x in "abc") {
        print(x);
    }
    print("x = $x$");
\end{Verbatim}
\vspace*{-0.3cm}
\caption{A program illustrating the scope of a \texttt{for} loop.}
\label{fig:scope-for-loop.stlx}
\end{figure}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "tutorial"
%%% End:


\chapter{Sorting}
\label{sortingchapter}

This chapter describes the \defrsixlibrary{sorting} library for
sorting lists and vectors.

\begin{entry}{%
\proto{list-sort}{ proc list}{procedure}
\proto{vector-sort}{ proc vector}{procedure}}

\domain{\var{Proc} should accept any two elements
  of \var{list} or \var{vector}, and should not have any side
  effects.}  \var{Proc} should return a true value when its first argument
is strictly less than its second, and \schfalse{} otherwise.

The {\cf list-sort} and {\cf vector-sort} procedures perform a stable
sort of \var{list} or \var{vector} in ascending order according to
\var{proc}, without changing \var{list} or
\var{vector} in any way.  The {\cf list-sort} procedure returns a
list, and {\cf vector-sort} returns a vector.  The results may be {\cf
  eq?} to the argument when the argument is already sorted, and the
result of {\cf list-sort} may share structure with a tail of the
original list.  The sorting algorithm performs $O(n \lg n)$ calls to
\var{proc} where $n$ is the length of \var{list} or \var{vector},
and all arguments passed to \var{proc} are elements of the list or
vector being sorted, but the pairing of arguments and the sequencing
of calls to \var{proc} are not specified.
If multiple returns occur from {\cf list-sort} or {\cf vector-sort}, the return
values returned by earlier returns are not mutated.

\begin{scheme}
(list-sort < '(3 5 2 1)) \ev (1 2 3 5)
(vector-sort < '\sharpsign(3 5 2 1)) \ev \sharpsign(1 2 3 5)%
\end{scheme}

\implresp The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.
An
implementation may check whether \var{proc} is an appropriate argument
before applying it.
\end{entry}

\begin{entry}{%
\proto{vector-sort!}{ proc vector}{procedure}}

\domain{\var{Proc} should accept any two elements
  of the vector, and should not have any side
  effects.  \var{Proc} should return a true value when its first
argument is strictly less than its second, and \schfalse{} otherwise.}
The {\cf vector-sort!} procedure destructively sorts \var{vector} in
ascending order according to \var{proc}.  The sorting algorithm
performs $O(n^2)$ calls to \var{proc} where $n$ is the length of
\var{vector}, and all arguments passed to \var{proc} are elements
of the vector being sorted, but the pairing of arguments and the
sequencing of calls to \var{proc} are not specified.  The sorting
algorithm may be unstable.  The procedure returns \unspecifiedreturn.

\begin{scheme}
(define v (vector 3 5 2 1))
(vector-sort! < v) \ev \theunspecified
v \ev \sharpsign(1 2 3 5)
\end{scheme}
\implresp The implementation must check the restrictions
on \var{proc} to the extent performed by applying it as described.
An
implementation may check whether \var{proc} is an appropriate argument
before applying it.
\end{entry}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "r6rs-lib"
%%% End:


\chapter{The Analytical Gradient for CI Methods}
%
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{CI Energy}
%
%
%
%
In this chapter, we are going to consider the analytical gradients for general
CI method. Here we follow the general convention that to use
$C$ (capital C) to represent the Slater determinant amplitude in CI state,
to use $c$ (lowercase c) to designate the MO coefficients, $\Psi$ is used to
refer to CI wave function, $\Phi$ means the corresponding Slater
determinant, and $\varphi$  is refer to MO.

For the index, all the capital letters such as $I,J,K,L$ etc. indicates it's
CI wave functions, and the lowercase letter is used to refer to MO. Again, we
use a, b, c etc. to designate the virtual orbitals, the i, j, k etc. to refer to
the occupied orbitals; and p, q, r etc. to specify the general orbitals.

Suppose that we have gained a set of reference MO from HF calculation, then we
are able to form the corresponding slater determinants:
\begin{equation}
 \label{CI_energy_CI_derivatives:1}
\Psi_{K} = \sum_{I}C_{IK}\Phi_{I}
\end{equation}
Where the normalization condition for the wave functions requires:
\begin{equation}
 \label{CI_energy_CI_derivatives:2}
\langle\Psi_{J}|\Psi_{K}\rangle = \delta_{JK} \rightarrow \sum_{I}C_{IJ}C_{IK}
= \delta_{JK}
\end{equation}

From the Schrodinger equation, we know:
\begin{align}
 \label{CI_energy_CI_derivatives:3}
\hat{H}\Psi_{K} &= E_{K}\Psi_{K} \Longrightarrow \nonumber \\
E_{K} &= \langle\Psi_{K}|\hat{H}|\Psi_{K}\rangle   \nonumber \\
&=\sum_{I}\sum_{J}C_{IK}C_{JK}\langle\Phi_{I}|\hat{H}|\Phi_{J}\rangle \nonumber
\\
&= \sum_{I}\sum_{J}C_{IK}C_{JK}H_{IJ}
\end{align}

For $H_{IJ}$, if we express it into the MO representation, it becomes:
\begin{equation}
 \label{CI_energy_CI_derivatives:4}
H_{IJ} = \sum_{pq}^{MO}Q_{pq}^{IJ}h_{pq} + \sum_{pqrs}^{MO}G_{pqrs}^{IJ}(pq|rs)
\end{equation}
From Slater rules, it turns out that $Q_{pq}^{IJ}$ and $G_{pqrs}^{IJ}$ are some
numbers, which could be $0$, $\pm 1$ or $\pm 2$.

By further considering the CI amplitudes, we have:
\begin{equation}
 \label{CI_energy_CI_derivatives:5}
E_{K} = \sum_{pq}^{MO}Q^{K}_{pq}h_{pq} + \sum_{pqrs}^{MO}G^{K}_{pqrs}(pq|rs)
\end{equation}
Where
\begin{align}
 \label{CI_energy_CI_derivatives:6}
Q^{K}_{pq} &= \sum_{I}\sum_{J}C_{IK}C_{JK}Q_{pq}^{IJ} \nonumber \\
G^{K}_{pqrs} &= \sum_{I}\sum_{J}C_{IK}C_{JK}G_{pqrs}^{IJ}
\end{align}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{The First Order Derivatives for CI Method}
%
%
%
%
Now according to the (\ref{CI_energy_CI_derivatives:3}), the first order energy
derivatives can be expressed as:
\begin{equation}
  \label{CI_1st_CI_derivatives:1}
\begin{split}
\frac{\partial E_{K}}{ \partial \bm{R}_{a}} &=
\sum_{I}\sum_{J}\frac{\partial C_{IK}}{\partial \bm{R}_{a}}C_{JK}H_{IJ} +
\sum_{I}\sum_{J}C_{IK}\frac{\partial C_{JK}}{\partial \bm{R}_{a}}H_{IJ} \\
&+\sum_{I}\sum_{J}C_{IK}C_{JK}\frac{\partial H_{IJ} }{\partial \bm{R}_{a}}
\\
&= 2\sum_{I}\sum_{J}\frac{\partial C_{IK}}{\partial \bm{R}_{a}}C_{JK}H_{IJ} +
\sum_{I}\sum_{J}C_{IK}C_{JK}\frac{\partial H_{IJ} }{\partial \bm{R}_{a}}
\end{split}
\end{equation}
In this derivation, we have used the relation that $I$ and $J$ are symmetrical.

According to Winger's theorem (see \ref{Winger_theorem}), the derivatives for
the variational parameters should not appear in the first order derivatives
expression, this is because the $C_{I}$ has made the energy minimum. Hence by
applying the CI equation in (\ref{CIeq:17}), we have:
\begin{align}
  \label{CI_1st_CI_derivatives:2}
HC &= EC \Longrightarrow \nonumber \\
\sum_{J}H_{IJ}C_{JK} &= E_{K}C_{IK}
\end{align}
Here $C_{JK}$ indicates the amplitudes for the $K$th CI wave function. By bring
(\ref{CI_1st_CI_derivatives:2}) into (\ref{CI_1st_CI_derivatives:1}), we have:
\begin{align}
 \label{CI_1st_CI_derivatives:3}
\frac{\partial E_{K}}{ \partial \bm{R}_{a}} &= 2E_{K}\sum_{I}\frac{\partial
C_{IK}}{\partial \bm{R}_{a}}C_{IK} +
\sum_{I}\sum_{J}C_{IK}C_{JK}\frac{\partial H_{IJ} }{\partial \bm{R}_{a}}
\nonumber \\
&= \sum_{I}\sum_{J}C_{IK}C_{JK}\frac{\partial H_{IJ} }{\partial \bm{R}_{a}}
\end{align}
This is because that from the normalization condition, we have:
\begin{equation}
 \begin{split}
  \frac{\partial \sum_{I}C_{IK}^{2}}{\partial \bm{R}_{a}} &= 0 \Longrightarrow
\\
2\sum_{I}\frac{\partial
C_{IK}}{\partial \bm{R}_{a}}C_{IK} &= 0
 \end{split}
\label{CI_1st_CI_derivatives:4}
\end{equation}

Expanding the (\ref{CI_1st_CI_derivatives:3}) in terms of
(\ref{CI_energy_CI_derivatives:5}), we can get that:
\begin{equation}
\label{CI_1st_CI_derivatives:5}
 \frac{\partial E_{K}}{ \partial \bm{R}_{a}} =
\sum_{pq}^{MO}Q^{K}_{pq}\frac{\partial h_{pq}}{\partial \bm{R}_{a}} +
\sum_{pqrs}^{MO}G^{K}_{pqrs}\frac{\partial (pq|rs)}{\partial \bm{R}_{a}}
\end{equation}

Now the problem is back to the MO derivatives. From
(\ref{core_Hamiltonian_MO_INT_gradient_eq:1}) and
(\ref{two_electron_MO_INT_gradient_eq:1}), which are:
\begin{align}
 \label{CI_1st_CI_derivatives:6}
\frac{\partial h_{pq}}{\partial \bm{R}_{a}} &= \sum_{t}\left[U^{a}_{tp}H_{qt} +
U^{a}_{tq}H_{pt}\right]  + H^{a}_{pq} \nonumber \\
(pq|rs)^{[a]} &= \Pi_{pqrs}^{[a]} =\sum_{t}\left[
U^{a}_{tp}\Pi_{tqrs} +
U^{a}_{tq}\Pi_{ptrs} +
U^{a}_{tr}\Pi_{pqts} +
U^{a}_{ts}\Pi_{pqrt}
\right] + \Pi^{a}_{pqrs}
\end{align}
the (\ref{CI_1st_CI_derivatives:5}) can be further expressed as:
\begin{align}
  \label{CI_1st_CI_derivatives:7}
 \frac{\partial E_{K}}{ \partial \bm{R}_{a}} &=
\sum_{pq}^{MO}Q^{K}_{pq}\left\lbrace \sum_{t}\left[U^{a}_{tp}H_{qt} +
U^{a}_{tq}H_{pt}\right]  + H^{a}_{pq} \right\rbrace \nonumber \\
&+
\sum_{pqrs}^{MO}G^{K}_{pqrs}\left\lbrace \sum_{t}\left[
U^{a}_{tp}\Pi_{tqrs} +
U^{a}_{tq}\Pi_{ptrs} +
U^{a}_{tr}\Pi_{pqts} +
U^{a}_{ts}\Pi_{pqrt}
\right] + \Pi^{a}_{pqrs}\right\rbrace \nonumber \\
&= \sum_{pq}^{MO}Q^{K}_{pq}H^{a}_{pq} +
\sum_{pqrs}^{MO}G^{K}_{pqrs}\Pi^{a}_{pqrs} \nonumber \\
&+ \sum_{pq}^{MO}Q^{K}_{pq}\left\lbrace \sum_{t}\left[U^{a}_{tp}H_{qt} +
U^{a}_{tq}H_{pt}\right]  \right\rbrace \nonumber \\
&+ \sum_{pqrs}^{MO}G^{K}_{pqrs}\left\lbrace \sum_{t}\left[
U^{a}_{tp}\Pi_{tqrs} +
U^{a}_{tq}\Pi_{ptrs} +
U^{a}_{tr}\Pi_{pqts} +
U^{a}_{ts}\Pi_{pqrt}
\right] \right\rbrace \nonumber \\
\end{align}

Now let's try to understand the symmetry behind the
(\ref{CI_1st_CI_derivatives:7}). Compared with the Hatree-Fock derivatives,
here a important distinguishment is that the MO index are ``sumed up'', which
means, the $p$ and $q$ are identical with each other in the core Hamiltonian
derivatives, and the four indices of $p$, $q$, $r$, $s$ are identical with each
other in the double electron integral derivatives. That is to say:
\begin{equation}
 \begin{split}
  \sum_{pq}^{MO}\sum_{t}Q^{K}_{pq}U^{a}_{tp}H_{qt} &=
  \sum_{pq}^{MO}\sum_{t}Q^{K}_{pq}U^{a}_{tq}H_{pt} \\
\sum_{pqrs}^{MO} \sum_{t}G^{K}_{pqrs}
U^{a}_{tp}\Pi_{tqrs}
&=
\sum_{pqrs}^{MO} \sum_{t}G^{K}_{pqrs}
U^{a}_{tq}\Pi_{ptrs} \\
&=
\sum_{pqrs}^{MO} \sum_{t}G^{K}_{pqrs}
U^{a}_{tr}\Pi_{pqts}  \\
&=
\sum_{pqrs}^{MO} \sum_{t}G^{K}_{pqrs}
U^{a}_{ts}\Pi_{pqrt}
 \end{split}
\label{CI_1st_CI_derivatives:8}
\end{equation}
This can be further explained as below: since in the summation
$\sum_{pq}^{MO}\sum_{t}$, $Q^{K}_{pq} = Q^{K}_{qp}$ (see its original
definition); then if we exchange the index of $p$ and $q$, then everything
should be same for the core integral:
\begin{equation}
  \sum_{pq}^{MO}\sum_{t}Q^{K}_{pq}U^{a}_{tq}H_{pt} \xrightarrow{p
\leftrightarrow q} \sum_{pq}^{MO}\sum_{t}Q^{K}_{qp}U^{a}_{tp}H_{qt}
\end{equation}
Then the second integral changes into the first one, hence they should be
identical with each other. For the double electron integrals, we can get the
similar proof by remembering that $Q^{K}_{pqrs}$ does not change if we
exchange the label of $p$, $q$, $r$ and $s$.

By bringing the (\ref{CI_1st_CI_derivatives:8}) into the
(\ref{CI_1st_CI_derivatives:7}), then we can get:
\begin{align}
 \label{CI_1st_CI_derivatives:9}
\frac{\partial E_{K}}{ \partial \bm{R}_{a}} &=
\sum_{pq}^{MO}Q^{K}_{pq}H^{a}_{pq} +
\sum_{pqrs}^{MO}G^{K}_{pqrs}\Pi^{a}_{pqrs} \nonumber \\
&+ 2\sum_{pq}^{MO}\sum_{t}Q^{K}_{pq}U^{a}_{tp}H_{qt} +
4\sum_{pqrs}^{MO}\sum_{t} G^{K}_{pqrs}
U^{a}_{tp}\Pi_{tqrs} \nonumber \\
&= \sum_{pq}^{MO}Q^{K}_{pq}H^{a}_{pq} +
\sum_{pqrs}^{MO}G^{K}_{pqrs}\Pi^{a}_{pqrs} \nonumber \\
&+ 2\sum_{tp}U^{a}_{tp}\left\lbrace
\sum_{q}^{MO}Q^{K}_{pq}H_{qt} +
2\sum_{qrs}^{MO}G^{K}_{pqrs}
\Pi_{tqrs}
\right\rbrace \nonumber \\
&= \sum_{pq}^{MO}Q^{K}_{pq}H^{a}_{pq} +
\sum_{pqrs}^{MO}G^{K}_{pqrs}\Pi^{a}_{pqrs}
+ 2\sum_{tp}U^{a}_{tp}X_{tp}
\end{align}
Where $X_{tp}$ is:
\begin{equation}
 \label{CI_1st_CI_derivatives:10}
X_{tp} =
\sum_{q}^{MO}Q^{K}_{pq}H_{qt} +
2\sum_{qrs}^{MO}G^{K}_{pqrs}
\Pi_{tqrs}
\end{equation}
Now here the only thing left we need to solve is the MO response matrix of $U$
in (\ref{CI_1st_CI_derivatives:9}).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Z-Vector method}
%
%
%
%
\cite{handy1984evaluation}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../../main"
%%% End:


\documentclass[twoside]{MATH77}
\usepackage{multicol}
\usepackage[fleqn,reqno,centertags]{amsmath}
\begin{document}
\begmath 7.1 Roots of a Polynomial

\silentfootnote{$^\copyright$1997 Calif. Inst. of Technology, \thisyear \ Math \`a la Carte, Inc.}

\subsection{Purpose}

Given the coefficients $a_i$ of a polynomial of degree $n=$ {NDEG }$>0,$%
\begin{equation*}
a_1z^n+a_2z^{n-1}+...+a_nz+a_{n+1}
\end{equation*}
with $a_1\neq 0$, this subroutine computes the NDEG roots of the polynomial.
Since the roots may be complex, they will always be returned as complex
numbers, even when they are real.

Subroutines are provided for four cases:

\begin{tabular}{ll}
{\bf SPOLZ} & for single precision real coefficients.\\
{\bf DPOLZ} & for double precision real coefficients.\\
{\bf CPOLZ} & for single precision complex coefficients.\\
{\bf ZPOLZ} & for double precision complex coefficients.\\
\end{tabular}

See Section E for remarks on the method of storing double precision complex
numbers.

\subsection{Usage}

\subsubsection{Program Prototype, Single Precision Real Coefficients}

\begin{description}
\item[INTEGER]  \ {\bf NDEG, IERR}

\item[REAL]  \ {\bf A}$(\geq $ NDEG + 1){\bf , H}$(\geq $ NDEG**2)

\item[~~~~COMPLEX]  \ {\bf Z}$(\geq $ NDEG)
\end{description}

Assign values to A(), and NDEG.%
$$
\fbox{{\bf CALL SPOLZ(A, NDEG, Z, H, IERR)}}
$$
Computed quantities are returned in Z() and IERR.

\subsubsection{Program Prototype, Double Precision Real Coefficients}

\begin{description}
\item[INTEGER]  \ {\bf NDEG, IERR}

\item[DOUBLE PRECISION]  \ {\bf A}$(\geq $ NDEG + 1){\bf ,\newline
H}$(\geq $NDEG**2)

\item[DOUBLE PRECISION]  \ {\bf Z}(2, $\geq $ NDEG) or

\item[~~~~COMPLEX*16]  {\bf Z}$(\geq $ NDEG)
\end{description}

Assign values to A(), and NDEG.%
$$
\fbox{{\bf CALL DPOLZ(A, NDEG, Z, H, IERR)}}
$$
Computed quantities are returned in Z() and IERR.

\subsubsection{Program Prototype, Single Precision Complex Coefficients}

\begin{description}
\item[INTEGER]  \ {\bf NDEG, IERR}

\item[COMPLEX]  \ {\bf A}$(\geq $NDEG + 1)

\item[REAL]  \ {\bf H}$(\geq $ 2 * NDEG**2)

\item[COMPLEX]  \ {\bf Z}$(\geq $ NDEG)
\end{description}

Assign values to A(), and NDEG.%
$$
\fbox{{\bf CALL CPOLZ(A, NDEG, Z, H, IERR)}}
$$
Computed quantities are returned in Z() and IERR.

\subsubsection{Program Prototype, Double Precision Complex Coefficients}

\begin{description}
\item[INTEGER]  \ {\bf NDEG, IERR}

\item[DOUBLE PRECISION]  \ {\bf A}(2, $\geq $ NDEG + 1) or

\item[~~~~COMPLEX*16]  \ {\bf A}$(\geq $ NDEG + 1)

\item[DOUBLE PRECISION]  \ {\bf H} $(\geq $2 * NDEG**2)

\item[DOUBLE PRECISION]  \ {\bf Z}(2, $\geq $ NDEG) or

\item[~~~~COMPLEX*16]  \ {\bf Z}$(\geq $ NDEG)
\end{description}

Assign values to A(), and NDEG.%
$$
\fbox{{\bf CALL ZPOLZ(A, NDEG, Z, H, IERR)}}
$$
Computed quantities are returned in Z() and IERR.

\subsubsection{Argument Definitions}

\begin{description}
\item[A()]  [in] Contains the coefficients of a polynomial, high order
coefficient first, with A($1)\neq 0$. The contents of this array will not be
modified by the subroutine.

In the case of ZPOLZ, if the declaration DOUBLE PRECISION A(2, NDEG$+1)$ is
used, the user must store the real part of $a_i$ in A(1, $i$) and the imaginary
part in A(2, $i$).

\item[NDEG]  [in] Degree of the polynomial.

\item[H()]  [scratch] Work space for the subroutine.

\item[Z()]  [out] Contains the polynomial roots stored as complex numbers.
In the cases of DPOLZ and ZPOLZ, if the declaration DOUBLE PRECISION Z($2,$
NDEG) is used, the real part of $z_i$ will be returned in Z($1, i)$ and the
imaginary part in Z($2, i).$

\item[IERR]  [out] Error flag. Set by the subroutine to~0 on normal
termination. Set to $-$1 if A($1)=0$. Set to $-$2 if NDEG $<1$. Set to J $>0$
if the iteration count limit has been exceeded and roots~1 through J have
not been determined.
\end{description}

\subsection{Examples and Remarks}

The program, DRSPOLZ, uses SPOLZ to compute the roots of the two polynomials%
\begin{gather*}
x^3-4x^2+x-4,\quad \text{and}\\
x^5-15x^4+85x^3-225x^2+274x-120
\end{gather*}
The output is shown in ODSPOLZ.

The Fortran~77 standard does not support a double precision complex data
type, although such a type is supported in many compilers using the
declaration, COMPLEX*16. The subroutines described here conform to the
standard and thus do not use COMPLEX*16. For cases in which double precision
complex quantities are communicated using the arrays A() or Z(), these
subroutines store a complex number as an adjacent pair of double precision
numbers, representing respectively the real and imaginary parts of the
complex number.  This is compatible with the Fortran~90 storage
convention for double precision complex.  If the user has the COMPLEX*16
declaration available and wishes to use it, it will generally be compatible
with this storage
convention.

\subsection{Functional Description}

\subparagraph{Method}

The degree, NDEG, and coefficients, $a_1$, $..., a_{NDEG+1}$, are given. An
error condition is reported if NDEG $< 1$ or if $a_1 = 0.$

Let $k+1$ be the index of the last nonzero coefficient. If $k<\text{NDEG}$, the
polynomial has a root at zero repeated $\text{NDEG}-k$ times and these roots
are recorded. The remaining roots will be roots of the polynomial of degree $k$
whose coefficients are the first $k+1$ given coefficients. If $k=1$, the
root $-a_2/a_1$ is recorded.

If  $k>1$, the subroutine forms the $k\times k$ companion matrix $H$ for
this $k^{th}$ degree polynomial. The matrix $H$ is zero except for the first
row,%
\begin{equation*}
h_{1,j}=-a_{j+1}/a_1,\quad j=1, ..., k
\end{equation*}
and the elements just below the diagonal,%
\begin{equation*}
h_{i,i-1}=1,\quad i=2, ..., k
\end{equation*}
A scaling algorithm is applied to $H$ to balance the sizes of the nonzero
elements.  Testing showed that accuracy could be very unsatisfactory if no
scaling were done.  The scaling method used is a modification of the
subroutine BALANC from the EISPACK collection of matrix eigensystem
subroutines \cite{Smith:1974:MER}, \cite{Garbow:1977:MER}.  The
modification avoids treating the elements that are known to be zero due to
the form of the companion matrix.  The search for useful row or column
permutations done in BALANC is also deleted since, with $a_{k+1}$ known to
be nonzero, none of these permutations are possible.

The eigenvalues of the balanced $H$ matrix are then computed using appropriate
code for the QR algorithm from EISPACK. For SPOLZ and DPOLZ the code for the
EISPACK subroutine, HQR, has been incorporated in-line. For CPOLZ or ZPOLZ,
a call is made to SCOMQR or DCOMQR, respectively. These latter two
subroutines are, respectively, single precision and double precision versions
of the EISPACK subroutine, COMQR.

Reference \cite{Goedecker:1994:RAF} reports that compared with other
widely used methods, the conversion of the root finding problem to an
eigenvalue problem is superior in reliability, generally superior in
accuracy, and comparable in speed.

\subparagraph{Accuracy tests}

A root of a polynomial is called ill-conditioned if a small relative change
in the coefficients makes a significantly larger relative change in the
root. Roots that are bunched closely together relative to their magnitude,
or relative to their distance from other roots, tend to be ill-conditioned.
An extreme case of ill-conditioning occurs with multiple roots. If the
coefficients of a polynomial are only known to some relative precision, say $%
p$, then a double root will typically have a relative uncertainty of about $%
p^{1/2}$, and a triple root a relative uncertainty of about $p^{1/3}.$

The accuracy of a computed root is limited by the inherent conditioning of
the root. Rather than directly testing the accuracy of the computed roots,
we have chosen to test the accuracy with which polynomial coefficients could
be reconstituted from the computed roots.

To test these subroutines we selected eight sets of roots to test SPOLZ and
DPOLZ and a different group of eight sets of roots to test CPOLZ and ZPOLZ.
These sets included double and triple roots, roots that formed a small
cluster relative to other roots, roots that differed by a factor of $10^8$,
and both real and complex roots. The number of roots in each set varied
from~1 to~7.

From each set of roots we created 8~test sets by multiplying all roots in
the set by one of the factors, $10^{-3}$, $10^{-2}$, ..., $10^3$, or $10^4$.
This produced a total of 64~test sets for each subroutine.

To execute the test for one subroutine, say xPOLZ, and one set of roots, say
$r_1$, ..., $r_n$, we did the following:

\begin{itemize}
\item[1.]  Compute, in double precision, the coefficients, say $a_i$, of the
monic polynomial having the roots, $r_i$.  Subroutine ZCOEF of
Chapter 15.3 is used for this.

\item[2.]  Use subroutine xPOLZ to compute the roots, say $s_i$, of this
polynomial.

\item[3.]  Compute, in double precision, the coefficients, say $b_i$, of the
monic polynomial having the roots, $s_i.$

\item[4.]  Compute $\delta =$ the maximum of the relative differences
between corresponding coefficients, $a_i$ and $b_i.$

\item[5.]  Compute $\varepsilon =\delta \ /\rho $, where $\rho $ is the
relative precision of the arithmetic being used by xPOLZ. The value for $%
\rho $ was obtained as R1MACH(4) for single precision and D1MACH(4) for
double precision.  (See Chapter~19.1.)
\end{itemize}

Ideally, Step~3 should be done using significantly higher precision than is
used by the subroutine xPOLZ being tested, so the error measures, $\delta $
and $\varepsilon $, will be attributable only to xPOLZ with no inflation
from Step~3. Since we used double precision in Step~3 for all cases, we
conclude that the reported values of $\varepsilon $ are solely attributable
to SPOLZ and CPOLZ in the tests of those subroutines, while the values of $%
\varepsilon $ reported for DPOLZ and ZPOLZ are somewhat inflated due to
errors from Step~3.

These tests were run on an IBM PC/{AT} equipped with the Intel 80287 math
coprocessor. The precision was $\rho \approx 1.2 \times 10^{-7}$ for single
precision and $2.2\times 10^{-16}$ for double precision. The results may be
summarized as follows:

\begin{tabular}{lrr}
    & \multicolumn{1}{c}{\bf
Max. $\varepsilon $ over}  &  \multicolumn{1}{c}{\bf Number of Cases}\\
  \multicolumn{1}{c}{\bf Subroutine} & \multicolumn{1}{c}{\bf 64 test cases} &
  \multicolumn{1}{c}{\bf with $\epsilon >10$}  \\
  \hspace{.15in} SPOLZ   &  35 \hspace{.3in}   &  19 \hspace{.5in}  \\
  \hspace{.15in} DPOLZ   &  57 \hspace{.3in}  &  21 \hspace{.5in} \\
  \hspace{.15in} CPOLZ   &    8 \hspace{.3in}   &    0 \hspace{.5in} \\
  \hspace{.15in} ZPOLZ   &  43  \hspace{.3in}  &    8 \hspace{.5in}
\end{tabular}

\bibliography{math77}
\bibliographystyle{math77}

\subsection{Error Procedures and Restrictions}

The error indicator, IERR, will be set as follows:

\begin{description}
\item[\rm = 0]  \ when no errors are detected.

\item[\rm = $-$1]  \ if A(1) is zero, or A(1,~1) and A(2,~1) are both zero.

\item[\rm = $-$2]  \ if NDEG $<1.$

\item[\rm = J $>$ 0]  \ if the iteration count limit has been exceeded and
roots 1 through J have not been determined. The matrix eigenvalue codes
allow a maximum of 30~iterations for each root. This limit is ample.
\end{description}

When IERR is set nonzero, the subroutine will also issue an error message
using ERMSG, of Chapter~19.2, with an error level of 0.

\subsection{Supporting Information}

\begin{tabular}{@{\bf}l@{\hspace{5pt}}l}
\bf Entry & \hspace{.35in} {\bf Required Files}\vspace{2pt}\\
CPOLZ & \parbox[t]{2.7in}{\hyphenpenalty10000 \raggedright
 AMACH, CPOLZ, ERFIN, ERMSG, SCOMQR\rule[-5pt]{0pt}{8pt}}\\
DPOLZ & \parbox[t]{2.7in}{\hyphenpenalty10000 \raggedright
 AMACH, DPOLZ, ERFIN, ERMSG\rule[-5pt]{0pt}{8pt}}\\
SPOLZ & \parbox[t]{2.7in}{\hyphenpenalty10000 \raggedright
 AMACH, ERFIN, ERMSG, SPOLZ\rule[-5pt]{0pt}{8pt}}\\
ZPOLZ & \parbox[t]{2.7in}{\hyphenpenalty10000 \raggedright
 AMACH, DCOMQR, DZABS, ERFIN, ERMSG, ZPOLZ, ZQUO, ZSQRT}\\
\end{tabular}

Designed by C. L. Lawson, JPL, May~1986. Programmed by C. L. Lawson and S.
Y. Chiu, JPL, May~1986, Feb.~1987.

\begcodenp
\lstset{language=[77]Fortran,showstringspaces=false}
\lstset{xleftmargin=.8in}

\centerline{\bf \large DRSPOLZ}\vspace{10pt}
\lstinputlisting{\codeloc{spolz}}

\vspace{30pt}\centerline{\bf \large ODSPOLZ}\vspace{10pt}
\lstset{language={}}
\lstinputlisting{\outputloc{spolz}}
\end{document}


\documentclass[Physics.tex]{subfiles}
\begin{document}
\chapter{Wave Motion}
A \sldef{wave} is a disturbance or oscillation that travels through space, accompanied by a transfer of energy, but without any transfer of material between the points.

Waves are mechanical or electromagnetic, transverse or longitudinal, and progressive or stationary.

A mechanical wave requires a medium for propagation, while electromagnetic waves do not. In mechanical waves, particles of the medium oscillate, while in electromagnetic waves, the electric and magnetic fields oscillate. In either case there is no propagation of material.

\sldef{Transverse waves} have particles oscillating perpendicularly to the direction of wave propagation, while \sldef{longitudinal waves} have particles oscillating parallel to the direction of wave propagation.

In a \sldef{progressive wave}, the profile of the wave appears to be moving, and energy is transferred. In a \sldef{standing wave}, the profile of the wave does not appear to move, and energy may or may not be transferred.

The \sldef{crest} on a sinusoidal waveform is the highest point while the \sldef{trough} is the lowest point. The \sldef{wavelength} \(\lambda\) is the distance between two successive points on a wave that are in phase.

The (phase) velocity of a wave is the velocity at which the phase of the wave travels. \begin{slderiv}If we assume it is constant, then velocity is the distance travelled by the wave in one cycle over the time taken for one cycle of the wave. For one cycle of the wave, the distance travelled is the wavelength \(\lambda\) and time taken is the period \(T\). Thus the speed of the wave \begin{equation}v = \frac{\lambda}{T} = f\lambda\qedhere\end{equation}\end{slderiv}
\section{Graphs}
The angular wavenumber (or simply wavenumber) \(k\) is the radians per unit distance of the wave. \[k = \frac{2\pi}{\lambda}\]

The displacement-time graph of a single particle in a wave is given by \begin{equation}y = y_0\sin(\frac{2\pi}{T}t) = y_0\sin\omega t\end{equation} It shows the displacement of a single particle along the path of propagation at various times.

The displacement-distance graph of a wave is given by \begin{equation}y = y_0\sin(\frac{2\pi}{\lambda}x) = y_0\sin k\lambda\end{equation} It shows the displacement of all particles along the path of propagation at various distances from the source at an instant in time.

\sldef{Wavefronts} show the position of points of a wave that are in phase. The direction of wave propagation is perpendicular to the wavefronts.

For a longitudinal wave, if displacement to e.g. the left is taken as negative, and to the right as positive, then the displacement-time and displacement-distance graphs can also be plotted.
\section{Phase}
Phase and phase difference are as defined in oscillations. However, phase difference can also be determined using the path difference \(\Delta x\): \begin{equation}\Delta\phi = \frac{\Delta x}{\lambda}2\pi\end{equation}

Particles in phase have a phase difference of \SI{0}{\radian} and a path difference that is an integer multiple of the wavelength. Particles in antiphase have a phase difference of \SI{\pi}{\radian} and a path difference that is an odd multiple of \(\lambda/2\) i.e. \((n + \smash{\frac{1}{2}})\lambda\), \(n \in \mathbb{Z}^+_0\).
\section{Intensity}
The \sldef{intensity} of a wave is the rate of transfer of energy per unit area, with units \si{\watt\per\square\metre}. In three dimensions, intensity is inversely proportional to the square of distance; in two dimensions, it is inversely proportional to distance only, since the energy spreads out only on the circumference of a circle.

For a point source that spreads out uniformly from the source, energy is spread out in 3 dimensions on an expanding spherical surface. Since the area of a sphere is \(4\pi r^2\), then \begin{equation}I = \frac{P}{4\pi r^2}\end{equation} A directed source spreads out over the area of a hemisphere, and so on.

Intensity is always proportional to the square of amplitude, for both 2 and 3 dimensions i.e. \begin{equation}I \propto {x_0}^2\end{equation}
\section{Polarisation}
\sldef{Polarisation} is a property of waves that can oscillate with more than one orientation i.e. for transverse waves. A wave is linearly polarised when it oscillates in a single plane only; it is circularly polarised when the plane of oscillation rotates with time, but waves only oscillate in that plane.

When referring to polarised electromagnetic waves, by convention, we refer to the electric field polarisation.

A polariser blocks waves that do not oscillate along the polarising axis. Electric field waves that are parallel to the polarising axis will be transmitted while those that are perpendicular to the polarising axis will be blocked. For oscillations not parallel or perpendicular to the polarising axis, they can be resolved into the two axes. Light that emerges from a polariser will be polarised along the polariser's polarising axis.

The intensity of polarised light after passing through a polariser \begin{equation}I = I_0\cos^2\theta\end{equation} where \(\theta\) is the angle between the plane the light is polarised in, and the polariser's polarising axis.

Longitudinal waves cannot be polarised as the direction of oscillation of particles is already in a single plane (parallel to the direction of wave propagation), and they will not be restricted by the polarising axis.
\section{Determination of \(f\) and \(\lambda\)}
Sound waves create pressure differences in the air that can be detected and converted into electrical signals by a microphone, which is connected to the Y-input of a cathode ray oscilloscope to display the electrical signal. The time-base should be adjusted to a suitable sweep frequency so a sinusoidal trace can be displayed. The period of the trace can be read off after determining the scale of the time-base.

To determine the wavelength of a sound, use a reflector set perpendicularly to the direction the sound is coming from, which will form a stationary sound wave. Use a microphone connected to a cathode ray oscilloscope to find a point (a displacement node) where maximum amplitude is detected on the CRO. Mark this point. Then find the next adjacent point where there is maximum amplitude, and mark this point. Measure the distance between the two marked points and double it; this is the wavelength of the sound wave.
\end{document}