% LAST EDIT: Tue May  3 13:16:12 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Wed Apr 27 17:08:06 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Tue Feb 15 10:46:39 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Sun Feb 13 17:51:26 1994 by Juergen Exner (hektor!jue) 
% LAST EDIT: Tue Jan 12 16:07:49 1993 by Juergen Exner (hektor!jue) 
\chapter{A First Example}
\label{chap:example}
\novice
Before starting with the precise description of \opal,  let us first present
a short overview using two introductory examples.

The first is the famous ``HelloWorld'' program. 
The second (a little bit more complex and incorporating simple interactive I/O)
calculates the rabbit numbers invented by the Italian mathematician
Fibbonacci.

These examples are intended only as  short survey and so we won't
discuss all the details; this will be left to the following chapters.

\advanced A third example---not included in this tutorial---can be found in
``The Programming Language \opal\ '' \cite[p.~27]{Pe}. 
It displays the contents of a named file on the terminal.

 A fourth example (``expression'') will be included in the
appendix. 
It simulates a small pocket calculator and illustrates user-defined
types, higher-order functions and more complex interactive I/O.

\medskip
\novice
{\mbox{\bf Note:}} All these examples are included in the
\opal\ distribution and can be found in the subdirectory \pro{examples}.

\section{``Hello World''}
\novice
In the world of programming, writing the words ``Hello World'' on the
terminal seems to be absolutely imperative.
An \opal\ program which does  this would probably look like Figures 2.1
and 2.2.
\begin{figure}[htbp]
  \leavevmode
  \begin{prog}
    1    SIGNATURE HelloWorld
    2    IMPORT  Void            ONLY void
    3            Com[void]       ONLY com
    4    FUN hello : com[void]    -- top level command\end{prog}
  \caption{HelloWorld.sign}
\end{figure}

\begin{figure}[htbp]
  \leavevmode
  \begin{prog}
    1    IMPLEMENTATION HelloWorld
    2    IMPORT  DENOTATION      ONLY denotation
    3            Char            ONLY char newline
    4            Denotation      ONLY ++ \% 
    5            Stream          ONLY output stdOut 
    6                      write : output ** denotation -> com[void]
    7    
    8    -- FUN hello:com[void] (already declared in Signature-Part)
    9    DEF hello ==
    10        write(stdOut, "Hello World" ++ (\%(newline)) )
  \end{prog}
  \caption{HelloWorld.impl}
\end{figure}

In this example the program consists of one structure named
\pro{HelloWorld}, which  is stored physically in two files
(\pro{HelloWorld.sign} and \pro{HelloWorld.impl}). 
The files have to be named using the name of the structure plus the
extension \pro{.sign} or \pro{.impl}.
So the possible names for structures are restricted due to the naming
conventions of the  file system used.

The signature part declares the export interface of a structure.
In the case of a program this must be a constant (e.g.,~a function
without arguments) of sort
\pro{com[void]}\footnote{The type system will be explained in Chapter
\ref{chap:types}, instantiations ([\dots]) in Chapter
\ref{chap:large} and the I/O-system in  Chapter \ref{chap:IO}} whereby
the sorts \pro{com} and \pro{void} must be imported from their
corresponding structures \pro{Com} and \pro{Void}.

In the implementation part we need some additional sorts (\pro{denotation},
\pro{output} and \pro{char}) and operations
(\pro{stdOut}, \pro{write}, \pro{\%},\pro{++} and \pro{newline}) which
are also imported from their corresponding structures.

Line 8 is a comment line, indicated by a leading ``\pro{--}''.

The definition of the constant \pro{hello}, which was declared in the
signature part, defines this function to write a text to \pro{stdOut}
(which is a predefined constant describing the terminal).

The text consists of the words ``Hello World'' and a trailing
newline character, which is converted into a denotation with the operation
\pro{\%} and appended to the text by the function \pro{++}.
 The function \pro{++} is used as an infix operator in this example,
but this is not essential.
%
%\advanced 
%Note, that the exclamation mark ``\pro{!}'' (in this example
%used as a postfix-operator) is essential as \pro{"Hello World"} is
%only a denotation, not a string.
%The function ``\pro{!}'' converts a denotation to a string as required by
%the function \pro{write}.
%More about the differences between denotations and strings can be
%found in Chapter \ref{denotations}.
\newline\rule{5cm}{1pt}

{\small \novice 
  To compile the program you should ensure that the
\opal\ Compilation System (OCS) is properly installed at your site and
that the OCS 
directory \pro{bin} is included in your search path.
The GNU \pro{gmake} must be available too.
If you don't know how to set up  your path or if OCS is not installed,
call a local guru. 


Within the proper environment---assuming the program \pro{HelloWorld}
resides in the current working directory---you just have to type 
\begin{prog}
  >  \underline{ocs -top HelloWorld hello}
\end{prog}
to compile and link the program \pro{HelloWorld} with
top-level-command \pro{hello} and you will receive an executable
binary named \pro{hello}.
You can start this program just by typing 
\begin{prog}
  >  \underline{./hello}
\end{prog}

For more information about using OCS try 
\begin{prog}
  >  \underline{ocs help}
\end{prog}
or 
\begin{prog}
  >  \underline{ocs info}
\end{prog} 
and consult the OCS-guide ``A User's Guide to the \opal\  Compilation
System'' \cite{Ma} and the man-pages.
\newline\rule{5cm}{1pt}

\novice
 A pseudo-interpreter (oi) for \opal\ programs is also available.
Although this interpreter is not intended for complete programs, it is
very helpful in the development of separate structures as it simplifies
testing considerably. For details, see ``The \opal\ Interpreter'' \cite{Le}.
}



\section{Rabbit Numbers}
\novice
Let us have a second example. Imagine a population of rabbits which
propagate according to the following rules:
\begin{itemize}
\item In the first generation\footnote{As we are good computer scientists we
    will start numbering at 0.} there is only one young couple of
  rabbits.
\item In each following generation the former young couples become grown-ups.
\item In each generation each already grown-up couple produces one couple of
  young rabbits.
\item Rabbits never die.
\end{itemize}

To calculate the total number of couples you may combine the two
functions and you will receive the so-called Fibbonacci-Numbers. 
We will just call them {\em rabbits\/}:
\[ \mbox{\em rabbits}(\mbox{\em gen}) = \left\{ \begin{array}{ll}
1 & \mbox{if\ {\em gen\/}} = 0\\
1 & \mbox{if\ {\em gen\/}} = 1\\
\mbox{\em rabbits}(\mbox{\em gen}-1) + \mbox{\em rabbits}(\mbox{\em gen}-2) & \mbox{if\ {\em gen\/}} > 1\\
\end{array}\right. 
\]


\begin{figure}[hbtp]
  \leavevmode
  \begin{center}
    \begin{prog}
   1    SIGNATURE Rabbits
   2
   3    IMPORT  Void            ONLY void
   4            Com[void]       ONLY com
   5
   6    FUN main : com[void]    -- top level command
    \end{prog}
    \caption{Rabbits.sign}
  \end{center}
\end{figure}

\begin{figure}[hbtp]
  \leavevmode
  \begin{prog}
   1    IMPLEMENTATION Rabbits
   2
   3    IMPORT  Denotation      ONLY  ++
   4            Nat             ONLY nat ! 0 1 2 - + > =
   5            NatConv         ONLY `
   6            String          ONLY string
   7            StringConv      ONLY `
   8            Com             ONLY ans:SORT
   9            ComCompose      COMPLETELY
  10            Stream          ONLY input stdIn readLine
  11                               output stdOut writeLine
  12                               write:output**denotation->com[void]
  13
  14    -- FUN main : com[void] -- already declared in signature part
  15    DEF main ==
  16        write(stdOut,
  17           "For which generation do you want 
                        to know the number of rabbits? ") &
  18        (readLine(stdIn)    & (\LAMBDA in.
  19         processInput(in`)
  20        ))
  21
  22    FUN processInput: denotation -> com[void]
  23    DEF processInput(ans) ==
  24              LET generation == !(ans)
  25                  bunnys     == rabbits(generation)
  26                  result     == "In the "
  27                                ++ (generation`)
  28                                ++ ". generation there are "
  29                                ++ (bunnys`)
  30                                ++ " couples of rabbits."
  31              IN writeLine(stdOut, result)
  32    -- ----------------------------------------------------------
  33
  34    FUN rabbits : nat -> nat
  35    DEF rabbits(generation) ==
  36            IF generation = 0 THEN 1
  37            IF generation = 1 THEN 1
  38            IF generation > 1 THEN rabbits(generation - 1)
  39                                   + rabbits(generation - 2) FI
 \end{prog}
    \caption{Rabbits.impl}
  \label{fig:rabbits}
\end{figure}

In the example (Figure \ref{fig:rabbits})
%, shortened to the
%essential parts; the whole program will be included in appendix
%\ref{prog:rabbits}) 
this formula can be found in the definition of the
function \pro{rabbits} (lines 35--39), which is a direct
1-to-1-translation of the mathematical notation.

\advanced This direct translation is typical for functional
programming. 
In contrast to traditional imperative languages, you don't need to
think about variables and their actual values (which 
must be supervised very carefully), about call-by-value or
call-by-reference parameters or about pointers to results and
dereferencing them.
 This also applies to real problems, not only to  such trivial
examples as the rabbit numbers.

\novice This example also illustrates local declarations as another
feature of \opal. 
In lines 24--30 three local declarations are established as
notational abbreviations:
\begin{itemize}
\item \pro{generation} stands for the number the user has typed,
\item \pro{bunnies} is the computed number of couples,
\item and \pro{result} is the final answer (as a text) of the program.
\end{itemize}

By using these abbreviations the logical structure of the program will be
emphasized and the main action can be notated in a very short form:
\begin{prog}
      write(stdOut, result)
\end{prog}
Local declarations will be  detailed in Chapter
\ref{chap:small}, Section \ref{subsec:objdecl}



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