slang.txt

./mudtem/slang/doc/text/slang.txt · 179.8 KB

From the archive mudtem.tar.gz

Download the archive   « Back to the archive contents

  A Guide to the S-Lang Language
  John E. Davis, davis@space.mit.edu
  Sat May 15 13:50:27 1999
  ____________________________________________________________

  Table of Contents




























































   Preface

  1. A Brief History of

  2. Acknowledgements

  2. Introduction

  3. Language Features

  4. Data Types and Operators

  5. Statements and Functions

  6. Error Handling

  7. Run-Time Library

  8. Input/Output

  9. Obtaining

  9. Overview of the Language

  10. Variables and Functions

  11. Strings

  12. Referencing and Dereferencing

  13. Arrays

  14. Structures and User-Defined Types

  15. Namespaces

  15. Data Types and Literal Constants

  16. Predefined Data Types

     16.1 Integers
     16.2 Floating Point Numbers
     16.3 Complex Numbers
     16.4 Strings
     16.5 Null[lowbar]Type
     16.6 Ref[lowbar]Type
     16.7 Array[lowbar]Type and Struct[lowbar]Type
     16.8 DataType[lowbar]Type Type

  17. Typecasting: Converting from one Type to Another


  17. Identifiers


  17. Variables


  17. Operators

  18. Unary Operators

  19. Binary Operators

     19.1 Arithmetic Operators
     19.2 Relational Operators
     19.3 Boolean Operators
     19.4 Bitwise Operators
     19.5 Namespace operator
     19.6 Operator Precedence
     19.7 Binary Operators and Functions Returning Multiple Values

  20. Mixing Integer and Floating Point Arithmetic

  21. Short Circuit Boolean Evaluation

  21. Statements

  22. Variable Declaration Statements

  23. Assignment Statements

  24. Conditional and Looping Statements

     24.1 Conditional Forms
        24.1.1 if
        24.1.2 if-else
        24.1.3 !if
        24.1.4 orelse, andelse
        24.1.5 switch
     24.2 Looping Forms
        24.2.1 while
        24.2.2 do...while
        24.2.3 for
        24.2.4 loop
        24.2.5 forever
        24.2.6 foreach

  25. break, return, continue


  25. Functions

  26. Declaring Functions

  27. Parameter Passing Mechanism

  28. Referencing Variables

  29. Functions with a Variable Number of Arguments

  30. Returning Values

  31. Multiple Assignment Statement

  32. Exit-Blocks

  32. Name Spaces

  32. Arrays

  33. Creating Arrays

  34. Reshaping Arrays

  35. Indexing Arrays

  36. Arrays and Variables

  37. Using Arrays in Computations

  37. Associative Arrays
  37. Structures and User-Defined Types

  38. Defining a Structure

  39. Accessing the Fields of a Structure

  40. Linked Lists

  41. Defining New Types

  41. Error Handling

  42. Error-Blocks

  43. Clearing Errors

  43. Loading Files: evalfile and autoload

  43. File Input/Output

  44. Input/Output via stdio

     44.1 Stdio Overview
     44.2 Stdio Examples

  45. POSIX I/O

  46. Advanced I/O techniques

     46.1 Example: Reading /var/log/wtmp
     46.1 Debugging
     46.1 Regular Expressions

  47. (BF

  48. Differences between

  48. Future Directions

  48. Copyright

  49. The GNU Public License

  50. The Artistic License



  ______________________________________________________________________


















  1.  Preface



  S-Lang 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 S-Lang as an
  extension language include the jed text editor, the slrn newsreader,
  and sldxe (unreleased), a numerical computation program.  For this
  reason, S-Lang 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.

  S-Lang is also a programmer's library that permits a programmer to
  develop sophisticated platform-independent software.  In addition to
  providing the S-Lang 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 S-Lang
  library.  For information about the other components of the library,
  the reader is referred to the The S-Lang Library Reference.


  1.1.  A Brief History of S-Lang



  I first began working on S-Lang sometime during the fall of 1992.  At
  that time I was writing a text editor (jed), 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, S-Lang was born.

  S-Lang was originally a stack language that supported a postscript-
  like syntax.  For that reason, I named it S-Lang, where the S 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 `%' character is still used as a comment delimiter.



  1.2.  Acknowledgements



  Since I first released S-Lang, 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 <lionkov@sf.cit.bg> 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 <olesen@weber.me.queensu.ca> for his many patches to
  various aspects of the library and his support on AIX. He also
  contributed a lot to the pre-processing (SLprep) routines.


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

  Darrel Hankerson <hankedr@mail.auburn.edu> for cleaning up and
  unifying some of the code and the makefiles.

  Dominik Wujastyk <ucgadkw@ucl.ac.uk> who was always willing to test
  new releases of the library.

  Michael Elkins <me@muddcs.cs.hmc.edu> for his work on the curses
  emulation.

  Ulli Horlacher <framstag@belwue.de> and Oezguer Kesim <kesim@math.fu-
  berlin.de> for the S-Lang newsgroup and mailing list.

  Hunter Goatley, Andy Harper <Andy.Harper@kcl.ac.uk>, and Martin P.J.
  Zinser <zinser@decus.decus.de> for their VMS support.

  Dave Sims <sims@usa.acsys.com> and Chin Huang <cthuang@vex.net> for
  Windows 95 and Windows NT support.

  Lloyd Zusman <ljz@asfast.com> and Rich Roth <rich@on-the-net.com> for
  creating and maintaining www.s-lang.org.

  I am also grateful to many other people who send in bug-reports and
  bug-fixes, for without such community involvement, S-Lang 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.




































  2.  Introduction



  S-Lang 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 will much more flexibility and power.
  Examples of applications that take advantage of the interpreter in
  this way include the jed editor and the slrn newsreader.


  2.1.  Language Features


  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.


  2.2.  Data Types and Operators



  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 Mark_Type that the jed 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 (+) 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 a and b are arrays, then a + b produces an array whose
  elements are the result of element by element addition of a and b.
  This permits one to do vector operations without explicitly looping
  over the array indices.



  2.3.  Statements and Functions



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

  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 reference data type that
  allows one to simulate pass by reference.

  Unlike many interpreted languages, S-Lang 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.



  2.4.  Error Handling



  The S-Lang language defines a construct called an error-block 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++.



  2.5.  Run-Time Library



  Functions that compose the S-Lang run-time library are called
  intrinsics.  Examples of S-Lang intrinsic functions available to every
  S-Lang application include string manipulation functions such as
  strcat, strchop, and strcmp.  The S-Lang library also provides
  mathematical functions such as sin, cos, and tan; however, not all
  applications enable the use of these intrinsics.  For example, to
  conserve memory, the 16 bit version of the jed 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 jed editor
  adds over 100 application specific intrinsic functions to the
  language.  Consult your application specific documentation to see what
  additional intrinsics are supported.



  2.6.  Input/Output


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





  2.7.  Obtaining S-Lang



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

  S-Lang as well as some programs that embed it are freely available via
  anonymous ftp in the United States from

  o  ftp://space.mit.edu/pub/davis.

     It is also available outside the United States from the following
     mirror sites:

  o  ftp://ftp.uni-stuttgart.de/pub/unix/misc/slang/

  o  ftp://ftp.fu-berlin.de/pub/unix/news/slrn/

  o  ftp://ftp.ntua.gr/pub/lang/slang/

  The Usenet newsgroup alt.lang.s-lang was created for S-Lang
  programmers to exchange information and share macros for the various
  programs the embed the language.  The newsgroup comp.editors can be a
  useful resource for S-Lang macros for the jed editor.  Similarly, slrn
  users will find news.software.readers to be a valuable source of
  information.

  Finally, two mailing lists dealing with the S-Lang library have been
  created:

  o  slang-announce@babayaga.math.fu-berlin.de

  o  slang-workers@babayaga.math.fu-berlin.de

     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 slang-announce-subscribe@babayaga.math.fu-
     berlin.de and include the word subscribe in the body of the
     message.  To subscribe to the developers list, use the address
     slang-workers-subscribe@babayaga.math.fu-berlin.de.
























  3.  Overview of the Language



  This purpose of this section is to give the reader a feel for the S-
  Lang 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.


  3.1.  Variables and Functions



  S-Lang 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 variable keyword, e.g.,


            variable x, y, z;




  declares three variables, x, y, and z.  Note the semicolon at the end
  of the statement.  All S-Lang statements must end in a semi-colon.

  Unlike compiled languages such as C, it is not necessary to specify
  the data type of a S-Lang variable.  The data type of a S-Lang
  variable is determined upon assignment.  For example, after execution
  of the statements


            x = 3;
            y = sin (5.6);
            z = "I think, therefore I am.";




  x will be an integer, y will be a double, and z will be a string.  In
  fact, it is even possible to re-assign x to a string:


            x = "x was an integer, but now is a string";




  Finally, one can combine variable declarations and assignments in the
  same statement:


            variable x = 3, y = sin(5.6), z = "I think, therefore I am.";




  Most functions are declared using the define keyword.  A simple
  example is



        define compute_average (x, y)
        {
           variable s = x + y;
           return s / 2.0;
        }




  which defines a function that simply computes the average of two num-
  bers and returns the result.  This example shows that a function con-
  sists 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 local
  variables used in the function must be declared.  If the function
  takes no parameters, then the parameter list must still be present,
  but empty:


             define go_left_5 ()
             {
                go_left (5);
             }




  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 procedures.
  However, S-Lang, like C, does not make such a distinction.

  The language permits recursive functions, i.e., functions that call
  themselves.  The way to do this in S-Lang is to first declare the
  function using the form:

       define function-name ();


  It is not necessary to declare a parameter list when declaring a func-
  tion in this way.

  The most famous example of a recursive function is the factorial
  function.  Here is how to implement it using S-Lang:


            define factorial ();   % declare it for recursion

            define factorial (n)
            {
               if (n < 2) return 1;
               return n * factorial (n - 1);
            }




  This example also shows how to mix comments with code.  S-Lang uses
  the `%' character to start a comment and all characters from the com-
  ment character to the end of the line are ignored.



  3.2.  Strings



  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 S-Lang handles string
  variables with a lower level language such as C.  Consider a function
  that concatenates three strings.  An example in S-Lang is:


            define concat_3_strings (a, b, c)
            {
               return strcat (a, strcat (b, c));
            }




  This function uses the built-in strcat function for concatenating two
  strings.  In C, the simplest such function would look like:


            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;
            }




  Even this C example is misleading since none of the issues of memory
  management of the strings has been dealt with.  The S-Lang language
  hides all these issues from the user.

  Binary operators have been defined to work with the string data type.
  In particular the + operator may be used to perform string
  concatenation.  That is, one can use the + operator as an alternative
  to strcat:


             define concat_3_strings (a, b, c)
             {
                return a + b + c;
             }




  See section ??? for more information about string variables.



  3.3.  Referencing and Dereferencing


  The unary prefix operator, &, may be used to create a reference 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:


              define compute_functional_sum (funct)
              {
                 variable i, sum;

                 sum = 0;
                 for (i = 0; i < 10; i++)
                  {
                     sum += @funct (i);
                  }
                 return sum;
              }

              variable sin_sum = compute_functional_sum (&sin);
              variable cos_sum = compute_functional_sum (&cos);




  Here, the function compute_functional_sum applies the function speci-
  fied by the parameter funct to the first 10 integers and returns the
  sum.  The two statements following the function definition show how
  the sin and cos functions may be used.

  Note the @ operator in the definition of compute_functional_sum.  It
  is known as the dereference operator and is the inverse of the
  reference operator.

  Another use of the reference operator is in the context of the fgets
  function.  For example,


             define read_nth_line (file, n)
             {
                variable fp, line;
                fp = fopen (file, "r");

                while (n > 0)
                  {
                     if (-1 == fgets (&line, fp))
                       return NULL;
                     n--;
                  }
                return line;
             }




  uses the fgets function to read the nth line of a file.  In particu-
  lar, a reference to the local variable line is passed to fgets, and
  upon return line will be set to the character string read by fgets.

  Finally, references may be used as an alternative to multiple return
  values by passing information back via the parameter list.  The
  example involving fgets presented above provided an illustration of
  this.  Another example is






         define set_xyz (x, y, z)
         {
            @x = 1;
            @y = 2;
            @z = 3;
         }
         variable X, Y, Z;
         set_xyz (&X, &Y, &Z);




  which, after execution, results in X set to 1, Y set to 2, and Z set
  to 3.  A C programmer will note the similarity of set_xyz to the fol-
  lowing C implementation:


             void set_xyz (int *x, int *y, int *z)
             {
                *x = 1;
                *y = 2;
                *z = 3;
             }





  3.4.  Arrays


  The S-Lang 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:


              variable A = Integer_Type [10];
              variable B = Integer_Type [10, 3];
              variable C = [1, 3, 5, 7, 9];




  The first example creates an array of 10 integers and assigns it to
  the variable A.  The second example creates a 2-d array of 30 integers
  arranged in 10 rows and 3 columns and assigns the result to B.  In the
  last example, an array of 5 integers is assigned to the variable C.
  However, in this case the elements of the array are initialized to the
  values specified.  This is known as an inline-array.

  S-Lang also supports something called an range-array.  An example of
  such an array is


             variable C = [1:9:2];




  This will produce an array of 5 integers running from 1 through 9 in
  increments of 2.

  Arrays are passed by reference to functions and never by value.  This
  permits one to write functions which can initialize arrays.  For
  example,
             define init_array (a)
             {
                variable i, imax;

                imax = length (a);
                for (i = 0; i < imax; i++)
                  {
                     a[i] = 7;
                  }
             }

             variable A = Integer_Type [10];
             init_array (A);




  creates an array of 10 integers and initializes all its elements to 7.

  There are more concise ways of accomplishing the result of the
  previous example.  These include:


             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;




  The second and third methods use an array of indices to index the
  array A.  In the second, the range of indices has been explicitly
  specified, whereas the third example uses a wildcard form.  See sec-
  tion ??? for more information about array indexing.

  Although the examples have pertained to integer arrays, the fact is
  that S-Lang arrays can be of any type, e.g.,


              variable A = Double_Type [10];
              variable B = Complex_Type [10];
              variable C = String_Type [10];
              variable D = Ref_Type [10];




  create 10 element arrays of double, complex, string, and reference
  types, respectively.  The last example may be used to create an array
  of functions, e.g.,


             D[0] = &sin;
             D[1] = &cos;




  The language also defines unary, binary, and mathematical operations
  on arrays.  For example, if A and B are integer arrays, then A + B is
  an array whose elements are the sum of the elements of A and B.  A
  trivial example that illustrates the power of this capability is




          variable X, Y;
          X = [0:2*PI:0.01];
          Y = 20 * sin (X);




  which is equivalent to the highly simplified C code:


               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 < n; i++)
                 {
                   X[i] = i * 0.01;
                   Y[i] = 20 * sin (X[i]);
                 }







  3.5.  Structures and User-Defined Types



  A structure 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 Any_Type), whereas a structure is heterogeneous.  As an
  example, consider


             variable person = struct
             {
                first_name, last_name, age
             };
             variable bill = @person;
             bill.first_name = "Bill";
             bill.last_name = "Clinton";
             bill.age = 51;




  In this example a structure consisting of the three fields has been
  created and assigned to the variable person.  Then an instance of this
  structure has been created using the dereference operator and assigned
  to bill.  Finally, the individual fields of bill were initialized.
  This is an example of an anonymous structure.

  A named structure is really a new data type and may be created using
  the typedef keyword:








        typedef struct
        {
           first_name, last_name, age
        }
        Person_Type;

        variable bill = @Person_Type;
        bill.first_name = "Bill";
        bill.last_name = "Clinton";
        bill.age = 51;




  The big advantage of creating a new type is that one can go on to cre-
  ate arrays of the data type


             variable People = Person_Type [100];
             People[0].first_name = "Bill";
             People[1].first_name = "Hillary";




  The creation and initialization of a structure may be facilitated by a
  function such as


             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);




  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 ???.




  3.6.  Namespaces


  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 static keyword will be placed in the private
  namespace associated with compilation unit.  For example,


              variable i;
              static variable i;




  defines two variables called i.  The first declaration defines i in
  the global namespace, but the second declaration defines i in the
  private namespace.

  The -> 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 i in the global namespace, one would use
  Global->i.  Unless otherwise specified, a private namespace has no
  name and its objects may not be accessed from outside the compilation
  unit.  However, the implements function may be used give the private
  namespace a name, allowing access to its objects.  For example, if the
  file t.sl contains


             implements ("A");
             static variable i;




  then another file may access the variable i via A->i.















































  4.  Data Types and Literal Constants



  The current implementation of the S-Lang 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 typedef mechanism.

  Literal constants are objects such as the integer 3 or the string
  "hello".  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.


  4.1.  Predefined Data Types



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


  4.1.1.  Integers



  The S-Lang 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 literal can be specified in one of several ways:

  o  As a decimal (base 10) integer consisting of the characters 0
     through 9, e.g., 127.  An integer specified this way cannot begin
     with a leading 0.  That is, 0127 is not the same as 127.

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

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

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

     Finally, a character literal may be specified using a notation
     containing a character enclosed in single quotes as 'a'.  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,


                i = '0';




  assigns to i the character 48 since the '0' character has an ASCII
  value of 48.

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



  4.1.2.  Floating Point Numbers



  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:


                12.    12.0    12e0   1.2e1   120e-1   .12e2   0.12e2




  Note that 12 is not a floating point number since it contains neither
  a decimal point nor an exponent.  In fact, 12 is an integer.

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



  4.1.3.  Complex Numbers



  The language implements complex numbers as a pair of double precision
  floating point numbers.  The first number in the pair forms the real
  part, while the second number forms the imaginary 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 S-Lang 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 i or j is appended.  For example,


                12i    12.0i   12e0j




  all represent the same imaginary number.  Actually, 12i is really an
  imaginary integer except that S-Lang 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.,
               3.0 + 4.0i




  produces a complex number whose real part is 3.0 and whose imaginary
  part is 4.0.

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



  4.1.4.  Strings



  A string literal must be enclosed in double quotes as in:


             "This is a string".




  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.,


            "This is the first part of a long string"
              + "and this is the second half"




  Any character except a newline (ASCII 10) or the null character (ASCII
  0) may appear explicitly in a string literal.  However, these charac-
  ters 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:


              \"    --  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




  For example, to include the double quote character as part of the
  string, it must be preceded by a backslash character, e.g.,


              "This is a \"quote\""


  Similarly, the next illustrates how a newline character may be
  included:


              "This is the first line\nand this is the second"






  4.1.5.  Null_Type


  Objects of type Null_Type can have only one value: NULL.  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,
  Null_Type 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


             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 (,);




  It should be clear that after these statements have been executed, c
  will have a value of 3.  It should also be clear that d will have a
  value of 1 because NULL 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 NULL.  Hence, e and f will be set to 1 and 0, respectively.

  The Null_Type data type also plays an important role in the context of
  structures.


  4.1.6.  Ref_Type

  Objects of Ref_Type are created using the unary reference operator &.
  Such objects may be dereferenced using the dereference operator @.
  For example,


             variable sin_ref = &sin;
             variable y = @sin_ref (1.0);




  creates a reference to the sin function and assigns it to sin_ref.
  The second statement uses the dereference operator to call the func-
  tion that sin_ref references.
  The Ref_Type 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 ???.


  4.1.7.  Array_Type and Struct_Type


  Variables of type Array_Type and Struct_Type are known as container
  objects.  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 ???.


  4.1.8.  DataType_Type Type



  S-Lang defines a type called DataType_Type.  Objects of this type have
  values that are type names.  For example, an integer is an object of
  type Integer_Type.  The literals of DataType_Type include:


            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)




  as well as the names of any other types that an application defines.

  The built-in function typeof returns the data type of its argument,
  i.e., a DataType_Type.  For instance typeof(7) returns Integer_Type
  and typeof(Integer_Type) returns DataType_Type.  One can use this
  function as in the following example:


             if (Integer_Type == typeof (x)) message ("x is an integer");




  The literals of DataType_Type have other uses as well.  One of the
  most common uses of these literals is to create arrays, e.g.,


               x = Complex_Type [100];

  creates an array of 100 complex numbers and assigns it to x.



  4.2.  Typecasting: Converting from one Type to Another


  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 String_Type.  The typecast
  function may be used to perform such conversions.  For example,
  consider


             variable x = 10, y;
             y = typecast (x, Double_Type);




  After execution of these statements, x will have the integer value 10
  and y will have the double precision floating point value 10.0.  If
  the object to be converted is an array, the typecast function will act
  upon all elements of the array.  For example,


             variable x = [1:10];       % Array of integers
             variable y = typecast (x, Double_Type);




  will create an array of 10 double precision values and assign it to y.
  One should also realize that it is not always possible to perform a
  typecast.  For example, any attempt to convert an Integer_Type to a
  Null_Type 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
  Integer_Type with a Double_Type, it will convert the Integer_Type to a
  Double_Type 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 1.0, i.e.,


             variable x = [1:10];       % Array of integers
             variable y = 1.0 * x;




  The string 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 String_Type
  is not the same as converting an object to its string operation.
  That is, typecast(x,String_Type) is not equivalent to string(x).  The
  reason for this is that when given an array, the typecast function
  acts on each element of the array to produce another array, whereas
  the string function produces a a string.

  The string function is useful for printing the value of an object.
  This use is illustrated in the following simple example:




        define print_object (x)
        {
           message (string (x));
        }




  Here, the message function has been used because it writes a string to
  the display.  If the string function was not used and the message
  function was passed an integer, a type-mismatch error would have
  resulted.






















































  5.  Identifiers



  The names given to variables, functions, and data types are called
  identifiers.  There are some restrictions upon the actual characters
  that make up an identifier.  An identifier name must start with a
  letter ([A-Za-z]), 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:


             mary    _3    _this_is_ok
             a7e1    $44   _44$_Three




  However, the following are not legal:


             7abc   2e0    #xx




  In fact, 2e0 actually specifies the real number 2.0.

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

  The following identifiers are reserved by the language for use as
  keywords:


               !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

















  6.  Variables



  A variable must be declared before it can be used, otherwise an
  undefined name error will be generated.  A variable is declared using
  the variable keyword, e.g,


             variable x, y, z;




  declares three variables, x, y, and z.  This is an example of a vari-
  able 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,


               x = "This is a string";
               x = 1.2;
               x = 3;
               x = 2i;




  results in x being set successively to a string, a float, an integer,
  and to a complex number (0+2i).  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,


                variable x = 1, y = sin (x);




  are legal variable declarations.  This also provides a convenient way
  of initializing a variable.

  Variables are classified as either global or local. 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 public, static, or private, 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:


             $0 $1 $2 $3 $4 $5 $6 $7 $8 $9




  An intrinsic 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 PI which is a read-only double
  precision variable with a value of approximately
  3.14159265358979323846.






























































  7.  Operators



  S-Lang 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 not is an example of an unary operator.  Examples of binary
  operators include the usual arithmetic operators +, -, *, and /.  The
  operator given by - 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., a + b.  Unary
  operators fall in one of two classes: postfix-unary or prefix-unary.
  For example, in the expression -x, the minus sign is a prefix-unary
  operator.

  Not all data types have binary or unary operations defined.  For
  example, while String_Type objects support the + operator, they do not
  admit the * operator.


  7.1.  Unary Operators


  The unary operators operate only upon a single operand.  They include:
  not, ~, -, @, &, as well as the increment and decrement operators ++
  and --, respectively.

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

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

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

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


  7.2.  Binary Operators



  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 String_Type data
  type to permit concatenation between strings.




  7.2.1.  Arithmetic Operators



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

  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 8/5 which indicates division of the
  integer 8 by the integer 5.  The result will be the integer 1 and not
  the floating point value 1.6.  However, 8/5.0 will produce 1.6 because
  5.0 is a floating point number.



  7.2.2.  Relational Operators



  The relational operators are >, >=, <, <=, ==, and !=.  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 1 if the comparison is true, or 0
  if the comparison is false.  For example, 6 >= 5 returns 1, but 6 == 5
  produces 0.



  7.2.3.  Boolean Operators


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

  Neither of these operators perform the so-called boolean short-circuit
  evaluation.  For example, consider the expression:


             (x != 0) and (1/x > 10)




  Here, if x were to have a value of zero, a division by zero error
  would occur because even though x!=0 evaluates to zero, the and opera-
  tor is not short-circuited and the 1/x expression would still be eval-
  uated.  Although these operators are not short-circuited, S-Lang does
  have another mechanism of performing short-circuit boolean evaluation
  via the orelse and andelse expressions.  See below for information
  about these constructs.




  7.2.4.  Bitwise Operators



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

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

  As an example of using & to perform tests on bits, consider the
  following: The jed 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 jed intrinsic function getbuf_info, 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


             define get_buffer_flags ()
             {
                variable flags;
                (,,,flags) = getbuf_info ();
                return flags;
             }




  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 0 the buffer has not been modified, otherwise it has.  Thus we can
  create the function,


            define is_buffer_modified ()
            {
               variable flags = get_buffer_flags ();
               return (flags & 1);
            }




  where the integer 1 has been used since it has all of its bits set to
  0, except for the zeroth one, which is set to 1.  (At this point, it
  should also be apparent that bits are numbered from zero, thus an 8
  bit integer consists of bits 0 to 7, where 0 is the least significant
  bit and 7 is the most significant one.)  Similarly, we can create
  another function



       define is_autosave_on ()
       {
          variable flags = get_buffer_flags ();
          return (flags & 2);
       }




  to determine whether or not autosave has been turned on for the
  buffer.

  The shl operator may be used to form the integer with only the nth bit
  set.  For example, 1 shl 6 produces an integer with all bits set to
  zero except the sixth bit, which is set to one.  The following example
  exploits this fact:


            define test_nth_bit (flags, nth)
            {
               return flags & (1 shl nth);
            }






  7.2.5.  Namespace operator

  The operator -> is used to in conjunction with the name of a namespace
  to access an object within the namespace.  For example, if A is the
  name of a namespace containing the variable v, then A->v refers to
  that variable.


  7.2.6.  Operator Precedence



  7.2.7.  Binary Operators and Functions Returning Multiple Values


  Care must be exercised when using binary operators with an operand the
  returns multiple values.  In fact, the current implementation of the
  S-Lang language will produce incorrect results if both operands of a
  binary expression return multiple values.  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.  For example,


           define read_line (fp)
           {
              variable line, status;

              status = fgets (&line, fp);
              if (status == -1)
                return -1;
              return (line, status);
           }




  defines a function, read_line that takes a single argument, a handle
  to an open file, and returns one or two values, depending upon the
  return value of fgets.  Now consider


               while (read_line (fp) > 0)
                 {
                    text = ();
                    % Do something with text
                    .
                    .
                 }




  Here the relational binary operator > forms a comparison between one
  of the return values (the one at the top of the stack) and 0.  In
  accordance with the above rule, since read_line returns multiple val-
  ues, it occurs as the left binary operand.  Putting it on the right as
  in


               while (0 < read_line (fp))    % Incorrect
                 {
                    text = ();
                    % Do something with text
                    .
                    .
                 }




  violates the rule and will result in the wrong answer.




  7.3.  Mixing Integer and Floating Point Arithmetic


  If a binary operation (+, -, * , /) 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:


             11 / 2           --> 5   (integer)
             11 / 2.0         --> 5.5 (float)
             11.0 / 2         --> 5.5 (float)
             11.0 / 2.0       --> 5.5 (float)




  Finally note that only integers may be used as array indices, loop
  control variables, and bit operations.  The conversion functions, int
  and float, may be used convert between floats and ints where appropri-
  ate, e.g.,


             int (1.5)         --> 1 (integer)
             float(1.5)        --> 1.5 (float)
             float (1)         --> 1.0 (float)




  7.4.  Short Circuit Boolean Evaluation


  The boolean operators or and and are not short circuited as they are
  in some languages.  S-Lang uses orelse and andelse expressions for
  short circuit boolean evaluation.  However, these are not binary
  operators. Expressions of the form:

       expr-1 and expr-2 and ... expr-n


  can be replaced by the short circuited version using andelse:

       andelse {expr-1} {expr-2} ... {expr-n}


  A similar syntax holds for the orelse operator.  For example, consider
  the statement:


             if ((x != 0) and (1/x > 10)) do_something ();




  Here, if x were to have a value of zero, a division by zero error
  would occur because even though x!=0 evaluates to zero, the and opera-
  tor is not short circuited and the 1/x expression would be evaluated
  causing division by zero. For this case, the andelse expression could
  be used to avoid the problem:


             if (andelse
                 {x != 0}
                 {1 / x > 10})  do_something ();































  8.  Statements



  Loosely speaking, a statement is composed of expressions 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 S-Lang 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.


  8.1.  Variable Declaration Statements

  Variable declarations were already discussed in chapter ???.  For the
  sake of completeness, a variable declaration is a statement of the
  form

       variable variable-declaration-list ;


  where the variable-declaration-list is a comma separated list of one
  or more variable names with optional initializations, e.g.,


            variable x, y = 2, z;




  8.2.  Assignment Statements



  Perhaps the most well known form of statement is the assignment
  statement.  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 lvalue.

  The most common assignment operator is the simple assignment operator
  =.  Simple of its use include


             x = 3;
             x = some_function (10);
             x = 34 + 27/y + some_function (z);
             x = x + 3;




  In addition to the simple assignment operator, S-Lang also supports
  the assignment operators += and -=.  Internally, S-Lang transforms


              a += b;


  to


              a = a + b;




  Similarly, a -= b is transformed to a = a - b.  It is extremely impor-
  tant to realize that, in general, a+b is not equal to b+a.  This means
  that a+=b is not the same as a=b+a.  As an example consider


             a = "hello"; a += "world";




  After execution of these two statements, a will have the value "hel-
  loworld" and not "worldhello".

  Since adding or subtracting 1 from a variable is quite common, S-Lang
  also supports the unary increment and decrement operators ++, and --,
  respectively.  That is, for numeric data types,


              x = x + 1;
              x += 1;
              x++;




  are all equivalent.  Similarly,


              x = x - 1;
              x -= 1;
              x--;




  are also equivalent.

  Strictly speaking, ++ and -- are unary operators.  When used as x++,
  the ++ operator is said to be a postfix-unary operator.  However, when
  used as ++x it is said to be a prefix-unary operator.  The current
  implementation does not distinguish between the two forms, thus x++
  and ++x are equivalent.  The reason for this equivalence is that
  assignment expressions do not return a value in the S-Lang language as
  they do in C.  Thus one should exercise care and not try to write C-
  like code such as


             x = 10;
             while (--x) do_something (x);     % Ok in C, but not in S-Lang




  The closest valid S-Lang form involves a comma-expression:




        x = 10;
        while (x--, x) do_something (x);  % Ok in S-Lang and in C




  S-Lang also supports a multiple-assignment statement.  It is discussed
  in detail in section ???.



  8.3.  Conditional and Looping Statements



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


  8.3.1.  Conditional Forms



  8.3.1.1.  if

  The simplest condition statement is the if statement.  It follows the
  syntax

       if (integer-expression) statement-or-block next-statement


  If integer-expression evaluates to a non-zero result, then the state-
  ment or group of statements implied statement-or-block will get exe-
  cuted.  Otherwise, control will proceed to next-statement.

  An example of the use of this type of conditional statement is


              if (x != 0)
                {
                   y = 1.0 / x;
                   if (x > 0) z = log (x);
                }




  This example illustrates two if statements where the second if state-
  ment is part of the block of statements that belong to the first.


  8.3.1.2.  if-else

  Another form of if statement is the if-else statement.  It follows the
  syntax:

       if (integer-expression) statement-or-block-1 else statement-or-block-2
       next-statement


  Here, if expression returns non-zero, statement-or-block-1 will get
  executed and control will pass on to next-statement. However, if
  expression returns zero, statement-or-block-2 will get executed before
  continuing with next-statement.  A simple example of this form is


            if (x > 0) z = log (x); else error ("x must be positive");




  Consider the more complex example:


            if (city == "Boston")
              if (street == "Beacon") found = 1;
            else if (city == "Madrid")
              if (street == "Calle Mayor") found = 1;
            else found = 0;




  This example illustrates a problem that beginners have with if-else
  statements.  The grammar presented above shows that the this example
  is equivalent to


            if (city == "Boston")
              {
                if (street == "Beacon") found = 1;
                else if (city == "Madrid")
                  {
                    if (street == "Calle Mayor") found = 1;
                    else found = 0;
                  }
              }




  It is important to understand the grammar and not be seduced by the
  indentation!


  8.3.1.3.  !if


  One often encounters if statements similar to

       if (integer-expression == 0) statement-or-block


  or equivalently,

       if (not(integer-expression)) statement-or-block


  The !if statement was added to the language to simplify the handling
  of such statements.  It obeys the syntax

       !if (integer-expression) statement-or-block


  and is functionally equivalent to

  if (not (expression)) statement-or-block



  8.3.1.4.  orelse, andelse


  These constructs were discussed earlier.  The syntax for the orelse
  statement is:

       orelse {integer-expression-1} ... {integer-expression-n}


  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 exam-
  ple,


            orelse { 0 } { 6 } { 2 } { 3 }




  returns 6 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 andelse statement is:

       andelse {integer-expression-1} ... {integer-expression-n}


  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,


            andelse { 6 } { 2 } { 0 } { 4 }




  returns 0 since the third block will be the last to execute.


  8.3.1.5.  switch

  The switch statement deviates the most from its C counterpart.  The
  syntax is:


                 switch (x)
                   { ...  :  ...}
                     .
                     .
                   { ...  :  ...}




  The `:' 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.  Other-
  wise, the execution of the block will be terminated and the process
  will be repeated for the next block.  If a block contains no : opera-
  tor, the entire block is executed and control will pass onto the next
  statement following the switch statement.  Such a block is known as
  the default case.

  As a simple example, consider the following:


             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.");}




  Suppose x has an integer value of 3.  The first two blocks will termi-
  nate at the `:' character because each of the comparisons with x will
  produce zero.  However, the third block will execute to completion.
  Similarly, if x is 7, only the last block will execute in full.

  A more familiar way to write the previous example used the case
  keyword:


             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.");}




  The case keyword is a more useful comparison operator because it can
  perform a comparison between different data types while using == may
  result in a type-mismatch error.  For example,


             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.");}




  will fail because the == operation is not defined between strings and
  integers.  The correct way to write this to use the case keyword:


             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.");}


  8.3.2.  Looping Forms




  8.3.2.1.  while

  The while statement follows the syntax

       while (integer-expression) statement-or-block next-statement


  It simply causes statement-or-block to get executed as long as inte-
  ger-expression evaluates to a non-zero result.  For example,


             i = 10;
             while (i)
               {
                 i--;
                 newline ();
               }




  will cause the newline function to get called 10 times.  However,


             i = -10;
             while (i)
               {
                 i--;
                 newline ();
               }




  will loop forever since i will never be 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:


             i = 10;
             while (i--) newline ();




  The fact is that expressions such as i-- do not return a value in S-
  Lang as they do in C.  If you must write this way, use the comma oper-
  ator as in


             i = 10;
             while (i, i--) newline ();








  8.3.2.2.  do...while

  The do...while statement follows the syntax

       do statement-or-block while (integer-expression);


  The main difference between this statement and the while statement is
  that the do...while form performs the test involving integer-expres-
  sion after each execution of statement-or-block rather than before.
  This guarantees that statement-or-block will get executed at least
  once.

  A simple example from the jed editor follows:


            bob ();      % Move to beginning of buffer
            do
              {
                 indent_line ();
              }
            while (down (1));




  This will cause all lines in the buffer to get indented via the jed
  intrinsic function indent_line.


  8.3.2.3.  for

  Perhaps the most complex looping statement is the for statement;
  nevertheless, it is a favorite of many programmers.  This statement
  obeys the syntax

       for (init-expression; integer-expression; end-expression) statement-
       or-block next-statement


  In addition to statement-or-block, its specification requires three
  other expressions.  When executed, the for statement evaluates init-
  expression, then it tests integer-expression.  If integer-expression
  returns zero, control passes to next-statement.  Otherwise, it exe-
  cutes statement-or-block as long as integer-expression evaluates to a
  non-zero result.  After every execution of statement-or-block, end-
  expression will get evaluated.

  This statement is almost equivalent to

       init-expression; while (integer-expression) { statement-or-block end-
       expression; }


  The reason that they are not fully equivalent involves what happens
  when statement-or-block contains a continue statement.

  Despite the apparent complexity of the for statement, it is very easy
  to use.  As an example, consider


            sum = 0;
            for (i = 1; i <= 10; i++) sum += i;



  which computes the sum of the first 10 integers.


  8.3.2.4.  loop

  The loop statement simply executes a block of code a fixed number of
  times.  It follows the syntax

       loop (integer-expression) statement-or-block next-statement


  If the integer-expression evaluates to a positive integer, statement-
  or-block will get executed that many times.  Otherwise, control will
  pass to next-statement.

  For example,


             loop (10) newline ();




  will cause the function newline to get called 10 times.


  8.3.2.5.  forever

  The forever statement is similar to the loop statement except that it
  loops forever, or until a break or a return statement is executed.  It
  obeys the syntax

       forever statement-or-block


  A trivial example of this statement is


            n = 10;
            forever
              {
                 if (n == 0) break;
                 newline ();
                 n--;
              }





  8.3.2.6.  foreach

  The foreach 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 foreach statement obeys the syntax

       foreach (container-object) statement-or-block


  Here container-object can be an expression that returns a container
  object.  A simple example is

       foreach (["apple", "peach", "pear"])
        {
           fruit = ();
           process_fruit (fruit);
        }




  This example shows that if the container object is an array, then suc-
  cessive 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
  using form of the foreach statement.  This more complex type of
  foreach statement follows the syntax

       foreach ( container-object ) using ( control-list ) statement-or-block


  The allowed values of control-list will depend upon the type of con-
  tainer object.  For associative arrays (Assoc_Type), control-list
  specified whether keys, values, or both are pushed onto the stack.
  For example,


            foreach (a) using ("keys")
              {
                 k = ();
                  .
                  .
              }




  results in the keys of the associative array a being pushed on the
  list.  However,


            foreach (a) using ("values")
              {
                 v = ();
                  .
                  .
              }




  will cause the values to be used, and


            foreach (a) using ("keys", "values")
              {
                 (k,v) = ();
                  .
                  .
              }




  will use both the keys and values of the array.

  Similarly, for linked-lists of structures, one may walk the list via
  code like


            foreach (linked_list) using ("next")
              {
                 s = ();
                   .
                   .
              }




  This foreach statement is equivalent


            s = linked_list;
            while (s != NULL)
              {
                 .
                 .
                s = s.next;
              }




  Consult the type-specific documentation for a discussion of the using
  control words, if any, appropriate for a given type.


  8.4.  break, return, continue


  S-Lang also includes the non-local transfer functions return, break,
  and continue.  The return statement causes control to return to the
  calling function while the break and continue statements are used in
  the context of loop structures.  Consider:


              define fun ()
              {
                 forever
                   {
                      s1;
                      s2;
                      ..
                      if (condition_1) break;
                      if (condition_2) return;
                      if (condition_3) continue;
                      ..
                      s3;
                   }
                 s4;
                 ..
              }




  Here, a function fun has been defined that contains a forever loop
  consisting of statements s1, s2,...,s3, and three if statements.  As
  long as the expressions condition_1, condition_2, and condition_3
  evaluate to zero, the statements s1, s2,...,s3 will be repeatedly exe-
  cuted.  However, if condition_1 returns a non-zero value, the break
  statement will get executed, and control will pass out of the forever
  loop to the statement immediately following the loop which in this
  case is s4. Similarly, if condition_2 returns a non-zero number, the
  return statement will cause control to pass back to the caller of fun.
  Finally, the continue statement will cause control to pass back to the
  start of the loop, skipping the statement s3 altogether.




























































  9.  Functions



  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.


  9.1.  Declaring Functions



  Like variables, functions must be declared before they can be used.
  The define keyword is used for this purpose.  For example,


             define factorial ();




  is sufficient to declare a function named factorial.  Unlike the vari-
  able keyword used for declaring variables, the define 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:

       define function-name (parameter-list) { statement-list }


  The function-name is an identifier and must conform to the naming
  scheme for identifiers discussed in chapter ???.  The parameter-list
  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 (statement-list).

  The variables in the parameter-list 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.



  9.2.  Parameter Passing Mechanism



  Parameters to a function are always passed by value and never by
  reference.  To see what this means, consider


            define add_10 (a)
            {
               a = a + 10;
            }
            variable b = 0;
            add_10 (b);



  Here a function add_10 has been defined, which when executed, adds 10
  to its parameter.  A variable b has also been declared and initialized
  to zero before it is passed to add_10.  What will be the value of b
  after the call to add_10?  If S-Lang were a language that passed
  parameters by reference, the value of b would be changed to 10.  How-
  ever, S-Lang always passes by value, which means that b would retain
  its value of zero after the function call.

  S-Lang 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
  NULL.  To make this clear, consider the function


            define add_two_numbers (a, b)
            {
               if (a == NULL) a = 0;
               if (b == NULL) b = 0;
               return a + b;
            }




  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 follow-
  ing ways:


            variable s = add_two_numbers (2,3);
            variable s = add_two_numbers (2,);
            variable s = add_two_numbers (,3);
            variable s = add_two_numbers (,);




  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


            variable s = add_two_numbers (2, NULL);
            variable s = add_two_numbers (NULL, 3);
            variable s = add_two_numbers (NULL, NULL);




  It is important to note that this mechanism is available only for
  function calls that specify more than one parameter.  That is,


            variable s = add_10 ();




  is not equivalent to add_10(NULL).  The reason for this is simple: the
  parser can only tell whether or not NULL 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.
  9.3.  Referencing Variables



  One can achieve the effect of passing by reference by using the
  reference (&) and dereference (@) operators. Consider again the add_10
  function presented in the previous section.  This time we write it as


            define add_10 (a)
            {
               @a = @a + 10;
            }
            variable b = 0;
            add_10 (&b);




  The expression &b creates a reference to the variable b and it is the
  reference that gets passed to add_10.  When the function add_10 is
  called, the value of a will be a reference to b.  It is only by deref-
  erencing this value that b can be accessed and changed.  So, the
  statement @a=@a+10; should be read `add 10' to the value of the object
  that a references and assign the result to the object that a refer-
  ences.

  The reader familiar with C will note the similarity between references
  in S-Lang and pointers 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:


            define derivative (f, x)
            {
               variable h = 1e-6;
               return (@f(x+h) - @f(x)) / h;
            }




  It can be used to differentiate the function


            define x_squared (x)
            {
               return x^2;
            }




  at the point x = 3 via the expression derivative(&x_squared,3).




  9.4.  Functions with a Variable Number of Arguments



  S-Lang 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 add_10 example presented earlier.  This time it is
  written


            define add_10 ()
            {
               variable x;
               x = ();
               return x + 10;
            }
            variable s = add_10 (12);  % ==> s = 22;




  For the uninitiated, this example looks as if it is destined for dis-
  aster.  The add_10 function looks like it accepts zero arguments, yet
  it was called with a single argument.  On top of that, the assignment
  to x 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 add_10 is called with the the
  parameter 12.  Internally, 12 is pushed onto the stack and then the
  function called.  Now, consider the function itself.  x is a variable
  local to the function.  The strange looking assignment `x=()' simply
  takes whatever is on the stack and assigns it to x.  In other words,
  after this statement, the value of x will be 12, since 12 will be at
  the top of the stack.

  A generic function of the form


           define function_name (x, y, ..., z)
           {
              .
              .
           }




  is internally transformed by the interpreter to


           define function_name ()
           {
              variable x, y, ..., z;
              z = ();
              .
              .
              y = ();
              x = ();
              .
              .
           }



  before further parsing.  (The add_10 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:


           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);        % ==> 3.0
          variable ave2 = average_n (3.0, 5.0, 2);   % ==> 4.0




  Here, the last argument passed to average_n 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 else if
  constructs is rather straightforward but hardly worth the effort.
  There must be a better way, and there is:


          define average_n (n)
          {
             variable sum, x;
             sum = 0;
             loop (n)
               {
                  x = ();    % get next value from stack
                  sum += x;
               }
             return sum / n;
          }




  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 _NARGS and may be used as follows:





     define average_n ()
     {
        variable x, sum = 0;

        if (_NARGS == 0) error ("Usage: ave = average_n (x, ...);");

        loop (_NARGS)
          {
             x = ();
             sum += x;
          }
        return sum / _NARGS;
     }




  Here, if no arguments are passed to the function, a simple message
  that indicates how it is to be used is printed out.





  9.5.  Returning Values


  As stated earlier, the usual way to return values from a function is
  via the return statement.  This statement has the simple syntax

       return expression-list ;


  where expression-list 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


               define sum_and_diff (x, y)
               {
                   variable sum, diff;

                   sum = x + y;  diff = x - y;
                   return sum, diff;
               }




  which is a function returning two values.

  It is extremely important to note that the calling routine must
  explicitly handle all values returned by a function.  Although some
  languages such as C do not have this restriction, S-Lang does and it
  is a direct result of a S-Lang function's ability to return many
  values and accept a variable number of parameters.  Examples of
  properly handling the above function include


              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


  See the section below on assignment statements for more information
  about this important point.


  9.6.  Multiple Assignment Statement



  S-Lang functions can return more than one value, e.g.,


              define sum_and_diff (x, y)
              {
                 return x + y, x - y;
              }




  returns two values.  It accomplishes this by placing both values on
  the stack before returning.  If you understand how S-Lang 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.,


             sum_and_diff (9, 4);
             d = ();
             s = ();




  However, the most convenient way to accomplish this is to use a
  multiple assignment statement such as


              (s, d) = sum_and_diff (9, 4);




  The most general form of the multiple assignment statement is


            ( var_1, var_2, ..., var_n ) = expression;




  In fact, internally the interpreter transforms this statement into the
  form


            expression; var_n = (); ... var_2 = (); var_1 = ();




  for further processing.

  If you do not care about one of return values, simply omit the
  variable name from the list.  For example,



          (s, ) = sum_and_diff (9, 4);




  assigns the sum of 9 and 4 to s and the difference (9-4) will be
  removed from the stack.

  As another example, the jed editor provides a function called down
  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


              variable dummy = down (10);




  it is more convenient to use a multiple assignment expression and omit
  the variable name, e.g.,


              () = down (10);




  Some functions return a variable number of values instead of a fixed
  number.  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:


            define read_line (fp)
            {
               variable line;
               if (-1 == fgets (&line, fp))
                 return -1;
               return (line, 0);
            }




  This function returns either one or two values, depending upon the
  return value of fgets.  Such a function may be handled as in the fol-
  lowing example:


             status = read_line (fp);
             if (status != -1)
               {
                  s = ();
                  .
                  .
               }




  In this example, the last value returned by read_line is assigned to
  status and then tested.  If it is non-zero, the second return value is
  assigned to s.  In particular note the empty set of parenthesis in the
  assignment to s.  This simply indicates that whatever is on the top of
  the stack when the statement is executed will be assigned to s.

  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 S-Lang programmers make.  For example, the fflush
  function returns a value that many C programmer's never check.
  Instead of writing


             fflush (fp);




  as one could in C, a S-Lang programmer should write


             () = fflush (fp);




  in S-Lang.  (Many good C programmer's write (void)fflush(fp) to indi-
  cate that the return value is being ignored).



  9.7.  Exit-Blocks


  An exit-block 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 return from deep within a
  function.

  An exit-block is created by using the EXIT_BLOCK keyword according to
  the syntax

       EXIT_BLOCK { statement-list }


  where statement-list represents the list of statements that comprise
  the exit-block.  The following example illustrates the use of an exit-
  block:


             define simple_demo ()
             {
                variable n = 0;

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

                forever
                 {
                   if (n == 10) return;
                   n++;
                 }
             }


  Here, the function contains an exit-block and a forever loop.  The
  loop will terminate via the return statement when n 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,


             define simple_demo (n)
             {
                EXIT_BLOCK { return 1; }

                if (n != 1)
                  {
                     EXIT_BLOCK { return 2; }
                  }
                return;
             }




  If 1 is passed to this function, the first exit-block will get exe-
  cuted 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.






































  10.  Name Spaces


  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 S-Lang code) has an
  anonymous namespace.  Objects may be defined in the anonymous
  namespace via the static declaration keyword.  For example,


            static variable x;
            static define hello () { message ("hello"); }




  defines a variable x and a function hello 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 implements 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,


            implements ("foo");
            static variable x;




  allows the variable x to be accessed via foo->x, e.g.,


            if (foo->x == 1) foo->x = 2;




  The implements function does more than simply giving the anonymous
  namespace a name.  It also changes the default variable and function
  declaration mode from public to static.  That is,


            implements ("foo");
            variable x;




  and


            implements ("foo");
            static variable x;




  are equivalent.  Then to create a public object within the namespace,
  one must explicitly use the public keyword.

  Finally, the private keyword may be used to create an object that is
  truly private within the compilation unit.  For example,

      implements ("foo");
      variable x;
      private variable y;




  allows x to be accessed from outside the namespace via foo->x, however
  y cannot be accessed.

























































  11.  Arrays



  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 S-Lang language.


  11.1.  Creating Arrays



  The S-Lang language supports multi-dimensional arrays of all data
  types.  Since the Array_Type is a data type, one can even have arrays
  of arrays.  To create a multi-dimensional array of SomeType use the
  syntax


             SomeType [dim0, dim1, ..., dimN]




  Here dim0, dim1, ... dimN specify the size of the individual dimen-
  sions of the array.  The current implementation permits arrays consist
  of up to 7 dimensions.  When a numeric array is created, all its ele-
  ments are initialized to zero.  The initialization of other array
  types depend upon the data type, e.g., String_Type and Struct_Type
  arrays are initialized to NULL.

  As a concrete example, consider


            a = Integer_Type [10];




  which creates a one-dimensional array of 10 integers and assigns it to
  a.  Similarly,


            b = Double_Type [10, 3];




  creates a 30 element array of double precision numbers arranged in 10
  rows and 3 columns, and assigns it to b.

  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 1 through 10, one may simply use:


            a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];




  Similarly,



       b = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];




  specifies an array of ten doubles.

  An even more compact way of specifying a numeric array is to use a
  range-array.  For example,


            a = [0:9];




  specifies an array of 10 integers whose elements range from 0 through
  9.  The most general form of a range array is


            [first-value : last-value : increment]




  where the increment is optional and defaults to 1.  This creates an
  array whose first element is first-value and whose successive values
  differ by increment.  last-value sets an upper limit upon the last
  value of the array.  The number of elements in the array is given by
  the expression

       1 + (last-value - first-value)/increment


  Another way to create an array is apply the dereference operator @ to
  the DataType_Type literal Array_Type.  The actual syntax for this
  operation resembles a function call

       variable a = @Array_Type (data-type, integer-array);


  where data-type is of type DataType_Type and integer-array is a 1-d
  array of integers that specify the size of each dimension.  For exam-
  ple,


            variable a = @Array_Type (Double_Type, [10, 20]);




  will create a 10 by 20 array of doubles and assign it to a.  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 array_info
  function.



  11.2.  Reshaping Arrays


  It is sometimes possible to change the `shape' of an array using the
  reshape 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 reshape function follows the syntax

       reshape (array-name, integer-array);


  where array-name specifies the array to be reshaped to have the dimen-
  sions given by integer-array, a 1-dimensional array of integers.  It
  is important to note that this does not create a new array, it simply
  reshapes the existing array.  Thus,


              variable a = Double_Type [100];
              reshape (a, [10, 10]);




  turns a into a 10 by 10 array.



  11.3.  Indexing Arrays


  An individual element of an array may be referred to by its index.
  For example, a[0] specifies the zeroth element of the one dimensional
  array a, and b[3,2] specifies the element in the third row and second
  column of the two dimensional array b.  As in C array indices are
  numbered from 0.  Thus if a is a one-dimensional array of ten
  integers, the last element of the array is given by a[9].  Using a[10]
  would result in a range error.

  A negative index may be used to index from the end of the array, with
  a[-1] referring to the last element of a, a[-2] 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 6, use


            a[3] = 6;




  Similarly, that element may be used in an expression, such as


            y = a[3] + 7;




  Unlike other S-Lang 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





        variable i, sum;
        sum = 0;
        for (i = 0; i < 10; i++) sum += a[i];




  Unlike many other languages, S-Lang permits arrays to be indexed by
  other integer arrays.   Suppose that a is a 1-d array of 10 doubles.
  Now consider:


             i = [6:8];
             b = a[i];




  Here, i is a 1-dimensional range array of three integers with i[0]
  equal to 6, i[1] equal to 7, and i[2] equal to 8.  The statement b =
  a[i]; will create a 1-d array of three doubles and assign it to b.
  The zeroth element of b, b[0] will be set to the sixth element of a,
  or a[6], and so on.  In fact, these two simple statements are equiva-
  lent to


            b = Double_Type [3];
            b[0] = a[6];
            b[1] = a[7];
            b[2] = a[8];




  except that using an array of indices is not only much more conve-
  nient, 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


            a = Double_Type [1000];
            i = [0:499];
            j = [500:999];
            a[i] = -1.0;
            a[j] = 1.0;




  This creates an array of 1000 doubles and sets the first 500 elements
  to -1.0 and the last 500 to 1.0.  Actually, one may do away with the i
  and j variables altogether and use


            a = Double_Type [1000];
            a [[0:499]] = -1.0;
            a [[500:999]] = 1.0;




  It is important to understand the syntax used and, in particular, to
  note that a[[0:499]] is not the same as a[0:499].  In fact, the latte

Showing the first 100 KB of 179.8 KB. Download the archive for the full file.

Site Stats

Snippets: 1791
Codebases: 571