Sophie

Sophie

distrib > Mandriva > 8.1 > i586 > by-pkgid > 700475c8ae73fb4d57b6df4485c29e1c > files > 218

slang-doc-1.4.4-2mdk.i586.rpm









<!doctype linuxdoc system>

<book>

<title> A Guide to the S-Lang Language
<author> John E. Davis, <tt>davis@space.mit.edu</tt>
<date> Sat Feb  3 01:58:05 2001

<toc>


<chapt>Preface<p> 

  <bf>S-Lang</bf> is an interpreted language that was designed from the start
  to be easily embedded into a program to provide it with a powerful
  extension language.  Examples of programs that use <bf>S-Lang</bf> as an
  extension language include the <bf>jed</bf> text editor, the <bf>slrn</bf>
  newsreader, and <bf>sldxe</bf> (unreleased), a numerical computation
  program.  For this reason, <bf>S-Lang</bf> does not exist as a separate
  application and many of the examples in this document are presented
  in the context of one of the above applications.

  <bf>S-Lang</bf> is also a programmer's library that permits a programmer to
  develop sophisticated platform-independent software.  In addition to
  providing the <bf>S-Lang</bf> extension language, the library provides
  facilities for screen management, keymaps, low-level terminal I/O,
  etc.  However, this document is concerned only with the extension
  language and does not address these other features of the <bf>S-Lang</bf>
  library.  For information about the other components of the library,
  the reader is referred to the <bf>The <bf>S-Lang</bf> Library Reference</bf>.

<sect>A Brief History of <bf>S-Lang</bf><p> 

  I first began working on <bf>S-Lang</bf> sometime during the fall of 1992.
  At that time I was writing a text editor (<bf>jed</bf>), which I wanted to
  endow with a macro language.  It occured to me that an
  application-independent language that could be embedded into the
  editor would prove more useful because I could envision embedding it
  into other programs.  As a result, <bf>S-Lang</bf> was born.  
  
  <bf>S-Lang</bf> was originally a stack language that supported a
  postscript-like syntax.  For that reason, I named it <bf>S-Lang</bf>, where
  the <em>S</em> was supposed to emphasize its stack-based nature.  About
  a year later, I began to work on a preparser that would allow one to
  write using a more traditional infix syntax making it easier to use
  for those unfamiliar with stack based languages.  Currently, the
  syntax of the language resembles C, nevertheless some
  postscript-like features still remain, e.g., the `<tt>%</tt>' character
  is still used as a comment delimiter.


<sect>Acknowledgements<p> 

   Since I first released <bf>S-Lang</bf>, I have received a lot feedback about
   the library and the language from many people.  This has given me
   the opportunity and pleasure to interact with several people to
   make the library portable and easy to use.  In particular, I would
   like to thank the following individuals:

     Luchesar Ionkov <tt>&lt;lionkov@sf.cit.bg&gt;</tt> for his comments and
     criticisms of the syntax of the language.  He was the person who
     made me realize that the low-level byte-code engine should be
     totally type-independent.  He also improved the tokenizer and
     preparser and impressed upon me that the language needed a
     grammar.

     Mark Olesen <tt>&lt;olesen@weber.me.queensu.ca&gt;</tt> for his many patches to
     various aspects of the library and his support on AIX. He also
     contributed a lot to the pre-processing (<tt>SLprep</tt>) routines.

     John Burnell <tt>&lt;j.burnell@irl.cri.nz&gt;</tt> for the OS/2 port of the
     video and keyboard routines.  He also made value suggestions
     regarding the interpreter interface.

     Darrel Hankerson <tt>&lt;hankedr@mail.auburn.edu&gt;</tt> for cleaning up and
     unifying some of the code and the makefiles.

     Dominik Wujastyk <tt>&lt;ucgadkw@ucl.ac.uk&gt;</tt> who was always willing to test
     new releases of the library.

     Michael Elkins <tt>&lt;me@muddcs.cs.hmc.edu&gt;</tt> for his work on the curses
     emulation.

     Ulli Horlacher <tt>&lt;framstag@belwue.de&gt;</tt> and Oezguer Kesim
     <tt>&lt;kesim@math.fu-berlin.de&gt;</tt> for the <bf>S-Lang</bf> newsgroup and mailing list.
     
     Hunter Goatley, Andy Harper <tt>&lt;Andy.Harper@kcl.ac.uk&gt;</tt>, and Martin
     P.J. Zinser <tt>&lt;zinser@decus.decus.de&gt;</tt> for their VMS support.
     
     Dave Sims <tt>&lt;sims@usa.acsys.com&gt;</tt> and Chin Huang
     <tt>&lt;cthuang@vex.net&gt;</tt> for Windows 95 and Windows NT support.
     
     Lloyd Zusman <tt>&lt;ljz@asfast.com&gt;</tt> and Rich Roth <tt>&lt;rich@on-the-net.com&gt;</tt>
     for creating and maintaining <tt>www.s-lang.org</tt>.

  I am also grateful to many other people who send in bug-reports and
  bug-fixes, for without such community involvement, <bf>S-Lang</bf> would not
  be as well-tested and stable as it is.  Finally, I would like to
  thank my wife for her support and understanding while I spent long
  weekend hours developing the library.



<chapt>Introduction<p> 

   <bf>S-Lang</bf> is a powerful interpreted language that may be embedded into
   an application to make the application extensible.  This enables
   the application to be used in ways not envisioned by the programmer,
   thus providing the application with much more flexibility and
   power.  Examples of applications that take advantage of the
   interpreter in this way include the <bf>jed</bf> editor and the <bf>slrn</bf>
   newsreader.

<sect>Language Features<p>

   The language features both global and local variables, branching
   and looping constructs, user-defined functions, structures,
   datatypes, and arrays.  In addition, there is limited support for
   pointer types.  The concise array syntax rivals that of commercial
   array-based numerical computing environments.

<sect>Data Types and Operators<p> 

   The language provides built-in support for string, integer (signed
   and unsigned long and short), double precision floating point, and
   double precision complex numbers.  In addition, it supports user
   defined structure types, multi-dimensional array types, and
   associative arrays.  To facilitate the construction of
   sophisticated data structures such as linked lists and trees, a
   `reference' type was added to the language.  The reference type
   provides much of the same flexibility as pointers in other
   languages.  Finally, applications embedding the interpreter may
   also provide special application specific types, such as the
   <tt>Mark_Type</tt> that the <bf>jed</bf> editor provides.

   The language provides standard arithmetic operations such as
   addition, subtraction, multiplication, and division.  It also
   provides support for modulo arithmetic as well as operations at
   the bit level, e.g., exclusive-or.  Any binary or unary operator
   may be extended to work with any data type.  For example, the
   addition operator (<tt>+</tt>) has been extended to work between
   string types to permit string concatenation.

   The binary and unary operators work transparently with array types.
   For example, if <tt>a</tt> and <tt>b</tt> are arrays, then <tt>a + b</tt>
   produces an array whose elements are the result of element by
   element addition of <tt>a</tt> and <tt>b</tt>.  This permits one to do
   vector operations without explicitly looping over the array
   indices.


<sect>Statements and Functions<p> 

   The <bf>S-Lang</bf> language supports several types of looping constructs and
   conditional statements.  The looping constructs include <tt>while</tt>,
   <tt>do...while</tt>, <tt>for</tt>, <tt>forever</tt>, <tt>loop</tt>, <tt>foreach</tt>,
   and <tt>_for</tt>. The conditional statements include <tt>if</tt>,
   <tt>if-then-else</tt>, and <tt>!if</tt>.

   User defined functions may be defined to return zero, one, or more
   values.  Functions that return zero values are similar to
   `procedures' in languages such as PASCAL.  The local variables of a
   function are always created on a stack allowing one to create
   recursive functions.  Parameters to a function are always passed by
   value and never by reference. However, the language supports a
   <em>reference</em> data type that allows one to simulate pass by
   reference.

   Unlike many interpreted languages, <bf>S-Lang</bf> allows functions to be
   dynamically loaded (function autoloading).  It also provides
   constructs specifically designed for error handling and recovery as
   well as debugging aids (e.g., function tracebacks).

   Functions and variables may be declared as private belonging to a
   namespace associated with the compilation unit that defines the
   function or variable.  The ideas behind the namespace implementation
   stems from the C language and should be quite familiar to any one
   familiar with C.


<sect>Error Handling<p> 

   The <bf>S-Lang</bf> language defines a construct called an <em>error-block</em>
   that may be used for error handling and recovery.  When a non-fatal
   run-time error is encountered, any error blocks that have been
   defined are executed as the run-time stack unwinds.  An error block
   can optionally clear the error and the program will continue
   running after the statement that triggered the error.  This
   mechanism is somewhat similar to try-catch in C++.


<sect>Run-Time Library<p> 

   Functions that compose the <bf>S-Lang</bf> run-time library are called
   <em>intrinsics</em>.  Examples of <bf>S-Lang</bf> intrinsic functions available
   to every <bf>S-Lang</bf> application include string manipulation functions
   such as <tt>strcat</tt>, <tt>strchop</tt>, and <tt>strcmp</tt>.  The <bf>S-Lang</bf>
   library also provides mathematical functions such as <tt>sin</tt>,
   <tt>cos</tt>, and <tt>tan</tt>; however, not all applications enable the
   use of these intrinsics.  For example, to conserve memory, the 16
   bit version of the <bf>jed</bf> editor does not provide support for any
   mathematics other than simple integer arithmetic, whereas other
   versions of the editor do support these functions.

   Most applications embedding the languages will also provide a set of
   application specific intrinsic functions.  For example, the <bf>jed</bf>
   editor adds over 100 application specific intrinsic functions to
   the language.  Consult your application specific documentation to
   see what additional intrinsics are supported.


<sect>Input/Output<p>

   The language supports C-like stdio input/output functions such as
   <tt>fopen</tt>, <tt>fgets</tt>, <tt>fputs</tt>, and <tt>fclose</tt>.  In
   addition it provides two functions, <tt>message</tt> and <tt>error</tt>,
   for writing to the standard output device and standard error.
   Specific applications may provide other I/O mechanisms, e.g.,
   the <bf>jed</bf> editor supports I/O to files via the editor's
   buffers.

<sect>Obtaining <bf>S-Lang</bf><p> 

  Comprehensive information about the library may be obtained via the
  World Wide Web from <tt>http://www.s-lang.org</tt>.

  <bf>S-Lang</bf> as well as some programs that embed it are freely available
  via anonymous ftp in the United States from
<itemize>
  <item> <htmlurl url="ftp://space.mit.edu/pub/davis" name="ftp://space.mit.edu/pub/davis">.
</itemize>
  It is also available outside the United States from the following
  mirror sites:
<itemize>
    <item> <htmlurl url="ftp://ftp.uni-stuttgart.de/pub/unix/misc/slang/" name="ftp://ftp.uni-stuttgart.de/pub/unix/misc/slang/">
    <item> <htmlurl url="ftp://ftp.fu-berlin.de/pub/unix/news/slrn/" name="ftp://ftp.fu-berlin.de/pub/unix/news/slrn/">
    <item> <htmlurl url="ftp://ftp.ntua.gr/pub/lang/slang/" name="ftp://ftp.ntua.gr/pub/lang/slang/">
</itemize>

  The Usenet newsgroup <tt>alt.lang.s-lang</tt> was created for <bf>S-Lang</bf>
  programmers to exchange information and share macros for the various
  programs the embed the language.  The newsgroup <tt>comp.editors</tt>
  can be a useful resource for <bf>S-Lang</bf> macros for the <bf>jed</bf> editor.
  Similarly, <bf>slrn</bf> users will find <tt>news.software.readers</tt> to be a
  valuable source of information.
  
  Finally, two mailing lists dealing with the <bf>S-Lang</bf> library have been
  created: 
<itemize>
     <item> <tt>slang-announce@babayaga.math.fu-berlin.de</tt>
     <item> <tt>slang-workers@babayaga.math.fu-berlin.de</tt>
</itemize>
  The first list is for announcements of new releases of the library, while the
  second list is intended for those who use the library for their own code
  development.  To subscribe to the announcement list, send an email to
  <tt>slang-announce-subscribe@babayaga.math.fu-berlin.de</tt> and include
  the word <tt>subscribe</tt> in the body of the message.  To subscribe to
  the developers list, use the address
  <tt>slang-workers-subscribe@babayaga.math.fu-berlin.de</tt>.



<chapt>Overview of the Language<p> 

   This purpose of this section is to give the reader a feel for the
   <bf>S-Lang</bf> language, its syntax, and its capabilities.  The information
   and examples presented in this section should be sufficient to
   provide the reader with the necessary background to understand the
   rest of the document.

<sect>Variables and Functions<p> 

   <bf>S-Lang</bf> is different from many other interpreted languages in the
   sense that all variables and functions must be declared before they
   can be used.

   Variables are declared using the <tt>variable</tt> keyword, e.g.,
<tscreen><verb>
     variable x, y, z;
</verb></tscreen>
   declares three variables, <tt>x</tt>, <tt>y</tt>, and <tt>z</tt>.  Note the
   semicolon at the end of the statement.  <em>All <bf>S-Lang</bf> statements must
   end in a semi-colon.</em>

   Unlike compiled languages such as C, it is not necessary to specify
   the data type of a <bf>S-Lang</bf> variable.  The data type of a <bf>S-Lang</bf>
   variable is determined upon assignment.  For example, after
   execution of the statements
<tscreen><verb>
     x = 3;
     y = sin (5.6);
     z = "I think, therefore I am.";
</verb></tscreen>
   <tt>x</tt> will be an integer, <tt>y</tt> will be a
   double, and <tt>z</tt> will be a string.  In fact, it is even possible
   to re-assign <tt>x</tt> to a string:
<tscreen><verb>
     x = "x was an integer, but now is a string";
</verb></tscreen>
   Finally, one can combine variable declarations and assignments in
   the same statement:
<tscreen><verb>
     variable x = 3, y = sin(5.6), z = "I think, therefore I am.";
</verb></tscreen>

   Most functions are declared using the <tt>define</tt> keyword.  A
   simple example is
<tscreen><verb>
      define compute_average (x, y)
      {
         variable s = x + y;
         return s / 2.0;
      }
</verb></tscreen>
   which defines a function that simply computes the average of two
   numbers and returns the result.  This example shows that a function
   consists of three parts: the function name, a parameter list, and
   the function body.

   The parameter list consists of a comma separated list of variable
   names.  It is not necessary to declare variables within a parameter
   list; they are implicitly declared.  However, all other <em>local</em>
   variables used in the function must be declared.  If the function
   takes no parameters, then the parameter list must still be present,
   but empty:
<tscreen><verb>
      define go_left_5 ()
      {
         go_left (5);
      }
</verb></tscreen>
   The last example is a function that takes no arguments and returns
   no value.  Some languages such as PASCAL distinguish such objects
   from functions that return values by calling these objects
   <em>procedures</em>.  However, <bf>S-Lang</bf>, like C, does not make such a
   distinction.
   
   The language permits <em>recursive</em> functions, i.e., functions that
   call themselves.  The way to do this in <bf>S-Lang</bf> is to first declare
   the function using the form:
<tscreen>
     define <em>function-name</em> ();
</tscreen>
   It is not necessary to declare a parameter list when declaring a
   function in this way.

   The most famous example of a recursive function is the factorial
   function.  Here is how to implement it using <bf>S-Lang</bf>:
<tscreen><verb>
     define factorial ();   % declare it for recursion
     
     define factorial (n)
     {
        if (n &lt; 2) return 1;
        return n * factorial (n - 1);
     }
</verb></tscreen>
   This example also shows how to mix comments with code.  <bf>S-Lang</bf> uses
   the `<tt>%</tt>' character to start a comment and all characters from
   the comment character to the end of the line are ignored.


<sect>Strings<p> 

   Perhaps the most appealing feature of any interpreted language is
   that it frees the user from the responsibility of memory management.
   This is particularly evident when contrasting how
   <bf>S-Lang</bf> handles string variables with a lower level language such as
   C.  Consider a function that concatenates three strings.  An
   example in <bf>S-Lang</bf> is:
<tscreen><verb>
     define concat_3_strings (a, b, c)
     {
        return strcat (a, strcat (b, c));
     }
</verb></tscreen>
   This function uses the built-in
   <tt>strcat</tt> function for concatenating two strings.  In C, the
   simplest such function would look like:
<tscreen><verb>
     char *concat_3_strings (char *a, char *b, char *c)
     {
        unsigned int len;
        char *result;
        len = strlen (a) + strlen (b) + strlen (c);
        if (NULL == (result = (char *) malloc (len + 1)))
          exit (1);
        strcpy (result, a);
        strcat (result, b);
        strcat (result, c);
        return result;
     }
</verb></tscreen>
   Even this C example is misleading since none of the issues of memory
   management of the strings has been dealt with.  The <bf>S-Lang</bf> language
   hides all these issues from the user.

   Binary operators have been defined to work with the string data
   type.  In particular the <tt>+</tt> operator may be used to perform
   string concatenation.  That is, one can use the
   <tt>+</tt> operator as an alternative to <tt>strcat</tt>:
<tscreen><verb>
      define concat_3_strings (a, b, c)
      {
         return a + b + c;
      }
</verb></tscreen>
   See section ??? for more information about string variables.


<sect>Referencing and Dereferencing<p> 
   The unary prefix operator, <tt>&amp;</tt>, may be used to create a
   <em>reference</em> to an object, which is similar to a pointer
   in other languages.  References are commonly used as a mechanism to
   pass a function as an argument to another function as the following
   example illustrates:
<tscreen><verb>
       define compute_functional_sum (funct)
       {
          variable i, sum;

          sum = 0;
          for (i = 0; i &lt; 10; i++)
           {
              sum += @funct (i);
           }
          return sum;
       }
       
       variable sin_sum = compute_functional_sum (&amp;sin);
       variable cos_sum = compute_functional_sum (&amp;cos);
</verb></tscreen>
   Here, the function <tt>compute_functional_sum</tt> applies the
   function specified by the parameter <tt>funct</tt> to the first
   <tt>10</tt> integers and returns the sum.  The two statements
   following the function definition show how the <tt>sin</tt> and
   <tt>cos</tt> functions may be used.
   
   Note the <tt>@</tt> operator in the definition of
   <tt>compute_functional_sum</tt>.  It is known as the <em>dereference</em>
   operator and is the inverse of the reference operator.
   
   Another use of the reference operator is in the context of the
   <tt>fgets</tt> function.  For example,
<tscreen><verb>
      define read_nth_line (file, n)
      {
         variable fp, line;
         fp = fopen (file, "r");
           
         while (n &gt; 0)
           {
              if (-1 == fgets (&amp;line, fp))
                return NULL;
              n--;
           }
         return line;
      }
</verb></tscreen>
   uses the <tt>fgets</tt> function to read the nth line of a file.
   In particular, a reference to the local variable <tt>line</tt> is
   passed to <tt>fgets</tt>, and upon return <tt>line</tt> will be set to
   the character string read by <tt>fgets</tt>.
   
   Finally, references may be used as an alternative to multiple
   return values by passing information back via the parameter list.
   The example involving <tt>fgets</tt> presented above provided an
   illustration of this.  Another example is
<tscreen><verb>
       define set_xyz (x, y, z)
       {
          @x = 1;
          @y = 2;
          @z = 3;
       }
       variable X, Y, Z;
       set_xyz (&amp;X, &amp;Y, &amp;Z);
</verb></tscreen>
   which, after execution, results in <tt>X</tt> set to <tt>1</tt>, <tt>Y</tt>
   set to <tt>2</tt>, and <tt>Z</tt> set to <tt>3</tt>.  A C programmer will
   note the similarity of <tt>set_xyz</tt> to the following C
   implementation:
<tscreen><verb>
      void set_xyz (int *x, int *y, int *z)
      {
         *x = 1;
         *y = 2;
         *z = 3;
      }
</verb></tscreen>

<sect>Arrays<p> 
   The <bf>S-Lang</bf> language supports multi-dimensional arrays of all
   datatypes.  For example, one can define arrays of references to
   functions as well as arrays of arrays.  Here are a few examples of
   creating arrays:
<tscreen><verb>
       variable A = Integer_Type [10];  
       variable B = Integer_Type [10, 3];
       variable C = [1, 3, 5, 7, 9];
</verb></tscreen>
   The first example creates an array of <tt>10</tt> integers and assigns
   it to the variable <tt>A</tt>.  The second example creates a 2-d array
   of <tt>30</tt> integers arranged in <tt>10</tt> rows and <tt>3</tt> columns
   and assigns the result to <tt>B</tt>.  In the last example, an array
   of <tt>5</tt> integers is assigned to the variable <tt>C</tt>.  However,
   in this case the elements of the array are initialized to the
   values specified.  This is known as an <em>inline-array</em>.
   
   <bf>S-Lang</bf> also supports something called an
   <em>range-array</em>.  An example of such an array is
<tscreen><verb>
      variable C = [1:9:2];
</verb></tscreen>
   This will produce an array of 5 integers running from <tt>1</tt>
   through <tt>9</tt> in increments of <tt>2</tt>.
   
   Arrays are passed by reference to functions and never by value.
   This permits one to write functions which can initialize arrays.
   For example,
<tscreen><verb>
      define init_array (a)
      {
         variable i, imax;
         
         imax = length (a);
         for (i = 0; i &lt; imax; i++)
           { 
              a[i] = 7;
           }
      }
      
      variable A = Integer_Type [10];
      init_array (A);
</verb></tscreen>
   creates an array of <tt>10</tt> integers and initializes all its
   elements to <tt>7</tt>.  

   There are more concise ways of accomplishing the result of the
   previous example.  These include:
<tscreen><verb>
      variable A = [7, 7, 7, 7, 7, 7, 7, 7, 7, 7];
      variable A = Integer_Type [10];  A[[0:9]] = 7;
      variable A = Integer_Type [10];  A[*] = 7;
</verb></tscreen>
   The second and third methods use an array of indices to index the array
   <tt>A</tt>.  In the second, the range of indices has been explicitly
   specified, whereas the third example uses a wildcard form.  See
   section ??? for more information about array indexing.

   Although the examples have pertained to integer arrays, the fact is
   that <bf>S-Lang</bf> arrays can be of any type, e.g.,
<tscreen><verb>
       variable A = Double_Type [10];
       variable B = Complex_Type [10];
       variable C = String_Type [10];
       variable D = Ref_Type [10];
</verb></tscreen>
   create <tt>10</tt> element arrays of double, complex, string, and
   reference types, respectively.  The last example may be used to
   create an array of functions, e.g.,
<tscreen><verb>
      D[0] = &amp;sin;
      D[1] = &amp;cos;
</verb></tscreen>

   The language also defines unary, binary, and mathematical
   operations on arrays.  For example, if <tt>A</tt> and <tt>B</tt> are
   integer arrays, then <tt>A + B</tt> is an array whose elements are
   the sum of the elements of <tt>A</tt> and <tt>B</tt>.  A trivial example
   that illustrates the power of this capability is
<tscreen><verb>
        variable X, Y;
        X = [0:2*PI:0.01];
        Y = 20 * sin (X);
</verb></tscreen>
   which is equivalent to the highly simplified C code:
<tscreen><verb>
        double *X, *Y;
        unsigned int i, n;
        
        n = (2 * PI) / 0.01 + 1;
        X = (double *) malloc (n * sizeof (double));
        Y = (double *) malloc (n * sizeof (double));
        for (i = 0; i &lt; n; i++)
          {
            X[i] = i * 0.01;
            Y[i] = 20 * sin (X[i]);
          }
</verb></tscreen>



<sect>Structures and User-Defined Types<p> 

   A <em>structure</em> is similar to an array in the sense that it is a
   container object.  However, the elements of an array must all be of
   the same type (or of <tt>Any_Type</tt>), whereas a structure is
   heterogeneous.  As an example, consider
<tscreen><verb>
      variable person = struct 
      {
         first_name, last_name, age
      };
      variable bill = @person;
      bill.first_name = "Bill";
      bill.last_name = "Clinton";
      bill.age = 51;
</verb></tscreen>
   In this example a structure consisting of the three fields has been
   created and assigned to the variable <tt>person</tt>.  Then an
   <em>instance</em> of this structure has been created using the
   dereference operator and assigned to <tt>bill</tt>.  Finally, the
   individual fields of <tt>bill</tt> were initialized.  This is an
   example of an <em>anonymous</em> structure.
   
   A <em>named</em> structure is really a new data type and may be created
   using the <tt>typedef</tt> keyword:
<tscreen><verb>
      typedef struct
      {
         first_name, last_name, age
      }
      Person_Type;
      
      variable bill = @Person_Type;
      bill.first_name = "Bill";
      bill.last_name = "Clinton";
      bill.age = 51;
</verb></tscreen>
   The big advantage of creating a new type is that one can go on to
   create arrays of the data type
<tscreen><verb>
      variable People = Person_Type [100];
      People[0].first_name = "Bill";
      People[1].first_name = "Hillary";
</verb></tscreen>

   The creation and initialization of a structure may be facilitated
   by a function such as
<tscreen><verb>
      define create_person (first, last, age)
      {
          variable person = @Person_Type;
          person.first_name = first;
          person.last_name = last;
          person.age = age;
          return person;
      }
      variable Bill = create_person ("Bill", "Clinton", 51);
</verb></tscreen>
   
   Other common uses of structures is the creation of linked lists,
   binary trees, etc.  For more information about these and other
   features of structures, see section ???.



<sect>Namespaces<p>

   In addition to the global namespace, each compilation unit (e.g., a
   file) is given a private namespace.  A variable or function name
   that is declared using the <tt>static</tt> keyword will be placed in
   the private namespace associated with compilation unit.  For
   example, 
<tscreen><verb>
       variable i;
       static variable i;
</verb></tscreen>
   defines two variables called <tt>i</tt>.  The first declaration
   defines <tt>i</tt> in the global namespace, but the second declaration
   defines <tt>i</tt> in the private namespace.
   
   The <tt>-&gt;</tt> operator may be used in conjunction with the name of
   the namespace to access objects in the name space.  In the above
   example, to access the variable <tt>i</tt> in the global namespace,
   one would use <tt>Global-&gt;i</tt>.  Unless otherwise specified, a
   private namespace has no name and its objects may not be accessed
   from outside the compilation unit.  However, the <tt>implements</tt>
   function may be used give the private namespace a name, allowing
   access to its objects.  For example, if the file <tt>t.sl</tt> contains
<tscreen><verb>
      implements ("A");
      static variable i;
</verb></tscreen>
   then another file may access the variable <tt>i</tt> via <tt>A-&gt;i</tt>.
   

<chapt>Data Types and Literal Constants<p> 

   The current implementation of the <bf>S-Lang</bf> language permits up to 256
   distinct data types, including predefined data types such as integer and
   floating point, as well as specialized applications specific data
   types.  It is also possible to create new data types in the
   language using the <tt>typedef</tt> mechanism.

   Literal constants are objects such as the integer <tt>3</tt> or the
   string <tt>"hello"</tt>.  The actual data type given to a literal
   constant depends upon the syntax of the constant.  The following
   sections describe the syntax of literals of specific data types.

<sect>Predefined Data Types<p> 

   The current version of <bf>S-Lang</bf> defines integer, floating point,
   complex, and string types. It also defines special purpose data
   types such as <tt>Null_Type</tt>, <tt>DataType_Type</tt>, and
   <tt>Ref_Type</tt>.  These types are discussed below.

<sect1>Integers<p> 

   The <bf>S-Lang</bf> language supports both signed and unsigned characters,
   short integer, long integer, and plain integer types. On most 32
   bit systems, there is no difference between an integer and a long
   integer; however, they may differ on 16 and 64 bit systems.
   Generally speaking, on a 16 bit system, plain integers are 16 bit
   quantities with a range of -32767 to 32767.  On a 32 bit system,
   plain integers range from -2147483648 to 2147483647.

   An plain integer <em>literal</em> can be specified in one of several ways:
<itemize>
<item> As a decimal (base 10) integer consisting of the characters
      <tt>0</tt> through <tt>9</tt>, e.g., <tt>127</tt>.  An integer specified
      this way cannot begin with a leading <tt>0</tt>.  That is,
      <tt>0127</tt> is <em>not</em> the same as <tt>127</tt>.

<item> Using hexadecimal (base 16) notation consisting of the characters
      <tt>0</tt> to <tt>9</tt> and <tt>A</tt> through <tt>F</tt>.  The hexadecimal
      number must be preceded by the characters <tt>0x</tt>.  For example,
      <tt>0x7F</tt> specifies an integer using hexadecimal notation and has
      the same value as decimal <tt>127</tt>.

<item> In Octal notation using characters <tt>0</tt> through <tt>7</tt>.  The Octal
      number must begin with a leading <tt>0</tt>.  For example,
      <tt>0177</tt> and <tt>127</tt> represent the same integer.

   Short, long, and unsigned types may be specified by using the
   proper suffixes: <tt>L</tt> indicates that the integer is a long
   integer, <tt>h</tt> indicates that the integer is a short integer, and
   <tt>U</tt> indicates that it is unsigned.  For example, <tt>1UL</tt>
   specifies an unsigned long integer.

   Finally, a character literal may be specified using a notation
   containing a character enclosed in single quotes as <tt>'a'</tt>.
   The value of the character specified this way will lie in the
   range 0 to 256 and will be determined by the ASCII value of the
   character in quotes.  For example,
<tscreen><verb>
              i = '0';
</verb></tscreen>
      assigns to <tt>i</tt> the character 48 since the <tt>'0'</tt> character 
      has an ASCII value of 48.
</itemize>

    Any integer may be preceded by a minus sign to indicate that it is a
    negative integer.


<sect1>Floating Point Numbers<p> 

    Single and double precision floating point literals must contain either a
    decimal point or an exponent (or both). Here are examples of
    specifying the same double precision point number:
<tscreen><verb>
         12.    12.0    12e0   1.2e1   120e-1   .12e2   0.12e2
</verb></tscreen>
    Note that <tt>12</tt> is <em>not</em> a floating point number since it
    contains neither a decimal point nor an exponent.  In fact,
    <tt>12</tt> is an integer.

    One may append the <tt>f</tt> character to the end of the number to
    indicate that the number is a single precision literal.


<sect1>Complex Numbers<p> 

    The language implements complex numbers as a pair of double
    precision floating point numbers.  The first number in the pair
    forms the <em>real</em> part, while the second number forms the
    <em>imaginary</em> part.  That is, a complex number may be regarded as the
    sum of a real number and an imaginary number.
    
    Strictly speaking, the current implementation of the <bf>S-Lang</bf> does
    not support generic complex literals.  However, it does support
    imaginary literals and a more generic complex number with a non-zero
    real part may be constructed from the imaginary literal via
    addition of a real number.

    An imaginary literal is specified in the same way as a floating
    point literal except that <tt>i</tt> or <tt>j</tt> is appended.  For
    example,
<tscreen><verb>
         12i    12.0i   12e0j
</verb></tscreen>
    all represent the same imaginary number.  Actually, <tt>12i</tt> is
    really an imaginary integer except that <bf>S-Lang</bf> automatically
    promotes it to a double precision imaginary number.

    A more generic complex number may be constructed from an imaginary
    literal via addition, e.g.,
<tscreen><verb>
        3.0 + 4.0i
</verb></tscreen>
    produces a complex number whose real part is <tt>3.0</tt> and whose
    imaginary part is <tt>4.0</tt>.

    The intrinsic functions <tt>Real</tt> and <tt>Imag</tt> may be used to
    retrieve the real and imaginary parts of a complex number,
    respectively.


<sect1>Strings<p> 

    A string literal must be enclosed in double quotes as in:
<tscreen><verb>
      "This is a string".
</verb></tscreen>
    Although there is no imposed limit on the length of a string,
    string literals must be less than 256 characters in length.  It is
    possible to go beyond this limit by string concatenation, e.g.,
<tscreen><verb>
     "This is the first part of a long string"
       + "and this is the second half"
</verb></tscreen>
    Any character except a newline (ASCII 10) or the null character
    (ASCII 0) may appear explicitly in a string literal.  However,
    these characters may be used implicitly using the mechanism
    described below. 

    The backslash character is a special character and is used to
    include other special characters (such as a newline character) in
    the string. The special characters recognized are:
<tscreen><verb>
       \"    --  double quote
       \'    --  single quote
       \\    --  backslash
       \a    --  bell character (ASCII 7)
       \t    --  tab character (ASCII 9)
       \n    --  newline character (ASCII 10)
       \e    --  escape character (ASCII 27)
       \xhhh --  character expressed in HEXADECIMAL notation
       \ooo  --  character expressed in OCTAL notation
       \dnnn --  character expressed in DECIMAL
</verb></tscreen>
    For example, to include the double quote character as part of the
    string, it must be preceded by a backslash character, e.g.,
<tscreen><verb>
       "This is a \"quote\""
</verb></tscreen>
    Similarly, the next illustrates how a newline character may be
    included:
<tscreen><verb>
       "This is the first line\nand this is the second"
</verb></tscreen>


<sect1>Null_Type<p>

   Objects of type <tt>Null_Type</tt> can have only one value:
   <tt>NULL</tt>.  About the only thing that you can do with this data
   type is to assign it to variables and test for equality with
   other objects.  Nevertheless, <tt>Null_Type</tt> is an important and
   extremely useful data type.  Its main use stems from the fact that
   since it can be compared for equality with any other data type, it
   is ideal to represent the value of an object which does not yet
   have a value, or has an illegal value.
   
   As a trivial example of its use, consider
<tscreen><verb>
      define add_numbers (a, b)
      {
         if (a == NULL) a = 0;
         if (b == NULL) b = 0;
         return a + b;
      }
      variable c = add_numbers (1, 2);
      variable d = add_numbers (1, NULL);
      variable e = add_numbers (1,);
      variable f = add_numbers (,);
</verb></tscreen>
   It should be clear that after these statements have been executed,
   <tt>c</tt> will have a value of <tt>3</tt>.  It should also be clear
   that <tt>d</tt> will have a value of <tt>1</tt> because <tt>NULL</tt> has
   been passed as the second parameter.  One feature of the language
   is that if a parameter has been omitted from a function call, the
   variable associated with that parameter will be set to <tt>NULL</tt>.
   Hence, <tt>e</tt> and <tt>f</tt> will be set to <tt>1</tt> and <tt>0</tt>,
   respectively.
   
   The <tt>Null_Type</tt> data type also plays an important role in the
   context of <em>structures</em>.

<sect1>Ref_Type<p>
   Objects of <tt>Ref_Type</tt> are created using the unary
   <em>reference</em> operator <tt>&amp;</tt>.  Such objects may be
   <em>dereferenced</em> using the dereference operator <tt>@</tt>.  For
   example, 
<tscreen><verb>
      variable sin_ref = &amp;sin;
      variable y = @sin_ref (1.0);
</verb></tscreen>
   creates a reference to the <tt>sin</tt> function and assigns it to
   <tt>sin_ref</tt>.  The second statement uses the dereference operator
   to call the function that <tt>sin_ref</tt> references.
   
   The <tt>Ref_Type</tt> is useful for passing functions as arguments to
   other functions, or for returning information from a function via
   its parameter list.  The dereference operator is also used to create
   an instance of a structure.  For these reasons, further discussion
   of this important type can be found in section ??? and section ???.

<sect1>Array_Type and Struct_Type<p>
   
   Variables of type <tt>Array_Type</tt> and <tt>Struct_Type</tt> are known
   as <em>container objects</em>.  They are much more complicated than the
   simple data types discussed so far and each obeys a special syntax.
   For these reasons they are discussed in a separate chapters.
   See ???.

<sect1>DataType_Type Type<p> 

   <bf>S-Lang</bf> defines a type called <tt>DataType_Type</tt>.  Objects of
   this type have values that are type names.  For example, an integer
   is an object of type <tt>Integer_Type</tt>.  The literals of
   <tt>DataType_Type</tt> include:
<tscreen><verb>
     Char_Type            (signed character)
     UChar_Type           (unsigned character)
     Short_Type           (short integer)
     UShort_Type          (unsigned short integer)
     Integer_Type         (plain integer)
     UInteger_Type        (plain unsigned integer)
     Long_Type            (long integer)
     ULong_Type           (unsigned long integer)
     Float_Type           (single precision real)
     Double_Type          (double precision real)
     Complex_Type         (complex numbers)
     String_Type          (strings, C strings)
     BString_Type         (binary strings)
     Struct_Type          (structures)
     Ref_Type             (references)
     Null_Type            (NULL)
     Array_Type           (arrays)
     DataType_Type        (data types)
</verb></tscreen>
   as well as the names of any other types that an application
   defines.
   
   The built-in function <tt>typeof</tt> returns the data type of
   its argument, i.e., a <tt>DataType_Type</tt>.  For instance
   <tt>typeof(7)</tt> returns <tt>Integer_Type</tt> and
   <tt>typeof(Integer_Type)</tt> returns <tt>DataType_Type</tt>.  One can use this
   function as in the following example:
<tscreen><verb>
      if (Integer_Type == typeof (x)) message ("x is an integer");
</verb></tscreen>
   The literals of <tt>DataType_Type</tt> have other uses as well.  One
   of the most common uses of these literals is to create arrays, e.g.,
<tscreen><verb>
        x = Complex_Type [100];
</verb></tscreen>
   creates an array of <tt>100</tt> complex numbers and assigns it to
   <tt>x</tt>.


<sect>Typecasting: Converting from one Type to Another<p>

   Occasionally, it is necessary to convert from one data type to
   another.  For example, if you need to print an object as a string,
   it may be necessary to convert it to a <tt>String_Type</tt>.  The
   <tt>typecast</tt> function may be used to perform such conversions.
   For example, consider
<tscreen><verb>
      variable x = 10, y;
      y = typecast (x, Double_Type);
</verb></tscreen>
   After execution of these statements, <tt>x</tt> will have the integer
   value <tt>10</tt> and <tt>y</tt> will have the double precision floating
   point value <tt>10.0</tt>.  If the object to be converted is an
   array, the <tt>typecast</tt> function will act upon all elements of
   the array.  For example, 
<tscreen><verb>
      variable x = [1:10];       % Array of integers
      variable y = typecast (x, Double_Type);
</verb></tscreen>
   will create an array of <tt>10</tt> double precision values and
   assign it to <tt>y</tt>.  One should also realize that it is not
   always possible to perform a typecast.  For example, any attempt to
   convert an <tt>Integer_Type</tt> to a <tt>Null_Type</tt> will result in a
   run-time error.
   
   Often the interpreter will perform implicit type conversions as necessary
   to complete calculations.  For example, when multiplying an
   <tt>Integer_Type</tt> with a <tt>Double_Type</tt>, it will convert the
   <tt>Integer_Type</tt> to a <tt>Double_Type</tt> for the purpose of the
   calculation.  Thus, the example involving the conversion of an
   array of integers to an array of doubles could have been performed
   by multiplication by <tt>1.0</tt>, i.e.,
<tscreen><verb>
      variable x = [1:10];       % Array of integers
      variable y = 1.0 * x;
</verb></tscreen>

   The <tt>string</tt> intrinsic function is similar to the typecast
   function except that it converts an object to a string
   representation.  It is important to understand that a typecast from
   some type to <tt>String_Type</tt> is <em>not</em> the same as converting
   an object to its string operation.   That is,
   <tt>typecast(x,String_Type)</tt> is not equivalent to
   <tt>string(x)</tt>.  The reason for this is that when given an array,
   the <tt>typecast</tt> function acts on each element of the array to
   produce another array, whereas the <tt>string</tt> function produces a
   a string.
   
   The <tt>string</tt> function is useful for printing the value of an
   object.  This use is illustrated in the following simple example:
<tscreen><verb>
      define print_object (x)
      {
         message (string (x));
      }
</verb></tscreen>
   Here, the <tt>message</tt> function has been used because it writes a
   string to the display.  If the <tt>string</tt> function was not used
   and the <tt>message</tt> function was passed an integer, a
   type-mismatch error would have resulted.


<chapt>Identifiers<p> 

   The names given to variables, functions, and data types are called
   <em>identifiers</em>.  There are some restrictions upon the actual
   characters that make up an identifier.  An identifier name must
   start with a letter (<tt>[A-Za-z]</tt>), an underscore character, or a
   dollar sign.  The rest of the characters in the name can be any
   combination of letters, digits, dollar signs, or underscore
   characters.  However, all identifiers whose name begins with two
   underscore characters are reserved for internal use by the
   interpreter and declarations of objects with such names should be
   avoided.

   Examples of valid identifiers include:
<tscreen><verb>
      mary    _3    _this_is_ok
      a7e1    &dollar;44   _44&dollar;_Three
</verb></tscreen>
   However, the following are not legal:
<tscreen><verb>
      7abc   2e0    #xx
</verb></tscreen>
   In fact, <tt>2e0</tt> actually specifies the real number
   <tt>2.0</tt>.

   Although the maximum length of identifiers is unspecified by the
   language, the length should be kept below <tt>64</tt> characters.

   The following identifiers are reserved by the language for use as
   keywords:
<tscreen><verb>
        !if            _for        do         mod       sign       xor
        ERROR_BLOCK    abs         do_while   mul2      sqr        public
        EXIT_BLOCK     and         else       not       static     private
        USER_BLOCK0    andelse     exch       or        struct
        USER_BLOCK1    break       for        orelse    switch
        USER_BLOCK2    case        foreach    pop       typedef
        USER_BLOCK3    chs         forever    return    using
        USER_BLOCK4    continue    if         shl       variable
        __tmp          define      loop       shr       while
</verb></tscreen>

<chapt>Variables<p> 

   A variable must be declared before it can be used, otherwise an
   undefined name error will be generated.  A variable is declared
   using the <tt>variable</tt> keyword, e.g,
<tscreen><verb>
      variable x, y, z;
</verb></tscreen>
   declares three variables, <tt>x</tt>, <tt>y</tt>, and <tt>z</tt>.  This
   is an example of a variable declaration statement, and like all
   statements, it must end in a semi-colon.

   Variables declared this way are untyped and inherit a type upon
   assignment.  The actual type checking is performed at run-time.  For
   example,
<tscreen><verb>
        x = "This is a string";
        x = 1.2;
        x = 3;
        x = 2i;
</verb></tscreen>
   results in x being set successively to a string, a float, an
   integer, and to a complex number (<tt>0+2i</tt>).  Any attempt to use
   a variable before it has acquired a type will result in an
   uninitialized variable error.

   It is legal to put executable code in a variable declaration list.
   That is,
<tscreen><verb>
         variable x = 1, y = sin (x);
</verb></tscreen>
   are legal variable declarations.  This also provides a convenient way
   of initializing a variable.

   Variables are classified as either <em>global</em> or <em>local</em>. A
   variable declared inside a function is said to be local and has no
   meaning outside the function.  A variable is said to be global if
   it was declared outside a function.  Global variables are further
   classified as being <tt>public</tt>, <tt>static</tt>, or <tt>private</tt>,
   according to the name space where they were defined.
   See chapter ??? for more information about name spaces.

   The following global variables are predefined by the language and
   are mainly used as convenience variables:
<tscreen><verb>
      &dollar;0 &dollar;1 &dollar;2 &dollar;3 &dollar;4 &dollar;5 &dollar;6 &dollar;7 &dollar;8 &dollar;9
</verb></tscreen>

   An <em>intrinsic</em> variable is another type of global variable.
   Such variables have a definite type which cannot be altered.
   Variables of this type may also be defined to be read-only, or
   constant variables.  An example of an intrinsic variable is
   <tt>PI</tt> which is a read-only double precision variable with a value
   of approximately <tt>3.14159265358979323846</tt>.
   

<chapt>Operators<p> 

   <bf>S-Lang</bf> supports a variety of operators that are grouped into three
   classes: assignment operators, binary operators, and unary operators.

   An assignment operator is used to assign a value to a variable.
   They will be discussed more fully in the context of the assignment
   statement in section ???.

   An unary operator acts only upon a single quantity while a binary
   operation is an operation between two quantities.  The boolean
   operator <tt>not</tt> is an example of an unary operator.  Examples of
   binary operators include the usual arithmetic operators
   <tt>+</tt>, <tt>-</tt>, <tt>*</tt>, and <tt>/</tt>.  The operator given by
   <tt>-</tt> can be either an unary operator (negation) or a binary operator
   (subtraction); the actual operation is determined from the context
   in which it is used.

   Binary operators are used in algebraic forms, e.g., <tt>a + b</tt>.
   Unary operators fall in one of two classes: postfix-unary or
   prefix-unary.  For example, in the expression <tt>-x</tt>, the minus
   sign is a prefix-unary operator.
   
   Not all data types have binary or unary operations defined.  For
   example, while <tt>String_Type</tt> objects support the <tt>+</tt>
   operator, they do not admit the <tt>*</tt> operator.

<sect>Unary Operators<p>

   The <bf>unary</bf> operators operate only upon a single operand.  They
   include: <tt>not</tt>, <tt>~</tt>, <tt>-</tt>, <tt>@</tt>, <tt>&amp;</tt>, as well as the
   increment and decrement operators <tt>++</tt> and <tt>--</tt>,
   respectively.

   The boolean operator <tt>not</tt> acts only upon integers and produces
   <tt>0</tt> if its operand is non-zero, otherwise it produces <tt>1</tt>.

   The bit-level not operator <tt>~</tt> performs a similar function,
   except that it operates on the individual bits of its integer
   operand.

   The arithmetic negation operator <tt>-</tt> is the most well-known
   unary operator.  It simply reverses the sign of its operand.

   The reference (<tt>&amp;</tt>) and dereference (<tt>@</tt>) operators will be
   discussed in greater detail in section ???.  Similarly, the
   increment (<tt>++</tt>) and decrement (<tt>--</tt>) operators will be
   discussed in the context of the assignment operator.

<sect>Binary Operators<p> 

   The binary operators may be grouped according to several classes:
   arithmetic operators, relational operators, boolean operators, and
   bitwise operators.
   
   All binary and unary operators may be overloaded.  For example, the
   arithmetic plus operator has been overloaded by the
   <tt>String_Type</tt> data type to permit concatenation between strings.

<sect1>Arithmetic Operators<p> 

   The arithmetic operators include <tt>+</tt>, <tt>-</tt>, <tt>*</tt>, <tt>/</tt>,
   which perform addition, subtraction, multiplication, and division,
   respectively.  In addition to these, <bf>S-Lang</bf> supports the <tt>mod</tt>
   operator as well as the power operator <tt>^</tt>.

   The data type of the result produced by the use of one of these
   operators depends upon the data types of the binary participants.
   If they are both integers, the result will be an integer.  However,
   if the operands are not of the same type, they will be converted to
   a common type before the operation is performed.  For example, if
   one is a floating point value and the other is an integer, the
   integer will be converted to a float. In general, the promotion
   from one type to another is such that no information is lost, if
   possible.  As an example, consider the expression <tt>8/5</tt> which
   indicates division of the integer <tt>8</tt> by the integer <tt>5</tt>.
   The result will be the integer <tt>1</tt> and <em>not</em> the floating
   point value <tt>1.6</tt>.  However, <tt>8/5.0</tt> will produce
   <tt>1.6</tt> because <tt>5.0</tt> is a floating point number.


<sect1>Relational Operators<p> 

   The relational operators are <tt>&gt;</tt>, <tt>&gt;=</tt>, <tt>&lt;</tt>, <tt>&lt;=</tt>,
   <tt>==</tt>, and <tt>!=</tt>.  These perform the comparisons greater
   than, greater than or equal, less than, less than or equal, equal,
   and not equal, respectively.  The result of one of these
   comparisons is the integer <tt>1</tt> if the comparison is true, or
   <tt>0</tt> if the comparison is false.  For example, <tt>6 &gt;= 5</tt>
   returns <tt>1</tt>, but <tt>6 == 5</tt> produces
   <tt>0</tt>.


<sect1>Boolean Operators<p> 
   There are only two boolean binary operators: <tt>or</tt> and
   <tt>and</tt>.  These operators are defined only for integers and
   produce an integer result.  The <tt>or</tt> operator returns <tt>1</tt>
   if either of its operands are non-zero, otherwise it produces
   <tt>0</tt>.  The <tt>and</tt> operator produces <tt>1</tt> if and only if
   both its operands are non-zero, otherwise it produces <tt>0</tt>.

   Neither of these operators perform the so-called boolean
   short-circuit evaluation.  For example, consider the expression:
<tscreen><verb>
      (x != 0) and (1/x &gt; 10)
</verb></tscreen>
   Here, if <tt>x</tt> were to have a value of zero, a division by zero error
   would occur because even though <tt>x!=0</tt> evaluates to zero, the
   <tt>and</tt> operator is not short-circuited and the <tt>1/x</tt> expression
   would still be evaluated.  Although these operators are not
   short-circuited, <bf>S-Lang</bf> does have another mechanism of performing
   short-circuit boolean evaluation via the <tt>orelse</tt> and
   <tt>andelse</tt> expressions.  See below for information about these
   constructs.


<sect1>Bitwise Operators<p> 

   The bitwise binary operators are defined only with integer operands
   and are used for bit-level operations.  Operators that fall in this
   class include <tt>&amp;</tt>, <tt>|</tt>, <tt>shl</tt>, <tt>shr</tt>, and
   <tt>xor</tt>.  The <tt>&amp;</tt> operator performs a boolean AND operation
   between the corresponding bits of the operands.  Similarly, the
   <tt>|</tt> operator performs the boolean OR operation on the bits.
   The bit-shifting operators <tt>shl</tt> and <tt>shr</tt> shift the bits
   of the first operand by the number given by the second operand to
   the left or right, respectively.  Finally, the <tt>xor</tt> performs
   an EXCLUSIVE-OR operation.

   These operators are commonly used to manipulate variables whose
   individual bits have distinct meanings.  In particular, <tt>&amp;</tt> is
   usually used to test bits, <tt>|</tt> can be used to set bits, and
   <tt>xor</tt> may be used to flip a bit.

   As an example of using <tt>&amp;</tt> to perform tests on bits, consider
   the following: The <bf>jed</bf> text editor stores some of the information
   about a buffer in a bitmapped integer variable.  The value of this
   variable may be retrieved using the <bf>jed</bf> intrinsic function
   <tt>getbuf_info</tt>, which actually returns four quantities: the
   buffer flags, the name of the buffer, directory name, and file
   name.  For the purposes of this section, only the buffer flags are
   of interest and can be retrieved via a function such as
<tscreen><verb>
      define get_buffer_flags ()
      {
         variable flags;
         (,,,flags) = getbuf_info ();
         return flags;
      }
</verb></tscreen>
   The buffer flags is a bitmapped quantity where the 0th bit
   indicates whether or not the buffer has been modified, the first
   bit indicates whether or not autosave has been enabled for the
   buffer, and so on.  Consider for the moment the task of determining
   if the buffer has been modified.  This can be
   determined by looking at the zeroth bit, if it is <tt>0</tt> the
   buffer has not been modified, otherwise it has.  Thus we can create
   the function,
<tscreen><verb>
     define is_buffer_modified ()
     {
        variable flags = get_buffer_flags ();
        return (flags &amp; 1);
     }
</verb></tscreen>
   where the integer <tt>1</tt> has been used since it has all of its
   bits set to <tt>0</tt>, except for the zeroth one, which is set to
   <tt>1</tt>.  (At this point, it should also be apparent that bits are
   numbered from zero, thus an <tt>8</tt> bit integer consists of bits
   <tt>0</tt> to <tt>7</tt>, where <tt>0</tt> is the least significant bit and
   <tt>7</tt> is the most significant one.)  Similarly, we can create another
   function
<tscreen><verb>
     define is_autosave_on ()
     {
        variable flags = get_buffer_flags ();
        return (flags &amp; 2);
     }
</verb></tscreen>
   to determine whether or not autosave has been turned on for the
   buffer.

   The <tt>shl</tt> operator may be used to form the integer with only
   the <em>nth</em> bit set.  For example, <tt>1 shl 6</tt> produces an
   integer with all bits set to zero except the sixth bit, which is
   set to one.  The following example exploits this fact:
<tscreen><verb>
     define test_nth_bit (flags, nth)
     {
        return flags &amp; (1 shl nth);
     }
</verb></tscreen>
  

<sect1>Namespace operator<p>
   The operator <tt>-&gt;</tt> is used to in conjunction with the name of a
   namespace to access an object within the namespace.  For example,
   if <tt>A</tt> is the name of a namespace containing the variable
   <tt>v</tt>, then <tt>A-&gt;v</tt> refers to that variable.

<sect1>Operator Precedence<p>

<sect1>Binary Operators and Functions Returning Multiple Values<p> 
   Care must be exercised when using binary operators with an operand
   the returns multiple values.  In fact, the current implementation
   of the <bf>S-Lang</bf> language will produce incorrect results if both
   operands of a binary expression return multiple values.  <em>At
   most, only one of operands of a binary expression can return
   multiple values, and that operand must be the first one, not the
   second.</em>  For example,
<tscreen><verb>
    define read_line (fp)
    {
       variable line, status;
       
       status = fgets (&amp;line, fp);
       if (status == -1)
         return -1;
       return (line, status);
    }
</verb></tscreen>
   defines a function, <tt>read_line</tt> that takes a single argument, a
   handle to an open file, and returns one or two values, depending
   upon the return value of <tt>fgets</tt>.  Now consider
<tscreen><verb>
        while (read_line (fp) &gt; 0)
          {
             text = ();
             % Do something with text
             .
             .
          }
</verb></tscreen>
   Here the relational binary operator <tt>&gt;</tt> forms a comparison
   between one of the return values (the one at the top of the stack)
   and <tt>0</tt>.  In accordance with the above rule, since <tt>read_line</tt>
   returns multiple values, it occurs as the left binary operand.
   Putting it on the right as in
<tscreen><verb>
        while (0 &lt; read_line (fp))    % Incorrect
          {
             text = ();
             % Do something with text
             .
             .
          }
</verb></tscreen>
   violates the rule and will result in the wrong answer.



<sect>Mixing Integer and Floating Point Arithmetic<p>

   If a binary operation (<tt>+</tt>, <tt>-</tt>, <tt>*</tt> , <tt>/</tt>) is
   performed on two integers, the result is an integer.  If at least
   one of the operands is a float, the other is converted to float and
   the result is float.  For example:
<tscreen><verb>
      11 / 2           --&gt; 5   (integer)
      11 / 2.0         --&gt; 5.5 (float)
      11.0 / 2         --&gt; 5.5 (float)
      11.0 / 2.0       --&gt; 5.5 (float)
</verb></tscreen>
   Finally note that only integers may be used as array indices, 
   loop control variables, and bit operations.  The conversion
   functions, <tt>int</tt> and <tt>float</tt>, may be used convert between
   floats and ints where appropriate, e.g.,
<tscreen><verb>
      int (1.5)         --&gt; 1 (integer)
      float(1.5)        --&gt; 1.5 (float)
      float (1)         --&gt; 1.0 (float)
</verb></tscreen>

<sect>Short Circuit Boolean Evaluation<p>

   The boolean operators <tt>or</tt> and <tt>and</tt> <em>are not short
   circuited</em> as they are in some languages.  <bf>S-Lang</bf> uses 
   <tt>orelse</tt> and <tt>andelse</tt> expressions for short circuit boolean
   evaluation.  However, these are not binary operators. Expressions
   of the form:
<tscreen>
        <em>expr-1</em> and <em>expr-2</em> and ... <em>expr-n</em>
</tscreen>
   can be replaced by the short circuited version using <tt>andelse</tt>:
<tscreen>
        andelse {<em>expr-1</em>} {<em>expr-2</em>} ... {<em>expr-n</em>}
</tscreen>
   A similar syntax holds for the <tt>orelse</tt> operator.  For example, consider
   the statement:
<tscreen><verb>
      if ((x != 0) and (1/x &gt; 10)) do_something ();
</verb></tscreen>
   Here, if <tt>x</tt> were to have a value of zero, a division by zero error
   would occur because even though <tt>x!=0</tt> evaluates to zero, the
   <tt>and</tt> operator is not short circuited and the <tt>1/x</tt> expression
   would be evaluated causing division by zero. For this case, the
   <tt>andelse</tt> expression could be used to avoid the problem:
<tscreen><verb>
      if (andelse
          {x != 0}
          {1 / x &gt; 10})  do_something ();
</verb></tscreen>


<chapt>Statements<p> 

   Loosely speaking, a <em>statement</em> is composed of <em>expressions</em>
   that are grouped according to the syntax or grammar of the language
   to express a complete computation.  Statements are analogous to
   sentences in a human language and expressions are like phrases.
   All statements in the <bf>S-Lang</bf> language must end in a semi-colon.

   A statement that occurs within a function is executed only during
   execution of the function.  However, statements that occur outside
   the context of a function are evaluated immediately.

   The language supports several different types of statements such as
   assignment statements, conditional statements, and so forth.  These
   are described in detail in the following sections.

<sect>Variable Declaration Statements<p>
   Variable declarations were already discussed in chapter ???.  For
   the sake of completeness, a variable declaration is a statement of
   the form
<tscreen>
     variable <em>variable-declaration-list</em> ;
</tscreen>
   where the <em>variable-declaration-list</em> is a comma separated list
   of one or more variable names with optional initializations, e.g.,
<tscreen><verb>
     variable x, y = 2, z;
</verb></tscreen>
<sect>Assignment Statements<p> 

   Perhaps the most well known form of statement is the <em>assignment
   statement</em>.  Statements of this type consist of a left-hand side,
   an assignment operator, and a right-hand side.  The left-hand side
   must be something to which an assignment can be performed.  Such
   an object is called an <em>lvalue</em>.
   
   The most common assignment operator is the simple assignment
   operator <tt>=</tt>.  Simple of its use include
<tscreen><verb>
      x = 3;
      x = some_function (10);
      x = 34 + 27/y + some_function (z);
      x = x + 3;
</verb></tscreen>
   In addition to the simple assignment operator, <bf>S-Lang</bf>
   also supports the assignment operators <tt>+=</tt> and <tt>-=</tt>.
   Internally, <bf>S-Lang</bf> transforms
<tscreen><verb>
       a += b;
</verb></tscreen>
   to
<tscreen><verb>
       a = a + b;
</verb></tscreen>
   Similarly, <tt>a -= b</tt> is transformed to <tt>a = a - b</tt>.  It is
   extremely important to realize that, in general, <tt>a+b</tt> is not
   equal to <tt>b+a</tt>.  This means that <tt>a+=b</tt> is not the same
   as <tt>a=b+a</tt>.  As an example consider
<tscreen><verb>
      a = "hello"; a += "world";
</verb></tscreen>
   After execution of these two statements, <tt>a</tt> will have the
   value <tt>"helloworld"</tt> and not <tt>"worldhello"</tt>.

   Since adding or subtracting <tt>1</tt> from a variable is quite
   common, <bf>S-Lang</bf> also supports the unary increment and decrement
   operators <tt>++</tt>, and <tt>--</tt>, respectively.  That is, for
   numeric data types, 
<tscreen><verb>
       x = x + 1;
       x += 1;
       x++;
</verb></tscreen>
   are all equivalent.  Similarly,
<tscreen><verb>
       x = x - 1;
       x -= 1;
       x--;
</verb></tscreen>
   are also equivalent.

   Strictly speaking, <tt>++</tt> and <tt>--</tt> are unary operators.  When
   used as <tt>x++</tt>, the <tt>++</tt> operator is said to be a
   <em>postfix-unary</em> operator.  However, when used as <tt>++x</tt> it is
   said to be a <em>prefix-unary</em> operator.  The current
   implementation does not distinguish between the two forms, thus
   <tt>x++</tt> and <tt>++x</tt> are equivalent.  The reason for this
   equivalence is <em>that assignment expressions do not return a value in
   the <bf>S-Lang</bf> language</em> as they do in C.  Thus one should exercise care
   and not try to write C-like code such as
<tscreen><verb>
      x = 10;
      while (--x) do_something (x);     % Ok in C, but not in S-Lang
</verb></tscreen>
   The closest valid <bf>S-Lang</bf> form involves a <em>comma-expression</em>:
<tscreen><verb>
      x = 10;
      while (x--, x) do_something (x);  % Ok in S-Lang and in C
</verb></tscreen>

   <bf>S-Lang</bf> also supports a <em>multiple-assignment</em> statement.  It is
   discussed in detail in section ???.


<sect>Conditional and Looping Statements<p> 

  <bf>S-Lang</bf> supports a wide variety of conditional and looping
  statements.  These constructs operate on statements grouped together
  in <em>blocks</em>.  A block is a sequence of <bf>S-Lang</bf> statements enclosed
  in braces and may contain other blocks. However, a block cannot
  include function declarations.  In the following,
  <em>statement-or-block</em> refers to either a single
  <bf>S-Lang</bf> statement or to a block of statements, and
  <em>integer-expression</em> is an integer-valued expression.
  <em>next-statement</em> represents the statement following the form
   under discussion.

<sect1>Conditional Forms<p> 
<sect2>if<p>
   The simplest condition statement is the <tt>if</tt> statement.  It
   follows the syntax
<tscreen>
        if (<em>integer-expression</em>) <em>statement-or-block</em>
        <em>next-statement</em>
</tscreen>
   If <em>integer-expression</em> evaluates to a non-zero result, then the
   statement or group of statements implied <em>statement-or-block</em>
   will get executed.  Otherwise, control will proceed to
   <em>next-statement</em>.

   An example of the use of this type of conditional statement is
<tscreen><verb>
       if (x != 0) 
         {
            y = 1.0 / x;
            if (x &gt; 0) z = log (x);
         }
</verb></tscreen>
   This example illustrates two <tt>if</tt> statements where the second
   <tt>if</tt> statement is part of the block of statements that belong to
   the first.

<sect2>if-else<p>
   Another form of <tt>if</tt> statement is the <em>if-else</em> statement.
   It follows the syntax:
<tscreen>
      if (<em>integer-expression</em>) <em>statement-or-block-1</em>
      else <em>statement-or-block-2</em>
      <em>next-statement</em>
</tscreen>
   Here, if <em>expression</em> returns non-zero,
   <em>statement-or-block-1</em> will get executed and control will pass
   on to <em>next-statement</em>. However, if <em>expression</em> returns zero,
   <em>statement-or-block-2</em> will get executed before continuing with
   <em>next-statement</em>.  A simple example of this form is
<tscreen><verb>
     if (x &gt; 0) z = log (x); else error ("x must be positive");
</verb></tscreen>
   Consider the more complex example:
<tscreen><verb>
     if (city == "Boston")
       if (street == "Beacon") found = 1;
     else if (city == "Madrid") 
       if (street == "Calle Mayor") found = 1;
     else found = 0;
</verb></tscreen>
   This example illustrates a problem that beginners have with
   <em>if-else</em> statements.  The grammar presented above shows that
   the this example is equivalent to
<tscreen><verb>
     if (city == "Boston")
       {
         if (street == "Beacon") found = 1;
         else if (city == "Madrid")
           {
             if (street == "Calle Mayor") found = 1;
             else found = 0;
           }
       }
</verb></tscreen>
   It is important to understand the grammar and not be seduced by the
   indentation!

<sect2>!if<p>

   One often encounters <tt>if</tt> statements similar to
<tscreen>
     if (<em>integer-expression</em> == 0) <em>statement-or-block</em>
</tscreen>
   or equivalently,
<tscreen>
     if (not(<em>integer-expression</em>)) <em>statement-or-block</em>
</tscreen>
   The <tt>!if</tt> statement was added to the language to simplify the
   handling of such statements.  It obeys the syntax
<tscreen>
     !if (<em>integer-expression</em>) <em>statement-or-block</em>
</tscreen>
   and is functionally equivalent to
<tscreen>
     if (not (<em>expression</em>)) <em>statement-or-block</em>
</tscreen>

<sect2>orelse, andelse<p>

  These constructs were discussed earlier.  The syntax for the
  <tt>orelse</tt> statement is:
<tscreen>
     orelse {<em>integer-expression-1</em>} ... {<em>integer-expression-n</em>}
</tscreen>
  This causes each of the blocks to be executed in turn until one of
  them returns a non-zero integer value.  The result of this statement
  is the integer value returned by the last block executed.  For
  example,
<tscreen><verb>
     orelse { 0 } { 6 } { 2 } { 3 }
</verb></tscreen>
  returns <tt>6</tt> since the second block is the first to return a
  non-zero result.  The last two block will not get executed.

  The syntax for the <tt>andelse</tt> statement is:
<tscreen>
     andelse {<em>integer-expression-1</em>} ... {<em>integer-expression-n</em>}
</tscreen>
  Each of the blocks will be executed in turn until one of
  them returns a zero value.  The result of this statement is the
  integer value returned by the last block executed.  For example,
<tscreen><verb>
     andelse { 6 } { 2 } { 0 } { 4 }
</verb></tscreen>
  returns <tt>0</tt> since the third block will be the last to execute.

<sect2>switch<p>
  The switch statement deviates the most from its C counterpart.  The
  syntax is:
<tscreen><verb>
          switch (x)
            { ...  :  ...}
              .
              .
            { ...  :  ...}
</verb></tscreen>
   The `<tt>:</tt>' operator is a special symbol which means to test
   the top item on the stack, and if it is non-zero, the rest of the block
   will get executed and control will pass out of the switch statement.
   Otherwise, the execution of the block will be terminated and the process
   will be repeated for the next block.  If a block contains no
   <tt>:</tt> operator, the entire block is executed and control will
   pass onto the next statement following the <tt>switch</tt> statement.
   Such a block is known as the <em>default</em> case.
   
   As a simple example, consider the following:
<tscreen><verb>
      switch (x)
        { x == 1 : print("Number is one.");}
        { x == 2 : print("Number is two.");}
        { x == 3 : print("Number is three.");}
        { x == 4 : print("Number is four.");}
        { x == 5 : print("Number is five.");}
        { print ("Number is greater than five.");}
</verb></tscreen>
   Suppose <tt>x</tt> has an integer value of <tt>3</tt>.  The first two
   blocks will terminate at the `<tt>:</tt>' character because each of the
   comparisons with <tt>x</tt> will produce zero.  However, the third
   block will execute to completion.  Similarly, if <tt>x</tt> is
   <tt>7</tt>, only the last block will execute in full.

   A more familiar way to write the previous example used the
   <tt>case</tt> keyword:
<tscreen><verb>
      switch (x)
        { case 1 : print("Number is one.");}
        { case 2 : print("Number is two.");}
        { case 3 : print("Number is three.");}
        { case 4 : print("Number is four.");}
        { case 5 : print("Number is five.");}
        { print ("Number is greater than five.");}
</verb></tscreen>
   The <tt>case</tt> keyword is a more useful comparison operator because
   it can perform a comparison between different data types while
   using <tt>==</tt> may result in a type-mismatch error.  For example,
<tscreen><verb>
      switch (x)
        { (x == 1) or (x == "one") : print("Number is one.");}
        { (x == 2) or (x == "two") : print("Number is two.");}
        { (x == 3) or (x == "three") : print("Number is three.");}
        { (x == 4) or (x == "four") : print("Number is four.");}
        { (x == 5) or (x == "five") : print("Number is five.");}
        { print ("Number is greater than five.");}
</verb></tscreen>
  will fail because the <tt>==</tt> operation is not defined between
  strings and integers.  The correct way to write this to use the
  <tt>case</tt> keyword:
<tscreen><verb>
      switch (x)
        { case 1 or case "one" : print("Number is one.");}
        { case 2 or case "two" : print("Number is two.");}
        { case 3 or case "three" : print("Number is three.");}
        { case 4 or case "four" : print("Number is four.");}
        { case 5 or case "five" : print("Number is five.");}
        { print ("Number is greater than five.");}
</verb></tscreen>


<sect1>Looping Forms<p> 

<sect2>while<p>
   The <tt>while</tt> statement follows the syntax
<tscreen>
      while (<em>integer-expression</em>) <em>statement-or-block</em>
      <em>next-statement</em>
</tscreen>
   It simply causes <em>statement-or-block</em> to get executed as long as
   <em>integer-expression</em> evaluates to a non-zero result.  For
   example, 
<tscreen><verb>
      i = 10; 
      while (i) 
        {
          i--;
          newline ();
        }
</verb></tscreen>
   will cause the <tt>newline</tt> function to get called 10 times.
   However, 
<tscreen><verb>
      i = -10;
      while (i) 
        {
          i--;
          newline ();
        }
</verb></tscreen>
   would loop forever (or until <tt>i</tt> wraps from the most negative
   integer value to the most positive and then decrements to zero).

   
   If you are a C programmer, do not let the syntax of the language
   seduce you into writing this example as you would in C:
<tscreen><verb>
      i = 10;
      while (i--) newline ();
</verb></tscreen>
   The fact is that expressions such as <tt>i--</tt> do not return a
   value in <bf>S-Lang</bf> as they do in C.  If you must write this way, use
   the comma operator as in
<tscreen><verb>
      i = 10;
      while (i, i--) newline ();
</verb></tscreen>

<sect2>do...while<p>
   The <tt>do...while</tt> statement follows the syntax
<tscreen>
      do 
         <em>statement-or-block</em>
      while (<em>integer-expression</em>);
</tscreen>
   The main difference between this statement and the <tt>while</tt>
   statement is that the <tt>do...while</tt> form performs the test
   involving <em>integer-expression</em> after each execution
   of <em>statement-or-block</em> rather than before.  This guarantees that
   <em>statement-or-block</em> will get executed at least once.
   
   A simple example from the <bf>jed</bf> editor follows:
<tscreen><verb>
     bob ();      % Move to beginning of buffer
     do
       {
          indent_line ();
       }
     while (down (1));
</verb></tscreen>
   This will cause all lines in the buffer to get indented via the
   <bf>jed</bf> intrinsic function <tt>indent_line</tt>.

<sect2>for<p>
   Perhaps the most complex looping statement is the <tt>for</tt>
   statement; nevertheless, it is a favorite of many programmers.
   This statement obeys the syntax
<tscreen>
    for (<em>init-expression</em>; <em>integer-expression</em>; <em>end-expression</em>) 
      <em>statement-or-block</em>
    <em>next-statement</em>
</tscreen>
   In addition to <em>statement-or-block</em>, its specification requires
   three other expressions.  When executed, the <tt>for</tt> statement
   evaluates <em>init-expression</em>, then it tests
   <em>integer-expression</em>.  If <em>integer-expression</em> returns zero,
   control passes to <em>next-statement</em>.  Otherwise, it executes
   <em>statement-or-block</em> as long as <em>integer-expression</em>
   evaluates to a non-zero result.  After every execution of
   <em>statement-or-block</em>, <em>end-expression</em> will get evaluated.
   
   This statement is <em>almost</em> equivalent to 
<tscreen>
    <em>init-expression</em>;
    while (<em>integer-expression</em>)
      {
         <em>statement-or-block</em>
         <em>end-expression</em>;
      }
</tscreen>
   The reason that they are not fully equivalent involves what happens
   when <em>statement-or-block</em> contains a <tt>continue</tt> statement.
   
   Despite the apparent complexity of the <tt>for</tt> statement, it is
   very easy to use.  As an example, consider
<tscreen><verb>
     sum = 0;
     for (i = 1; i &lt;= 10; i++) sum += i;
</verb></tscreen>
   which computes the sum of the first 10 integers.

<sect2>loop<p>
   The <tt>loop</tt> statement simply executes a block of code a fixed
   number of times.  It follows the syntax
<tscreen>
      loop (<em>integer-expression</em>) <em>statement-or-block</em>
      <em>next-statement</em>
</tscreen>
   If the <em>integer-expression</em> evaluates to a positive integer,
   <em>statement-or-block</em> will get executed that many times.
   Otherwise, control will pass to <em>next-statement</em>.
   
   For example,
<tscreen><verb>
      loop (10) newline ();
</verb></tscreen>
   will cause the function <tt>newline</tt> to get called 10 times.

<sect2>forever<p>
   The <tt>forever</tt> statement is similar to the <tt>loop</tt> statement
   except that it loops forever, or until a <tt>break</tt> or a
   <tt>return</tt> statement is executed.  It obeys the syntax
<tscreen>
     forever <em>statement-or-block</em>
</tscreen>
   A trivial example of this statement is
<tscreen><verb>
     n = 10;
     forever
       {
          if (n == 0) break;
          newline ();
          n--;
       }
</verb></tscreen>

<sect2>foreach<p>
   The <tt>foreach</tt> statement is used to loop over one or more
   statements for every element in a container object.  A container
   object is a data type that consists of other types.  Examples
   include both ordinary and associative arrays, structures, and
   strings.  Every time through the loop the current member of the
   object is pushed onto the stack.

   The simple type of <tt>foreach</tt> statement obeys the syntax
<tscreen>
     foreach (<em>container-object</em>) <em>statement-or-block</em>
</tscreen>
   Here <em>container-object</em> can be an expression that returns a
   container object.  A simple example is
<tscreen><verb>
     foreach (["apple", "peach", "pear"])
      {
         fruit = ();
         process_fruit (fruit);
      } 
</verb></tscreen>
   This example shows that if the container object is an array, then
   successive elements of the array are pushed onto the stack prior to
   each execution cycle.  If the container object is a string, then
   successive characters of the string are pushed onto the stack.

   What actually gets pushed onto the stack may be controlled via the
   <tt>using</tt> form of the <tt>foreach</tt> statement.  This more complex
   type of <tt>foreach</tt> statement follows the syntax
<tscreen>
     foreach ( <em>container-object</em> ) using ( <em>control-list</em> ) 
       <em>statement-or-block</em>
</tscreen>
   The allowed values of <em>control-list</em> will depend upon the type
   of container object.  For associative arrays (<tt>Assoc_Type</tt>),
   <em>control-list</em> specified whether <em>keys</em>, <em>values</em>, or both
   are pushed onto the stack.  For example,
<tscreen><verb>
     foreach (a) using ("keys") 
       {
          k = ();
           .
           .
       }
</verb></tscreen>
   results in the keys of the associative array <tt>a</tt> being pushed
   on the list.  However, 
<tscreen><verb>
     foreach (a) using ("values")
       {
          v = ();
           .
           .
       }
</verb></tscreen>
   will cause the values to be used, and
<tscreen><verb>
     foreach (a) using ("keys", "values")
       {
          (k,v) = ();
           .
           .
       }
</verb></tscreen>
  will use both the keys and values of the array.
  
  Similarly, for linked-lists of structures, one may walk the list via
  code like
<tscreen><verb>
     foreach (linked_list) using ("next")
       {
          s = ();
            .
            .
       }
</verb></tscreen>
  This <tt>foreach</tt> statement is equivalent
<tscreen><verb>
     s = linked_list;
     while (s != NULL)
       {
          .
          .
         s = s.next;
       }
</verb></tscreen>
  Consult the type-specific documentation for a discussion of the
  <tt>using</tt> control words, if any, appropriate for a given type.

<sect>break, return, continue<p>

   <bf>S-Lang</bf> also includes the non-local transfer functions <tt>return</tt>, <tt>break</tt>,
   and <tt>continue</tt>.  The <tt>return</tt> statement causes control to return to the
   calling function while the <tt>break</tt> and <tt>continue</tt> statements are used in
   the context of loop structures.  Consider:
<tscreen><verb>
       define fun ()
       {
          forever
            {
               s1;
               s2;
               ..
               if (condition_1) break;
               if (condition_2) return;
               if (condition_3) continue;
               ..
               s3;
            }
          s4;
          ..
       }
</verb></tscreen>
   Here, a function <tt>fun</tt> has been defined that contains a <tt>forever</tt>
   loop consisting of statements <tt>s1</tt>, <tt>s2</tt>,...,<tt>s3</tt>, and
   three <tt>if</tt> statements.  As long as the expressions <tt>condition_1</tt>,
   <tt>condition_2</tt>, and <tt>condition_3</tt> evaluate to zero, the statements
   <tt>s1</tt>, <tt>s2</tt>,...,<tt>s3</tt> will be repeatedly executed.  However,
   if <tt>condition_1</tt> returns a non-zero value, the <tt>break</tt> statement
   will get executed, and control will pass out of the <tt>forever</tt> loop to
   the statement immediately following the loop which in this case is
   <tt>s4</tt>. Similarly, if <tt>condition_2</tt> returns a non-zero number,
   the <tt>return</tt> statement will cause control to pass back to the
   caller of <tt>fun</tt>.  Finally, the <tt>continue</tt> statement will
   cause control to pass back to the start of the loop, skipping the
   statement <tt>s3</tt> altogether.





<chapt>Functions<p> 

   A function may be thought of as a group of statements that work
   together to perform a computation.  While there are no imposed
   limits upon the number statements that may occur within a function,
   it is considered poor programming practice if a function contains
   many statements. This notion stems from the belief that a function
   should have a simple, well defined purpose.

<sect>Declaring Functions<p> 

   Like variables, functions must be declared before they can be used. The
   <tt>define</tt> keyword is used for this purpose.  For example,
<tscreen><verb>
      define factorial ();
</verb></tscreen>
   is sufficient to declare a function named <tt>factorial</tt>.  Unlike
   the <tt>variable</tt> keyword used for declaring variables, the
   <tt>define</tt> keyword does not accept a list of names.  

   Usually, the above form is used only for recursive functions.  In
   most cases, the function name is almost always followed by a
   parameter list and the body of the function:
<tscreen>
      define <em>function-name</em> (<em>parameter-list</em>)
      {
         <em>statement-list</em>
      }
</tscreen>
   The <em>function-name</em> is an identifier and must conform to the
   naming scheme for identifiers discussed in chapter ???.
   The <em>parameter-list</em> is a comma-separated list of variable names
   that represent parameters passed to the function, and
   may be empty if no parameters are to be passed.
   The body of the function is enclosed in braces and consists of zero
   or more statements (<em>statement-list</em>).
   
   The variables in the <em>parameter-list</em> are implicitly declared,
   thus, there is no need to declare them via a variable declaration
   statement.  In fact any attempt to do so will result in a syntax
   error.
   

<sect>Parameter Passing Mechanism<p> 

   Parameters to a function are always passed by value and never by
   reference.  To see what this means, consider
<tscreen><verb>
     define add_10 (a) 
     {
        a = a + 10;
     }
     variable b = 0;
     add_10 (b);
</verb></tscreen>
   Here a function <tt>add_10</tt> has been defined, which when executed,
   adds <tt>10</tt> to its parameter.  A variable <tt>b</tt> has also been
   declared and initialized to zero before it is passed to
   <tt>add_10</tt>.  What will be the value of <tt>b</tt> after the call to
   <tt>add_10</tt>?  If <bf>S-Lang</bf> were a language that passed parameters by
   reference, the value of <tt>b</tt> would be changed to
   <tt>10</tt>.  However, <bf>S-Lang</bf> always passes by value, which means that
   <tt>b</tt> would retain its value of zero after the function call.
   
   <bf>S-Lang</bf> does provide a mechanism for simulating pass by reference
   via the reference operator.  See the next section for more details.
   
   If a function is called with a parameter in the parameter list
   omitted, the corresponding variable in the function will be set to
   <tt>NULL</tt>.  To make this clear, consider the function
<tscreen><verb>
     define add_two_numbers (a, b)
     {
        if (a == NULL) a = 0;
        if (b == NULL) b = 0;
        return a + b;
     }
</verb></tscreen>
   This function must be called with two parameters.  However, we can
   omit one or both of the parameters by calling it in one of the
   following ways:
<tscreen><verb>
     variable s = add_two_numbers (2,3);
     variable s = add_two_numbers (2,);
     variable s = add_two_numbers (,3);
     variable s = add_two_numbers (,);
</verb></tscreen>
   The first example calls the function using both parameters;
   however, at least one of the parameters was omitted in the other
   examples.  The interpreter will implicitly convert the last three
   examples to
<tscreen><verb>
     variable s = add_two_numbers (2, NULL);
     variable s = add_two_numbers (NULL, 3);
     variable s = add_two_numbers (NULL, NULL);
</verb></tscreen>
   It is important to note that this mechanism is available only for
   function calls that specify more than one parameter.  That is,
<tscreen><verb>
     variable s = add_10 ();
</verb></tscreen>
  is <em>not</em> equivalent to <tt>add_10(NULL)</tt>.  The reason for this
  is simple: the parser can only tell whether or not <tt>NULL</tt> should
  be substituted by looking at the position of the comma character in
  the parameter list, and only function calls that indicate more than
  one parameter will use a comma.  A mechanism for handling single
  parameter function calls is described in the next section.


<sect>Referencing Variables<p> 

   One can achieve the effect of passing by reference by using the
   reference (<tt>&amp;</tt>) and dereference (<tt>@</tt>) operators. Consider
   again the <tt>add_10</tt> function presented in the previous section.
   This time we write it as
<tscreen><verb>
     define add_10 (a)
     {  
        @a = @a + 10;
     }
     variable b = 0;
     add_10 (&amp;b);
</verb></tscreen>
   The expression <tt>&amp;b</tt> creates a <em>reference</em> to the variable
   <tt>b</tt> and it is the reference that gets passed to <tt>add_10</tt>.
   When the function <tt>add_10</tt> is called, the value of <tt>a</tt> will
   be a reference to <tt>b</tt>.  It is only by <em>dereferencing</em> this
   value that <tt>b</tt> can be accessed and changed.  So, the statement
   <tt>@a=@a+10;</tt> should be read `add <tt>10</tt>' to the value of the
   object that <tt>a</tt> references and assign the result to the object
   that <tt>a</tt> references.
   
   The reader familiar with C will note the similarity between
   <em>references</em> in <bf>S-Lang</bf> and <em>pointers</em> in C.  

   One of the main purposes for references is that this mechanism
   allows reference to functions to be passed to other functions.  As
   a simple example from elementary calculus, consider the following
   function which returns an approximation to the derivative of another
   function at a specified point:
<tscreen><verb>
     define derivative (f, x)
     {
        variable h = 1e-6;
        return (@f(x+h) - @f(x)) / h;
     }
</verb></tscreen>
   It can be used to differentiate the function
<tscreen><verb>
     define x_squared (x)
     {
        return x^2;
     }
</verb></tscreen>
   at the point <tt>x = 3</tt> via the expression
   <tt>derivative(&amp;x_squared,3)</tt>.



<sect>Functions with a Variable Number of Arguments<p> 

  <bf>S-Lang</bf> functions may be defined to take a variable number of
  arguments.  The reason for this is that the calling routine pushes
  the arguments onto the stack before making a function call, and it
  is up to the called function to pop the values off the stack and
  make assignments to the variables in the parameter list.  These
  details are, for the most part, hidden from the programmer.
  However, they are important when a variable number of arguments are
  passed.

  Consider the <tt>add_10</tt> example presented earlier.  This time it
  is written
<tscreen><verb>
     define add_10 ()
     {
        variable x;
        x = ();
        return x + 10;
     }
     variable s = add_10 (12);  % ==&gt; s = 22;
</verb></tscreen>
  For the uninitiated, this example looks as if it
  is destined for disaster.  The <tt>add_10</tt> function looks like it
  accepts zero arguments, yet it was called with a single argument.
  On top of that, the assignment to <tt>x</tt> looks strange.  The truth
  is, the code presented in this example makes perfect sense, once you
  realize what is happening.
  
  First, consider what happened when <tt>add_10</tt> is called with the
  the parameter <tt>12</tt>.  Internally, <tt>12</tt> is
  pushed onto the stack and then the function called.  Now,
  consider the function itself.  <tt>x</tt> is a variable local to the
  function.  The strange looking assignment `<tt>x=()</tt>' simply
  takes whatever is on the stack and assigns it to <tt>x</tt>.  In
  other words, after this statement, the value of <tt>x</tt> will be
  <tt>12</tt>, since <tt>12</tt> will be at the top of the stack.

  A generic function of the form
<tscreen><verb>
    define function_name (x, y, ..., z)
    {
       .
       .
    }
</verb></tscreen>
  is internally transformed by the interpreter to
<tscreen><verb>
    define function_name ()
    {
       variable x, y, ..., z;
       z = ();
       .
       .
       y = ();
       x = ();
       .
       .
    }
</verb></tscreen>
  before further parsing.  (The <tt>add_10</tt> function, as defined above, is
  already in this form.)  With this knowledge in hand, one can write a
  function that accepts a variable number of arguments.  Consider the
  function:
<tscreen><verb>
    define average_n (n)
    {
       variable x, y;
       variable sum;
       
       if (n == 1) 
         {
            x = ();
            sum = x;
         }
       else if (n == 2)
         {
            y = ();
            x = ();
            sum = x + y;
         }
       else error ("average_n: only one or two values supported");
       
       return sum / n;
   }
   variable ave1 = average_n (3.0, 1);        % ==&gt; 3.0
   variable ave2 = average_n (3.0, 5.0, 2);   % ==&gt; 4.0
</verb></tscreen>
  Here, the last argument passed to <tt>average_n</tt> is an integer
  reflecting the number of quantities to be averaged.  Although this
  example works fine, its principal limitation is obvious: it only
  supports one or two values.  Extending it to three or more values
  by adding more <tt>else if</tt> constructs is rather straightforward but
  hardly worth the effort.  There must be a better way, and there is:
<tscreen><verb>
   define average_n (n)
   {
      variable sum, x;
      sum = 0;
      loop (n) 
        {
           x = ();    % get next value from stack
           sum += x;
        }
      return sum / n;
   }
</verb></tscreen>
  The principal limitation of this approach is that one must still
  pass an integer that specifies how many values are to be averaged.

  Fortunately, a special variable exists that is local to every function
  and contains the number of values that were passed to the function.
  That variable has the name <tt>_NARGS</tt> and may be used as follows:
<tscreen><verb>
   define average_n ()
   {
      variable x, sum = 0;
      
      if (_NARGS == 0) error ("Usage: ave = average_n (x, ...);");

      loop (_NARGS)
        {
           x = ();
           sum += x;
        }
      return sum / _NARGS;
   }
</verb></tscreen>
  Here, if no arguments are passed to the function, a simple message
  that indicates how it is to be used is printed out.




<sect>Returning Values<p>

   As stated earlier, the usual way to return values from a function
   is via the <tt>return</tt> statement.  This statement has the
   simple syntax
<tscreen>
      return <em>expression-list</em> ;
</tscreen>
   where <em>expression-list</em> is a comma separated list of expressions.
   If the function does not return any values, the expression list
   will be empty.  As an example of a function that can return
   multiple values, consider
<tscreen><verb>
        define sum_and_diff (x, y)
        {
            variable sum, diff;

            sum = x + y;  diff = x - y;
            return sum, diff;
        }
</verb></tscreen>
   which is a function returning two values.

   It is extremely important to note that <em>the calling routine must
   explicitly handle all values returned by a function</em>.  Although
   some languages such as C do not have this restriction, <bf>S-Lang</bf> does
   and it is a direct result of a <bf>S-Lang</bf> function's ability to return
   many values and accept a variable number of parameters.  Examples
   of properly handling the above function include
<tscreen><verb>
       variable sum, diff;
       (sum, diff) = sum_and_diff (5, 4);  % ignore neither
       (sum, ) = sum_and_diff (5, 4);      % ignore diff
       (,) = sum_and_diff (5, 4);          % ignore both sum and diff
</verb></tscreen>
   See the section below on assignment statements for more information
   about this important point.

<sect>Multiple Assignment Statement<p> 

   <bf>S-Lang</bf> functions can return more than one value, e.g.,
<tscreen><verb>
       define sum_and_diff (x, y)
       {
          return x + y, x - y;
       }
</verb></tscreen>
   returns two values.  It accomplishes this by placing both values on
   the stack before returning.  If you understand how <bf>S-Lang</bf> functions
   handle a variable number of parameters (section ???), then it
   should be rather obvious that one assigns such values to variables.
   One way is to use, e.g.,
<tscreen><verb>
      sum_and_diff (9, 4);
      d = ();
      s = ();
</verb></tscreen>

   However, the most convenient way to accomplish this is to use a
   <em>multiple assignment statement</em> such as 
<tscreen><verb>
       (s, d) = sum_and_diff (9, 4);
</verb></tscreen>
   The most general form of the multiple assignment statement is
<tscreen><verb>
     ( var_1, var_2, ..., var_n ) = expression;
</verb></tscreen>
   In fact, internally the interpreter transforms this statement into
   the form
<tscreen><verb>
     expression; var_n = (); ... var_2 = (); var_1 = ();
</verb></tscreen>
   for further processing.

   If you do not care about one of return values, simply omit the
   variable name from the list.  For example,
<tscreen><verb>
        (s, ) = sum_and_diff (9, 4);
</verb></tscreen>
   assigns the sum of <tt>9</tt> and <tt>4</tt> to <tt>s</tt> and the
   difference (<tt>9-4</tt>) will be removed from the stack.

   As another example, the <bf>jed</bf> editor provides a function called
   <tt>down</tt> that takes an integer argument and returns an integer.
   It is used to move the current editing position down the number of
   lines specified by the argument passed to it.  It returns the number
   of lines it successfully moved the editing position.  Often one does
   not care about the return value from this function.  Although it is
   always possible to handle the return value via
<tscreen><verb>
       variable dummy = down (10);
</verb></tscreen>
   it is more convenient to use a multiple assignment expression and
   omit the variable name, e.g.,
<tscreen><verb>
       () = down (10);
</verb></tscreen>

   Some functions return a <em>variable number</em> of values instead of a
   <em>fixed number</em>.  Usually, the value at the top of the stack will
   indicate the actual number of return values.  For such functions,
   the multiple assignment statement cannot directly be used.  To see
   how such functions can be dealt with, consider the following
   function:
<tscreen><verb>
     define read_line (fp)
     {
        variable line;
        if (-1 == fgets (&amp;line, fp))
          return -1;
        return (line, 0);
     }
</verb></tscreen>
   This function returns either one or two values, depending upon the
   return value of <tt>fgets</tt>.  Such a function may be handled as in
   the following example:
<tscreen><verb>
      status = read_line (fp);
      if (status != -1)
        {
           s = ();
           .
           .
        }
</verb></tscreen>
   In this example, the <em>last</em> value returned by <tt>read_line</tt> is
   assigned to <tt>status</tt> and then tested.  If it is non-zero, the
   second return value is assigned to <tt>s</tt>.  In particular note the
   empty set of parenthesis in the assignment to <tt>s</tt>.  This simply
   indicates that whatever is on the top of the stack when the
   statement is executed will be assigned to <tt>s</tt>.

   Before leaving this section it is important to reiterate the fact
   that if a function returns a value, the caller must deal with that
   return value.  Otherwise, the value will continue to live onto the
   stack and may eventually lead to a stack overflow error.
   Failing to handle the return value of a function is the
   most common mistake that inexperienced <bf>S-Lang</bf> programmers make.
   For example, the <tt>fflush</tt> function returns a value that many C
   programmer's never check.  Instead of writing
<tscreen><verb>
      fflush (fp);
</verb></tscreen>
   as one could in C, a <bf>S-Lang</bf> programmer should write
<tscreen><verb>
      () = fflush (fp);
</verb></tscreen>
   in <bf>S-Lang</bf>.  (Many good C programmer's write <tt>(void)fflush(fp)</tt>
   to indicate that the return value is being ignored).


<sect>Exit-Blocks<p>

   An <em>exit-block</em> is a set of statements that get executed when a
   functions returns.  They are very useful for cleaning up when a
   function returns via an explicit call to <tt>return</tt> from deep
   within a function.
   
   An exit-block is created by using the <tt>EXIT_BLOCK</tt> keyword
   according to the syntax 
<tscreen>
      EXIT_BLOCK { <em>statement-list</em> }
</tscreen>
   where <em>statement-list</em> represents the list of statements that
   comprise the exit-block.  The following example illustrates the use
   of an exit-block:
<tscreen><verb>
      define simple_demo ()
      {
         variable n = 0;

         EXIT_BLOCK { message ("Exit block called."); }

         forever
          {
            if (n == 10) return;
            n++;
          }
      }
</verb></tscreen>
   Here, the function contains an exit-block and a <tt>forever</tt> loop.
   The loop will terminate via the <tt>return</tt> statement when <tt>n</tt>
   is 10.  Before it returns, the exit-block will get executed.

   A function can contain multiple exit-blocks, but only the last
   one encountered during execution will actually get executed.  For
   example,
<tscreen><verb>
      define simple_demo (n)
      {
         EXIT_BLOCK { return 1; }
         
         if (n != 1)
           {
              EXIT_BLOCK { return 2; }
           }
         return;
      }
</verb></tscreen>
   If <tt>1</tt> is passed to this function, the first exit-block will
   get executed because the second one would not have been encountered
   during the execution.  However, if some other value is passed, the
   second exit-block would get executed.  This example also
   illustrates that it is possible to explicitly return from an
   exit-block, although nested exit-blocks are illegal.


<chapt>Name Spaces<p> 

  By default, all global variables and functions are defined in the
  global namespace.  In addition to the global namespace, every
  compilation unit (e.g., a file containing <bf>S-Lang</bf> code) has an
  anonymous namespace.  Objects may be defined in the anonymous
  namespace via the <tt>static</tt> declaration keyword.  For example,
<tscreen><verb>
     static variable x;
     static define hello () { message ("hello"); }
</verb></tscreen>
  defines a variable <tt>x</tt> and a function <tt>hello</tt> in the
  anonymous namespace.  This is useful when one wants to define
  functions and variables that are only to be used within the file, or
  more precisely the compilation unit, that defines them.

  The <tt>implements</tt> function may be used to give the anonymous
  namespace a name to allow access to its objects from outside the
  compilation unit that defines them.  For example,
<tscreen><verb>
     implements ("foo");
     static variable x;
</verb></tscreen>
  allows the variable <tt>x</tt> to be accessed via <tt>foo-&gt;x</tt>, e.g.,
<tscreen><verb>
     if (foo-&gt;x == 1) foo-&gt;x = 2;
</verb></tscreen>

  The <tt>implements</tt> function does more than simply giving the
  anonymous namespace a name.  It also changes the default variable
  and function declaration mode from <tt>public</tt> to <tt>static</tt>.
  That is, 
<tscreen><verb>
     implements ("foo");
     variable x;
</verb></tscreen>
  and
<tscreen><verb>
     implements ("foo");
     static variable x;
</verb></tscreen>
  are equivalent.  Then to create a public object within the
  namespace, one must explicitly use the <tt>public</tt> keyword.

  Finally, the <tt>private</tt> keyword may be used to create an object
  that is truly private within the compilation unit.  For example,
<tscreen><verb>
    implements ("foo");
    variable x;
    private variable y;
</verb></tscreen>
  allows <tt>x</tt> to be accessed from outside the namespace via
  <tt>foo-&gt;x</tt>, however <tt>y</tt> cannot be accessed.


<chapt>Arrays<p> 

   An array is a container object that can contain many values of one
   data type.  Arrays are very useful objects and are indispensable
   for certain types of programming.  The purpose of this chapter is
   to describe how arrays are defined and used in the <bf>S-Lang</bf> language.
   
<sect>Creating Arrays<p> 

   The <bf>S-Lang</bf> language supports multi-dimensional arrays of all data
   types.  Since the <tt>Array_Type</tt> is a data type, one can even
   have arrays of arrays.  To create a multi-dimensional array of
   <em>SomeType</em> use the syntax
<tscreen><verb>
      SomeType [dim0, dim1, ..., dimN]
</verb></tscreen>
   Here <em>dim0</em>, <em>dim1</em>, ... <em>dimN</em> specify the size of
   the individual dimensions of the array.  The current implementation
   permits arrays consist of up to <tt>7</tt> dimensions.  When a
   numeric array is created, all its elements are initialized to zero.
   The initialization of other array types depend upon the data type,
   e.g., <tt>String_Type</tt> and <tt>Struct_Type</tt> arrays are
   initialized to <tt>NULL</tt>.

   As a concrete example, consider
<tscreen><verb>
     a = Integer_Type [10];
</verb></tscreen>
   which creates a one-dimensional array of <tt>10</tt> integers and
   assigns it to <tt>a</tt>.
   Similarly, 
<tscreen><verb>
     b = Double_Type [10, 3];
</verb></tscreen>
   creates a <tt>30</tt> element array of double precision numbers
   arranged in <tt>10</tt> rows and <tt>3</tt> columns, and assigns it to
   <tt>b</tt>.

<sect1>Range Arrays<p>

   There is a more convenient syntax for creating and initializing a
   1-d arrays.  For example, to create an array of ten
   integers whose elements run from <tt>1</tt> through <tt>10</tt>, one
   may simply use:
<tscreen><verb>
     a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
</verb></tscreen>
   Similarly, 
<tscreen><verb>
     b = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
</verb></tscreen>
   specifies an array of ten doubles.  
   
   An even more compact way of specifying a numeric array is to use a
   <em>range-array</em>.  For example,
<tscreen><verb>
     a = [0:9];
</verb></tscreen>
   specifies an array of 10 integers whose elements range from <tt>0</tt>
   through <tt>9</tt>.  The most general form of a range array is
<tscreen><verb>
     [first-value : last-value : increment]
</verb></tscreen>
   where the <em>increment</em> is optional and defaults to <tt>1</tt>. This
   creates an array whose first element is <em>first-value</em> and whose
   successive values differ by <em>increment</em>.  <em>last-value</em> sets
   an upper limit upon the last value of the array as described below.

   If the range array <tt>[a:b:c]</tt> is integer valued, then the
   interval specified by <tt>a</tt> and <tt>b</tt> is closed.  That is, the
   kth element of the array x_k is given by x_k=a+ck and
   must satisfy a&lt;=x_k&lt;=b.  Hence, the number of elements in an
   integer range array is given by the expression 1 + (b-a)/c.

   The situation is somewhat more complicated for floating point range
   arrays.  The interval specified by a floating point range array
   <tt>[a:b:c]</tt> is semi-open such that <tt>b</tt> is not contained in
   the interval.  In particular, the kth element of <tt>[a:b:c]</tt> is
   given by x_k=a+kc such that a&lt;=x_k&lt;b when
   c&gt;=0, and b&lt;x_k&lt;=a otherwise.  The number of elements
   in the array is one greater than the largest k that
   satisfies the open interval constraint.

   Here are a few examples that illustrate the above comments:
<tscreen><verb>
       [1:5:1]         ==&gt; [1,2,3,4,5]
       [1.0:5.0:1.0]   ==&gt; [1.0, 2.0, 3.0, 4.0]
       [5:1:-1]        ==&gt; [5,4,3,2,1]
       [5.0:1.0:-1.0]  ==&gt; [5.0, 4.0, 3.0, 2.0];
       [1:1]           ==&gt; [1]
       [1.0:1.0]       ==&gt; []
       [1:-3]          ==&gt; []
</verb></tscreen>

<sect1>Creating arrays via the dereference operator<p>

   Another way to create an array is apply the dereference operator
   <tt>@</tt> to the <tt>DataType_Type</tt> literal <tt>Array_Type</tt>.  The
   actual syntax for this operation resembles a function call
<tscreen>
     variable a = @Array_Type (<em>data-type</em>, <em>integer-array</em>);
</tscreen>
  where <em>data-type</em> is of type <tt>DataType_Type</tt> and
  <em>integer-array</em> is a 1-d array of integers that specify the size
  of each dimension.  For example,
<tscreen><verb>
     variable a = @Array_Type (Double_Type, [10, 20]);
</verb></tscreen>
  will create a <tt>10</tt> by <tt>20</tt> array of doubles and assign it
  to <tt>a</tt>.  This method of creating arrays derives its power from
  the fact that it is more flexible than the methods discussed in this
  section.  We shall encounter it again in section ??? in the context
  of the <tt>array_info</tt> function.


<sect>Reshaping Arrays<p> 
   It is sometimes possible to change the `shape' of an array using
   the <tt>reshape</tt> function.  For example, a 1-d 10 element array
   may be reshaped into a 2-d array consisting of 5 rows and 2
   columns.  The only restriction on the operation is that the arrays
   must be commensurate.  The <tt>reshape</tt> function follows the
   syntax
<tscreen>
       reshape (<em>array-name</em>, <em>integer-array</em>);
</tscreen>
   where <em>array-name</em> specifies the array to be reshaped to have
   the dimensions given by <tt>integer-array</tt>, a 1-dimensional array of
   integers.  It is important to note that this does <em>not</em> create a
   new array, it simply reshapes the existing array.  Thus,
<tscreen><verb>
       variable a = Double_Type [100];
       reshape (a, [10, 10]);
</verb></tscreen>
   turns <tt>a</tt> into a <tt>10</tt> by <tt>10</tt> array.


<sect>Indexing Arrays<p> 
   An individual element of an array may be referred to by its
   <em>index</em>.  For example, <tt>a[0]</tt> specifies the zeroth element
   of the one dimensional array <tt>a</tt>, and <tt>b[3,2]</tt> specifies
   the element in the third row and second column of the two
   dimensional array <tt>b</tt>.  As in C array indices are numbered from
   <tt>0</tt>.  Thus if <tt>a</tt> is a one-dimensional array of ten
   integers, the last element of the array is given by <tt>a[9]</tt>.
   Using <tt>a[10]</tt> would result in a range error.
  
   A negative index may be used to index from the end of the array,
   with <tt>a[-1]</tt> referring to the last element of <tt>a</tt>,
   <tt>a[-2]</tt> referring to the next to the last element, and so on.

   One may use the indexed value like any other variable.  For
   example, to set the third element of an integer array to <tt>6</tt>, use
<tscreen><verb>
     a[2] = 6;
</verb></tscreen>
   Similarly, that element may be used in an expression, such as
<tscreen><verb>
     y = a[2] + 7;
</verb></tscreen>
   Unlike other <bf>S-Lang</bf> variables which inherit a type upon assignment,
   array elements already have a type.  For example, an attempt to
   assign a string value to an element of an integer array will result
   in a type-mismatch error.

   One may use any integer expression to index an array.  A simple
   example that computes the sum of the elements of 10 element 1-d
   array is
<tscreen><verb>
      variable i, sum;
      sum = 0;
      for (i = 0; i &lt; 10; i++) sum += a[i];
</verb></tscreen>
   
   Unlike many other languages, <bf>S-Lang</bf> permits arrays to be indexed by
   other integer arrays.   Suppose that <tt>a</tt> is a 1-d array of 10
   doubles.  Now consider:
<tscreen><verb>
      i = [6:8];
      b = a[i];
</verb></tscreen>
   Here, <tt>i</tt> is a 1-dimensional range array of three integers with
   <tt>i[0]</tt> equal to <tt>6</tt>, <tt>i[1]</tt> equal to <tt>7</tt>,
   and <tt>i[2]</tt> equal to <tt>8</tt>.  The statement <tt>b = a[i];</tt>
   will create a 1-d array of three doubles and assign it to <tt>b</tt>.
   The zeroth element of <tt>b</tt>, <tt>b[0]</tt> will be set to the sixth
   element of <tt>a</tt>, or <tt>a[6]</tt>, and so on.  In fact, these two simple
   statements are equivalent to
<tscreen><verb>
     b = Double_Type [3];
     b[0] = a[6];
     b[1] = a[7];
     b[2] = a[8];
</verb></tscreen>
   except that using an array of indices is not only much more
   convenient, but executes much faster.

   More generally, one may use an index array to specify which
   elements are to participate in a calculation.  For example, consider
<tscreen><verb>
     a = Double_Type [1000];
     i = [0:499];
     j = [500:999];
     a[i] = -1.0;
     a[j] = 1.0;
</verb></tscreen>
   This creates an array of <tt>1000</tt> doubles and sets the first
   <tt>500</tt> elements to <tt>-1.0</tt> and the last <tt>500</tt> to
   <tt>1.0</tt>.  Actually, one may do away with the <tt>i</tt> and <tt>j</tt>
   variables altogether and use
<tscreen><verb>
     a = Double_Type [1000];
     a [[0:499]] = -1.0;
     a [[500:999]] = 1.0;
</verb></tscreen>
   It is important to understand the syntax used and, in particular,
   to note that <tt>a[[0:499]]</tt> is <em>not</em> the same as
   <tt>a[0:499]</tt>.  In fact, the latter will generate a syntax error.
   
   Often, it is convenient to use a <em>rubber</em> range to specify
   indices.  For example, <tt>a[[500:]]</tt> specifies all elements of
   <tt>a</tt> whose index is greater than or equal to <tt>500</tt>.  Similarly,
   <tt>a[[:499]]</tt> specifies the first 500 elements of <tt>a</tt>.
   Finally, <tt>a[[:]]</tt> specifies all the elements of <tt>a</tt>;
   however, using <tt>a[*]</tt> is more convenient.

   Now consider a multi-dimensional array.  For simplicity, suppose
   that <tt>a</tt> is a <tt>100</tt> by <tt>100</tt> array of doubles.  Then
   the expression <tt>a[0, *]</tt> specifies all elements in the zeroth
   row.  Similarly, <tt>a[*, 7]</tt> specifies all elements in the
   seventh column.  Finally, <tt>a[[3:5][6:12]]</tt> specifies the
   <tt>3</tt> by <tt>7</tt> region consisting of rows <tt>3</tt>, <tt>4</tt>,
   and <tt>5</tt>, and columns <tt>6</tt> through <tt>12</tt> of <tt>a</tt>.

   We conclude this section with a few examples.

   Here is a function that computes the trace (sum of the diagonal
   elements) of a square 2 dimensional <tt>n</tt> by <tt>n</tt> array:
<tscreen><verb>
      define array_trace (a, n)
      {
         variable sum = 0, i;
         for (i = 0; i &lt; n; i++) sum += a[i, i];
         return sum;
      }
</verb></tscreen>
   This fragment creates a <tt>10</tt> by <tt>10</tt> integer array, sets
   its diagonal elements to <tt>5</tt>, and then computes the trace of
   the array: 
<tscreen><verb>
      a = Integer_Type [10, 10];
      for (j = 0; j &lt; 10; j++) a[j, j] = 5;
      the_trace = array_trace(a, 10);
</verb></tscreen>
   We can get rid of the <tt>for</tt> loop as follows:
<tscreen><verb>
      j = Integer_Type [10, 2];
      j[*,0] = [0:9];
      j[*,1] = [0:9];
      a[j] = 5;
</verb></tscreen>
   Here, the goal was to construct a 2-d array of indices that
   correspond to the diagonal elements of <tt>a</tt>, and then use that
   array to index <tt>a</tt>.  To understand how
   this works, consider the middle statements.  They are equivalent
   to the following <tt>for</tt> loops:
<tscreen><verb>
      variable i;
      for (i = 0; i &lt; 10; i++) j[i, 0] = i;
      for (i = 0; i &lt; 10; i++) j[i, 1] = i;
</verb></tscreen>
   Thus, row <tt>n</tt> of <tt>j</tt> will have the value <tt>(n,n)</tt>,
   which is precisely what was sought.
   
   Another example of this technique is the function:
<tscreen><verb>
      define unit_matrix (n)
      {
         variable a = Integer_Type [n, n];
         variable j = Integer_Type [n, 2];
         j[*,0] = [0:n - 1];
         j[*,1] = [0:n - 1];
         
         a[j] = 1;
         return a;
      }
</verb></tscreen>
   This function creates an <tt>n</tt> by <tt>n</tt> unit matrix,
   that is a 2-d <tt>n</tt> by <tt>n</tt> array whose elements are all zero
   except on the diagonal where they have a value of <tt>1</tt>.



<sect>Arrays and Variables<p>

   When an array is created and assigned to a variable, the
   interpreter allocates the proper amount of space for the array,
   initializes it, and then assigns to the variable a <em>reference</em>
   to the array.   So, a variable that represents an array has a value
   that is really a reference to the array.  This has several
   consequences, some good and some bad.  It is believed that the
   advantages of this representation outweigh the disadvantages.
   First, we shall look at the positive aspects.

   When a variable is passed to a function, it is always the value of
   the variable that gets passed.  Since the value of a variable
   representing an array is a reference, a reference to the array gets
   passed.  One major advantage of this is rather obvious: it is a
   fast and efficient way to pass the array.  This also has another
   consequence that is illustrated by the function
<tscreen><verb>
      define init_array (a, n)
      {
         variable i;
         
         for (i = 0; i &lt; n; i++) a[i] = some_function (i);
      }
</verb></tscreen>
   where <tt>some_function</tt> is a function that generates a scalar
   value to initialize the <em>ith</em> element.  This function can be
   used in the following way:
<tscreen><verb>
      variable X = Double_Type [100000];
      init_array (X, 100000);
</verb></tscreen>
   Since the array is passed to the function by reference, there is no
   need to make a separate copy of the <tt>100000</tt> element array. As
   pointed out above, this saves both execution time and memory. The
   other salient feature to note is that any changes made to the
   elements of the array within the function will be manifested in the
   array outside the function.  Of course, in this case, this is a
   desirable side-effect.

   To see the downside of this representation, consider:
<tscreen><verb>
      variable a, b;
      a = Double_Type [10];
      b = a;
      a[0] = 7;
</verb></tscreen>
   What will be the value of <tt>b[0]</tt>?  Since the value of <tt>a</tt>
   is really a reference to the array of ten doubles, and that
   reference was assigned to <tt>b</tt>, <tt>b</tt> also refers to the same
   array.  Thus any changes made to the elements of <tt>a</tt>, will also
   be made implicitly to <tt>b</tt>.

   This begs the question: If the assignment of one variable which
   represents an array, to another variable results in the assignment
   of a reference to the array, then how does one make separate copies
   of the array?  There are several answers including using an index
   array, e.g., <tt>b = a[*]</tt>; however, the most natural method is
   to use the dereference operator:
<tscreen><verb>
      variable a, b;
      a = Double_Type [10];
      b = @a;
      a[0] = 7;
</verb></tscreen>
   In this example, a separate copy of <tt>a</tt> will be created and
   assigned to <tt>b</tt>.  It is very important to note that <bf>S-Lang</bf>
   never implicitly dereferences an object.  So, one must explicitly use
   the dereference operator.  This means that the elements of a
   dereferenced array are not themselves dereferenced.  For example,
   consider dereferencing an array of arrays, e.g.,
<tscreen><verb>
      variable a, b;
      a = Array_Type [2];  
      a[0] = Double_Type [10];
      a[1] = Double_Type [10];
      b = @a;
</verb></tscreen>
   In this example, <tt>b[0]</tt> will be a reference to the array that
   <tt>a[0]</tt> references because <tt>a[0]</tt> was not explicitly
   dereferenced.

<sect>Using Arrays in Computations<p> 

   Many functions and operations work transparently with arrays.
   For example, if <tt>a</tt> and <tt>b</tt> are arrays, then the sum
   <tt>a + b</tt> is an array whose elements are formed from the sum of
   the corresponding elements of <tt>a</tt> and <tt>b</tt>.  A similar
   statement holds for all other binary and unary operations.

   Let's consider a simple example.  Suppose, that we wish to solve a
   set of <tt>n</tt> quadratic equations whose coefficients are given by
   the 1-d arrays <tt>a</tt>, <tt>b</tt>, and <tt>c</tt>.  In general, the
   solution of a quadratic equation will be two complex numbers.  For
   simplicity, suppose that all we really want is to know what subset of
   the coefficients, <tt>a</tt>, <tt>b</tt>, <tt>c</tt>, correspond to
   real-valued solutions.  In terms of <tt>for</tt> loops, we can write:
<tscreen><verb>
     variable i, d, index_array;
     index_array = Integer_Type [n];
     for (i = 0; i &lt; n; i++)
       {
          d = b[i]^2 - 4 * a[i] * c[i];
          index_array [i] = (d &gt;= 0.0);
       }
</verb></tscreen>
   In this example, the array <tt>index_array</tt> will contain a
   non-zero value if the corresponding set of coefficients has a
   real-valued solution.  This code may be written much more compactly
   and with more clarity as follows:
<tscreen><verb>
     variable index_array = ((b^2 - 4 * a * c) &gt;= 0.0);
</verb></tscreen>

   <bf>S-Lang</bf> has a powerful built-in function called <tt>where</tt>.  This
   function takes an array of integers and returns a 2-d array of
   indices that correspond to where the elements of the input array
   are non-zero.  This simple operation is extremely useful. For
   example, suppose <tt>a</tt> is a 1-d array of <tt>n</tt> doubles, and it
   is desired to set to zero all elements of the array whose value is
   less than zero. One way is to use a <tt>for</tt> loop:
<tscreen><verb>
     for (i = 0; i &lt; n; i++) 
       if (a[i] &lt; 0.0) a[i] = 0.0;
</verb></tscreen>
   If <tt>n</tt> is a large number, this statement can take some time to
   execute.  The optimal way to achieve the same result is to use the
   <tt>where</tt> function:
<tscreen><verb>
     a[where (a &lt; 0.0)] = 0;
</verb></tscreen>
   Here, the expression <tt>(a &lt; 0.0)</tt> returns an array whose
   dimensions are the same size as <tt>a</tt> but whose elements are
   either <tt>1</tt> or <tt>0</tt>, according to whether or not the
   corresponding element of <tt>a</tt> is less than zero.  This array of
   zeros and ones is then passed to <tt>where</tt> which returns a 2-d
   integer array of indices that indicate where the elements of
   <tt>a</tt> are less than zero.  Finally, those elements of <tt>a</tt> are
   set to zero.

   As a final example, consider once more the example involving the set of
   <tt>n</tt> quadratic equations presented above.  Suppose that we wish
   to get rid of the coefficients of the previous example that
   generated non-real solutions.  Using an explicit <tt>for</tt> loop requires
   code such as:
<tscreen><verb>
     variable i, j, nn, tmp_a, tmp_b, tmp_c;
     
     nn = 0;
     for (i = 0; i &lt; n; i++) 
       if (index_array [i]) nn++;
     
     tmp_a = Double_Type [nn];
     tmp_b = Double_Type [nn];
     tmp_c = Double_Type [nn];
     
     j = 0;
     for (i = 0; i &lt; n; i++)
       {
          if (index_array [i]) 
            {
               tmp_a [j] = a[i];
               tmp_b [j] = b[i];
               tmp_c [j] = c[i];
               j++;
            }
       }
     a = tmp_a;
     b = tmp_b;
     c = tmp_c;
</verb></tscreen>
   Not only is this a lot of code, it is also clumsy and error-prone.
   Using the <tt>where</tt> function, this task is trivial:
<tscreen><verb>
     variable i;
     i = where (index_array != 0);
     a = a[i];
     b = b[i];
     c = c[i];
</verb></tscreen>

   All the examples up to now assumed that the dimensions of the array
   were known.  Although the intrinsic function <tt>length</tt> may be
   used to get the total number of elements of an array, it cannot be
   used to get the individual dimensions of a multi-dimensional array.
   However, the function <tt>array_info</tt> may be used to
   get information about an array, such as its data type and size.
   The function returns three values: the data type, the number of
   dimensions, and an integer array containing the size
   of each dimension.  It may be used to determine the number of rows
   of an array as follows:
<tscreen><verb>
     define num_rows (a)
     {
        variable dims, type, num_dims;
        
        (dims, num_dims, type) = array_info (a);
        return dims[0];
     }  
</verb></tscreen>
   The number of columns may be obtained in a similar manner:
<tscreen><verb>
     define num_cols (a)
     {
        variable dims, type, num_dims;
        
        (dims, num_dims, type) = array_info (a);
        if (num_dims &gt; 1) return dims[1];
        return 1;
     }     
</verb></tscreen>
   
   Another use of <tt>array_info</tt> is to create an array that has the
   same number of dimensions as another array:
<tscreen><verb>
     define make_int_array (a)
     {
        variable dims, num_dims, type;
        
        (dims, num_dims, type) = array_info (a);
        return @Array_Type (Integer_Type, dims);
     }
</verb></tscreen>



<chapt>Associative Arrays<p> 

   An associative array differs from an ordinary array in the sense
   that its size is not fixed and that is indexed by a string, called
   the <em>key</em>. For example, consider:
<tscreen><verb>
       variable A = Assoc_Type [Integer_Type];
       A["alpha"] = 1;
       A["beta"] = 2;
       A["gamma"] = 3;
</verb></tscreen>
   Here, <tt>A</tt> represents an associative array of integers
   (<tt>Integer_Type</tt>) and three keys have been added to the array.
   
   As the example suggests, an associative array may be created using
   one of the following forms:
<tscreen>
      Assoc_Type [<em>type</em>]
      Assoc_Type [<em>type</em>, <em>default-value</em>]
      Assoc_Type []
</tscreen>
   The last form returns an associative array of <tt>Any_Type</tt>
   objects allowing any type of object to may be stored in
   the array.

   The form involving a <em>default-value</em> is useful for associating a
   default value for non-existent array members.  This feature is
   explained in more detail below.

   There are several functions that are specially designed to work
   with associative arrays.  These include:
<itemize>
<item> <tt>assoc_get_keys</tt>, which returns an ordinary array of strings
      containing the keys in the array.
   
<item> <tt>assoc_get_values</tt>, which returns an ordinary array of the
      values of the associative array.
   
<item> <tt>assoc_key_exists</tt>, which can be used to determine whether
      or not a key exists in the array.

<item> <tt>assoc_delete_key</tt>, which may be used to remove a key (and
      its value) from the array.
</itemize>

   To illustrate the use of an associative array, consider the problem
   of counting the number of repeated occurrences of words in a list.
   Let the word list be represented as an array of strings given by
   <tt>word_list</tt>.  The number of occurrences of each word may be
   stored in an associative array as follows:
<tscreen><verb>
     variable a, word;
     a = Assoc_Type [Integer_Type];
     foreach (word_list)
       {
          word = ();
          if (0 == assoc_key_exists (a, word))
            a[word] = 0;
          a[word]++;  % same as a[word] = a[word] + 1;
       }
</verb></tscreen>
   Note that <tt>assoc_key_exists</tt> was necessary to determine whether
   or not a word was already added to the array in order to properly
   initialize it.  However, by creating the associative array with a
   default value of <tt>0</tt>, the above code may be simplified to
<tscreen><verb>
     variable a, word;
     a = Assoc_Type [Integer_Type, 0];
     foreach (word_list)
       {
          word = ();
          a[word]++;
       }
</verb></tscreen>



<chapt>Structures and User-Defined Types<p> 

   A <em>structure</em> is a heterogeneous container object, i.e., it is
   an object with elements whose values do not have to be of the same
   data type.  The elements or fields of a structure are named, and
   one accesses a particular field of the structure via the field
   name. This should be contrasted with an array whose values are of
   the same type, and whose elements are accessed via array indices.

   A <em>user-defined</em> data type is a structure with a fixed set of
   fields defined by the user.
   
<sect>Defining a Structure<p>

   The <tt>struct</tt> keyword is used to define a structure.  The syntax
   for this operation is:
<tscreen>
     struct {<em>field-name-1</em>, <em>field-name-2</em>, ... <em>field-name-N</em>};
</tscreen>
   This creates and returns a structure with <em>N</em> fields whose names
   are specified by <em>field-name-1</em>, <em>field-name-2</em>, ...,
   <em>field-name-N</em>.  When a structure is created, all its fields are
   initialized to <tt>NULL</tt>.

   For example,
<tscreen><verb>
     variable t = struct { city_name, population, next };
</verb></tscreen>
   creates a structure with three fields and assigns it to the
   variable <tt>t</tt>.

   Alternatively, a structure may be created by dereferencing
   <tt>Struct_Type</tt>.  For example, the above structure may also be
   created using one of the two forms:
<tscreen><verb>
      t = @Struct_Type ("city_name", "population", "next");
      t = @Struct_Type (["city_name", "population", "next"]);
</verb></tscreen>
   These are useful when creating structures dynamically where one does
   not know the name of the fields until run-time.

   Like arrays, structures are passed around via a references.  Thus,
   in the above example, the value of <tt>t</tt> is a reference to the
   structure.  This means that after execution of
<tscreen><verb>
     variable u = t;
</verb></tscreen>
   <em>both</em> <tt>t</tt> and <tt>u</tt> refer to the <em>same</em> structure,
   since only the reference was used in the assignment.  To actually
   create a new copy of the structure, use the <em>dereference</em>
   operator, e.g.,
<tscreen><verb>
     variable u = @t;
</verb></tscreen>

<sect>Accessing the Fields of a Structure<p>

   The dot (<tt>.</tt>) operator is used to specify the a particular
   field of structure.  If <tt>s</tt> is a structure and <tt>field_name</tt>
   is a field of the structure, then <tt>s.field_name</tt> specifies
   that field of <tt>s</tt>.  This specification can be used in
   expressions just like ordinary variables.  Again, consider
<tscreen><verb>
     variable t = struct { city_name, population, next };
</verb></tscreen>
   described in the last section.  Then,
<tscreen><verb>
     t.city_name = "New York";
     t.population = 13000000;
     if (t.population &gt; 200) t = t.next;
</verb></tscreen>
   are all valid statements involving the fields of <tt>t</tt>.

<sect>Linked Lists<p>

  One of the most important uses of structures is to create a
  <em>dynamic</em> data structure such as a <em>linked-list</em>.  A
  linked-list is simply a chain of structures that are linked together
  such that one structure in the chain is the value of a field of the
  previous structure in the chain.  To be concrete, consider the
  structure discussed earlier:
<tscreen><verb>
     variable t = struct { city_name, population, next };
</verb></tscreen>
  and suppose that we desire to create a list of such structures.
  The purpose of the <tt>next</tt> field is to provide the link to the
  next structure in the chain.  Suppose that there exists a function,
  <tt>read_next_city</tt>, that reads city names and populations from a
  file.  Then we can create the list via:
<tscreen><verb>
     define create_population_list ()
     {
        variable city_name, population, list_root, list_tail;
        variable next;
        
        list_root = NULL;
        while (read_next_city (&amp;city_name, &amp;population))
          {
             next = struct {city_name, population, next };

             next.city_name = city_name;
             next.population = population;
             next.next = NULL;

             if (list_root == NULL)
               list_root = next;
             else
               list_tail.next = next;
               
             list_tail = next;
          }
        return list_root;
     }
</verb></tscreen>
  In this function, the variables <tt>list_root</tt> and <tt>list_tail</tt>
  represent the beginning and end of the list, respectively. As long
  as <tt>read_next_city</tt> returns a non-zero value, a new structure is
  created, initialized, and then appended to the list via the
  <tt>next</tt> field of the <tt>list_tail</tt> structure.  On the first
  time through the loop, the list is created via the assignment to the
  <tt>list_root</tt> variable.  
  
  This function may be used as follows:
<tscreen><verb>
    variable Population_List = create_population_list ();
    if (Population_List == NULL) error ("List is empty");
</verb></tscreen>
  We can create other functions that manipulate the list.  An example is
  a function that finds the city with the largest population:
<tscreen><verb>
    define get_largest_city (list)
    {
       variable largest;

       largest = list;
       while (list != NULL)
         {
            if (list.population &gt; largest.population)
              largest = list;
            list = list.next;
         }
       return largest.city_name;
    }
    
    vmessage ("%s is the largest city in the list", 
               get_largest_city (Population_List)));
</verb></tscreen>
  The <tt>get_largest_city</tt> is a typical example of how one traverses
  a linear linked-list by starting at the head of the list and
  successively moves to the next element of the list via the
  <tt>next</tt> field.
  
  In the previous example, a <tt>while</tt> loop was used to traverse the
  linked list.  It is faster to use a <tt>foreach</tt> loop for this:
<tscreen><verb>
    define get_largest_city (list)
    {
       variable largest, elem;

       largest = list;
       foreach (list)
         {
            elem = ();
            if (item.population &gt; largest.population)
              largest = item;
         }
       return largest.city_name;
    }
</verb></tscreen>
  Here a <tt>foreach</tt> loop has been used to walk the list via its
  <tt>next</tt> field.  If the field name was not <tt>next</tt>, then it
  would have been necessary to use the <tt>using</tt> form of the
  <tt>foreach</tt> statement.  For example, if the field name implementing the
  linked list was <tt>next_item</tt>, then 
<tscreen><verb>
     foreach (list) using ("next_item")
     {
        elem = ();
        .
        .
     }
</verb></tscreen>
  would have been used.  In other words, unless otherwise indicated
  via the <tt>using</tt> clause, <tt>foreach</tt> walks the list using a field
  named <tt>next</tt>.
  
  Now consider a function that sorts the list according to population.
  To illustrate the technique, a <em>bubble-sort</em> will be used, not
  because it is efficient, it is not, but because it is simple and
  intuitive.
<tscreen><verb>
    define sort_population_list (list)
    {
       variable changed;
       variable node, next_node, last_node;
       do
         {
            changed = 0;
            node = list;
            next_node = node.next;
            last_node = NULL;
            while (next_node != NULL)
              {
                 if (node.population &lt; next_node.population)
                   {
                      % swap node and next_node
                      node.next = next_node.next;
                      next_node.next = node;
                      if (last_node != NULL)
                        last_node.next = next_node;
                      
                      if (list == node) list = next_node;
                      node = next_node;
                      next_node = node.next;
                      changed++;
                   }
                 last_node = node;
                 node = next_node;
                 next_node = next_node.next;
              }
         }
       while (changed);
       
       return list;
    }
</verb></tscreen>
   Note the test for equality between <tt>list</tt> and <tt>node</tt>, i.e.,
<tscreen><verb>
                      if (list == node) list = next_node;
</verb></tscreen>
   It is important to appreciate the fact that the values of these
   variables are references to structures, and that the 
   comparison only compares the references and <em>not</em> the actual
   structures they reference.  If it were not for this, the algorithm
   would fail.
   
<sect>Defining New Types<p>

   A user-defined data type may be defined using the <tt>typedef</tt>
   keyword.  In the current implementation, a user-defined data type
   is essentially a structure with a user-defined set of fields. For
   example, in the previous section a structure was used to represent
   a city/population pair.  We can define a data type called
   <tt>Population_Type</tt> to represent the same information:
<tscreen><verb>
      typedef struct 
      {
         city_name, 
         population
      } Population_Type;
</verb></tscreen>
   This data type can be used like all other data types.  For example,
   an array of Population_Type types can be created,
<tscreen><verb>
      variable a = Population_Type[10];
</verb></tscreen>
   and `populated' via expressions such as
<tscreen><verb>
      a[0].city_name = "Boston";
      a[0].population = 2500000;
</verb></tscreen>
   The new type <tt>Population_Type</tt> may also be used with the
   <tt>typeof</tt> function:
<tscreen><verb>
      if (Population_Type = typeof (a)) city = a.city_name;
</verb></tscreen>
   The dereference <tt>@</tt> may be used to create an instance of the
   new type:
<tscreen><verb>
     a = @Population_Type;
     a.city_name = "Calcutta";
     a.population = 13000000;
</verb></tscreen>



<chapt>Error Handling<p> 

   Many intrinsic functions signal errors in the event of failure.
   User defined functions may also generate an error condition via the
   <tt>error</tt> function.  Depending upon the severity of the error, it
   can be caught and cleared using a construct called an
   <em>error-block</em>.

<sect>Error-Blocks<p>

   When the interpreter encounters a recoverable run-time error, it
   will return to top-level by <em>unwinding</em> its function call
   stack.  Any error-blocks that it encounters as part of this
   unwinding process will get executed.  Errors such as syntax errors
   and memory allocation errors are not recoverable, and error-blocks
   will not get executed when such errors are encountered.

   An error-block is defined using the syntax
<tscreen><verb>
       ERROR_BLOCK { statement-list }
</verb></tscreen>
   where <em>statement-list</em> represents a list of statements that
   comprise the error-block.  A simple example of an error-block is
<tscreen><verb>
       define simple (a)
       {
          ERROR_BLOCK { message ("error-block executed"); }
          if (a) error ("Triggering Error");
          message ("hello");
       }
</verb></tscreen>
   Executing this function via <tt>simple(0)</tt> will result in the
   message <tt>"hello"</tt>.  However, calling it using <tt>simple(1)</tt>
   will generate an error that will be caught, but not cleared, by
   the error-block and the <tt>"error-block executed"</tt> message will
   result.
   
   Error-blocks are never executed unless triggered by an error.  The
   only exception to this is when the user explicitly indicates that
   the error-block in scope should execute.  This is indicated by the
   special keyword <tt>EXECUTE_ERROR_BLOCK</tt>.  For example,
   <tt>simple</tt> could be recoded as
<tscreen><verb>
       define simple (a)
       {
          variable err_string = "error-block executed";
          ERROR_BLOCK { message (err_string); }
          if (a) error ("Triggering Error");
          err_string = "hello";
          EXECUTE_ERROR_BLOCK;
       }
</verb></tscreen>
   Please note that <tt>EXECUTE_ERROR_BLOCK</tt> does not initiate an
   error condition; it simply causes the error-block to be executed
   and control will pass onto the next statement following the
   <tt>EXECUTE_ERROR_BLOCK</tt> statement.

<sect>Clearing Errors<p>

   Once an error has been caught by an error-block, the error can be cleared
   by the <tt>_clear_error</tt> function.  After the error has been cleared,
   execution will resume at the next statement at the level of the error block
   following the statement that generated the error.  For example, consider:
<tscreen><verb>
       define make_error ()
       {
           error ("Error condition created.");
           message ("This statement is not executed.");
       }

       define test ()
       {
           ERROR_BLOCK
             {
                _clear_error ();
             }
           make_error ();
           message ("error cleared.");
       }
</verb></tscreen>
   Calling <tt>test</tt> will trigger an error in the <tt>make_error</tt>
   function, but will get cleared in the <tt>test</tt> function.  The
   call-stack will unwind from <tt>make_error</tt> back into <tt>test</tt>
   where the error-block will get executed.  As a result, execution
   resumes after the statement that makes the call to <tt>make_error</tt>
   since this statement is at the same level as the error-block that
   cleared the error.

   Here is another example that illustrates how multiple error-blocks
   work:
<tscreen><verb>
       define example ()
       {
          variable n = 0, s = "";
          variable str;

          ERROR_BLOCK {
              str = sprintf ("s=%s,n=%d", s, n);
              _clear_error ();
          }

          forever
            {
              ERROR_BLOCK {
               s += "0";
               _clear_error ();
              }

              if (n == 0) error ("");

              ERROR_BLOCK {
               s += "1";
              }

              if (n == 1) error ("");
              n++;
            }
          return str;
       }
</verb></tscreen>
   Here, three error-blocks have been declared.  One has been declared
   outside the <tt>forever</tt> loop and the other two have been declared
   inside the <tt>forever</tt> loop.  Each time through the loop, the variable
   <tt>n</tt> is incremented and a different error-block is triggered.  The
   error-block that gets triggered is the last one encountered, since
   that will be the one in scope.  On the first time through the loop,
   <tt>n</tt> will be zero and the first error-block in the loop will get
   executed.  This error block clears the error and execution resumes
   following the <tt>if</tt> statement that triggered the error. The
   variable <tt>n</tt> will get incremented to <tt>1</tt> and, on the
   second cycle through the loop the second <tt>if</tt> statement
   will trigger an error causing the second error-block to execute.
   This time, the error is not cleared and the call-stack unwinds out
   of the <tt>forever</tt> loop, at which point the error-block outside
   the loop is in scope, causing it to execute. This error-block
   prints out the values of the variables <tt>s</tt> and <tt>n</tt>.  It
   will clear the error and execution resumes on the statement
   <em>following</em> the <tt>forever</tt> loop.  The result of this
   complicated series of events is that the function will return the
   string <tt>"s=01,n=1"</tt>. 


<chapt>Loading Files: evalfile and autoload<p> 

<chapt>File Input/Output<p> 

 <bf>S-Lang</bf> provides built-in supports for two different I/O facilities.
 The simplest interface is modeled upon the C language <tt>stdio</tt>
 streams interface and consists of functions such as <tt>fopen</tt>,
 <tt>fgets</tt>, etc.  The other interface is modeled on a lower level
 POSIX interface consisting of functions such as <tt>open</tt>,
 <tt>read</tt>, etc.  In addition to permitting more control, the lower
 level interface permits one to access network objects as well as disk
 files.

<sect>Input/Output via stdio<p>
<sect1>Stdio Overview<p>
 The <tt>stdio</tt> interface consists of the following functions:
<itemize>
<item> <tt>fopen</tt>, which opens a file for read or writing.

<item> <tt>fclose</tt>, which closes a file opened by <tt>fopen</tt>.

<item> <tt>fgets</tt>, used to read a line from the file.

<item> <tt>fputs</tt>, which writes text to the file.

<item> <tt>fprintf</tt>, used to write formatted text to the file.

<item> <tt>fwrite</tt>, which may be used to write objects to the
       file.

<item> <tt>fread</tt>, which reads a specified number of objects from
       the file.

<item> <tt>feof</tt>, which is used to test whether the file pointer is at the
       end of the file.

<item> <tt>ferror</tt>, which is used to see whether or not the stream
       associated with the file has an error.
  
<item> <tt>clearerr</tt>, which clears the end-of-file and error
       indicators for the stream.

<item> <tt>fflush</tt>, used to force all buffered data associated with
       the stream to be written out.

<item> <tt>ftell</tt>, which is used to query the file position indicator
       of the stream.
       
<item> <tt>fseek</tt>, which is used to set the position of the file
      position indicator of the stream.

<item> <tt>fgetslines</tt>, which reads all the lines in a text file and
      returns them as an array of strings.

</itemize>

 In addition, the interface supports the <tt>popen</tt> and <tt>pclose</tt>
 functions on systems where the corresponding C functions are available.

 Before reading or writing to a file, it must first be opened using
 the <tt>fopen</tt> function.  The only exceptions to this rule involves
 use of the pre-opened streams: <tt>stdin</tt>, <tt>stdout</tt>, and
 <tt>stderr</tt>.  <tt>fopen</tt> accepts two arguments: a file name and a
 string argument that indicates how the file is to be opened, e.g.,
 for reading, writing, update, etc.  It returns a <tt>File_Type</tt>
 stream object that is used as an argument to all other functions of
 the <tt>stdio</tt> interface.  Upon failure, it returns <tt>NULL</tt>.  See the
 reference manual for more information about <tt>fopen</tt>.

<sect1>Stdio Examples<p>

 In this section, some simple examples of the use of the <tt>stdio</tt>
 interface is presented.  It is important to realize that all the
 functions of the interface return something, and that return value
 must be dealt with.
 
 The first example involves writing a function to count the number of
 lines in a text file.  To do this, we shall read in the lines, one by
 one, and count them:
<tscreen><verb>
    define count_lines_in_file (file)
    {
       variable fp, line, count;
       
       fp = fopen (file, "r");    % Open the file for reading
       if (fp == NULL)
         verror ("%s failed to open", file);
         
       count = 0;
       while (-1 != fgets (&amp;line, fp))
         count++;
         
       () = fclose (fp);
       return count;
    }
</verb></tscreen>
 Note that <tt>&amp;line</tt> was passed to the <tt>fgets</tt> function.  When
 <tt>fgets</tt> returns, <tt>line</tt> will contain the line of text read in
 from the file.  Also note how the return value from <tt>fclose</tt> was
 handled.  
 
 Although the preceding example closed the file via <tt>fclose</tt>,
 there is no need to explicitly close a file because <bf>S-Lang</bf> will
 automatically close the file when it is no longer referenced.  Since
 the only variable to reference the file is <tt>fp</tt>, it would have
 automatically been closed when the function returned.

 Suppose that it is desired to count the number of characters in the
 file instead of the number of lines.  To do this, the <tt>while</tt>
 loop could be modified to count the characters as follows:
<tscreen><verb>
      while (-1 != fgets (&amp;line, fp))
        count += strlen (line);
</verb></tscreen>
 The main difficulty with this approach is that it will not work for
 binary files, i.e., files that contain null characters.  For such
 files, the file should be opened in <em>binary</em> mode via
<tscreen><verb>
      fp = fopen (file, "rb");
</verb></tscreen>
 and then the data read in using the <tt>fread</tt> function:
<tscreen><verb>
      while (-1 != fread (&amp;line, Char_Type, 1024, fp))
           count += bstrlen (line);
</verb></tscreen>
 The <tt>fread</tt> function requires two additional arguments: the type
 of object to read (<tt>Char_Type</tt> in the case), and the number of
 such objects to read.  The function returns the number of objects
 actually read, or -1 upon failure.  The <tt>bstrlen</tt> function was
 used to compute the length of <tt>line</tt> because for <tt>Char_Type</tt>
 or <tt>UChar_Type</tt> objects, the <tt>fread</tt> function assigns a
 <em>binary</em> string (<tt>BString_Type</tt>) to <tt>line</tt>.

 The <tt>foreach</tt> construct also works with <tt>File_Type</tt> objects.
 For example, the number of characters in a file may be counted via
<tscreen><verb>
     foreach (fp) using ("char")
     {
        ch = ();
        count++;
     }
</verb></tscreen>
 To count the number of lines, one can use:
<tscreen><verb>
     foreach (fp) using ("line")
     {
        line = ();
        num_lines++;
        count += strlen (line);
     }
</verb></tscreen>

 Finally, it should be mentioned that neither of these examples should
 be used to count the number of characters in a file when that
 information is more readily accessible by another means.  For
 example, it is preferable to get this information via the
 <tt>stat_file</tt> function:
<tscreen><verb>
     define count_chars_in_file (file)
     {
        variable st;
        
        st = stat_file (file);
        if (st == NULL)
          error ("stat_file failed.");
        return st.st_size;
     }
</verb></tscreen>

<sect>POSIX I/O<p>

<sect>Advanced I/O techniques<p>

  The previous examples illustrate how to read and write objects of a
  single data-type from a file, e.g.,
<tscreen><verb>
      num = fread (&amp;a, Double_Type, 20, fp);
</verb></tscreen>
  would result in a <tt>Double_Type[num]</tt> array being assigned to
  <tt>a</tt> if successful.  However, suppose that the binary data file
  consists of numbers in a specified byte-order.  How can one read
  such objects with the proper byte swapping?  The answer is to use
  the <tt>fread</tt> function to read the objects as <tt>Char_Type</tt> and
  then <em>unpack</em> the resulting string into the specified data type,
  or types.  This process is facilitated using the <tt>pack</tt> and
  <tt>unpack</tt> functions.

  The <tt>pack</tt> function follows the syntax
<tscreen>
    BString_Type pack (<em>format-string</em>, <em>item-list</em>);
</tscreen>
  and combines the objects in the <em>item-list</em> according to
  <em>format-string</em> into a binary string and returns the result.
  Likewise, the <tt>unpack</tt> function may be used to convert a binary
  string into separate data objects:
<tscreen>
   (<em>variable-list</em>) = unpack (<em>format-string</em>, <em>binary-string</em>);
</tscreen>

  The format string consists of one or more data-type specification
  characters, and each may be followed by an optional decimal length
  specifier. Specifically, the data-types are specified according to
  the following table:
<tscreen><verb>
     c     char
     C     unsigned char
     h     short
     H     unsigned short
     i     int
     I     unsigned int
     l     long
     L     unsigned long
     j     16 bit int
     J     16 unsigned int
     k     32 bit int
     K     32 bit unsigned int
     f     float
     d     double
     F     32 bit float
     D     64 bit float
     s     character string, null padded
     S     character string, space padded
     x     a null pad character
</verb></tscreen>
  A decimal length specifier may follow the data-type specifier. With
  the exception of the <tt>s</tt> and <tt>S</tt> specifiers, the length
  specifier indicates how many objects of that data type are to be
  packed or unpacked from the string.  When used with the <tt>s</tt> or
  <tt>S</tt> specifiers, it indicates the field width to be used.  If the
  length specifier is not present, the length defaults to one.

  With the exception of <tt>c</tt>, <tt>C</tt>, <tt>s</tt>, <tt>S</tt>, and
  <tt>x</tt>, each of these may be prefixed by a character that indicates
  the byte-order of the object:
<tscreen><verb>
     &gt;    big-endian order (network order)
     &lt;    little-endian order
     =    native byte-order
</verb></tscreen>
  The default is native byte order.

  Here are a few examples that should make this more clear:
<tscreen><verb>
     a = pack ("cc", 'A', 'B');         % ==&gt; a = "AB";
     a = pack ("c2", 'A', 'B');         % ==&gt; a = "AB";
     a = pack ("xxcxxc", 'A', 'B');     % ==&gt; a = "\0\0A\0\0B";
     a = pack ("h2", 'A', 'B');         % ==&gt; a = "\0A\0B" or "\0B\0A"
     a = pack ("&gt;h2", 'A', 'B');        % ==&gt; a = "\0\xA\0\xB"
     a = pack ("&lt;h2", 'A', 'B');        % ==&gt; a = "\0B\0A"
     a = pack ("s4", "AB", "CD");       % ==&gt; a = "AB\0\0"
     a = pack ("s4s2", "AB", "CD");     % ==&gt; a = "AB\0\0CD"
     a = pack ("S4", "AB", "CD");       % ==&gt; a = "AB  "
     a = pack ("S4S2", "AB", "CD");     % ==&gt; a = "AB  CD"
</verb></tscreen>
  
  When unpacking, if the length specifier is greater than one, then an
  array of that length will be returned.  In addition, trailing
  whitespace and null character are stripped when unpacking an object
  given by the <tt>S</tt> specifier.  Here are a few examples:
<tscreen><verb>
    (x,y) = unpack ("cc", "AB");         % ==&gt; x = 'A', y = 'B'
    x = unpack ("c2", "AB");             % ==&gt; x = ['A', 'B']
    x = unpack ("x&lt;H", "\0\xAB\xCD");    % ==&gt; x = 0xCDABuh
    x = unpack ("xxs4", "a b c\0d e f");  % ==&gt; x = "b c\0"
    x = unpack ("xxS4", "a b c\0d e f");  % ==&gt; x = "b c"
</verb></tscreen>

<sect1>Example: Reading /var/log/wtmp<p>

  Consider the task of reading the Unix system file
  <tt>/var/log/utmp</tt>, which contains login records about who logged
  onto the system.  This file format is documented in section 5 of the
  online Unix man pages, and consists of a sequence of entries
  formatted according to the C structure <tt>utmp</tt> defined in the
  <tt>utmp.h</tt> C header file.  The actual details of the structure
  may vary from one version of Unix to the other.  For the purposes of
  this example, consider its definition under the Linux operating
  system running on an Intel processor:
<tscreen><verb>
    struct utmp {
       short ut_type;              /* type of login */
       pid_t ut_pid;               /* pid of process */
       char ut_line[12];           /* device name of tty - "/dev/" */
       char ut_id[2];              /* init id or abbrev. ttyname */
       time_t ut_time;             /* login time */
       char ut_user[8];            /* user name */
       char ut_host[16];           /* host name for remote login */
       long ut_addr;               /* IP addr of remote host */
    };
</verb></tscreen>
  On this system, <tt>pid_t</tt> is defined to be an <tt>int</tt> and
  <tt>time_t</tt> is a <tt>long</tt>.  Hence, a format specifier for the
  <tt>pack</tt> and <tt>unpack</tt> functions is easily constructed to be:
<tscreen><verb>
     "h i S12 S2 l S8 S16 l"
</verb></tscreen>
  However, this particular definition is naive because it does not
  allow for structure padding performed by the C compiler in order to
  align the data types on suitable word boundaries.  Fortunately, the
  intrinsic function <tt>pad_pack_format</tt> may be used to modify a
  format by adding the correct amount of padding in the right places.
  In fact, <tt>pad_pack_format</tt> applied to the above format on an
  Intel-based Linux system produces the result:
<tscreen><verb>
     "h x2 i S12 S2 x2 l S8 S16 l"
</verb></tscreen>
  Here we see that 4 bytes of padding were added.

  The other missing piece of information is the size of the structure.
  This is useful because we would like to read in one structure at a
  time using the <tt>fread</tt> function.  Knowing the size of the
  various data types makes this easy; however it is even easier to use
  the <tt>sizeof_pack</tt> intrinsic function, which returns the size (in
  bytes) of the structure described by the pack format.
  
  So, with all the pieces in place, it is rather straightforward to
  write the code:
<tscreen><verb>
    variable format, size, fp, buf;
    
    typedef struct
    {
       ut_type, ut_pid, ut_line, ut_id,
       ut_time, ut_user, ut_host, ut_addr
    } UTMP_Type;

    format = pad_pack_format ("h i S12 S2 l S8 S16 l");
    size = sizeof_pack (format);

    define print_utmp (u)
    {
       
      () = fprintf (stdout, "%-16s %-12s %-16s %s\n",
		    u.ut_user, u.ut_line, u.ut_host, ctime (u.ut_time));
    }

       
   fp = fopen ("/var/log/utmp", "rb");
   if (fp == NULL)
     error ("Unable to open utmp file");

   () = fprintf (stdout, "%-16s %-12s %-16s %s\n",
                          "USER", "TTY", "FROM", "LOGIN@");

   variable U = @UTMP_Type;

   while (-1 != fread (&amp;buf, Char_Type, size, fp))
     {
	set_struct_fields (U, unpack (format, buf));
	print_utmp (U);
     }

   () = fclose (fp);
</verb></tscreen>
  A few comments about this example are in order.  First of all, note
  that a new data type called <tt>UTMP_Type</tt> was created, although
  this was not really necessary.  We also opened the file in binary
  mode, but this too is optional under a Unix system where there is no
  distinction between binary and text modes. The <tt>print_utmp</tt>
  function does not print all of the structure fields.  Finally, last
  but not least, the return values from <tt>fprintf</tt> and <tt>fclose</tt>
  were dealt with.


<chapt>Debugging<p> 

 The current implementation provides no support for an interactive
 debugger, although a future version will.  Nevertheless, <bf>S-Lang</bf> has
 several features that aid the programmer in tracking down problems,
 including function call tracebacks and the tracing of function calls.
 However, the biggest debugging aid stems from the fact that the
 language is interpreted permitting one to easily add debugging
 statements to the code.
  
 To enable debugging information, add the lines
<tscreen><verb>
    _debug_info = 1;
    _traceback = 1;
</verb></tscreen>
 to the top of the source file of the code containing the bug and the
 reload the file.  Setting the <tt>_debug_info</tt> variable to
 <tt>1</tt> causes line number information to be compiled into the
 functions when the file is loaded.  The <tt>_traceback</tt> variable
 controls whether or not traceback information should be generated.
 If it is set to <tt>1</tt>, the values of local variables will be
 dumped when the traceback is generated.  Setting this variable
 to <tt>-1</tt> will cause only function names to be reported in the
 traceback.

 Here is an example of a traceback report:
<tscreen><verb>
    S-Lang Traceback: error
    S-Lang Traceback: verror
    S-Lang Traceback: (Error occurred on line 65)
    S-Lang Traceback: search_generic_search
      Local Variables:
        &dollar;0: Type: String_Type,  Value:  "Search forward:"
        &dollar;1: Type: Integer_Type, Value:  1
        &dollar;2: Type: Ref_Type,     Value:  _function_return_1
        &dollar;3: Type: String_Type,  Value:  "abcdefg"
        &dollar;4: Type: Integer_Type, Value:  1
    S-Lang Traceback: (Error occurred on line 72)
    S-Lang Traceback: search_forward
</verb></tscreen>
 There are several ways to read this report; perhaps the simplest is
 to read it from the bottom.  This report says that on line <tt>72</tt>,
 the <tt>search_forward</tt> function called the
 <tt>search_generic_search</tt> function.  On line <tt>65</tt> it called the
 <tt>verror</tt> function, which called <tt>error</tt>.  The
 <tt>search_generic_search</tt> function contains <tt>5</tt> local variables
 and are represented symbolically as <tt>&dollar;0</tt> through <tt>&dollar;4</tt>.



<chapt>Regular Expressions<p>

 The S-Lang library includes a regular expression (RE) package that
 may be used by an application embedding the library.  The RE syntax
 should be familiar to anyone acquainted with regular expressions.  In
 this section the syntax of the <bf>S-Lang</bf> regular expressions is
 discussed.

<sect><bf>S-Lang</bf> RE Syntax<p>
 
 A regular expression specifies a pattern to be matched against a
 string, and has the property that the contcatenation of two REs is
 also a RE.
 
 The <bf>S-Lang</bf> library supports the following standard regular
 expressions: 
<tscreen><verb>
   .                 match any character except newline
   *                 matches zero or more occurences of previous RE
   +                 matches one or more occurences of previous RE
   ?                 matches zero or one occurence of previous RE
   ^                 matches beginning of a line
   &dollar;                 matches end of line
   [ ... ]           matches any single character between brackets.
                     For example, [-02468] matches `-' or any even digit.
		     and [-0-9a-z] matches `-' and any digit between 0 and 9
		     as well as letters a through z.
   \&lt;                Match the beginning of a word.
   \&gt;                Match the end of a word.
   \( ... \)
   \1, \2, ..., \9   Matches the match specified by nth \( ... \) 
                     expression.
</verb></tscreen>
 In addition the following extensions are also supported:
<tscreen><verb>
   \c                turn on case-sensitivity (default)
   \C                turn off case-sensitivity
   \d                match any digit
   \e                match ESC char
</verb></tscreen>
Here are some simple examples:

  <tt>"^int "</tt> matches the <tt>"int "</tt> at the beginning of a line.
  
  <tt>"\&lt;money\&gt;"</tt> matches <tt>"money"</tt> but only if it appears
  as a separate word.
  
  <tt>"^&dollar;"</tt> matches an empty line.
  
 A more complex pattern is
<tscreen><verb>
  "\(\&lt;[a-zA-Z]+\&gt;\)[ ]+\1\&gt;"
</verb></tscreen>
 which matches any word repeated consecutively.  Note how the grouping
 operators <tt>\(</tt> and <tt>\)</tt> are used to define the text
 matched by the enclosed regular expression, and then subsequently
 referred to <tt>\1</tt>.
 
 Finally, remember that when used in string literals either in the
 <bf>S-Lang</bf> language or in the C language, care must be taken to
 "double-up" the <tt>'\'</tt> character since both languages treat it
 as as an escape character.

<sect>Differences between <bf>S-Lang</bf> and egrep REs<p>

 There are several differences between <bf>S-Lang</bf> regular expressions and,
 e.g., <bf>egrep</bf> regular expressions.

 The most notable difference is that the <bf>S-Lang</bf> regular expressions do
 not support the <bf>OR</bf> operator <tt>|</tt> in expressions.  This means
 that <tt>"a|b"</tt> or <tt>"a\|b"</tt> do not have the meaning that they
 have in regular expression packages that support egrep-style
 expressions.

 The other main difference is that while <bf>S-Lang</bf> regular expressions
 support the grouping operators <tt>\(</tt> and <tt>\)</tt>, they are
 only used as a means of specifying the text that is matched.  That
 is, the expression
<tscreen><verb>
     "@\([a-z]*\)@.*@\1@"
</verb></tscreen>
 matches <tt>"xxx@abc@silly@abc@yyy"</tt>, where the pattern <tt>\1</tt>
 matches the text enclosed by the <tt>\(</tt> and <tt>\)</tt>
 expressions. However, in the current implementation, the grouping
 operators are not used to group regular expressions to form a single
 regular expression.  Thus expression such as <tt>"\(hello\)*"</tt> is
 <em>not</em> a pattern to match zero or more occurances of <tt>"hello"</tt>
 as it is in e.g., <bf>egrep</bf>.
 
 One question that comes up from time to time is why doesn't <bf>S-Lang</bf>
 simply employ some posix-compatible regular expression library.  The
 simple answer is that, at the time of this writing, none exists that
 is is available across all the platforms that the <bf>S-Lang</bf> library
 supports (Unix, VMS, OS/2, win32, win16, BEOS, MSDOS, and QNX) and
 can be distributed under both the GNU and Artistic licenses.  It is
 particularly important that the library and the interpreter support a
 common set of regular expressions in a platform independent manner.
 

<chapt>Future Directions<p> 

 Several new features or enhancements to the <bf>S-Lang</bf> language are
 planned for the next major release.  In no particular order, these
 include:
<itemize>
  <item> An interactive debugging facility.
  <item> Function qualifiers.  These entities should already be
  familiar to VMS users or to those who are familiar with the IDL
  language.  Basically, a qualifier is an optional argument that is
  passed to a function, e.g., <tt>plot(X,Y,/logx)</tt>.  Here
  <tt>/logx</tt> is a qualifier that specifies that the plot function
  should use a log scale for <tt>x</tt>.
  <item> File local variables and functions.  A file local variable or
  function is an object that is global to the file that defines it.
  <item> Multi-threading.  Currently the language does not support
  multiple threads.
</itemize>



<appendix>

<chapt>Copyright<p>
 The <bf>S-Lang</bf> library is distributed under two copyrights: the GNU
 Genral Public License, and the Artistic License.  Any program
 that uses the interpreter must adhere to rules of one of these
 licenses.

<sect>The GNU Public License<p>
<tscreen><verb>
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                          675 Mass Ave, Cambridge, MA 02139, USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble
</verb></tscreen>
  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.
<tscreen><verb>
		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
</verb></tscreen>
  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
<tscreen><verb>
    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)
</verb></tscreen>
These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
<tscreen><verb>
    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)
</verb></tscreen>
The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
<tscreen><verb>
			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS
</verb></tscreen>
	Appendix: How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<tscreen><verb>
    &lt;one line to give the program's name and a brief idea of what it does.&gt;
    Copyright (C) 19yy  &lt;name of author&gt;

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
</verb></tscreen>
Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
<tscreen><verb>
    Gnomovision version 69, Copyright (C) 19yy name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.
</verb></tscreen>
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:
<tscreen><verb>
  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  &lt;signature of Ty Coon&gt;, 1 April 1989
  Ty Coon, President of Vice
</verb></tscreen>
This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.

<sect>The Artistic License<p>
<tscreen><verb>
			 The "Artistic License"

				Preamble
</verb></tscreen>
The intent of this document is to state the conditions under which a
Package may be copied, such that the Copyright Holder maintains some
semblance of artistic control over the development of the package,
while giving the users of the package the right to use and distribute
the Package in a more-or-less customary fashion, plus the right to make
reasonable modifications.

Definitions:
<tscreen><verb>
	"Package" refers to the collection of files distributed by the
	Copyright Holder, and derivatives of that collection of files
	created through textual modification.

	"Standard Version" refers to such a Package if it has not been
	modified, or has been modified in accordance with the wishes
	of the Copyright Holder as specified below.

	"Copyright Holder" is whoever is named in the copyright or
	copyrights for the package.

	"You" is you, if you're thinking about copying or distributing
	this Package.

	"Reasonable copying fee" is whatever you can justify on the
	basis of media cost, duplication charges, time of people involved,
	and so on.  (You will not be required to justify it to the
	Copyright Holder, but only to the computing community at large
	as a market that must bear the fee.)

	"Freely Available" means that no fee is charged for the item
	itself, though there may be fees involved in handling the item.
	It also means that recipients of the item may redistribute it
	under the same conditions they received it.
</verb></tscreen>
1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.

2. You may apply bug fixes, portability fixes and other modifications
derived from the Public Domain or from the Copyright Holder.  A Package
modified in such a way shall still be considered the Standard Version.

3. You may otherwise modify your copy of this Package in any way, provided
that you insert a prominent notice in each changed file stating how and
when you changed that file, and provided that you do at least ONE of the
following:
<tscreen><verb>
    a) place your modifications in the Public Domain or otherwise make them
    Freely Available, such as by posting said modifications to Usenet or
    an equivalent medium, or placing the modifications on a major archive
    site such as uunet.uu.net, or by allowing the Copyright Holder to include
    your modifications in the Standard Version of the Package.

    b) use the modified Package only within your corporation or organization.

    c) rename any non-standard executables so the names do not conflict
    with standard executables, which must also be provided, and provide
    a separate manual page for each non-standard executable that clearly
    documents how it differs from the Standard Version.

    d) make other distribution arrangements with the Copyright Holder.
</verb></tscreen>
4. You may distribute the programs of this Package in object code or
executable form, provided that you do at least ONE of the following:
<tscreen><verb>
    a) distribute a Standard Version of the executables and library files,
    together with instructions (in the manual page or equivalent) on where
    to get the Standard Version.

    b) accompany the distribution with the machine-readable source of
    the Package with your modifications.

    c) give non-standard executables non-standard names, and clearly
    document the differences in manual pages (or equivalent), together
    with instructions on where to get the Standard Version.

    d) make other distribution arrangements with the Copyright Holder.
</verb></tscreen>
5. You may charge a reasonable copying fee for any distribution of this
Package.  You may charge any fee you choose for support of this
Package.  You may not charge a fee for this Package itself.  However,
you may distribute this Package in aggregate with other (possibly
commercial) programs as part of a larger (possibly commercial) software
distribution provided that you do not advertise this Package as a
product of your own.  You may embed this Package's interpreter within
an executable of yours (by linking); this shall be construed as a mere
form of aggregation, provided that the complete Standard Version of the
interpreter is so embedded.

6. The scripts and library files supplied as input to or produced as
output from the programs of this Package do not automatically fall
under the copyright of this Package, but belong to whomever generated
them, and may be sold commercially, and may be aggregated with this
Package.  If such scripts or library files are aggregated with this
Package via the so-called "undump" or "unexec" methods of producing a
binary executable image, then distribution of such an image shall
neither be construed as a distribution of this Package nor shall it
fall under the restrictions of Paragraphs 3 and 4, provided that you do
not represent such an executable image as a Standard Version of this
Package.

7. C subroutines (or comparably compiled subroutines in other
languages) supplied by you and linked into this Package in order to
emulate subroutines and variables of the language defined by this
Package shall not be considered part of this Package, but are the
equivalent of input as in Paragraph 6, provided these subroutines do
not change the language in any way that would cause it to fail the
regression tests for the language.

8. Aggregation of this Package with a commercial distribution is always
permitted provided that the use of this Package is embedded; that is,
when no overt attempt is made to make this Package's interfaces visible
to the end user of the commercial distribution.  Such use shall not be
construed as a distribution of this Package.

9. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.

10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.



</book>