
\documentstyle[twoside,fullpage,makeidx,verbatim,texhelp,fancyhea,mysober,mytitle,html,epsf,mr]{report}
%
%              %%%%%%%    %%%%%        %%%%%%    %%%%%   %     %
%              %      %  %             %     %  %     %   %   %
%              %      %  %             %     %  %     %    % %
%              %%%%%%%    %%%%%        %%%%%%   %     %     %
%              %               %       %     %  %     %    % %
%              %               %       %     %  %     %   %   %
%              %         %%%%%%        %%%%%%    %%%%%   %     %
%
%              By Jean Orloff
%              Comments & suggestions by e-mail: ORLOFF@surya11.cern.ch
%              No modification of this file allowed if not e-sent to me.
%
% A simple way to measure the size of encapsulated postscript figures
%   from inside TeX, and to use it for automatically formatting texts
%   with inserted figures. Works both under Plain TeX-based macros
%   (Phyzzx, Harvmac, Psizzl, ...) and LaTeX environment.
% Provides exactly the same result on any PostScript printer provided
%   the single instruction \psfor... is changed to fit the needs of the
%   particular dvi->ps translator used.
% History:
%   1.31: adds \psforDVIALW(?)
%   1.30: adds \splitfile & \joinfiles for multi-file management
%   1.24: fix error handling & add \psonlyboxes
%   1.23: adds \putsp@ce for OzTeX fix
%   1.22: makes \drawingBox \global for use in Phyzzx
%   1.21: accepts %%BoundingBox: (atend)
%   1.20: tries to add \psfordvitps for the TeXPS package.
%   1.10: adds \psforoztex, error handling...
%2345678 1 2345678 2 2345678 3 2345678 4 2345678 5 2345678 6 2345678 7 23456789
%
\def\temp{1.31}
\let\tempp=\relax
\expandafter\ifx\csname psboxversion\endcsname\relax
  \message{version: \temp}
\else
    \ifdim\temp cm>\psboxversion cm
      \message{version: \temp}
    \else
      \message{psbox(\psboxversion) is already loaded: I won't load
        psbox(\temp)!}
      \let\temp=\psboxversion

% Remove this for processing with dvi2ps instead of dvips
%\special{!/@scaleunit 1 def}

\parskip=10pt%
\parindent=0pt%


\title{Reference Manual for MzScheme}

\author{Matthew Flatt\\mflatt@cs.rice.edu\\Rice University\\Houston, TX}
\date{February 1996}

\makeindex

\begin{document}
\maketitle

\newpage
\pagestyle{empty}
\setcounter{page}{0}

\RealCopyright

\cleardoublepage

\pagestyle{fancyplain}
\bibliographystyle{plain}

\begin{latexonly}

\pagenumbering{roman}
\setfooter{\thepage}{}{}{}{}{\thepage}

\end{latexonly}

\tableofcontents

\cleardoublepage
\pagenumbering{arabic}

\RTFCopyright

\begin{htmlonly}
\newcommand{\SetTolerance}[0]{}
\end{htmlonly}

\SetTolerance

\begin{htmlonly}
\newcommand{\CHAPTER}[1]{
\begin{rawhtml}<HR>\end{rawhtml}
\chapter{#1}
}
\newcommand{\SECTION}[1]{\section{#1}}
\newcommand{\Index}[1]{}
\newcommand{\Label}[1]{}
\newcommand{\Ref}[2]{the section titled ``#1''}
\newcommand{\FRef}[1]{Figure ``#1''}
\newcommand{\PhoneBookFigure}[0]{\begin{rawhtml}<IMG SRC="pb.gif">\end{rawhtml}}
\newcommand{\www}[1]{\\
\centerline
{\tt
\begin{rawhtml}<A HREF="\end{rawhtml}#1\begin{rawhtml}">\end{rawhtml}%
#1
\begin{rawhtml}</A>\end{rawhtml}%
\\}}
\end{htmlonly}


\newcommand{\scm}[1]{{\tt #1}}
\newcommand{\scmclass}[1]{\scm{#1\%}}
\newcommand{\var}[1]{{\em #1}}
\newcommand{\defterm}[1]{{\bf #1}}
\newcommand{\idefterm}[1]{{\bf #1}\index{#1}}

\newcommand{\scmindex}[1]{\index{#1@{\tt #1}}}
\newcommand{\scmfirst}[1]{\scmindex{#1}\scm{#1}}

\newcommand{\scmline}[1]{
\begin{tt}
\begin{tabbing}
\ \ \=#1
\end{tabbing}
\end{tt}
}

\newcommand{\example}[1]{
\begin{list}{}{
\setlength{\leftmargin}{0.25in}
\setlength{\rightmargin}{0.25in}
}
\small
\item {\sc Example}: #1
\end{list}
}

\newcommand{\ignorethisfornow}[1]{}

\CHAPTER{This Manual}

This manual describes the specific features of MzScheme, including its
object and thread syntax, leaving the details of standard Scheme to
the $R^4RS$ document.  For information about command line flags for
the standalone console version of MzScheme, run with the ``{-}-help''
flag.\index{--help@{-}-help}
\index{MzScheme!standalone}

MzScheme is fully $R^4RS$-compliant, although command line
or internal flags can change some features affecting compliance.
(For example, case-sensitivity can be enabled.) \index{case sensitivity}
MzScheme differs from most other Schemes in two notable ways:
\begin{itemize}
\item MzScheme is extended with a class and object system.
\item MzScheme supports internal pre-emptive threads.
\end{itemize}

This manual assumes familiarity with the Scheme programming
language. The typesetting sources are taken from Julian Smart's {\it
Reference Manual for wxWindows 1.60: a portable C++ GUI toolkit}.

\CHAPTER{Programming Constructs}

\SECTION{Void}

\scmindex{undefined values}
\scmindex{void}
MzScheme returns the unique value \scm{\#<void>} for procedures that
have undefined results in $R^4RS$. \scmindex{\#<void>}
The procedure \scm{void} takes any number of arguments and returns
\scm{\#<void>}. \scm{(void?\ \var{v})} returns \scm{\#t} if and only if \var{v} is \scm{\#<void>}.

\SECTION{Numbers}

\index{numbers}
A number in MzScheme is one of the following:
\begin{itemize}
\item a \defterm{fixnum} \index{fixnum} integer (30 bits plus a sign bit)
\item a \defterm{bignum} \index{bignums} integer (cannot be represented in 30 bits)
\item a \defterm{rational} \index{rational} number
\item a \defterm{flonum} \index{flonum} (double-precision floating-point number)
\item a \defterm{complex} \index{complex} number; the real and imaginary parts
are either both flonums or both rationals.
\end{itemize}
The first four number types are always exact. Flonums are always inexact.
A complex number is inexact if its real and imginary parts are flonums,
otherwise it is exact.

In addition to the standard numerical procedures, the following
procedures work on fixnums:
\begin{itemize}
\item \scmindex{binary-or} \scm{(binary-or \var{n$_1$} \dots \var{n$_n$})}
returns the result of a bitwise ``or'' on the binary representations
of \var{n$_1$} through \var{n$_n$}.
\item \scmindex{binary-and} \scm{(binary-and \var{n$_1$} \dots \var{n$_n$})}
returns the result of a bitwise ``and'' on the binary representations
of \var{n$_1$} through \var{n$_n$}.
\item \scmindex{binary-xor} \scm{(binary-xor \var{n$_1$} \dots \var{n$_n$})}
returns the result of a bitwise ``exclusive or'' on the binary
representations of \var{n$_1$} through \var{n$_n$}.
\item \scmindex{binary-not} \scm{(binary-not \var{n}}
returns the result of a bitwise ``not'' on the binary
representation of \var{n}.
\end{itemize}

\index{infinity} \index{not-a-number}
The following are inexact constants: \scmfirst{+inf.0} (infinity),
\scmfirst{-inf.0} (negative infinity), \scmfirst{+nan.0} (not a number),
and \scmfirst{-nan.0} (not a number). They have no exact form.

Standard procedures that take an integer index argument
(e.g. \scm{vector-ref}) must be given a fixnum argument or an integer
flonum argument whose exact translation is a fixnum.

\SECTION{Boxes}\label{boxes}

\index{boxes}
MzScheme provides the usual implementation of boxes:
\begin{itemize}
\item{} \scm{(box \var{v})} returns a new box that contains \var{v}. 
\scmindex{box}
\item{} \scm{(unbox \var{b})} returns the content of the box \var{b}. 
For example \scm{(unbox (box \var{v}))} returns 
\var{v}. \scmindex{unbox}
\item{} \scm{(set-box!\ \var{b} \var{v})} sets the content of box \var{b}
to \var{v}. \scmindex{set-box"!}
\item{} \scm{(box?\ \var{b})} returns \scm{\#t} if \var{b} is a box,
\scm{\#f} otherwise. 
\scmindex{box?}
\end{itemize}

\SECTION{Structures}

\index{structures}
\scmindex{define-struct}

\scm{(define-struct \var{s} (\var{field$_1$} \dots \var{field$_n$}))},
where \var{s} and \var{field$_i$} must be symbols, creates a new abstract 
record datatype by adding these definitions to the top-level environment:
\begin{itemize}
\item \scm{make-}\var{s} --- a constructor procedure
that takes $n$ arguments and returns a new structure value.

\item \var{s}\scm{?} --- a predicate procedure that returns 
\scm{\#t} for values constructed by \scm{make-}\var{s}.

\item \var{s}\scm{-}\var{field$_1$} \dots \var{s}\scm{-}\var{field$_n$}
--- selector procedures that take a structure value and extract
a field value.

\item \scm{set-}\var{s}\scm{-}\var{field$_1$}\scm{!}\ 
\dots \scm{set-}\var{s}\scm{-}\var{field$_n$}\scm{!} ---  setter 
procedures that take a structure value and a new field value. The
field is destructively updated in the structure.

\item \scm{structure:}\var{s} --- a value representing the new abstract
datatype. This value can be used with the extended form of \scm{define-struct} 
(see below) to create a new datatype that is a subtype of \scm{structure:}\var{s}.
\end{itemize}

\scm{(define-struct (\var{s} \var{t}) (\var{field$_1$} \dots 
\var{field$_n$}))} 
is like \scm{(define-struct \var{s} ...)}, but the resulting datatype
is a subtype of \var{t}. The \var{t} expression can be anything that
evaluates to an abstract datatype (created by another
\scm{define-struct} expression).  If the type returned by \var{t} has
\var{m} fields, then a value created with
\scm{make-}\var{s} will have \var{m}+\var{n} fields. The first \var{m}
fields are accessed with accessors from the type \var{t}, and the rest
are accessed with the \var{s}\scm{-}\var{field$_i$} accessors.
A value created with \scm{make-}\var{s} will answer \scm{\#t} to both
\scm{\var{s}?}\ and to the predicate that tests for type \var{t}. The
\scm{\var{s}?} predicate will only return \scm{\#t} for
values created by \scm{make-}\var{s} or by constructors for
subtypes of \scm{structure:}\var{s}.

MzScheme structures are not opaque, but structures can only
be updated with the setter procedures defined by \scm{define-struct}. 
These utility functions work on with structure values of any type:

\begin{itemize}
\item \scmindex{struct?} \scm{(struct?\ \var{v})} returns
\scm{\#t} if \var{v} was created by any \scm{make-}\var{s}
or \scm{\#f} otherwise. All other built-in predicates will return
\scm{\#f} for values constructed by a \scm{make-}\var{s}.

\item \scmindex{struct-length} \scm{(struct-length \var{v})} returns
the number of fields in the structure value \var{v}.

\item \scmindex{struct-ref} \scm{(struct-ref \var{v} \var{n})}
returns the value of the \var{n}th field of the structure values
\var{v}. If \var{v} does not have an \var{n}th field, an error is
raised.

\item \scmindex{struct->vector} \scm{(struct->vector \var{v})}
converts the structure value \var{v} to a vector.
The first slot of the result vector contains a symbol of the form
\scm{structure:\var{s}}. T he remaining slots contain the
values of the fields of \var{v}. The \scm{struct->vector} procedure 
is intended for printing and debugging purposes.
\end{itemize}

\scmindex{let-struct}
\scm{(let-struct \var{s} (\var{field$_1$} \dots \var{field$_n$}) \var{body})}
and
\scm{(let-struct (\var{s} \var{t}) (\var{field$_1$} \dots \var{field$_n$}) 
\var{body})} are like \scm{define-struct}, but the generated procedures are only
bound within \var{body}.

If a \scm{define-struct} statement is embedded within a closure, then
it is transformed into a \scm{let-struct} statement; all statements
following the \scm{define-struct} statement in the closure are moved
into the body of the \scm{let-struct} statement.

If \scm{define-struct} is evaluated multiple times for the same
structure name, then each evaluation produces a new structure
type. 

Two structures are \scmfirst{eqv?}\ if and only if they are
\scmfirst{eq?}. Two structures are \scmfirst{equal?}\ if they have the
same structure type and their corresponding fields are all
\scm{equal?}.

Examples:
\scmline{
  (define-struct cons-cell (car cdr))\\
\>(define x (make-cons-cell 1 2))\\
\>(cons-cell?\ x) ; => \#t\\
\>(define orig-cons-cell?\ cons-cell?)\\
\>(define-struct cons-cell (car cdr))\\
\>(define y (make-cons-cell 1 2))\\
\>(cons-cell?\ y) ; => \#t\\
\>(cons-cell?\ x) ; => \#f, cons-cell?\ now checks a different type\\
\>(orig-cons-cell?\ x) ; => \#t\\
\>(orig-cons-cell?\ y) ; => \#f\\
\>(define-struct (tagged-cons-cell structure:cons-cell) (tag))\\
\>(define z (make-tagged-cons-cell 3 4 'x))\\
\>(cons-cell?\ z) ; => \#t\\
\>(tagged-cons-cell?\ z) ; => \#t\\
\>(tagged-cons-cell?\ y) ; => \#f\\
\>(cons-cell-car z) ; => 3\\
\>(tagged-cons-cell-tag z) ; => 'x
}

\SECTION{Objects}

\index{objects}
\index{classes}

MzScheme's object system uses the class-object model: a
\defterm{class} describes a prototypical object (possibly in terms
of other classes) and an \defterm{object} is an instance of a class.
Classes and objects are both first-class Scheme values. However, a
MzScheme class is not a MzScheme object. (There are no
``meta-classes''.)

A MzScheme class specifies
\begin{itemize}
\item a collection of instance variable names,
\item initial values for the instance variables, and
\item an initialization procedure that is called when an object is 
created.
\end{itemize}

An object is a collection of instance variables that are instantiated
according to a class description. There is no distinction in MzScheme
between ``methods'' and ``instance variables''; a method is simply an
instance variable with a procedural value.  

The most important feature of the object system is the ability to
define a new class in terms of another class. Briefly, the central
concepts are \idefterm{inheritance} and
\idefterm{overriding}. Inheritance is the ability to describe a new
class in terms of one or more existing classes: an instance of the new
\idefterm{derived class} will automatically have the instance
variables described in the \idefterm{superclasses}.  Overriding is the
ability, in a derived class, to redirect references to instance
variables that have already been defined in the superclasses.

\subsection{An Example}

Classes are defined using the \scm{make-class} syntactic form.
Here are four class definitions:

\begin{verbatim}
  (define stack% 
    (make-class '() 
       ((private 
         [stack '()]) ; A private instance variable
        (public 
         [name 'stack] ; A public instance variable 
         [push! (lambda (v) 
                  (set! stack (cons v stack)))] 
         [pop! (lambda () 
                 (let ([v (car stack)]) 
                   (set! stack (cdr stack)) 
                    v))]
         [empty? (lambda () 
                   (null? stack))] 
         [print-name (lambda () 
                       (display name) (newline))]))))

 (define named-stack% 
    (make-class stack% 
       ((public 
         [name #f]))
       (lambda (stack-name)  ; The intialization procedure
        (set! name stack-name) 
        (super-init))))

 (define double-stack% 
    (make-class stack% 
       ((inherit push!) 
        (public 
         [name 'double-stack]
         [double-push! (lambda (v) 
                         (push! v)
                         (push! v))]))))

  (define safe-stack%
    (make-class stack% 
       ((inherit empty?)
        (rename [std-pop! pop!])
        (public 
         [name 'safe-stack]
         [pop! (lambda ()
                 (if (empty?) #f (std-pop!)))]))))
\end{verbatim}

A percent sign (``\%'') is used by convention in MzScheme to indicate
that a variable's value is a class. Here, the class \scm{stack\%}
defines the usual stack object with \scm{push!}, \scm{pop!}, and
\scm{empty?}\ methods. The class \scm{named-stack\%} is derived from
\scm{stack\%}; it defines a stack that is named through the intialization
function. In this initialization procedure, the call \scm{(super-init)}
invokes the superclass's intialization procedure. The class \scm{double-stack\%}
extends the functionality \scm{stack\%} with a new method,
\scm{double-push!}. The class \scm{safe-stack\%} overrides the \scm{pop!} 
method of \scm{stack\%}, insuring that \scm{\#f} is returned whenever
the stack is empty.

In each of these classes, the instance variable \scm{name} contains
the name of the class. The \scm{name} declarations in
\scm{named-stack\%},
\scm{double-stack\%}, and \scm{safe-stack\%} override the declaration 
in \scm{stack\%}. Thus, when the \scm{print-name} method of an object
from \scm{double-stack\%} is invoked, the name printed to the screen
will be ``double-stack''.

While all of \scm{named-stack\%}, \scm{double-stack\%}, and
\scm{safe-stack\%} inherit the \scm{push!}\ method of \scm{stack\%}, it
is declared with \scm{inherit} only in \scm{double-stack\%}. This is
because \scm{named-stack\%} and \scm{safe-stack\%} do not need to use
\scm{push!}, so the inheritance does not need to be
declared. Similarly, only \scm{safe-stack\%} needs to declare
\scm{(inherit empty?)}.

Although \scm{safe-stack\%} is overriding \scm{pop!}, it actually needs
to {\em extend} \scm{pop!}. Thus, it must access the original \scm{pop!}\
method that is defined in \scm{stack\%}. The \scm{rename} declaration
does this: it binds a new name, \scm{std-pop!}\ to the original
\scm{pop!}.  Then, \scm{std-pop!}\ is used in the overriding \scm{pop!}.

Objects are instantiated from a class with the \scm{make-object}
procedure. \scm{make-object} always takes a class. Additional
arguments are passed on to the class's initialization procedure. Here
are some object creations using the classes defined above:

\scmline{
  (define stack (make-object stack\%)) \\
\>(define fred (make-object named-stack\% 'Fred)) \\
\>(define joe (make-object named-stack\% 'Joe)) \\
\>(define double-stack (make-object double-stack\%))\\
\>(define safe-stack (make-object safe-stack\%))
}

Note that an extra argument is given to \scm{make-class} for the
\scmclass{named-stack} class; this is because \scmclass{named-stack}
has an initialization procedure that requires one argument (the
stack's name).

The \scm{ivar} and \scm{send} forms are used to access the instance
variables of an object. \scm{ivar} looks up a variable by name. \scm{send}
uses \scm{ivar} to extract a variable's value, which should be a procedure;
it then applies the procedure to arguments. For example, here is a simple
loop that uses the objects created above:

\scmline{
  ((\=ivar\=\ s\=tack push!)\ fred) ; or (send stack push!\ fred)\\
\>(send stack push!\ double-stack)\\
\>(let loop () \\
\>\>(if (not (send stack empty?)) \\
\>\> \>(begin \\
\>\> \>\>(send (send stack pop!)\ print-name) \\
\>\> \>\>(loop)))) \\
}

This loop displays ``Fred'' and ``double-stack'' to the standard
output port.

Although \scmclass{named-stack} has overridden the \scm{name}
declaration of \scmclass{stack}, the \scmclass{stack}-defined value is
still present in \scm{fred} and \scm{joe}. We can access the value
defined in \scmclass{stack} by specifying a class with \scm{ivar}:

\scmline{
  (ivar fred name) ; => Fred\\
\>(ivar frame stack\% name) ; => stack
}

\subsection{Class Creation}

\index{classes!creating}

Classes are created with the following syntax. (Square brackets
indicate optional syntax, and ellipses indicate repeated patterns.)

\scmindex{make-class*}
\scmline{
   (ma\=ke-class* ((\var{superclass-name} \var{superclass-expression}) \dots)\\
\>    \>(\var{instance-variable-declaration-clause}\\
\>    \>\dots)\\
\>    \>[\var{initialization-closure}])
}

\scmindex{make-class}
A special single-inheritance macro is also provided:
\scmline{(make-class \var{superclass-expression} \dots)}
expands to
\scmline{(make-class* ([super \var{superclass-expression}]) \dots)}

The value of each \var{superclass-expression} must be a class from
which this class will be derived. Each \var{superclass-name} must be a
symbol; within the class definition, this name can be used to refer to
a specific superclass. Each \var{superclass-name} must be distinct. If
a \var{superclass-expression} evaluates to the empty list, then an
empty superclass is used.

The \var{instance-variable-declaration-clause}s define
the class's \defterm{instance variables}. The expression
\var{initialization-closure} defines an
\defterm{initialization procedure} that will be applied when an
instance of the class is created (see {\bf \ref{objcreation} Object
Creation}).

\subsubsection{Instance Variables}

Each \var{instance-variable-declaration-clause} has the form:
\scmline{(\var{simple-variable-specifier} \var{instance-var-declaration} \dots)}
or
\scmline{(\var{directed-variable-specifier} \var{superclass-name} 
\var{instance-var-declaration} \dots)}

\var{simple-variable-specifier} and \var{directed-variable-specifier}
are keyword \defterm{variable specifiers}. They are used in variable
declaration clauses to define the properties of instance
variables:
\begin{itemize}
 \item \defterm{Visibility} --- Each instance variable is either
\defterm{private} or \defterm{public}. A private variable can only be
used within the class definition; a public variable can be accessed
from derived classes and from outisde the object, and can be
overridden in a derived class. When a public variable is overridden,
the original value can still be accessed.

 \item \defterm{Generation} --- Each instance variable
declarartion can be either a new value \defterm{definition} or a
\defterm{reference} to an existing variable in a superclass.

 \item \defterm{Binding} --- An instance variable declaration can
\defterm{override} declarations in the superclasses, or provide only a
\defterm{local} value. Private instance variable declarations can
never override superclass declarations.  Public variable access from
outside the object (i.e., using \scm{ivar}) cannot distinguish between
local and overriding declarations; the distinction affects {\em only}
the superclasses, in which an overriding declaration redirects references
and a local declaration does not.

\end{itemize}

Figure~\ref{ssummary} shows how combinations of the above properties
are specified with different variable specifier keyword.

A \var{simple-variable-specifier} can be:

\index{instance variables!accessibility}
\begin{itemize}

 \item \scm{public} \scmindex{public} --- These instance variables can
be read by anyone. A derived class can override \scm{public}
declarations, and \scm{public} declarations override existing
declarations in the superclasses.

 \item \scm{private} \scmindex{private} --- These instance variables
can be accessed only within the class definition. They cannot be
overridden in a derived class and do not override declarations in the
superclasses.

 \item \scm{local} \scmindex{local} --- Like \scm{public}, but declarations
in the superclass are not overidden.

 \item \scm{inherit} \scmindex{inherit} --- Declares \scm{public}
instance variables that must be defined in one of the superclasses.
If the specified variable name is declared in multiple superclasses, a
single declaration is selected by the search path described in section
\ref{searchpath}.  No variables in the superclasses are overridden by
an \scm{inherit} declaration, but an \scm{inherit} declaration can be
overridden.

 \item \scm{rename} \scmindex{rename} --- Similar to \scm{inherit},
but a new name is used to access the value locally. This new name can
only be used within the class definition. A \scm{rename} declaration
accesses the superclass-defined variable value, even if that value is
overridden.

 \item \scm{share} \scmindex{share} --- Like \scm{rename}, but the new
name is publicly accessible. Existing declarations in
superclasses using the new variable name are overridden by
the referenced declaration.

\end{itemize}

A \var{directed-variable-specifier} can be either \scm{inherit-from},
\scm{rename-from}, or \scm{share-from}; these specifiers are refinements
of \scm{inherit}, \scm{rename}, and \scm{share}, repsectively, where
the search path for the inherited instance variable is narrowed to
a single superclass.

\begin{figure}
\begin{center}
\begin{tabular}{|l|l|l|c|c|}
\cline{4-5}
\multicolumn{3}{r|}{Binding} & Local & Override \\
\multicolumn{1}{l}{Visibility} & \multicolumn{2}{l|}{Generation} & & \\
\hline
         & \multicolumn{2}{|l|}{Define} & \scm{private}       & --- \\
\cline{2-5}
 Private & Reference  & simple   & \scm{rename}        & --- \\
\cline{3-5}
         &            & directed & \scm{rename-from}   & --- \\
\hline
         & \multicolumn{2}{|l|}{Define} & \scm{local}  & \scm{public}  \\
\cline{2-5}
 Public  & Reference  & simple   & \scm{inherit}       & \scm{share}    \\
\cline{3-5}
         &            & directed & \scm{inherit-from}  & \scm{share-from} \\
\hline
\end{tabular}
\end{center}
\caption{Variable specifier summary}\label{ssummary}
\end{figure}

There can be multiple clauses with the same variable specifier, and
different variable specifiers clauses can be declared in any order.

In \scm{public}, \scm{private}, and \scm{local} clauses,
each \var{instance-var-declaration} has one of the following forms:
\index{instance variables!declaring}
\scmline{
  (\var{instance-var-name} \var{instance-var-initial-value})\\
\>(\var{instance-var-name})\\
\>\var{instance-var-name}
}

\var{instance-var-name} must be a symbol and 
\var{instance-var-initial-value} is an expression. The scoping rules
for the initial value expressions are decribed below.  When an
initial value expression is not given, \scm{(void)} is assumed. An
instance variable name can be declared only once within a class
definition.

In \scm{inherit} and \scm{inherit-from} clauses, each
\var{instance-var-declaration} is just symbol that is used as
the name of the variable that is inherited.

In \scm{rename}, \scm{share}, \scm{rename-from}, and \scm{share-from}
clauses, each \var{instance-var-declaration} has the form:
\scmline{(\var{instance-var-name} \var{inherited-name})}
Both \var{instance-var-name} and \var{inherited-name} must be a symbol.
\var{instance-var-name} is the new variable name, and \var{inherited-name}
is the name of the variable that is inherited.

\subsubsection{Initial Values}\label{varinit}

The initial value expressions, initialization procedure expression,
and instance variable name handling procedure expression are all
evaluated in a special environment. This environment includes:
\begin{itemize}
\item the environment of the class definition
\item all instance variables of this class
\item the variable \scm{this}, which is bound to the object itself
\scmindex{super}
\item each \var{superclass-name}, which is bound to the value of
the corresponding \var{superclass-expression}
\end{itemize}

The initial value expressions are evaluated at the time that an object
is created. Within each clause, the initial value expressions are
evaluated in the order in which they are defined. The evaluation order
across clauses is unspecified. The initial values are determined
before the initialization procedure and instance variable name
handling procedure expressions are evaluated.

\subsection{Object Creation}\label{objcreation}

\index{objects!creating}

Objects are created with the following syntax:

\scmindex{make-object}
\scmindex{make-object}
\scmline{(make-object \var{class} \var{init-param$_1$} \dots 
\var{init-param$_N$})}

The values of \var{init-param$_1$} \dots \var{init-param$_N$} are passed as
arguments to the class initialization procedure. The default
initialization procedure immediately invokes all of the superclasses's
initialization procedure with the same arguments.

An initialization procedure must invoke each superclass's initialization
procedure (once) by invoking \scm{\var{superclass-name}-init} or 
\scm{apply-\var{superclass-name}-init}:

\scmindex{super-init}
\scmindex{apply-super-init}
\scmline{
  (\var{superclass-name}-init \var{super-init-param$_1$} \dots \var{super-init-param$_M$})\\
\>(apply-\var{superclass-name}-init \var{super-init-param-list})
}

Like the Scheme procedure \scm{apply},
\scm{apply-\var{superclass-name}-init} can take non-list arguments
before the final list argument. When using the single-inheritance
form \scm{make-class}, then the superclass initialization proceudres
are named \scm{super-init} and \scm{apply-super-init}.

Instance variables inherited from a superclass will not be initialized
until the superclass's initialization procedure is invoked. It is an
error to reach the end of an initialization procedure without invoking
all of the (non-null) superclasses's initialization procedures.

\subsection{Instance Variable Access}\label{ivaraccess}

\index{instance variables!accessing}

Within a class definition (e.g., within an instance variable's
initial value expression), instance variables declared in the class
are part of the environment; the instance variable name can be used
directly to get a value, and \scm{set!}\ can be used to set an instance
variable's value.

Instance variable values are accessed from outside an object with
the \scm{ivar} procedure:

\scmindex{ivar}
\scmline{(ivar [\var{class}] \var{object} \var{name})}

The \var{name} is not evaluated: it should be a symbol naming the
desired instance variable. Private variables can never be accessed
using \scm{ivar}. If the specified instance variable cannot be
found, an error is raised.

If \var{class} is specified, the non-overridden instance variable
value is found for the specified class. In this way, the value of an
instance variable can be obtained even if it has been overridden in a
derived class.

The \scm{uq-ivar} procedure is like \scm{ivar}, but the naming argument is
evaluated:
\scmindex{uq-ivar}
\scmline{(uq-ivar [\var{class}] [\var{object}] \var{name-expr})}

The \scm{send} abbreviation is useful for invoking methods:
\scmindex{send}
\scmline{(send \var{object} \var{name} \var{arg} \dots)}
expands to
\scmline{((ivar \var{object} \var{name}) \var{arg} \dots)}

\subsubsection{Generic Procedures}

A \defterm{generic procedure} takes an object and extracts an instance
variable value from the object. Each generic procedure works on
instances of a single class (or instances of derived classes) and
always extracts a value for the same instance variable.

The \scm{make-generic} \scmindex{make-generic} form creates a generic
procedure:

\scmline{(make-generic \var{class} \var{name})}

The expression \var{class} is evaluated and must be a class value. The
expression \var{name} is not evaluated; it must be a symbol that is
the name of an instance variable defined in the class (or one of its
superclasses).

The \scm{uq-make-generic} \scmindex{uq-make-generic} form is like
\scm{make-generic}, but the naming argument is evaluated:
\scmline{(uq-make-generic \var{class} \var{name-expr})}

A generic functionextracts the (potentially) overridden value of an
instance. This is different than \scm{ivar}, which always extracts the
non-overidden value of an instance variable with respect to some
class. Thus, \scm{((make-generic \var{class}
\var{name}) \var{obj})} is not necessarily equivalent to \scm{(ivar \var{obj}
\var{name})}: these expressions can give different results if
\var{obj} is an instance of a class derived from \var{class} in which
\var{name} is locally redeclared (with a \scm{local} or \scm{inherit} 
declaration).

Generic functions are provided mainly for efficiency.  To extract the
value of the same instance variable from multiple objects, it is
usually more efficient to create a single generic function and use it
each time than to use \scm{ivar} each time.

\subsection{Utilities}

\scmindex{object?}
\scm{(object?\ \var{v})} returns \scm{\#t} if \var{v} is a object,
\scm{\#f} otherwise.

\scmindex{class?}
\scm{(class?\ \var{v})} returns \scm{\#t} if \var{v} is a class,
\scm{\#f} otherwise.

\scmindex{object-class}
\scm{(object-class \var{obj})} returns the class of the object \var{obj}.

\scmindex{is-a?}
\scm{(is-a?\ \var{v} \var{class})} returns \scm{\#t} if
\var{v} is an instance of \var{class} (or of a class derived
from \var{class}), and \scm{\#f} otherwise.

\scmindex{subclass?}
\scm{(subclass?\ \var{v} \var{class})} returns \scm{\#t} if \var{v} is 
a class derived from (or equal to) \var{class}, \scm{\#f} otherwise.

\scmindex{ivar-in-class?}
\scm{(ivar-in-class?\ \var{name} \var{class})} returns \scm{\#t} if 
\var{class} (or any of its superclasses) defines an instance variable
\var{name} (where \var{name} is a symbol), \scm{\#f} otherwise. 

Classes and objects can be compared with \scm{eq?}.

\subsection{Superclass Search Algorithm}\label{searchpath}

A special search argorithm is used to find an instance variable in a
tree of class definitions. Like a breadth-first search, the search
algorithm is biased towards declarations in the shallow part of the
tree.  However, like a depth-first search, the search algorithm is
independent of the tree's shape beyond the immediate superclass.
Think of the algorithm as a modified pre-order search, where the
immediate children are checked before recurring on subtrees.

The algorithm first checks each immediate superclass, left-to-right,
for the variable declarartion. If a declaration is found, the search
ends immediately.  Otherwise, for each superclass, left-to-right, the
entire super-tree is checked. Each super-tree is checked using this
algorithm recursively. If a declaration is found in anywhere in a
super-tree, then the search ends.

The following Scheme procedure illustrates the search algorithm:
\scmline{
    (d\=efine find-ivar      \\
\>    \>(l\=ambda (class ivar-name)    \\
\>    \>  \>(if \=(has-immediate-ivar?\ class ivar-name)    \\
\>    \>  \>    \>(get-immediate-ivar class ivar-name)    \\
\>    \>  \>    \>(l\=et ([ivar (ormap \=(l\=ambda (super)    \\
\>    \>  \>    \>  \>                 \>  \>(if \=(has-immediate-ivar?\ super ivar-name)    \\
\>    \>  \>    \>  \>                 \>  \>    \>(get-immediate-ivar super ivar-name)    \\
\>    \>  \>    \>  \>                 \>  \>    \>\#f)))    \\
\>    \>  \>    \>  \>                 \>(get-superclass-list classs))])    \\
\>    \>  \>    \>  \>(if \=ivar    \\
\>    \>  \>    \>  \>    \>ivar    \\
\>    \>  \>    \>  \>    \>(ormap \=(l\=ambda (super)    \\
\>    \>  \>    \>  \>    \>       \>  \>(find-ivar super ivar-name))    \\
\>    \>  \>    \>  \>    \>       \>(get-superclass-list classs)))))))
}


\SECTION{MzScheme Threads}\label{mzprocess}

\index{threads}
MzScheme can support multiple internal threads in the same operating
system process and thread. Each \defterm{thread} is essentially an
invocation of \scm{eval} or \scm{apply}: when a thread is created, it
begins evaluating an expression; when this expression's result is
obtained, the thread is terminated.

When a new thread is created, it can either use the creator thread's
global variable space or get a new global variable space. However,
this global variable space is only a starting point for the
thread:
\begin{itemize}
\item Various mechanisms allow data to be transmitted between any two 
threads,
even if the two threads use separate global variables spaces.
\item Closures are closed over the global variable space in
which they are created. This includes the built-in primitives; for example,
the \scm{eval} procedure in each global variable space always evaluates
its argument in its own space, regardless of the thread that applied
\scm{eval} to it argument.
\end{itemize}
As a result, a thread can execute code that references
globals in a variable space different from the one initially used by
the thread.

In applications that use MzScheme with a top-level event loop (MrEd is
such an application), the main thread is special because it does not
end when \scm{eval} returns. The main thread is usually invoked in to
handle user events; while each event is handled, pending events are
blocked until the event handling is completed. A thread can be
explicitly spawned to handle any event asynchonously, but each event is
received from the queue synchronously.

\index{error handlers} \index{user break polling handlers}
\index{exit handlers} \index{evaluation handlers}
\index{ports}
Each thread has its own original input, output, and error ports (see
section \ref{ports}) and its own error escape handler (see section
\ref{errescapehandler}). Each global variable space has its own evaluation 
handler (see section \ref{evalhandler}), print
handler (see section \ref{printhandler}), error display handler 
(see section \ref{errdisplayhandler}), prompt read handler
(see section \ref{promptreadhandler})
exit handler (see section \ref{exithandler}), and user break polling handler
(see section \ref{breakhandler}).

There are two ways to create a thread:

\begin{itemize}
\item \scmindex{spawn-eval} \scm{(spawn-eval \var{expr} \var{flags} ...)} 
creates a thread with a new global variable space and
evaluates the expression \var{expr}, where \var{expr} is any
S-expression (like an argument to \scm{eval}). Note that any value,
even an unprintable value, can be part of \var{expr}. The new variable
space's handlers are set to the default handlers and the current ports
are initially set to the new thread's original ports. The \var{flags}
arguments are optional; they can be any combination of the following:
\begin{itemize}
\item \scmfirst{'constants} --- built-in procedures are constant
in the new variable space.
\item \scmfirst{'no-constants} --- built-in procedures are {\em not} constant
in the new variable space.
\item \scmindex{set"!-undefined} \scm{'set!-undefined} --- \scm{set!} can
be used on undefined identifiers in the new variable space.
\item \scmindex{no-set"!-undefined} \scm{'no-set!-undefined} --- \scm{set!} 
{\em cannot} be used on undefined identifiers in the new variable space.
\end{itemize}

Later flags take precedence over earlier flags.

\item \scmindex{thread} \scm{(thread \var{thunk})} creates
a new thread that shares the same global variable space as the
creator thread. The new thread invokes \var{thunk} with no
arguments. Although the new thread gets its own ``original''
input, output, and error ports, the new thread inherits the creator
thread's standard ports though the shared global environment.
\end{itemize}

Both \scm{spawn-eval} and \scm{thread} return a thread value. A
thread value encapsulates the state of the thread and provides
access to the thread's ports:

\begin{itemize}
\item \scmindex{thread-write-port} \scm{(thread-write-port \var{thread})}
returns an output port; data written to this port ca be read by
\var{thread} from it's original input port.
\item \scmindex{thread-read-port} \scm{(thread-read-port \var{thread})}
returns an input port; data can be read from this port when \var{thread}
writes to its original output port.
\item \scmindex{thread-readerr-port} 
\scm{(thread-readerr-port \var{thread})}
returns an input port; data can be read from this port when \var{thread}
writes to its original error port.
\end{itemize}

\subsection{Utilities}

\scmindex{thread?} \scm{(thread?\ \var{v})} returns \scm{\#t} if
\var{v} is a thread value or \scm{\#f} otherwise.

\scmindex{atomic} \scm{(atomic \var{thunk})} invokes \var{thunk}
with no arguments. No other threads are allowed to execute until
\var{thunk} returns a result.

\scmindex{sleep} \scm{(sleep \var{time})} causes the current thread
to sleep for at least \var{time} seconds. The \var{time} argument
defaults to 0, allowing other threads to execute. The value of
\var{time} can be non-integral to request a sleep duration to any
precision, but the precision of the actual sleep time is unspecified.

\scmindex{current-thread} \scm{(current-thread)} returns a
thread value for the currently executing thread.

\scmindex{thread-weight} 
\scm{(thread-weight \var{thread})} returns the weight
of the given thread. A \defterm{thread weight} is a positive integer
indicating how much work this thread can perform before another
thread is swapped in. The default weight is 10000.

\scmindex{set-thread-weight"!} 
\scm{(set-thread-weight!\ \var{thread} \var{weight})} sets
the weight of \var{thread}.

Thread values can be compared with \scm{eq?}. 

\SECTION{Triggers}

\index{triggers}
\index{communication}
\index{threads!communication}

A \defterm{trigger} is a value that is used to communicate a signal,
usually between MzScheme threads.
\begin{itemize}
\item \scm{(make-trigger)} \scmindex{make-trigger} creates and returns
a new trigger.
\item \scm{(trigger-hit \var{trigger})} \scmindex{trigger-hit} causes
a signal on \var{trigger}.
\item \scm{(trigger-hit?\ \var{trigger})} \scmindex{trigger-hit?}
returns \scm{\#t} is \var{trigger} has ever been hit or \scm{\#f}
otherwise.
\item \scm{(trigger-block \var{trigger} \var{ever?})} \scmindex{trigger-block}
waits until a signal appears on \var{trigger}. If \var{ever?} is \scm{\#f},
then the signal must appear after \scm{trigger-block} starts waiting. 
The \var{ever?} argument can be omitted; it defaults to \scm{\#f}.
\item \scm{(trigger-callback \var{trigger} \var{closure})} 
\scmindex{trigger-callback} installs \var{closure} to be invoked when
a signal appears on \var{trigger}. \scm{trigger-callback} can only be used
within applications that have a top-level event loop instead of a simple
read-eval-print loop. (MrEd is such an application.) \index{event loop}
\var{closure} will be invoked in the threads that handles events ---
usually the main thread --- in a single-threaded manner. The callback
\var{closure} is invoked only once following signal on the trigger.
\item \scm{(input-port-trigger \var{port} \var{trigger})} \index{ports}
\scmindex{input-port-trigger} sends a signal on \var{trigger} when
a character is ready to be read from \var{port}. A signal is sent only
once. The port is checked by periodically evaluating
\scmindex{char-ready?} \scm{(char-ready?\ \var{port})}. (Therefore,
it may be possible to read characters from \var{port} without a signal
occuring on \var{tigger}. The \scm{input-port-trigger} is most useful
when \var{port} is read only after a signal on \var{tigger}.)
\end{itemize}

Except for \scm{make-trigger}, the return value for each procedure above is
\scm{\#<void>}.

\SECTION{Ports}\label{ports}

\index{ports}
The standard Scheme procedures \scmfirst{current-input-port} and
\scmfirst{current-output-port} have been extended, and another procedure
\scmfirst{current-error-port} port has been added. When called without any
arguments, these procedures return the current input/output/error
port. When called with a single port argument, the given port
becomes the current input/output/error port.

The procedures \scmfirst{thread-input-port},
\scmfirst{thread-output-port}, and \scmfirst{thread-error-port}
take no arguments and return the original input, output and error
ports for the current thread. For the main thread, these ports will
usually be the standard input and output ports created by the
operating system.

\scmfirst{open-input-file} and \scmfirst{open-output-file} can
take an optional argument after the filename that specifies a mode for
the file. This additional argument must be either
\scmfirst{'text} or \scmfirst{'binary}, indicating that the file
should be opened using text mode or binary mode. By default, files are
opened in binary mode.

\scmfirst{open-output-file} can also take an argument
that specifies how to proceed when a file with the specified name
already exists:
\begin{itemize}
\itemsep=-4pt
\parsep=-4pt
\item \scmfirst{'error} --- Raise an error. This is the default.
\item \scmfirst{'replace} --- Remove the old file and write a new one.
\item \scmfirst{'truncate} --- Overwrite the old data.
\item \scmfirst{'append} --- Append to the end of the file.
\end{itemize}

Extra arguments can be passed to \scm{open-output-file} in any order.
Appropriate arguments can also be passed as the last argument(s) to
\scmfirst{call-with-input-file},
\scmfirst{with-input-from-file}, \scmfirst{call-with-output-file}, and
\scmfirst{with-output-to-file}.

\scmindex{pipe} \scm{(pipe)} returns a list of two ports: the first
port is an input port and the second is an output port. Data written
to the output port can be read from the input port.

\subsection{String Ports}

\index{strings!reading and writing}
\scmindex{open-input-string}
\scm{(open-input-string \var{string})} creates an input port that reads
characters from \var{string}. \scmindex{open-output-string}
\scm{(open-output-string)} creates an output port that accumulates the
output into a string; \scm{(get-output-string \var{port})} returns the
string accumulated in such a port. String input and output ports do
not need to be explicitly closed.

Example:
\scmline{
  (define i (open-input-string "hello world"))\\
\>(define o (open-output-string))\\
\>(write (read i) o)\\
\>(get-output-string o) ; => "hello"
}

\subsection{File Ports}

\index{files}
Two special procedures work on file ports:
\begin{itemize}
\item \scm{(flush-output \var{port})} \index{ports!flushing}
\scmindex{flush-output} forces all buffered data in the given file output 
port to be physically written. Buffered data is
automatically flushed after each newline. The standard output and
error ports are automatically flushed before a charater is read from
the standard input port. When called on a non-file port,
\scm{flush-output} takes no action. If \var{port} is omitted, then
the current output port is flushed.
\item \scm{(file-position \var{port})} 
\scmindex{file-position} returns the current read/write position of the 
file port \var{port}, and \scm{(file-position \var{port} \var{pos})}
sets the read/write position to \var{pos}. Calling \scm{file-position}
without a position on a non-file input port returns the number of
characters that have been read from that port. It is an error to call
\scm{file-position} on a non-file output port, or to call
\scm{file-position} with a position on a 
non-file input port.
\end{itemize}

\subsection{Custom Ports}

\index{ports!custom}
Ports with arbitrary control procedures are created with
\scm{make-input-port} and \scm{make-output-port}:

\begin{itemize}
\item \scm{(make-input-port \var{getc} \var{char-ready?}\ \var{close})}
creates an input port. \var{Getc} must be a procedure that takes no
arguments and returns the next input character from the
port. \var{Char-ready?}\ must be a procedure that takes no arguments
and returns \scm{\#t} if a character is ready to be read or \scm{\#f}
otherwise. \var{Close} must a procedure of no arguments; it is called
when the port is closed.

\item \scm{(make-output-port \var{write} \var{close})} creates an output
port. \var{Write} must be a procedure that takes a string and writes it.
\var{Close} must be a  procedure of no arguments; it is called
when the port is closed.
\end{itemize}

Ports created by \scm{make-input-port} and \scm{make-output-port} are
immediately open for reading or writing. If the \scm{close} procedure
does not have any side-affects, then the custom port does not need to
be explicitly closed.

\SECTION{Filesystem Utilities}

\subsection{Pathnames}\label{pathutils}

\index{pathnames}

File and directory paths are specified as strings. Since the syntax
for pathnames can vary across platforms (e.g., under Unix,
directories are separated by ``/'' and ``$\sim$'' can be used as the
initial character to specify a user's home directory, while the Mac
uses ``:'' as a directory separator and ``$\sim$'' is not treated
specially), MzScheme provides tools for portably constructing and
deconstructing pathnames.

\begin{itemize}
\item \scm{(build-path \var{base} \var{subpaths} \dots)}
creates an pathname given a base pathname and any
number of sub-pathname extensions. If \var{base} is an
absolute pathname, the result is an absolute pathname;
if \var{base} is a relative pathname, the result is a relative
pathname. Each \var{subpath} must be either a
relative pathname, a directory name, or the symbol \scm{'up}
(indicating the parent directory). The last \var{subpath} can be a
filename.

Each \var{subpath} and \var{base} can optionally end in a directory
separator. If the last \var{subpath} ends in a separator, it is
included in the resulting pathname.
If an absolute path is provided for any \var{subpath}, then an 
error is raised.

The following examples assume that the current directory is
``/home/joeuser'' for Unix examples and ``My Disk:Joe's Files'' for
Macintosh examples.

\scmline{
  (define p1 (build-path (current-directory) "src" "scheme")) \\
\>  ; UNIX: p1 => "/home/joeuser/src/scheme" \\
\>  ; Macintosh: p1 => "My Disk:Joe's Files:src:scheme" \\
\>(define p2 (build-path 'up 'up "docs" "MzScheme")) \\
\>  ; UNIX: p2 => "../../docs/MzScheme" \\
\>  ; Macintosh: p2 => ":::docs:MzScheme" \\
\>(build-pathname p2 p1) ; Error! p1 is absolute \\
\>(build-pathname p1 p2) \\
\>  ; UNIX: p2 => "/home/joeuser/src/scheme/../../docs/MzScheme" \\
\>  ; Macintosh: p2 => "My Disk:Joe's Files:src:scheme:::docs:MzScheme"
}

\item \scmindex{relative-path?} \scm{(relative-path?\ \var{path})}
returns
\var{\#t} if \var{path} is a relative pathname or \scm{\#f} otherwise. 
The result is only meaningful when \var{path} is a legal pathname.

\item \scmindex{resolve-path} \scm{(resolve-path \var{path})}
returns
a pathname that references the same file or directory as \var{path}.
If \var{path} is a soft link to another pathname, then the referenced
pathname is returned (this may be a relative pathname with respect to
the directory owning \var{path}) otherwise \var{path} is returned.
The result is only meaningful when \var{path} is a legal pathname.

\item \scmindex{expand-path} \scm{(expand-path \var{path})}
returns an expanded version of \var{path}. Under Unix, a user directory
specification using ``$\sim$'' is expanded. Under Windows, if an absolute
pathname is provided without a drive specifier, the result pathname
contains a drive specifier. The result is only meaningful when
\var{path} is a legal pathname.

\item \scmindex{normal-case-path} \scm{(normal-case-path \var{path})}
returns \var{path} with normalized case letters. Under Unix, this procedure 
always returns the input path. Under Windows and on the Macintosh,
the resulting pathname uses only lowercase letters.

\item \scmindex{split-path} \scm{(split-path \var{path})} deconstructs
\var{path} into a smaller pathname and an immediate directory or file name. 
Three values are returned (see section \ref{multiple}):
\begin{itemize}
\item \var{base} is either
 \begin{itemize}
 \item a string pathname, 
 \item \scm{'relative} if \var{path} is an immediate relative directory 
  or filename, or
 \item \scm{\#f} if \var{path} is a root directory.
 \end{itemize}
\item \var{name} is either 
 \begin{itemize}
 \item a string directory name, 
 \item a string file name,
 \item \scm{'up} if the last part of \var{path} specifies the parent
  directory of the preceeding path (e.g., ``..'' under Unix), or
 \item \scm{'same} if the last part of \var{path} specifies the 
  same directory as the  preceeding path (e.g., ``.'' under Unix).
 \end{itemize}
\item \var{must-be-dir?} is \scm{\#t} if \var{path} explicitly
specifies a directory (e.g. with a trailing separator) or \scm{\#f}
otherwise. Note that \var{must-be-dir?}\ does not specify whether
\var{name} is actually a directory or not, buth whether \var{path}
syntactically specified a directory.
\end{itemize}
If \var{base} is \scm{\#f}, then \var{name} cannot be \scm{'up} or
\scm{'same}.  All strings returned for \var{base} and \var{name}
are newly allocated.

\item \scmindex{find-executable-path} \scm{(find-executable-path \var{progpath}
\var{related})} returns an absolute path for the executable \var{progpath}
such that the file or directory \var{related} exists with respect to
the executable's directory. This procedure is used mainly to allow
MzScheme to find the mzlib library (see chapter \ref{mzlib}). The
\var{related} argument is used because \scm{progpath} may refer to a
sequence of soft links under Unix; in this case, \var{related}
determines which directory in the sequence of links is relevant.
\end{itemize}

\subsection{Files}

The file management utilities are:

\begin{itemize}
\item \scmindex{file-exists?} \scm{(file-exists?\ \var{path})} 
returns \scm{\#t} if a file (not a directory) with the path 
\var{path} exists, \scm{\#f} otherwise.

\item \scmindex{delete-file} \scm{(delete-file \var{path})}
deletes the file with pathname \var{path} if it exists.
Returns \scm{\#t} if a file was deleted successfully, \scm{\#f}
otherwise.

\item \scmindex{rename-file} \scm{(rename-file \var{old} \var{new})}
renames the file with pathname \var{old} if it exists to
the pathname \var{new}. Returns \scm{\#t} if a file was renamed 
successfully, \scm{\#f} otherwise.

\ignorethisfornow{
\item \scmindex{file-status} \scm{(file-status \var{path})} 
returns an association list of information
about the file with pathname \var{path} or \scm{\#f} if no
file with the name exists. This association list contains the
following fields:
 \begin{itemize}
 \item \scm{creation-date} --- The file's creation date as a
platform-specific integer
 \item \scm{modify-date} --- The file's last modification date as
a platform-specific integer
 \item \scm{creation-date-string} --- The file's creation date
as a human-readable string
 \item \scm{modify-date-string} --- The file's last modification 
date as a human-readable-string
 \item \scm{creator} (Macintosh only) --- The file's creator as
a four-letter string
 \item \scm{type} (Macintosh only) --- The file's type as a
four-letter string
 \end{itemize}
New fields may be added in the future.
}

\end{itemize}

\subsection{Directories}

The directory management utilities are:

\begin{itemize}
\item \scmindex{current-directory} \scm{(current-directory \var{path})}
sets the current working directory to \var{path} and returns \scm{\#<void>}.  
If no \var{path} argument is provided, the name of the current
working directory is returned. If \var{path} cannot be made the current
directory, an error is raised.

\item \scmindex{directory-exists?} \scm{(directory-exists?\ \var{path})}
returns \scm{\#t} if \var{path} refers to a directory or \scm{\#f}
otherwise.

\item \scmindex{make-directory} \scm{(make-directory \var{path})}
creates a new directory with the pathname \var{path}, returning
\scm{\#t} if a directory is created sucessfully or \scm{\#f} otherwise.

\item \scmindex{delete-directory} \scm{(delete-directory \var{path})}
deletes an existing directory with the pathname \var{path}, returning
\scm{\#t} if the directory is deleted sucessfully or \scm{\#f} otherwise.
The directory must already be empty.

\item \scmindex{directory-list} \scm{(directory-list \var{path})}
returns a list of all files and directories in the directory
specified by \var{path}. If no path is provided, a list of
files and directories in the current directory is returned.

\item \scmindex{filesystem-root-list} \scm{(filesystem-root-list)}
returns a list of all current root directories.
\end{itemize}

\SECTION{Hash Tables}

\index{hash tables}
MzScheme provides efficient built-in hash tables. Key comparisons
use \scm{eq?}.

\begin{itemize}
\item \scmindex{make-hash-table} \scm{(make-hash-table)} creates and
returns a new hash table. A hash table with weakly-held keys
can be created by providing the symbol \scm{'weak} as an
argument to \scm{make-hash-table}.
\item \scmindex{hash-table?} \scm{(hash-table?\ \var{v})} returns
\scm{\#t} if \var{v} was created by \scm{make-hash-table} or
\scm{\#f} otherwise.
\item \scmindex{hash-table-put"!} \scm{(hash-table-put!\ \var{table} 
\var{key} \var{value})} puts the specified value in the table, overwriting
any existing assignments for the key.
\item \scmindex{hash-table-get} \scm{(hash-table-get \var{table} \var{key}
\var{failure-thunk})} gets the value for the specified key. If no
value is found for \var{key}, then \var{failure-thunk} is invoked. The
\var{failure-thunk} argument is optional; if it is not specified, an error 
is reported when no value is found for \var{key}.
\item \scmindex{hash-table-remove"!} \scm{(hash-table-remove!\ \var{table} 
\var{key})} removes the value assignment of \var{key} if it
exists in the table.
\item \scmindex{hash-table-map} \scm{(hash-table-map \var{table} \var{f})}
applies the procedure \var{f} to each element in \var{table}, accumulating
the results into a list. The procedure \var{f} must take two arguments: a key and
a value.
\item \scmindex{hash-table-for-each} \scm{(hash-table-for-each \var{table} 
\var{f})} applies the procedure \var{f} to each element in \var{table}
(for the side-effects of \var{f}) and returns \scm{\#<void>}. The
procedure \var{f} must take two arguments: a key and a value.
\end{itemize}

\SECTION{Weak Boxes}

A \defterm{weak box} is similar to a normal box (see section
ref{boxes}), but a weak box does not keep its contents from being
garbage-collected.

\begin{itemize}
\item \scmindex{make-weak-box} \scm{(make-weak-box \var{v})} returns a 
new weak box that initially contains \var{v}. 

\item \scmindex{weak-box-value} \scm{(weak-box-value \var{wb})} returns
the value contained in the weak box \var{wb}. If the value that was in
\var{wb} has already been garbage-collected, then \scm{\#f} is
returned instead.

\item \scmindex{weak-box?} \scm{(weak-box?\ \var{wb})} returns
\scm{\#t} if \var{wb} is a weak box or \scm{\#f} otherwise.
\end{itemize}


\SECTION{Regular Expressions}

\index{regular expressions}
\index{pattern matching}
\index{strings!pattern matching}
MzScheme provides built-in support for regular expression pattern
matching on strings. The regular expression primitives are implemented
by Henry Spencer's package. Regular expressions are specified as
strings, using the same pattern language as egrep. String-based
regular expressions can be compiled into a regexp value (of type
\scmfirst{\#<regexp>}) for repeated matches using \scmindex{regexp}.

\newcommand{\vbar}[0]{$\mid$}
\newcommand{\jump}[0]{\>\>\vbar\>}
\newcommand{\rxcom}[1]{\>#1}
\newcommand{\rxxcom}[1]{\>\>\>#1}

\begin{figure*}[htb]
{\noindent\hrulefill\par}
\begin{center}
\begin{minipage}{8in}
\begin{tabbing}
\var{Regexp} \=:\=:= \=\var{Regexp} \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \=\\
        \jump \var{Regexp}\vbar\var{Regexp} 
   \rxcom{Match either, try left first} \\
        \jump \var{Pieces} \\
\var{Pieces} \>::= \var{Piece} \\
        \jump \var{Piece}\var{Piece} \rxcom{Match first then second} \\
\var{Piece} \>::= \var{Atom}* 
    \rxxcom{Match \var{Atom} 0 or more times, match longest possible} \\
        \jump \var{Atom}+ 
    \rxcom{Match \var{Atom} 1 or more times, match longest possible} \\
        \jump \var{Atom}? 
    \rxcom{Match \var{Atom} 0 or 1 times, match longest possible}\\
        \jump \var{Atom} \\
\var{Atom} \>::= (\var{Regexp}) \rxxcom{Match sub-expression \var{Regexp}} \\
        \jump [\var{Range}] \rxcom{Match any charcter in \var{Range}}\\
	\jump [\verb+^+\var{Range}] 
            \rxcom{Match any character not in \var{Range}}\\
        \jump .  \rxcom{Match any character} \\
        \jump \verb+^+ \rxcom{Match start of string} \\
        \jump \$ \rxcom{Match end of string} \\
        \jump \var{Literal} \\
\var{Literal} \>::= \var{Normalcharacter} 
   \rxxcom{Not (, ), *, +, ?, [, ], ., $\wedge$, or \$} \\
        \jump $\backslash$\var{Anycharacter} \rxcom{Match \var{Anycharacter}}\\
\var{Range} \>::= ] \rxxcom{Range contains ] only} \\
	\jump - \rxcom{Range contains - only} \\
	\jump ]\var{Lrange} 
    \rxcom{Range contains ] and everything in \var{Lrange}} \\
        \jump -\var{Lrange} 
    \rxcom{Range contains - and everything in \var{Lrange}} \\
        \jump \var{Lrange}- 
    \rxcom{Range contains - and everything in \var{Lrange}} \\
        \jump \var{Lrange} \\
\var{Lrange} \>::= \var{Rliteral} \\
	\jump \var{Rliteral}-\var{Rliteral} 
    \rxcom{Range contains ASCII range inclusive} \\
        \jump \var{Lrange}\var{Lrange} 
    \rxcom{Range contains everyting in both} \\
\var{Rliteral} \>::= \var{Anything except ] and -}\\
\end{tabbing}
\end{minipage}
\end{center}
\caption{Grammar for regular expressions}\label{regexpgram}
{\noindent\hrulefill\par}
\end{figure*}

The format of a regular expression is specified by the grammar in
Figure~\ref{regexpgram}. The regular expression procedures are:

\begin{itemize}
\item \scmindex{regexp} \scm{(regexp \var{str})} takes a string
representation of a regular expression and compiles it into a regexp
value. The other regular expression procedures can take a string or a
regexp as the matching pattern. If a regular expression string will be
used multiple times, it is faster to compile the string to a regexp
and use this for repeated matches.

\item \scmindex{regexp?} \scm{(regexp?\ \var{v})} returns \scm{\#t}
if \var{v} is a regexp or \scm{\#f} otherwise.

\item \scmindex{regexp-match} \scm{(regexp-match \var{pattern} \var{str})}
attempts to match \var{pattern} (a string or a regexp) to a
portion of \var{str}.  If the match fails, \scm{\#f} is returned. If
the match succeeds, a list of strings will be returned. The first
string in this list is the portion of \var{str} that matched
\var{pattern}. If two portions of \var{str} can match \var{pattern},
then the earliest match will be found.

Additional strings are returned in the list if
\var{pattern} contains parenthesized subexpressions; matches for
the subexpressions are provided using the order of the opening
parentheses in \var{pattern}. When sub-expressions occur in different
branches of an ``or'' (\scm{|}), a \scm{\#f} is returned for each
sub-expression that was not used in the match. Whan a sub-expression
can be used mulitple times for a match (e.g., a sub-expression is
followed by ``*''), then the last match found for the sub-expression
is returned in the list.

\item \scmindex{regexp-match-positions}
\scm{(regexp-match-positions \var{pattern} \var{str})} is like
\scm{regexp-match}, but instead of returning a list of strings, a
list of number pairs is returned. Each pair of numbers refers to the
range of characters in \var{str} that matched the corresponding
(sub-)expression.

\item \scmindex{regexp-replace} 
\scm{(regexp-replace \var{pattern} \var{src} \var{insert})} performs
a match using \var{pattern} on \var{src} and then returns a string in
which the matching portion of \var{src} is replaced with \var{insert}.
If \var{pattern} matches no part of \var{src}, then \var{src} is
returned unmodified.

If \var{insert} contains ``\&'', then ``\&'' is replaced with the matching
portion of \var{src} before it is substituted into \var{src}.  If
\var{insert} constains ``$\backslash$\var{n}'', then is is replaced with
the \var{n}th matching sub-expression from \var{src}. (``\&'' and
``$\backslash$0'' are synonymous.) If the \var{n}th sub-expression was
not used in the match or if \var{n} is greater than the number of
sub-expressions in \var{pattern}, then ``$\backslash$\var{n}'' is
replaced with the empty string.

\end{itemize}

Examples:
\scmline{
  (define r (regexp "(-[0-9]*)+")) \\
\>(regexp-match r "a-12--345b") ; => ("-12--345" "-345") \\
\>(regexp-match-positions r "a-12--345-b") ; => ((1 . 9) (5 . 9)) \\
\>(regexp-match "x+" "12345") ; => \#f \\
\>(regexp-replace "me" "me casa" "su") ; => "su casa" \\
\>(define r2 (regexp "([Mm])e ([a-zA-Z]*)")) \\
\>(define insert "$\backslash\backslash$1y $\backslash\backslash$2") \\
\>(regexp-replace r2 "Me Casa" insert) ; => "My Casa" \\
\>(regexp-replace r2 "me cerveza" insert) ; => "my cerveza"
}

\SECTION{Flow Control}

\index{continuations}
\index{flow control}
\scmindex{call/cc}
\scmindex{let/cc}
\scmindex{call-with-current-continuation}
MzScheme supports fully re-entrant
\scm{call-with-current-continuation} (or \scm{call/cc}). The binding
form \scm{let/cc} has the form
\scmline{(let/cc \var{k} \var{body})}
which expands to
\scmline{(call/cc (lambda (\var{k}) \var{body}))}
A continuation can only be invoked from the thread (see {\bf
\ref{mzprocess} MzScheme Threads}) in which it was
obtained. Multiple return values can be passed to a continuation; see
section \ref{multiple} for details.

\index{continuations!escaping}
\scmindex{call/ec} \scmindex{let/ec} \scmindex{catch}
\scmindex{call-with-escaping-continuation}
In addition to regular \var{call/cc}, MzScheme provides
\scm{call-with-escaping-continuation} (or \scm{call/ec}) and
\scm{catch} (or \scm{let/ec}, but \scm{catch} is preferred). A
continuation obtained from \scm{call/ec} or
\scm{catch} can only be used to {\em escape} from the expression; i.e., 
the continuation is only valid until the \scm{call/ec} or \scm{catch} 
expression returns a value. The application of \scm{call/ec}'s argument
is not a tail call. \index{tail calls}

Escaping continuations are provided for two reasons: 1) they are
significantly cheaper than full continuations; and 2) full
continuations are not allowed to cross certain boundaries (e.g., error
handling) that escaping continuations can safely cross.

\scmindex{dynamic-wind}
MzScheme supports the the usual \scm{dynamic-wind}
procedure. (\scm{dynamic-wind} \var{pre-thunk} \var{value-thunk}
\var{post-thunk}) applies its three thunk arguments in order.
The value of the \scm{dynamic-wind} expression is the value returned
by \var{value-thunk}. The \var{pre-thunk} procedure will be invoked
before calling \var{value-thunk} and \var{post-thunk} will be invoked after
\var{value-thunk} returns. The special properties of \scm{dynamic-wind} are
manifest when control jumps into or out of \var{value-thunk} (either
due to an error or a continuation invocation): every time control jumps
into \var{value-thunk}, \var{pre-thunk} will be invoked, and
every time control jumps out of \var{value-thunk}, \var{post-thunk} 
will be invoked.

\SECTION{Multiple Return Values}\label{multiple}

MzScheme provides support for mutliple return values. Briefly, the
procedure \scm{values} provides a mechanism for returning multiple
values, and \scm{call-with-values} and \scm{let-values} provide
mechanisms for binding multiply-returned values to identifiers.
Multiple values can also be returned by applying a continuation
to multiple arguments.

\begin{itemize}
\scmindex{values}
\item \scm{(values \var{args} \dots)} returns the given \var{args}
as mulitple values. If \var{args} is not a single value, then the
result of this expression must be used in a multiple-value context,
However, \scm{(values \var{v})} is always equivalent to \var{v}.

\scmindex{call-with-values}
\item \scm{(call-with-values \var{producer} \var{consumer})} invokes
\var{producer} and passes the result to \var{consumer}. The
\var{producer} argument must be a procedure that takes no arguments and 
returns one or more values. The \var{consumer} argumentmust be a procedure 
that takes the same number of arguments as returned by \var{producer}.
The result of the \scm{call-with-values} expression is the result of the 
\var{consumer} application.

\scmindex{let-values}
\item \scm{(let-values ([\var{binding} \var{value}] \dots) \var{body})}
is a binding form for multiple return values. Each \var{binding}
speificies identifiers to receieve the multiple return values of
\var{value}. If \var{binding} is a symbol, then the mulitply-returned
values are placed in a list. If \var{binding} is a list of symbols,
then each symbol receives one of the multiply returned values; the
number of symbols in \var{bindings} must then match the number of
values returned by \var{values}. An improper list can be used for
\var{binding} (as in the formal arguments of a \scm{lambda} form), to
collect extra return values into a list. If mulitple
\var{binding}-\var{values} pairs are given, the bindings from one pair
are visible in the next pair (similar to
\scm{let*}).
\end{itemize}

Examples:
\scmline{
  (values 1) ; => 1 \\
\>(values 1 2) ; => Error - returned 2 values to single-value context\\
\>(values) ; => Error - returned 0 values to single-value context\\
\>(c\=all-with-values \\
\>  \>(lambda () (values 1 2)) \\
\>  \>(lambda (x y) y)) ; => 2 \\
\>(l\=et-values ([(x y) (values 1 2)]) y) ; => 2 \\
\>(l\=et-values ([z (values 1 2)]) z) ; => (1 2) \\
\>(l\=et-values (\=[z (values 1 2)] \\
\>  \>           \>[(x y) (apply values z)]) \\
\>  \>y) ; => 2 \\
\>(l\=et-values ([(x y) (let/cc k (k 3 4))]) y) ; => 4 \\
\>(c\=all-with-values \\
\>  \>(lambda () (values 'hello 1 2 3 4)) \\
\>  \>(l\=ambda (s . l) \\
\>  \>  \>(format "~s = ~s" s l))) ; => "hello = (1 2 3 4)" \\
}

\SECTION{Arity}

\scmindex{arity}
\scm{(arity \var{f})} returns information
about the number of arguments that the procedure \var{f} takes. The
result \var{a} of \scm{(arity \var{f})} is either:

\begin{itemize}
\item A number --- The procedure always takes exactly \var{a} arguments.
\item An \scm{arity-at-least} structure --- The procedure takes
\scm{(arity-at-least-value \var{a})} or more arguments.
\scmindex{arity-at-least} \scmindex{arity-at-least-value}
\scmindex{arity-at-least?}
\item A list containing numbers and \scm{arity-at-least} structures --- The
procedure takes any number of arguments that can match one of the
arities in the list.
\end{itemize}

For example:
\scmline{
  (arity cons) ; => 2 \\
\>(arity list) ; => \#<structure:arity-at-least> \\
\>(arity-at-least?\ (arity list)) ; => \#t \\
\>(arity-at-least-value (arity list)) ; => 0 \\
\>(arity-at-least-value (arity (lambda (x .\ y) x))) ; => 1 \\
\>(arity (case-lambda [(x) 0] [(x y) 1])) ; => (1 2)
}

\CHAPTER{Additional Facilities}

\SECTION{Input Parsing}\label{parsing}

MzScheme's input parser follows these non-standard rules:
\begin{itemize}
\item Square brackets (``[''  and ``]'') can always be used in place of
parentheses. An open square bracket must be closed by a closing
square bracket.

\index{vectors}
\item Vector constants can be unquoted, and a vector size can
be speified between the ``\#'' and opening parenthesis. If the
specified size is larger than the number of vector elements that
are provided, then the last specified element is used to fill the
remaing vector slots. If no vector elements are specified, the vector
is filled with zeros.

\index{boxes}
\scmindex{\#\&}
\item Boxed constants can be created using \scm{\#\&}. The S-expression 
following \scm{\#\&} is treated as a quoted constant and put into the
new box.  (Spaces following the \scm{\#\&} are ignored.)  Box reading
is controlled with \scmfirst{read-accept-box}; this procedure takes zero
arguments to return the current mode, or one Boolean argument to set the mode.
Box reading is on by default.

\index{graphs}
\scmindex{\#\var{n}=}
\scmindex{\#\var{n}\#}
\item S-expressions with shared stucture are expressed using 
\scm{\#\var{n}=} and \scm{\#\var{n}\#}. See section \ref{sexpressions}.

\index{symbols} \scmindex{|} \index{$\backslash$}
\item Symbols containing non-standard
characters (including spaces) can be expressed using an escaping
backslash ($\backslash$) or quoting vertical bars ($\mid$).  A
backslash preceeding any character includes that character in the
symbol literally; double backslashes produce a single backslash in the
symbol. Also, one or more symbol characters can be quoted using
vertical bars. Quoting bars can be used for any part of a symbol, or
the whole symbol can be quoted. Backslashes and quoting bars can be
mixed within a symbol, but a backslash is {\em not} a special
character within a pair of quoting bars. Input syntax containing a
backslash or vertical bars will never be treated as a numerical
contant.

Examples:
\begin{itemize}
\item \scm{(quote a$\backslash$(b)} produces the same 
symbol as \scm{(string->symbol "a(b")}.
\item \scm{(quote a$\backslash$ b)}, \scm{(quote |a b|)}, 
and \scm{(quote a| |b)} all produce
the same symbol as \scm{(string->symbol "a b")}.
\item \scm{(quote |a||b|)} is the same as \scm{(quote ab)}.
\item \scm{(quote 10)} is the fixnum 10, but \scm{(quote |10|)} produces 
the same symbol as \scm{(string->symbol "10")}.
\end{itemize}

Whether a vertical bar is used as a special or normal symbol character
is controlled with \scmfirst{read-accept-bar-quote}; this procedure
takes zero arguments to return the current mode, or one Boolean
argument to set the mode.  Vertical bar quotes are on by default.


\scmindex{\#<>}
\item Expressions of the form \scm{\#<\var{x}>} are
read as special \defterm{type symbol} values (they are not
symbols). \index{type symbols} This feature insures that all printed
Scheme values can be handled by \scm{read}.  The \var{x} part can be
any expression that is acceptable as a symbol and \var{x} can contain
(unquoted) spaces.

For any \var{x}, \scm{(eq?\ \#<\var{x}> \#<\var{x}>)}
will be \scm{\#t}, but \scm{\#<\var{x}>} is not \scm{equal?} to
anything else. \scm{(quote \#<\var{x}>)} is the same as
\scm{\#<\var{x}>}. 
\scmindex{type-symbol?} \scm{(type-symbol?\ \var{x})} returns \scm{\#t}
if \var{x} is a type symbol, or \scm{\#f} otherwise. Type symbol
reading is controlled with \scmfirst{read-accept-type-symbol}; this
procedure takes zero arguments to return the current mode, or one
Boolean argument to set the mode. Type symbol reading is on by default.

\scmindex{\#\%}
\item Expressions of the form \scm{\#\%\var{x}} are symbols. See
section \ref{keywords}.

\scmindex{\#`}
\item Expressions beginning with \scm{\#`} are interpreted as
compiled MzScheme code. See section \ref{compilation}.

\item Multi-line comments can be started with \scm{\#|} and
terminated with \scm{|\#}. Comments of this form can be nested
arbitrarily.

\scmindex{load}
\scmindex{\#"!}
\item If the first line of a \scm{load}ed file begins with
\scm{\#!}, it is ignored. If an ignored line ends with
a backslash ($\backslash$), then the next line is also ignored.

\end{itemize}

\SECTION{Output Printing}

MzScheme's printer follows these non-standard rules:
\begin{itemize}
\item Boxes can be printed with the \scm{\#\&} notation (see section
\ref{parsing}). When box printing is off, all boxes are printed as 
\scm{\#<box>}. Box printing
is controlled with \scmfirst{print-box}; this procedure takes zero
arguments to return the current mode, or one Boolean argument to set
the mode. Box printing is on by default.

\item Structures can be printed as vectors. In the vector, the first
item will be a symbol of the form \scm{structure:\var{s}} --- where 
\var{s} is the name of the structure --- and the remaining elements are
the elements of the structure. When structure printing is off,
structures are printed as \scm{\#<structure:\var{s}>}. Structure printing
is controlled with \scmfirst{print-struct}; this procedure takes zero
arguments to return the current mode, or one Boolean argument to set
the mode. Structure printing is off by default.

\item S-expressions with shared stucture can be printed using 
\scm{\#\var{n}=} and \scm{\#\var{n}\#}. See section \ref{sexpressions}.

\item Symbols containing spaces or special charaters are printed
using escaping backslashes and quoting vertical bars. Symbols are
quoted with vertical bars when they would otherwise print the same
as a numerical constant. See section \ref{parsing}.

\end{itemize}

\SECTION{Graphs}\label{sexpressions}

\index{graphs} \index{expressions!shared structure}
\scmindex{\#\var{n}=}
\scmindex{\#\var{n}\#}
MzScheme can read and print \defterm{graphs}, S-expressions with
shared structure (e.g., a cycle).  Graphs are described by tagging the
shared structure once with \scm{\#\var{n}=} (using some number
\var{n}) and then referencing it later with \scm{\#\var{n}\#}.  For
example, this S-expression descibes the infinite list of ones:
\scmline{\#0=(1 . \#0\#)}
If this graph is entered into MzScheme's read-eval-print loop,
then MzScheme's compiler will loop forever, trying to
compile an infinite expression. In contrast, this expression defines
\scm{ones} to the infinite list of ones, using \scm{quote} to hide 
the infinite list from the compiler:
\scmline{(define ones (quote \#0=(1 . \#0\#)))}
A tagged structure can be referenced multiple
times. Here, \scm{v} is defined to be a vector containing the same
\scm{cons} cell in all three slots:
\scmline{(define v \#(\#1=(cons 1 2) \#1\# \#1\#))}
A tag \scm{\#\var{n}=} must appear to the left of all references
\scm{\#\var{n}\#}, and all references must appear in the same S-expression
as the tag. By default, MzScheme's printer will display \scm{v} without
showing the shared structure:
\scmline{\#((1 . 2) (1 . 2) (1 . 2))}

Graph reading and printing are controlled with
\scmfirst{read-accept-graph} and \scmfirst{print-graph}; these
procedures take zero arguments to return the current mode, or one
Boolean argument to set the mode. Graph reading is on by default,
and graph printing is off by default. When the printer
encounters an graph containing a \index{cycles} cycle, graph
printing is automatically enabled (temporarily).

\SECTION{Macros}

\index{macros}
\scmindex{defmacro}
\scmindex{letmacro}

Global macros can be defined with \scm{defmacro}:
\scmline{(defmacro \var{name} \var{formals} \var{macro-body} \dots)}

where \var{formals} and \var{macro-body} are as in a \scm{lambda}
expression. When the macro is applied, the (unevaluated) argument
expressions are passed to the closure defined by \var{formals} and
\var{body}. The result should be a new S-expression that can be 
evaluated (or expanded further). Macros defined with \scm{defmacro}
are not hygenic.

For example, the usual \scm{when} macro can be defined as follows:
\scmline{
  (d\=efm\=a\=cro when (test . body)\\
\>  \>`(if ,test\\
\>  \>   \>(begin\\
\>  \>   \>\>,@body)))
}

Local macros can be defined with \scm{letmacro}:
\scmline{(letmacro \var{name} \var{formals} \var{macro-body} \var{body} \dots)}

This syntax is similar to \scm{defmacro}, except that the macro body
must be a single expression, and the macro is only available in
\var{body}. The result of a \scm{letmacro} expression is the value of
\var{body}. Note that the environment for \var{macro-body} includes
only global variables and the arguments bound by \var{formals}.

When a \scm{defmacro} statement is embedded in a closure, it is
transformed into a \scm{letmacro} expression, where the body of the
closure following the \scm{defmacro} statement becomes the body
of the \scm{letmacro} expression.

\index{macros!expanding}
\scmindex{expand-defmacro} \scmindex{expand-defmacro-once}
The procedure \scm{expand-defmacro} takes a single (quoted) expression and
expands all macros in the expression. The procedure \scm{expand-defmacro-once}
is similar: it expands macros, but does not try to expand the result
of an expansion.  Only the syntactic forms shown in
Figure~\ref{survive} will occur in a fully expanded
expression.\footnote{If MzScheme is extended with new primitive syntax,
those forms may appear in expanded expressions.}

\begin{figure}
\begin{center}
\begin{tt}
\fbox{
\begin{tabular}{ll}
lambda $\;\;$ & case-lambda \\
let &  letrec* \\
letrec & defmacro \\
define & letmacro \\
quote & define-struct \\
if & let-struct \\
begin & make-class*  \\
set! &  \\
delay & \\
\end{tabular}
}
\end{tt}
\end{center}
\caption{Syntactic forms after \scm{expand}ing}\label{survive}
\end{figure}

\SECTION{Global and Constant Names}\label{constant}

\index{global variables}
\scmindex{defined?}
\scmindex{bound?}
\scmindex{undefine}

\scm{(defined?\ \var{name})}, where \var{name} is a symbol, returns \scm{\#t}
if a global variable is defined with the name \var{name}, or \scm{\#f}
otherwise. The procedure \scm{bound?}\ is a synonym for \scm{defined?}.

\scm{(undefine \var{name})}, where \var{name} is a symbol, causes \var{name} to
be undefined if it was defined previously.

\scmindex{define} \scmindex{letrec*}
When a \scm{define} statement is embedded in a closure, it is
transformed into a \scm{letrec*} statement\footnote{The \scm{letrec*}
form is equivalent to \scm{letrec}, except that the value expressions
for \scm{letrec*} bindings are always evaluated in order.}  where the
remainder of the closure (i.e., the statements following the
\scm{define}) are moved to the body of the \scm{letrec*}. Multiple
adjacent \scm{define} statements are collected into a single
\scm{letrec*} transformation.

\index{constant names}
\index{names!constant}
\scmindex{set"!} \scmindex{define}

A constant name in MzScheme is a global variable name that cannot be
changed by \scm{define}, \scm{undefine}, or \scm{set!}\ once it has been
defined.  However, constant names can still be used for variables
bound by \scm{lambda}, \scm{let}, etc.

New constant names can be declared with the following syntax:
\scmindex{constant-name}
\scmline{(constant-name \var{s})}
If the symbol \var{s} has not been globally defined before
\scm{constant-name} is invoked, then \var{s} can still be defined
once.  Constance is a property of a global variable name (within a
single global variable space), not a variable's value.

For example:

\scmline{
  (define x 2)\\
\>(define x (box 5)) ; OK\\
\>(constant-name 'x)\\
\>(define x 9) ; Bad!\\
\>(set!\ x 5) ; Bad!\\
\>(let ([x 0]) (set! x 1)) ; OK\\
\>(set-box!\ x 7) ; OK\\
\>(constant-name 'y) ; assuming y is not yet defined...\\
\>(define y 8) ; OK
}

The procedure \scmfirst{constant-name-all-globals} makes all currently
\scm{define}d names constant. Any number of symbol arguments can be
provided to \scm{constant-name-all-globals}; the global names for
these symbols will {\em not} be made constant (although they may
be constant already).

\SECTION{Keywords}\label{keywords}

\index{keywords}
Keyword names cannot be redefined or used as local variable names.
Primitive syntax names (the ones listed in Figure~\ref{survive}) are
reserved keywords, as are \scm{cond}, \scm{and}, \scm{or}, \scm{case},
\scm{let*}, \scm{do}, and \scm{quasiquote}. For every built-in procedure 
\var{x}, there is a corresponding keyword \scm{\#\%\var{x}} that accesses 
the same value. Built-in syntactic forms that are not themselves
keywords also have corresponding \scm{\#\%} keywords.

There are no other global keywords. Local keywords --- such as
\scm{else} within a \scm{cond} expression or \scm{public} within a
\scm{make-class*} expression --- are not globally enforced. This means, for
example, that the name \scm{else} may be bound to a value, but
\scm{else} as the first part of a \scm{cond} clause will not reference
such a binding.

A new keyword can be declared with \scmindex{keyword-name}
\scm{(keyword-name \var{s})}, where \var{s} is a symbol. Once
a symbol \var{s} has been designated as a keyword, it cannot be bound
locally or globally. Keywords declared this way are local to the
global variable space.


\SECTION{Evaluation Handler}\label{evalhandler}

\scmindex{eval} \scmindex{load} \scmindex{read-eval-print-loop} 
\index{evaluation handlers}
An \defterm{evaluation handler} is invoked by \scmfirst{eval},
\scmfirst{read-eval-print-loop}, and \scmfirst{load} to evaluate Scheme
expressions. An evaluation handler takes one argument, an S-expression
to be evaluated, and returns the value of the expression (possibly multiple
values; see section \ref{multiple}).
\begin{itemize}
\scmindex{current-eval}
\item \scm{(current-eval)} returns the current evaluation handler.
\item \scm{(current-eval \var{f})} sets the handler to \var{f}.
\end{itemize}
The default evaluation handler expands, compiles, and executes the
input expression in the top-level environment.
\index{evaluation order}
In an application, the applied expression and the argument expressions
are always evaluated left-to-right.

\SECTION{Print Handler}\label{printhandler}

\scmindex{read-eval-print-loop} \index{print handlers}
A \defterm{print handler} is invoked by \scmfirst{read-eval-print-loop}
to print Scheme expressions. A print handler takes one argument, 
a value to be printed. The handler's return value is ignored.
\begin{itemize}
\scmindex{current-print}
\item \scm{(current-print)} returns the current print handler.
\item \scm{(current-print \var{f})} sets the handler to \var{f}.
\end{itemize}
The default print handler \scm{display}s the value to the current output
port and prints a newline.

\SECTION{Prompt Read Handler}\label{promptreadhandler}

\scmindex{read-eval-print-loop} \index{prompt read handlers}
A \defterm{prompt read handler} is invoked by \scmfirst{read-eval-print-loop}
to print the prompt and read input Scheme expressions. A prompt read handler 
takes no arguments and returns an S expression.
\begin{itemize}
\scmindex{current-prompt-read}
\item \scm{(current-prompt-read)} returns the current prompt read handler.
\item \scm{(current-prompt-read \var{f})} sets the handler to \var{f}.
\end{itemize}
The default prompt read handler prints ``$>$ '' and returns the result
of \scm{(read)}.

\SECTION{Errors}

\index{errors}
\scmindex{error}

Use the procedure \scm{error} to raise a run-time error. The \scm{error}
procedure can be invoked three ways:
\begin{itemize}
\item \scm{(error \var{message})} where \var{message} is a symbol.
This creates a message string of the form ``error: \var{message}''.
\item \scm{(error \var{message} \var{value$_1$} \dots)}
where \var{message} is a string. Theis creates a message string
by concatenating \var{message} with string versions of the \var{value}s
(as printed by \scm{write}). A space is inserted before each \var{value}.
\item \scm{(error \var{proc} \var{message} \var{value$_1$} \dots)}
where \var{proc} is a symbol and \var{message} is a string. 
This creates a message string by evaluating
\scmline{
(format (string-append "$\sim$s: " \var{message}) 
  \var{proc} \var{value$_1$} \dots)}
(The built-in \scm{format} and \scm{string-append} are always used.)
\end{itemize}

The constructed message string is passed on to the current error display
handler (see below) and then the current error escape handler (see
below) is called.

\subsection{Error Display Handlers}\label{errdisplayhandler}

\index{error display handlers}
\scmindex{error-display-handler}
Errors are reported by an \defterm{error display handler} that is
called by \scm{error}:
\scmline{(\var{error-handler-proc} \var{string-message})}
The argument to \var{error-handler-proc} is a complete error message
to be displayed. The default error display handler \scm{display}s
\var{string-message} to the current error port.

\begin{itemize}
\item \scm{(error-display-handler)} returns the current error display handler.
\item \scm{(error-display handler \var{f})} sets the handler to \var{f}.
\end{itemize}

Only invoke an error display handler directly when chaining from
one error display handler to another. To raise a run-time error, use
\scm{error} instead.

\subsection{Error Escape Handlers}\label{errescapehandler}

\index{error escape handlers}
\scmindex{error-escape-handler}
Special control flow for errors is perfomred 
an \defterm{error escape handler} that is called by \scm{error}. An
error escape handler takes no arguments and must escape from the
expression that caused the error.

\begin{itemize}
\item \scm{(error-escape-handler)} returns the current error escape handler.
\item \scm{(error-escape-handler \var{f})} sets the handler to \var{f}.
The procedure \var{f} cannot invoke a full continuation that was
created prior to the error, but it {\em can} invoke an escaping
continuation.
\end{itemize}

Only invoke an error escape handler directly when chaining from
one error escape handler to another. To raise a run-time error, use
\scm{error} instead.

\SECTION{Exit Handlers}\label{exithandler}

\index{exiting} \index{exit handlers}
\scmindex{exit-handler} \scmindex{exit}
An \defterm{exit handler} is invoked when MzScheme's \scm{exit}
procedure is called. An exit handler is a closure that takes one integer
argument: the exit code passed to \scm{exit} (or the default, 0).
\begin{itemize}
\item \scm{(exit-handler)} returns the current exit handler.
\item \scm{(exit-handler \var{f})} sets the handler to \var{f}.
\end{itemize}
The default exit handler shuts down MzScheme. (When MzScheme is used
within another application, such as MrEd, the default exit handler
may be remapped internally.)

\SECTION{User Breaks}\label{breakhandler}

\index{user break polling handlers}
A \defterm{user-break polling handler} is periodically invoked to
determine if the user wants to escape from the current evaluation.
(For example, a user-break polling handler might check to see if
Ctl-c was pressed.) A user-break polling handler takes no arguments
and returns \scm{\#f} to continue to current evaluation.

\scmindex{user-break-poll-handler}
\begin{itemize}
\item \scm{(user-break-poll-handler)} returns the current user-break polling
handler.
\item \scm{(user-break-poll-handler \var{f})} sets the user-break polling 
handler to \var{f}.
\end{itemize}


\scmindex{break-enabled}
User-break polling is initially disabled in some applications that use
MzScheme. \scm{(break-enabled)} returns \scm{\#t} when user-break polling is
enabled or \scm{\#f} otherwise. \scm{(break-enabled \var{v})} disables 
user-break polling if \var{v} is \scm{\#f} or enables polling otherwise. 
\scmindex{dynamic-enable-break} \scm{(dynamic-enable-break \var{thunk})} invokes 
\var{thunk} with breaking allowed; on exit from \var{thunk}, the enable state is
restored.\footnote{\scm{dynamic-enable-break} cannot be implemented
with \scm{dynamic-wind} and \scm{break-enabled} becuase the user could
break during the evaluation of \scm{enable-break}.}

\SECTION{Compilation}\label{compilation}

\index{compiling}
Normally, compilation happens automatically: when an S-expression is
evaluated, it is first compiled and then the compiled code is
executed.  Howevere, MzScheme can also write and read compiled
MzScheme code. MzScheme can read compiled code somewhat faster than
reading S-expression code and compiling it, so compilation can be used
to speed up program loading. The procedure \scm{compile-file} is sufficient 
for most compilation purposes.

\scmindex{compile-file}
\scm{(compile-file \var{src} \var{dest} \var{expand-load?})}
compiles the Scheme file \var{src} and saves the compiled code to
\var{dest}. The \var{src} and \var{dest} arguments are usually
filenames\footnote{A MzScheme compiled code file should
use the extension ``.zo'', \index{.zo} but this convention is not
enforced.}; \var{src} can also be an input port and \var{dest} can
be an output port. If an input or output port is provided, the port is
{\em not} closed when compilation is finished.
If \var{dest} is a filename and the file already exists, 
it will be replaced.
\var{expand-load?} is an optional argument that defaults to 
\scm{\#f}; if it is not \scm{\#f}, then top-level \scmfirst{load}
statements in the \var{src} file are expanded and compiled into
\var{dest}. \index{macros} All macros used in the source file must 
either be defined at
compile-time, defined using a top-level \scmfirst{defmacro} statement
in the source file (or in an \scm{load}ed file that is expanded), or
defined locally in a \scm{letmacro} expression.

\scmindex{compile}
\scm{(compile \var{expr})} compiles \var{expr}, where \var{expr} is 
any S-expression that can be passed to \scm{eval}. The result is a
compiled expression Scheme value. This value can be passed to
\scm{eval} to evaluate the compiled expression.

When a compiled expression is written, it starts with \scm{\#`}.
These expressions are essentially assembly code for the MzScheme
interpreter. Never ask MzScheme to evaluate an expression starting
with \scm{\#`} unless \scm{compile} generated the expression.
To keep users from accidentally specifying bad
instructions, \scm{read} will not accept expressions beginning
with \scm{\#`} unless it is specifically enabled.
\scmindex{read-accept-compiled} \scm{(read-accept-compiled)} returns
\scm{\#t} if \scm{read} currently allows compiled expressions,
or \scm{\#f} otherwise. \scm{(read-accept-compiled \var{on?})}
disables compiled expression reading if \var{on?} is \scm{\#f}, or
enables it otherwise.  When the \scm{load} procedure is used to load a
MzScheme file, compiled expression reading is automatically enabled
while the the file is read.

\SECTION{Dynamic Extensions}

\scmindex{load-extension }
A dynamically-linked extension library is loaded into MzScheme with
\scm{(load-extension \var{filename})}. The separate document {\it
Embedding and Extending MzScheme} contains information about writing
MzScheme extensions.


\SECTION{Operating System Processes}

\index{processes}
\index{subprocesses}
\scmindex{system}
\scm{(system \var{command})}
executes a shell command synchonously (i.e., the call to
\scm{system} does not return until the subprocess has ended). The \var{command}
argument must be a string. If the command succeeds, the return value is
\scm{\#t}, or \scm{\#f} otherwise.

\scmindex{system*}
\scm{(system* \var{command} \var{argument$_1$} \dots \var{argument$_n$})}
is like \scm{system}, but \var{command} is a filename that is executed
directly (instead of through a shell command) and passed the specified
string arguments.

\scmindex{process}
\scm{(process \var{command})}
executes a shell command asynchonously. If the subprocess is launched
successfully, the result is a list of four values: 
\begin{itemize}
\item an input port piped from the subprocess's standard output,
\item an output port piped to the subprocess standard input, 
\item the system process id of the subprocess, and
\item an input port piped from the subprocess's standard error.\footnote{
The standard error port is placed last for compatibility with other
Scheme implementations.}
\end{itemize}

\scmindex{process*}
\scm{(process* \var{command} \var{argument$_1$} \dots \var{argument$_n$})}
is like \scm{process}, but \var{command} is a filename that is executed
directly.

\SECTION{Miscellaneous Extensions}

\newcommand{\dogenscmutilsection}[3]{
\vspace{.25in}
\scmindex{#3}
\noindent
{\tt #1} \hfill {\rm (#2)}
\nopagebreak
}

\newcommand{\doscmutilsection}[4]{
\dogenscmutilsection{(#1\var{#2})}{#3}{#4}
}

\newcommand{\scmutilsection}[3]{
\doscmutilsection{#1\ }{#2}{#3}{#1}
}
\newcommand{\scmutilsectionzero}[2]{
\doscmutilsection{#1}{}{#2}{#1}
}
\newcommand{\scmutilsectionwithindex}[4]{
\doscmutilsection{#1\ }{#3}{#4}{#2}
}

\newcommand{\scmutilsectionvar}[2]{
\dogenscmutilsection{#1}{#2}{#1}
}

\scmutilsection{add1}{n}{procedure}

Returns \var{n} + 1.


\scmutilsection{andmap}{f lists \dots}{procedure}

The arguments are as with \scm{map}. When an application of
\var{f} returns \scm{\#f}, then \scm{\#f} is returned; otherwise,
the result of the last application of \var{f} is returned.
If \var{lists} are empty, them \scm{\#t} is returned.
The procedure \var{f} will be applied to the itesm in \var{lists}
from left to right.


\scmutilsectionwithindex{append!}{append"!}{lists \dots}{procedure}

Like \scm{append}, but the \var{lists} are destructively appended.


\scmutilsectionzero{banner}{procedure}

Returns a string for the MzScheme's start-up banner text.


\scmutilsection{begin0}{body \dots}{syntax}

Like \scm{begin}, but the value of the first expression
is returned, instead of the last expression.


\scmutilsection{case-lambda}{\scm{(}formals body \dots\scm{)} \dots}{syntax}

This is the \scm{case-lambda} of Dybvig et al. The \scm{case-lambda}
form defines a procedure that, when applied, automatically dispatches
to a procedure body based on the number of arguments in the
application.

A \scm{case-lambda} expression consists of a sequence of clauses,
where each clause has the form form \scm{(\var{formals} \var{body}
\dots)}. Each clause is analogous to a closure of the form \scm{(lambda
\var{formals} \var{body} \dots)}. When a \scm{case-lambda} procedure is
applied to \var{n} arguments, it evaluates the body of the first
clause that can accept \var{n} arguments. A \scm{case-lambda}
expression can have any number of clauses; the order of the clauses
determines the order in which they are tried.

For example, given this definition:
\scmline{
  (de\=fin\=e f\\
\>   \>(case-lambda\\
\>   \>   \>[(x) x]\\
\>   \>   \>[(x y) (+ x y)]\\
\>   \>   \>[(a . any) a]))}
then \scm{(f 1)} will return 1, \scm{(f 1 2)} will return 3, and
\scm{(f 3 4 5 6)} will return 3. \scm{(f)} is an error, because no
clause can handle 0 arguments.

The predicate \scmindex{procedure?} returns \scm{\#t} when applied to
a \scm{case-lambda} value.

\scmutilsectionzero{collect-garbage}{procedure}

\index{garbage collection}
Forces an immediate garbage collection. Since MzScheme uses a
``conservative'' garbage collector, some unreachable data may remain
uncollected (because the collector is not certain that it is
unreachable).

\scmutilsection{exit}{code}{procedure}

Invokes the exit handler (see section \ref{exithandler}). The default
exit handler quits MzScheme with the exit code \var{code}. The \var{code}
argument is optional; the default value is 0.


\scmutilsectionzero{current-milliseconds}{procedure}

Returns the current ``time'' in milliseconds. This time is be based
on a platform-specific starting date or on the machine's startup time.


\scmutilsection{fluid-let}{bindings body \dots}{syntax}

This is the usual \scm{fluid-let}. The variable names in
\var{bindings} must already be bound in the environment of the \scm{fluid-let}
expression.  Before \var{body} is evaluated, the existing bindings
will be \scm{set!} to the values specified in \var{bindings}.  When
\var{body} returns, the values of the bindings are restored.


\scmutilsection{format}{format args \dots}{procedure}

Creates a new string based on \var{format} and \var{args} using
\scm{fprintf}.


\scmutilsection{fprintf}{port format args \dots}{procedure}

\index{printing}
Prints formatted output to \var{port}, where \var{format} is a string
that will be printed; \var{format} can contain special formatting
tags:
\begin{itemize}
\item $\sim$n or $\sim$\% --- prints a newline
\item $\sim$a --- \scm{display}s the next argument in \var{args}
\item $\sim$s --- \scm{write}s the next argument in \var{args}
\item $\sim$c --- \scm{write-char}s the next argument in \var{args} (it 
must be a character)
\item $\sim$$\sim$ --- prints a tilde ($\sim$)
\end{itemize}

For example,
\scmline{(fprintf port "$\sim$a as a string is $\sim$s.$\sim$n" '(3 4) "(3 4)")}
prints this message to \var{port}:
\scmline{(3 4) as a string is "(3 4)".}
followed by a newline. See also \scm{printf} and \scm{format}.


\scmutilsection{gensym}{prefix}{procedure}

\index{symbols!generating}
Returns a symbol that is not \scm{eq?}, \scm{eqv?}, or 
\scm{equal?} to any other symbol. The \var{prefix} argument is optional; if
it is specified as a string or symbol, then it is used as a prefix for
the generated symbol's printed name. See also \scm{string->uninterned-symbol}.


\scmutilsection{getenv}{name}{procedure}

\index{envrionment variables}
Gets the value of an operating system environment variable. The
\var{name} argument must be a string; if an environment variable
\var{name} exists, its value is returned (as a string); otherwise,
\scm{\#f} is returned. See also \scm{putenv}.


\scmutilsection{letrec*}{bindings body \dots}{syntax}

\scm{letrec*} is equivalent to \scm{letrec}, except that the value
expressions in \var{bindings} are guaranteed to be evaluated in
sequential order.


\scmutilsection{list*}{args \dots}{procedure}

Like \scm{list}, but the last argument is used directly as the \scm{cdr} of
the last pair constructed for the list.


\scmutilsection{load/cd}{filename}{procedure}

This is a synonym for \scm{load-with-cd}


\scmutilsection{load-with-cd}{filename}{procedure}

Sets the current directory to be the directory of \var{filename},
loads \var{filename}, and then restores the current directory.


\scmutilsectionzero{make-global-value-list}{procedure}

\index{globals}
Returns an association list that pairs each globally-defined symbol
with its current value.


\scmutilsection{ormap}{f lists \dots}{procedure}

The arguments are as with \scm{map}. When an application of
\var{f} returns anything except \scm{\#f}, then that value is returned; 
otherwise, the result of the last application of \var{f} is returned.
If \var{lists} are empty, them \scm{\#f} is returned.
The procedure \var{f} will be applied to the itesm in \var{lists} from
left to right.

\scmutilsection{primitive?}{v}{procedure}

Returns \scm{\#t} if \var{v} is a built-in primitive procedure or
\scm{\#f} otherwise.  All R$^4$RS procedures are primitives, and are
most all of the procedures described in this manual. The exceptions
are \scm{compile-file}, \scm{format}, \scm{printf}, and \scm{fprintf}.

\scmutilsection{primitive-name}{prim}{procedure}

Returns the name of the primitive procedure \var{prim} as a symbol.

\scmutilsection{printf}{format args \dots}{procedure}

Calls \scm{fprintf} with the current output port.


\scmutilsection{promise?}{v}{procedure}

Returns \scm{\#t} if \var{v} is a promise (created with \scm{delay})
or \scm{\#f} otherwise.


\scmutilsection{putenv}{name value}{procedure}

\index{envrionment variables}
Sets the value of an operating system environment variable. The
\var{name} and \var{value} arguments must be strings; the envrionment
variable \var{name} will be set to \var{value}. The return value is
\scm{\#t} if the assignment succeeds, or \scm{\#f} otherwise.  See
also \scm{getenv}.

\scmutilsection{random}{n}{procedure}

Returns a random integer in the range 0 to $\var{n} - 1$. \var{n} must
be a positive fixnum integer.

\scmutilsection{random-seed}{n}{procedure}

Seeds the random number generator. \var{n} must be a fixnum integer.


\scmutilsectionzero{read-eval-print-loop}{procedure}

Starts a new read-eval-print loop using the currint input, output, and
error ports. Uncaught errors are ignored.

\scmutilsection{read-line}{port}{procedure}

Returns a string containing the next line of characters from
\var{port}.  If \var{port} is not specified, the current input port is
used. Characters are read from \var{port} until a carriage-return, a
line-feed, and an end-of-file is read. The carriage-return or
line-feed is not returned in the result string.  If no characters are
available from the port, EOF is returned.


\scmutilsectionwithindex{reverse!}{reverse"!}{list}{procedure}

Like \scm{reverse}, but \var{list} is destructively reversed.


\scmutilsection{string->uninterned-symbol}{s}{procedure}

\index{uninterned symbols}
Like \scmfirst{string->symbol}, but the resulting symbol is a new
uninterned symbol; i.e., it is not a symbol that can be expressed as a
quoted contant, although its printed form looks the same as the symbol
returned by \scm{string->symbol}.


\scmutilsection{sub1}{n}{procedure}

Returns \var{n} - 1.


\scmutilsectionzero{system-type}{procedure}

Returns a symbol indicating the type of operating system where
MzScheme is being executed. The possible values are

\begin{itemize}
\item \scmfirst{'unix}
\item \scmfirst{'windows}
\item \scmfirst{'macos}
\end{itemize}

Future ports of MzScheme will expand this list of system types.


\scmutilsection{time}{expr}{syntax}

Expands to \scm{(time-apply (lambda () \var{expr}))}, timing the
evaluation of \var{expr}.


\scmutilsection{time-apply}{thunk}{procedure}

The procedure \var{thunk} is invoked with no arguments. The time
required to evaluate the application is printed to the standard output
port. If multiple MzScheme threads are running, then the reported time
may include work performed by other threads.


\scmutilsection{unless}{test body \dots}{syntax}

If the value of \var{test} is \scm{\#f}, then \var{body} is evaluated;
otherwise, the return value is \scm{\#<void>}.


\scmutilsectionzero{version}{procedure}

Returns a string representing the executing version of MzScheme.

\scmutilsection{when}{test body \dots}{syntax}

If the value of \var{test} is not \scm{\#f}, then \var{body} is
evaluated; otherwise, the return value is \scm{\#<void>}.


\CHAPTER{mzlib Library}\label{mzlib}

\index{libraries}
\index{mzlib library}
\newcommand{\libindex}[1]{\index{#1@``#1''}}
\newcommand{\LIBSECTION}[1]{\SECTION{``#1''} \libindex{#1}}
\newcommand{\Requires}[1]{Requires: #1}
\newcommand{\RequiresNone}[0]{}

MzScheme is distributed with a library of additional utility functions.
The library files should be installed in a ``mzlib'' directory that is
in the same directory is the MzScheme excutable. 
With the proper directory configuration, the standalone console
MzScheme will find the library directory automatically; under other
circumstances, the library pathname may need to be set. The library
pathname can be obtained as \scmindex{current-library-path}
\scm{(current-library-path)}; the library pathname can be set to
\var{path} with \scm{(current-library-path \var{path})}. The
procedure \scm{find-executable-path} (see \ref{pathutils}) is
useful for finding the library pathname.

The library pathname is used by \scmfirst{require-library}. This
procedure takes a filename (e.g., \scm{"pretty.ss"}) and loads the
library file by that name. If the file has already been loaded, it
is not loaded again.

The \scm{current-library-path} and \scm{require-library} procedures
are normally used for the mzlib library. However, these procedures may
be used with a different library, especially if MzScheme is embedded
within another application.

The rest of this section describes the utilities provided by the
standard mzlib library. These utilities are not built into MzScheme
and they are {\em not} already present after the standalone console
version of MzScheme has loaded. To use a utility descibed in one of
the following sections, execute \scm{(require-library "x.ss")}, where
``x.ss'' is the name of the section.

\libindex{mzlib.ss}
All of the libraries can be loaded by requiring ``mzlib.ss''.
When a library is loaded, the procedures and macros defined by the
library are made constant (see section \ref{constant}) if 
\scm{mzlib:constant-lib?} is defined and not \scm{\#f}.

\LIBSECTION{compat.ss}

\Requires{``constant.ss''}

This library defines a number of procedures that are commonly provided
by other Scheme implementations. Most of these are aliases for
built-in MzScheme procedures:

\begin{center}
\begin{tt}
\fbox{
\begin{tabular}{cc}
Compatible & MzScheme \\
\hline
=? & = \\
<? & < \\
>? & > \\
<=? & <= \\
>=? & >= \\
1+ & add1 \\
1- & sub1 \\
gentemp & gensym \\
bound? & defined? \\
flush-output-port & flush-output \\
real-time & current-milliseconds
\end{tabular}
}
\end{tt}
\end{center}

\scmutilsection{atom?}{v}{procedure}

Same as \scm{(not (pair? \var{v}))}.

\scmutilsection{getprop}{sym property default}{procedure}

Gets a property value associated with the symbol \var{sym}.
The \var{property} argument is also a symbol that names the
property to be found. If the property is not found, \var{default}
is returned. If the \var{default} argument is omitted, \scm{\#f}
is used as the default.

\scmutilsectionzero{newcafe}{}{procedure}

Simluates Chez Scheme's \scm{new-cafe}, except that the result
is always \scm{\#<void>}.

\scmutilsection{putprop}{sym property value}{procedure}

Installs a value for \var{property} of the symbol \var{sym}.
See \scm{getprop} above.

\scmutilsection{sort}{less-than? list}{procedure}

This is the same as \scm{quicksort} (see ``function.ss'') with the
arguments reversed.


\LIBSECTION{constant.ss}

\RequiresNone

\scmutilsection{constant}{name}{syntax}

Makes the identifier \var{name} constant if \scm{mzlib:constant-lib?} 
is defined and not \scm{\#f}.


\LIBSECTION{defstruct.ss}

\Requires{``constant.ss''}

This library provides \scm{define-structure} and
\scm{define-const-structure} consistent with the ``match.ss''
library. The \scm{define-structure} and \scm{define-const-structure}
forms expand into \scm{define-struct} forms. While
\scm{define-const-structure} and the mutability annotations
are supported, immutable fields are {\em not} actually
immutable\footnote{ A properly implemented \scm{define-const-struct}
is not inconsistent with \scm{define-struct}, it simply has not been
implemented, yet.}.


\LIBSECTION{file.ss}

\Requires{``constant.ss''}

\scmutilsection{build-absolute-path}{base path ...}{procedure}

Like \scmfirst{build-path}, but \var{base} is required to be
an absolute pathname. If \var{base} is not an absolute pathname,
an error is raised.

\scmutilsection{build-relative-path}{base path ...}{procedure}

Like \scmfirst{build-path}, but \var{base} is required to be
a relative pathname. If \var{base} is not a relative pathname,
an error is raised.

\scmutilsection{explode-path}{path}{procedure}

Returns the list of directories that constitute \var{path}.
The \var{path} argument must be normalized (see
\scm{normalize-path} below).


\scmutilsection{filename-extension}{path}{procedure}

Returns a string that is the extension part of the filename
in \var{path}.

\scmutilsection{find-relative-path}{basepath path}{procedure}

Finds a relative pathname with respect to \var{basepath} that
names the same file as \var{path}. Both \var{basepath} and
\var{path} must be normalized (see \scm{normalize-path} below).

\scmutilsection{normalize-path}{path wrt}{procedure}

Returns a normalized, absolute version of \var{path}, expanding the
path and resolving all soft links. If \var{path} is realtive, then the
pathname \var{wrt} is used as the base path. The \var{wrt} argument is
optional; if is omitted, then the current working directory is used as
the base path.

Letter case is {\em not} normalized by \scm{normalize-path}, so
combine \scm{normalize-path} with \scm{normal-case-path} to get
strings for path comparison.


\LIBSECTION{function.ss}

\Requires{``constant.ss''}

\scmutilsection{compose}{f g}{procedure}

Returns a procedure that takes \scm{x} and returns
\scm{(call-with-values (lambda () (g x)) f)}.

\scmutilsection{dynamic-disable-break}{thunk}{procedure}

Invokes \var{thunk} and returns the result. During the
application of \var{thunk}, user breaks are disabled.

\scmutilsection{identity}{x}{procedure}

Returns \var{x}.

\scmutilsection{ignore-errors}{thunk}{procedure}

Invokes \var{thunk} and returns the result. If an error occurs
duuring the application of \var{thunk}, no error is reported
and \scm{\#<void>} is returned.

\scmutilsection{make-parameter}{initval filter}{procedure}

Returns a procedure that maintains a parameter value, like the
built-in procedures \scm{current-output-port},  \scm{current-eval}, etc.
The \var{initval} argument is the initial value of the parameter.  The
\var{filter} argument is optional. If \var{filter} is provided, it
must be a procedure that takes one argument, a candidate value for the
parameter; the filter must either raise an error or return a value
that will be installed for the parameter.

\scmutilsection{quicksort}{list less-than?}{procedure}

Sorts \var{list} using the comparison procedure \var{less-than?}.

\scmutilsection{remove}{item list eq?}{procedure}

Returns \var{list} without \var{item}. The \var{eq?}\ argument
is optional; it defaults to \var{eq?}. When \var{eq?} is invoked,
\var{item} will be the first argument.


\LIBSECTION{macros.ss}

\Requires{``constant.ss''}

\scmutilsection{catch-errors}{err-display err-result body ...}{syntax}

In the absence of run-time errors, the result of a \scm{catch-errors}
expression is the result of \var{body}.  If an error is encountered
during the evaluation of \var{body}, \var{err-display} is invoked as
the error display handler and the result of the \scm{catch-errors}
expression is the result of applying the thunk \var{err-result}. If
\var{err-display} is \scm{\#f}, then the current error display handler
is used instead.

\scmutilsection{let-enumerate}{name-lists body ...}{syntax}

This is a \scm{let}-form, but instead of name-value pairs, lists of
names are specified. For each name list, the first name is bound
to the constant 1, the second name is bound to 2, etc.

For example:
\scmline{
  (let\=-enumerate (\=[\=FILE-OPEN\\
\>    \>            \>\>FILE-CLOSE\\
\>    \>            \>\>FILE-QUIT]\\
\>    \>            \>[EDIT-COPY\\
\>    \>            \>\>EDIT-CUT\\
\>    \>            \>\>EDIT-PASTE])\\
\>    \>\var{body})
}

Within \var{body}, \scm{FILE-OPEN} is 1, \scm{FILE-CLOSE} is 2, 
\scm{FILE-QUIT} is 3, \scm{EDIT-COPY} will be 1, etc.

\scmutilsection{local}{definitions body ...}{syntax}

This \scm{local} syntax roughly simulates Rice Scheme's \scm{local}
syntax by expanding to \scm{(begin \var{definition} \var{body}
...)}. This expansion has slightly different semantics than Rice
Scheme's local, but the result is always the same when
\var{definitions} contains only
\scm{define} expressions that do not capture a continuation. 
No checks are performed on the structure of the \scm{local}
expression.

\scmutilsection{make-spawner}{opts-list params body ...}{syntax}

Returns a procedure that spawns a new thread and global variable space
when the procedure is applied. The procedure's formal arguments are
specified by \var{params} and these are bound by the application in
\var{body}. The \var{body} will be evaluated in the new thread, so
free variables in \var{body} that are not in \var{params} will refer
to global variables in the new global variable space. The
\var{opt-list} expression should return a list of symbols that are
passed on to \var{spawn-eval} to set options in the spawned process.


\scmutilsection{opt-lambda}{formals body ...}{syntax}

The \scm{opt-lambda} form is like \scm{lambda}, except that default values
can be assigned to parameters (C++-style). Default values are defined
in the \var{formals} list by replacing an identifier \var{id} by
\scm{[\var{id} \var{default-value-expression}]}. If an identifier has a
default value expression, then all (non-aggregate) identifiers after
it must have default value expressions. A final aggregate identifier can be
used as in \scm{lambda}, but it cannot be given a default value. Each
default value expression is evaluated only if it is needed. The
environment of each default value expression includes the preceeding
parameters.

For example:
\scmline{
  (de\=fin\=e f\\
\>   \>(opt-lambda (a [b (add1 a)] . c)\\
\>   \> \>...))
}

Here, \scm{f} is a function which takes at least one argument. If a second
argument is specified, it will be the value of \scm{b}, otherwise
\scm{b} will be \scm{(add1 a)}. If more than two arguments are specified, 
then the extra arguments are placed in a new list that is the value of
\scm{c}.


\scmutilsection{package}{export-var-list body ...}{syntax}

This syntactic form makes it convienent to develop a library of
functions with helper functions at the top level, and then package the
library so that only some of the names are actually exported to the
top-level. The \scm{package} form is only useful at the top-level.

The \var{body} expression can be any sequence of top-level
expressions. Only the variables listed in \var{export-var-list} will
actually be defined at the top-level (with the values they have at the
end of \var{body}).

For example, if this is evaluated at the top-level:

\scmline{
  (p\=ack\=age (f)\\
\>  \>(define f-helper-1\\
\>  \> \>(lambda ...))\\
\>  \>(define f-helper-2\\
\>  \> \>(lambda ...))\\
\>  \>(define f\\
\>  \> \>(lambda ...)))\\
} 

then \var{f} will be defined, but \var{f-helper-1} and
\var{f-helper-2} are visible only to \var{f} and themselves.


\scmutilsection{recur}{name bindings body ...}{syntax}

This is equivalent to a named \scm{let}: \scm{(let \var{name} 
\var{bindings} \var{body})}.


\scmutilsection{send*}{obj msg$_1$ ... msg$_n$}{syntax}

Calls multiple methods of \var{obj} (in the specified order).
Each \var{msg$_i$} should have the form:
\scmline{
(\var{name} \var{params} ...)
}
where \var{name} is the method name. For example:
\scmline{
  (send* edit \=(begin-edit-sequence)\\
\>            \>(insert "Hello")\\
\>            \>(insert \#$\backslash$newline)\\
\>            \>(end-edit-sequence))
}
is the same as
\scmline{
  (send edit begin-edit-sequence)\\
\>(send edit insert "Hello")\\
\>(send edit insert \#$\backslash$newline)\\
\>(send edit end-edit-sequence))
}


\LIBSECTION{match.ss}

\Requires{``constant.ss''}

This is the pattern matching system by Andrew Wright and Bruce Duba.
See {\it Pattern Matching for Scheme} for details.
The following syntactic forms are defined by the 
``match.ss'' library:

\begin{itemize}
\item \scm{match}
\item \scm{match-lambda}
\item \scm{match-lambda*}
\item \scm{match-let}
\item \scm{match-let*}
\item \scm{match-letrec}
\item \scm{match-define}
\end{itemize}

All forms of \scm{match} can be used with \scm{define-struct} values,
as well as \scm{define-structure} and \scm{define-const-structure} 
values (see ``defstruct.ss'').


\LIBSECTION{pretty.ss}

\Requires{``constant.ss''}

\scmutilsection{pretty-print}{v port width graph? struct?}{procedure}

Pretty-prints the value \var{v}. All other argument are optional.
\begin{itemize}
\item If \var{port} is provided, \var{v} is printed into \var{port};
otherwise, \var{v} is printed to the current output port.
\item If \var{width} is provided, \var{v} is printed with a column width of
\var{width} characters; otherwise, the internal column setting (as
parameterized by \scm{pretty-print-columns}) is used.
\item If \var{graph?} is provided, graph printing is enabled when
\var{graph?} is not \scm{\#f}; otherwise, \scm{(print-graph)} determines
the graph printing mode.
\item If \var{struct?} is provided, structure printing is enabled when
\var{struct?} is not \scm{\#f}; otherwise, \scm{(print-struct)} determines
the structure printing mode.
\end{itemize}

\scmutilsection{pretty-print-columns}{width}{procedure}

Sets the default width for pretty printing to \var{width} and
returns \scm{\#<void>}. If no \var{width} argument is provided,
the current value is returned instead.

\scmutilsection{pretty-print-handler}{v}{procedure}

Pretty-prints \var{v} if \var{v} is not \scm{\#<void>} or prints
nothing otherwise. Pass this procedure to \scm{current-print} to
install the pretty printer into the \scm{read}-\scm{eval}-\scm{print}
loop.


\LIBSECTION{strings.ss}

\Requires{``constant.ss''}

\scmutilsection{eval-string}{str err-display err-result}{procedure}

Reads the string \var{str} as an S-expression, evaluates it, and
returns the result. If \var{str} contains mutliple S-expressions, they
are all read and only the final result is returned.

The \var{err-display} and \var{err-result} arguments are optional; if
\var{err-display} is not \scm{\#f}, then errors will be caught and
\var{err-display} is used as the error display handler.  If 
\var{err-result} is specified, it must be a thunk
that returns a value to be returned when an error is caught;
otherwise, \scm{\#f} will be returned when an error is caught.


\scmutilsection{expr->string}{expr}{procedure}

Prints \var{expr} into a string and returns the string.


\scmutilsectionvar{newline-string}{string}

A string containing a single newline character.


\scmutilsection{read-string}{str err-display err-result}{procedure}

Reads the first S-expression from the string \var{str} and returns it.
The \var{err-display} and \var{err-result} are as in \scm{eval-str}.


\scmutilsection{read-string-all}{str err-display err-result}{procedure}

Reads all S-expressions from the string \var{str} and returns them in a list.
The \var{err-display} and \var{err-result} are as in \scm{eval-str}.


\scmutilsection{regexp-match-exact?}{regexp str}{procedure}

This procedure is like MzScheme's built-in \scmfirst{regexp-match},
but the result is always \scm{\#t} or \scm{\#f}; \scm{\#t} is
only returned when the entire string \var{str} matches \var{regexp}.

\scmutilsectionwithindex{string-lowercase!\ }{string-lowercase"!}{str}{procedure}

Destructively changes \var{str} to contain only lowercase characters.

\scmutilsectionwithindex{string-uppercase!\ }{string-uppercase"!}{str}{procedure}

Destructively changes \var{str} to contain only uppercase characters.


\newcommand{\Printindex}[1]{\printindex{#1}}

\newpage
\setheader{{\it INDEX}}{}{}{}{}{{\it INDEX}}\setfooter{\thepage}{}{}{}{}{\thepage}
\addcontentsline{toc}{chapter}{Index}

\Printindex

\end{document}


