Introduction
************

General Information
===================

The UtiLisp32 is a new implementation of UtiLisp for Unix system. The original UtiLisp  (University of Tokyo Interactive LISt Processor) system  was  designed  for  highly  interactive programming and debugging of sophisticated programs on mainframes.

The new UtiLisp system is a transportation of the original UtiLisp. UtiLisp32 is for Unix 4.2 bsd machines whose CPU's have 32 bit address bus. It is now available on MC68010, MC68020 and Vaxen. This new UtiLisp is called "Unix UtiLisp" or simply "UtiLisp".

The transportation was done carefully so that the new system is compatible to old one. However some of operating system interface functions were not implemented or have different formats.

This  document is intended to serve both as a User's Guide and as  a Reference Manual for the language and the system.  It is hoped  that  those who are familiar with the Lisp language acquire a complete knowledge of the system from this manual.

How to Run and Stop the System on Unix
======================================

UtiLisp32 on Unix is supported as Unix shell command. It is invoked from shell as follows:

         % utilisp

Options are:

-h SIZE
     This specifies that the heap area is to be  SIZE kilo bytes.  The default heap size is 512 kilo bytes.

-ls SIZE
     引数スタックの大きさを SIZE kバイトにします. デフォルトは32kバイトです.

-cs SIZE
     コードスタックの大きさを SIZE kバイトにします. デフォルトは16kバイトです.

-bs SIZE
     束縛スタックの大きさを SIZE kバイトにします. デフォルトは64kバイトです.

-es SIZE
     環境スタックの大きさを SIZE kバイトにします. デフォルトは16kバイトです.

-m SIZE
     mallocで使われる領域の大きさを SIZE kバイトにします. デフォルトは16kバイトです.

-d FILENAME
     FILENAMEで指定されるダンプファイルから, 立ち上げます. スタック, malloc領域の大きさは自動的にdumpfile実行時の大きさに決定されます.

-gctype TYPE
     Garbage Collection(GC)のアルゴリズムを変更します. 0の時はCopying GC, 1の時はMark and Sweep GCを採用します. Mark and Sweep GCは同じヒープサイズでのGC時間がCopying GCの3倍ほどかかりますが, ヒープに使用するメモリ量が半分になるので, 大容量のメモリを必要とするプログラムでは有利になることがあります.

-n
     This specifies that UtiLisp32 should not read and evaluate the file named  .utilisprc  in your home directory on starting up.

-F FILENAME
     This specifies that UtiLisp32 should read and evaluate  FILENAME  file on starting up.

-p SIZE
     This specifies the extendheap-ratio(0-100). If the size of live cells exceeds extendheap-ratio % of heap size after an GC, extendheap was called and heap size becomes twice as before.

-E EXPRESSION
     EXPRESSION is evaled as an Lisp expression on starting up.

If you have a run command file named " .utilisprc " in your home directory, the UtiLisp32 system will read and evaluate it first. This evaluation is identical with that of the  standard toplevel Lisp loop, except that the results are not displayed. The  -n  option supresses this initial evaluation.

After  the  evaluation of the run command file (if any), UtiLisp32 enters  the  toplevel  loop.   Each  S-expression  read in is evaluated  and  the  result  is displayed.  Note that the toplevel evaluator is eval, not evalquote.

The  session  is terminated by evaluating the function quit. If  one  wishes  to  terminate  the  session  abnormally, evaluate function abend.

There  are  cases  in  which  these  system  functions are not recognized  by  the  Lisp  reader, e.g., when the readtable or obvector  has  been  destroyed.   In  such  cases, the UtiLisp32 session can be terminated by ten consecutive exclamation marks

( !!!!!!!!!! )  at  the  beginning  of  an  input  line from the terminal.

In  case  an  endless  or unexpectedly long computation should occur,  an  attention interrupt from the terminal (usually by means  of interrupt) will stop the current computation and the system enters the break loop.  For details, see Chapter ~see ErrDebug "Errors and Debugging".

Notational Conventions and Notes on Syntax
==========================================

There  are  several  notational conventions,  which should  be  understood  before  reading the manual in order to avoid confusion.

In this manual,  Lisp  symbols  are  printed  in   typewriter type style . ITALIC WORDS  appearing  in  S-expressions represent  certain  Lisp  objects  the  details  of  which are irrelevant  or  explained  elsewhere.

In what follows, a Lisp object whose  car  is A and  cdr  is B may sometimes be written in the form (A .  B). However, note  that A and, especially, B are not necessarily atoms. Thus, a list beginning with the symbol progn may be written in the form (progn  .   BODY), where BODY is a list following progn.   Similarly,  in  titles  of descriptions of functions, "plus .  ARGS",  for  example, ARGS indicates  a list of arguments following the function plus.

Lisp  symbols  appearing  as  titles  are  followed  by a description of its arguments. And if it is not an ordinary function, its category will be shown in curly brackets, "" and "".  Specifically, the categories  are  "Function'', "Special Form", "Macro", and "Variable". The following   examples   illustrate  the  manner  in  which  the arguments are described:

quote ARG Special Form

quote is a " special form " and takes one argument.

cons X Y Function

cons is an ordinary function and requires exactly two arguments, X and Y, and their absence generates an error.

gensym (PREFIX) (BEGIN) Function

gensym  may  take  zero  to  two  arguments; PREFIX and BEGIN are optional.

plus . ARGS Function

plus may take arbitrarily many (possibly zero) arguments.

- ARG . ARGS Function

- may take arbitrarily many (but at least one) arguments.

As  in the examples, argument names appear in italics in the description of the function.

The  symbol "=>"  is  used  to  indicate  evaluation in examples,  e.g.,  "foo => nil"  means  that "the  result of evaluating foo is nil".

There  are  several terms which are widely used in this manual but   will   not   be  rigorously  defined.   They  are:  S-expression , which  means  a  Lisp  object, especially in its printed  representation;   dotted pair , which means a  cons ; and  atom ,  which  means  a Lisp object other than a  cons . Note  that  an atom does not necessarily mean a symbolic atom; it may be a number, string, etc.  It is recommended that those who  are  not familiar with these terms consult an appropriate Lisp textbook.

Several  characters  have  special  meanings in UtiLisp, i.e., single  quote('),  backquote( ` ), comma( , ),semicolon( ; ), and slash( / ).

Semicolons  are  used  for  comments.   When  the  Lisp reader encounters   a   semicolon,  it  ignores  all  the  characters remaining  on  the  current  line and resumes reading from the beginning  of the next line.  In such a case, a blank space is automatically introduced between the last symbol preceding the semicolon  and  the first symbol on the next line.  However, a semicolon  may occur as an element of a string (see remarks on double quotes below).

A  single  quote ' has the same effect as the special form quote(see below).  For example, \sexpr'foo is read as (quote foo), and  \sexpr'(cons  'foo  'bar) is  read as (quote (cons (quote foo) (quote bar))), etc.

Slashes  are  used  for  escaping  characters possessing special functions  so  that  they  are  merely  interpreted  as normal alphabetic characters.  For example, \sexpr/'foo is read as a symbol whose  print name is \sexpr"'foo" and not as "(quote foo)".  Thus, one must type " // " to convey the symbol " / " to the Lisp reader.

Double quotes are used for indicating strings.  Any characters occurring between a double quote and the next double quote are read  as  a  string.   Double  quotes occurring inside strings should  be typed twice.  For example,  """"  represents a string consisting  of  one  double quote.  A string may extend beyond the ends of a line.

Concerning backquotes and commas, see Chapter ~see Macros "Macros".

Data Types
==========

There  are ten data types in UtiLisp32, i.e.,  symbol ,  cons , fixnum ,  bignum ,  flonum ,  string ,  vector , reference ,  stream , and  code piece .

A  symbol has a  print name ,

a  value (sometimes called a binding ),  a  definition ,

and  a  property list . The  print name is  a  string  which is the value of the function pname when  applied to the symbol in question; this string serves as the of the symbol.  The  value  may be any Lisp object, and is interpreted as the value of the symbol when the  symbol  is used as a variable.  The symbol may also be in  unbound state,  in  which case, it has no value at all. Access to the value of a symbol is effected by evaluating the symbol, and the value may be updated by using the functions set and setq. The  definition  is functional attribute of the symbol; access is effected by getd and updating by putd or defun.  The  property list  contains  an  even  number(possibly zero) of elements; direct  access  and  updating  are  effected  by plist and setplist, respectively,  but it is usually more convenient to use  the  functions  get (for access), putprop (for adding and updating  properties),  and remprop (for removing properties). symbol is the basic function for creating a new symbol with a certain  print  name.   All symbols which are normally read in are  registered in a table called  obvector , and any of these which  bear  the  same  name  are  identified  by means of the function intern (for  details,  see  Chapter ~see InandOut, "Input and Output").   The  function gensym serves to generate a sequence of distinct symbols.

A  cons  is a Lisp object possessing two components,  car  and cdr ,  which  may  be  any Lisp objects.  Access to these two components   is   effected  by  the  functions car and cdr, respectively, and updating by rplaca and rplacd, respectively. A  cons  may be constructed by means of the function cons.

There are three kinds of numerical objects

in this system, upon which arithmetical operations may be performed; one is fixnum   which  possesses  28-bit  signed  integer value. Bignum  is an  integer of arbitrary length. Both  fixnum  and bignum  are categorized as integers. Most of arithmetic functions convert the type between the two automatically. The other is   flonum  which possesses 64-bit floating point value. The is about 15 decimal digits in MC68000 series and 17 decimal digits in Vax.

A  string is a finite(possibly zero) sequence of

.  Each character has an 8-bit code value which is usually interpreted in terms of the ASCII code. Independent access to and updating of these  characters are effected by means of the functions sref and sset, respectively. The length of a string may be known by applying the function string-length.

A  vector is a finite(possibly zero) ordered set of Lisp objects. Vectors are  created  by means of the function vector. Access to the vector element is effected by means  of the function vref and updating by the function vset. The  length  of a vector may be known by applying the function vector-length.

A  reference is  a pointer indicating an element of a vector. It  is  often  useful to have access to and update elements of vectors. A reference   is  created  by  the  function reference; access to and updating of the corresponding element can  be  effected  by means of the functions deref and setref, respectively.

A  stream is an object related to I/O.  All the

in  this  system are carried out by means of such intermediary streams, which are created by the function stream.

A  code piece is a segment of machine code which constitutes the  body of a predefined or compiled functions.  Code pieces have names, normally a symbol, access to which is effected by means of the function funcname.

Lambda Lists
============

A lambda-expression  is  the format specifying an interpreted function in Lisp, and is of the form

          (lambda LAMBDA-LIST . BODY)

where  BODY is a list of forms.  Usually, LAMBDA-LIST is a list  of  symbols  which  corresponds  to the so-called formal parameter list in certain other programming languages.When a lambda-expression  is applied to given values of the argument

(actual  parameters),  the  symbols are bound to these values, and  the  forms constituting BODY are evaluated sequentially and the result of the last of these evaluations becomes the  final  result  of the application.  The formal parameters are  then  unbound  and the state is restored to that of preapplication. If  the  number of actual arguments is not equal to the length of LAMBDA-LIST, an error is generated.

In UtiLisp32, an element of LAMBDA-LIST may be either a symbol or a list of the form

          (SYMBOL . DEFAULTS)

When  the  number of actual arguments to which the function is applied  is  less  than the length of LAMBDA-LIST, the given actual arguments are first bound to the corresponding symbols. The  remaining  elements  of  LAMBDA-LIST must have the list form (SYMBOL . DEFAULTS). Here, DEFAULTS

is a list of forms which  are  evaluated  sequentially and the result of the last one  (or nil in the case when DEFAULTS is empty) is bound to SYMBOL.   If  an  actual  argument corresponding to a symbol associated with a list DEFAULTS is given, then the symbol is  bound  to  this  actual  argument  and the associated list DEFAULTS is merely ignored.

Default   values  are  evaluated  after  the  binding  of  the preceding  arguments,  hence, they may depend upon the results of the preceding bindings.

Examples of lambda-lists:

(a b c)
     actual parameters for a, b, and c are all required.

(a b (c))
     a and b are required but c is optional; the default value of c is nil.

(a b (c 0))
     a and b are required but c is optional; the default value of c is 0.

(a b (c (print "Default value is used for C.") 0))
     a and b are required and c is optional; when the default value is used, the indicated message is printed.

(a b (c (cons a b)))
     a and b are required and c is optional; the default value of c depends upon a and b.

Predicates
**********

A predicate is a function which tests the validity of some condition involving its arguments and returns the symbol t if the condition holds, and the symbol nil otherwise.

When  a  Lisp  object  is  used  as  a  logical  value,  it is interpreted  as  false if  and  only if it is nil; all Lisp objects other than nil are interpreted as  true.

Predicates on Data Types
========================

The  following  predicates  are for testing data types.  These predicates  return t if its argument is of the type indicated by the name of the function, nil if it is of some other type.

symbolp ARG Function

symbolp returns t if ARG is a  symbol ; otherwise nil.

consp ARG Function

consp returns t if ARG is a  cons ; otherwise nil.

listp ARG Function

listp is equivalent to consp.  This is incorporated mainly for compatibility with other Lisp systems.

atom ARG Function

atom returns t if ARG is not a  cons ; otherwise nil.

fixp ARG Function

fixp returns t if ARG is a  fixnum  object, i.e., a small integer number; otherwise nil.

bigp ARG Function

bigp returns t if ARG is a  bignum  object, i.e., a big integer number; otherwise nil.

integerp ARG Function

integerp returns t if ARG is a  fixnum  or a bignum , i.e., an integer number; otherwise nil.

floatp ARG Function

floatp returns t if  ARG  is  a   flonum   object, i.e., a floating-point number; otherwise nil.

numberp ARG Function

numberp returns t if ARG is a  fixnum , a  bignum or a  flonum , i.e., a numerical object; otherwice nil.

stringp ARG Function

stringp returns t if ARG is a  string ; otherwise nil.

vectorp ARG Function

vectorp returns t if ARG is a  vector ; otherwise nil.

referencep ARG Function

referencep returns t if ARG is a  reference  pointer; otherwise nil.

streamp ARG Function

streamp returns t if ARG is a  stream ; otherwise nil.

codep ARG Function

codep returns t if ARG is a  code piece ; otherwise nil.

General Purpose Predicates
==========================

The   following  functions  are  some  other  general  purpose predicates.

eq X Y Function

eq returns t if  X  and Y denote the same Lisp object; otherwise  nil.  Lisp objects which have the same printed representations  are  not necessarily identical.  However, the  interning  process ensures that two symbols with the same  print  name  are  identical  (see  Chapter ~see InandOut "Input and Output", for details).   Unlike  some  other Lisp systems, equality of values of small integer numbers ( fixnums )  may  also  be compared using eq.

Note:   In  this manual, the expression "two Lisp objects are eq" means that they are the same object.

neq X Y Function

(neq X Y) is equivalent to (not (eq X Y))

equal X Y Function

equal returns t if X and Y are "similar" Lisp objects;  otherwise  nil.  That is, two strings are equal if  they  have  the same length and all the characters in corresponding  positions  are the same, two  bignums  are equal if they have the same integer value, two  flonums  are equal  if  they  have the same floating-point value, two vectors equal if their size is same and all their contents are eq, and two  cons   cells  are  equal  if  their respective  cars  and   cdrs  are equal inductively. In all other cases, two objects are equal if and only if they are eq.

If two Lisp objects are equal, they have the same printed representation, however, the reverse does not necessarily hold (e.g., for symbols which have not been "interned").

not X Function

null X Function

not returns the symbol t if X is eq to nil; the symbol  nil  otherwise. null is equivalent to not; both functions  are  incorporated for the sake of readability. It  is recommended that null is used for checking whether a  given value is nil, and that not be used for inverting a logical value.

UtiLisp32  also  includes  various predicates in addition to those  introduced in this chapter.  These will be described in the  chapters  on  the  various  data  types accepted by these predicates;  for  example, the predicate zerop is described in Chapter ~see Numbers, "Numbers".

Evaluation
**********

The Evaluator
=============

The process of evaluation of a Lisp form is as follows:

If the form is neither a  symbol  nor a  cons , i.e., if it is a fixnum , a   bignum , a  flonum , a  string , a  code piece , a  vector , a  reference  or a  stream , then the result of its evaluation is simply the form itself.

If the form is a  symbol , then the result is the value to which that  symbol  is bound.  If the symbol is unbound, an error is generated.

A  so-called special form (i.e., a  cons  identified by a distinguished  symbol  in  its  car ) is evaluated in a manner which  depends  upon  the particular form in question.  All of these   special  forms   will  be individually described in this manual.

If  the  form  in  question is not a so-called  special form , then  it  requires the application of a function or a macro to its  arguments.   The  car  of the form is a lambda-expression or  the name of a function.  If the function is not a  macro , the   cdr   of the form is a list of forms which are evaluated sequentially,  from left to right, and the resulting arguments

are  then supplied to the function; the value finally returned is the result of applying the function to these arguments.

The evaluation process for macro forms is described in Chapter ~see Macros, "Macros".

A more detailed and accurate description of the evaluator will be given after various improvements of present implementation have been carried out.

Various Functions Concerned with Evaluation
===========================================

eval X Function

eval evaluates  X, and returns the result.  Ordinarily, eval is not often used explicitly, since evaluation is usually carried  out  implicitly.   eval  is  primarily useful in programs  concerning  Lisp  itself,  rather  than  in its applications.

apply FN ARGLIST Function

apply applies  the  function FN to the set of arguments given by ARGLIST, and returns the resulting value.

funcall FN . ARGS Function

funcall applies the function FN to the set of arguments ARGS, and   returns   the   resulting  value.   Note  that  the functional  argument  FN is evaluated in the usual way, while function which constitutes the  car  of an ordinary Lisp application is not.

Example: s

            (setq cons 'plus) => plus
            (funcall cons 1 2) =>  3
            (cons 1 2) => (1 . 2)

Thus,  explicit  application  using  funcall,  instead of simple  implicit function application, should be used for functional  arguments, since, the binding of the function is  not  examined  by  the  evaluator  in simple implicit function  applications, whereas when funcall is used, the functional argument symbol is evaluated first, yielding a function which is then applied in the ordinary manner.

quote ARG Special Form

quote simply returns  the  argument  ARG.   Its  usefulness largely  consists  in  the  fact that its argument is not evaluated by the evaluator.

Example: s

            (quote x) => x
            (setq x (quote (cons 1 2))) => (cons 1 2)
            x => (cons 1 2)

Since  quote  is  very  frequently  used, the Lisp reader allows  the  user  to  reduce the burden of keying in the program  by converting S-expressions preceded by a single quote character "\sexpr'" into quoted forms.  For example,

               (setq x '(cons 1 2))

is converted into

               (setq x (quote (cons 1 2)))

function FN Special Form

The  form  (function X) has precisely the same effect as (quote X); these alternative forms are available for the sake  of  clarity in reading and writing programs.  It is recommended  that  function be used to quote a piece of a program,  and  that  quote  be used for segments of data. The   compiler  utilizes  this  information  to  generate efficient object codes.

Note:  Function-valued arguments in Lisp functions should be  evoked using funcall.  See the description of funcall (above) for details.

comment  . ARGS Special Form

comment ignores its arguments and always returns nil; it is useful for inserting explanatory remarks.

progn  . ARGS Special Form

The  arguments  ARGS  are  evaluated sequentially, from left  to  right,  and  the value of the final argument is returned.   This operation is useful in cases where it is necessary  to  evaluate a number of forms for the sake of the  concomitant  side  effects but only the value of the last  form  is  required.   Note that lambda-expressions, cond  forms,  and  many  other  control  structure  forms incorporate  this  property  of  progn implicitly (in the sense  that  multiple  forms  are  handled  in  a similar manner).

prog1  . ARGS Special Form

prog1 functions in the same manner as progn, except that it  returns  the  value of the first argument rather than the  last.   prog1  is  most  commonly used to evaluate a number  of  expressions,  with possible occurrence of the side  effects,  and return a value which must be computed before the side effect occur.

Example:

                (setq x (prog1 y (setq y x)))

This  form interchanges the values of the variables x and y.

prog2  . ARGS Special Form

The  action  of  prog2  is  the same as that of progn and prog1,  except  that  it  returns the value of its second argument.   It  is  incorporated mainly for compatibility with other Lisp systems.

              (prog2 X Y . Z)

is equivalent to

              (progn X (prog1 Y . Z))

let BINDINGS . BODY Macro

A let form has the syntax:

                (let ((VAR1 VFORM1)
                      (VAR2 VFORM2)
                      ...)
     	   (l
                  BFORM1
                  BFORM2
                  ...)

which  is  automatically  converted  into and effectively equivalent to the following form:

                ((lambda (VAR1 VAR2 ...)
     	   ((lam
                  BFORM1
                  BFORM2
                  ...)
     	   (
     	   VFORM1
     	   VFORM2
                ...)

It is often preferable to use let rather than to directly use  lambda,  since  the  variables and the corresponding forms  appear  textually  close  to  one  another,  which increases the readability of the program.

As let forms are converted into lambda application forms, all  the  values  of  the  VFORM's  are computed before binding  any  of  these  values  to the corresponding VAR's.    For  example,  VFORM2  cannot  depend  upon VAR1,  that  is,  if VAR1 appears in VFORM2, then a variable  named  VAR1  must  have  been bound somewhere outside this let form.

lets BINDINGS . BODY Macro

lets  is  similar to let except that lets  binds its
variables   sequentially,  one  by  one,  while  let,  as
mentioned   above,  binds  them  at  once.   (lets  is  a
contraction of "let Sequentially").

A lets form has the syntax:

                (lets ((VAR1 . VFORMS1)
                      (VAR2 . VFORMS2)
                      ...)
     	   (l
                  BFORM1
                  BFORM2
                  ...)

which is effectively equivalent to:

                ((lambda ((VAR1 . VFORMS1)
                          (VAR2 . VFORMS2)
                          ...)
     	   ((lam
                     BFORM1
                     BFORM2
                     ...))

each  list  VFORMS-I  constitutes the default value list for  the  corresponding VAR-I, and therefore can depend upon  the  preceding  VAR's  (see  Section 1.5, "Lambda Lists", for details).

Note:   The interpretation of lets is faster than that of
let.    However,   once  compiled,  their  speeds  become
identical.

Flow of Control
***************

The  present  system  provides a variety of structures for the flow of control.

Functional application is  the basic  method for constructing programs.   Moreover,  the definition of a function may always call  the  function  being  defined.  This process is known as "recursion".

Both  explicit  and  implicit progn structures may be used for sequential  execution  of  programs.   The  forms  in  a progn structure are evaluated sequentially from left to right.

In  this  chapter,  some even more flexible control  structures are described.   Conditional  constructs  are useful for making  decisions,  while iteration and mapping constructs

may be  convenient  for  repetition.  There are also more flexible control structures known as non-local exits.

Conditionals
============

A  conditional construct incorporates a decision in a program, resulting  in  the execution of one of several alternatives in accordance with certain logical conditions.

and  . ARGS Special Form

and evaluates the arguments sequentially, from left to right. If the value of some argument is nil, then nil is returned and  the  remaining  arguments are not evaluated.  If the value of all the arguments are non-nil , then the value of the  last  argument  is returned.  and can be interpreted for  logical  operation, where nil stands for  false  and non-nil for  true .

Example: s

             (and x y)
             (and (setq temp (assq x y))
                  (rplacd temp z))
             (and error-exists (princ "There is an error!"))

Note:  (and) => \sexprt

or  . ARGS Special Form

or evaluates the arguments sequentially, from left to right. If the value of some argument is nil, the next argument is evaluated.  If there are no remaining arguments, then nil is  returned.   However,  if the value of some argument is non-nil,  then that value is immediately returned and the remaining  arguments,  if any, are not evaluated.  or can be  interpreted  as a logical operation, where nil stands for  false  and non-nil for  true .

Note:  (or) => \sexprnil

cond  . CLAUSES Special Form

The   arguments  of  cond  are  usually  referred  to  as "clauses".   Each clause consists of a predicate followed by  a  number (possibly zero) of forms.  The predicate is called  the  "antecedent"  and  the  forms are called the "consequents".

Thus, a cond-form might have the following syntax:

       (cond (ANTECEDENT CONSEQUENT CONSEQUENT ...)
             (ANTECEDENT)
             (ANTECEDENT CONSEQUENT ...)
             ...)

Each  clause  represents an alternative which is selected if its ANTECEDENT is satisfied and the ANTECEDENTs of all preceding clauses were not satisfied when evaluated.

The  clauses  are  processed  sequentially  from  left to right.   First,  the  ANTECEDENT of the current clause is evaluated.  If the result is nil, the process advances to the   next   clause.    Otherwise,  the  CONSEQUENTs  are evaluated  sequentially  from  left  to right (in a  progn manner),  the  value  of the last consequent is returned, and the remaining clauses (if any) are not processed.  If there  were  no  CONSEQUENTs in the selected clause, then the  value of the ANTECEDENT is returned.  If the clauses are  exhausted, that is, the value of every ANTECEDENT is nil, then the value of the cond form is nil.

selectq KEY-FORM . CLAUSES Special Form

Many  programs  require multiplex branchings which depend on  the  value  of  some  form.   A typical example is as follows:

       (cond ((eq x 'foo) ...)
             ((eq x 'bar) ...)
             ((memq x '(baz quux mum)) ...)
             (t ...))

selectq   is   incorporated   for   convenience  in  such situations.  A selectq form has the following syntax:

       (selectq  KEY-FORM
           (PATTERN CONSEQUENT CONSEQUENT ...)
           (PATTERN CONSEQUENT CONSEQUENT ...)
           (PATTERN CONSEQUENT CONSEQUENT ...)
           ...)

The  first  argument  KEY-FORM is evaluated first (only once).  The resulting value is called the key.  The KEY-FORM is followed by a number of  cluases , each of which consists  of  a  PATTERN followed by a number (possibly zero)  of CONSEQUENT forms . The PATTERN of each clause is  compared  with  the  key,  and  if  it "matches" , the CONSEQUENTs  of  this  clause  are evaluated, and selectq returns  the  value of the last CONSEQUENT.  If there are no  "matches",  or  if  there  is  no  CONSEQUENT  in the selected  clause,  then  nil  is returned.  Note that the PATTERNs are not evaluated.

The  objects  which may be used as the PATTERNs and their "matching" conditions are as follows:

 1. Any atom (symbol, number, etc.), except the symbol t The  key matches if it is eq to the atom.

 2. A list The key matches if it is eq to one of the top-level elements of the list.

 3. The symbol t The  symbol  t  constitutes  a special pattern which matches anything.

Example:  The preceding example  is  expressed with  selectq  as follows:

              (selectq x
              (sel
                  (foo ...)
                  (bar ...)
                  ((baz quux mum) ...)
                  (t ...))

Note:   The  symbol  t  itself  may  be used as the first component  of  a  clause,  in  a  non-trivial  manner, by selecting (t) as the pattern.

match KEY-FORM . CLAUSES Special Form

match is a special form for pattern matching. A match form has the following syntax:

       (match KEY-FORM
              (PATTERN CONSEQUENT CONSEQUENT ...)
              (PATTERN CONSEQUENT CONSEQUENT ...)
              (PATTERN CONSEQUENT CONSEQUENT ...)
              ...)

The first argument KEY-FORM is evaluated first (only once). The resulting value is called the key. The KEY-FORM is followed by a number of  clauses , each of which consists of a PATTERN followed by a number (possibly zero) of CONSEQUENT forms

. The PATTERN of each clause is compared with the KEY, and if it "matches", the CONSEQUENTS of this clause are evaluated, and match returns the value of the last CONSEQUENT. If ther are no "matches", or if there is no CONSEQUENT in the selected clause, then nil is returned. Note that the PATTERNS are not evaluated.

The Objects which may be used as the PATTERN and their "matching" conditions are as follows:

 1. nil The KEY matches if it is nil.

 2. Any symbol except the symbol nil The KEY matches any symbol, and the symbol is lambda-bound to the KEY. The binding is unbound when the pattern matching fails. When the matching succeeds, the binding is kept during the evaluation of the clause and is unbound immediately before the evaluation ot the match form.

 3. non symbolic atom The KEY matches if it is eq the atom.

 4. ( quote  S-expression) The KEY matches if it is eq the S-expression.

 5. cons  other than 4 The KEY matches if its  car  "matches" the  car of the PATTERN and its  cdr  "matches" the  cdr  of the pattern.

Example: s To return the S-expression if what is read in is of the form (quote S-expression); the first element if it is a list; nil for all other cases:

     	(match (read)
     	  (('quote sexpr) sexpr)
     	  ((top . rest) top))

The same program would become with cond form as follows:

     	(lets ((x (read)))
     	  (cond ((atom x) nil)
     	        ((and (eq (car x) 'quote)
     	              (consp (cdr x))
     	              (null (cddr x)))
     	        (cadr x))
     	        (t (car x))))

Function copy is realized with  match  as follows:

     	(match x
     	  ((head . tail) (cons (copy head) (copy tail)))
     	  (x x))

Note: When the some variables appear more than twice in PATTERN, consistency of the parts correspond to the same pattern would not be checked. The variable is lambda-bound by the last corresponding part.

Iteration
=========

prog LOCALS . BODY Special Form

prog   is   a   special  form  which  provides temporary variables

, sequential  evaluation  of  forms, and  goto operations.  A typical prog form might have, for example, the following structure:

              (prog (VAR1
     	        (VAR2 . INITS2)
     	        VAR3
     	        (VAR4 . INITS4))
              TAG1 STATEMENT1
                          STATEMENT2
              TAG2 STATEMENT3
                          ...)

VAR1,  VAR2,  ... are  temporarily bound variables. The  binding of these variables prior to the execution of the prog are saved, and when the execution of the prog has  been  completed, the original bindings are restored. If  a  variable  is associated with an initial value list INITS,  then  the  elements  of  the list are evaluated sequentially,  from  left  to right, and the value of the last  one  becomes the initial value of the variable.  If there  are  no  initial value forms, then the variable is initialized to nil.

Example:

             (prog ((a t)
                    b
                    (c (print "c is bound")
     	          (car '(foo . bar))))
                    . BODY)

Here, the initial value of a is t, that of b is nil, and that  of c is the symbol foo. Before the binding of c is executed, the indicated message is printed.  The bindings are  processed  sequentially,  and the value of each form may depend upon previous bindings.

The  portion of a prog which follows the variable list is called  the body.  The elements of BODY may be atoms, which  are  called  tags,  or   cons   cells, which are called statements.

After  the temporary variables have been bound, the forms in  the  BODY  are  processed sequentially.  TAGs are not evaluated,  whereas  STATEMENTs  are  evaluated and their values  discarded.   If  process  reaches  the end of the BODY, then nil is returned.  However, two special devices (described  below)  may  be  used  to  alter  the flow of control in the BODY of a prog.

When

     	(return $X_1$ ...  $X_N$)

is evaluated, then processing of the BODY is terminated and the value of the last argument $X_N$ is returned as the value of the prog form.  If N=0, i.e., if no arguments are present, then the value returned will be   nil.    Only   those  return  statements  which  are explicitly  included  in  the  body  of  a  prog form should legitimately  be used  in this manner (for example, a return statement  occurring  within the definition of a function called  during  the  execution of a prog will generate an error when the program is compiled.)

When

     	(go TAG)

is evaluated, then the evaluation process is resumed  from  the statement labelled with TAG (in case there  is  no statement associated with TAG, i.e., when TAG  is  at the end of a prog body, the prog routine is simply terminated); TAG is not evaluated.  If the label TAG  does  not  occur  in  the  body  of  the prog form currently  being executed, the body of the innermost prog form  properly including the current one is searched, and so  forth; if TAG is found, then the execution sequence leaves the current prog form and the program execution is resumed from the point labelled with TAG.  If the label TAG  does not occur in any prog form which contains (go TAG), then an error is generated. Any statement of the form (go TAG) must explicitly be included in the prog form containing the destination indicated by TAG.

go TAG Special Form

See the explanation under the entry for prog above.

Note:   TAG  may  be  an  atom  of  any  type including symbols  or   fixnums .   Since  the  process  of searching  is  effected  using the equality criterion eq,  bignum , flonums ,  strings ,  vectors ,  etc. are  generally not appropriate as labels.

return . ARGS Function

See the explanation under the entry for prog above.

loop . BODY Special Form

loop  is  a   special form  used for simple iteration.  The arguments of loop are evaluated sequentially from left to right.   As  long  as  exit  is  not  evoked during these evaluations,   this  process  is  interminably  repeated. However,  if  an exit form is encountered, the inner-most loop  containing  it  is  terminated and the value of the last  argument  of  this exit is returned as the value of that loop form.

Example:  The  top-level  loop  of  UtiLisp32, although actually defined in terms of machine language, could have been defined as follows:

                (loop (print (eval (read))))

exit . ARGS Function

See the explanation under the entry for loop above.  exit being  an  ordinary function, its arguments are evaluated sequentially, from left to right, in the usual manner.

When  a  loop  form  is to be compiled, the corresponding exit forms must be explicitly contained in the loop.

do INDEX-PART EXIT-PART . BODY Macro

do  is  a  control form which facilitates iteration using so-called   index variables . The first argument INDEX-PART is a list, the elements of which have the form

       (VAR INIT NEXT)

where  VAR  is  a symbol employed as an index variable, INIT is the initial value assigned to VAR, and NEXT is  a  form  which  is  computed  after  each  iteration, whereupon the resulting value is assigned to VAR.

The  initial  values  are computed sequentially, and only after  this  process  is  completed are they bound to the corresponding  variables;  the same applies to subsequent assignments arising from the NEXT forms.

The second argument EXIT-PART has the syntax as

       (END-TEST . EXIT-FORMS)

After  initially  binding  the index variables, and after each  round  of  NEXT value updating, the form END-TEST is  evaluated.   If  the  result  is  non-nil, the termination  process  begins;  the forms constituting the list  EXIT-FORMS  are evaluated sequentially, from left to  right,  and the value of the last one (or nil, if the list EXIT-FORMS is empty) will be returned as the value of  the  do  form.  The index variables are then unbound, their original values are restored, and the evaluation of the do form terminates.

Otherwise,  if  the  evaluation of END-TEST yields nil, execution  of  BODY  begins; BODY is a list of forms, which are evaluated sequentially, from left to right, and the results are discarded.  When BODY is exhausted, the evaluation  process  proceeds  to  the  evaluation of the NEXT forms.

Any  NEXT form may be omitted from INDEX-PART when no assignment  of  the  corresponding  variable  is required after  iteration; in this case, VAR merely serves as an ordinary  local variable.  Any initiation form INIT may also  be  omitted;  in this case, nil becomes the initial value of the corresponding VAR.

A do form, being a macro, is automatically converted into an  equivalent  combination  of  let  and loop.  Thus, to depart  from  a do form, the function exit may be used in its  BODY,  EXIT-PART,  or  the  NEXT  forms of its INDEX-PART.  It should be borne in mind that, since the INIT  forms  are evaluated outside the loop, the use of exit in an INIT form will terminate the evaluation of a still  "larger"  do  or  loop  form  than  the  one under consideration.

Example: s  Printing  all  the  elements  of  a  list  x separated  by  a  space may be performed by the following program:

              (do ((l x (cdr l)))
                  ((atom l))
                  (prin1 (car l))
                  (princ " "))

When  each  element  of a vector v is a number, their sum may be computed by the following program:

             (do ((i 0 (1+ i))
                   (l (vector-length v))
                   (sum 0 (plus sum (vref v i))))
                 ((= i l) sum))

Note  that,  in  this  example,  the body of do is empty. This  is,  in  fact, the case in many applications, since the  index  and  exit  parts of a do control form can, in themselves,  be  quite  powerful.   Also  note that, when (vref v i) is computed, the variable \sexpri still retains its previous  value, that is, the NEXT value (1+ i) has not yet  been assigned to it.  l does not have a NEXT part, and  is merely a temporary variable which facilitates the computation of END-TEST.

do* INDEX-PART EXIT-PART . BODY Macro

Non-local Exits
===============

catch TAG . FORMS Special Form

catch  is  a  function  primarily  utilized for non-local exits non-local exit. (catch TAG . FORMS) evaluates the elements of the  list FORMS and returns the value of the last form, unless  an  expression  of the form (throw TAG .  VALUES) with  the same TAG is encountered during the evaluation of  FORMS,  in which case the arguments in VALUES are evaluated,  and catch immediately returns the last of the VALUES  (or nil when VALUES is empty) and performs no further evaluation.

Note:   The argument TAG is evaluated, which is not the case  in  some  other Lisp systems.  However, no repeated evaluation  is  applied  to  the  elements  of  the  list FORMS,  which  are  evaluated  only  once as the normal arguments  of  a  function.   The special action of catch occurs  during  the  evaluation  of its arguments, rather than  during  the execution of catch itself; the function catch,  in itself, only returns its last argument (or nil when  there is only one argument TAG) if the evaluation of its arguments is completed without calling throw.

Example:

            (catch 'atomic
              (mapcar l
                (function
                  (lambda (x)
                    (cond ((atom x) (throw 'atomic x))
                          (t (car x)))))))

This  program  returns  a  list  of  the   car 's  of the elements of the list l, if the latter are all non-atomic, otherwise, the first atomic element of l is returned.

throw TAG . VALUES Function

As  described  above,  throw  is used in conjunction with catch for (primarily non-local) exits.  throw conveys the value  of  the  last  argument  in  VALUES (or nil when VALUES is empty) back to the closest preceding catch in the execution sequence which possesses the same TAG and has  not  yet  been  evoked.   Any  catch forms (or other control  forms  or functions) which may be nested between the  throw form under consideration and the corresponding catch are effectively ignored.  See the above description of catch for further details.

Note:   As  in the case of catch, both TAG and forms in VALUES are evaluated, unlike the corresponding function throw in some other Lisp systems.

Example:   The following program returns a rather than b.

                (catch 'a (catch 'b (throw 'a 'a)) 'b)

Mapping
=======

Mapping is a type of iteration in which a certain function is successively  applied  to portions of a list or a vector given as  an  argument.  There are several options for the manner in which  the  portions  of the list or the vector are chosen and the  results  returned  by the application of the function are presented.

The table shows the relations between the six map functions on list structures.

+---------------------------------------------------+
|                        |   applies function to    |
+------------------------+--------------------------+
|                        |  successive | successive |
|                        |   sublists  |  elements  |
+------------------------+-------------+------------+
|         |    its own   |             |            |
|         |    first     |   `map'     | `mapc'     |
|         |   argument   |             |            |
|         +--------------+-------------+------------+
|         |  list of the |             |            |
| returns |    function  |   `maplist' | `mapcar'   |
|         |    results   |             |            |
|         +--------------+-------------+------------+
|         | nconc of the |             |            |
|         |   function   |   `mapcon'  |  `mapcan'  |
|         |   results    |             |            |
+---------+--------------+-------------+------------+

map LIST FN Function

The  function  FN is applied to the successive sublists of  LIST,  i.e.,  first  LIST itself, then its  cdr , then   cddr ,  and so on.   The  value returned is its original argument LIST (possibly modified by FN).

Example:

                (map '(a b c) (function prin1))

This  program prints out

          	(a b c)(b c)(c)

and returns (a b c)

mapc LIST FN Function

The  function  FN is applied to the successive elements
of  LIST,  i.e.,  first  the   car  of LIST, then its
cadr ,  then   caddr ,  and so on.   The value returned is its
original argument LIST (possibly modified by FN).

Example:

                (mapc '(a b c) (function prin1))

This  program prints out

          	abc

and returns (a b c)

maplist LIST FN Function

The  function  FN is applied to the successive sublists of  LIST,  i.e.,  first  LIST itself, then its  cdr , then  cddr , and so on.  The value returned is a newly created list of the results of these applications.

Example:

                (maplist '(a b c) (function prin1))

This  program prints out

          	(a b c)(b c)(c)

and returns ((a b c) (b c) (c))

mapcar LIST FN Function

The  function  FN is applied to the successive elements of  LIST, i.e., first  car  of LIST, then its  cadr , then  caddr , and so on .  The value returned is a newly created list of the results of these applications.

Example:

                (mapcar '(a b c) (function prin1))

This  program prints out

          	abc

and returns (a b c) , which appears   the   same  as  the  original  arguments,  but, actually, has newly been created.

mapcon LIST FN Function

The  function  FN is applied to the successive sublists of  LIST,  i.e.,  first  LIST itself, then its  cdr , then   cddr ,  and so on.  The value returned is the results of these applications concatenated together.

Example:

                (mapcon '(a b c) (function ncons))

This program returns ((a b c) (b c) (c))

mapcan LIST FN Function

The  function  FN is applied to the successive elements of  LIST, i.e., first  car  of LIST, then its  cadr , then   caddr , etc.  The value returned is the results of these applications concatenated together.

Example:

                (mapcan '(a b c) (function ncons))

This  program  returns (a b c), which appears the same as the  original  argument,  but,  actually,  has newly been created.

mapv VECTOR FN Function

mapv  successively  applies  FN  to all the elements of VECTOR,  in increasing order of indices.  The arguments presented  to  the  function FN are  reference  objects "pointing"  to  the elements of VECTOR.  See Chapter 9, "Vectors",  for  further  information  about  reference . The  value  returned  by  mapv  is  simply  the  original argument  VECTOR (possibly modified by the execution of the function FN).

Example:

             (mapv (vector 5)
               (function (lambda (r)
                           (setref r (read)))))

This   will   return   a  vector  of  five  Lisp  objects consecutively read in.

mapvector VECTOR FN Function

mapvector  also  applies  FN  to  all  the  elements of VECTOR,  in  increasing  order  of indices. However, in this  case,  the  arguments  presented  to  FN  are the elements themselves, rather than  references  "pointing" to them  (see the description of mapv).  mapvector returns a new  vector the components of which are the corresponding results of these applications.

Manipulating List Structure
***************************

Cons manipulation
=================

car X Function

car  returns  the  car  of X. If X is an atom, an error is generated.

cdr X Function

cdr  returns the  cdr   of  X.  If X is an atom, an error is generated.

c...r X Function

All  the  compositions  of  car  and cdr, upto a total of four,  are  defined  as, so-called, "built-in" functions. The  names of these functions begin with c, followed by a  sequence  of  a's  and  d's  corresponding  to the indicated composition of functions, and end with r.

Example:

              (cddar X)

is effectively the same as

              (cdr (cdr (car X)))

cr X Function

cr  returns  X itself, and is the function in the c...r
group  for  which  the total number of a's and d's is
zero.   This  function  is  sometimes useful when dealing
with   mapping  functions.   For  example,

     	(mapcar  LIST (function  cr))

may be used to obtain a top-level copy of LIST.

cons X Y Function

cons  is  a primitive function which creates a new  cons cell,  the  car   and   cdr   of  which are X and Y, respectively.

Example: s

                (cons 'a 'b)  =>  (a . b)
                (cons 'a '(b c d))  =>  (a b c d)

ncons X Function

(ncons X) is effectively the same as (cons X nil)

xcons Y X Function

xcons  (an  abbreviation of "eXchange cons") differs from cons only in that the order of the arguments is reversed. xcons  is useful when the  cdr  part of the result should be evaluated before the  car  part.

Example:

                (xcons 'a 'b)  =>  (b . a)

copy X Function

copy  creates  and  returns  a copy of X.  The atoms constituting  the copy are the same as those constituting the  original  argument  X, but all the  cons  cells of the copy are newly created.

Note:   List  structures  in  which  a non-atomic node is indicated  by  more  than  one  pointer  are  not  copied faithfully;  such nodes will be duplicated in the "copy". Copying a cyclic structure in this manner results in an endless computation.

List Manipulation
=================

The  following  section  explains  some of the basic functions provided   for   manipulating    lists . A  list   is  defined recursively  as  either  the  symbol  nil, which represents an empty  list,  or  a  cons  whose  cdr  is a list.  However, it should  be noted that, although their arguments are denoted by the  word  list , the functions described below are applicable whether or not the final atom is nil. Most functions treat the dotted list as if the last non- nil  atom being  nil .

last LIST Function

last  returns  the  last  top-level  cons  of LIST.  If LIST  is  an  atom,  an error is generated; if the toplevel structure  of  LIST  is  cyclic, then an endless computation occurs.

Example:

                (last '(a (b c) d e))  =>  (e)
     	   (last '(a b c . d)) => (c . d)

length LIST Function

length  returns  the  length  of LIST.  The length of a list is the number of its top-level elements.

As  in  the  case  of last, if the top-level structure of LIST is cyclic, an endless computation occurs.

Example: s

                (length '(a (b c) d e))  =>  4
                (length nil)  =>  0
     		   (length '(a b c . d)) => 3

first X Function

(first X) is equivalent to \sexpr(car X)

second X Function

(second X) is equivalent to \sexpr(cadr X)

third X Function

(third X) is equivalent to \sexpr(caddr X)

fourth X Function

(fourth X) is equivalent to \sexpr(cadddr X)

fifth X Function

(fifth X) is equivalent to \sexpr(car (cddddr X))

sixth X Function

(sixth X) is equivalent to \sexpr(cadr (cddddr X))

seventh X Function

\sexpr(seventh X) is equivalent to \sexpr(caddr (cddddr X))

nth N LIST Function

nth  returns the Nth top-level element of LIST, where (car LIST) is counted as the zeroth element.  If N is negative  or not less than the length of LIST, an error is  generated.  Note that (nth 2 X) is actually
\sexpr(third X) rather than \sexpr(second X).

Example:

                (nth 2 '(a b c d e))  =>  c

nthcdr N LIST Function

nthcdr  applies cdr to the second argument for N times, and  returns  the result; for N=0, the result is simply LIST  itself.   If N is negative or not less than the length of LIST, an error is generated.

Example:

                (nthcdr 2 '(a b c d e))  =>  (c d e)

list . ARGS Function

list  constructs  and  returns  a  list of its arguments, ordered in the same manner as the arguments themselves.

Example: s

                (list 1 2 (car '(3 5)) (+ 2 2))  =>  (1 2 3 4)
                (list)  =>  nil

append . LISTS Function

The  result  of  append is essentially a concatenation of its arguments, however, avoiding physical alteration, the arguments  are  copied (except for the last one; see also the  description  of  nconc  below).   The  tail  of  the resulting  list  is physically identical with that of the last argument.

Example: s

                (append '(a b c) '(d e) nil '(f g h))
                        =>  (a b c d e f g h)
                (append)  =>  nil

Note:   When  several  lists  are to be appended and the order of the resulting list is not essential, the longest argument  should  be placed last since it is not copied; this  reduces  both  computing  time  and required memory space.

reverse LIST Function

reverse  creates  a  new  list, the top-level elements of which  are  the  same  as those of LIST but arranged in reverse  order.   reverse,  unlike  nreverse (see below), does not modify its argument.

Example:

                (reverse '(a (b c) d))  =>  (d (b c) a)

nconc . LISTS Function

nconc  returns  a  list which is the concatenation of the arguments.   The  arguments  (except  the  last  one) are physically  altered  in  the manner of rplacd rather than copied (see also the description of append above).

Example: s

                (setq x '(a b c))
                (setq y '(d e f))
                (nconc x y)  =>  (a b c d e f)
                x  =>  (a b c d e f)

Note  that  the value of x itself has been altered, since the   cdr   of  its  last  cons  has been replaced by the value of y. Note: when x is nil,x is not altered.So,you use not side effect but return value.

nreverse LIST Function

nreverse  reverses  its argument LIST, which is altered in  the  rplacd  manner throughout the list (see also the description of reverse).

Example:

                (setq x '(a b c))
                (nreverse x)  =>  (c b a)
                x  =>  (a)

Note  that  the value of x itself has been altered, since the original list has been modified in rplacd fashion.

push ITEM VAR Special Form

(push ITEM VAR) has the same effect and value as

                (setq VAR (cons ITEM VAR))

but  is  more  readable.  VAR must be a bound variable. push   is   useful,   along  with  pop  (see  below),  in maintaining a list in the manner of a push-down stack.

pop VAR Special Form

(pop VAR) has the same effect and value as

                (prog1 (car VAR) (setq VAR (cdr VAR)))

but  is  more  readable.  VAR must be a symbol which is bound  to  a  non-atomic  value prior to the execution of pop. pop  is  useful,  along  with push (see above), in maintaining a list in the manner of a push-down stack.

Alteration of List Structure
============================

The  functions  rplaca and rplacd serve to alter existing list structure;  that  is,  to  change  the   car   and   cdr  of existing  cons  cells.

Since  structure  is  physically  altered  rather than copied, caution  should  be  exercised  when using these functions, as unexpected  side effects may occur if portions of the affected list  structures  are  common  to  several  Lisp objects.  The functions  nconc  and  nreverse  also  alter  list  structure, however,  they  are  not  normally  used  to obtain such side effect side effect, rather,  the concomitant list-structure modification is   effected   purely   for   the   sake  of  efficiency  and corresponding non-destructive functions are also available.

rplaca X Y Function

rplaca  replaces  the   car   of  X  by Y and returns
(modified)  X.   X must be a  cons , while Y may be
any Lisp object.

Example:

                (setq x '(a b c))
                (rplaca x 'n)  =>  (n b c)
                x  =>  (n b c)

rplacd X Y Function

rplacd  replaces  the  cdr   of  X  by Y and returns
(modified)  X.   X must be a  cons , while Y may be
any Lisp object.

Example:

                (setq x '(a b c))
                (rplacd x 'c)  =>  (a . c)
                x  =>  (a . c)

subst X Y Z Function

(subst X Y Z) substitutes X for all occurrences of Y in Z  (using eq for testing equality) and returns the modified copy of Z. The original Z is not altered, as subst recursively copies all the  cons  cells of Z, replacing by X all elements which are eq to Y.

Example:

        (subst 'a 'b '(a b (c b))) =>  (a a (c a))

Note:   List  structures  in  which  a non-atomic node is designated  by  more  than  one  pointer  are  not copied faithfully;  such nodes will be duplicated in the "copy". Applying  subst  to  a  cyclic  structure  results  in an endless computation.

Tables
======

UtiLisp32  provides  several  functions  which  simplify the maintenance  of  several  varieties of tabular data structures assembled from  cons  cells.

The  simplest  of these structures is just an ordinary list of items, which represents an ordered set.

An  association list is a list the element of which are  cons cells.   The  car   of each such  cons  is called a "key" and the  cdr  represents an associated datum.

Although these simple data structures are convenient for small data  bases,  their  form  is  such that search time increases linearly with the size of the data base, and consequently they are  inefficient  when handling large amounts of data.  Large- scale data bases are best maintained using vectors and hashing functions (see Chapter ~see Hashing for details).

memq ITEM LIST Function

(memq ITEM LIST) returns nil if ITEM is not identical (with respect to the function eq) with one of the elements  of LIST, otherwise, it returns the portion of LIST  beginning  with  the  first occurrence of ITEM. The  procedure  searches  LIST  on  the top-level only. Since memq returns nil if ITEM is not found, and a non-nil  object  if  it  is  found,  memq  may  be  used as a predicate.

Example:

                (setq x '(a b c d e))
                (memq 'c x)  =>  (c d e)
                (memq 'foo x)  =>  nil

member ITEM LIST Function

member  functions in the same manner as memq, except that equal, rather than eq, is used for comparison.

mem PREDICATE ITEM LIST Function

mem  functions in the same manner as memq, except that it takes  an additional argument PREDICATE, which may be  any  predicate  taking two arguments.

             (mem (function eq) A B)

is  effectively identical with

             (memq A B)

and

             (mem (function equal) A B)

with

             (member A B)

Example:

              (mem (function (lambda (x y) (0= (+ x y))))
                   13
                   '(1 3 -4 -13 7 -6))
                 =>  (-13 7 -6)

delq ITEM LIST (N) Function

When  the  optional  argument N is absent, delq returns LIST  with all top-level occurrences of ITEM deleted; eq  is  used  for  comparison.   The  argument  LIST is actually altered in the rplacd manner when occurrences of ITEM  are  exercised,  except that any initial segment of LIST  all the elements of which are eq to ITEM is not altered  in  this  manner (see Example below).  If N is present,  it  must  be  a  fixnum  and only the first N top-level  occurrences of ITEM are deleted.  N may be zero,  in  which  case, LIST itself is returned without any alteration.

Example:

                (setq x '(a b a b))
                (delq 'b x)  =>  (a a)
                x  =>  (a a)

Note:   delq  should  be  used for value, not for effect. Thus, the two pairs of operations

                (setq y '(a b a b))
                (setq y (delq 'a y))

and

                (setq y '(a b a b))
                (delq 'a y)

result  in  different values of y.  The value returned by delq is (b b) in both cases.  However, y is given the
value (b b) in the former case and \sexpr(a b b) in the latter.

remq ITEM LIST (N) Function

remq  yields  the same result as delq, except that LIST
itself  is not altered; what is returned is a copy of the
original  argument  LIST  with  the first M
top-level occurrences of ITEM removed, where M is the
minimum of N and the number of top-level occurrences of
ITEM in LIST.

every LIST PREDICATE Function

every  applies  PREDICATE,  a predicate function of one
argument,   to   the   top-level   elements   of   LIST
sequentially, from left to right.  If PREDICATE returns
non-nil  for every element, then every returns t.  If any
of  these applications yields nil, then every returns nil
immediately, and no further applications are executed.

some LIST PREDICATE Function

some  applies  PREDICATE,  a  predicate function of one
argument,   to   the   top-level   elements   of   LIST
sequentially, from left to right.  If PREDICATE returns
non-nil  for  some element, then some immediately returns
the  portion  of  LIST beginning with the element which
yielded   non-nil,   and   no  further  applications  are
executed.   If  all the applications yield nil, then some
returns nil.

assq ITEM ALIST Function

assq  searches  for  and returns the first element in the
association list  ALIST  the   car   of which is eq to
ITEM,  if  such an element exists, or otherwise,
nil  is returned.  The association list may be updated by
applying  rplacd  to the result of assq, if the latter is
not nil.

Example:

                (assq 'c '((a b) (c d) (e f))) =>  (c d)

assoc ITEM ALIST Function

assoc  functions  in the same manner as assq, except that equal instead of eq is used for comparison.

ass PREDICATE ITEM ALIST Function

ass  functions in the same manner as assq, except that it takes  an  additional  argument  PREDICATE, a predicate taking  two  arguments, which is used for comparison.  In the  special  case where PREDICATE is eq, this function effectively reduces to assq.

Sorting
=======

sort TABLE PREDICATE Function

The  list  TABLE is arranged in increasing order, using the  ordering  relation corresponding to PREDICATE, and the  resulting  ordered  list  is  returned.  PREDICATE should be a function of two arguments, which returns non-nil if  and  only if the first argument is strictly less than the second in the sense of total ordering relation.

Example:

            (sort '(3 1 4 5 2) 'greaterp)
                  => (5 4 3 2 1)

Hashing
=======

Some  hashing  scheme  is  desirable  in  order  to reduce the computing time required for data retrieval in large-scale data bases.   Time required for searching an item remains constant using  hashing,  as  long  as  the hash table is large enough, compared with the number of its entries.

UtiLisp32  provides a standard hashing function for Lisp  objects  to  facilitate  the maintainance of hashed data bases.

hash X Function

hash  computes  hash  value  for X and returns it as an integer  number   fixnum .   The  result may be positive, negative, or zero.  Its properties guaranteed are:

 1. Objects which are equal are hashed to the equal value.

 2. A  fixnum  is hashed to itself.

 3. A  bignum  is hashed to non negative value.

 4. A string is hashed to non-negative value.

 5. A  symbol  is hashed to the same value as its print-name.

Symbols
*******

Symbolic atoms such as x or cons are called  symbols in UtiLisp32.   A   symbol   is associated with four Lisp objects; the binding   is  the  value  of  the symbol when it is used as a variable; the definition is the functional definition of the symbol   when  it is used as the name of a function or a macro; the  property list  is  used to retain various Lisp objects associated with the  symbol ; the print name is used for input and output operations.

The Value
=========

A   symbol   may  be associated with its value, which may be a Lisp  object  of  any  type,  and is returned as the result of evaluating  the  symbol .  The  symbol  may be in unbound state, in  which  case  the   symbol   has  no  value  at  all; when an unbound symbol   is evaluated, an error is generated.  Newly created  symbols  (by intern, gensym, etc.) are initially in the unbound   state.   A   symbol   is called a variable when the primary concern is its value.

The  value  of  a  variable  may be changed either by  lambda-binding or by assignment; when a  symbol  is  lambda-bound , its  previous  value  is  saved  and  will  be restored later, whereas   assignment   discards  the previous value.   lambda-binding is sometimes called simply  binding  in this manual.

The symbols nil and t always must be  bound to themselves; they may not  be  assigned  nor lambda-bound (The error of changing the value of t or nil is not detected!).

set VARIABLE NEW-VALUE Function

Assignment    to  VARIABLE  is  effected  by  the function  set.   The  value  of  VARIABLE is changed to NEW-VALUE  which  may be any Lisp object.  The previous value  of  VARIABLE, if any, is discarded.  set returns the newly assigned value NEW-VALUE.

setq . ARGS Special Form

(setq X Y) is effectively the same as (set 'X Y)

Additional  feature  of  setq is concurrent assignment of variables  without  explicit temporary variables.  A setq form such as

               (setq VAR1 FORM1 VAR2 FORM2 ...)

is used for this purpose.  FORM1, FORM2, ...  are all evaluated first, sequentially, in this order.  Then their resulting values are assigned to VAR1, VAR2, ...

Example:    Values  of  two  variables  x  and  y are exchanged by

               (setq x y y x)

boundp VARIABLE Function

boundp  returns  t  if VARIABLE is bound to some value; otherwise, i.e., if it is unbound, nil is returned.

make-unbound VARIABLE Function

make-unbound makes VARIABLE unbound.  The current value of   VARIABLE,  if  any,  is  discarded.   make-unbound returns the symbol VARIABLE as its value.

The Definition
==============

A  symbol  may be associated with its functional definition, or  definition , for short.  When a function is called via its name,  that is, when the first argument of funcall or apply is a  symbol,  or  a  symbol appears as the  car  of a form to be evaluated,  the  definition  of  that  symbol is called as a function.   When  a  symbol is not defined as a function nor a macro,  the  symbol  is  said  to  be  undefined ; an error is generated when an undefined symbol is used as a function.

defun NAME LAMBDA-LIST . BODY Macro

defun is used for defining functions.  NAME should be a symbol.  A list

               (lambda LAMBDA-LIST . BODY)

will  be  the  new  definition  of  NAME.  The previous definition  of  NAME,  if  any,  is  discarded.   defun returns NAME as its value.

macro NAME LAMBDA-LIST . BODY Macro

macro  is used for defining macros.  NAME should be a symbol.  A list

               (macro lambda (ARG) . BODY)

will  be  the  new  definition  of  NAME.  The previous definition  of  NAME,  if  any,  is  discarded.   macro returns NAME as its value.

Note:    Macros  are  more  elegantly  defined  using defmacro.  See Chapter ~see Macros "Macros", for detail.

getd SYM Function

getd  returns the definition of a symbol SYM.  If SYM is undefined, an error is generated.

putd SYM DEF Function

putd makes the definition of SYM be DEF. SYM must be  a  symbol  while  DEF  may  be any Lisp object.  It returns SYM as its value.

definedp SYM Function

definedp returns t if SYM is defined as a function or a macro;  otherwise,  i.e.,  if  it  is  undefined,  nil is returned.

Note:   definedp  returns nil for special form indicators
such  as  cond, since they are not defined as an ordinary
function  nor  a  macro.   Use the function specialp (see
below) to discriminate special form indicators.

specialp SYM Function

specialp  returns  t if SYM is a special form indicator (such as cond or prog); otherwise, it returns nil.

make-undefined SYM Function

make-undefined makes the symbol SYM undefined.  Current definition  of  SYM,  if any, is discarded.  It returns SYM as its value.

The Property List
=================

Every  symbol is associated with its property list, which is a list used for associating certain Lisp objects with symbols. A  property list  has an even number of elements; each pair of elements  constitutes  a property. The first of the pair is called  the  indicator  or the  name  of the  property , and the second is a Lisp object called the  value  of the  property .

Example: A  property list  which have the form

                (Japan Tokyo England London France Paris)

indicates  that  there  are three  properties  named Japan, England and France, and their values are Tokyo, London and Paris, respectively.

When a  symbol  is created, its  property list  is set initially to nil.

Note:  Printnames ,  bindings  and  functional definitions  are often implemented as  properties  of  symbols  in various Lisp systems;   however, they   are   not  implemented  as  usual properties  in UtiLisp32.

get SYM NAME Function

get searches for a  property  of SYM named NAME.  If it finds  such  a  property ,  it  returns  the value of that property ; otherwise, it returns nil.

Note:   If  the  value  of  a  property   is  nil,  it  is impossible  to distinguish whether that  property  exists or not, only from the result of get.

putprop SYM VALUE NAME Function

If  the  symbol SYM has no  property  with its name being NAME, then putprop adds a new  property  named NAME with  the  value  VALUE;  otherwise,  the  value of the existing property is updated to VALUE.  putprop returns VALUE as its resulting value.

defprop SYM VALUE NAME Macro

(defprop X Y Z) is effectively the same as (putprop 'X 'Y 'Z)

defnprop SYM VALUE NAME Macro

(defnprop X Y Z) is effectively the same as (putprop 'X (function Y) 'Z)

remprop SYM NAME Function

remprop removes the  property  of SYM with its name being NAME.   If  SYM  has no such  property , it merely does nothing.  remprop returns nil as its value.

plist SYM Function

plist returns the  property list  of SYM.

setplist SYM PROPERTY-LIST Function

setplist sets the   property list  of SYM to PROPERTY-LIST.  It returns PROPERTY-LIST as its value.

The Print Name
==============

Every symbol has an associated string called the print name, or   pname   for  short.   This  string is used as the printed representation of the symbol in input and output operations.

Though   print names   are  normal character string objects (see Chapter ~see Strings "Strings",  for  more  information  about strings), modifying  them  (by  sset, etc.) requires certain care, since they  are  used  to   hash   symbols into the Lisp name table, obvector  (see Chapter ~see InandOut "Input and Output", for details).

pname SYM (NEW-NAME) Function

pname returns the  print name  of the symbol SYM. 2引数で呼んだ時には, print nameをnew-nameに変更する.

Creation of Symbols
===================

symbol PNAME Function

symbol creates  and returns a new uninterned  symbol  with its  print name being PNAME.

{symbolとまったく同じシンボルを生成する.

gensym (PREFIX) (BEGIN) Function

gensym  generates  a  new  print name,  and creates a new "uninterned" symbol with that print name (see Chapter~see InandOut "Input and Output", for "interning").

The  generated   print name  is prefixed by a string, which is initially g but may be changed by giving gensym a string  argument PREFIX.  The prefix string is followed by a 4-digit decimal representation of an integer number. This  number  is  incremented by one every time gensym is called  and only the least significant 4 digits are used. This number can also be initiated by giving a  fixnum  to gensym as its second argument BEGIN.

Example: s

        (gensym)  =>  g0034
        (gensym "gen")  =>  gen0035
        (gensym "abc" 15)  =>  abc0015
        (gensym)  =>  abc0016

Note:    Print names   of  symbols  generated by gensym are
primarily   for  ease  of  their  inspection  in  printed
representations.   After  ten  thousand gensym calls, the
print name   of  the  generated symbol will be the same as
the first one, but they are not the same symbol,as far as they are not interned.

See  also  Chapter~see InandOut "Input and Output", for intern which may create a symbol with given  print name .

Numbers
*******

There are three types  of  numbers in UtiLisp32, namely fixnums ,  bignums  and  flonums .

The  fixnums  of UtiLisp32 have a signed integer value of 28 bits. No overflow  checking  is  made  on  arithmetical  operations  for fixnums  only. All the results are treated modulo $2^28$.

The  bignums  are arbitrary long integer. The integer which exceeds the length of  fixnum  will be  bignum . The  bignums  are made when the reader reads a big integer and when results of computation exceed the limit of  fixnum . But some functions don't do this conversion. The  fixnum  and the  bignum  are categorized to  integers together.

The  flonums  have a 64-bit floating point value with the accuracy of about 15 decimal digits in MC68000 microprocessors. In case of Vax, the accuracy is about 17 decimal digits. Neither overflow nor underflow are checked on arithmetical operations on flonums .

Integers  are  denoted  using  conventional  decimal notation (e.g., 15) and  flonums  using decimal notation with a decimal point  (e.g.,  15.0);   flonums  may also have "exponent part" indicated by the character "^" (e.g., 1.5^1).

Functions   described   in  this  chapter  expect  numbers  of appropriate  types  for  their  arguments; if an argument of an illegal type is given, an error is generated.

Functions  on  numbers are grouped into three categories by the  type  of  the numbers they accept:  Functions the name of which  includes  alphabetic  characters  (e.g., plus)  are applied to all of the types of the numbers. Conversions between  fixnum  and  bignum  are automatically made in these functions. Functions consisting only of non-alphabetic characters are special purpose functions.  If their names  end  with  the  character  "$" (e.g., +$), they are for flonums   only;  otherwise  (e.g., +),  for   fixnums  only. Notice that no overflow check or conversion to  bignum  are made for fixnum  functions. These  rules  apply  to  all  the  functions described in this chapter except explicitly stated otherwise.

Special purpose  arithmetic  functions  are  computed more efficiently  than  general purpose  ones,  especially when the functions using them are compiled.

Numeric Predicates
==================

zerop X Function

0= X Function

0=$ X Function

zerop, 0= and 0=$ return t if X is zero (of proper type); otherwise, they return nil.

plusp X Function

0< X Function

0<$ X Function

plusp, 0< and 0<$ return t if X is a positive number (of proper type); otherwise, they return nil.

minusp X Function

0> X Function

0>$ X Function

minusp, 0> and 0>$ return t if X is a negative number (of proper type); otherwise, they return nil.

oddp X Function

oddp returns t if X is odd integer; otherwise, it returns nil. X must be a  fixnum  or a  bignum .

= X Y Function

=$ X Y Function

= and =$ return t if X and Y are equal numbers (of proper type); otherwise, they return nil.

Note:   Equality  of numbers is also tested using the function equal; equality of  fixnums  is also tested using eq.

# X Y Function

<> X Y Function

#$ X Y Function

<>$ X Y Function

#, <>, #$ and <>$ return t if X and Y are not equal numbers; otherwise, they return nil.

lessp ARGS Function

< ARGS Function

<$ ARGS Function

lessp, < and <$ return t if the number of arguments is less than 2,  or each argument (except the last) is  strictly  smaller  than  its successor; otherwise, they return nil.

greaterp ARGS Function

> ARGS Function

>$ ARGS Function

lessp, < and <$ return t if the number of arguments is less than 2,  or each argument (except the last) is  strictly  larger than  its successor; otherwise, they return nil.

<= ARGS Function

<=$ ARGS Function

lessp, < and <$ return t if the number of arguments is less than 2,  or each argument (except the last) is  strictly  smaller  than or equal to its successor; otherwise, they return nil.

>=  ARGS Function

>=$ ARGS Function

lessp, < and <$ return t if the number of arguments is less than 2,  or each argument (except the last) is  strictly  larger  than or equal to its successor; otherwise, they return nil.

Conversion Functions
====================

fix X Function

fix converts  a  flonum  X into an integer (a  fixnum  or a  bignum ) and returns that integer; rounding is used for the conversion.   \beginfunctionfloatx float converts a fixnum  or a  bignum  X into a  flonum  and returns that flonum .

Arithmetics
===========

plus . ARGS Function

+ . ARGS Function

+$ . ARGS Function

plus, + and +$ return the sum of its arguments.  With no argument, plus and + return 0, and +$ returns 0.0.

minus X Function

minus returns the nagative of X.

difference ARG . ARGS Function

difference returns its first argument minus all the rest of its arguments.

- ARG . ARGS Function

-$ ARG . ARGS Function

With  only  one  argument,  - and -$ behave the same as minus;  they  return  the negative of the argument.  With more than one arguments, - and -$ are effectively the same as difference; they return their first argument minus all of the rest of the arguments.

times . ARGS Function

* . ARGS Function

*$ . ARGS Function

times, * and *$  return  the product of its arguments. With  no argument, times and * return 1, and *$ returns 1.0.

quotient ARG . ARGS Function

// ARG . ARGS Function

//$ ARG . ARGS Function

quotient, // and //$ return the first argument divided by all  of  the rest of its arguments.  For //, the division performed  is  integer division with truncation; for //$, floating-point  division;  for quotient, the type of the division performed depends on the type of the arguments.

// is  written here as "//" rather than "/" since "/" is the escape character in UtiLisp32 syntax and must be doubled.

add1 X Function

\sexpr(add1 X) is equivalent to \sexpr(plus X 1)

1+ X Function

\sexpr(1+ X) is equivalent to \sexpr(+ X 1)

1+$ X Function

\sexpr(1+$ X) is eqivalent to \sexpr(+$ X 1.0)

sub1 X Function

\sexpr(sub1 X) is equivalent to \sexpr(difference X 1)

1- X Function

\sexpr(1- X) is equivalent to \sexpr(- X 1)

1-$ X Function

\sexpr(1-$ X) is equivalent to \sexpr(-$ X 1.0)

incr VAR AMOUNT Macro

(incr VAR AMOUNT) is equivalent to
(setq VAR (+ VAR AMOUNT))

decr VAR AMOUNT Macro

(decr VAR AMOUNT) is equivalent to
(setq VAR (- VAR AMOUNT))

remainder X Y Function

X Y
$ X Y

  * remainder, and $ return the remainder of X divided by  Y.  The sign of the result is the same with X (if not zero).

max ARG . ARGS Function

max returns the largest of its arguments.

min ARG . ARGS Function

min returns the smallest of its arguments.

abs X Function

abs returns $|$X$|$, the absolute value of the number X.

expt X Y Function

\ X Y Function

\$ X Y Function

expt, \ and \$ return the Yth power of X. Y must be  a   fixnum .   When X is a  fixnum  and Y is non negative,  then the result will be a  fixnum  or  bignum ; in all the other cases, the result will be a  flonum .

sin X Function

sin  computes and returns  sin X.  X may be any type of numbers, and the result is a  flonum .

cos X Function

cos  computes  and  returns cos X.  X may be any type of numbers, and the result is a  flonum .

tan X Function

tan  computes  and  returns tan X.  X may be any type of numbers, and the result is a  flonum .

arcsin X Function

arcsin computes  and  returns arcsin X.   X may be any type of numbers, and the result is a  flonum .

arccos X Function

arccos  computes  and  returns arccos X.    X may be any type of numbers, and the result is a  flonum .

arctan X Function

arctan computes  and  returns arctan X. X may be any type of numbers, and the result is a  flonum .

sqrt X Function

sqrt computes and returns the square root of  X. X may be any type of nonnegative numbers, and the result is a  flonum .

log X Function

log  computes  and  returns the natural logarithm of X. X may be any type of positive numbers, and the result is a  flonum .

log10 X Function

log10 computes and returns the ordinary logarithm of X. X may be any type of positive numbers, and the result is a  flonum .

exp X Function

exp computes and returns a  flonum  the natural logarithm of which is X.

Logical Operations on Numbers
=============================

Following functions treat  fixnums  as bit sequences

of 28-bit long.   If  a  non  fixnum  argument  is  supplied, an error is generated.

logor . ARGS Function

logor  returns  bitwise  logical  "or"  of the arguments. When no arguments are supplied, 0 is returned.

logand . ARGS Function

logand  returns  bitwise  logical "and" of the arguments. When no arguments are supplied, -1 is returned.

logxor . ARGS Function

logxor  returns  bitwise  logical "xor" of the arguments. When no arguments are supplied, 0 is returned.

logshift X Y Function

logshift returns X logically shifted Y bits.  If Y is positive, X is shifted left; if Y is negative, X is  shifted  right.  Absolute value of Y should be less than 28.

Strings
*******

A  string is a Lisp object consisting of a sequence of zero or more  characters.  Strings   are  primarily used for manipulating texts.  Print names  of  symbols  are  also represented using strings .

Characters of a  string  may be independently referenced and updated  using  sref and  sset,  respectively.  The subscript

origin  for  sl strings is zero.  If a subscript value specified is not appropriate, i.e., if it is negative or greater than or equal  to  the length of the corresponding sl string, an error is generated.

Characters are   fixnums   which resides between 0 and 255, i.e.,  representable  in  one byte (8 bits).  They are usually treated   as  ASCII  character  codes  in  input  and  output operations.

Strings  may also  be  seen  as  vectors  of small non negative integer   fixnums   ranging 0 through 255.  This kind of usage may save a considerable memory space, compared with the use of normal vectors which requires 4 bytes for each component.

Characters
==========

Characters  are a  fixnum   which resides between 0 and 255.
They   are  treated  as  ASCII  codes  in  input  and  output
operations.

character X Function

Some  of the functions manipulating  strings  require their
arguments to be  a   character .   Though  most  of  the
functions   introduced   in  this  chapter  automatically
coerce   strings   or   symbols   to   characters ,  there are
certain cases in which explicit conversion is required.

character  coerces X to a single  character , represented
as  a   fixnum .  If X is a  character , i.e.  a  fixnum
which  resides between 0 and 255, X itself is returned.
If  X  is  a  non-null   string ,  its first character is
returned.  If X is a sl symbol, the first character of its
print name  is   returned.    Otherwise,   an  error  is generated.

String Manipulation
===================

Note that the subscript origin for strings is zero.

string X Function

Functions  manipulating  strings  require  string  arguments. Though  most  of the functions introduced in this chapter automatically  coerce   symbols   to   strings ,  there  are certain cases in which explicit conversion is required.

string  coerces  X  into a  string . If X is a  string , X itself is returned. If X is a  symbol , its  print name  is returned.   If X is a  character , a one-character  string containing  X  is  returned.   Otherwise,  an  error is generated.

make-string LENGTH (CHAR) Function

make-string allocates  and  returns  a new  string  of the length  given  by  LENGTH.   If  the  optional argument CHAR,  which  must be a  character , is given, all the characters  of  the allocated  string  will be initiated to CHAR;  otherwise,  to the  fixnum  0 (not the character code for "0").

string-length STRING Function

string-length   returns   the  number  of  characters  in STRING,  which  is  one more than the largest subscript value for STRING.

string-equal STRING1 STRING2 Function

string-equal  compares  two   strings  and returns t if two
strings   have  the  same length and all the corresponding
characters are the same; otherwise, it returns nil.

Although comparison  of  equality  of  two   strings   is  also effected  by  the  function equal, string-equal is more specific and, therefore, more efficient.

string-lessp STRING1 STRING2 Function

string-lessp compares two  strings  in dictionary order. The  result  is  t if STRING1 is the lesser, and nil if they are equal or STRING2 is the lesser.

Example: s

        (string-lessp "abc" "abd")  =>  t
        (string-lessp "abc" "ab")  =>  nil

substring STRING (START) (END) Function

substring  extracts  a substring of STRING, starting at the character  indexed  by  START  up  to  but  not including  the  character  indexed by END.  Thus, the length  of  the   string   returned  will  be  END  minus START.   The  default  value for END is the length of STRING, and that of START is 0.

Example: s

        (substring "abcde" 1 3)  =>  "bc"
        (substring "abcde" 1)  =>  "bcde"
        (substring "abcde")  =>  "abcde"

Note:   Even  if  both  START  and  END  are omitted, substring makes a new copy of STRING and returns that copy.

string-append  . STRINGS Function

Any  number of  strings  are copied and concatenated into a single   string .   If  no  arguments are given, string-append returns a null string \sexpr"".

string-reverse STRING Function

string-reverse returns  a  copy of STRING with the order of characters reversed. The original  string  is not physically altered (see also the description of string-nreverse below).

string-nreverse STRING Function

string-nreverse returns  STRING  with the order of characters reversed.  The  reversing is made on the argument STRING directly, physically  altering  the order of characters in STRING (see also the description of string-reverse above).

string-search-char CHAR STRING (FROM) Function

string-search-char  searches  for CHAR through STRING starting  at  the  index FROM.  It returns the index of the  first appearance of CHAR, or nil if none is found. CHAR may be a character or a list of characters, in the latter case, the subscript of the first occurrence of one of  the listed characters is returned.  The default value for FROM is zero.

Example:

        (string-search-char "b" "abcde")  =>  1

string-search-not-char CHAR STRING (FROM) Function

string-search-not-char  is the same as string-search-char except  that  it searches for the occurrence of character which is  not  CHAR, or, when CHAR is a list,  not  a member of CHAR.

Example:

        (string-search-not-char "0" "007") =>  2

string-search KEY STRING (FROM) Function

string-search searches for the  string  KEY in the  string STRING.   The  search  begins  at subscript FROM, the default  value  of  which is zero.  The value returned is the  subscript  of  the  first  character  of  the  first instance of KEY, or nil if none is found.

Example:

        (string-search "word" "Where is the word?") => 13

translate STRING TABLE Function

translate  converts  characters in STRING using TABLE as the conversion table. TABLE must be a string of 256 characters.   Its  subscript-sl n  character substitutes the character  whose  code  is  sl n.   The argument STRING is physically  altered.   translate  returns  the (modified) STRING.

lower-case Variable

upper-case Variable

Values   of   lower-case   and  upper-case  are  standard conversion tables for converting upper-case characters to lower-case  ones  and  the  reverse, respectively.  These tables  are  also used by the Lisp reader and the printer (see Chapter ~see InandOut "Input and Output", for details).

string-amend STRING1 STRING2 (FROM) Function

string-amend moves characters in STRING2 into STRING1 physically  altering  characters  in  STRING1.  All the characters  in  STRING2  are  moved  to  the portion of STRING1  beginning  with  the specified subscript value FROM.  The default value of FROM is 0.

string-amend-and STRING1 STRING2 (FROM) Function

string-amend-or STRING1 STRING2 (FROM) Function

string-amend-xor STRING1 STRING2 (FROM) Function

string-amend-and, -or and -xor are the same as string-amend except that characters in STRING2 are not simply moved  into  STRING1,  rather,  logical  "and", "or" or "xor" of  characters  in  STRING2  and  corresponding characters  in  STRING1  are  moved  to  a  portion  of STRING1  beginning  with  the specified subscript value FROM.  The default value of FROM is 0.

string-trim STRING (CHAR) Function

string-trim trims consecutive CHARs from both left and right ends of STRING and returns it. The default value of CHAR is a blank space.

string-left-trim STRING (CHAR) Function

string-trim trims consecutive CHARs from left end of STRING and returns it. The default value of CHAR is a blank space.

string-right-trim STRING (CHAR) Function

string-trim trims consecutive CHARs from right end of STRING and returns it. The default value of CHAR is a blank space.

string-match PATTERN STRING Function

string-match matches STRING against PATTERN and returns t or nil according to the result. pattern  is a (limited) regular-expression, with special characters " ? " and " * ". " ? " matches any single character, and " * " matches any sequence of characters (possibly empty). There is no way to escape these special characters.

Example: s

        (string-match "?b?" "abc")  =>  t
        (string-match "*b*" "b")  =>  t

Manipulation of Characters in Strings
=====================================

Characters  of  strings  are  independently manipulated by following  functions.   Note  that  the  subscript  origin  of strings is zero.

getchar STRING INDEX Function

getchar returns the INDEX-th character of STRING as an interned one-character symbol.

Example:

                (getchar "abc" 2)  =>  c

sref STRING INDEX Function

sref  returns  the  INDEX-th  character of STRING as a character, i.e., a  fixnum .

sset STRING INDEX CHARACTER Function

sset   sets   the  INDEX-th  character  of  STRING  to CHARACTER, and returns CHARACTER.

Converting Strings and Numbers
==============================

Consecutive  characters  of  a  string  may be considered as a binary   representation   of  an  integer  number.   Following functions are for conversions between such character sequences and  fixnums .

cutout STRING POS LENGTH Function

cutout  converts  a  character  sequence beginning at the POS-th character of STRING with length LENGTH into a fixnum .  LENGTH should be positive. Upper bytes of the result will be padded with zero.

spread VALUE LENGTH Function

spread converts a fixnum VALUE into a string which contains the binary representation of VALUE.  The resulting string has the length LENGTH, which should be positive.  If VALUE cannot be represented in LENGTH bytes, only lower bytes are converted and overflowed upper bytes are ignored.

Bit String Manipulation
=======================

A  string  may also be regarded as a sequence of binary digits (bits).   Thus,  an array of logical values may be represented by  a  string,  in  which  case,  one character holds eight distinct  logical  values.   Using  this  representation,  the memory  space  required  for  a  large-scale bit table will be eight  times  smaller  than when each character of a string is used  to represent one logical value, or thirty-two times than when  each  vector  element  is  used.   To  facilitate such a representation of bit tables , following functions are provided by  UtiLisp32.   Compact  representation of bit tables using following   functions  may  save  considerable  memory  space, however,  computing  speed will be somewhat slowed down.  Note that functions such as string-amend-and, -or and -xor may also be useful for logical operation on bit tables.

bref STRING INDEX Function

bref returns t if INDEX-th bit of STRING is set; otherwise,  it returns nil.  INDEX should be non negative and smaller than eight times the length of STRING.

Note: Bits are indexed from left to right, the most significant bit of the 0th character of  string  being 0.

bset STRING INDEX VALUE Function

If VALUE is non nil, the INDEX-th bit of STRING is set;  otherwise,  it  is  reset.   INDEX  should  be non negative  and  smaller  than  eight  times  the length of STRING.  bset returns VALUE as its value.

Vectors
*******

A  vector is a Lisp object that consists of a number (possibly zero) of elements, each of which  is  a  Lisp  object again.  The individual elements are selected  by  numerical subscripts origined zero. An error is generated  if an subscript value specified is not appropriate, i.e., if it is negative or not less than the number of the elements.

As  elements  of a  vector  are accessed in constant time, it is  advantageous  compared  with  list structure consisting of binary   cons   cells  when  a  large  amount of data is to be manipulated.   Disadvantage  of  using   vectors , compared with lists , is that the size should be known before used.

Vectors  are arbitrarily allocated and discarded like  cons cells; they are independent objects on their own right, rather than  being  attributes  of  symbols  as  in  some  other Lisp systems.   However, it is usually convenient to lambda-bind or assign a  vector  to a  symbol , to use the  symbol  as its name, since  vectors  are not directly  identified  by  the Lisp reader.

Multi-dimensional  arrays  are  represented  by  vectors  of vectors ;  vectors  the elements of which are  vectors  again.

Vector Manipulation
===================

vector SIZE (FILLER) Function

vector allocates and returns a  vector  with its size being SIZE;  its  subscript  ranges from 0 to SIZE - 1. If  the  optional  argument FILLER is not given, all the  elements  of  the  allocated  vector  are initiated to nil. Otherwise, if FILLER is given, the allocated vector  will  be initiated using FILLER in the same way as the function fill-vector (see the description of fill-vector below).

vector-length VECTOR Function

vector-length returns the number of elements of VECTOR.

vref VECTOR SUBSCRIPT Function

vref returns the SUBSCRIPT-th element of VECTOR.

vset VECTOR SUBSCRIPT VALUE Function

VSET  sets VALUE into  the  SUBSCRIPT-th  element of VECTOR.  vset returns VALUE as its value.

fill-vector VECTOR FILLER Function

fill-vector  fills  VECTOR  with  specified  data  and returns (modified) VECTOR.

When  FILLER  is  an   atom  and  not  a  vector , all the elements of VECTOR become FILLER.

When  FILLER is a  list  with  one  or more elements, VECTOR  is  filled with the elements of that  list .  The subscript  0 element of VECTOR is assigned the  car  of the  list , subscript 1, the sl cadr, and so on.  If the list is shorter than VECTOR, remaining elements of VECTOR are not affected. If the list is longer, remaining elements of the list are merely ignored.

When FILLER is a  vector , VECTOR  is  filled with
corresponding  elements  of  the  filler  vector .  If the
filler   vector  is shorter, remaining elements of VECTOR
are  not  affected.   If  the  filler  vector   is longer,
remaining  elements  of  the  filler  vector   are  merely
ignored.

Example: s   When the value of v is a  vector  with, for example, 10 elements,

       (fill-vector v nil)

fills the vector with nil's.

       (fill-vector v '(0 1 2 3 4))

sets  first 5 elements of the  vector  with 0, 1, 2, 3, and 4,  respectively.  Remaining 5 elements are not affected. If the value of w is another  vector  with the same size,

       (fill-vector v w)

copies the contents of w into v.

References
==========

It is often required to pass a  vector  and its subscript as a pair to functions. It would be more convenient if the pair could  be  treated  just  as  a  variable.  UtiLisp32 provides reference  objects for this purpose.

A   reference is  a  pointer to an element of a  vector .  The pointed  element  is  accessed  by deref and updated by setref. deref and  setref are also applied to variables, i.e., symbols.  It is recommended that deref and setref should be   used   in  functions  which  utilize   call-by-reference

parameter, instead of eval and set.

reference VECTOR SUBSCRIPT Function

reference makes and returns a  reference  pointing to the SUBSCRIPT-th element of VECTOR.

deref REFERENCE Function

deref  returns  the  value  of  REFERENCE;  if  it is a symbol,  the value of the symbol; if it is a  reference , the element of a  vector  it is pointing.

setref REFERENCE VALUE Function

setref sets VALUE  to REFERENCE; if it is a symbol, its  value  is  set;  if  it  is a reference pointer, the pointed  element  of  a   vector   is  set.  setref returns VALUE as its value.

referred-vector REFERENCE Function

referred-vector returns the  vector  an element of which is pointed by REFERENCE.

Note:    Computation   of  this  function  requires  time proportional  to  the subscript of the element pointed by REFERENCE.

referred-index REFERENCE Function

referred-index  returns  the  subscript of the  vector element pointed by REFERENCE.

Note:    Computation   of  this  function  requires  time proportional  to  the subscript of the element pointed by REFERENCE.

See  also  mapvector  and mapv (Section 4.4, "Mapping") which perform certain computation on all the elements of a  vector .

Macros
******

Evaluation of Macros
====================

When a  cons  cell with its  car  being a  symbol  is evaluated, the  evaluator inspects the definition of that  symbol .  If the definition  is  a   cons   cell,  and  its  car  is the  symbol macro, then that definition is called a  macro

.  The  cdr  of the  definition is treated as a function that has one argument.  The evaluator  applies  that function to the  cdr  of the original form.   The  result  of this application is evaluated again by the evaluator, and the value returned by this re-evaluation is finally  returned  as  the  result  of  the  evaluation of the original form.

Example: Suppose the definition of ncons is

       (macro lambda (x) (list 'cons (car x) nil))

This is a macro; it is a  cons  the  car  of which is the symbol  macro. The evaluation process of a form (ncons 'foo) is as follows:

The evaluator recognizes that the form to be evaluated is a   cons   cell  the   car   of  which is a  symbol , i.e., ncons; the definition of the  symbol  ncons is examined and the   car   of  the  definition is found to be the  symbol macro.   Then  the  evaluator  takes  the   cdr   of  the definition,  which is a lambda-expression, and applies it to the  cdr  of the original form, i.e., the list ('foo). x  is  bound  to ('foo) and the result of the application will be (cons 'foo nil).

The  evaluator  then  evaluates this new form in place of
the  original one. (cons 'foo nil) is evaluated to \sexpr(foo)
and so the result of (ncons 'foo) is, finally, \sexpr(foo).

Macros  may  be expanded recursively; expanded form of a macro
form  can  be  another macro form, in which case, the expanded
form is expanded again, until it becomes a non-macro form.

Macros  are used for a variety of purposes.  For example,
custom-made   control structures are easily implemented with
macros.

Example:
while-do construct such as

        (while-do CONDITION . BODY)

is defined as a macro using macro special form as

        (macro while-do (x)
           (nconc (list 'loop
                        (list 'and (car x) '(exit)))
                  (cdr x)))

which expands the original form into

        (loop (and CONDITION (exit)) . BODY)

Using  macros  may  result  in  a  considerable time and space overhead   while   the  program  is  executed  interpretively. However,  once compiled, programs using macros are executed as  efficiently  as  those  without macros, since the compiler expands macro  calls  prior  to the compilation.  Thus, using macros is considered   to   pay  no  penalty  on  run-time performance. Efficient execution may only be realized through compilation anyway.

As  macros are expanded in compilation time, macros should not refer  to  global variables.  The expansion should be the same in  any  context (on the assumption that, of course, car still means car, cdr means cdr, etc).

Macros cannot be applied to arguments in the same way as usual functions. Macros takes  arguments  which are not evaluated yet,  while  application  is  calling  a function with already evaluated  arguments.   Thus,  calling  funcall or apply with macros as the first argument will generate an error.

macro-expand . FORM Macro

macro-expand only expands a macro in FORM and returns it without second evaluation.

Example:

       (macro-expand incr x 3) => (setq x (plus x 3))

Defmacro Facility
=================

Complicated  macros  must have access to structural details of their  argument lists.  Such an access requires densely nested car  and  cdr  functions,  which  may  not  only  increase the difficulty  of programming but also damages the readability of the  resulting  program. defmacro facility is provided to facilitate  access  to portions of the argument list by giving names to portions of the argument list.

defmacro NAME ARG-PATTERN . BODY Macro

A defmacro form of the syntax

       (defmacro NAME ARG-PATTERN . BODY)

is expanded into

       (macro NAME (@) . EXPANDED-BODY)

where ARG-PATTERN  may  be  an arbitrarily complicated tree  structure of  symbols , which serves as a template of the argument list.  Its  car  represents the  car  of the argument   list,  its   cdr ,  the   cdr   of  the  list. EXPANDED-BODY  is almost the same as BODY except that all  the  accesses  to  the   symbols  in ARG-PATTERN are converted  to  accesses  to corresponding portions of the argument list.

Example:    The while-do in the former example may be more elegantly defined using defmacro as follows:

        (defmacro while-do (CONDITION . BODY)
           (nconc (list 'loop
                      (list 'and CONDITION '(exit)))
                  BODY))

Backquote Facility
==================

It  is  still  not  easy to define a macro even with defmacro. The  difficulty lies in the fact that two different forms must be  considered  at  a  time:   The expanded form which will be finally evaluated is one; the form which produces that form is the  other, and this form is what the programmer have to write down.   The  backquote  facility is provided to facilitate the construction of the latter.

The backquote character ( ` ) is defined as a read macro (see Chapter ~see InandOut, "Input and Output" for detail), which acts similarly to normal single quote  (')  that  makes  a QUOTEd  form  of  the S-expression following  it.  However, when a form included in the following S-expression  is  preceded  by  a  comma ( , ), that form is not quoted while all the other portions are effectively quoted.

Example: s `x is read in as (quote x) which is the same as 'x.

\sexpr`(a ,b c) is read in as (list 'a b 'c). As b is not quoted, it is evaluated when the whole form is evaluated.

while-do macro may be still more elegantly defined as

        (defmacro while-do (CONDITION . BODY)
            `(loop (and ,CONDITION (exit))
                   . ,BODY))

Backquotes  may  be nested.  When backquotes are nested twice, double  comma  will  make  a form to be evaluated in the first evaluation  of  the  whole  form;  a form preceded by a single comma will be evaluated in its second evaluation.

Input and Output
****************

Streams
=======

Streams are  Lisp  objects  through  which I/O operations are performed.  Streams may be connected to an external file or to the  user terminal.  File streams are created by the function stream.   They  should  be  opened  by the functions inopen or outopen before being used.

Any  number of streams may be connected to a single external file.   It  is  also  possible  to  open  two  or more streams connected  to  one  file  in  output  mode.   However,  it  is difficult  to  predict the result of output operations in such cases, since the files are modified through file buffers.

stream FILENAME Function

stream  makes a stream which is connected to the external file  defined  by  FILENAME. Unixのすでにopenされているファイルディスクリプタをストリームにする時は FILENAMEとしてファイルディスクリプタをfixnumで渡す.

string-stream STRING Function

文字列をストリームとして扱う.

inopen STREAM Function

inopen  opens  STREAM as an input stream.  When opening is  unsuccessful,  an  error  is generated; otherwise, it returns  STREAM.

outopen STREAM Function

outopen  opens STREAM as an output file. When opening is unsuccessful, an error is generated; otherwise, outopen returns STREAM.

appendopen STREAM Function

appendopen opens STREAM as an open file and makes it append mode. When opening is unsuccessful, an error is generated; otherwise, appendopen returns STREAM.

close STREAM Function

close  closes the  file  associated with STREAM.  When closing   is   unsuccessful,   an   error  is  generated; otherwise, it returns STREAM.

openfiles Variable

The value of openfiles is a  list  of  streams  which are currently  open.   The  most recently opened  stream  comes first  in the  list .  The  list  is automatically maintained by inopen, outopen, appendopen and close; the user may not update the value of openfiles explicitly.

Example:   All the files currently open are closed by

        (mapc openfiles (function close))

stream-mode STREAM Function

stream-mode returns the current state of STREAM; if it is  open  as an input file, it returns the symbol inopen; if  it  is  open as an output file, it returns the symbol outopen; if it is not open, it returns nil.

linelength (STREAM) Function

linelength  returns  the  maximum  line  length allowed,  for  output  streams.   The  default  value for STREAM is the value of standard-output.

cursor (STREAM) Function

cursor returns current column position of STREAM for output streams, where column zero being the first column.  The default value of STREAM is the value of standard-output.

colleft (STREAM) Function

When  STREAM is an  output  streams,  it returns how many more characters can be printed on the current line.  The default value of STREAM is the value of standard-output.

Note: (cursor) + (colleft) is always equal to (linelength) for outputstreams.

charleft (STREAM) Function

一行の長さが可変長の場合のcolleft.

string-stream-index (STRING-STREAM) Function

文字列ストリームの先頭から何バイト目までを読み書きしたかをfixnumで返す.

string-stream-limit (STRING-STREAM) Function

文字列ストリームの何バイト目まで読み書きすることができるかをfixnumで返す.

standard-input Variable

standard-output Variable

Values  of  these  variables  are  streams  for which I/O operations   are  normally  performed;  values  of  these variables  are  used  as  the  default  values  of stream arguments in various I/O functions.  Reading and printing are elegantly directed to a desired stream by lambda-binding these variables to the stream.  Using this style, these  variables  will recover their old values when they are unbound. The  initial values of standard-input and standard-output are the same    as   those   of   terminal-input  and   terminal-output, respectively,  which  are  the streams connected with the user terminal (see below).

Example:

        (let ((standard-input SOME-STREAM)) (read))

is effectively the same as

        (read SOME-STREAM)

terminal-input Variable

terminal-output Variable

Values  of  these  variables  are  the  streams which are connected to the user terminal.

Example:   While the standard output stream is directed to some  file  stream,  messages  to  the  terminal  can  be explicitly  directed  to the terminal as in the following example

        (let ((standard-output SOME-STREAM))
           (cond ((null l)
                 (print "l is null" terminal-output))
                 (t (mapc l 'print))))

prompt Variable

Value  of prompt is a string which is used for prompting

input from the terminal.  Initial value of prompt is  "> " . It  is  recommended  that  subsystems  of the Lisp system should bind prompt to certain string which identifies the subsystem  to notify the terminal user what the prompting system is, or, what kind of input is expected.

Example:

        (setq name
              (let ((prompt "Who are you?  "))
                   (read)))

Allocating Files
================

alloc FILENAME Function

alloc returns FILENAME itself. This function is only for compatibility with UtiLisp on mainframes.

Printed Representation
======================

Lisp  objects are not directly handled since they are stored inside  the  machine  memory.   In order to examine these Lisp objects,  UtiLisp32 provides a representation of its objects in  the  form  of  printed  text;  this  is called the printed representation .

Functions  such  as print, prin1, and princ take a Lisp object as  their  argument,  and  send  the characters of its printed representation  to  a stream; these functions are known as the printer .

The  function read takes characters from a stream, interprets them  as a printed representation of a Lisp object, constructs a corresponding object, and returns it; this function is known as the reader .

This  section describes printed representation of various Lisp objects.

The Printer
-----------

Printing is done either with or without slashification.  The non slashified   representation  looks simple and readable to human  eyes, but they may not be properly read in again by the machine.  The  slashified  version is faithfully converted back  into  Lisp  objects  by  read,  except for some peculiar objects, namely,  streams ,  vectors ,  references , and code pieces .

The printed representation of an object depends on its type.

For  an   integer :   If  the   integer  is negative, the printed
representation  is  preceded  by  a  minus sign (-); if non negative,
no sign is  printed.   Then  comes  the  decimal
representation  of the absolute  value  of  the   integer .
Slashification does not affect the printing of  integers .

For  a   flonum :  The printed representation is preceded by a sign ( +  or -), then a digit zero ( 0 ),a decimal point

( . ),  and  the  fraction part which is a sequence of decimal digits.  Number of digits in the fraction part is specified by the value of the symbol digits.  Then comes the exponent part indicator (^), sign of the exponent part ( +  or -),  and the value of the exponent part in two decimal digits.   Thus,  the  number  of  characters  of  the  printed representation  of  a   flonum   is,  in  total,  digits + 7. Slashification does not affect the printing of  flonums .

For a  symbol :   If   slashification   is  off,  the  printed representation  is  simply  the  successive  characters of the print name   string   of the  symbol . If  slashification   is  on, some special characters are preceded by  the  escape character  / .  The decision whether escape is required  is  made  using  the  current  readtable,  i.e., the current  value  of the  symbol  readtable.  Objects printed with slashification  on are always  read  back faithfully, provided that the same readtable is used as when it is printed out.

For a  string :   If   slashification   is  off,  the  printed representation  is  simply  the  successive  characters of the string . If  slashification   is  on,  the string is printed between double quotes ( " ), and double quotes inside the  string are duplicated.

For  cons  cells:  The printed representation for  cons  cells tends  to favor to lists, rather than dotted pairs.  It starts with  an  open  parenthesis.  Then, the  car  of the  cons  is printed,  and  the   cdr  of the  cons  is examined.  If it is nil,  a close parenthesis is printed.  If it is anything but a cons ,  then  a  space,  a  dot,  a space, and that object is printed followed by a close parenthesis.  If it is a  cons , a space  is  printed and the printing starts again all over from the  point  after  the open parenthesis is printed, using this new    cons  followed by a close parenthesis.   This  procedure  produces  the  usual  printed representation such as those seen in this manual.

For a  code piece :  The printed representation has the syntax C# NAME, where NAME is the name of the  code piece , normally the   name  of  the  function  to  which  the  code piece  is associated.  Code pieces  are not read back in properly.

For a  stream :  The printed representation has the syntax S# NAME, where NAME is the name of the external file which the  stream  is connected to. When the  stream  is connected to terminal, the NAME is  "terminal-input"  or  "terminal-output" . Streams  are not read back in properly.

For  other objects:  The printed representation has the syntax TYPE # ADDRESS, where TYPE is a character indicating the type  of  the object ( "V"  for  vectors ,  "R"  for  references ), and ADDRESS is the decimal representation of the  current address of the object.  The address is merely for convenience  in discriminating two objects; the objects may be relocated  by the garbage collector.   Vectors  and  references are not read back in properly.

digits Variable

The  value  of digits, which must be a positive  fixnum , specifies  how  many  digits  are  to  be  printed in the fraction part of the printed representation of  flonums . The  initial  value of digits is 7, and, thus, the length of the printed   representation  of  a   flonum   is, initially, 14.

atomlength X Function

atomlength returns   the   length   of   the   printed
representation  of  an atom X.  The printing is assumed
to  be   slashified .  If X is not an atom, an error is generated.

The  following  additional feature is provided for the printed representation  of   cons   cells; as a list is printed, print maintains  the  length  of  the  list  so far, and the depth of recursion  of printing  lists .  If the length exceeds the value of  the variable printlength, print will terminate the printed representation of the list with  ???  and a close parenthesis. If  the  depth  of recursion exceeds the value of the variable printlevel,  the  list will be printed as  ? .  These features allow  abbreviated printing  which  is concise and suppresses detail.

printlevel Variable

printlength Variable

Values  of  these  variables are used as described above. Their   initial   values   are  4  and  10  respectively. Infinitely  deep  or  long  printed representation may be obtained by setting zero to these variables.

The Reader
----------

The  purpose  of the reader is to accept characters, interpret them  as  the  printed  representation  of  a Lisp object, and return  the corresponding Lisp object.  The reader does not accept all  the  printed representations; the printed representations of  vectors,  references,  streams,  and code pieces are not read  in  again.   However, the reader has many features which are not seen in the printer.

The reader  accepts  slashified  printed  representation  of numbers,  symbols ,  strings , and  conses .   Some  special characters  may  be defined as single character object, which are  read  in  as  a  one  character  symbol  of that character. Macro  characters may  be defined, reading which will cause a call  to  a  function  associated  with  that  character.  See following sections about the  readtable  and read macros.

Symbols  with the same  print name  are read as the same object. This  is realized by keeping all the useful symbols in a table called  the  obvector.   This  table  is organized as a hash table   the   keys  used  are   print name  of  symbols . The registration process to the  obvector  is called interning.

obvector Variable

The  value  of obvector is  the  current  obvector.  An interned   symbol  SY  is  a top-level element of the list which is the element of the obvector, the index of which is given by

        ( (hash (pname SY))
           (vector-length obvector))

default-obvector Variable

Value of default-obvector is  the  initial  value  of obvector.   All  the  predefined  symbols  are  initially registered in this table.

oblist (OBVECTOR) Function

oblist  returns   a   list   of  symbols  registered  in
OBVECTOR.   The  default  value  of  OBVECTOR  is the
current  value of the symbol obvector.  The list is newly
created each time when this function is called.

intern Variable

The  value  of intern is the  interning  function used by the  reader,  which  must  be a function of one argument. When a character sequence which is to be interpreted as a symbol   is  encountered,  the  Lisp  reader  calls  this function  with one argument, the string consisting of the characters  of  that sequence.  The result of reading the symbol will be the result of this function.

The  initial  value of intern is the function intern (see below).  Any user-defined name table management principle may  be established  by binding intern to a user-defined interning  function.

intern STRING (OBVECTOR) Function

intern searches OBVECTOR for a  symbol  which has the  print name  string-equal to  STRING.  If it is found, intern returns that symbol ;  if  not,  a new symbol with its  print name  being STRING   is  created,  registered  in  OBVECTOR,  and returned  as  the value of intern.  The default value for OBVECTOR is the current value of the symbol obvector.

intern-soft STRING (OBVECTOR) Function

intern-soft works  almost the same as intern except that it  does not create a new  symbol .  OBVECTOR is searched for a  symbol  with the  print name  string-equal to STRING.   If  it  is  found, a list beginning with that symbol  is returned; if  not  found, nil is returned.

remob SYMBOL (OBVECTOR) Function

remob searches  OBVECTOR  for  a  symbol  which is eq to SYMBOL.   If found, it is removed from the table making it  hidden from the Lisp reader; if not, nothing is done. It  returns  nil  as  its  value.   The  default value of OBVECTOR is the current value of the symbol obvector.

The Readtable
-------------

The  reader  is controlled by a vector called the readtable. A  readtable  is a vector consisting of 256  fixnum  elements, the  index N element of which corresponds to the character of ASCII code N, and indicates the nature of the character.

Currently, only lower 16 bits of each element are used.  Their meanings  and  the initial values in the default readtable are as follows:

0x0000001
     (LSB) means that this character is an ordinary alphabetic character.  All the usual characters have this bit on and others off.

0x0000002
     means  that  this  character  is  an  extended alphabetic character.  This bit is currently not used.

0x0000004
     means   that   this  character  is  a  digit. Characters "0" through "9" has this bit on.

0x0000008
     means  that this character is a sign. "+" and "-" has this bit on.

0x0000010
     is   alternate meaning  bit.  This bit is used in several ways.  For example, "-" has this bit on, while it is off for "+".

0x0000020
     means  the escape character.  " / " has this bit on.

0x0000040
     means that this character should be slashified in a  symbol .  Characters with special meaning have this bit on.

0x0000080
     means that this character should be slashified when   appeared   at  the top  of  a  symbol .   Special characters, signs, and digits have this bit on.

0x0000100
     means string quote character.  Double quote has this bit on.

0x0000200
     means macro character.  The macro definition (a function  with  no  argument)  is  in  the  corresponding position of the macrotable.

0x0000400
     means right parenthesis, " ) ".

0x0000800
     means dotted pair dot, ".".

0x0001000
     means left parenthesis, " ( ".

0x0002000
     means  blank  and  alike,  which  is  normally skipped between lexical elements.

0x0004000
     means a single character object.

0x0008000
     means  that this character terminates a symbol or  a  number.   All the special characters have this bit on.

The  macrotable  is  used  to  hold  the definition of macro characters.   The  definition  should  be  a  function  of  no argument,  the  result of which is returned as the object read in.

readtable Variable

macrotable Variable

Values  of readtable and macrotable are  the  current readtable and the macrotable, respectively.  The initial value  of  these  variables  are  the  same  as  those of default-readtable  and default-macrotable, respectively  (see below).  User defined readtable or macrotable may be used by binding these variable to certain values.

default-readtable Variable

default-macrotable Variable

Value  of  these variables are the standard readtable and the standard  macrotable of the system.

Setting Readtable
-----------------

Characters may be defined as a macro character by the function readmacro. When the  reader encounters a macro character in the  input  text, a function associated with that character is called.   The result of the function is returned as the return value of read.

readmacro CHAR FN (READTABLE) (MACROTABLE) Function

CHAR  is  defined  as a macro character associated with
FN.    This  definition  is  done  in  READTABLE  and
MACROTABLE  given  as  arguments.   If they are absent,
current values of readtable and macrotable are assumed.

Example: s   The  macro  character  "'"  could  have  been defined by

        (readmacro (character "'")
          (function (lambda nil (list (quote quote) (read)))))

Note  that  this  works  not only for (read) but also for (read  SOME-STREAM);   the  latter  binds  the  variable standard-input to  SOME-STREAM,  making  (read) in the definition of the read macro input from that stream.

If  the  backquote  character " ` " never be typed in from certain terminal, an alternative character, say, " % ", may be settled for backquote macro by

        (readmacro "%" (vref macrotable 96))

96 is the ASCII code for " ` ".

Predefined read macros are quote "'", backquote " ` ", and comma " , ".  See Chapter 10, "Macros", for backquote and comma.

Characters  may  be defined as single character objects.  When the  reader  encounters  one  of  them  (except  when  reading characters  in  a  string),  then  it is read as an  interned single  character  symbol , regardless of preceding or following characters.   Single  character  objects may be defined by the function single-character.

single-character CHAR (READTABLE) Function

CHAR  is  defined  as  a  single  character  object  in READTABLE.   If  READTABLE  is  not supplied, current value of readtable is assumed.

Example:

        (single-character "&")

From then on,

        a&nil&b

will be read as 5 symbols, a, &, nil, &,and b.

Input Functions
===============

Functions   described   in  this  section  bind  the  variable
standard-input to  the  argument STREAM, before reading any
character  in.   Thus,  input is always performed on standard-input
stream.   The  default value of STREAM is the current
value of standard-input.

read (STREAM) Function

read reads in one printed representation of a Lisp object from STREAM, and returns it as its value.

readline (STREAM) Function

readline reads the current line, from current position to the  line  end,  and  return  a  string consisting of the characters  read  in.   The next character input from the stream will be the first character on the next line.

skipline (STREAM) Function

skipline  works  the  same  as  readline except  that it returns nil, instead of a string.

current-line (STREAM) Function

current-line returns  the  current line of STREAM as a string   object.    Returned   string  includes  all  the characters  in  the current input line, regardless of the current  character  position.   The character position is not affected. Notice that this function only reads the current buffer contents of STREAM and never updates the STREAM. The line which is spread over two buffers is not read by current-line.

tyi (STREAM) Function

tyi  inputs  one  character from STREAM and returns its code as a  fixnum .

tyipeek (STREAM) Function

tyipeek  returns  the  next  character  of STREAM.  The difference  with tyi is that tyipeek does not advance the current    character   position   of   STREAM.    Thus, consecutive calls of tyipeek will result the same.

readch (STREAM) Function

readch is  the  same  as  tyi,  except  that, instead of returning  a  character  as  a   fixnum ,  it  returns an interned   symbol the  print-name  of  which  is a one- character string of the character read in.

Output Functions
================

The  functions  in  this  section  first  bind  the  variable standard-output to  the  argument STREAM, before any actual output.   Thus,  output operations are always performed on the standard-output stream.  The default value for STREAM is the current value of the symbol standard-output.

prin1 X (STREAM) Function

prin1  outputs  the  printed  representation  of  X  to STREAM,  with   slashification .  The value of prin1 is X.

print X (STREAM) Function

print works  the  same  as  prin1,  except  that print terminates the current line after printing out.

princ X (STREAM) Function

princ  is  the  same as prin1 except that the printing is done without  slashification .

tyo CHAR (STREAM) Function

tyo  outputs the character whose ASCII code is specified by CHAR to STREAM. tyo returns CHAR as its value.

terpri (STREAM) Function

terpri  terminates  the current line of STREAM.  terpri returns nil as its value.

flush (STREAM) Function

flush flushes out the contents of buffer of STREAM and returns nil. In general, output of newline character flushes out stream .

tab N (STREAM) Function

tab will  set  the character position of STREAM at the column  N.   If  the current character position is less than  N, spaces are printed out until the column N is reached;  if the current position exceeds the column N, the  line is terminated and N spaces are put out on the next line. tab returns nil as its value.

Formatted Printing
==================

It  is often required to print  Lisp objects in the midst of a  certain  message.   For  example, given a symbol SY and a number NUM, one might require such an output as

          "The symbol SY appeared NUM times."

with SY and NUM varying time to time.  Of course, this can be achieved by

          (progn (princ "The symbol ")
                 (prin1 SY)
                 (princ " appeared ")
                 (prin1 NUM)
                 (princ " times.")
                 (terpri))

but this looks ugly and not readable.

This  kind  of  output  is  required  so often that the system provides formatted printing facility .

format PATTERN . ARGS Macro

format  is  a  macro  for  formatted printing.  The first argument  PATTERN  is  a  string  specifying the output format  and the rest of the arguments ARGS is a list of forms   which   are   evaluated  and  used  according  to PATTERN.

The  string  PATTERN  is normally printed out as it is. However,  when  a  slant  character  ( / )  is encountered, printing   is   controlled  by  the  directive  character immediately  following  it.   If  the directive character requires   arguments,   values   of   ARGS   are   used sequentially  from  left  to  right.   Control  directive characters currently available and their meanings are as follows:

s
     prints one Lisp object with  slashification .

c
     prints one Lisp object without  slashification .

b
     prints  one character the code of which is supplied as an argument.

g
     pretty-prints one Lisp object.

t
     tabulates to the column specified by the argument.

n
     terminates the current line.

/
     prints " / ".

Case of directive characters is ignored.

Example:   The former example is printed by

       (format "The symbol /s appeared /s times./n" SY NUM)

Indented Printing
=================

Printed   representations  of Lisp object  are  not  easily
examined  by  human  eyes,  especially  when  parentheses  are
densely  nested.   The  indented  printer

prind will help you producing   more   readable   outputs  by  giving  appropriate indentation.

prind X (WIDTH) (ASBLOCK) (LEVEL) (LENGTH) Function

X  is  printed  with certain indentation.  WIDTH is the maximum width for printing, the default value of which is the line length of the current output stream.  When  ASBLOCK  is  non nil,  then the print out will be more  compact than when it is nil (the readability may be somewhat  damaged).   The  default  value of ASBLOCK is nil. When  LEVEL  and  LENGTH arguments are supplied, they should be  non negative   fixnums , and when they are non zero, the maximum level and length of printing lists will be LEVEL and LENGTH, respectively.  quote forms such as (quote  a) are  printed as 'a .  Moreover,  when  the  value of the variable usebq is non nil, backquotes and commas are used for printing cons and
list forms; (list a 'b c) is printed as \sexpr`(,a b ,c),
(cons 'a b) as \sexpr`(a .  ,b)

prind returns  nil  as  its  value,  unlike print which
returns its first argument.

usebq Variable

When the value of usebq is non nil, backquotes and commas
are used in the print out of prind.  The initial value of
usebq is nil.

pp FUNCNAME Macro

The  definition  of  the  symbol FUNCNAME is printed so
that  the definition will be recovered when the print out
is read in and evaluated.  Usual functions are printed as

        (defun FUNCNAME LAMBDA-LIST . BODY)

Macros defined using defmacro are printed as

        (defmacro FUNCNAME LAMBDA-PATTERN . BODY)

Other macros are printed as

        (macro FUNCNAME LAMBDA-LIST . BODY)

Code Pieces
***********

A  Code piece is a Lisp object which contains machine language instructions and some Lisp objects which are accessed from the code.  Though  code pieces  may itself be used as functions, it is  usually more convenient to use their names, i.e., symbols, as functions.   Code pieces  are either predefined by UtiLisp32 or obtained by compiling lambda forms.

A  code piece  has its name, which is normally a function  symbol associated with that  code piece .

funcname CODE Function

funcname returns the name of CODE.

Number  of  arguments  for a  code piece  may be restricted to reside  in some range.  The minimum and the maximum numbers of arguments  are  stored somehow in the code pieces for run time checking, and may be examined by the following functions.

minarg CODE Function

maxarg CODE Function

minarg and maxarg return  the  minimum and the maximum number of arguments for CODE, respectively.  The values returned  by  these  functions may not always be precise. However, it is guaranteed that an error is generated when CODE  is  applied  to less arguments than the result of minarg  or  more  than  the  result of maxarg. If CODE allows arbitrarily many arguments, maxarg returns -1.

A  code piece  may be constructed by the following function.

load-code X Function

load-code constructs and returns a  code piece  specified by the argument X, which has the syntax

        (NAME MAXARG MACHINE-CODE QUOTED)

where NAME is the name of the function, MAXARG is the maximum  number  of  arguments of the function, MACHINE-CODE is a list of  fixnums  each of which represents one half word  (16 bits in Suns, 8 bits on Vaxen)  of the machine code, and, finally, QUOTED  is  a  list  of  Lisp objects accessed from the machine code. この関数はUtiLisp/Cではサポートされていない.

program-load C-LIBRARY . FUNCS Macro

Cのライブラリに含まれるCの関数をLispの関数として利用する. FUNCSは (Lispの関数名 Cの関数名 引数の型のリスト nil 返り値の型) の形式をしたリストである. 型としては, fix, float, stringが指定できる.

     (program-load '("-lm") '(arctan2 "atan2" (float float)  nil float))

code-load COMPILED . C-LIBRARY Macro

複数のオブジェクトファイルをロードする. COMPILEDにはコンパイラの生成したオブジェクトファイルを, C-LIBRARYにはそれ以外のCのライブラリなどを指定する. COMPILEDにファイル名のリストを渡すこともできる.

SystemVでインクリメンタルローダがない場合は使うことができない. その場合はコンパイルされたコードを実行するには, 次のmake-a.outを使う必要がある.

make-a.out A.OUT COMPILED C-LIBRARY Macro

コンパイルされたコードを含んだUtiLisp/Cの実行ファイルを作る. コンパイルされたコードは, lispsys.lを実行しないので, compiledの中にはlispsys.o を含んでいる必要がある.

dumpfile FILENAME Function

現在のロードされたコード, ヒープ内の情報をファイルに書き出す. このファイルを次の起動時に-dオプションで指定すると, 同じ状態から再起動される.

Compilation
***********

The  Lisp  compiler is a program which translates interpretive

functions,  which  have  the form of lists, into machine codes which  are  directly  executed  by the hardware.  The merit of compilation is  that the execution speed will be considerably improved.

Compiling Functions
===================

compile . FUNCTION-NAMES Macro

The  compiler is evoked by simply applying the macro compile as

       (compile . FUNCTION-NAMES)

where  FUNCTION-NAMES is  a list of symbolic atoms the definitions of which are lambda expressions.  The definition of these   symbols  will  be  replaced  by the compiled code . compile returns the list FUNCTION-NAMES as its value.

Example:  Interpretive functions f and g are compiled by:

       (compile f g)

revert . FUNCTION-NAMES Macro

The  interpretive  definition  of  a  function  which  is compiled  using  compile is saved in the property list of the  function symbol as its previous-definition property. revert  sets  the definition of the symbols in FUNCTION-NAMES to  their previous-definition properties.  revert returns FUNCTION-NAMES as its value.

The  calling  interface of compiled and interpretive functions are  totally  compatible.   Thus, a compiled function may call interpretive functions and vice versa.

Macro  calls  in the definition of the function being compiled are  expanded  before the compilation.  Thus, such macros must be defined before the compilation.

Usually,  the compiler generates various run time check codes. When   the   program  has  been  completed  and  there  is  no possibility  of  errors, these check codes may be superfluous. The  following  variables  are  used  to give direction to the compiler whether such check codes are required or not.

typecheck Variable

When  the  value  of  typecheck  is non nil, the compiler generates  type  check codes; otherwise, no run time type check  code is generated.  The initial value of typecheck is t.

ubvcheck Variable

When  the  value  of  ubvcheck  is  non nil, the compiler generates  check  codes for unbound variables; otherwise, unbound  variables  are  not  checked in the object code. The initial value of ubvcheck is t.

indexcheck Variable

When  the  value  of  indexcheck is non nil, the compiler generates  check  codes  for array or string index range ; otherwise,  no  run time  check  code  for index range is generated.  The initial value of indexcheck is t.

udfcheck Variable

When the value of udfcheck is non nil, the compiler generates check codes for undefined function; otherwise, no run time check code for index range is generated. The initial value of udfcheck is t.

Declaration
===========

Various  declarations may  be required for exact compilation. The macro declare and defconst and the function reset-compilation-flags are provided for such declarations.

declare ITEM-LIST INDICATOR Macro

declare  is  used  to declare that the elements of ITEM-LIST have  the  attribute  indicated  by  INDICATOR. Currently, the indicators used are special, redefine and fix-value.

defconst VAR VAL Macro

When it is evaluated by the interpreter, it has the same effect as (setq VAR VAL).When it is compiled, the code in which VARS are replaced by VALS is generated. An error occurs when VAR is assigned a new value in the context in which VAR is assumed a constant.

reset-compilation-flags  Function

reset-compilation-flags  revokes  all  the  declarations effected via the macro declare so far.

The  compiled  object  is designed so as to use  static scope rule for local variables

(authentic Lisp scope rule is  dynamic ). For exact compilation of functions which  utilize  global variables , all the non locally referred variables

(i.e., variables referred from functions other than that  which  binds  the  variable)  should  be  declared to be special.

The declaration of special variables is effected by

          (declare VAR-LIST special)

where VAR-LIST is a list of non locally referred variables.

Example:    When  variables  x and y are used non-locally, they should  be  declared  special  before compiling functions which binds them by

          (declare (x y) special)

If a non local variable is not properly declared, the compiler treats  the variable as a special variable; the value of a local variable  is  stored  somewhere  on the system stack access to which  can  only be possible from the function which binds the variable.

For  calls  to some of the predefined functions (such as atom, car,  cdr,  etc.), the compiler generates certain machine code sequences  which work effectively the same as these functions. Thus,  if  some of the predefined standard functions are to be redefined by the user program, they should be declared by

          (declare FN-LIST redefine)

where FN-LIST is a list of the names of predefined functions which are to be redefined.

By the declaration

          (declare SYM-LIST fix-value)

you can tell the compiler that the symbols in SYM-LIST have only fixnum value.

Storing Compiled Objects
========================

The  compiler puts the compiled code in a relocatable form (in a  form  of  list  of  numbers  and  some Lisp objects) in the property  list  of  the  name  of the compiled function as its compiled-code property.   This  may be printed to a file as a normal  Lisp  object  and  may  later  be  read back in.  This relocatable  form  may  be  converted into machine code object (code  piece)  by the function load-code.  The result of load-code may be put into the definition cell of the function name by  the  function putd (see  Chapter ~see CodePiec,"Code Pieces", for details).

Example:   If the relocatable compiled code for the function f is  stored in the file connected to an input stream which is the value of the variable obj, the definition of f may be loaded by:

          (putd 'f (load-code (read obj)))

Difference from the Interpreter
===============================

As  the  compiled object is designed so as to attain efficient execution,   some   differences  exist  between  the  run time behaviour of compiled codes and interpretive codes.

Non local go and return in prog forms as well as non local exit in loop forms  are  not allowed in compiled functions. Only  available  non-local  exit structure is that provided by catch and throw.

Providing Space for Compiled Codes
==================================

Compiled  codes  are stored in an area called  fixed-heap  which is  different from usual  heap  for ordinary Lisp objects.  When a  large  amount  of  code should be compiled, the size of the fixed-heap  must be specified to be large enough.  This can be achieved  by  supplying an optional parameter  "-f"  to the Unix command  utilisp  as

          % utilisp -f N

where  N  is  a  number  indicating  how  many  kilobytes should  be  provided  for  compiled objects.  The default value of N is 64. If enough fix heap space doesn't exist, then Lisp process abnormally terminates.

As  the  garbage  collector  does  not collect garbages in the
fixed-heap    area,   re-compilation   of   functions   leaves
uncollectable  garbages.   See  Chapter ~see MMS, "Memory Management
System", for details.

Errors and Debugging
********************

The Error System
================

UtiLisp32  generates an error when some invalid operation is tried  by  the program; for example, when the  car  of an atom has been taken.

When   an   error  is  generated,  the  value  of  the  symbol corresponding to the kind of the error is examined.  The value is  interpreted  as  a function, which is called by the system with  one argument; it depends upon the kind of the error what this argument is.  The initial value for these symbols are the symbols  themselves.   These symbols themselves are defined as standard  error handlers , which  print  an appropriate error diagnostic  message,  the  information passed as the argument, and  the  function  in which, or while evaluating arguments of which, the error took place.

Then  the value of the symbol break is examined, which should be a function of no argument, and this function is then called in the  environment  where  the error has occurred (the variables have  the  same  values  as  when  the error took place).  The result  of  this  function  call  will  be  the  result of the function during the evaluation of which the error occurred.

break Variable

The  value  of break is a function which is called by the standard error handlers after printing error diagnostics. The initial value of break is break itself.

break  Function

break first binds standard-input and standard-output to the streams connected to the  terminal, i.e. terminal-input and terminal-output,  readtable and macrotable  to  the  standard  ones, prompt to the string "@" ,  and  then  enters a read-eval-print loop similar to the  top-level  loop.  This loop may be terminated by the

unbreak . ARGS Function

unbreak  is  used  to  terminate  a break loop.  The inner-most   break  loop  is  terminated  and  the  value returned  by  that  break  will  be  the last argument of unbreak.   If no break encloses an unbreak call, an error is generated.

Following  are  the  variables the values of which are used as the  error  handlers, and, at the same time, function names of the  standard  error  handlers.   The  initial values of these variables  are  themselves.   The optional argument WHERE is interpreted as the function name where the error has occurred. The  default  value  of WHERE is the function from which the error  handler  is  called.   When  an  error handler is to be called   explicitly   (usually  by  funcall),  an  appropriate function name should be given for this optional argument.

Example:  The function cadr could have been defined as:

         (defun cadr (x)
            (cond ((or (atom x) (atom (cdr x)))
                   (funcall err:argument-type x 'cadr))
                  (t (car (cdr x)))))

err:argument-type Variable

err:argument-type X (WHERE) Function

The type of X was not valid for the function applied to it.

err:buffer-overflow Variable

err:buffer-overflow DC (WHERE) Function

A  string or a symbol is read in which is longer than the string  buffer .   The  size  of  the  string  buffer  is, currently, 512 characters.  DC is always nil.

err:catch Variable

err:catch TAG (WHERE) Function

throw was called with its first argument being TAG, but the  corresponding  catch  with  its first argument eq to TAG was no found.

err:end-of-file Variable

err:end-of-file STREAM (WHERE) Function

The  end  of  the file was reached while reading the file associated  with  STREAM.   STREAM  is  automatically closed.

err:floating-overflow Variable

err:floating-overflow DC (WHERE) Function

Overflow of a floating point number occurred. DC is always nil.

err:function Variable

err:function X (WHERE) Function

X  was used as a function but is illegal as a function, i.e., a non-symbolic atom or a  cons  cell which is not a lambda expression.

err:go Variable

err:go TAG (WHERE) Function

A go form was evaluated with TAG but the corresponding prog that has the label TAG in its body was not found.

err:index Variable

err:index INDEX (WHERE) Function

INDEX  was  used  as an index for a vector or a string, but is out of index range or not even a  fixnum .

err:io Variable

err:io STREAM (WHERE) Function

STREAM was used for some I/O operation but has not been opened properly; an input stream was used for output, the reverse case, or STREAM was not open at all.

err:number-of-arguments Variable

err:number-of-arguments DC (WHERE) Function

The  number  of  arguments for a function was too many or too few.  DC is always nil.

err:open-close Variable

err:open-close STREAM (WHERE) Function

Opening  or  closing  of  STREAM failed.  Occasionally, some diagnostic  message,  besides that of the Lisp system, is printed out by the operating system.

err:read Variable

err:read DC (WHERE) Function

The  character  sequence read in cannot be interpreted as a Lisp object.   This  error  is  often  caused  by an improper usage of dots ( . ).

err:return Variable

err:return DC (WHERE) Function

return, exit, or unbreak was called but the corresponding prog, loop, or break was not found. DC is always nil.

err:unbound-variable Variable

err:unbound-variable VAR (WHERE) Function

VAR was evaluated but is unbound.

err:undefined-function Variable

err:undefined-function FN (WHERE) Function

The symbol FN was used as a function but is undefined.

err:variable Variable

err:variable X (WHERE) Function

X was used as a variable but is not a symbol.

err:zero-division Variable

err:zero-division DC (WHERE) Function

Division  by zero was attempted.  This error may occur in both  integer  and  floating arithmetics.  DC is always nil.

Two  special  errors  are handled quite differently.  They are the  overflow  of  the system  stack and the shortage of the available  memory.   When a stack overflow occurs, or when the garbage   collector   failed  to  collect  enough  memory  for computation,  a  diagnostic message indicating the kind of the error  is  printed,  all the variables recover their top-level values, and UtiLisp32 resumes the top-level loop.

When  a stack overflow occurs during a garbage collection, UtiLisp32 prints out a message and the Lisp session is terminated abnormally,  since  such  a situation is fatal and recovery is impossible.

Attention Handling
==================

When  the  execution of a Lisp program is interrupted from the terminal  (usually  by the break key), the attention interrupt handler attention interrupt handler  is  called.   If  the  system is during a certain I/O operation,  this  call will be postponed until the termination of that I/O.

attention-handler Variable

The value of attention-handler is the attention interrupt

handler,  which  must  be a function of no argument.  The initial value of attention-handler is break.

The Debugger
============

The  debugger is a collection of functions which are useful in debugging Lisp   programs. As  debugger  is  designed  for interpretive functions, it is recommended to debug programs in interpretive  form  and  then  compile them into machine codes (see Section~see Compile,"Compilation", for details).

trace . FUNCNAMES Macro

trace takes arbitrarily many arguments which are names of interpretive   functions.    The   functions   listed  in FUNCNAMES become  traced ; the function  name  and arguments  are  printed  on entry to these functions, the name  and the result of the function are printed on exit, with the nesting level, in appropriate indention.

Tracing   is  effected  by  automatically  rewriting the
definition  of  the   traced  functions.  This alteration
can be restored by the function untrace.

trace-when PRED . FUNCNAMES Macro

trace-when is the same as trace except that tracing is conditional.   The  form  PRED is evaluated each time a function  listed  in  FUNCNAMES  is  called,  and  that function  call  will be  traced  if and only if the value of  evaluating  PRED  is  non-nil.  As arguments to the function  are  already  bound  when  PRED is evaluated, PRED may depend upon the arguments.

untrace . FUNCNAMES Macro

untrace  stops   tracing   of  the  functions  listed  in FUNCNAMES.

backtrace (N) Function

With  no  argument, backtrace returns a list of the names of all the functions which are nesting around the current environment.   When  N is supplied, a list of the names of only N innerly nested functions is returned.  Inside the break  loop  of  the  standard  error  handler, this function may be used to examine the calling sequence upto where the error has occurred.

oldvalue (N) Function

With  no  argument, oldvalue returns a list of dotted pairs.   The   car   of  each pair is a variable which is bound  by  lambda-binding  and  the  cdr  is its previous value  before  the  binding.  If the variable had been in unbound  state  before the binding, its previous value is indicated  by the symbol *UnBoundVariable*.  The order in the list is such  that  recently  bound variables come earlier.  When N is supplied,  only  pairs  concerning  recent  N bindings  are included.  This function may be used to get information on the binding history.

toplevel Variable

The  value of toplevel is a function of no argument which is  used  as  the  Lisp  top-level .  The initial value of toplevel is utilisp.

toplevel  Function

toplevel  first  undoes  all the variable bindings except top-level  ones.  Then the value of the variable toplevel is  examined.   The  value  should  be  a  function  of  no argument,  and  this  function  is  then  called.  As the initial  value  of  the  toplevel  is the symbol utilisp, toplevel can be used to resume the top-level loop.

The Low-Level Debugger
======================

The  low-level  debugger is a  collections  of  functions for debugging  the  UtiLisp  system itself.  As they are primarily prepared  for maintainance of the system, some of them are not safe;  misuse of them may cause a fatal error.  They should be used  with  proper  knowledge of the physical represenation of various Lisp objects.

address X Function

address returns  the  current memory address

of X as a fixnum .   If  X  is a  reference , the address of the vector  element  pointed by X is returned.  If X is a fixnum , X itself is returned.

Note:   The  Lisp objects may be relocated by the garbage collector,  except  for  those which are allocated in the fixed-heap  area.

peek ADDR LENGTH Function

peek  returns  a  string  which  contains  a  copy of the machine  memory  beginning at (address ADDR) and LENGTH long.

Memory Management System
************************

The  memory  space  used by the UtiLisp32 is divided into four areas.  They are:

heap

     for usual Lisp objects (including symbol area)

fixed-heap
     for predefined objects and compiled codes

stack
     for control information and temporary storage

kernel
     for the system kernel

The  size  of  the  heap  and the  fixed-heap  and areas may be specified  by  the  parameters  at  the initiation of the Lisp process  (see Chapter ~see Introduc, "Introduction", for details). The sizes of   the   kernel  area  is  system-defined constants.   The size of the area available for the  heap  area is the maximum memory size allowed for a user job by the operating system minus the total size of all the other areas.

When  an  object  is to be allocated, by cons for example, and not  enough space is left in the heap area, then the garbage collector is called.

The  garbage  collector gathers all the Lisp objects which will never  be  accessed; the memory space occupied by them becomes reusable.   Then,  the  execution  of  the original program is resumed.

The  garbage  collector  may  also be called explicitly by gc.

gc  Function

gc  invokes  the garbage collector.  It returns nil as its value.

Following   functions   are  for  asking  states  and  setting
parameters  of  the  memory  management  system.   The unit of
memory space used in these functions is  byte  in UtiLisp32.

extendheap SIZE Function

extendheap は起動時に指定したヒープ領域の大きさを SIZEに拡張します. 拡張に成功したらt, 失敗したらnilを返します.

extendheapK SIZE Function

extendheapKは ヒープ領域の大きさを SIZE Kバイトに拡張します. 拡張に成功したらt, 失敗したらnilを返します.

gc-hook Variable

シンボル gc-hookに値が束縛されていると, gc終了直後にこの値が funcallされます.

gccount  Function

gccount returns a  fixnum  which indicates how many times the  garbage  collector  has been called since the system initiation.

gctime  Function

gctime  returns  a   fixnum  indicating CPU time required for gc so far.  The unit used is one 60th second.

heapsize  Function

heapsize returns the size of the heap area as  fixnum .

heapsizeK  Function heapsizeK は (heapsizeK) / 1024 を返します.

heapfree  Function

heapfree returns the size of the free heap area as  fixnum .

heapfreeK  Function heapfreeK は (heapfreeK) / 1024 を返します.

symsize  Function

symsize returns the size of the symbol area as  fixnum . UtiLisp/C ではヒープ領域が型毎に分かれていないので, 必ず0を返す.

symfree  Function

symfree returns the size of the free symbol area as  fixnum . UtiLisp/C ではヒープ領域が型毎に分かれていないので, 必ず0を返す.

fixsize  Function

fixsize returns the size of the fixed heap area as  fixnum . UtiLisp/C ではヒープ領域が型毎に分かれていないので, 必ず0を返す.

fixfree  Function

fixfree returns the size of the free fixed heap area as  fixnum . UtiLisp/C ではヒープ領域が型毎に分かれていないので, 必ず0を返す.

stacksize  Function

stacksize returns the size of the stack area as  fixnum .

stack-used  Function

stack-used returns the size of the stack area currently in use.

stack-bottom  Function

stack-bottom returns the bottom of the stack.

stack-top  Function

stack-top returns the top of the stack.

stack-base  Function

stack-base returns the current base of the stack.

stackWM  Function

stackWMは, 引数スタック, 束縛スタック, コードスタック, 環境スタックのそれぞれに関して, これまで使ったスタックの最大量とスタック量(バイト数)の対をリストにして返す.

init-stackWM  Function

init-stackWMを呼び出すと, stackWMで表示するスタックの最大量の記録をリセットされる.

Structure Editor - USE
**********************

USE  (Utilisp Structure Editor) is a structure-oriented editor for inspecting and changing list structures, which may be Lisp programs or data.

One  merit  of  using USE, compared with text-oriented editors such  as Emacs or  vi,  is that editing is done on Lisp data structures   themselves,   rather   than   on   their  printed representations;  USE  has  the  knowledge of the hierarchical structure  of the edited data, and the editing commands of USE reflect  this hierarchy.  Another merit is that the editing is done  in  the  Lisp  environment;  arbitrary  Lisp form may be evaluated  during  editing and currently edited structures may also be manipulated by Lisp functions.

USE  always manipulates a copy of the original list structure; all the atoms in the copy are the same with the original ones, but  all  the   cons   cells  are  newly created for the copy. Thus, when a USE session is aborted by a k command, the original program or data is not affected at all.

Invoking USE
============

Following  macros  are used to invoke USE and, on their normal termination, restore the edited result.

ed FN Macro

ed invokes  USE for editing interpretive functions.  The definition  of FN will be edited.  ed puts edited result in the  definition  cell of FN on normal termination.

edv VAR Macro

edv  invokes  USE for editing  values  of variables.  The value  of VAR is edited.  edv sets edited result in the value  cell of VAR on normal termination.

edp SYM Macro

edp  invokes  USE for editing  properties  of  symbols .  The property  list   of  SYM  is edited, and the result will become the new  property list  of SYM on normal termination.

edf FILE-NAME Macro

edf invokes USE for editing text files containing printed representations   of   Lisp   objects.  FILE-NAME  is evaluated   first.    Its   result   must   be  a  string representing  the  name  of the file to be edited.  It is often convenient to set a file name to a variable and use that  variable  as the argument of edf, since a file name may be quite complicated.  A string indicating the file name  may  also  be  used directly as an argument of edf, since a string is evaluated to itself.

What  is  edited  is  a  list  of all the objects the printed  representations of which are stored in the file. The  order  of the elements in the list is the same as in the  file.   In  other  words,  an extra left and a right parentheses  are  assumed at the beginning and at the end of  the  file.   The  top-level elements of the result of editing  will  be  printed  back  to  the  file on normal termination.

Note:   Rewriting  an  external  file does not affect the
state  of  the  Lisp  objects,  even if the file contains
function  definitions  such as defun or macro forms.  The
content   of   the  file  should  be  evaluated  to  effect redefinition.

edl LOC Macro

edl  invokes  USE  for  editing some data which never be edited  by  ed, edv nor edp. LOC should be a form to  access a component of certain structure, for example, (car CONS) to access the  car  of a  cons  cell CONS, (vref VEC N) to access N-th element of a vector VEC. LOC is evaluated first, and its value will be edited by USE.  The result will be put back to where it was derived from, on normal termination.

use X Function

use  is  the  USE  system  itself.  It is normally called using above macros, but users may also call use directly. use returns one component list of the edited result, when the  use  session  is normally terminated; it returns nil when it is terminated abnormally (by k command).

USE Session
===========

USE  prompts terminal-input by "?"  when it expects a command.   If  a  symbol  or  a  number  is typed in, it is interpreted  as a command; otherwise, especially when you type in  a  list,  the  list  is  interpreted  as  a  form which is evaluated  and  the  result  is  printed.   When  the  form is evaluated,  the symbol ? is bound to the current  scope  (see the  next  section for details).  The e command may be used to evaluate an atom.

e FORM Use

The form FORM is evaluated and the result is printed.

Arbitrarily many commands and their operands may be typed on  a  single  line.   They are executed sequentially, as long  as  no error is found.  When an error is found, the rest of the current input line will be ignored.

Following two commands are for terminating an editor session.

q  Use

q (quit) terminates the current session normally. The edited result will be restored depending how the editor is called from one of the macros described in the previous secrion.

k  Use

k (kill)  terminates the current session abnormally. The edited result will be merely discarded no matter how the editor is called, and the  original definition, value, property list, etc.  are not affected.

Scope and Position Numbers
==========================

The  editor always have current  scope , which is a portion of the  whole  Lisp object  being  edited.   The  scope  may be nested;  the  current  scope  may be an element of its parent scope,  and  this parent scope may again have its parent, and so on. All  insertion,  deletion,  and  replacement are effected only inside the current scope.

When  the current scope is a list, elements in the list are specified   by   their   positions.   A  positive   fixnum  N represents  the N-th element.  A negative number -n represents the  N-th  element counted from the last.  1 means the first element and -1 the last.

Example: s Suppose the current scope is (a b c d e f g), then

          1   means  a .
          3   means  c .
          -1   means  g .
          -3   means  e .
          10   is invalid.
          -10   is invalid.

Pattern Matching Rules
======================

It  is  sometimes  desired  to  search a certain pattern of Lisp object, without  specifying  its detail.  For example, a form  setqing  to  a  symbol  x may be of programmer's concern irrespective  of  the  value  assigned.   This  example may be expressed as (setq x ?).

The rules of pattern matching are quite simple:

 1. A pattern matches an Lisp object equal to it.

 2. ?  matches any Lisp object.

 3. ???  matches any portion of a list.

Example: s

       (car x)   matches  (car x)   but not  (car '(a b)) .
       (car ?)   matches both  (car x)   and  (car '(a b)) .
       (cons ? ?)   matches both  (cons x x)   and  (cons x y) .
       (list ???)   matches both  (list)   and  (list x y z) .
       (a ??? z)   matches any of  (a z) ,  (a b z) , or  (a b c d e z) .

Printing Current Scope
======================

p  Use

p  (print)  command  prints  the  current  scope in usual abbreviated  way.   See Chapter ~see InandOut, "Input and Output", for abbreviated printing.

pp  Use

pp (pretty print) command prints the current scope with appropriate indention.  See Chapter ~see InandOut, "Input and Output", for pretty-printing.

level N Use

length N Use

level  and  length  commands  are used to set the maximum printing level and length in abbreviated printing to N. N should be a  fixnum .

Note:   The  level  and  the  length  specified  by these commands  are  only  effective  in  one editor session.  The values of printlevel and printlength are not affected.

Changing the Scope
==================

N Use

-N Use

0  Use

Position  numbers  themselves  are commands to change the scope  to  the position specified.  The command 0 changes the  scope  to  the  parent of the current scope, i.e.  a list which contains the current scope as its element.

top  Use

top  command  changes the scope to the whole Lisp object being edited.

n  Use

n  (next)  command moves the scope to the element next to the  current scope in the parent scope.  When there is no parent  scope or the current scope is the last element of the parent scope, it is an error.

l  Use

l  (last)  command  moves  the  scope  to the element one before the current scope in the parent scope.  When there is  no  parent  scope  or  the current scope is the first element of the parent scope, it is an error.

w  Use

w (where)  command  prints  where  the  current scope is beginning from the top level.

Searching
=========

f PATTERN Use

f (find) command searches an Lisp object which "matches" PATTERN in textual order (searches  car  before  cdr ). Searching  is  done in the current scope only.  If one is found,  the  scope  is changed to the Lisp object found. The  intermediate  scopes  are  saved and can be accessed using  the  command  "0".   If  PATTERN is not found, a message is generated and the scope remains unchanged.

ff PATTERN Use

ff (find forward) command is the same as f command except that the search begins in the next scope, that is after the current scope.

fb PATTERN Use

fb (find  backward)  command  is  the  same as f command except  that the search is performed in reverse direction ( cdr  before  car ) and the search begins in last scope, that is, before the current scope. current scope.

fn  Use

fn (find  next) command is the same as ff command except that  the  same PATTERN is used as previous f ff or fb command.

Inserting and Deleting Parentheses
==================================

bi M N Use

bi (both in) command inserts an open parenthesis at the left  of M and a close parenthesis at the right of N. M and N are position numbers.

Example:

       (a b c d e)
          bi 2 4
       --> (a (b c d) e)

bo N Use

bo  (both  out) command deletes the parentheses enclosing N  which  should  be a list.  N is a position number. It is the inverse operation of bi.

Example:

       (a (b c d) e)
          bo 2
       --> (a b c d e)

li N Use

li  (left in) command inserts an open parenthesis at the left of N, and a close parenthesis at the end of scope. N is a position number.

Example:

       (a b c d e)
          li 2
       --> (a (b c d e))

ri N Use

ri  (right in) command inserts an open parenthesis at the beginning of scope and a close parenthesis at the right of N.  N is a position number.

Example:

       (a b c d e)
          ri 2
       --> ((a b) c d e)

lo N Use

lo  (left  out) command moves the open parenthesis of N to  the  beginning  of  the  current  scope.   N must a Position number which specifies a list.

Example:

       (a (b c d) e)
          lo 2
       --> ((a b c d) e)

ro N Use

ro (right out) command moves the close parenthesis of N to  the  end  of  the  current  scope.   N  should be a position number specifying a list.

Example:

       (a (b c d) e)
          ro 2
       --> (a (b c d e))

Inserting and Deleting S-expressions
====================================

i POS SEXPR Use

i (insert) command inserts SEXPR at the right of POS. If  POS  is  a  number, it is interpreted as a position number.   Otherwise,  it  is interpreted as a pattern and the  first  Lisp object found to match POS is assumed. To  use  a number as a pattern, quote the number like '3. In  this  case,  the quote is not included in the pattern used for matching.

Example: s

       (a b c d e)
          i 3 x
       --> (a b c x d e)
          i b (foo bar)
       --> (a b (foo bar) c x d e)

Note:   Insertion to the top of a list can be achieved by specifying 0 for POS.

a SEXPR Use

a (append) command replaces the tail of the current scope by  SEXPR.   If  the current scope is atomic, the whole scope is replaced by SEXPR.

Example: s

       nil
          a (a b c)
       --> (a b c)
          a d
       --> (a b c . d)

in SEXPR Use

in (insert next) commands inserts SEXPR at the right of the current scope in the parent scope.

d POS Use

d (delete) command deletes POS from current scope.  The meaning of POS is the same as in i command.

Example: s

       (a b c d e)
          d 3
       --> (a b d e)
          d b
       --> (a d e)

y POS Use

y (yank)  command  inserts an Lisp object most recently saved  by  the editor  at  the right of POS.  What is saved is either  the  Lisp object  deleted  using  d  command, Lisp object  replaced  using  r  command, or the result of evaluating a form which is typed in instead of a command. The  meaning  of POS is the same as in i command.  This command can be used, with d command, to move a portion of Lisp object inside the edited structure.

Example: s

        (a b c d e)
           d 3
        --> (a b d e)
           y a
        --> (a c b d e)
           (cons 'a 'b) => (a . b)
           y 3
        --> (a c b (a . b) d e)

Replacing S-expressions
=======================

r POS EXPR Use

r (replace) command replaces POS with EXPR. POS has the same meaning as in i command.

Example:

      (a b c d e)
         r 3 (foo bar)
      --> (a b (foo bar) d e)

ra PATTERN EXPR Use

ra (replace all)  command replaces all Lisp object in the  current  scope  which matches PATTERN with EXPR. Number of actual replacements is reported.

Example:

      (a x b x c)
         ra x y
      --> (a y b y c)
      2 occurrences are replaced

Unix Interface
**************

Calling Shell Commands
======================

call COMMAND-STRING Function

This function executes COMMAND-STRING and waits its termination. Because the execution is done by a subprocess rather than UtiLisp32 itself, some commands such as cd have no effect on the status of UtiLisp32. Return value is a  fixnum that represents the status of the command execution.

cd (DIR) Function

cd changes the current working directory of UtiLisp32 to DIR which must be a string. The default value for DIR is the user's home directory defined by the HOME environment variable.

Environment Variables
=====================

getenv NAME Function

getenv searches environment variable list for the name NAME and return its value as a  string . If the variable is not defined, nil is returned.

Example:

     (getenv "HOME") => "/usr/usr1/bill"

putenv NAME VALUE Function

getpid Function

現在のプロセスのプロセスIDを返す.

syscall ... Function

Unixのシステムコールを呼び出す.

errno Function

システムコールの結果のエラー番号を返す.

Command Line Arguments
======================

argv  Function

argv returns the command line that invoked UtiLisp32 as a list of  strings . Note that the command name itself is also included as the first element of the list.

Miscellaneous
*************

This  chapter  describes  functions  that  do  not seem to fit anywhere else.

time FORM Function

With  no  argument,  time returns the CPU time elapsed by the  Lisp system since its initiation.  This includes the time  required  for  garbage  collection and for external programs   which   are  called  using  call. If the optional argument FORM is supplied, FORM is evaluated again, and CPU time required for this re-evaluation  is  returned.   The  time is returned as a fixnum  object in one 60th seconds.

quit  Function

quit will  return  control  to  the  caller  of the UtiLisp32, usually  to Unix shell. All the files  opened by in the UtiLisp32 will be automatically closed.

abend  Function

abend abnormally  terminates the UtiLisp32.

version Variable

The  value of version is a string which indicates version

of the system.

date-time  Function

date-time returns a string containing the date

and time.

The string has the format

               "YYMMDDHHMMSS"

where   YY   are  two least significant digits of the year, MM , month,  DD , day,  HH , hour in 24-hour system,  MM , minute,  SS , second.

Example: At  5:30  in  the evening of January the 20th, 1988,

        (date-time)  =>  "880120173000"

userid  Function

userid  returns  user name as a  string .

utilisp  Function

utilisp  is the top-level loop of the UtiLisp32.  An S-expression  is read in, evaluated and printed.  This is repeated again and again.  The prompting character

of the top-level  loop is  ">" .   This  symbol  utilisp  is the initial  value  of  the  symbol toplevel (see Chapter ~see ErrDebug, "Errors and Debugging", for details).

? Variable

Each  time a form read in is evaluated in a utilisp loop  or  in  a  break  loop,  the  result  is set to the variable ?.

Example: s In the top-level UtiLisp loop,

        (cons 'foo 'bar)  =>  (foo . bar)
        ?  =>  (foo . bar)

setl LOC VAL Macro

setl is a macro which makes it easy to describe list structure modification or vector element updating. It is particularly useful for defining such macroes that access and update an element simultaneously. LOC is either a variable name or an expression which indicates the element in list or vector. VAL is a value set to the place indicated by LOC. setl rerurns the value  VAL. Example: s

     (setl x y)   is equivalent to  (setq x y)
     (setl (car x) y)   is equivalent to  (car (rplaca x y))
     (setl (cadr x) y)   is equivalent to  (car (rplaca (cdr x) y))
     (setl (vref v 3) y)   is equivalent to  (vset v 3 y)
     (setl (plist x) y)   is equivalent to  (setplist x y)
     (setl (nth n x) y)   is equivalent to  (car (rplaca (nthcdr n x) y))

exfile FILENAME (SHOW) Function

exfile evaluates (executes) all the S-expression in the file specified by FILENAME and returns nil. If SHOW is non-nil, exfile output the result of each evaluation. The default value for SHOW is nil.

package-load LISPFILE . EXTERNALS Macro

Common Lisp風ライブラリ
*****************

X-Windowインタフェース
***************