% LAST EDIT: Wed May  4 11:40:52 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Tue May  3 14:14:44 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Fri Apr 29 15:07:10 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Thu Apr 28 12:11:30 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Tue Feb 15 14:23:58 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Mon Feb 14 14:03:32 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Sun Feb 13 19:55:39 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Tue Nov 16 10:51:39 1993 by Mario Suedholt (kreusa!fish) 
\chapter{Programming in the Small}
\label{chap:small}
\novice
In functional languages the algorithms are expressed in terms of
functions---as the name ``functional programming'' already implies.
In this chapter we will explain how to declare and define functions
(Section \ref{sec:fun}) and how to use functions to express algorithms
(Section \ref{sec:expr.simple}).
We will also describe the rules for scoping and visibility of
names (Section \ref{sec:scope}).

\medskip
This chapter is called ``Programming in the Small'' because functions
are used to structure a program in a fine grain.
There are also features for  structuring a program in a coarse grain, which
means summarizing several functions (and data types) in structures
of their own. 
This will be explained in Chapter \ref{chap:large}: ``Programming in
the Large''.
\medskip

The examples in this chapter are generally taken from the two example 
programs,
\pro{HelloWorld} and \pro{Rabbits} (see Chapter
\ref{chap:example}:~``A first Example''), for the novice, and from
\pro{Expressions} (see Appendix \ref{app:expressions}) for the more
advanced features.
Before reading the advanced paragraphs you should first read about data
types  (see Chapter \ref{chap:types}: ``Types''), because the program
``\pro{Expression}'' uses a lot of data type definitions and the
algorithms are based on these.


\section{Declaration and Definition of Functions}
\label{sec:fun}
\novice
Functions are the basis of functional programming and they are the
only way to express algorithms in purely functional languages
like \opal.
Although traditional imperative languages  generally also  offer
functions, their usage is  restricted by several constraints.

In \opal\ functions are much more general and there is  in fact no
difference between functions and ordinary values as is the case in
imperative languages.
Both can be used in exactly the same way (this is sometimes
apostrophized as
``functions as first-class-citizens'').
From now on we will just say ``object'' if we don't want to
distinguish between functions and ordinary elements of data types.

\medskip
To write a function you perform two steps: you have to declare and you have
to define the function. 
Both steps will be explained in the following.


\subsection{Declaration of Functions}
\label{sec:fun.decl}
\novice The declaration tells about the {\em kind\/} of arguments and results
of a function.
It does not fix what the function will do (this is the task of the
specification)
% as \opal\ does not support specifications in the
%current release we won't mention them any further
or how this will be done (this is the object of the definition; see below).

\medskip
A function declaration is introduced by the keyword \pro{FUN},
followed by the name of the function, a colon and the functionality of
the function. 
 The declaration
\begin{prog}
        FUN rabbits : nat -> nat
\end{prog}
declares the function named \pro{rabbits}, which will take one natural
number as argument and deliver a natural number as result.

The argument (and also the result, see below) could be tuples:
\begin{prog}
        FUN add : nat ** nat -> nat
\end{prog}
This means the function \pro{add} will take two natural numbers as
arguments and deliver one natural number as result. 

Remember, a declaration does not say  anything about what the
function will do. 
The function \pro{add} might deliver as  result the minimum of the
two arguments; this would be rather contra-intuitive and should therefore
be avoided.

 The arguments may be missing altogether as in
\begin{prog}
        FUN main : com
\end{prog}
This means the function \pro{main} takes no argument, and in this case
we say \pro{main} is a constant of the sort \pro{com} (which means
\pro{command}; see Chapter \ref{chap:IO}: ``Input/Output in OPAL'' for
details about commands).

 The sorts of arguments and results need not to be the
same. The function
\begin{prog}
        FUN ! : string ** nat -> char
\end{prog}
as declared in the library structure \pro{StringIndex}  takes as
arguments a string and a natural number and delivers a character.

Remember that graphical symbols are allowed as identifiers and that
the space between ``\pro{!}'' and  ``\pro{:}'' is very
important (see Section \ref{sec:ide} if you'd  forgotten about that).

\medskip
As you could see above, the functionality is always expressed in terms
of sorts. 
These sorts must be known in the structure, i.e.~they must be either
 imported or declared in the structure.

\advanced  Arguments and results of a function could be much
more general than explained above.

Thus the result of a function could also be a tuple. 
This might be useful, e.g., in a function
\begin{prog}
        FUN divmod : nat ** nat -> nat ** nat
\end{prog}
which returns the quotient and the remainder of a division
simultaneously (on how to select the elements of a tupled result, see
Section \ref{subsec:objdecl}: ``Object Declarations'').

\medskip
\experienced Theoretically, the number of arguments is unlimited; in the current
implementation it is restricted to 16. 
This is not a serious restriction, because  16 is
quite a large amount.
IF you really do need more parameters, you can combine several
arguments into a new data type to reduce the number of arguments. 

\subsubsection{Higher-Order Functions}
\label{sec:higherOrderFunctions}

\advanced You can have functions as arguments and results too.
These functions are called higher-order functions.
Usually higher-order functions are supported only very rudimentarily
in traditional languages, if at all.

 A function to compute the integral may be declared like this:
\begin{prog}
        FUN integral : (real -> real) ** real ** real -> real
\end{prog}
which means that the first argument is the function to be
integrated and the second and third argument are real numbers defining
the lower and upper bound of the integral.

Another example can be found in the program \pro{Expression}:
\begin{prog}
        FUN doDyop : dyadicOp -> nat ** nat -> nat
\end{prog}
The function \pro{doDyop} takes an element of the sort \pro{dyadicOp}
and delivers a function which itself takes two numbers as arguments and
delivers one number as result.

The symbol \pro{->} is right-associative. This means the declaration
above is equivalent to 
\begin{prog}
        FUN doDyop : dyadicOp -> (nat ** nat -> nat)
\end{prog}
and the parentheses may be omitted.

This process of functions as arguments or results could be continued.
There is no limit to the ``nesting depth''.


\subsubsection{Currying}
\label{sec:currying}
\advanced
As known from theoretical computer science and mathematics, it is
always possible to transform a function which takes more than one
argument into a function which takes only one argument and delivers a
function as result, without altering the semantics of the function.
This process is called {\em currying\/}.
\begin{prog}
        FUN + : nat ** nat -> nat
        FUN + : nat -> nat -> nat
\end{prog}
The second  variant is the curried version of the first.

In some functional languages this transformation is done automatically and the
two declarations are recognized as identical.

In \opal\ the two declarations are distinguished and need their own
definitions. 
Each variant has its own advantages:
with the first the function \pro{+} could be used as
infix-operator, whereas with the second one you can define a function,
e.g.~\pro{+(3)}, a brand  new function which will add three to
its only remaining parameter.
This can be useful, for example in conjunction with other higher-order
functions, such as  apply-to-all on sequences.

On the other hand, if you have used the uncurried version, you can use
sections and lambda expressions (see 
\ref{sec:sections} and \ref{subsec:lambda}) to do a
``currying on the fly'', i.e.~to
define a temporary, auxiliary function with partially supplied
parameters.
It is therefore simply  a matter of taste, whether you prefer the
curried or the uncurried version.

\subsection{Definition of Functions}
\label{sec:fun.def}
\novice
The definition of a function defines how the function works, i.e.~it
represents the real algorithm.

The definition of a function consists of a header on the left side of
the ``\pro{==}'' and a body on the right side. The function
\pro{rabbits} will be defined by
\begin{prog}
        DEF rabbits (n) == {\em \verb+<<+ body \verb+>>+\/}
\end{prog}

The number of parameters (``\pro{n}'') must match the number of
parameters given in the declaration of the function (in this example
one argument). 
In the body the name \pro{n} will be visible (see next section). 
And due to the declaration of \pro{rabbits} it will stand for an
object of type \pro{nat}.
The parameters are used to reference  the arguments of a concrete call
of \pro{rabbits} in the body. 

The body of a function definition is an expression. We will explain
expressions in Section \ref{sec:expr.simple}.

The headers of the other examples from the previous section
(``Declaration of Functions'') will be something like
\begin{prog}
        DEF main == {\em \verb+<<+ body \verb+>>+\/}
        DEF !(str, n) == {\em \verb+<<+ body \verb+>>+\/}
\end{prog}

They define \pro{main} to have no parameters and \pro{!} to have two
parameters, named \pro{str} and \pro{n}, which can be used in the body
of the definition.
\medskip

The functionality%
\footnote{Functionalities are required for checking
  the correctness of expressions; see Section \ref{sec:expr.simple}
  below.}
of the parameters can be derived from the declaration of the
corresponding function.
Function ``\pro{!}'' is declared as \pro{FUN ! :string**nat->char}.
Therefore the first parameter, \pro{str}, has functionality \pro{string}
and the second, \pro{n}, has functionality \pro{nat}.
\medskip

\advanced There is a bunch of other ways to notate the header
of a function definition. First of all you can use infix-notation
which is quite similar to infix expression \ref{subsec:func.appl}. 
You could  also write
\begin{prog}
          DEF str ! n == {\em \verb+<<+ body \verb+>>+\/}
\end{prog}
\noindent instead of the definition above.

Furthermore, you can use pattern-matching to define functions. Pattern
matching depends on free types and will be explained in Section
\ref{sec:patternType}: ``Pattern-Matching''.

\medskip
Higher-order functions with functions as arguments are defined the
same way as first-order functions. 
The function \pro{integral} (see above) could be defined as
\begin{prog}
        DEF integral (f, low, high) == {\em \verb+<<+ body \verb+>>+\/}
\end{prog}
where \pro{f} denotes the function to be integrated.

The functionality of the parameters is naturally extended: \pro{f} has
functionality \pro{real->real}, \pro{low} and \pro{high} have
\pro{real} respectively.

Higher-order functions with functions as results will be defined with
additional parameters for the parameters of the result function.
The function \pro{FUN doDyop : dyadicOp -> nat ** nat -> nat} could be
defined as 
\begin{prog}
        DEF doDyop (op)(l, r) == {\em \verb+<<+ body \verb+>>+\/}
\end{prog}
In this case \pro{op} is a dyadic operand and \pro{l} and \pro{r} are
the natural numbers as arguments for the resulting function.

More concretely, this means you define this function as 
\begin{prog}
        DEF doDyop (op)(l, r) == IF op addOp? THEN +(l,r)
                                 \dots
\end{prog}
The functionality of the parameters again are naturally extended: \pro{op}
has functionality \pro{dyadicOp} and \pro{l} and \pro{r} have \pro{nat}.

But you can even shorten this header.
 If you want to define a function \pro{myadd : nat ** nat -> nat} with the
same semantics as the standard definition of addition (i.e. renaming
the function \pro{+}) you can do this by  writing:
\begin{prog}
        DEF myadd (a,b) == +(a,b)
\end{prog}
It is not true however, that for each parameter in the declaration there
must be a corresponding parameter in the definition.
As long as the type remains correct you can omit the parameters.
\begin{prog}
        DEF myadd == +
\end{prog}
On the right side there is only one identifier with the functionality
\pro{nat**nat->nat}, and the left side has the same. 
So this definition is correct. 

 Omission of parameters can only be done on whole tuples.
This means you cannot leave out \pro{b} alone. You must write
either all or none of the parameters of a tuple.
And---of course---you can only omit trailing tuples.

\medskip
This scheme is especially useful with higher-order functions. 
You can shorten the definition of the function \pro{ doDyop} to  
\begin{prog}
        DEF doDyop (op) == IF op addOp? THEN +
                           \dots 
\end{prog}
where the function yields---depending on the operation \pro{op}---just
one of the well-known functions \pro{+, -, *, /}.

\experienced
Omitting parameters entails one small catch.
In \opal\ all constants are evaluated only once during the initialization
phase of the program. 
Constants are  function {\em definitions\/} without parameters. 
Therefore the second definition of \pro{myadd} (see above) is a
constant definition (it does not depend on arguments), whereas the
first is a function definition (it has two arguments).

In general this won't make any difference and you can use the two as
you please.
 But you should note, that the definition of constants
must be acyclic, i.e.~you can't use a constant in its own definition,
neither direct nor transitive.

Moreover there are rare cases where the time of evaluation of
functions and arguments might be significant.
Sometimes it is even useful to add an empty argument tuple to delay
the evaluation of a function call until later:
\begin{prog}
        FUN f : nat ** nat -> () -> res
\end{prog}
In this case the function call \pro{LET g == f(1,2) IN \dots} won't be
evaluated, but yields a closure (i.e.~a new function) which could be
submitted  as an argument or stored in a data structure.

Only if this closure is applied with the empty tuple (e.g.~\pro{g()}), then
the call  \pro{f(1,2)} is evaluated.
Using this method you can simulate lazy execution within the strict
language \opal.


\section{Scoping and Overloading}
\label{sec:scope}
\novice
Scoping and overloading generally involve very complex rules.
Scoping means: I have declared an object somewhere in  the
program text and want to know if this object is known (accessible)
somewhere else.
If the object is accessible, we say it is {\em visible\/} at this
location.

Overloading means using the same identifier for different objects.

Concerning scoping and overloading in \opal\ you have to  distinguish
two different kinds of objects
\begin{itemize}
\item global objects
\item and local objects.
\end{itemize}
Global objects are all imported objects as well as all functions and sorts
declared in the structure, either in the signature or in the
implementation part. 

Global objects may have the same identifier as long as they can still be
distinguished by annotations (see Section \ref{sec:name} for details).
This means that if two global objects differ in at least one of their
identifiers, their origins, their instantiations  or their kinds (sort or
functionality) you can use both objects side by side.

If they are the same in identifier and all possible annotations, the
compiler will perceive them as identical.
This means it is possible, for example, to import the same object several times.

Local objects are parameters, lambda- and let-bound variables (see
Section~\ref{sec:expr.simple}).
They cannot be annotated with origin or instantiation.

\important The names of local objects must be disjoint within their visibility
region, i.e.~they cannot be overloaded at all.

\medskip
\novice The rules for scoping (i.e.~visibility) are fairly simple in \opal.
A signature part cannot have local objects.
In the signature part the only  visible objects are those which are 
imported or declared in the signature part.
\medskip

Throughout  the implementation part, all global objects from the signature part
and the implementation part are visible.

\medskip
Parameters of function definitions are visible throughout the function
definition; lambda- and let-bound variables are visible only within
their expressions. 

\important If a local and a
global object have the same identifier, the global object will be invisible
as long as the local object is visible, {\em even if the identifier is
  annotated\/}. In this case the annotation on local objects is ignored!
This does not apply to sort-names, because these can be identified by their
position in the program text.

\section{Expressions}
\label{sec:expr.simple}
\novice 
In this  section we will explain how to construct
the body of a function definition.
First we introduce the fundamental expressions essential even for
trivial programs; these are atomic expressions, tupling of expressions,
function applications and case distinctions. 
Then we will discuss the more elaborate features which improve the
power of  functional programming and the readability of \opal\ 
programs: lambda abstractions, sections and local declarations. 

\medskip
A basic issue regarding correctness of expressions is the
functionality of an expression.
The main context condition for expressions demands that
functionalities must fit together.
Therefore we will also discuss the functionality of each expression
and the conditions it must satisfy.


\subsection{Atomic Expressions}
\label{subsec:atomic}
\novice
The most simple expressions are atomic expressions. 
There are two kinds of atomic expressions: identifiers and
denotations.

Identifiers denote objects (i.e.~functions, local objects  and
elements of data types) which have to be visible\footnote{see
  explanation of visibility above.} when the identifier
is used. 

Examples are \pro{rabbits}, \pro{0}, \pro{=}, \pro{+} and
\pro{generation} (all are taken from the example program
\pro{rabbits}). 
In the case of a global identifier the functionality is
declared in the identifiers declaration; the
functionality of a local identifier can  be derived either from the declaration of the
corresponding function (for parameters; see Section
\ref{sec:fun.def}) or from the context (for local declarations and
lambda-bound variables; see Sections \ref{subsec:objdecl} and \ref{subsec:lambda} for details).

\medskip
Denotations are special notations for denoting arbitrary objects.
They are enclosed in quotation marks and are often used to
represent text, e.g. ``\pro{Hello World}'', but you can write conversion
routines to represent just about every data object using denotations.
The corresponding conversion functions for natural numbers, integers and reals are
predefined in the standard library.

These conversion functions are usually named ``\pro{!}''.
For example \pro{"1234"!'Nat} represents the natural number 1234
(remember,  \pro{'Nat} is an annotation defining the origin of
``\pro{!}'' being the structure \pro{Nat}).
More about denotations can be found in Section \ref{denotations}.

Denotations always have functionality ``\pro{denotation}''.

\subsection{Tuples}
\label{sec:tuples}
\novice
Expressions (any expression, not only atomic ones) can be grouped
together as tuples by enclosing them in parentheses:
\begin{prog}
        ("Hello World", 1, +(5,3))
\end{prog}

\noindent is a tuple with three elements, a denotation, a number and a function
application.
Tuples are used mainly to unite the arguments of a function
application, e.g. in \pro{+(3, 5)}.

Tuples are always flat in \opal.
That is, you can write a nested tuple like \pro{(a, b, (c, d), e)} which
seems to consist of four elements, the third being a tuple itself.
But in \opal\ this is identical with the tuple \pro{(a, b, c, d, e)}.

A tuple may contain only one element while the empty tuple is allowed
only as an argument of function calls.

\advanced  Flat tuples allow some compact notations on using
functions which return tuples as results. 
Suppose you have a function \pro{f:nat**nat**nat->nat} 
which takes three arguments.
Remember the function \pro{divmod:nat**nat->nat**nat} which
returns a tuple of two numbers.

You can write \pro{f(3, divmod(22,5))} which is the same as
\pro{f(3, (4, 2))} (the function call \pro{divmod(22,5)} being
evaluated and---because tuples are flat---this is a correct call of 
\pro{f(3, 4, 2)}). 


\subsection{Function Applications}
\label{subsec:func.appl}
\novice
A function application consists of two expressions, the second being
a tuple, e.g.~\pro{+(3,4)} or \pro{rabbits(generation-1)}.
The tuple consists of the arguments of the functions call.

The functionality of the first expression must be a function
functionality consisting of parameters and a result.
The functionality of the tuple must match the functionality parameters.
The functionality of the whole function application is the result.

In the example above the first expression is ``\pro{+}'', which has a 
functionality of \pro{nat**nat->nat}.
The second expression is the tuple ``\pro{(3,4)}'' with
functionality \pro{nat**nat}, which matches the parameters of
``\pro{+}''.
The functionality of the application is \pro{nat}, the result part of the
functions functionality.

\advanced There are several variations on the notation of function
applications.
Each function application could also be written as a postfix-operation,
i.e. just exchange the two expressions: \pro{(3,4)+}.

In this case the parentheses around a tuple containing only one
element may be omitted.
Postfix-operations are often used to shorten the notation for
conversions like \pro{"Hello World"!} which is the same as
\pro{!("Hello World")}.

Postfix-operations are also known from mathematics;for example the
factorial is usually written as $3!$.

\medskip
Function applications may also be written as infix-operations:
\pro{(3)+(4)}.
Again you can omit the parentheses if the tuples only contain one
element. This results in the usual notation for mathematical
expressions: \pro{3+4}.

In general graphical symbols like \pro{+}, \pro{*}, \pro{!}, \pro{::}
or \pro{+\%} are used as function names if the function is intended to
be used as an infix- or postfix-operation, but this is not necessary.

The definition and the application of a function are independent.
You can define a function using pattern-based definitions and
infix-notation and you can still apply the function in traditional
prefix style.

\medskip
Infix-notation could also be used with more than two arguments:
\begin{prog}
     f(a,b,c); f(a, (b,c)); a f (b,c); (a) f (b,c); (a,b) f c; (a,b,c)f 
\end{prog}
are all the same function application.
\bigskip

You could also nest infix-notation, but there is  one little problem
with this very flexible notation. 
Because the analysis of arbitrary infix notations is very expensive,
you should use at most 5--6 infix operations without bracketing. 
If your expression is larger, you should enclose subexpressions in
parentheses.
This will  also enhance readability.

This problem seems ridiculous, especially as even traditional
imperative languages can deal with any number of infix-operations.
But remember a ``\pro{+}'' in \opal\ could be any function, including a
user-defined function or a function computed at run-time (in contrast to
traditional languages), and this much more general problem has not
been resolved satisfactorily to date.
\medskip

\advanced There is one more problem with arbitrary infix-notation. 
As the compiler cannot have any knowledge about precedence rules
between the different functions (in contrast to C, for example), 
it can use only
the various functionalities to detect  which applications were
intended by the programmer. 

A typical example is the construction of a list (using
\pro{FUN~::~:data**seq->seq}): 
\begin{prog}
          1 :: 2 :: 3 :: 4 :: <>
\end{prog}
\noindent Due to the functionalities, the compiler will recognize this as:
\begin{prog}
          1 :: (2 :: (3 :: (4 :: <> )))
\end{prog}

If the compiler cannot resolve this problem with a unique solution,
you will receive an error message like \pro{ambiguous infix
  application} and you should insert some parentheses to
help the compiler.

\important If you are using the same function several times in nested
infix-notation, the compiler will assume right-associativity.

\noindent The concatenation of several denotations
\begin{prog}
        "ab" ++ "cd" ++ "ef" ++ "gh"
\end{prog}
will be recognized as 
\begin{prog}
        "ab" ++ ("cd" ++ ("ef" ++ "gh"))
\end{prog}
{\bf WARNING:} This is contra-intuitive with respect to normal mathematics!
The expression \pro{20-10-5}
yields 15 instead of 5 as expected because the compiler assumes
right-associative functions and ``\pro{-}'' is not right associative!
In this case you must supply parenthesis: \pro{(20-10)-5}.
\medskip

\advanced
The application of higher-order functions is just the same as for
first-order functions.
Remember the functions
\begin{prog}
        FUN integral:(real->real) ** real ** real -> real
\end{prog}
and
\begin{prog}
        FUN doDyop: dyadicOp -> nat ** nat -> nat
\end{prog}

\pro{integral} will be applied as
\begin{prog}
        integral(sin, 0, 1)
\end{prog}
 for example to compute  the integral over the sinus function between 0 and
1.
Remember, you also can write this application as infix or postfix, e.g.
\begin{prog}
        sin integral (1, 2)
\end{prog}

The function \pro{doDyop} expects one argument of functionality
\pro{dyadicOp}. A correct application will be 
\begin{prog}
        doDyop(addOp)
\end{prog}
You could also write it as postfix\footnote{This time you cannot use
  infix-notation, because there is only one argument.}:
\begin{prog}
        addOp doDyop
\end{prog}

The result of this application is a function with functionality
\pro{nat**nat->nat}.
Thus you can apply this function to two numbers:
\begin{prog}
        doDyop(addOp)(3,4)
\end{prog}
Function application associates to the left, i.e.~the expression
above is the same as 
\begin{prog}
        (doDyop(addOp))(3,4)
\end{prog}

This application could also be written as
\begin{prog}
        (addOp doDyop)(3,4)
\end{prog}
for example.

But note that a function used as an infix-operator
must be an identifier. 
Therefore you cannot write
\begin{prog}
        3 (addOp doDyop) 4     -- this is illegal
\end{prog}
because  \pro{(addOp doDyop)} is no identifier.

\medskip

This example also illustrates another feature. 
The first expression (i.e., the function of the function application)
need not be a name. 
It can be any expression including another function
application (as above), a case distinction, a lambda abstraction or an
object declaration.
The only context condition is that it must have a functions
functionality.

\subsection{Case Distinctions}
\label{subsec:cases}
\novice Case distinctions are used to control the evaluation of the program.
Depending on the value of conditions, the program will continue to
evaluate different parts.

A case distinction in \opal\ is written as  
\begin{prog}
        IF cond_1 THEN part_1
        IF cond_2 THEN part_2
        ...
        IF cond_n THEN part_n
        FI
\end{prog}
\pro{cond\_1} \dots \pro{cond\_n} and \pro{part\_1} \dots \pro{part\_n}
are arbitrary expressions including function applications, other case
distinctions or local declarations.

\pro{cond\_1} \dots \pro{cond\_n} are called guards and all of them must
have functionality \pro{bool}.
\pro{part\_1} \dots \pro{part\_n} must have identical functionalities
and this common functionality is also the functionality of the case
distinction. 

Let us have a concrete example. The function \pro{rabbits} is defined
as:
\begin{prog}
          DEF rabbits(generation) ==
              IF generation = 0 THEN 1
              IF generation = 1 THEN 1
              IF generation > 1 THEN rabbits(generation - 1) 
                                     + rabbits(generation - 2)
              FI  
\end{prog}
The guards are infix function applications, each of functionality
\pro{bool}.
Each of the THEN-parts has functionality \pro{nat} which is the
functionality of the case distinction and also of the result of the
function.

The semantics of a case distinction is:      
evaluate one of the guards. 
If the guard yields false, forget about this case and try
another one.
As soon as a guard yields true, stop searching and evaluate the
corresponding THEN-part.

If none of the guards yields true, the value of the case distinction is
undefined and the program will terminate with an error message.

\important  The order the guards are evaluated in is selected by the
compiler! It does not depend on the order in which the guards are
denoted in the program!

\novice The example above may be evaluated as follows (supposing
\pro{n} has the value~\pro{0}):
first the program might check the last guard. \pro{0>1} yields
\pro{false}, therefore the next guard will be checked;  let us now
assume it to be the  first guard.
\pro{0=0} yields \pro{true}.  The corresponding THEN-part
will therefore be evaluated, yielding \pro{1} and the value of the case
distinction is computed as \pro{1}.

\medskip
If the guards are not disjoint there is no specification as to  which THEN-part
will be evaluated.
Sometimes this is desirable, as in
\begin{prog}
        DEF maximum(n, m) == 
                 IF n <= m THEN m
                 IF m <= n THEN n FI
\end{prog}
In this case the program will always check only one guard if the
values of \pro{n} and \pro{m} are the same.

But you should ensure that the result is the same in any possible
case. Otherwise your program might behave unexpectedly.

\medskip
Remember that \opal\ is a strict language and the guards are just
expressions.
If you have a condition consisting of two parts and the second is
valid only if the first yields \pro{true}, you cannot combine the two
parts with an \pro{and}-function!

There is a well-known example for this fault:
given a list of numbers, you want to compare the first element of the
list with some value.
The first part of the condition checks if the list is not empty
(because otherwise you can't access the first element) and the second
part does the comparison.

It is wrong to write
\begin{prog}
     IF (~(list empty?) and (ft(list) = 0)) THEN ... -- this is wrong
     ...
     FI
\end{prog}
because {\em both\/} arguments of the \pro{and} will always be
evaluated.
This results in a runtime-error if the list is empty.

Instead you have to split the condition into two guards in a nested
case distinction:
\begin{prog}
        IF ~(list empty?) THEN
                    IF  ft(list) = 0 THEN ...
                    ...
                    FI
        ...
        FI
\end{prog}
This could be abbreviated to the short-hand notation
\begin{prog}
     IF (~(list empty?) ANDIF (ft(list) = 0)) THEN ...-- this is correct
     ...
     FI
\end{prog}
There is also a corresponding \pro{ORIF}.
Both operations evaluate their first argument.
 Only if this evaluation yields \pro{true} for
\pro{ANDIF} or ~\pro{false} for \pro{ORIF}, the second argument will
be evaluated too.
\bigskip

\advanced There are two notational variations for case distinctions.
Firstly, you can add an ``\pro{OTHERWISE}'' between any two cases.
Then the program will first check all guards in front of the
\pro{OTHERWISE}, and 
only if all of these guards yield \pro{false} will it continue with
the guards following the \pro{OTHERWISE}.
\smallskip

\noindent The expression 
\begin{prog}
        IF cond_1 THEN part_1
        ...
        IF cond_n THEN part_n 
        OTHERWISE 
        IF cond_n+1 THEN part_n+1
        ...
        IF cond_n+m THEN part_n+m 
        FI 
\end{prog}
is exactly the same as 
\begin{prog}
        IF cond_1 THEN part_1
        ...
        IF cond_n THEN part_n 
        IF ~(cond_1 or ... or cond_n) 
           THEN 
              IF cond_n+1 THEN part_n+1
              ...
              IF cond_n+m THEN part_n+m
              FI
        FI  
\end{prog}

Secondly, you can add an ``\pro{ELSE expr}'' after the last case of a
case distinction. 
If the evaluation of all guards yields \pro{false}, the ELSE-expression
will be evaluated instead of the program terminating with an error.

\smallskip
\noindent The case distinction
\begin{prog}
        IF cond_1 THEN part_1
        ...
        IF cond_n THEN part_n 
        ELSE expr
        FI
\end{prog}
is the equivalent of 
\begin{prog}
        IF cond_1 THEN part_1
        ...
        IF cond_n THEN part_n 
        OTHERWISE
        IF true THEN expr
        FI
\end{prog}
\bigskip

\advanced In addition to the fundamental expressions  described above,
\opal\ offers three more constructs for defining expressions.
These are  lambda abstractions, sections and local declarations.
Lambda abstractions and local declarations also enlarge the number of
local objects by new objects  
which are visible inside their expressions (see below). 

\subsection{Lambda Abstraction}
\label{subsec:lambda}
\advanced
Lambda abstractions define auxiliary functions without a name.
The notation is
\begin{prog}
        \LAMBDA{}x,y. expr 
\end{prog}

This lambda expression defines a function which takes two arguments.
The parameters are called \pro{x} and \pro{y}.
These new local objects are visible only inside \pro{expr}.
The functionality of \pro{x} and \pro{y} could either be annotated or it
will be derived automatically from their usage in \pro{expr}.

\smallskip\noindent Let us have a concrete example: 
\begin{prog}
        \LAMBDA{}x.x=3
\end{prog}
defines a function with functionality \pro{nat -> bool}, which compares
a number to 3.

You can apply this function: for example \pro{(\LAMBDA x.x=3)(4)} yields
\pro{false}.
Or you can use it in an object declaration:
\begin{prog}
        LET equalThree == \LAMBDA{}x.x=3
        IN ...
\end{prog}
This way you receive a named auxiliary function, although
lambda abstractions cannot be recursive.

Very often  lambda abstractions are used to  submit an auxiliary
function to  higher-order functions as arguments, e.g. 
 \begin{prog}
         LET a == pi
             b == e
             c == "-5.0"!
         IN integral(\LAMBDA{}x.a*x*x + b*x + c, 0, 1)\end{prog}
computes the integral $\int_{0}^{1}a x^2 + b x + c$ with $a=\pi$,
$b=e$ and $c=-5$.
\bigskip

Lambda abstractions may also be nested to define higher-order
functions and they can be used to define ordinary named functions:
The definitions
\begin{prog}
        DEF f(a,b)(c) == expr
\end{prog}
and
\begin{prog}
        DEF f == \LAMBDA{}a,b. \LAMBDA{}c. expr
\end{prog}
are equivalent and each of them defines a function with functionality, \\
e.g.~\pro{FUN f:s1**s2->s3->s4}.

As in  pattern-matching (see Section \ref{sec:patternType}), an
underscore character may be used as a wildcard in a lambda
abstraction;  the meaning is that there is a parameter for a
(lambda-defined) function, 
but I am not interested in its value.


\subsection{Sections}
\label{sec:sections}
\advanced Sections are a shorthand notation for simple lambda
abstractions.
You will often  need a function where some arguments should not yet be
fixed.

As an example you may think of a function that adds the value of 3 to
each element of a sequence of numbers \pro{s}.
Using the apply-to-all-function ``\pro{*}'', this could be written with lambda
abstraction as
\begin{prog}
        * (\LAMBDA x. 3+x)(s)
\end{prog}
or in shorthand form with section as
\begin{prog}
        * (3 + _) (s)
\end{prog}
Note: don't forget the separator between ``\pro{+}'' and ``\pro{\_}''.
Otherwise you apply the (probably undefined) function ``\pro{+\_}'' on the
argument 3.

Underscores represent arguments of a function call which are
missing at the moment, but will be supplied later.

Sections could be regarded as a generalization of currying, because not
only trailing (as with currying) but also arbitrary arguments can be
postponed until later.
 
In detail, the expressions
\begin{prog}
        f(a,b,c,d,e);    f(a,b,\_,d,\_)(c,e);    (f(a,\_,\_,d,\_))(b,\_,e)(c)
\end{prog}
are all the same.


\subsection{Local Declarations}
\label{subsec:objdecl}
\advanced
Local declarations can be used to structure the definition of a
single function and to introduce abbreviations.

\smallskip\noindent
Local declarations are written as
\begin{prog}
        LET o_1 == expr_1
            o_2 == expr_2
            ...
            o_n == expr_n
        IN expr
\end{prog}
or
\begin{prog}
        expr WHERE o_1 == expr_1
                   o_2 == expr_2
                   ...
                   o_n == expr_n
\end{prog}
The two notations are equivalent.

The additional local objects \pro{o\_1} \dots \pro{o\_n} are visible in
the expression \pro{expr} and in all expressions \pro{expr\_1} \dots
\pro{expr\_n}.

A declaration \pro{o\_i == expr\_i} is said to depend on the
declaration \pro{o\_j == expr\_j} if \pro{o\_j} is used in \pro{expr\_i}.
The ordering of the declarations is irrelevant, but there must  not be
cyclic dependencies between the declarations.

\smallskip\noindent The expression \pro{expr} will be as long as
possible; in the local declaration
\begin{prog}
        LET a == ...
        IN f(a)(e_2)
\end{prog}
for example, the \pro{a} will be visible in the whole expression
\pro{f(a)(e\_2)}, not only in the expression \pro{f}.

The semantics of local declarations could be explained with lambda
abstraction. Assuming the declaration \pro{o\_1 == expr\_1} does not
depend on any of \pro{o\_2} to  \pro{o\_n},  then the local declaration
\begin{prog}
        LET o_1 == expr_1
            o_2 == expr_2
            ...
            o_n == expr_n
        IN expr
\end{prog}
is equivalent to 
\begin{prog}
        (\LAMBDA o_1. LET o_2 == expr_2
                 ...
                 o_n == expr_n
                 IN expr           ) (expr_1)
\end{prog}
The declaration that does not depend on any other must not necessarily be
the first one, because ordering of declarations is irrelevant.
But because the dependency between the declarations must be acyclic,
there is always a declaration, that does not depend on any other.

\important Note that local declarations are strict. Therefore a
declaration like 
\begin{prog}
        LET cond     == ...           -- dangerous pgm style
            thenpart == ...
            elsepart == ...
        IN IF cond THEN thenpart ELSE elsepart FI
\end{prog}

\noindent will not behave as expected, because \pro{thenpart} and
\pro{elsepart} are {\em always\/}  evaluated  due to the strict semantics
of local declarations.


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