This is mit-scheme-ref.info, produced by makeinfo version 4.8 from
scheme.texinfo.

   This manual documents MIT/GNU Scheme 9.1.

   Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993,
1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
2005, 2006, 2007, 2008, 2009, 2010, 2011 Massachusetts Institute     of
Technology

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.2 or any later version published by the Free Software
     Foundation; with no Invariant Sections, with no Front-Cover Texts
     and no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."

INFO-DIR-SECTION Programming Languages
START-INFO-DIR-ENTRY
* MIT/GNU Scheme Ref: (mit-scheme-ref).	MIT/GNU Scheme Reference Manual
END-INFO-DIR-ENTRY


File: mit-scheme-ref.info,  Node: Top,  Next: Acknowledgements,  Prev: (dir),  Up: (dir)

MIT/GNU Scheme
**************

This manual documents MIT/GNU Scheme 9.1.

   Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993,
1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
2005, 2006, 2007, 2008, 2009, 2010, 2011 Massachusetts Institute     of
Technology

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.2 or any later version published by the Free Software
     Foundation; with no Invariant Sections, with no Front-Cover Texts
     and no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."

* Menu:

* Acknowledgements::
* Overview::
* Special Forms::
* Equivalence Predicates::
* Numbers::
* Characters::
* Strings::
* Lists::
* Vectors::
* Bit Strings::
* Miscellaneous Datatypes::
* Associations::
* Procedures::
* Environments::
* Input/Output::
* Operating-System Interface::
* Error System::
* Graphics::
* Win32 Package Reference::
* GNU Free Documentation License::
* Binding Index::
* Concept Index::

 --- The Detailed Node Listing ---

Overview

* Notational Conventions::
* Scheme Concepts::
* Lexical Conventions::
* Expressions::

Notational Conventions

* Errors::
* Examples::
* Entry Format::

Scheme Concepts

* Variable Bindings::
* Environment Concepts::
* Initial and Current Environments::
* Static Scoping::
* True and False::
* External Representations::
* Disjointness of Types::
* Storage Model::

Lexical Conventions

* Whitespace::
* Delimiters::
* Identifiers::
* Uppercase and Lowercase::
* Naming Conventions::
* Comments::
* Additional Notations::

Expressions

* Literal Expressions::
* Variable References::
* Special Form Syntax::
* Procedure Call Syntax::

Special Forms

* Lambda Expressions::
* Lexical Binding::
* Dynamic Binding::
* Definitions::
* Assignments::
* Quoting::
* Conditionals::
* Sequencing::
* Iteration::
* Structure Definitions::
* Macros::
* SRFI syntax::

Definitions

* Top-Level Definitions::
* Internal Definitions::

Macros

* Syntactic Binding Constructs::
* Pattern Language::
* Syntactic Closures::
* Explicit Renaming::

Syntactic Closures

* Syntax Terminology::
* SC Transformer Definition::
* SC Identifiers::

SRFI syntax

* cond-expand (SRFI 0)::
* receive (SRFI 8)::
* and-let* (SRFI 2)::
* define-record-type (SRFI 9)::

Numbers

* Numerical types::
* Exactness::
* Implementation restrictions::
* Syntax of numerical constants::
* Numerical operations::
* Numerical input and output::
* Fixnum and Flonum Operations::
* Random Numbers::

Fixnum and Flonum Operations

* Fixnum Operations::
* Flonum Operations::

Characters

* External Representation of Characters::
* Comparison of Characters::
* Miscellaneous Character Operations::
* Internal Representation of Characters::
* ISO-8859-1 Characters::
* Character Sets::
* Unicode::

Unicode

* Wide Strings::
* Unicode Representations::

Strings

* Construction of Strings::
* Selecting String Components::
* Comparison of Strings::
* Alphabetic Case in Strings::
* Cutting and Pasting Strings::
* Searching Strings::
* Matching Strings::
* Regular Expressions::
* Modification of Strings::
* Variable-Length Strings::
* Byte Vectors::

Regular Expressions

* Regular-expression procedures::
* REXP abstraction::

Lists

* Pairs::
* Construction of Lists::
* Selecting List Components::
* Cutting and Pasting Lists::
* Filtering Lists::
* Searching Lists::
* Mapping of Lists::
* Reduction of Lists::
* Miscellaneous List Operations::

Vectors

* Construction of Vectors::
* Selecting Vector Components::
* Cutting Vectors::
* Modifying Vectors::

Bit Strings

* Construction of Bit Strings::
* Selecting Bit String Components::
* Cutting and Pasting Bit Strings::
* Bitwise Operations on Bit Strings::
* Modification of Bit Strings::
* Integer Conversions of Bit Strings::

Miscellaneous Datatypes

* Booleans::
* Symbols::
* Cells::
* Records::
* Promises::
* Streams::
* Weak Pairs::
* Ephemerons::

Associations

* Association Lists::
* 1D Tables::
* The Association Table::
* Hash Tables::
* Object Hashing::
* Red-Black Trees::
* Weight-Balanced Trees::

Hash Tables

* Construction of Hash Tables::
* Basic Hash Table Operations::
* Resizing of Hash Tables::
* Address Hashing::

Weight-Balanced Trees

* Construction of Weight-Balanced Trees::
* Basic Operations on Weight-Balanced Trees::
* Advanced Operations on Weight-Balanced Trees::
* Indexing Operations on Weight-Balanced Trees::

Procedures

* Procedure Operations::
* Arity::
* Primitive Procedures::
* Continuations::
* Application Hooks::
* Generic Dispatch::

Generic Dispatch

* Generic Procedures::
* Method Generators::
* Dispatch Tags::

Environments

* Environment Operations::
* Environment Variables::
* REPL Environment::
* Top-level Environments::

Input/Output

* Ports::
* File Ports::
* String Ports::
* Input Procedures::
* Output Procedures::
* Format::
* Custom Output::
* Prompting::
* Port Primitives::
* Parser Buffers::
* Parser Language::
* XML Support::

Port Primitives

* Port Types::
* Constructors and Accessors for Ports::
* Input Port Operations::
* Output Port Operations::
* Blocking Mode::
* Terminal Mode::

Parser Language

* *Matcher::
* *Parser::
* Parser-language Macros::

XML Support

* XML Input::
* XML Output::
* XML Names::
* XML Structure::

Operating-System Interface

* Pathnames::
* Working Directory::
* File Manipulation::
* Directory Reader::
* Date and Time::
* Machine Time::
* Subprocesses::
* TCP Sockets::
* Miscellaneous OS Facilities::

Pathnames

* Filenames and Pathnames::
* Components of Pathnames::
* Operations on Pathnames::
* Miscellaneous Pathnames::

Date and Time

* Universal Time::
* Decoded Time::
* File Time::
* Time-Format Conversion::
* External Representation of Time::

Subprocesses

* Subprocess Procedures::
* Subprocess Conditions::
* Subprocess Options::

Error System

* Condition Signalling::
* Error Messages::
* Condition Handling::
* Restarts::
* Condition Instances::
* Condition Types::
* Taxonomy::

Restarts

* Establishing Restart Code::
* Invoking Standard Restart Code::
* Finding and Invoking General Restart Code::
* The Named Restart Abstraction::

Condition Instances

* Generating Operations on Conditions::
* Condition State::
* Simple Condition Instance Operations::

Graphics

* Opening and Closing of Graphics Devices::
* Coordinates for Graphics::
* Drawing Graphics::
* Characteristics of Graphics Output::
* Buffering of Graphics Output::
* Clipping of Graphics Output::
* Custom Graphics Operations::
* Images::
* X Graphics::                  Graphics on the X Window System
* Win32 Graphics::              Graphics on Microsoft Windows and Windows NT

X Graphics

* X Graphics Type::
* Utilities for X Graphics::
* Custom Operations on X Graphics Devices::

Win32 Graphics

* Win32 Graphics Type::
* Custom Operations for Win32 Graphics::  Custom Operations for Win32 Graphics Devices

Win32 Package Reference

* Win32 Package Overview::
* Foreign function interface::
* Device Independent Bitmap Utilities::

Foreign Function Interface

* Windows Types::
* Windows Foreign Procedures::
* Win32 API names and procedures::

Device Independent Bitmap Utilities

* DIB procedures::
* Other parts of the DIB Utilities implementation::


File: mit-scheme-ref.info,  Node: Acknowledgements,  Next: Overview,  Prev: Top,  Up: Top

Acknowledgements
****************

While "a cast of thousands" may be an overstatement, it is certainly the
case that this document represents the work of many people.  First and
foremost, thanks go to the authors of the `Revised^4 Report on the
Algorithmic Language Scheme', from which much of this document is
derived.  Thanks also to BBN Advanced Computers Inc. for the use of
parts of their `Butterfly Scheme Reference', and to Margaret O'Connell
for translating it from BBN's text-formatting language to ours.

   Special thanks to Richard Stallman, Bob Chassell, and Brian Fox, all
of the Free Software Foundation, for creating and maintaining the
Texinfo formatting language in which this document is written.

   This report describes research done at the Artificial Intelligence
Laboratory and the Laboratory for Computer Science, both of the
Massachusetts Institute of Technology.  Support for this research is
provided in part by the Advanced Research Projects Agency of the
Department of Defense and by the National Science Foundation.


File: mit-scheme-ref.info,  Node: Overview,  Next: Special Forms,  Prev: Acknowledgements,  Up: Top

1 Overview
**********

This manual is a detailed description of the MIT/GNU Scheme runtime
system.  It is intended to be a reference document for programmers.  It
does not describe how to run Scheme or how to interact with it -- that
is the subject of the `MIT/GNU Scheme User's Manual'.

   This chapter summarizes the semantics of Scheme, briefly describes
the MIT/GNU Scheme programming environment, and explains the syntactic
and lexical conventions of the language.  Subsequent chapters describe
special forms, numerous data abstractions, and facilities for input and
output.

   Throughout this manual, we will make frequent references to
"standard Scheme", which is the language defined by the document
`Revised^4 Report on the Algorithmic Language Scheme', by William
Clinger, Jonathan Rees, et al., or by IEEE Std. 1178-1990, `IEEE
Standard for the Scheme Programming Language' (in fact, several parts
of this document are copied from the `Revised Report').  MIT/GNU Scheme
is an extension of standard Scheme.

   These are the significant semantic characteristics of the Scheme
language:

Variables are statically scoped
     Scheme is a "statically scoped" programming language, which means
     that each use of a variable is associated with a lexically
     apparent binding of that variable.  Algol is another statically
     scoped language.

Types are latent
     Scheme has "latent" types as opposed to "manifest" types, which
     means that Scheme associates types with values (or objects) rather
     than with variables.  Other languages with latent types (also
     referred to as "weakly" typed or "dynamically" typed languages)
     include APL, Snobol, and other dialects of Lisp.  Languages with
     manifest types (sometimes referred to as "strongly" typed or
     "statically" typed languages) include Algol 60, Pascal, and C.

Objects have unlimited extent
     All objects created during a Scheme computation, including
     procedures and continuations, have unlimited extent; no Scheme
     object is ever destroyed.  The system doesn't run out of memory
     because the garbage collector reclaims the storage occupied by an
     object when the object cannot possibly be needed by a future
     computation.  Other languages in which most objects have unlimited
     extent include APL and other Lisp dialects.

Proper tail recursion
     Scheme is "properly tail-recursive", which means that iterative
     computation can occur in constant space, even if the iterative
     computation is described by a syntactically recursive procedure.
     With a tail-recursive implementation, you can express iteration
     using the ordinary procedure-call mechanics; special iteration
     expressions are provided only for syntactic convenience.

Procedures are objects
     Scheme procedures are objects, which means that you can create them
     dynamically, store them in data structures, return them as the
     results of other procedures, and so on.  Other languages with such
     procedure objects include Common Lisp and ML.

Continuations are explicit
     In most other languages, continuations operate behind the scenes.
     In Scheme, continuations are objects; you can use continuations for
     implementing a variety of advanced control constructs, including
     non-local exits, backtracking, and coroutines.

Arguments are passed by value
     Arguments to Scheme procedures are passed by value, which means
     that Scheme evaluates the argument expressions before the
     procedure gains control, whether or not the procedure needs the
     result of the evaluations.  ML, C, and APL are three other
     languages that pass arguments by value.  In languages such as SASL
     and Algol 60, argument expressions are not evaluated unless the
     values are needed by the procedure.

   Scheme uses a parenthesized-list Polish notation to describe programs
and (other) data.  The syntax of Scheme, like that of most Lisp
dialects, provides for great expressive power, largely due to its
simplicity.  An important consequence of this simplicity is the
susceptibility of Scheme programs and data to uniform treatment by other
Scheme programs.  As with other Lisp dialects, the `read' primitive
parses its input; that is, it performs syntactic as well as lexical
decomposition of what it reads.

* Menu:

* Notational Conventions::
* Scheme Concepts::
* Lexical Conventions::
* Expressions::


File: mit-scheme-ref.info,  Node: Notational Conventions,  Next: Scheme Concepts,  Prev: Overview,  Up: Overview

1.1 Notational Conventions
==========================

This section details the notational conventions used throughout the rest
of this document.

* Menu:

* Errors::
* Examples::
* Entry Format::


File: mit-scheme-ref.info,  Node: Errors,  Next: Examples,  Prev: Notational Conventions,  Up: Notational Conventions

1.1.1 Errors
------------

When this manual uses the phrase "an error will be signalled," it means
that Scheme will call `error', which normally halts execution of the
program and prints an error message.

   When this manual uses the phrase "it is an error," it means that the
specified action is not valid in Scheme, but the system may or may not
signal the error.  When this manual says that something "must be," it
means that violating the requirement is an error.


File: mit-scheme-ref.info,  Node: Examples,  Next: Entry Format,  Prev: Errors,  Up: Notational Conventions

1.1.2 Examples
--------------

This manual gives many examples showing the evaluation of expressions.
The examples have a common format that shows the expression being
evaluated on the left hand side, an "arrow" in the middle, and the
value of the expression written on the right.  For example:

     (+ 1 2)          =>  3

   Sometimes the arrow and value will be moved under the expression,
due to lack of space.  Occasionally we will not care what the value is,
in which case both the arrow and the value are omitted.

   If an example shows an evaluation that results in an error, an error
message is shown, prefaced by `error-->':

     (+ 1 'foo)                      error--> Illegal datum

   An example that shows printed output marks it with `-|':

     (begin (write 'foo) 'bar)
          -| foo
          => bar

   When this manual indicates that the value returned by some
expression is "unspecified", it means that the expression will evaluate
to some object without signalling an error, but that programs should
not depend on the value in any way.


File: mit-scheme-ref.info,  Node: Entry Format,  Prev: Examples,  Up: Notational Conventions

1.1.3 Entry Format
------------------

Each description of an MIT/GNU Scheme variable, special form, or
procedure begins with one or more header lines in this format:

 -- CATEGORY: TEMPLATE

where CATEGORY specifies the kind of item ("variable", "special form",
or "procedure").  The form of TEMPLATE is interpreted depending on
CATEGORY.

Variable
     TEMPLATE consists of the variable's name.  

Special Form
     TEMPLATE starts with the syntactic keyword of the special form,
     followed by a description of the special form's syntax.  The
     description is written using the following conventions.  

     Named components are italicized in the printed manual, and
     uppercase in the Info file.  "Noise" keywords, such as the `else'
     keyword in the `cond' special form, are set in a fixed width font
     in the printed manual; in the Info file they are not distinguished.
     Parentheses indicate themselves.

     A horizontal ellipsis (...) is describes repeated components.
     Specifically,

          THING ...

     indicates _zero_ or more occurrences of THING, while

          THING THING ...

     indicates _one_ or more occurrences of THING.

     Brackets, `[ ]', enclose optional components.

     Several special forms (e.g. `lambda') have an internal component
     consisting of a series of expressions; usually these expressions
     are evaluated sequentially under conditions that are specified in
     the description of the special form.  This sequence of expressions
     is commonly referred to as the "body" of the special form.

Procedure
     TEMPLATE starts with the name of the variable to which the
     procedure is bound, followed by a description of the procedure's
     arguments.  The arguments are described using "lambda list"
     notation (*note Lambda Expressions::), except that brackets are
     used to denote optional arguments, and ellipses are used to denote
     "rest" arguments.  

     The names of the procedure's arguments are italicized in the
     printed manual, and uppercase in the Info file.

     When an argument names a Scheme data type, it indicates that the
     argument must be that type of data object.  For example,

      -- procedure: cdr pair

     indicates that the standard Scheme procedure `cdr' takes one
     argument, which must be a pair.

     Many procedures signal an error when an argument is of the wrong
     type; usually this error is a condition of type
     `condition-type:wrong-type-argument'.  

     In addition to the standard data-type names (PAIR, LIST, BOOLEAN,
     STRING, etc.), the following names as arguments also imply type
     restrictions:

        * OBJECT: any object

        * THUNK: a procedure of no arguments

        * X, Y: real numbers

        * Q, N: integers

        * K: an exact non-negative integer

   Some examples:

 -- procedure: list object ...

indicates that the standard Scheme procedure `list' takes zero or more
arguments, each of which may be any Scheme object.

 -- procedure: write-char char [output-port]

indicates that the standard Scheme procedure `write-char' must be
called with a character, CHAR, and may also be called with a character
and an output port.


File: mit-scheme-ref.info,  Node: Scheme Concepts,  Next: Lexical Conventions,  Prev: Notational Conventions,  Up: Overview

1.2 Scheme Concepts
===================

* Menu:

* Variable Bindings::
* Environment Concepts::
* Initial and Current Environments::
* Static Scoping::
* True and False::
* External Representations::
* Disjointness of Types::
* Storage Model::


File: mit-scheme-ref.info,  Node: Variable Bindings,  Next: Environment Concepts,  Prev: Scheme Concepts,  Up: Scheme Concepts

1.2.1 Variable Bindings
-----------------------

Any identifier that is not a syntactic keyword may be used as a variable
(*note Identifiers::).  A variable may name a location where a value can
be stored.  A variable that does so is said to be "bound" to the
location.  The value stored in the location to which a variable is bound
is called the variable's "value".  (The variable is sometimes said to
"name" the value or to be "bound to" the value.)

   A variable may be bound but still not have a value; such a variable
is said to be "unassigned".  Referencing an unassigned variable is an
error.  When this error is signalled, it is a condition of type
`condition-type:unassigned-variable'; sometimes the compiler does not
generate code to signal the error.  Unassigned variables are useful
only in combination with side effects (*note Assignments::).  


File: mit-scheme-ref.info,  Node: Environment Concepts,  Next: Initial and Current Environments,  Prev: Variable Bindings,  Up: Scheme Concepts

1.2.2 Environment Concepts
--------------------------

An "environment" is a set of variable bindings.  If an environment has
no binding for a variable, that variable is said to be "unbound" in
that environment.  Referencing an unbound variable signals a condition
of type `condition-type:unbound-variable'.  

   A new environment can be created by "extending" an existing
environment with a set of new bindings.  Note that "extending an
environment" does *not* modify the environment; rather, it creates a
new environment that contains the new bindings and the old ones.  The
new bindings "shadow" the old ones; that is, if an environment that
contains a binding for `x' is extended with a new binding for `x', then
only the new binding is seen when `x' is looked up in the extended
environment.  Sometimes we say that the original environment is the
"parent" of the new one, or that the new environment is a "child" of
the old one, or that the new environment "inherits" the bindings in the
old one.

   Procedure calls extend an environment, as do `let', `let*',
`letrec', and `do' expressions.  Internal definitions (*note Internal
Definitions::) also extend an environment.  (Actually, all the
constructs that extend environments can be expressed in terms of
procedure calls, so there is really just one fundamental mechanism for
environment extension.)  A top-level definition (*note Top-Level
Definitions::) may add a binding to an existing environment.


File: mit-scheme-ref.info,  Node: Initial and Current Environments,  Next: Static Scoping,  Prev: Environment Concepts,  Up: Scheme Concepts

1.2.3 Initial and Current Environments
--------------------------------------

MIT/GNU Scheme provides an "initial environment" that contains all of
the variable bindings described in this manual.  Most environments are
ultimately extensions of this initial environment.  In Scheme, the
environment in which your programs execute is actually a child
(extension) of the environment containing the system's bindings.  Thus,
system names are visible to your programs, but your names do not
interfere with system programs.

   The environment in effect at some point in a program is called the
"current environment" at that point.  In particular, every REP loop has
a current environment.  (REP stands for "read-eval-print"; the REP loop
is the Scheme program that reads your input, evaluates it, and prints
the result.)  The environment of the top-level REP loop (the one you
are in when Scheme starts up) starts as `user-initial-environment',
although it can be changed by the `ge' procedure.  When a new REP loop
is created, its environment is determined by the program that creates
it.


File: mit-scheme-ref.info,  Node: Static Scoping,  Next: True and False,  Prev: Initial and Current Environments,  Up: Scheme Concepts

1.2.4 Static Scoping
--------------------

Scheme is a statically scoped language with block structure.  In this
respect, it is like Algol and Pascal, and unlike most other dialects of
Lisp except for Common Lisp.

   The fact that Scheme is statically scoped (rather than dynamically
bound) means that the environment that is extended (and becomes
current) when a procedure is called is the environment in which the
procedure was created (i.e. in which the procedure's defining lambda
expression was evaluated), not the environment in which the procedure
is called.  Because all the other Scheme "binding expressions" can be
expressed in terms of procedures, this determines how all bindings
behave.

   Consider the following definitions, made at the top-level REP loop
(in the initial environment):

     (define x 1)
     (define (f x) (g 2))
     (define (g y) (+ x y))
     (f 5)                                       =>  3 ; not 7

   Here `f' and `g' are bound to procedures created in the initial
environment.  Because Scheme is statically scoped, the call to `g' from
`f' extends the initial environment (the one in which `g' was created)
with a binding of `y' to `2'.  In this extended environment, `y' is `2'
and `x' is `1'.  (In a dynamically bound Lisp, the call to `g' would
extend the environment in effect during the call to `f', in which `x' is
bound to `5' by the call to `f', and the answer would be `7'.)

   Note that with static scoping, you can tell what binding a variable
reference refers to just from looking at the text of the program; the
referenced binding cannot depend on how the program is used.  That is,
the nesting of environments (their parent-child relationship)
corresponds to the nesting of binding expressions in program text.
(Because of this connection to the text of the program, static scoping
is also called "lexical" scoping.)  For each place where a variable is
bound in a program there is a corresponding "region" of the program
text within which the binding is effective.  For example, the region of
a binding established by a `lambda' expression is the entire body of
the `lambda' expression.  The documentation of each binding expression
explains what the region of the bindings it makes is.  A use of a
variable (that is, a reference to or assignment of a variable) refers
to the innermost binding of that variable whose region contains the
variable use.  If there is no such region, the use refers to the
binding of the variable in the global environment (which is an ancestor
of all other environments, and can be thought of as a region in which
all your programs are contained).


File: mit-scheme-ref.info,  Node: True and False,  Next: External Representations,  Prev: Static Scoping,  Up: Scheme Concepts

1.2.5 True and False
--------------------

In Scheme, the boolean values true and false are denoted by `#t' and
`#f'.  However, any Scheme value can be treated as a boolean for the
purpose of a conditional test.  This manual uses the word "true" to
refer to any Scheme value that counts as true, and the word "false" to
refer to any Scheme value that counts as false.  In conditional tests,
all values count as true except for `#f', which counts as false (*note
Conditionals::).


File: mit-scheme-ref.info,  Node: External Representations,  Next: Disjointness of Types,  Prev: True and False,  Up: Scheme Concepts

1.2.6 External Representations
------------------------------

An important concept in Scheme is that of the "external representation"
of an object as a sequence of characters.  For example, an external
representation of the integer 28 is the sequence of characters `28',
and an external representation of a list consisting of the integers 8
and 13 is the sequence of characters `(8 13)'.

   The external representation of an object is not necessarily unique.
The integer 28 also has representations `#e28.000' and `#x1c', and the
list in the previous paragraph also has the representations `( 08 13 )'
and `(8 . (13 . ( )))'.

   Many objects have standard external representations, but some, such
as procedures and circular data structures, do not have standard
representations (although particular implementations may define
representations for them).

   An external representation may be written in a program to obtain the
corresponding object (*note Quoting::).

   External representations can also be used for input and output.  The
procedure `read' parses external representations, and the procedure
`write' generates them.  Together, they provide an elegant and powerful
input/output facility.

   Note that the sequence of characters `(+ 2 6)' is _not_ an external
representation of the integer 8, even though it _is_ an expression that
evaluates to the integer 8; rather, it is an external representation of
a three-element list, the elements of which are the symbol `+' and the
integers `2' and `6'.  Scheme's syntax has the property that any
sequence of characters that is an expression is also the external
representation of some object.  This can lead to confusion, since it
may not be obvious out of context whether a given sequence of
characters is intended to denote data or program, but it is also a
source of power, since it facilitates writing programs such as
interpreters and compilers that treat programs as data or data as
programs.


File: mit-scheme-ref.info,  Node: Disjointness of Types,  Next: Storage Model,  Prev: External Representations,  Up: Scheme Concepts

1.2.7 Disjointness of Types
---------------------------

Every object satisfies at most one of the following predicates (but see
*Note True and False::, for an exception):

     bit-string?     environment?    port?           symbol?
     boolean?        null?           procedure?      vector?
     cell?           number?         promise?        weak-pair?
     char?           pair?           string?
     condition?


File: mit-scheme-ref.info,  Node: Storage Model,  Prev: Disjointness of Types,  Up: Scheme Concepts

1.2.8 Storage Model
-------------------

This section describes a model that can be used to understand Scheme's
use of storage.

   Variables and objects such as pairs, vectors, and strings implicitly
denote locations or sequences of locations.  A string, for example,
denotes as many locations as there are characters in the string.  (These
locations need not correspond to a full machine word.)  A new value may
be stored into one of these locations using the `string-set!'
procedure, but the string continues to denote the same locations as
before.

   An object fetched from a location, by a variable reference or by a
procedure such as `car', `vector-ref', or `string-ref', is equivalent
in the sense of `eqv?' to the object last stored in the location before
the fetch.

   Every location is marked to show whether it is in use.  No variable
or object ever refers to a location that is not in use.  Whenever this
document speaks of storage being allocated for a variable or object,
what is meant is that an appropriate number of locations are chosen from
the set of locations that are not in use, and the chosen locations are
marked to indicate that they are now in use before the variable or
object is made to denote them.

   In many systems it is desirable for constants (i.e. the values of
literal expressions) to reside in read-only memory.  To express this, it
is convenient to imagine that every object that denotes locations is
associated with a flag telling whether that object is mutable or
immutable.  The constants and the strings returned by `symbol->string'
are then the immutable objects, while all objects created by other
procedures are mutable.  It is an error to attempt to store a new value
into a location that is denoted by an immutable object.  Note that the
MIT/GNU Scheme compiler takes advantage of this property to share
constants, but that these constants are not immutable.  Instead, two
constants that are `equal?' may be `eq?' in compiled code.


File: mit-scheme-ref.info,  Node: Lexical Conventions,  Next: Expressions,  Prev: Scheme Concepts,  Up: Overview

1.3 Lexical Conventions
=======================

This section describes Scheme's lexical conventions.

* Menu:

* Whitespace::
* Delimiters::
* Identifiers::
* Uppercase and Lowercase::
* Naming Conventions::
* Comments::
* Additional Notations::


File: mit-scheme-ref.info,  Node: Whitespace,  Next: Delimiters,  Prev: Lexical Conventions,  Up: Lexical Conventions

1.3.1 Whitespace
----------------

"Whitespace" characters are spaces, newlines, tabs, and page breaks.
Whitespace is used to improve the readability of your programs and to
separate tokens from each other, when necessary.  (A "token" is an
indivisible lexical unit such as an identifier or number.)  Whitespace
is otherwise insignificant.  Whitespace may occur between any two
tokens, but not within a token.  Whitespace may also occur inside a
string, where it is significant.


File: mit-scheme-ref.info,  Node: Delimiters,  Next: Identifiers,  Prev: Whitespace,  Up: Lexical Conventions

1.3.2 Delimiters
----------------

All whitespace characters are "delimiters".  In addition, the following
characters act as delimiters:

     (  )  ;  "  '  `  |

   Finally, these next characters act as delimiters, despite the fact
that Scheme does not define any special meaning for them:

     [  ]  {  }

   For example, if the value of the variable `name' is `"max"':

     (list"Hi"name(+ 1 2))                   =>  ("Hi" "max" 3)


File: mit-scheme-ref.info,  Node: Identifiers,  Next: Uppercase and Lowercase,  Prev: Delimiters,  Up: Lexical Conventions

1.3.3 Identifiers
-----------------

An "identifier" is a sequence of one or more non-delimiter characters.
Identifiers are used in several ways in Scheme programs:

   * An identifier can be used as a variable or as a syntactic keyword.  

   * When an identifier appears as a literal or within a literal, it
     denotes a symbol.  

   Scheme accepts most of the identifiers that other programming
languages allow.  MIT/GNU Scheme allows all of the identifiers that
standard Scheme does, plus many more.

   MIT/GNU Scheme defines a potential identifier to be a sequence of
non-delimiter characters that does not begin with either of the
characters `#' or `,'.  Any such sequence of characters that is not a
syntactically valid number (*note Numbers::) is considered to be a
valid identifier.  Note that, although it is legal for `#' and `,' to
appear in an identifier (other than in the first character position),
it is poor programming practice.

   Here are some examples of identifiers:

     lambda             q
     list->vector       soup
     +                  V17a
     <=?                a34kTMNs
     the-word-recursion-has-many-meanings


File: mit-scheme-ref.info,  Node: Uppercase and Lowercase,  Next: Naming Conventions,  Prev: Identifiers,  Up: Lexical Conventions

1.3.4 Uppercase and Lowercase
-----------------------------

Scheme doesn't distinguish uppercase and lowercase forms of a letter
except within character and string constants; in other words, Scheme is
"case-insensitive".  For example, `Foo' is the same identifier as
`FOO', and `#x1AB' is the same number as `#X1ab'.  But `#\a' and `#\A'
are different characters.


File: mit-scheme-ref.info,  Node: Naming Conventions,  Next: Comments,  Prev: Uppercase and Lowercase,  Up: Lexical Conventions

1.3.5 Naming Conventions
------------------------

A "predicate" is a procedure that always returns a boolean value (`#t'
or `#f').  By convention, predicates usually have names that end in `?'.

   A "mutation procedure" is a procedure that alters a data structure.
By convention, mutation procedures usually have names that end in `!'.


File: mit-scheme-ref.info,  Node: Comments,  Next: Additional Notations,  Prev: Naming Conventions,  Up: Lexical Conventions

1.3.6 Comments
--------------

The beginning of a comment is indicated with a semicolon (`;').  Scheme
ignores everything on a line in which a semicolon appears, from the
semicolon until the end of the line.  The entire comment, including the
newline character that terminates it, is treated as whitespace.

   An alternative form of comment (sometimes called an "extended
comment") begins with the characters `#|' and ends with the characters
`|#'.  This alternative form is an MIT/GNU Scheme extension.  As with
ordinary comments, all of the characters in an extended comment,
including the leading `#|' and trailing `|#', are treated as
whitespace.  Comments of this form may extend over multiple lines, and
additionally may be nested (unlike the comments of the programming
language C, which have a similar syntax).

     ;;; This is a comment about the FACT procedure.  Scheme
     ;;; ignores all of this comment.  The FACT procedure computes
     ;;; the factorial of a non-negative integer.

     #|
     This is an extended comment.
     Such comments are useful for commenting out code fragments.
     |#

     (define fact
       (lambda (n)
         (if (= n 0)                      ;This is another comment:
             1                            ;Base case: return 1
             (* n (fact (- n 1))))))


File: mit-scheme-ref.info,  Node: Additional Notations,  Prev: Comments,  Up: Lexical Conventions

1.3.7 Additional Notations
--------------------------

The following list describes additional notations used in Scheme.
*Note Numbers::, for a description of the notations used for numbers.

`+ - .'
     The plus sign, minus sign, and period are used in numbers, and may
     also occur in an identifier.  A delimited period (not occurring
     within a number or identifier) is used in the notation for pairs
     and to indicate a "rest" parameter in a formal parameter list
     (*note Lambda Expressions::).

`( )'
     Parentheses are used for grouping and to notate lists (*note
     Lists::).

`"'
     The double quote delimits strings (*note Strings::).

`\'
     The backslash is used in the syntax for character constants (*note
     Characters::) and as an escape character within string constants
     (*note Strings::).

`;'
     The semicolon starts a comment.

`''
     The single quote indicates literal data; it suppresses evaluation
     (*note Quoting::).

``'
     The backquote indicates almost-constant data (*note Quoting::).

`,'
     The comma is used in conjunction with the backquote (*note
     Quoting::).

`,@'
     A comma followed by an at-sign is used in conjunction with the
     backquote (*note Quoting::).

`#'
     The sharp (or pound) sign has different uses, depending on the
     character that immediately follows it:

`#t #f'
     These character sequences denote the boolean constants (*note
     Booleans::).

`#\'
     This character sequence introduces a character constant (*note
     Characters::).

`#('
     This character sequence introduces a vector constant (*note
     Vectors::).  A close parenthesis, `)', terminates a vector
     constant.

`#e #i #b #o #d #l #s #x'
     These character sequences are used in the notation for numbers
     (*note Numbers::).

`#|'
     This character sequence introduces an extended comment.  The
     comment is terminated by the sequence `|#'.  This notation is an
     MIT/GNU Scheme extension.

`#!'
     This character sequence is used to denote a small set of named
     constants.  Currently there are only two of these, `#!optional' and
     `#!rest', both of which are used in the `lambda' special form to
     mark certain parameters as being "optional" or "rest" parameters.
     This notation is an MIT/GNU Scheme extension.  

`#*'
     This character sequence introduces a bit string (*note Bit
     Strings::).  This notation is an MIT/GNU Scheme extension.

`#['
     This character sequence is used to denote objects that do not have
     a readable external representation (*note Custom Output::).  A
     close bracket, `]', terminates the object's notation.  This
     notation is an MIT/GNU Scheme extension.

`#@'
     This character sequence is a convenient shorthand used to refer to
     objects by their hash number (*note Custom Output::).  This
     notation is an MIT/GNU Scheme extension.

`#='
`##'
     These character sequences introduce a notation used to show
     circular structures in printed output, or to denote them in input.
     The notation works much like that in Common Lisp, and is an
     MIT/GNU Scheme extension.


File: mit-scheme-ref.info,  Node: Expressions,  Prev: Lexical Conventions,  Up: Overview

1.4 Expressions
===============

A Scheme "expression" is a construct that returns a value.  An
expression may be a _literal_, a _variable reference_, a _special
form_, or a _procedure call_.

* Menu:

* Literal Expressions::
* Variable References::
* Special Form Syntax::
* Procedure Call Syntax::


File: mit-scheme-ref.info,  Node: Literal Expressions,  Next: Variable References,  Prev: Expressions,  Up: Expressions

1.4.1 Literal Expressions
-------------------------

"Literal" constants may be written by using an external representation
of the data.  In general, the external representation must be _quoted_
(*note Quoting::); but some external representations can be used
without quotation.

     "abc"                                   =>  "abc"
     145932                                  =>  145932
     #t                                      =>  #t
     #\a                                     =>  #\a

   The external representation of numeric constants, string constants,
character constants, and boolean constants evaluate to the constants
themselves.  Symbols, pairs, lists, and vectors require quoting.


File: mit-scheme-ref.info,  Node: Variable References,  Next: Special Form Syntax,  Prev: Literal Expressions,  Up: Expressions

1.4.2 Variable References
-------------------------

An expression consisting of an identifier (*note Identifiers::) is a
"variable reference"; the identifier is the name of the variable being
referenced.  The value of the variable reference is the value stored in
the location to which the variable is bound.  An error is signalled if
the referenced variable is unbound or unassigned.

     (define x 28)
     x                                       =>  28


File: mit-scheme-ref.info,  Node: Special Form Syntax,  Next: Procedure Call Syntax,  Prev: Variable References,  Up: Expressions

1.4.3 Special Form Syntax
-------------------------

     (KEYWORD COMPONENT ...)

   A parenthesized expression that starts with a "syntactic keyword" is
a "special form".  Each special form has its own syntax, which is
described later in the manual.

   Note that syntactic keywords and variable bindings share the same
namespace.  A local variable binding may shadow a syntactic keyword, and
a local syntactic-keyword definition may shadow a variable binding.

   The following list contains all of the syntactic keywords that are
defined when MIT/GNU Scheme is initialized:

access                   and                      begin
case                     cond                     cons-stream
declare                  define                   
define-integrable        define-structure         define-syntax
delay                    do                       er-macro-transformer
fluid-let                if                       lambda
let                      let*                     let*-syntax
let-syntax               letrec                   letrec-syntax
local-declare            named-lambda             non-hygienic-macro-transformer
or                       quasiquote               quote
rsc-macro-transformer    sc-macro-transformer     set!
syntax-rules             the-environment          


File: mit-scheme-ref.info,  Node: Procedure Call Syntax,  Prev: Special Form Syntax,  Up: Expressions

1.4.4 Procedure Call Syntax
---------------------------

     (OPERATOR OPERAND ...)

   A "procedure call" is written by simply enclosing in parentheses
expressions for the procedure to be called (the "operator") and the
arguments to be passed to it (the "operands").  The OPERATOR and
OPERAND expressions are evaluated and the resulting procedure is passed
the resulting arguments.  *Note Lambda Expressions::, for a more
complete description of this.

   Another name for the procedure call expression is "combination".
This word is more specific in that it always refers to the expression;
"procedure call" sometimes refers to the _process_ of calling a
procedure.

   Unlike some other dialects of Lisp, Scheme always evaluates the
operator expression and the operand expressions with the same
evaluation rules, and the order of evaluation is unspecified.

     (+ 3 4)                                 =>  7
     ((if #f = *) 3 4)                       =>  12

   A number of procedures are available as the values of variables in
the initial environment; for example, the addition and multiplication
procedures in the above examples are the values of the variables `+'
and `*'.  New procedures are created by evaluating `lambda' expressions.

   If the OPERATOR is a syntactic keyword, then the expression is not
treated as a procedure call: it is a special form.


File: mit-scheme-ref.info,  Node: Special Forms,  Next: Equivalence Predicates,  Prev: Overview,  Up: Top

2 Special Forms
***************

A special form is an expression that follows special evaluation rules.
This chapter describes the basic Scheme special forms.

* Menu:

* Lambda Expressions::
* Lexical Binding::
* Dynamic Binding::
* Definitions::
* Assignments::
* Quoting::
* Conditionals::
* Sequencing::
* Iteration::
* Structure Definitions::
* Macros::
* SRFI syntax::


File: mit-scheme-ref.info,  Node: Lambda Expressions,  Next: Lexical Binding,  Prev: Special Forms,  Up: Special Forms

2.1 Lambda Expressions
======================

 -- special form: lambda formals expression expression ...
     A `lambda' expression evaluates to a procedure.  The environment in
     effect when the `lambda' expression is evaluated is remembered as
     part of the procedure; it is called the "closing environment".
     When the procedure is later called with some arguments, the closing
     environment is extended by binding the variables in the formal
     parameter list to fresh locations, and the locations are filled
     with the arguments according to rules about to be given.  The new
     environment created by this process is referred to as the
     "invocation environment".

     Once the invocation environment has been constructed, the
     EXPRESSIONs in the body of the `lambda' expression are evaluated
     sequentially in it.  This means that the region of the variables
     bound by the `lambda' expression is all of the EXPRESSIONs in the
     body.  The result of evaluating the last EXPRESSION in the body is
     returned as the result of the procedure call.

     FORMALS, the formal parameter list, is often referred to as a
     "lambda list".

     The process of matching up formal parameters with arguments is
     somewhat involved.  There are three types of parameters, and the
     matching treats each in sequence:

    Required
          All of the "required" parameters are matched against the
          arguments first.  If there are fewer arguments than required
          parameters, an error of type
          `condition-type:wrong-number-of-arguments' is signalled; this
          error is also signalled if there are more arguments than
          required parameters and there are no further parameters.  

    Optional
          Once the required parameters have all been matched, the
          "optional" parameters are matched against the remaining
          arguments.  If there are fewer arguments than optional
          parameters, the unmatched parameters are bound to special
          objects called "default objects".  If there are more
          arguments than optional parameters, and there are no further
          parameters, an error of type
          `condition-type:wrong-number-of-arguments' is signalled.  

          The predicate `default-object?', which is true only of default
          objects, can be used to determine which optional parameters
          were supplied, and which were defaulted.

    Rest
          Finally, if there is a "rest" parameter (there can only be
          one), any remaining arguments are made into a list, and the
          list is bound to the rest parameter.  (If there are no
          remaining arguments, the rest parameter is bound to the empty
          list.)  

          In Scheme, unlike some other Lisp implementations, the list
          to which a rest parameter is bound is always freshly
          allocated.  It has infinite extent and may be modified
          without affecting the procedure's caller.

     Specially recognized keywords divide the FORMALS parameters into
     these three classes.  The keywords used here are `#!optional',
     `.', and `#!rest'.  Note that only `.' is defined by standard
     Scheme -- the other keywords are MIT/GNU Scheme extensions.
     `#!rest' has the same meaning as `.' in FORMALS.

     The use of these keywords is best explained by means of examples.
     The following are typical lambda lists, followed by descriptions
     of which parameters are required, optional, and rest.  We will use
     `#!rest' in these examples, but anywhere it appears `.' could be
     used instead.

    `(a b c)'
          `a', `b', and `c' are all required.  The procedure must be
          passed exactly three arguments.

    `(a b #!optional c)'
          `a' and `b' are required, `c' is optional.  The procedure may
          be passed either two or three arguments.

    `(#!optional a b c)'
          `a', `b', and `c' are all optional.  The procedure may be
          passed any number of arguments between zero and three,
          inclusive.

    `a'
    `(#!rest a)'
          These two examples are equivalent.  `a' is a rest parameter.
          The procedure may be passed any number of arguments.  Note:
          this is the only case in which `.' cannot be used in place of
          `#!rest'.

    `(a b #!optional c d #!rest e)'
          `a' and `b' are required, `c' and `d' are optional, and `e'
          is rest.  The procedure may be passed two or more arguments.

     Some examples of `lambda' expressions:

          (lambda (x) (+ x x))            =>  #[compound-procedure 53]

          ((lambda (x) (+ x x)) 4)                =>  8

          (define reverse-subtract
            (lambda (x y)
              (- y x)))
          (reverse-subtract 7 10)                 =>  3

          (define foo
            (let ((x 4))
              (lambda (y) (+ x y))))
          (foo 6)                                 =>  10

 -- special form: named-lambda formals expression expression ...
     The `named-lambda' special form is similar to `lambda', except
     that the first "required parameter" in FORMALS is not a parameter
     but the "name" of the resulting procedure; thus FORMALS must have
     at least one required parameter.  This name has no semantic
     meaning, but is included in the external representation of the
     procedure, making it useful for debugging.  In MIT/GNU Scheme,
     `lambda' is implemented as `named-lambda', with a special name
     that means "unnamed".

          (named-lambda (f x) (+ x x))    =>  #[compound-procedure 53 f]
          ((named-lambda (f x) (+ x x)) 4)        =>  8


File: mit-scheme-ref.info,  Node: Lexical Binding,  Next: Dynamic Binding,  Prev: Lambda Expressions,  Up: Special Forms

2.2 Lexical Binding
===================

The three binding constructs `let', `let*', and `letrec', give Scheme
block structure.  The syntax of the three constructs is identical, but
they differ in the regions they establish for their variable bindings.
In a `let' expression, the initial values are computed before any of
the variables become bound.  In a `let*' expression, the evaluations
and bindings are sequentially interleaved.  And in a `letrec'
expression, all the bindings are in effect while the initial values are
being computed (thus allowing mutually recursive definitions).

 -- special form: let ((VARIABLE INIT) ...) expression expression ...
     The INITs are evaluated in the current environment (in some
     unspecified order), the VARIABLEs are bound to fresh locations
     holding the results, the EXPRESSIONs are evaluated sequentially in
     the extended environment, and the value of the last EXPRESSION is
     returned.  Each binding of a VARIABLE has the EXPRESSIONs as its
     region.

     MIT/GNU Scheme allows any of the INITs to be omitted, in which
     case the corresponding VARIABLEs are unassigned.

     Note that the following are equivalent:

          (let ((VARIABLE INIT) ...) EXPRESSION EXPRESSION ...)
          ((lambda (VARIABLE ...) EXPRESSION EXPRESSION ...) INIT ...)

     Some examples:

          (let ((x 2) (y 3))
            (* x y))                              =>  6

          (let ((x 2) (y 3))
            (let ((foo (lambda (z) (+ x y z)))
                  (x 7))
              (foo 4)))                           =>  9

     *Note Iteration::, for information on "named `let'".

 -- special form: let* ((VARIABLE INIT) ...) expression expression ...
     `let*' is similar to `let', but the bindings are performed
     sequentially from left to right, and the region of a binding is
     that part of the `let*' expression to the right of the binding.
     Thus the second binding is done in an environment in which the
     first binding is visible, and so on.

     Note that the following are equivalent:

          (let* ((VARIABLE1 INIT1)
                 (VARIABLE2 INIT2)
                 ...
                 (VARIABLEN INITN))
             EXPRESSION
             EXPRESSION ...)

          (let ((VARIABLE1 INIT1))
            (let ((VARIABLE2 INIT2))
              ...
                (let ((VARIABLEN INITN))
                  EXPRESSION
                  EXPRESSION ...)
              ...))

     An example:

          (let ((x 2) (y 3))
            (let* ((x 7)
                   (z (+ x y)))
              (* z x)))                           =>  70

 -- special form: letrec ((VARIABLE INIT) ...) expression expression ...
     The VARIABLEs are bound to fresh locations holding unassigned
     values, the INITs are evaluated in the extended environment (in
     some unspecified order), each VARIABLE is assigned to the result
     of the corresponding INIT, the EXPRESSIONs are evaluated
     sequentially in the extended environment, and the value of the last
     EXPRESSION is returned.  Each binding of a VARIABLE has the entire
     `letrec' expression as its region, making it possible to define
     mutually recursive procedures.

     MIT/GNU Scheme allows any of the INITs to be omitted, in which
     case the corresponding VARIABLEs are unassigned.

          (letrec ((even?
                    (lambda (n)
                      (if (zero? n)
                          #t
                          (odd? (- n 1)))))
                   (odd?
                    (lambda (n)
                      (if (zero? n)
                          #f
                          (even? (- n 1))))))
            (even? 88))                           =>  #t

     One restriction on `letrec' is very important: it shall be possible
     to evaluated each INIT without assigning or referring to the value
     of any VARIABLE.  If this restriction is violated, then it is an
     error.  The restriction is necessary because Scheme passes
     arguments by value rather than by name.  In the most common uses
     of `letrec', all the INITs are `lambda' or `delay' expressions and
     the restriction is satisfied automatically.


File: mit-scheme-ref.info,  Node: Dynamic Binding,  Next: Definitions,  Prev: Lexical Binding,  Up: Special Forms

2.3 Dynamic Binding
===================

 -- special form: fluid-let ((VARIABLE INIT) ...) expression expression
          ...
     The INITs are evaluated in the current environment (in some
     unspecified order), the current values of the VARIABLEs are saved,
     the results are assigned to the VARIABLEs, the EXPRESSIONs are
     evaluated sequentially in the current environment, the VARIABLEs
     are restored to their original values, and the value of the last
     EXPRESSION is returned.

     The syntax of this special form is similar to that of `let', but
     `fluid-let' temporarily rebinds existing variables.  Unlike `let',
     `fluid-let' creates no new bindings; instead it _assigns_ the
     value of each INIT to the binding (determined by the rules of
     lexical scoping) of its corresponding VARIABLE.

     MIT/GNU Scheme allows any of the INITs to be omitted, in which
     case the corresponding VARIABLEs are temporarily unassigned.

     An error of type `condition-type:unbound-variable' is signalled if
     any of the VARIABLEs are unbound.  However, because `fluid-let'
     operates by means of side effects, it is valid for any VARIABLE to
     be unassigned when the form is entered.  

     Here is an example showing the difference between `fluid-let' and
     `let'.  First see how `let' affects the binding of a variable:

          (define variable #t)
          (define (access-variable) variable)
          variable                                =>  #t
          (let ((variable #f))
            (access-variable))                    =>  #t
          variable                                =>  #t

     `access-variable' returns `#t' in this case because it is defined
     in an environment with `variable' bound to `#t'.  `fluid-let', on
     the other hand, temporarily reuses an existing variable:

          variable                                =>  #t
          (fluid-let ((variable #f))              ;reuses old binding
            (access-variable))                    =>  #f
          variable                                =>  #t

     The "extent" of a dynamic binding is defined to be the time period
     during which the variable contains the new value.  Normally this
     time period begins when the body is entered and ends when it is
     exited; on a sequential machine it is normally a contiguous time
     period.  However, because Scheme has first-class continuations, it
     is possible to leave the body and then reenter it, as many times
     as desired.  In this situation, the extent becomes non-contiguous.

     When the body is exited by invoking a continuation, the new value
     is saved, and the variable is set to the old value.  Then, if the
     body is reentered by invoking a continuation, the old value is
     saved, and the variable is set to the new value.  In addition,
     side effects to the variable that occur both inside and outside of
     body are preserved, even if continuations are used to jump in and
     out of body repeatedly.

   Here is a complicated example that shows the interaction between
dynamic binding and continuations:

     (define (complicated-dynamic-binding)
       (let ((variable 1)
             (inside-continuation))
         (write-line variable)
         (call-with-current-continuation
          (lambda (outside-continuation)
            (fluid-let ((variable 2))
              (write-line variable)
              (set! variable 3)
              (call-with-current-continuation
               (lambda (k)
                 (set! inside-continuation k)
                 (outside-continuation #t)))
              (write-line variable)
              (set! inside-continuation #f))))
         (write-line variable)
         (if inside-continuation
             (begin
               (set! variable 4)
               (inside-continuation #f)))))

Evaluating `(complicated-dynamic-binding)' writes the following on the
console:

     1
     2
     1
     3
     4

Commentary: the first two values written are the initial binding of
`variable' and its new binding after the `fluid-let''s body is entered.
Immediately after they are written, `variable' is set to `3', and then
`outside-continuation' is invoked, causing us to exit the body.  At
this point, `1' is written, demonstrating that the original value of
`variable' has been restored, because we have left the body.  Then we
set `variable' to `4' and reenter the body by invoking
`inside-continuation'.  At this point, `3' is written, indicating that
the side effect that previously occurred within the body has been
preserved.  Finally, we exit body normally, and write `4',
demonstrating that the side effect that occurred outside of the body
was also preserved.


File: mit-scheme-ref.info,  Node: Definitions,  Next: Assignments,  Prev: Dynamic Binding,  Up: Special Forms

2.4 Definitions
===============

 -- special form: define variable [expression]
 -- special form: define FORMALS expression expression ...
     Definitions are valid in some but not all contexts where
     expressions are allowed.  Definitions may only occur at the top
     level of a program and at the beginning of a lambda body (that is,
     the body of a `lambda', `let', `let*', `letrec', `fluid-let', or
     "procedure `define'" expression).  A definition that occurs at the
     top level of a program is called a "top-level definition", and a
     definition that occurs at the beginning of a body is called an
     "internal definition".

     In the second form of `define' (called ""procedure `define'""),
     the component FORMALS is identical to the component of the same
     name in a `named-lambda' expression.  In fact, these two
     expressions are equivalent:

          (define (NAME1 NAME2 ...)
            EXPRESSION
            EXPRESSION ...)

          (define NAME1
            (named-lambda (NAME1 NAME2 ...)
              EXPRESSION
              EXPRESSION ...))

* Menu:

* Top-Level Definitions::
* Internal Definitions::


File: mit-scheme-ref.info,  Node: Top-Level Definitions,  Next: Internal Definitions,  Prev: Definitions,  Up: Definitions

2.4.1 Top-Level Definitions
---------------------------

A top-level definition,

     (define VARIABLE EXPRESSION)

has essentially the same effect as this assignment expression, if
VARIABLE is bound:

     (set! VARIABLE EXPRESSION)

   If VARIABLE is not bound, however, `define' binds VARIABLE to a new
location in the current environment before performing the assignment
(it is an error to perform a `set!' on an unbound variable).  If you
omit EXPRESSION, the variable becomes unassigned; an attempt to
reference such a variable is an error.

     (define add3
        (lambda (x) (+ x 3)))                =>  unspecified
     (add3 3)                                =>  6

     (define first car)                      =>  unspecified
     (first '(1 2))                          =>  1

     (define bar)                            =>  unspecified
     bar                                     error--> Unassigned variable


File: mit-scheme-ref.info,  Node: Internal Definitions,  Prev: Top-Level Definitions,  Up: Definitions

2.4.2 Internal Definitions
--------------------------

An "internal definition" is a definition that occurs at the beginning
of a BODY (that is, the body of a `lambda', `let', `let*', `letrec',
`fluid-let', or "procedure `define'" expression), rather than at the
top level of a program.  The variable defined by an internal definition
is local to the BODY.  That is, VARIABLE is bound rather than assigned,
and the region of the binding is the entire BODY.  For example,

     (let ((x 5))
       (define foo (lambda (y) (bar x y)))
       (define bar (lambda (a b) (+ (* a b) a)))
       (foo (+ x 3)))                        =>  45

   A BODY containing internal definitions can always be converted into
a completely equivalent `letrec' expression.  For example, the `let'
expression in the above example is equivalent to

     (let ((x 5))
       (letrec ((foo (lambda (y) (bar x y)))
                (bar (lambda (a b) (+ (* a b) a))))
         (foo (+ x 3))))


File: mit-scheme-ref.info,  Node: Assignments,  Next: Quoting,  Prev: Definitions,  Up: Special Forms

2.5 Assignments
===============

 -- special form: set! variable [expression]
     If EXPRESSION is specified, evaluates EXPRESSION and stores the
     resulting value in the location to which VARIABLE is bound.  If
     EXPRESSION is omitted, VARIABLE is altered to be unassigned; a
     subsequent reference to such a VARIABLE is an error.  In either
     case, the value of the `set!' expression is unspecified.

     VARIABLE must be bound either in some region enclosing the `set!'
     expression, or at the top level.  However, VARIABLE is permitted
     to be unassigned when the `set!' form is entered.

          (define x 2)                            =>  unspecified
          (+ x 1)                                 =>  3
          (set! x 4)                              =>  unspecified
          (+ x 1)                                 =>  5

     VARIABLE may be an `access' expression (*note Environments::).
     This allows you to assign variables in an arbitrary environment.
     For example,

          (define x (let ((y 0)) (the-environment)))
          (define y 'a)
          y                                       =>  a
          (access y x)                            =>  0
          (set! (access y x) 1)                   =>  unspecified
          y                                       =>  a
          (access y x)                            =>  1


File: mit-scheme-ref.info,  Node: Quoting,  Next: Conditionals,  Prev: Assignments,  Up: Special Forms

2.6 Quoting
===========

This section describes the expressions that are used to modify or
prevent the evaluation of objects.

 -- special form: quote datum
     `(quote DATUM)' evaluates to DATUM.  DATUM may be any external
     representation of a Scheme object (*note External
     Representations::).  Use `quote' to include literal constants in
     Scheme code.

          (quote a)                               =>  a
          (quote #(a b c))                        =>  #(a b c)
          (quote (+ 1 2))                         =>  (+ 1 2)

     `(quote DATUM)' may be abbreviated as `'DATUM'.  The two notations
     are equivalent in all respects.

          'a                                      =>  a
          '#(a b c)                               =>  #(a b c)
          '(+ 1 2)                                =>  (+ 1 2)
          '(quote a)                              =>  (quote a)
          ''a                                     =>  (quote a)

     Numeric constants, string constants, character constants, and
     boolean constants evaluate to themselves, so they don't need to be
     quoted.

          '"abc"                                  =>  "abc"
          "abc"                                   =>  "abc"
          '145932                                 =>  145932
          145932                                  =>  145932
          '#t                                     =>  #t
          #t                                      =>  #t
          '#\a                                    =>  #\a
          #\a                                     =>  #\a

 -- special form: quasiquote template
     "Backquote" or "quasiquote" expressions are useful for constructing
     a list or vector structure when most but not all of the desired
     structure is known in advance.  If no commas appear within the
     TEMPLATE, the result of evaluating ``TEMPLATE' is equivalent (in
     the sense of `equal?') to the result of evaluating `'TEMPLATE'.
     If a comma appears within the TEMPLATE, however, the expression
     following the comma is evaluated ("unquoted") and its result is
     inserted into the structure instead of the comma and the
     expression.  If a comma appears followed immediately by an at-sign
     (@), then the following expression shall evaluate to a list; the
     opening and closing parentheses of the list are then "stripped
     away" and the elements of the list are inserted in place of the
     comma at-sign expression sequence.

          `(list ,(+ 1 2) 4)                       =>  (list 3 4)

          (let ((name 'a)) `(list ,name ',name))   =>  (list a 'a)

          `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)    =>  (a 3 4 5 6 b)

          `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
                                                   =>  ((foo 7) . cons)

          `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
                                                   =>  #(10 5 2 4 3 8)

          `,(+ 2 3)                                =>  5

     Quasiquote forms may be nested.  Substitutions are made only for
     unquoted components appearing at the same nesting level as the
     outermost backquote.  The nesting level increases by one inside
     each successive quasiquotation, and decreases by one inside each
     unquotation.

          `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
               =>  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)

          (let ((name1 'x)
                (name2 'y))
             `(a `(b ,,name1 ,',name2 d) e))
               =>  (a `(b ,x ,'y d) e)

     The notations ``TEMPLATE' and (`quasiquote TEMPLATE') are
     identical in all respects.  `,EXPRESSION' is identical to `(unquote
     EXPRESSION)' and `,@EXPRESSION' is identical to `(unquote-splicing
     EXPRESSION)'.

          (quasiquote (list (unquote (+ 1 2)) 4))
               =>  (list 3 4)

          '(quasiquote (list (unquote (+ 1 2)) 4))
               =>  `(list ,(+ 1 2) 4)
               _i.e.,_ (quasiquote (list (unquote (+ 1 2)) 4))

     Unpredictable behavior can result if any of the symbols
     `quasiquote', `unquote', or `unquote-splicing' appear in a
     TEMPLATE in ways otherwise than as described above.


File: mit-scheme-ref.info,  Node: Conditionals,  Next: Sequencing,  Prev: Quoting,  Up: Special Forms

2.7 Conditionals
================

The behavior of the "conditional expressions" is determined by whether
objects are true or false.  The conditional expressions count only `#f'
as false.  They count everything else, including `#t', pairs, symbols,
numbers, strings, vectors, and procedures as true (but *note True and
False::).

   In the descriptions that follow, we say that an object has "a true
value" or "is true" when the conditional expressions treat it as true,
and we say that an object has "a false value" or "is false" when the
conditional expressions treat it as false.

 -- special form: if predicate consequent [alternative]
     PREDICATE, CONSEQUENT, and ALTERNATIVE are expressions.  An `if'
     expression is evaluated as follows: first, PREDICATE is evaluated.
     If it yields a true value, then CONSEQUENT is evaluated and its
     value is returned.  Otherwise ALTERNATIVE is evaluated and its
     value is returned.  If PREDICATE yields a false value and no
     ALTERNATIVE is specified, then the result of the expression is
     unspecified.

     An `if' expression evaluates either CONSEQUENT or ALTERNATIVE,
     never both.  Programs should not depend on the value of an `if'
     expression that has no ALTERNATIVE.

          (if (> 3 2) 'yes 'no)                   =>  yes
          (if (> 2 3) 'yes 'no)                   =>  no
          (if (> 3 2)
              (- 3 2)
              (+ 3 2))                            =>  1

 -- special form: cond clause clause ...
     Each CLAUSE has this form:

          (PREDICATE EXPRESSION ...)

     where PREDICATE is any expression.  The last CLAUSE may be an
     "`else' clause", which has the form:

          (else EXPRESSION EXPRESSION ...)

     A `cond' expression does the following:

       1. Evaluates the PREDICATE expressions of successive CLAUSEs in
          order, until one of the PREDICATEs evaluates to a true value.

       2. When a PREDICATE evaluates to a true value, `cond' evaluates
          the EXPRESSIONs in the associated CLAUSE in left to right
          order, and returns the result of evaluating the last
          EXPRESSION in the CLAUSE as the result of the entire `cond'
          expression.

          If the selected CLAUSE contains only the PREDICATE and no
          EXPRESSIONs, `cond' returns the value of the PREDICATE as the
          result.

       3. If all PREDICATEs evaluate to false values, and there is no
          `else' clause, the result of the conditional expression is
          unspecified; if there is an `else' clause, `cond' evaluates
          its EXPRESSIONs (left to right) and returns the value of the
          last one.

          (cond ((> 3 2) 'greater)
                ((< 3 2) 'less))                  =>  greater

          (cond ((> 3 3) 'greater)
                ((< 3 3) 'less)
                (else 'equal))                    =>  equal

     Normally, programs should not depend on the value of a `cond'
     expression that has no `else' clause.  However, some Scheme
     programmers prefer to write `cond' expressions in which at least
     one of the PREDICATEs is always true.  In this style, the final
     CLAUSE is equivalent to an `else' clause.

     Scheme supports an alternative CLAUSE syntax:

          (PREDICATE => RECIPIENT)

     where RECIPIENT is an expression.  If PREDICATE evaluates to a
     true value, then RECIPIENT is evaluated.  Its value must be a
     procedure of one argument; this procedure is then invoked on the
     value of the PREDICATE.

          (cond ((assv 'b '((a 1) (b 2))) => cadr)
                (else #f))                        =>  2

 -- special form: case key clause clause ...
     KEY may be any expression.  Each CLAUSE has this form:

          ((OBJECT ...) EXPRESSION EXPRESSION ...)

     No OBJECT is evaluated, and all the OBJECTs must be distinct.  The
     last CLAUSE may be an "`else' clause", which has the form:

          (else EXPRESSION EXPRESSION ...)

     A `case' expression does the following:

       1. Evaluates KEY and compares the result with each OBJECT.

       2. If the result of evaluating KEY is equivalent (in the sense of
          `eqv?'; *note Equivalence Predicates::) to an OBJECT, `case'
          evaluates the EXPRESSIONs in the corresponding CLAUSE from
          left to right and returns the result of evaluating the last
          EXPRESSION in the CLAUSE as the result of the `case'
          expression.  

       3. If the result of evaluating KEY is different from every
          OBJECT, and if there's an `else' clause, `case' evaluates its
          EXPRESSIONs and returns the result of the last one as the
          result of the `case' expression.  If there's no `else'
          clause, `case' returns an unspecified result.  Programs
          should not depend on the value of a `case' expression that
          has no `else' clause.

     For example,

          (case (* 2 3)
             ((2 3 5 7) 'prime)
             ((1 4 6 8 9) 'composite))            =>  composite

          (case (car '(c d))
             ((a) 'a)
             ((b) 'b))                            =>  unspecified

          (case (car '(c d))
             ((a e i o u) 'vowel)
             ((w y) 'semivowel)
             (else 'consonant))                   =>  consonant

 -- special form: and expression ...
     The EXPRESSIONs are evaluated from left to right, and the value of
     the first EXPRESSION that evaluates to a false value is returned.
     Any remaining EXPRESSIONs are not evaluated.  If all the
     EXPRESSIONs evaluate to true values, the value of the last
     EXPRESSION is returned.  If there are no EXPRESSIONs then `#t' is
     returned.

          (and (= 2 2) (> 2 1))                   =>  #t
          (and (= 2 2) (< 2 1))                   =>  #f
          (and 1 2 'c '(f g))                     =>  (f g)
          (and)                                   =>  #t

 -- special form: or expression ...
     The EXPRESSIONs are evaluated from left to right, and the value of
     the first EXPRESSION that evaluates to a true value is returned.
     Any remaining EXPRESSIONs are not evaluated.  If all EXPRESSIONs
     evaluate to false values, the value of the last EXPRESSION is
     returned.  If there are no EXPRESSIONs then `#f' is returned.

          (or (= 2 2) (> 2 1))                    =>  #t
          (or (= 2 2) (< 2 1))                    =>  #t
          (or #f #f #f)                           =>  #f
          (or (memq 'b '(a b c)) (/ 3 0))         =>  (b c)


File: mit-scheme-ref.info,  Node: Sequencing,  Next: Iteration,  Prev: Conditionals,  Up: Special Forms

2.8 Sequencing
==============

The `begin' special form is used to evaluate expressions in a
particular order.

 -- special form: begin expression expression ...
     The EXPRESSIONs are evaluated sequentially from left to right, and
     the value of the last EXPRESSION is returned.  This expression
     type is used to sequence side effects such as input and output.

          (define x 0)
          (begin (set! x 5)
                 (+ x 1))                 =>  6

          (begin (display "4 plus 1 equals ")
                 (display (+ 4 1)))
                                          -|  4 plus 1 equals 5
                                          =>  unspecified

     Often the use of `begin' is unnecessary, because many special forms
     already support sequences of expressions (that is, they have an
     implicit `begin').  Some of these special forms are:

          case
          cond
          define          ;"procedure `define'" only
          do
          fluid-let
          lambda
          let
          let*
          letrec
          named-lambda
     
     The obsolete special form `sequence' is identical to `begin'.  It
     should not be used in new code.


File: mit-scheme-ref.info,  Node: Iteration,  Next: Structure Definitions,  Prev: Sequencing,  Up: Special Forms

2.9 Iteration
=============

The "iteration expressions" are: "named `let'" and `do'.  They are also
binding expressions, but are more commonly referred to as iteration
expressions.  Because Scheme is properly tail-recursive, you don't need
to use these special forms to express iteration; you can simply use
appropriately written "recursive" procedure calls.

 -- special form: let name ((VARIABLE INIT) ...) expression expression
          ...
     MIT/GNU Scheme permits a variant on the syntax of `let' called
     "named `let'" which provides a more general looping construct than
     `do', and may also be used to express recursions.

     Named `let' has the same syntax and semantics as ordinary `let'
     except that NAME is bound within the EXPRESSIONs to a procedure
     whose formal arguments are the VARIABLEs and whose body is the
     EXPRESSIONs.  Thus the execution of the EXPRESSIONs may be
     repeated by invoking the procedure named by NAME.

     MIT/GNU Scheme allows any of the INITs to be omitted, in which
     case the corresponding VARIABLEs are unassigned.

     Note: the following expressions are equivalent:

          (let NAME ((VARIABLE INIT) ...)
            EXPRESSION
            EXPRESSION ...)

          ((letrec ((NAME
                     (named-lambda (NAME VARIABLE ...)
                       EXPRESSION
                       EXPRESSION ...)))
             NAME)
           INIT ...)

     Here is an example:

          (let loop
               ((numbers '(3 -2 1 6 -5))
                (nonneg '())
                (neg '()))
            (cond ((null? numbers)
                   (list nonneg neg))
                  ((>= (car numbers) 0)
                   (loop (cdr numbers)
                         (cons (car numbers) nonneg)
                         neg))
                  (else
                   (loop (cdr numbers)
                         nonneg
                         (cons (car numbers) neg)))))

               =>  ((6 1 3) (-5 -2))

 -- special form: do ((VARIABLE INIT STEP) ...) (TEST EXPRESSION ...)
          command ...
     `do' is an iteration construct.  It specifies a set of variables to
     be bound, how they are to be initialized at the start, and how
     they are to be updated on each iteration.  When a termination
     condition is met, the loop exits with a specified result value.

     `do' expressions are evaluated as follows: The INIT expressions
     are evaluated (in some unspecified order), the VARIABLEs are bound
     to fresh locations, the results of the INIT expressions are stored
     in the bindings of the VARIABLEs, and then the iteration phase
     begins.

     Each iteration begins by evaluating TEST; if the result is false,
     then the COMMAND expressions are evaluated in order for effect,
     the STEP expressions are evaluated in some unspecified order, the
     VARIABLEs are bound to fresh locations, the results of the STEPs
     are stored in the bindings of the VARIABLEs, and the next
     iteration begins.

     If TEST evaluates to a true value, then the EXPRESSIONs are
     evaluated from left to right and the value of the last EXPRESSION
     is returned as the value of the `do' expression.  If no
     EXPRESSIONs are present, then the value of the `do' expression is
     unspecified in standard Scheme; in MIT/GNU Scheme, the value of
     TEST is returned.

     The region of the binding of a VARIABLE consists of the entire
     `do' expression except for the INITs.  It is an error for a
     VARIABLE to appear more than once in the list of `do' variables.

     A STEP may be omitted, in which case the effect is the same as if
     `(VARIABLE INIT VARIABLE)' had been written instead of `(VARIABLE
     INIT)'.

          (do ((vec (make-vector 5))
                (i 0 (+ i 1)))
              ((= i 5) vec)
             (vector-set! vec i i))               =>  #(0 1 2 3 4)

          (let ((x '(1 3 5 7 9)))
             (do ((x x (cdr x))
                  (sum 0 (+ sum (car x))))
                 ((null? x) sum)))                =>  25


File: mit-scheme-ref.info,  Node: Structure Definitions,  Next: Macros,  Prev: Iteration,  Up: Special Forms

2.10 Structure Definitions
==========================

This section provides examples and describes the options and syntax of
`define-structure', an MIT/GNU Scheme macro that is very similar to
`defstruct' in Common Lisp.  The differences between them are
summarized at the end of this section.  For more information, see
Steele's Common Lisp book.

 -- special form: define-structure (name structure-option ...)
          slot-description ...
     Each SLOT-DESCRIPTION takes one of the following forms:

          SLOT-NAME
          (SLOT-NAME DEFAULT-INIT [SLOT-OPTION VALUE]*)

     The fields NAME and SLOT-NAME must both be symbols.  The field
     DEFAULT-INIT is an expression for the initial value of the slot.
     It is evaluated each time a new instance is constructed.  If it is
     not specified, the initial content of the slot is undefined.
     Default values are only useful with a BOA constructor with
     argument list or a keyword constructor (see below).

     Evaluation of a `define-structure' expression defines a structure
     descriptor and a set of procedures to manipulate instances of the
     structure.  These instances are represented as records by default
     (*note Records::) but may alternately be lists or vectors.  The
     accessors and modifiers are marked with compiler declarations so
     that calls to them are automatically transformed into appropriate
     references.  Often, no options are required, so a simple call to
     `define-structure' looks like:

          (define-structure foo a b c)

     This defines a type descriptor `rtd:foo', a constructor
     `make-foo', a predicate `foo?', accessors `foo-a', `foo-b', and
     `foo-c', and modifiers `set-foo-a!', `set-foo-b!', and
     `set-foo-c!'.

     In general, if no options are specified, `define-structure' defines
     the following (using the simple call above as an example):

    type descriptor
          The name of the type descriptor is `"rtd:"' followed by the
          name of the structure, e.g. `rtd:foo'.  The type descriptor
          satisfies the predicate `record-type?'.

    constructor
          The name of the constructor is `"make-"' followed by the name
          of the structure, e.g. `make-foo'.  The number of arguments
          accepted by the constructor is the same as the number of
          slots; the arguments are the initial values for the slots,
          and the order of the arguments matches the order of the slot
          definitions.

    predicate
          The name of the predicate is the name of the structure
          followed by `"?"', e.g. `foo?'.  The predicate is a procedure
          of one argument, which returns `#t' if its argument is a
          record of the type defined by this structure definition, and
          `#f' otherwise.

    accessors
          For each slot, an accessor is defined.  The name of the
          accessor is formed by appending the name of the structure, a
          hyphen, and the name of the slot, e.g. `foo-a'.  The accessor
          is a procedure of one argument, which must be a record of the
          type defined by this structure definition.  The accessor
          extracts the contents of the corresponding slot in that
          record and returns it.

    modifiers
          For each slot, a modifier is defined.  The name of the
          modifier is formed by appending `"set-"', the name of the
          accessor, and `"!"', e.g. `set-foo-a!'.  The modifier is a
          procedure of two arguments, the first of which must be a
          record of the type defined by this structure definition, and
          the second of which may be any object.  The modifier modifies
          the contents of the corresponding slot in that record to be
          that object, and returns an unspecified value.

     When options are not supplied, `(NAME)' may be abbreviated to
     NAME.  This convention holds equally for STRUCTURE-OPTIONS and
     SLOT-OPTIONS.  Hence, these are equivalent:

          (define-structure foo a b c)
          (define-structure (foo) (a) b (c))

     as are

          (define-structure (foo keyword-constructor) a b c)
          (define-structure (foo (keyword-constructor)) a b c)

     When specified as option values, `false' and `nil' are equivalent
     to `#f', and `true' and `t' are equivalent to `#t'.

   Possible SLOT-OPTIONS are:

 -- slot option: read-only value
     When given a VALUE other than `#f', this specifies that no
     modifier should be created for the slot.

 -- slot option: type type-descriptor
     This is accepted but not presently used.

   Possible STRUCTURE-OPTIONS are:

 -- structure option: predicate [name]
     This option controls the definition of a predicate procedure for
     the structure.  If NAME is not given, the predicate is defined with
     the default name (see above).  If NAME is `#f', the predicate is
     not defined at all.  Otherwise, NAME must be a symbol, and the
     predicate is defined with that symbol as its name.

 -- structure option: copier [name]
     This option controls the definition of a procedure to copy
     instances of the structure.  This is a procedure of one argument,
     a structure instance, that makes a newly allocated copy of the
     structure and returns it.  If NAME is not given, the copier is
     defined, and the name of the copier is `"copy-"' followed by the
     structure name (e.g.  `copy-foo').  If NAME is `#f', the copier is
     not defined.  Otherwise, NAME must be a symbol, and the copier is
     defined with that symbol as its name.

 -- structure option: print-procedure expression
     Evaluating EXPRESSION must yield a procedure of two arguments,
     which is used to print instances of the structure.  The procedure
     is an "unparser method" (*note Custom Output::).  If the structure
     instances are records, this option has the same effect as calling
     `set-record-type-unparser-method!'.  

 -- structure option: constructor [name [argument-list]]
     This option controls the definition of constructor procedures.
     These constructor procedures are called "BOA constructors", for "By
     Order of Arguments", because the arguments to the constructor
     specify the initial contents of the structure's slots by the order
     in which they are given.  This is as opposed to "keyword
     constructors", which specify the initial contents using keywords,
     and in which the order of arguments is irrelevant.

     If NAME is not given, a constructor is defined with the default
     name and arguments (see above).  If NAME is `#f', no constructor
     is defined; ARGUMENT-LIST may not be specified in this case.
     Otherwise, NAME must be a symbol, and a constructor is defined
     with that symbol as its name.  If NAME is a symbol, ARGUMENT-LIST
     is optionally allowed; if it is omitted, the constructor accepts
     one argument for each slot in the structure definition, in the
     same order in which the slots appear in the definition.
     Otherwise, ARGUMENT-LIST must be a lambda list (*note Lambda
     Expressions::), and each of the parameters of the lambda list must
     be the name of a slot in the structure.  The arguments accepted by
     the constructor are defined by this lambda list.  Any slot that is
     not specified by the lambda list is initialized to the
     DEFAULT-INIT as specified above; likewise for any slot specified
     as an optional parameter when the corresponding argument is not
     supplied.

     If the `constructor' option is specified, the default constructor
     is not defined.  Additionally, the `constructor' option may be
     specified multiple times to define multiple constructors with
     different names and argument lists.

          (define-structure (foo
                             (constructor make-foo (#!optional a b)))
            (a 6 read-only #t)
            (b 9))

 -- structure option: keyword-constructor [name]
     This option controls the definition of keyword constructor
     procedures.  A "keyword constructor" is a procedure that accepts
     arguments that are alternating slot names and values.  If NAME is
     omitted, a keyword constructor is defined, and the name of the
     constructor is `"make-"' followed by the name of the structure
     (e.g.  `make-foo').  Otherwise, NAME must be a symbol, and a
     keyword constructor is defined with this symbol as its name.

     If the `keyword-constructor' option is specified, the default
     constructor is not defined.  Additionally, the
     `keyword-constructor' option may be specified multiple times to
     define multiple keyword constructors; this is usually not done
     since such constructors would all be equivalent.

          (define-structure (foo (keyword-constructor make-bar)) a b)
          (foo-a (make-bar 'b 20 'a 19))         => 19

 -- structure option: type-descriptor name
     This option cannot be used with the `type' or `named' options.

     By default, structures are implemented as records.  The name of the
     structure is defined to hold the type descriptor of the record
     defined by the structure.  The `type-descriptor' option specifies a
     different name to hold the type descriptor.

          (define-structure foo a b)
          foo             => #[record-type 18]

          (define-structure (bar (type-descriptor <bar>)) a b)
          bar             error--> Unbound variable: bar
          <bar>         => #[record-type 19]

 -- structure option: conc-name [name]
     By default, the prefix for naming accessors and modifiers is the
     name of the structure followed by a hyphen.  The `conc-name'
     option can be used to specify an alternative.  If NAME is not
     given, the prefix is the name of the structure followed by a
     hyphen (the default).  If NAME is `#f', the slot names are used
     directly, without prefix.  Otherwise, NAME must a symbol, and that
     symbol is used as the prefix.

          `(define-structure (foo (conc-name moby/)) a b)'

     defines accessors `moby/a' and `moby/b', and modifiers
     `set-moby/a!' and `set-moby/b!'.

          `(define-structure (foo (conc-name #f)) a b)'

     defines accessors `a' and `b', and modifiers `set-a!' and `set-b!'.

 -- structure option: type representation-type
     This option cannot be used with the `type-descriptor' option.

     By default, structures are implemented as records.  The `type'
     option overrides this default, allowing the programmer to specify
     that the structure be implemented using another data type.  The
     option value REPRESENTATION-TYPE specifies the alternate data
     type; it is allowed to be one of the symbols `vector' or `list',
     and the data type used is the one corresponding to the symbol.

     If this option is given, and the `named' option is not specified,
     the representation will not be tagged, and neither a predicate nor
     a type descriptor will be defined; also, the `print-procedure'
     option may not be given.

          (define-structure (foo (type list)) a b)
          (make-foo 1 2)                          => (1 2)

 -- structure option: named [expression]
     This is valid only in conjunction with the `type' option and
     specifies that the structure instances be tagged to make them
     identifiable as instances of this structure type.  This option
     cannot be used with the `type-descriptor' option.

     In the usual case, where EXPRESSION is not given, the `named'
     option causes a type descriptor and predicate to be defined for the
     structure (recall that the `type' option without `named'
     suppresses their definition), and also defines a default unparser
     method for the structure instances (which can be overridden by the
     `print-procedure' option).  If the default unparser method is not
     wanted then the `print-procedure' option should be specified as
     `#F'.  This causes the structure to be printed in its native
     representation, as a list or vector, which includes the type
     descriptor.  The type descriptor is a unique object, _not_ a
     record type, that describes the structure instances and is
     additionally stored in the structure instances to identify them:
     if the representation type is `vector', the type descriptor is
     stored in the zero-th slot of the vector, and if the
     representation type is `list', it is stored as the first element
     of the list.

          (define-structure (foo (type vector) named) a b c)
          (vector-ref (make-foo 1 2 3) 0) => #[structure-type 52]

     If EXPRESSION is specified, it is an expression that is evaluated
     to yield a tag object.  The EXPRESSION is evaluated once when the
     structure definition is evaluated (to specify the unparser
     method), and again whenever a predicate or constructor is called.
     Because of this, EXPRESSION is normally a variable reference or a
     constant.  The value yielded by EXPRESSION may be any object at
     all.  That object is stored in the structure instances in the same
     place that the type descriptor is normally stored, as described
     above.  If EXPRESSION is specified, no type descriptor is defined,
     only a predicate.

          (define-structure (foo (type vector) (named 'foo)) a b c)
          (vector-ref (make-foo 1 2 3) 0) => foo

 -- structure option: safe-accessors [boolean]
     This option allows the programmer to have some control over the
     safety of the slot accessors (and modifiers) generated by
     `define-structure'.  If `safe-accessors' is not specified, or if
     BOOLEAN is `#f', then the accessors are optimized for speed at the
     expense of safety; when compiled, the accessors will turn into
     very fast inline sequences, usually one to three machine
     instructions in length.  However, if `safe-accessors' is specified
     and BOOLEAN is either omitted or `#t', then the accessors are
     optimized for safety, will check the type and structure of their
     argument, and will be close-coded.

          (define-structure (foo safe-accessors) a b c)

 -- structure option: initial-offset offset
     This is valid only in conjunction with the `type' option.  OFFSET
     must be an exact non-negative integer and specifies the number of
     slots to leave open at the beginning of the structure instance
     before the specified slots are allocated.  Specifying an OFFSET of
     zero is equivalent to omitting the `initial-offset' option.

     If the `named' option is specified, the structure tag appears in
     the first slot, followed by the "offset" slots, and then the
     regular slots.  Otherwise, the "offset" slots come first, followed
     by the regular slots.

          (define-structure (foo (type vector) (initial-offset 3))
            a b c)
          (make-foo 1 2 3)                => #(() () () 1 2 3)

   The essential differences between MIT/GNU Scheme's `define-structure'
and Common Lisp's `defstruct' are:

   * The default constructor procedure takes positional arguments, in
     the same order as specified in the definition of the structure.  A
     keyword constructor may be specified by giving the option
     `keyword-constructor'.

   * BOA constructors are described using Scheme lambda lists.  Since
     there is nothing corresponding to `&aux' in Scheme lambda lists,
     this functionality is not implemented.

   * By default, no `copier' procedure is defined.

   * The side-effect procedure corresponding to the accessor `foo' is
     given the name `set-foo!'.

   * Keywords are ordinary symbols - use `foo' instead of `:foo'.

   * The option values `false', `nil', `true', and `t' are treated as
     if the appropriate boolean constant had been specified instead.

   * The `print-function' option is named `print-procedure'.  Its
     argument is a procedure of two arguments (the unparser state and
     the structure instance) rather than three as in Common Lisp.

   * By default, named structures are tagged with a unique object of
     some kind.  In Common Lisp, the structures are tagged with
     symbols.  This depends on the Common Lisp package system to help
     generate unique tags; MIT/GNU Scheme has no such way to generate
     unique symbols.

   * The `named' option may optionally take an argument, which is
     normally the name of a variable (any expression may be used, but
     it is evaluated whenever the tag name is needed).  If used,
     structure instances will be tagged with that variable's value.
     The variable must be defined when `define-structure' is evaluated.

   * The `type' option is restricted to the values `vector' and `list'.

   * The `include' option is not implemented.


File: mit-scheme-ref.info,  Node: Macros,  Next: SRFI syntax,  Prev: Structure Definitions,  Up: Special Forms

2.11 Macros
===========

(This section is largely taken from the `Revised^4 Report on the
Algorithmic Language Scheme'.  The section on Syntactic Closures is
derived from a document written by Chris Hanson.  The section on
Explicit Renaming is derived from a document written by William
Clinger.)

   Scheme programs can define and use new derived expression types,
called "macros".  Program-defined expression types have the syntax

     (KEYWORD DATUM ...)

where KEYWORD is an identifier that uniquely determines the expression
type.  This identifier is called the "syntactic keyword", or simply
"keyword", of the macro.  The number of the DATUMs, and their syntax,
depends on the expression type.

   Each instance of a macro is called a "use" of the macro.  The set of
rules that specifies how a use of a macro is transcribed into a more
primitive expression is called the "transformer" of the macro.

   MIT/GNU Scheme also supports "anonymous syntactic keywords".  This
means that it's not necessary to bind a macro transformer to a syntactic
keyword before it is used.  Instead, any macro-transformer expression
can appear as the first element of a form, and the form will be expanded
by the transformer.

   The macro definition facility consists of these parts:

   * A set of expressions used to establish that certain identifiers are
     macro keywords, associate them with macro transformers, and
     control the scope within which a macro is defined.

   * A standard high-level pattern language for specifying macro
     transformers, introduced by the `syntax-rules' special form.

   * Two non-standard low-level languages for specifying macro
     transformers, "syntactic closures" and "explicit renaming".

   The syntactic keyword of a macro may shadow variable bindings, and
local variable bindings may shadow keyword bindings.  All macros
defined using the pattern language are "hygienic" and "referentially
transparent" and thus preserve Scheme's lexical scoping:

   * If a macro transformer inserts a binding for an identifier
     (variable or keyword), the identifier will in effect be renamed
     throughout its scope to avoid conflicts with other identifiers.

   * If a macro transformer inserts a free reference to an identifier,
     the reference refers to the binding that was visible where the
     transformer was specified, regardless of any local bindings that
     may surround the use of the macro.

* Menu:

* Syntactic Binding Constructs::
* Pattern Language::
* Syntactic Closures::
* Explicit Renaming::


File: mit-scheme-ref.info,  Node: Syntactic Binding Constructs,  Next: Pattern Language,  Prev: Macros,  Up: Macros

2.11.1 Binding Constructs for Syntactic Keywords
------------------------------------------------

`let-syntax', `letrec-syntax', `let*-syntax' and `define-syntax' are
analogous to `let', `letrec', `let*' and `define', but they bind
syntactic keywords to macro transformers instead of binding variables
to locations that contain values.

   Any argument named TRANSFORMER-SPEC must be a macro-transformer
expression, which is one of the following:

   * A macro transformer defined by the pattern language and denoted by
     the syntactic keyword `syntax-rules'.

   * A macro transformer defined by one of the low-level mechanisms and
     denoted by one of the syntactic keywords `sc-macro-transformer',
     `rsc-macro-transformer', or `er-macro-transformer'.

   * A syntactic keyword bound in the enclosing environment.  This is
     used to bind another name to an existing macro transformer.

 -- special form: let-syntax bindings expression expression ...
     BINDINGS should have the form

          ((KEYWORD TRANSFORMER-SPEC) ...)

     Each KEYWORD is an identifier, each TRANSFORMER-SPEC is a a
     macro-transformer expression, and the body is a sequence of one or
     more expressions.  It is an error for a KEYWORD to appear more
     than once in the list of keywords being bound.

     The EXPRESSIONs are expanded in the syntactic environment obtained
     by extending the syntactic environment of the `let-syntax'
     expression with macros whose keywords are the KEYWORDs, bound to
     the specified transformers.  Each binding of a KEYWORD has the
     EXPRESSIONs as its region.

          (let-syntax ((when (syntax-rules ()
                               ((when test stmt1 stmt2 ...)
                                (if test
                                    (begin stmt1
                                           stmt2 ...))))))
            (let ((if #t))
              (when if (set! if 'now))
              if))                           =>  now

          (let ((x 'outer))
            (let-syntax ((m (syntax-rules () ((m) x))))
              (let ((x 'inner))
                (m))))                       =>  outer

 -- special form: letrec-syntax bindings expression expression ...
     The syntax of `letrec-syntax' is the same as for `let-syntax'.

     The EXPRESSIONs are expanded in the syntactic environment obtained
     by extending the syntactic environment of the `letrec-syntax'
     expression with macros whose keywords are the KEYWORDs, bound to
     the specified transformers.  Each binding of a KEYWORD has the
     BINDINGS as well as the EXPRESSIONs within its region, so the
     transformers can transcribe expressions into uses of the macros
     introduced by the `letrec-syntax' expression.

          (letrec-syntax
            ((my-or (syntax-rules ()
                      ((my-or) #f)
                      ((my-or e) e)
                      ((my-or e1 e2 ...)
                       (let ((temp e1))
                         (if temp
                             temp
                             (my-or e2 ...)))))))
            (let ((x #f)
                  (y 7)
                  (temp 8)
                  (let odd?)
                  (if even?))
              (my-or x
                     (let temp)
                     (if y)
                     y)))        =>  7

 -- special form: let*-syntax bindings expression expression ...
     The syntax of `let*-syntax' is the same as for `let-syntax'.

     The EXPRESSIONs are expanded in the syntactic environment obtained
     by extending the syntactic environment of the `letrec-syntax'
     expression with macros whose keywords are the KEYWORDs, bound to
     the specified transformers.  Each binding of a KEYWORD has the
     subsequent BINDINGS as well as the EXPRESSIONs within its region.
     Thus

          (let*-syntax
             ((a (syntax-rules ...))
              (b (syntax-rules ...)))
            ...)

     is equivalent to

          (let-syntax ((a (syntax-rules ...)))
            (let-syntax ((b (syntax-rules ...)))
              ...))

 -- special form: define-syntax keyword transformer-spec
     KEYWORD is an identifier, and TRANSFORMER-SPEC is a macro
     transformer expression.  The syntactic environment is extended by
     binding the KEYWORD to the specified transformer.

     The region of the binding introduced by `define-syntax' is the
     entire block in which it appears.  However, the KEYWORD may only
     be used after it has been defined.

     MIT/GNU Scheme permits `define-syntax' to appear both at top level
     and within `lambda' bodies.  The Revised^4 Report permits only
     top-level uses of `define-syntax'.

     When compiling a program, a top-level instance of `define-syntax'
     both defines the syntactic keyword and generates code that will
     redefine the keyword when the program is loaded.  This means that
     the same syntax can be used for defining macros that will be used
     during compilation and for defining macros to be used at run time.

     Although macros may expand into definitions and syntax definitions
     in any context that permits them, it is an error for a definition
     or syntax definition to shadow a syntactic keyword whose meaning
     is needed to determine whether some form in the group of forms
     that contains the shadowing definition is in fact a definition,
     or, for internal definitions, is needed to determine the boundary
     between the group and the expressions that follow the group.  For
     example, the following are errors:

          (define define 3)

          (begin (define begin list))

          (let-syntax
            ((foo (syntax-rules ()
                    ((foo (proc args ...) body ...)
                     (define proc
                       (lambda (args ...)
                         body ...))))))
            (let ((x 3))
              (foo (plus x y) (+ x y))
              (define foo x)
              (plus foo x)))


File: mit-scheme-ref.info,  Node: Pattern Language,  Next: Syntactic Closures,  Prev: Syntactic Binding Constructs,  Up: Macros

2.11.2 Pattern Language
-----------------------

MIT/GNU Scheme supports a high-level pattern language for specifying
macro transformers.  This pattern language is defined by the Revised^4
Report and is portable to other conforming Scheme implementations.  To
use the pattern language, specify a TRANSFORMER-SPEC as a
`syntax-rules' form:

 -- special form: syntax-rules literals syntax-rule ...
     LITERALS is a list of identifiers and each SYNTAX-RULE should be
     of the form

          (PATTERN TEMPLATE)

     The PATTERN in a SYNTAX-RULE is a list PATTERN that begins with
     the keyword for the macro.

     A PATTERN is either an identifier, a constant, or one of the
     following

          (PATTERN ...)
          (PATTERN PATTERN ... . PATTERN)
          (PATTERN ... PATTERN ELLIPSIS)

     and a template is either an identifier, a constant, or one of the
     following

          (ELEMENT ...)
          (ELEMENT ELEMENT ... . TEMPLATE)

     where an ELEMENT is a TEMPLATE optionally followed by an ELLIPSIS
     and an ELLIPSIS is the identifier `...' (which cannot be used as
     an identifier in either a template or a pattern).

     An instance of `syntax-rules' produces a new macro transformer by
     specifying a sequence of hygienic rewrite rules.  A use of a macro
     whose keyword is associated with a transformer specified by
     `syntax-rules' is matched against the patterns contained in the
     SYNTAX-RULEs, beginning with the leftmost SYNTAX-RULE.  When a
     match is found, the macro use is transcribed hygienically
     according to the template.

     An identifier that appears in the pattern of a SYNTAX-RULE is a
     "pattern-variable", unless it is the keyword that begins the
     pattern, is listed in LITERALS, or is the identifier `...'.
     Pattern variables match arbitrary input elements and are used to
     refer to elements of the input in the template.  It is an error
     for the same pattern variable to appear more than once in a
     PATTERN.

     The keyword at the beginning of the pattern in a SYNTAX-RULE is
     not involved in the matching and is not considered a pattern
     variable or literal identifier.

     Identifiers that appear in LITERALS are interpreted as literal
     identifiers to be matched against corresponding subforms of the
     input.  A subform in the input matches a literal identifier if and
     only if it is an identifier and either both its occurrence in the
     macro expression and its occurrence in the macro definition have
     the same lexical binding, or the two identifiers are equal and
     both have no lexical binding.

     A subpattern followed by `...' can match zero or more elements of
     the input.  It is an error for `...' to appear in LITERALS.
     Within a pattern the identifier `...' must follow the last element
     of a nonempty sequence of subpatterns.

     More formally, an input form F matches a pattern P if and only if:

        * P is a non-literal identifier; or

        * P is a literal identifier and F is an identifier with the
          same binding; or

        * P is a list `(P_1 ... P_N)' and F is a list of N forms that
          match P_1 through P_N, respectively; or

        * P is an improper list `(P_1 P_2 ... P_N . P_N+1)' and F is a
          list or improper list of N or more forms that match P_1
          through P_N, respectively, and whose Nth "cdr" matches P_N+1;
          or

        * P is of the form `(P_1 ... P_N P_N+1 ELLIPSIS)' where
          ELLIPSIS is the identifier `...' and F is a proper list of at
          least N forms, the first N of which match P_1 through P_N,
          respectively, and each remaining element of F matches P_N+1;
          or

        * P is a datum and F is equal to P in the sense of the `equal?'
          procedure.

     It is an error to use a macro keyword, within the scope of its
     binding, in an expression that does not match any of the patterns.

     When a macro use is transcribed according to the template of the
     matching SYNTAX RULE, pattern variables that occur in the template
     are replaced by the subforms they match in the input.  Pattern
     variables that occur in subpatterns followed by one or more
     instances of the identifier `...' are allowed only in subtemplates
     that are followed by as many instances of `...'.  They are
     replaced in the output by all of the subforms they match in the
     input, distributed as indicated.  It is an error if the output
     cannot be built up as specified.

     Identifiers that appear in the template but are not pattern
     variables or the identifier `...' are inserted into the output as
     literal identifiers.  If a literal identifier is inserted as a
     free identifier then it refers to the binding of that identifier
     within whose scope the instance of `syntax-rules' appears.  If a
     literal identifier is inserted as a bound identifier then it is in
     effect renamed to prevent inadvertent captures of free identifiers.

          (let ((=> #f))
            (cond (#t => 'ok)))           => ok

     The macro transformer for `cond' recognizes `=>' as a local
     variable, and hence an expression, and not as the top-level
     identifier `=>', which the macro transformer treats as a syntactic
     keyword.  Thus the example expands into

          (let ((=> #f))
            (if #t (begin => 'ok)))

     instead of

          (let ((=> #f))
            (let ((temp #t))
              (if temp
                  ('ok temp))))

     which would result in an invalid procedure call.


File: mit-scheme-ref.info,  Node: Syntactic Closures,  Next: Explicit Renaming,  Prev: Pattern Language,  Up: Macros

2.11.3 Syntactic Closures
-------------------------

MIT/GNU Scheme's syntax-transformation engine is an implementation of
"syntactic closures", a mechanism invented by Alan Bawden and Jonathan
Rees.  The main feature of the syntactic-closures mechanism is its
simplicity and its close relationship to the environment models
commonly used with Scheme.  Using the mechanism to write macro
transformers is somewhat cumbersome and can be confusing for the newly
initiated, but it is easily mastered.

* Menu:

* Syntax Terminology::
* SC Transformer Definition::
* SC Identifiers::


File: mit-scheme-ref.info,  Node: Syntax Terminology,  Next: SC Transformer Definition,  Prev: Syntactic Closures,  Up: Syntactic Closures

2.11.3.1 Syntax Terminology
...........................

This section defines the concepts and data types used by the syntactic
closures facility.

   * "Forms" are the syntactic entities out of which programs are
     recursively constructed.  A form is any expression, any
     definition, any syntactic keyword, or any syntactic closure.  The
     variable name that appears in a `set!' special form is also a
     form.  Examples of forms:

          17
          #t
          car
          (+ x 4)
          (lambda (x) x)
          (define pi 3.14159)
          if
          define

   * An "alias" is an alternate name for a given symbol.  It can appear
     anywhere in a form that the symbol could be used, and when quoted
     it is replaced by the symbol; however, it does not satisfy the
     predicate `symbol?'.  Macro transformers rarely distinguish
     symbols from aliases, referring to both as "identifiers".  Another
     name for an alias is "synthetic identifier"; this document uses
     both names.

   * A "syntactic environment" maps identifiers to their meanings.  More
     precisely, it determines whether an identifier is a syntactic
     keyword or a variable.  If it is a keyword, the meaning is an
     interpretation for the form in which that keyword appears.  If it
     is a variable, the meaning identifies which binding of that
     variable is referenced.  In short, syntactic environments contain
     all of the contextual information necessary for interpreting the
     meaning of a particular form.

   * A "syntactic closure" consists of a form, a syntactic environment,
     and a list of identifiers.  All identifiers in the form take their
     meaning from the syntactic environment, except those in the given
     list.  The identifiers in the list are to have their meanings
     determined later.

     A syntactic closure may be used in any context in which its form
     could have been used.  Since a syntactic closure is also a form,
     it may not be used in contexts where a form would be illegal.  For
     example, a form may not appear as a clause in the `cond' special
     form.

     A syntactic closure appearing in a quoted structure is replaced by
     its form.


File: mit-scheme-ref.info,  Node: SC Transformer Definition,  Next: SC Identifiers,  Prev: Syntax Terminology,  Up: Syntactic Closures

2.11.3.2 Transformer Definition
...............................

This section describes the special forms for defining syntactic-closures
macro transformers, and the associated procedures for manipulating
syntactic closures and syntactic environments.

 -- special form: sc-macro-transformer expression
     The EXPRESSION is expanded in the syntactic environment of the
     `sc-macro-transformer' expression, and the expanded expression is
     evaluated in the transformer environment to yield a macro
     transformer as described below.  This macro transformer is bound
     to a macro keyword by the special form in which the `transformer'
     expression appears (for example, `let-syntax').

     In the syntactic closures facility, a "macro transformer" is a
     procedure that takes two arguments, a form and a syntactic
     environment, and returns a new form.  The first argument, the
     "input form", is the form in which the macro keyword occurred.
     The second argument, the "usage environment", is the syntactic
     environment in which the input form occurred.  The result of the
     transformer, the "output form", is automatically closed in the
     "transformer environment", which is the syntactic environment in
     which the `transformer' expression occurred.

     For example, here is a definition of a `push' macro using
     `syntax-rules':

          (define-syntax push
            (syntax-rules ()
              ((push item list)
               (set! list (cons item list)))))

     Here is an equivalent definition using `sc-macro-transformer':

          (define-syntax push
            (sc-macro-transformer
             (lambda (exp env)
               (let ((item (make-syntactic-closure env '() (cadr exp)))
                     (list (make-syntactic-closure env '() (caddr exp))))
                 `(set! ,list (cons ,item ,list))))))

     In this example, the identifiers `set!' and `cons' are closed in
     the transformer environment, and thus will not be affected by the
     meanings of those identifiers in the usage environment `env'.

     Some macros may be non-hygienic by design.  For example, the
     following defines a `loop' macro that implicitly binds `exit' to an
     escape procedure.  The binding of `exit' is intended to capture
     free references to `exit' in the body of the loop, so `exit' must
     be left free when the body is closed:

          (define-syntax loop
            (sc-macro-transformer
             (lambda (exp env)
               (let ((body (cdr exp)))
                 `(call-with-current-continuation
                   (lambda (exit)
                     (let f ()
                       ,@(map (lambda (exp)
                                (make-syntactic-closure env '(exit)
                                  exp))
                              body)
                       (f))))))))

 -- special form: rsc-macro-transformer expression
     This form is an alternative way to define a syntactic-closures
     macro transformer.  Its syntax and usage are identical to
     `sc-macro-transformer', except that the roles of the usage
     environment and transformer environment are reversed.  (Hence RSC
     stands for "Reversed Syntactic Closures".)  In other words, the
     procedure specified by EXPRESSION still accepts two arguments, but
     its second argument will be the transformer environment rather
     than the usage environment, and the returned expression is closed
     in the usage environment rather than the transformer environment.

     The advantage of this arrangement is that it allows a simpler
     definition style in some situations.  For example, here is the
     `push' macro from above, rewritten in this style:

          (define-syntax push
            (rsc-macro-transformer
             (lambda (exp env)
               `(,(make-syntactic-closure env '() 'SET!)
                 ,(caddr exp)
                 (,(make-syntactic-closure env '() 'CONS)
                  ,(cadr exp)
                  ,(caddr exp))))))

     In this style only the introduced keywords are closed, while
     everything else remains open.

     Note that `rsc-macro-transformer' and `sc-macro-transformer' are
     easily interchangeable.  Here is how to emulate
     `rsc-macro-transformer' using `sc-macro-transformer'.  (This
     technique can be used to effect the opposite emulation as well.)

          (define-syntax push
            (sc-macro-transformer
             (lambda (exp usage-env)
               (capture-syntactic-environment
                (lambda (env)
                  (make-syntactic-closure usage-env '()
                    `(,(make-syntactic-closure env '() 'SET!)
                      ,(caddr exp)
                      (,(make-syntactic-closure env '() 'CONS)
                       ,(cadr exp)
                       ,(caddr exp)))))))))

   To assign meanings to the identifiers in a form, use
`make-syntactic-closure' to close the form in a syntactic environment.

 -- procedure: make-syntactic-closure environment free-names form
     ENVIRONMENT must be a syntactic environment, FREE-NAMES must be a
     list of identifiers, and FORM must be a form.
     `make-syntactic-closure' constructs and returns a syntactic
     closure of FORM in ENVIRONMENT, which can be used anywhere that
     FORM could have been used.  All the identifiers used in FORM,
     except those explicitly excepted by FREE-NAMES, obtain their
     meanings from ENVIRONMENT.

     Here is an example where FREE-NAMES is something other than the
     empty list.  It is instructive to compare the use of FREE-NAMES in
     this example with its use in the `loop' example above: the
     examples are similar except for the source of the identifier being
     left free.

          (define-syntax let1
            (sc-macro-transformer
             (lambda (exp env)
               (let ((id (cadr exp))
                     (init (caddr exp))
                     (exp (cadddr exp)))
                 `((lambda (,id)
                     ,(make-syntactic-closure env (list id) exp))
                   ,(make-syntactic-closure env '() init))))))

     `let1' is a simplified version of `let' that only binds a single
     identifier, and whose body consists of a single expression.  When
     the body expression is syntactically closed in its original
     syntactic environment, the identifier that is to be bound by
     `let1' must be left free, so that it can be properly captured by
     the `lambda' in the output form.

   In most situations, the FREE-NAMES argument to
`make-syntactic-closure' is the empty list.  In those cases, the more
succinct `close-syntax' can be used:

 -- procedure: close-syntax form environment
     ENVIRONMENT must be a syntactic environment and FORM must be a
     form.  Returns a new syntactic closure of FORM in ENVIRONMENT,
     with no free names.  Entirely equivalent to

          (make-syntactic-closure ENVIRONMENT '() FORM)

   To obtain a syntactic environment other than the usage environment,
use `capture-syntactic-environment'.

 -- procedure: capture-syntactic-environment procedure
     `capture-syntactic-environment' returns a form that will, when
     transformed, call PROCEDURE on the current syntactic environment.
     PROCEDURE should compute and return a new form to be transformed,
     in that same syntactic environment, in place of the form.

     An example will make this clear.  Suppose we wanted to define a
     simple `loop-until' keyword equivalent to

          (define-syntax loop-until
            (syntax-rules ()
              ((loop-until id init test return step)
               (letrec ((loop
                         (lambda (id)
                           (if test return (loop step)))))
                 (loop init)))))

     The following attempt at defining `loop-until' has a subtle bug:

          (define-syntax loop-until
            (sc-macro-transformer
             (lambda (exp env)
               (let ((id (cadr exp))
                     (init (caddr exp))
                     (test (cadddr exp))
                     (return (cadddr (cdr exp)))
                     (step (cadddr (cddr exp)))
                     (close
                      (lambda (exp free)
                        (make-syntactic-closure env free exp))))
                 `(letrec ((loop
                            (lambda (,id)
                              (if ,(close test (list id))
                                  ,(close return (list id))
                                  (loop ,(close step (list id)))))))
                    (loop ,(close init '())))))))

     This definition appears to take all of the proper precautions to
     prevent unintended captures.  It carefully closes the
     subexpressions in their original syntactic environment and it
     leaves the `id' identifier free in the `test', `return', and `step'
     expressions, so that it will be captured by the binding introduced
     by the `lambda' expression.  Unfortunately it uses the identifiers
     `if' and `loop' _within_ that `lambda' expression, so if the user
     of `loop-until' just happens to use, say, `if' for the identifier,
     it will be inadvertently captured.

     The syntactic environment that `if' and `loop' want to be exposed
     to is the one just outside the `lambda' expression: before the
     user's identifier is added to the syntactic environment, but after
     the identifier `loop' has been added.
     `capture-syntactic-environment' captures exactly that environment
     as follows:

          (define-syntax loop-until
            (sc-macro-transformer
             (lambda (exp env)
               (let ((id (cadr exp))
                     (init (caddr exp))
                     (test (cadddr exp))
                     (return (cadddr (cdr exp)))
                     (step (cadddr (cddr exp)))
                     (close
                      (lambda (exp free)
                        (make-syntactic-closure env free exp))))
                 `(letrec ((loop
                            ,(capture-syntactic-environment
                              (lambda (env)
                                `(lambda (,id)
                                   (,(make-syntactic-closure env '() `if)
                                    ,(close test (list id))
                                    ,(close return (list id))
                                    (,(make-syntactic-closure env '() `loop)
                                     ,(close step (list id)))))))))
                    (loop ,(close init '())))))))

     In this case, having captured the desired syntactic environment,
     it is convenient to construct syntactic closures of the
     identifiers `if' and the `loop' and use them in the body of the
     `lambda'.

     A common use of `capture-syntactic-environment' is to get the
     transformer environment of a macro transformer:

          (sc-macro-transformer
           (lambda (exp env)
             (capture-syntactic-environment
              (lambda (transformer-env)
                ...))))


File: mit-scheme-ref.info,  Node: SC Identifiers,  Prev: SC Transformer Definition,  Up: Syntactic Closures

2.11.3.3 Identifiers
....................

This section describes the procedures that create and manipulate
identifiers.  The identifier data type extends the syntactic closures
facility to be compatible with the high-level `syntax-rules' facility.

   As discussed earlier, an identifier is either a symbol or an
"alias".  An alias is implemented as a syntactic closure whose FORM is
an identifier:

     (make-syntactic-closure env '() 'a) => an alias

Aliases are implemented as syntactic closures because they behave just
like syntactic closures most of the time.  The difference is that an
alias may be bound to a new value (for example by `lambda' or
`let-syntax'); other syntactic closures may not be used this way.  If
an alias is bound, then within the scope of that binding it is looked
up in the syntactic environment just like any other identifier.

   Aliases are used in the implementation of the high-level facility
`syntax-rules'.  A macro transformer created by `syntax-rules' uses a
template to generate its output form, substituting subforms of the
input form into the template.  In a syntactic closures implementation,
all of the symbols in the template are replaced by aliases closed in
the transformer environment, while the output form itself is closed in
the usage environment.  This guarantees that the macro transformation
is hygienic, without requiring the transformer to know the syntactic
roles of the substituted input subforms.

 -- procedure: identifier? object
     Returns `#t' if OBJECT is an identifier, otherwise returns `#f'.
     Examples:

          (identifier? 'a)        => #t
          (identifier? (make-syntactic-closure env '() 'a))
                                  => #t

          (identifier? "a")       => #f
          (identifier? #\a)       => #f
          (identifier? 97)        => #f
          (identifier? #f)        => #f
          (identifier? '(a))      => #f
          (identifier? '#(a))     => #f

   The predicate `eq?' is used to determine if two identifers are "the
same".  Thus `eq?' can be used to compare identifiers exactly as it
would be used to compare symbols.  Often, though, it is useful to know
whether two identifiers "mean the same thing".  For example, the `cond'
macro uses the symbol `else' to identify the final clause in the
conditional.  A macro transformer for `cond' cannot just look for the
symbol `else', because the `cond' form might be the output of another
macro transformer that replaced the symbol `else' with an alias.
Instead the transformer must look for an identifier that "means the
same thing" in the usage environment as the symbol `else' means in the
transformer environment.

 -- procedure: identifier=? environment1 identifier1 environment2
          identifier2
     ENVIRONMENT1 and ENVIRONMENT2 must be syntactic environments, and
     IDENTIFIER1 and IDENTIFIER2 must be identifiers.  `identifier=?'
     returns `#t' if the meaning of IDENTIFIER1 in ENVIRONMENT1 is the
     same as that of IDENTIFIER2 in ENVIRONMENT2, otherwise it returns
     `#f'.  Examples:

          (let-syntax
              ((foo
                (sc-macro-transformer
                 (lambda (form env)
                   (capture-syntactic-environment
                    (lambda (transformer-env)
                      (identifier=? transformer-env 'x env 'x)))))))
            (list (foo)
                  (let ((x 3))
                    (foo))))
                                  => (#t #f)

          (let-syntax ((bar foo))
            (let-syntax
                ((foo
                  (sc-macro-transformer
                   (lambda (form env)
                     (capture-syntactic-environment
                      (lambda (transformer-env)
                        (identifier=? transformer-env 'foo
                                      env (cadr form))))))))
              (list (foo foo)
                    (foo bar))))
                                  => (#f #t)

   Sometimes it is useful to be able to introduce a new identifier that
is guaranteed to be different from any existing identifier, similarly to
the way that `generate-uninterned-symbol' is used.

 -- procedure: make-synthetic-identifier identifier
     Creates and returns and new synthetic identifier (alias) that is
     guaranteed to be different from all existing identifiers.
     IDENTIFIER is any existing identifier, which is used in deriving
     the name of the new identifier.

     This is implemented by syntactically closing IDENTIFIER in a
     special empty environment.


File: mit-scheme-ref.info,  Node: Explicit Renaming,  Prev: Syntactic Closures,  Up: Macros

2.11.4 Explicit Renaming
------------------------

"Explicit renaming" is an alternative facility for defining macro
transformers.  In the MIT/GNU Scheme implementation, explicit-renaming
transformers are implemented as an abstraction layer on top of syntactic
closures.  An explicit-renaming macro transformer is defined by an
instance of the `er-macro-transformer' keyword:

 -- special form: er-macro-transformer expression
     The EXPRESSION is expanded in the syntactic environment of the
     `er-macro-transformer' expression, and the expanded expression is
     evaluated in the transformer environment to yield a macro
     transformer as described below.  This macro transformer is bound
     to a macro keyword by the special form in which the `transformer'
     expression appears (for example, `let-syntax').

     In the explicit-renaming facility, a "macro transformer" is a
     procedure that takes three arguments, a form, a renaming
     procedure, and a comparison predicate, and returns a new form.
     The first argument, the "input form", is the form in which the
     macro keyword occurred.

     The second argument to a transformation procedure is a "renaming
     procedure" that takes the representation of an identifier as its
     argument and returns the representation of a fresh identifier that
     occurs nowhere else in the program.  For example, the
     transformation procedure for a simplified version of the `let'
     macro might be written as

          (lambda (exp rename compare)
            (let ((vars (map car (cadr exp)))
                  (inits (map cadr (cadr exp)))
                  (body (cddr exp)))
              `((lambda ,vars ,@body)
                ,@inits)))

     This would not be hygienic, however.  A hygienic `let' macro must
     rename the identifier `lambda' to protect it from being captured by
     a local binding.  The renaming effectively creates an fresh alias
     for `lambda', one that cannot be captured by any subsequent
     binding:

          (lambda (exp rename compare)
            (let ((vars (map car (cadr exp)))
                  (inits (map cadr (cadr exp)))
                  (body (cddr exp)))
              `((,(rename 'lambda) ,vars ,@body)
                ,@inits)))

     The expression returned by the transformation procedure will be
     expanded in the syntactic environment obtained from the syntactic
     environment of the macro application by binding any fresh
     identifiers generated by the renaming procedure to the denotations
     of the original identifiers in the syntactic environment in which
     the macro was defined.  This means that a renamed identifier will
     denote the same thing as the original identifier unless the
     transformation procedure that renamed the identifier placed an
     occurrence of it in a binding position.

     The renaming procedure acts as a mathematical function in the
     sense that the identifiers obtained from any two calls with the
     same argument will be the same in the sense of `eqv?'.  It is an
     error if the renaming procedure is called after the transformation
     procedure has returned.

     The third argument to a transformation procedure is a "comparison
     predicate" that takes the representations of two identifiers as its
     arguments and returns true if and only if they denote the same
     thing in the syntactic environment that will be used to expand the
     transformed macro application.  For example, the transformation
     procedure for a simplified version of the `cond' macro can be
     written as

          (lambda (exp rename compare)
            (let ((clauses (cdr exp)))
              (if (null? clauses)
                  `(,(rename 'quote) unspecified)
                  (let* ((first (car clauses))
                         (rest (cdr clauses))
                         (test (car first)))
                    (cond ((and (identifier? test)
                                (compare test (rename 'else)))
                           `(,(rename 'begin) ,@(cdr first)))
                          (else `(,(rename 'if)
                                  ,test
                                   (,(rename 'begin) ,@(cdr first))
                                   (cond ,@rest))))))))))

     In this example the identifier `else' is renamed before being
     passed to the comparison predicate, so the comparison will be true
     if and only if the test expression is an identifier that denotes
     the same thing in the syntactic environment of the expression
     being transformed as `else' denotes in the syntactic environment
     in which the `cond' macro was defined.  If `else' were not renamed
     before being passed to the comparison predicate, then it would
     match a local variable that happened to be named `else', and the
     macro would not be hygienic.

     Some macros are non-hygienic by design.  For example, the following
     defines a `loop' macro that implicitly binds `exit' to an escape
     procedure.  The binding of `exit' is intended to capture free
     references to `exit' in the body of the loop, so `exit' is not
     renamed.

          (define-syntax loop
            (er-macro-transformer
             (lambda (x r c)
               (let ((body (cdr x)))
                 `(,(r 'call-with-current-continuation)
                   (,(r 'lambda) (exit)
                    (,(r 'let) ,(r 'f) () ,@body (,(r 'f)))))))))

     Suppose a `while' macro is implemented using `loop', with the
     intent that `exit' may be used to escape from the `while' loop.
     The `while' macro cannot be written as

          (define-syntax while
            (syntax-rules ()
              ((while test body ...)
               (loop (if (not test) (exit #f))
                     body ...))))

     because the reference to `exit' that is inserted by the `while'
     macro is intended to be captured by the binding of `exit' that
     will be inserted by the `loop' macro.  In other words, this
     `while' macro is not hygienic.  Like `loop', it must be written
     using the `er-macro-transformer' syntax:

          (define-syntax while
            (er-macro-transformer
             (lambda (x r c)
               (let ((test (cadr x))
                     (body (cddr x)))
                 `(,(r 'loop)
                   (,(r 'if) (,(r 'not) ,test) (exit #f))
                   ,@body)))))


File: mit-scheme-ref.info,  Node: SRFI syntax,  Prev: Macros,  Up: Special Forms

2.12 SRFI syntax
================

Several special forms have been introduced to support some of the
Scheme Requests for Implementation (http://srfi.schemers.org/) (SRFI).
Note that MIT/GNU Scheme has for some time supported SRFI 23
(http://srfi.schemers.org/srfi-23/srfi-23.html) (error-reporting
mechanism) and SRFI 30 (http://srfi.schemers.org/srfi-30/srfi-30.html)
(nested multi-line comments), since these SRFIs reflect existing
practice rather than introducing new functionality.

* Menu:

* cond-expand (SRFI 0)::
* receive (SRFI 8)::
* and-let* (SRFI 2)::
* define-record-type (SRFI 9)::


File: mit-scheme-ref.info,  Node: cond-expand (SRFI 0),  Next: receive (SRFI 8),  Prev: SRFI syntax,  Up: SRFI syntax

2.12.1 cond-expand (SRFI 0)
---------------------------

SRFI 0 (http://srfi.schemers.org/srfi-0/srfi-0.html) is a mechanism for
portably determining the availability of SRFI
(http://srfi.schemers.org/) "features".  The `cond-expand' special form
conditionally expands according to the features available.

 -- special form: cond-expand clause clause dots
     Each CLAUSE has the form

          (FEATURE-REQUIREMENT EXPRESSION ...)

     where FEATURE-REQUIREMENT can have one of the following forms:

          FEATURE-IDENTIFIER
          (and FEATURE-REQUIREMENT ...)
          (or FEATURE-REQUIREMENT ...)
          (not FEATURE-REQUIREMENT)
          else

     (Note that at most one `else' clause may be present, and it must
     always be the last clause.)

     The `cond-expand' special form tests for the existence of features
     at macro-expansion time.  It either expands into the body of one
     of its CLAUSEs or signals an error during syntactic processing.
     `cond-expand' expands into the body of the first CLAUSE whose
     FEATURE-REQUIREMENT is currently satisfied (an `else' CLAUSE, if
     present, is selected if none of the previous CLAUSES is selected).

     A FEATURE-REQUIREMENT has an obvious interpretation as a logical
     formula, where the FEATURE-IDENTIFIER variables have meaning true
     if the feature corresponding to the FEATURE-IDENTIFIER, as
     specified in the SRFI registry, is in effect at the location of
     the `cond-expand' form, and false otherwise.  A
     FEATURE-REQUIREMENT is satisfied if its formula is true under this
     interpretation.

          (cond-expand
            ((and srfi-1 srfi-10)
             (write 1))
            ((or srfi-1 srfi-10)
             (write 2))
            (else))

          (cond-expand
            (command-line
             (define (program-name) (car (argv)))))

     The second example assumes that `command-line' is an alias for some
     feature which gives access to command line arguments.  Note that an
     error will be signaled at macro-expansion time if this feature is
     not present.

     Note that MIT/GNU Scheme allows `cond-expand' in any context where
     a special form is allowed.  This is an extension of the semantics
     defined by SRFI 0, which only allows `cond-expand' at top level.


File: mit-scheme-ref.info,  Node: receive (SRFI 8),  Next: and-let* (SRFI 2),  Prev: cond-expand (SRFI 0),  Up: SRFI syntax

2.12.2 receive (SRFI 8)
-----------------------

SRFI 8 (http://srfi.schemers.org/srfi-8/srfi-8.html) defines a
convenient syntax to bind an identifier to each of the values of a
multiple-valued expression and then evaluate an expression in the scope
of the bindings.  As an instance of this pattern, consider the
following excerpt from a `quicksort' procedure:

     (call-with-values
       (lambda ()
         (partition (precedes pivot) others))
       (lambda (fore aft)
         (append (qsort fore) (cons pivot (qsort aft)))))

   Here `partition' is a multiple-valued procedure that takes two
arguments, a predicate and a list, and returns two lists, one comprising
the list elements that satisfy the predicate, the other those that do
not.  The purpose of the expression shown is to partition the list
`others', sort each of the sublists, and recombine the results into a
sorted list.

   For our purposes, the important step is the binding of the
identifiers `fore' and `aft' to the values returned by `partition'.
Expressing the construction and use of these bindings with the
call-by-values primitive is cumbersome: One must explicitly embed the
expression that provides the values for the bindings in a parameterless
procedure, and one must explicitly embed the expression to be evaluated
in the scope of those bindings in another procedure, writing as its
parameters the identifiers that are to be bound to the values received.

   These embeddings are boilerplate, exposing the underlying binding
mechanism but not revealing anything relevant to the particular program
in which it occurs.  So the use of a syntactic abstraction that exposes
only the interesting parts - the identifiers to be bound, the
multiple-valued expression that supplies the values, and the body of the
receiving procedure - makes the code more concise and more readable:

     (receive (fore aft) (partition (precedes pivot) others)
       (append (qsort fore) (cons pivot (qsort aft))))

   The advantages are similar to those of a `let' expression over a
procedure call with a `lambda' expression as its operator.  In both
cases, cleanly separating a "header" in which the bindings are
established from a "body" in which they are used makes it easier to
follow the code.

 -- special form: receive formals expression body
     FORMALS and BODY are defined as for `lambda' (*note Lambda
     Expressions::).  Specifically, FORMALS can have the following
     forms (the use of `#!optional' and `#!rest' is also allowed in
     FORMALS but is omitted for brevity):

    `(IDENT1 ... IDENTN)'
          The environment in which the `receive' expression is
          evaluated is extended by binding IDENT1, ..., IDENTN to fresh
          locations.  The EXPRESSION is evaluated, and its values are
          stored into those locations.  (It is an error if EXPRESSION
          does not have exactly N values.)

    `IDENT'
          The environment in which the `receive' expression is
          evaluated is extended by binding IDENT to a fresh location.
          The EXPRESSION is evaluated, its values are converted into a
          newly allocated list, and the list is stored in the location
          bound to IDENT.

    `(IDENT1 ... IDENTN . IDENTN+1)'
          The environment in which the `receive' expression is
          evaluated is extended by binding IDENT1, ..., IDENTN+1 to
          fresh locations.  The EXPRESSION is evaluated.  Its first N
          values are stored into the locations bound to IDENT1 ...
          IDENTN.  Any remaining values are converted into a newly
          allocated list, which is stored into the location bound to
          IDENTN+1.  (It is an error if EXPRESSION does not have at
          least N values.)

     In any case, the expressions in BODY are evaluated sequentially in
     the extended environment.  The results of the last expression in
     the body are the values of the `receive' expression.


File: mit-scheme-ref.info,  Node: and-let* (SRFI 2),  Next: define-record-type (SRFI 9),  Prev: receive (SRFI 8),  Up: SRFI syntax

2.12.3 and-let* (SRFI 2)
------------------------

SRFI 2 (http://srfi.schemers.org/srfi-2/srfi-2.html) provides a form
that combines `and' and `let*' for a logically short-circuiting
sequential binding operator.

 -- special form: and-let* (clause ...) body
     Runs through each of the clauses left-to-right, short-circuiting
     like `and' in that the first false clause will result in the whole
     `and-let*' form returning false.  If a body is supplied, and all
     of the clauses evaluate true, then the body is evaluated
     sequentially as if in a `begin' form, and the value of the
     `and-let*' expression is the value of the last body form,
     evaluated in a tail position with respect to the `and-let*'
     expression.  If no body is supplied, the value of the last clause,
     also evaluated in a tail position with respect to the `and-let*'
     expression, is used instead.

     Each CLAUSE should have one of the following forms:

    `IDENTIFIER'
          in which case IDENTIFIER's value is tested.

    `(EXPRESSION)'
          in which case the value of EXPRESSION is tested.

    `(IDENTIFIER EXPRESSION)'
          in which case EXPRESSION is evaluated, and, if its value is
          not false, IDENTIFIER is bound to that value for the
          remainder of the clauses and the optional body.

   Example:

     (and-let* ((list (compute-list))
                ((pair? list))
                (item (car list))
                ((integer? item)))
       (sqrt item))


File: mit-scheme-ref.info,  Node: define-record-type (SRFI 9),  Prev: and-let* (SRFI 2),  Up: SRFI syntax

2.12.4 define-record-type (SRFI 9)
----------------------------------

The `define-record-type' syntax described in SRFI 9
(http://srfi.schemers.org/srfi-9/srfi-9.html) is a slight
simplification of one written for Scheme 48 by Jonathan Rees.  Unlike
many record-defining special forms, it does not create any new
identifiers.  Instead, the names of the record type, predicate,
constructor, and so on are all listed explicitly in the source.  This
has the following advantages:

   * It can be defined using a simple macro in Scheme implementations
     that provide a procedural interface for creating record types.

   * It does not restrict users to a particular naming convention.

   * Tools like `grep' and the GNU Emacs tag facility will see the
     defining occurance of each identifier.

 -- special form: define-record-type type-name (constructor-name
          field-tag ...) predicate-name field-spec ...
     TYPE-NAME, CONTRUCTOR-NAME, FIELD-TAG, and PREDICATE-NAME are
     identifiers.  FIELD-SPEC has one of these two forms:

          (FIELD-TAG ACCESSOR-NAME)
          (FIELD-TAG ACCESSOR-NAME MODIFIER-NAME)

     where FIELD-TAG, ACCESSOR-NAME, and MODIFIER-NAME are each
     identifiers.

     `define-record-type' is generative: each use creates a new record
     type that is distinct from all existing types, including other
     record types and Scheme's predefined types.  Record-type
     definitions may only occur at top-level (there are two possible
     semantics for "internal" record-type definitions, generative and
     nongenerative, and no consensus as to which is better).

     An instance of `define-record-type' is equivalent to the following
     definitions:

        * TYPE-NAME is bound to a representation of the record type
          itself.  Operations on record types, such as defining print
          methods, reflection, etc. are left to other SRFIs.

        * CONSTRUCTOR-NAME is bound to a procedure that takes as many
          arguments as there are FIELD-TAGs in the (CONSTRUCTOR-NAME
          ...) subform and returns a new TYPE-NAME record.  Fields whose
          tags are listed with CONSTRUCTOR-NAME have the corresponding
          argument as their initial value.  The initial values of all
          other fields are unspecified.

        * PREDICATE-NAME is a predicate that returns `#t' when given a
          value returned by CONSTRUCTOR-NAME and `#f' for everything
          else.

        * Each ACCESSOR-NAME is a procedure that takes a record of type
          TYPE-NAME and returns the current value of the corresponding
          field.  It is an error to pass an accessor a value which is
          not a record of the appropriate type.

        * Each MODIFIER-NAME is a procedure that takes a record of type
          TYPE-NAME and a value which becomes the new value of the
          corresponding field; an unspecified value is returned.  It is
          an error to pass a modifier a first argument which is not a
          record of the appropriate type.

     Assigning the value of any of these identifiers has no effect on
     the behavior of any of their original values.

   The following

     (define-record-type :pare
       (kons x y)
       pare?
       (x kar set-kar!)
       (y kdr))

defines `kons' to be a constructor, `kar' and `kdr' to be accessors,
`set-kar!' to be a modifier, and `pare?' to be a predicate for objects
of type `:pare'.

     (pare? (kons 1 2))        => #t
     (pare? (cons 1 2))        => #f
     (kar (kons 1 2))          => 1
     (kdr (kons 1 2))          => 2
     (let ((k (kons 1 2)))
       (set-kar! k 3)
       (kar k))                => 3


File: mit-scheme-ref.info,  Node: Equivalence Predicates,  Next: Numbers,  Prev: Special Forms,  Up: Top

3 Equivalence Predicates
************************

A "predicate" is a procedure that always returns a boolean value (`#t'
or `#f').  An "equivalence predicate" is the computational analogue of
a mathematical equivalence relation (it is symmetric, reflexive, and
transitive).  Of the equivalence predicates described in this section,
`eq?' is the finest or most discriminating, and `equal?' is the
coarsest.  `eqv?' is slightly less discriminating than `eq?'.

 -- procedure: eqv? obj1 obj2
     The `eqv?' procedure defines a useful equivalence relation on
     objects.  Briefly, it returns `#t' if OBJ1 and OBJ2 should
     normally be regarded as the same object.

     The `eqv?' procedure returns `#t' if:

        * OBJ1 and OBJ2 are both `#t' or both `#f'.

        * OBJ1 and OBJ2 are both interned symbols and

               (string=? (symbol->string OBJ1)
                         (symbol->string OBJ2))
                    => #t
          
        * OBJ1 and OBJ2 are both numbers, are numerically equal
          according to the `=' procedure, and are either both exact or
          both inexact (*note Numbers::).  

        * OBJ1 and OBJ2 are both characters and are the same character
          according to the `char=?' procedure (*note Characters::).  

        * both OBJ1 and OBJ2 are the empty list.

        * OBJ1 and OBJ2 are procedures whose location tags are equal.

        * OBJ1 and OBJ2 are pairs, vectors, strings, bit strings,
          records, cells, or weak pairs that denote the same locations
          in the store.

     The `eqv?' procedure returns `#f' if:

        * OBJ1 and OBJ2 are of different types.

        * one of OBJ1 and OBJ2 is `#t' but the other is `#f'.

        * OBJ1 and OBJ2 are symbols but

               (string=? (symbol->string OBJ1)
                         (symbol->string OBJ2))
                    => #f
          
        * one of OBJ1 and OBJ2 is an exact number but the other is an
          inexact number.

        * OBJ1 and OBJ2 are numbers for which the `=' procedure returns
          `#f'.  

        * OBJ1 and OBJ2 are characters for which the `char=?' procedure
          returns `#f'.  

        * one of OBJ1 and OBJ2 is the empty list but the other is not.

        * OBJ1 and OBJ2 are procedures that would behave differently
          (return a different value or have different side effects) for
          some arguments.

        * OBJ1 and OBJ2 are pairs, vectors, strings, bit strings,
          records, cells, or weak pairs that denote distinct locations.

     Some examples:

          (eqv? 'a 'a)                    =>  #t
          (eqv? 'a 'b)                    =>  #f
          (eqv? 2 2)                      =>  #t
          (eqv? '() '())                  =>  #t
          (eqv? 100000000 100000000)      =>  #t
          (eqv? (cons 1 2) (cons 1 2))    =>  #f
          (eqv? (lambda () 1)
                (lambda () 2))            =>  #f
          (eqv? #f 'nil)                  =>  #f
          (let ((p (lambda (x) x)))
            (eqv? p p))                   =>  #t

     The following examples illustrate cases in which the above rules
     do not fully specify the behavior of `eqv?'.  All that can be said
     about such cases is that the value returned by `eqv?' must be a
     boolean.

          (eqv? "" "")                    =>  unspecified
          (eqv? '#() '#())                =>  unspecified
          (eqv? (lambda (x) x)
                (lambda (x) x))           =>  unspecified
          (eqv? (lambda (x) x)
                (lambda (y) y))           =>  unspecified

     The next set of examples shows the use of `eqv?' with procedures
     that have local state.  `gen-counter' must return a distinct
     procedure every time, since each procedure has its own internal
     counter.  `gen-loser', however, returns equivalent procedures each
     time, since the local state does not affect the value or side
     effects of the procedures.

          (define gen-counter
            (lambda ()
              (let ((n 0))
                (lambda () (set! n (+ n 1)) n))))
          (let ((g (gen-counter)))
            (eqv? g g))                   =>  #t
          (eqv? (gen-counter) (gen-counter))
                                          =>  #f

          (define gen-loser
            (lambda ()
              (let ((n 0))
                (lambda () (set! n (+ n 1)) 27))))
          (let ((g (gen-loser)))
            (eqv? g g))                   =>  #t
          (eqv? (gen-loser) (gen-loser))
                                          =>  unspecified

          (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
                   (g (lambda () (if (eqv? f g) 'both 'g)))
            (eqv? f g))
                                          =>  unspecified

          (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
                   (g (lambda () (if (eqv? f g) 'g 'both)))
            (eqv? f g))
                                          =>  #f

     Objects of distinct types must never be regarded as the same
     object.

     Since it is an error to modify constant objects (those returned by
     literal expressions), the implementation may share structure
     between constants where appropriate.  Thus the value of `eqv?' on
     constants is sometimes unspecified.

          (let ((x '(a)))
            (eqv? x x))                    =>  #t
          (eqv? '(a) '(a))                 =>  unspecified
          (eqv? "a" "a")                   =>  unspecified
          (eqv? '(b) (cdr '(a b)))         =>  unspecified

     Rationale: The above definition of `eqv?' allows implementations
     latitude in their treatment of procedures and literals:
     implementations are free either to detect or to fail to detect
     that two procedures or two literals are equivalent to each other,
     and can decide whether or not to merge representations of
     equivalent objects by using the same pointer or bit pattern to
     represent both.

 -- procedure: eq? obj1 obj2
     `eq?' is similar to `eqv?' except that in some cases it is capable
     of discerning distinctions finer than those detectable by `eqv?'.

     `eq?' and `eqv?' are guaranteed to have the same behavior on
     symbols, booleans, the empty list, pairs, records, and non-empty
     strings and vectors.  `eq?''s behavior on numbers and characters is
     implementation-dependent, but it will always return either true or
     false, and will return true only when `eqv?' would also return
     true.  `eq?' may also behave differently from `eqv?' on empty
     vectors and empty strings.

          (eq? 'a 'a)                     =>  #t
          (eq? '(a) '(a))                 =>  unspecified
          (eq? (list 'a) (list 'a))       =>  #f
          (eq? "a" "a")                   =>  unspecified
          (eq? "" "")                     =>  unspecified
          (eq? '() '())                   =>  #t
          (eq? 2 2)                       =>  unspecified
          (eq? #\A #\A)                   =>  unspecified
          (eq? car car)                   =>  #t
          (let ((n (+ 2 3)))
            (eq? n n))                    =>  unspecified
          (let ((x '(a)))
            (eq? x x))                    =>  #t
          (let ((x '#()))
            (eq? x x))                    =>  #t
          (let ((p (lambda (x) x)))
            (eq? p p))                    =>  #t

     Rationale: It will usually be possible to implement `eq?' much more
     efficiently than `eqv?', for example, as a simple pointer
     comparison instead of as some more complicated operation.  One
     reason is that it may not be possible to compute `eqv?' of two
     numbers in constant time, whereas `eq?' implemented as pointer
     comparison will always finish in constant time.  `eq?' may be used
     like `eqv?' in applications using procedures to implement objects
     with state since it obeys the same constraints as `eqv?'.

 -- procedure: equal? obj1 obj2
     `equal?' recursively compares the contents of pairs, vectors, and
     strings, applying `eqv?' on other objects such as numbers, symbols,
     and records.  A rule of thumb is that objects are generally
     `equal?' if they print the same.  `equal?' may fail to terminate
     if its arguments are circular data structures.

          (equal? 'a 'a)                  =>  #t
          (equal? '(a) '(a))              =>  #t
          (equal? '(a (b) c)
                  '(a (b) c))             =>  #t
          (equal? "abc" "abc")            =>  #t
          (equal? 2 2)                    =>  #t
          (equal? (make-vector 5 'a)
                  (make-vector 5 'a))     =>  #t
          (equal? (lambda (x) x)
                  (lambda (y) y))         =>  unspecified


File: mit-scheme-ref.info,  Node: Numbers,  Next: Characters,  Prev: Equivalence Predicates,  Up: Top

4 Numbers
*********

(This section is largely taken from the `Revised^4 Report on the
Algorithmic Language Scheme'.)

   Numerical computation has traditionally been neglected by the Lisp
community.  Until Common Lisp there was no carefully thought out
strategy for organizing numerical computation, and with the exception of
the MacLisp system little effort was made to execute numerical code
efficiently.  This report recognizes the excellent work of the Common
Lisp committee and accepts many of their recommendations.  In some ways
this report simplifies and generalizes their proposals in a manner
consistent with the purposes of Scheme.

   It is important to distinguish between the mathematical numbers, the
Scheme numbers that attempt to model them, the machine representations
used to implement the Scheme numbers, and notations used to write
numbers.  This report uses the types _number_, _complex_, _real_,
_rational_, and _integer_ to refer to both mathematical numbers and
Scheme numbers.  Machine representations such as fixed point and
floating point are referred to by names such as _fixnum_ and _flonum_.

* Menu:

* Numerical types::
* Exactness::
* Implementation restrictions::
* Syntax of numerical constants::
* Numerical operations::
* Numerical input and output::
* Fixnum and Flonum Operations::
* Random Numbers::


File: mit-scheme-ref.info,  Node: Numerical types,  Next: Exactness,  Prev: Numbers,  Up: Numbers

4.1 Numerical types
===================

Mathematically, numbers may be arranged into a tower of subtypes in
which each level is a subset of the level above it:

     number
     complex
     real
     rational
     integer

   For example, 3 is an integer.  Therefore 3 is also a rational, a
real, and a complex.  The same is true of the Scheme numbers that model
3.  For Scheme numbers, these types are defined by the predicates
`number?', `complex?', `real?', `rational?', and `integer?'.

   There is no simple relationship between a number's type and its
representation inside a computer.  Although most implementations of
Scheme will offer at least two different representations of 3, these
different representations denote the same integer.

   Scheme's numerical operations treat numbers as abstract data, as
independent of their representation as possible.  Although an
implementation of Scheme may use fixnum, flonum, and perhaps other
representations for numbers, this should not be apparent to a casual
programmer writing simple programs.

   It is necessary, however, to distinguish between numbers that are
represented exactly and those that may not be.  For example, indexes
into data structures must be known exactly, as must some polynomial
coefficients in a symbolic algebra system.  On the other hand, the
results of measurements are inherently inexact, and irrational numbers
may be approximated by rational and therefore inexact approximations.
In order to catch uses of inexact numbers where exact numbers are
required, Scheme explicitly distinguishes exact from inexact numbers.
This distinction is orthogonal to the dimension of type.


File: mit-scheme-ref.info,  Node: Exactness,  Next: Implementation restrictions,  Prev: Numerical types,  Up: Numbers

4.2 Exactness
=============

Scheme numbers are either _exact_ or _inexact_.  A number is exact if
it was written as an exact constant or was derived from exact numbers
using only exact operations.  A number is inexact if it was written as
an inexact constant, if it was derived using inexact ingredients, or if
it was derived using inexact operations. Thus inexactness is a
contagious property of a number.

   If two implementations produce exact results for a computation that
did not involve inexact intermediate results, the two ultimate results
will be mathematically equivalent.  This is generally not true of
computations involving inexact numbers since approximate methods such as
floating point arithmetic may be used, but it is the duty of each
implementation to make the result as close as practical to the
mathematically ideal result.

   Rational operations such as `+' should always produce exact results
when given exact arguments.  If the operation is unable to produce an
exact result, then it may either report the violation of an
implementation restriction or it may silently coerce its result to an
inexact value.  *Note Implementation restrictions::.

   With the exception of `inexact->exact', the operations described in
this section must generally return inexact results when given any
inexact arguments.  An operation may, however, return an exact result if
it can prove that the value of the result is unaffected by the
inexactness of its arguments.  For example, multiplication of any number
by an exact zero may produce an exact zero result, even if the other
argument is inexact.


File: mit-scheme-ref.info,  Node: Implementation restrictions,  Next: Syntax of numerical constants,  Prev: Exactness,  Up: Numbers

4.3 Implementation restrictions
===============================

Implementations of Scheme are not required to implement the whole tower
of subtypes (*note Numerical types::), but they must implement a
coherent subset consistent with both the purposes of the implementation
and the spirit of the Scheme language.  For example, an implementation
in which all numbers are real may still be quite useful.(1)

   Implementations may also support only a limited range of numbers of
any type, subject to the requirements of this section.  The supported
range for exact numbers of any type may be different from the supported
range for inexact numbers of that type.  For example, an implementation
that uses flonums to represent all its inexact real numbers may support
a practically unbounded range of exact integers and rationals while
limiting the range of inexact reals (and therefore the range of inexact
integers and rationals) to the dynamic range of the flonum format.
Furthermore the gaps between the representable inexact integers and
rationals are likely to be very large in such an implementation as the
limits of this range are approached.

   An implementation of Scheme must support exact integers throughout
the range of numbers that may be used for indexes of lists, vectors, and
strings or that may result from computing the length of a list, vector,
or string.  The `length', `vector-length', and `string-length'
procedures must return an exact integer, and it is an error to use
anything but an exact integer as an index.  Furthermore any integer
constant within the index range, if expressed by an exact integer
syntax, will indeed be read as an exact integer, regardless of any
implementation restrictions that may apply outside this range.
Finally, the procedures listed below will always return an exact integer
result provided all their arguments are exact integers and the
mathematically expected result is representable as an exact integer
within the implementation:

     *                gcd                modulo
     +                imag-part          numerator
     -                inexact->exact     quotient
     abs              lcm                rationalize
     angle            magnitude          real-part
     ceiling          make-polar         remainder
     denominator      make-rectangular   round
     expt             max                truncate
     floor            min

   Implementations are encouraged, but not required, to support exact
integers and exact rationals of practically unlimited size and
precision, and to implement the above procedures and the `/' procedure
in such a way that they always return exact results when given exact
arguments.  If one of these procedures is unable to deliver an exact
result when given exact arguments, then it may either report a
violation of an implementation restriction or it may silently coerce its
result to an inexact number.  Such a coercion may cause an error later.

   An implementation may use floating point and other approximate
representation strategies for inexact numbers.  This report recommends,
but does not require, that the IEEE 32-bit and 64-bit floating point
standards be followed by implementations that use flonum
representations, and that implementations using other representations
should match or exceed the precision achievable using these floating
point standards.

   In particular, implementations that use flonum representations must
follow these rules: A flonum result must be represented with at least as
much precision as is used to express any of the inexact arguments to
that operation.  It is desirable (but not required) for potentially
inexact operations such as `sqrt', when applied to exact arguments, to
produce exact answers whenever possible (for example the square root of
an exact 4 ought to be an exact 2).  If, however, an exact number is
operated upon so as to produce an inexact result (as by `sqrt'), and if
the result is represented as a flonum, then the most precise flonum
format available must be used; but if the result is represented in some
other way then the representation must have at least as much precision
as the most precise flonum format available.

   Although Scheme allows a variety of written notations for numbers,
any particular implementation may support only some of them.(2) For
example, an implementation in which all numbers are real need not
support the rectangular and polar notations for complex numbers.  If an
implementation encounters an exact numerical constant that it cannot
represent as an exact number, then it may either report a violation of
an implementation restriction or it may silently represent the constant
by an inexact number.

   ---------- Footnotes ----------

   (1) MIT/GNU Scheme implements the whole tower of numerical types.
It has unlimited-precision exact integers and exact rationals.  Flonums
are used to implement all inexact reals; on machines that support IEEE
floating-point arithmetic these are double-precision floating-point
numbers.

   (2) MIT/GNU Scheme implements all of the written notations for
numbers.


File: mit-scheme-ref.info,  Node: Syntax of numerical constants,  Next: Numerical operations,  Prev: Implementation restrictions,  Up: Numbers

4.4 Syntax of numerical constants
=================================

A number may be written in binary, octal, decimal, or hexadecimal by the
use of a radix prefix.  The radix prefixes are `#b' (binary), `#o'
(octal), `#d' (decimal), and `#x' (hexadecimal).  With no radix prefix,
a number is assumed to be expressed in decimal.

   A numerical constant may be specified to be either exact or inexact
by a prefix.  The prefixes are `#e' for exact, and `#i' for inexact.
An exactness prefix may appear before or after any radix prefix that is
used.  If the written representation of a number has no exactness
prefix, the constant may be either inexact or exact.  It is inexact if
it contains a decimal point, an exponent, or a `#' character in the
place of a digit, otherwise it is exact.

   In systems with inexact numbers of varying precisions it may be
useful to specify the precision of a constant.  For this purpose,
numerical constants may be written with an "exponent marker" that
indicates the desired precision of the inexact representation.  The
letters `s', `f', `d', and `l' specify the use of _short_, _single_,
_double_, and _long_ precision, respectively.  (When fewer than four
internal inexact representations exist, the four size specifications
are mapped onto those available.  For example, an implementation with
two internal representations may map short and single together and long
and double together.)  In addition, the exponent marker `e' specifies
the default precision for the implementation.  The default precision
has at least as much precision as _double_, but implementations may
wish to allow this default to be set by the user.

     3.14159265358979F0
            Round to single -- 3.141593
     0.6L0
            Extend to long -- .600000000000000


File: mit-scheme-ref.info,  Node: Numerical operations,  Next: Numerical input and output,  Prev: Syntax of numerical constants,  Up: Numbers

4.5 Numerical operations
========================

*Note Entry Format::, for a summary of the naming conventions used to
specify restrictions on the types of arguments to numerical routines.
The examples used in this section assume that any numerical constant
written using an exact notation is indeed represented as an exact
number.  Some examples also assume that certain numerical constants
written using an inexact notation can be represented without loss of
accuracy; the inexact constants were chosen so that this is likely to be
true in implementations that use flonums to represent inexact numbers.

 -- procedure: number? object
 -- procedure: complex? object
 -- procedure: real? object
 -- procedure: rational? object
 -- procedure: integer? object
     These numerical type predicates can be applied to any kind of
     argument, including non-numbers.  They return `#t' if the object
     is of the named type, and otherwise they return `#f'.  In general,
     if a type predicate is true of a number then all higher type
     predicates are also true of that number.  Consequently, if a type
     predicate is false of a number, then all lower type predicates are
     also false of that number.(1)

     If Z is an inexact complex number, then `(real? Z)' is true if and
     only if `(zero? (imag-part Z))' is true.  If X is an inexact real
     number, then `(integer? X)' is true if and only if `(= X (round
     X))'.

          (complex? 3+4i)         =>  #t
          (complex? 3)            =>  #t
          (real? 3)               =>  #t
          (real? -2.5+0.0i)       =>  #t
          (real? #e1e10)          =>  #t
          (rational? 6/10)        =>  #t
          (rational? 6/3)         =>  #t
          (integer? 3+0i)         =>  #t
          (integer? 3.0)          =>  #t
          (integer? 8/4)          =>  #t

     Note: The behavior of these type predicates on inexact numbers is
     unreliable, since any inaccuracy may affect the result.


 -- procedure: exact? z
 -- procedure: inexact? z
     These numerical predicates provide tests for the exactness of a
     quantity.  For any Scheme number, precisely one of these
     predicates is true.

 -- procedure: exact-integer? object
 -- procedure: exact-nonnegative-integer? object
 -- procedure: exact-rational? object
     These procedures test for some very common types of numbers.  These
     tests could be written in terms of simpler predicates, but are more
     efficient.

 -- procedure: = z1 z2 z3 ...
 -- procedure: < x1 x2 x3 ...
 -- procedure: > x1 x2 x3 ...
 -- procedure: <= x1 x2 x3 ...
 -- procedure: >= x1 x2 x3 ...
     These procedures return `#t' if their arguments are (respectively):
     equal, monotonically increasing, monotonically decreasing,
     monotonically nondecreasing, or monotonically nonincreasing.

     These predicates are transitive.  Note that the traditional
     implementations of these predicates in Lisp-like languages are not
     transitive.

     Note: While it is not an error to compare inexact numbers using
     these predicates, the results may be unreliable because a small
     inaccuracy may affect the result; this is especially true of `='
     and `zero?'.  When in doubt, consult a numerical analyst.

 -- procedure: zero? z
 -- procedure: positive? x
 -- procedure: negative? x
 -- procedure: odd? x
 -- procedure: even? x
     These numerical predicates test a number for a particular property,
     returning `#t' or `#f'.  See note above regarding inexact numbers.

 -- procedure: max x1 x2 ...
 -- procedure: min x1 x2 ...
     These procedures return the maximum or minimum of their arguments.

          (max 3 4)              =>  4    ; exact
          (max 3.9 4)            =>  4.0  ; inexact

     Note: If any argument is inexact, then the result will also be
     inexact (unless the procedure can prove that the inaccuracy is not
     large enough to affect the result, which is possible only in
     unusual implementations).  If `min' or `max' is used to compare
     numbers of mixed exactness, and the numerical value of the result
     cannot be represented as an inexact number without loss of
     accuracy, then the procedure may report a violation of an
     implementation restriction.(2) 

 -- procedure: + z1 ...
 -- procedure: * z1 ...
     These procedures return the sum or product of their arguments.

          (+ 3 4)                 =>  7
          (+ 3)                   =>  3
          (+)                     =>  0
          (* 4)                   =>  4
          (*)                     =>  1

 -- procedure: - z1 z2 ...
 -- procedure: / z1 z2 ...
     With two or more arguments, these procedures return the difference
     or quotient of their arguments, associating to the left.  With one
     argument, however, they return the additive or multiplicative
     inverse of their argument.

          (- 3 4)                 =>  -1
          (- 3 4 5)               =>  -6
          (- 3)                   =>  -3
          (/ 3 4 5)               =>  3/20
          (/ 3)                   =>  1/3

 -- procedure: 1+ z
 -- procedure: -1+ z
     `(1+ z)' is equivalent to `(+ z 1)'; `(-1+ z)' is equivalent to
     `(- z 1)'.

 -- procedure: abs x
     `abs' returns the magnitude of its argument.

          (abs -7)                =>  7

 -- procedure: quotient n1 n2
 -- procedure: remainder n1 n2
 -- procedure: modulo n1 n2
     These procedures implement number-theoretic (integer) division: for
     positive integers N1 and N2, if N3 and N4 are integers such that

          N1 = (N2 * N3) + N4

          0 <= N4 < N2

     then

          (quotient N1 N2)        =>  N3
          (remainder N1 N2)       =>  N4
          (modulo N1 N2)          =>  N4

     For integers N1 and N2 with N2 not equal to 0,

          (= N1
             (+ (* N2 (quotient N1 N2))
                (remainder N1 N2)))
                                              =>  #t

     provided all numbers involved in that computation are exact.

     The value returned by `quotient' always has the sign of the product
     of its arguments.  `remainder' and `modulo' differ on negative
     arguments -- the `remainder' always has the sign of the dividend,
     the `modulo' always has the sign of the divisor:

          (modulo 13 4)           =>  1
          (remainder 13 4)        =>  1

          (modulo -13 4)          =>  3
          (remainder -13 4)       =>  -1

          (modulo 13 -4)          =>  -3
          (remainder 13 -4)       =>  1

          (modulo -13 -4)         =>  -1
          (remainder -13 -4)      =>  -1

          (remainder -13 -4.0)    =>  -1.0  ; inexact

     Note that `quotient' is the same as `integer-truncate'.

 -- procedure: integer-floor n1 n2
 -- procedure: integer-ceiling n1 n2
 -- procedure: integer-truncate n1 n2
 -- procedure: integer-round n1 n2
     These procedures combine integer division with rounding.  For
     example, the following are equivalent:

          (integer-floor N1 N2)
          (floor (/ N1 N2))

     However, the former is faster and does not produce an intermediate
     result.

     Note that `integer-truncate' is the same as `quotient'.

 -- procedure: integer-divide n1 n2
 -- procedure: integer-divide-quotient qr
 -- procedure: integer-divide-remainder qr
     `integer-divide' is equivalent to performing both `quotient' and
     `remainder' at once.  The result of `integer-divide' is an object
     with two components; the procedures `integer-divide-quotient' and
     `integer-divide-remainder' select those components.  These
     procedures are useful when both the quotient and remainder are
     needed; often computing both of these numbers simultaneously is
     much faster than computing them separately.

     For example, the following are equivalent:

          (lambda (n d)
            (cons (quotient n d)
                  (remainder n d)))

          (lambda (n d)
            (let ((qr (integer-divide n d)))
              (cons (integer-divide-quotient qr)
                    (integer-divide-remainder qr))))

 -- procedure: gcd n1 ...
 -- procedure: lcm n1 ...
     These procedures return the greatest common divisor or least common
     multiple of their arguments.  The result is always non-negative.

          (gcd 32 -36)            =>  4
          (gcd)                   =>  0

          (lcm 32 -36)            =>  288
          (lcm 32.0 -36)          =>  288.0  ; inexact
          (lcm)                   =>  1

 -- procedure: numerator q
 -- procedure: denominator q
     These procedures return the numerator or denominator of their
     argument; the result is computed as if the argument was
     represented as a fraction in lowest terms.  The denominator is
     always positive.  The denominator of 0 is defined to be 1.

          (numerator (/ 6 4))  =>  3
          (denominator (/ 6 4))  =>  2
          (denominator (exact->inexact (/ 6 4))) => 2.0

 -- procedure: floor x
 -- procedure: ceiling x
 -- procedure: truncate x
 -- procedure: round x
     These procedures return integers.  `floor' returns the largest
     integer not larger than X.  `ceiling' returns the smallest integer
     not smaller than X.  `truncate' returns the integer closest to X
     whose absolute value is not larger than the absolute value of X.
     `round' returns the closest integer to X, rounding to even when X
     is halfway between two integers.

     Rationale: `round' rounds to even for consistency with the rounding
     modes required by the IEEE floating point standard.

     Note: If the argument to one of these procedures is inexact, then
     the result will also be inexact.  If an exact value is needed, the
     result should be passed to the `inexact->exact' procedure (or use
     one of the procedures below).

          (floor -4.3)          =>  -5.0
          (ceiling -4.3)        =>  -4.0
          (truncate -4.3)       =>  -4.0
          (round -4.3)          =>  -4.0

          (floor 3.5)           =>  3.0
          (ceiling 3.5)         =>  4.0
          (truncate 3.5)        =>  3.0
          (round 3.5)           =>  4.0  ; inexact

          (round 7/2)           =>  4    ; exact
          (round 7)             =>  7

 -- procedure: floor->exact x
 -- procedure: ceiling->exact x
 -- procedure: truncate->exact x
 -- procedure: round->exact x
     These procedures are similar to the preceding procedures except
     that they always return an exact result.  For example, the
     following are equivalent

          (floor->exact x)
          (inexact->exact (floor x))

     except that the former is faster and has fewer range restrictions.

 -- procedure: rationalize x y
 -- procedure: rationalize->exact x y
     `rationalize' returns the _simplest_ rational number differing
     from X by no more than Y.  A rational number R1 is _simpler_ than
     another rational number R2 if R1=P1/Q1 and R2=P2/Q2 (both in
     lowest terms) and |P1|<=|P2| and |Q1|<=|Q2|.  Thus 3/5 is simpler
     than 4/7.  Although not all rationals are comparable in this
     ordering (consider 2/7 and 3/5) any interval contains a rational
     number that is simpler than every other rational number in that
     interval (the simpler 2/5 lies between 2/7 and 3/5).  Note that
     0=0/1 is the simplest rational of all.

          (rationalize (inexact->exact .3) 1/10)  => 1/3    ; exact
          (rationalize .3 1/10)                   => #i1/3  ; inexact

     `rationalize->exact' is similar to `rationalize' except that it
     always returns an exact result.

 -- procedure: simplest-rational x y
 -- procedure: simplest-exact-rational x y
     `simplest-rational' returns the simplest rational number between X
     and Y inclusive; `simplest-exact-rational' is similar except that
     it always returns an exact result.

     These procedures implement the same functionality as `rationalize'
     and `rationalize->exact', except that they specify the input range
     by its endpoints; `rationalize' specifies the range by its center
     point and its (half-) width.

 -- procedure: exp z
 -- procedure: log z
 -- procedure: sin z
 -- procedure: cos z
 -- procedure: tan z
 -- procedure: asin z
 -- procedure: acos z
 -- procedure: atan z
 -- procedure: atan y x
     These procedures compute the usual transcendental functions.  `log'
     computes the natural logarithm of Z (not the base ten logarithm).
     `asin', `acos', and `atan' compute arcsine, arccosine, and
     arctangent, respectively.  The two-argument variant of `atan'
     computes `(angle (make-rectangular X Y))' (see below).

     In general, the mathematical functions log, arcsine, arccosine, and
     arctangent are multiply defined.  For nonzero real X, the value of
     log X is defined to be the one whose imaginary part lies in the
     range minus PI (exclusive) to PI (inclusive).  log 0 is undefined.
     The value of log Z when Z is complex is defined according to the
     formula

          log Z = log magnitude(Z) + i angle(Z)

     With log defined this way, the values of arcsine, arccosine, and
     arctangent are according to the following formulae:

          arcsin(Z) = -i log(i Z + sqrt(1 - Z^2))
          arccos(Z) = pi/2 - arcsin(Z)
          arctan(Z) = (log(1 + i Z) + log(1 - i Z)) / (2 i)

     The above specification follows `Common Lisp: the Language', which
     in turn cites `Principal Values and Branch Cuts in Complex APL';
     refer to these sources for more detailed discussion of branch cuts,
     boundary conditions, and implementation of these functions.  When
     it is possible these procedures produce a real result from a real
     argument.

 -- procedure: sqrt z
     Returns the principal square root of Z.  The result will have
     either positive real part, or zero real part and non-negative
     imaginary part.

 -- procedure: expt z1 z2
     Returns Z1 raised to the power Z2:

          Z1^Z2 = e^(Z2 log Z1)

     0^0 is defined to be equal to 1.

 -- procedure: make-rectangular x1 x2
 -- procedure: make-polar x3 x4
 -- procedure: real-part z
 -- procedure: imag-part z
 -- procedure: magnitude z
 -- procedure: angle z
 -- procedure: conjugate z
     Suppose X1, X2, X3, and X4 are real numbers and Z is a complex
     number such that

          Z = X1 + X2 i = X3 e^(i X4)

     Then `make-rectangular' and `make-polar' return Z, `real-part'
     returns X1, `imag-part' returns X2, `magnitude' returns X3, and
     `angle' returns X4.  In the case of `angle', whose value is not
     uniquely determined by the preceding rule, the value returned will
     be the one in the range minus PI (exclusive) to PI (inclusive).

     `conjugate' returns the complex conjugate of Z.

 -- procedure: exact->inexact z
 -- procedure: inexact->exact z
     `exact->inexact' returns an inexact representation of Z.  The
     value returned is the inexact number that is numerically closest
     to the argument.  If an exact argument has no reasonably close
     inexact equivalent, then a violation of an implementation
     restriction may be reported; MIT/GNU Scheme signals an error of
     type `condition-type:bad-range-argument' in this case.  

     `inexact->exact' returns an exact representation of Z.  The value
     returned is the exact number that is numerically closest to the
     argument.  If an inexact argument has no reasonably close exact
     equivalent, then a violation of an implementation restriction may
     be reported; in MIT/GNU Scheme this case does not occur because
     all inexact numbers are representable as exact numbers.

     These procedures implement the natural one-to-one correspondence
     between exact and inexact integers throughout an
     implementation-dependent range.  *Note Implementation
     restrictions::.

   ---------- Footnotes ----------

   (1) In MIT/GNU Scheme the `rational?' procedure is the same as
`real?', and the `complex?' procedure is the same as `number?'.

   (2) MIT/GNU Scheme signals an error of type
`condition-type:bad-range-argument' in this case.


File: mit-scheme-ref.info,  Node: Numerical input and output,  Next: Fixnum and Flonum Operations,  Prev: Numerical operations,  Up: Numbers

4.6 Numerical input and output
==============================

 -- procedure: number->string number [radix]
     RADIX must be an exact integer, either 2, 8, 10, or 16.  If
     omitted, RADIX defaults to 10.  The procedure `number->string'
     takes a number and a radix and returns as a string an external
     representation of the given number in the given radix such that

          (let ((number NUMBER)
                (radix RADIX))
            (eqv? number
                  (string->number (number->string number radix)
                                  radix)))

     is true.  It is an error if no possible result makes this
     expression true.

     If NUMBER is inexact, the radix is 10, and the above expression
     can be satisfied by a result that contains a decimal point, then
     the result contains a decimal point and is expressed using the
     minimum number of digits (exclusive of exponent and trailing
     zeroes) needed to make the above expression true; otherwise the
     format of the result is unspecified.

     The result returned by `number->string' never contains an explicit
     radix prefix.

     Note: The error case can occur only when NUMBER is not a complex
     number or is a complex number with an non-rational real or
     imaginary part.

     Rationale: If NUMBER is an inexact number represented using
     flonums, and the radix is 10, then the above expression is normally
     satisfied by a result containing a decimal point.  The unspecified
     case allows for infinities, NaNs, and non-flonum representations.

 -- variable: flonum-parser-fast?
     This variable controls the behavior of `string->number' when
     parsing inexact numbers.  Specifically, it allows the user to
     trade off accuracy against speed.

     When set to its default value, `#f', the parser provides maximal
     accuracy, as required by the Scheme standard.  If set to `#t', the
     parser uses faster algorithms that will sometimes introduce small
     errors in the result.  The errors affect a few of the
     least-significant bits of the result, and consequently can be
     tolerated by many applications.

 -- variable: flonum-unparser-cutoff
     This variable controls the action of `number->string' when NUMBER
     is a flonum (and consequently controls all printing of flonums).
     The value of this variable is normally a list of three items:

    ROUNDING-TYPE
          One of the following symbols: `normal', `relative', or
          `absolute'.  The symbol `normal' means that the number should
          be printed with full precision.  The symbol `relative' means
          that the number should be rounded to a specific number of
          digits.  The symbol `absolute' means that the number should
          be rounded so that there are a specific number of digits to
          the right of the decimal point.

    PRECISION
          An exact integer.  If ROUNDING-TYPE is `normal', PRECISION is
          ignored.  If ROUNDING-TYPE is `relative', PRECISION must be
          positive, and it specifies the number of digits to which the
          printed representation will be rounded.  If ROUNDING-TYPE is
          `absolute', the printed representation will be rounded
          PRECISION digits to the right of the decimal point; if
          PRECISION is negative, the representation is rounded `(-
          PRECISION)' digits to the left of the decimal point.

    FORMAT-TYPE
          One of the symbols: `normal', `scientific', or `engineering'.
          This specifies the format in which the number will be
          printed.
          `scientific' specifies that the number will be printed using
          scientific notation: `X.XXXeYYY'.  In other words, the number
          is printed as a mantissa between zero inclusive and ten
          exclusive, and an exponent.  `engineering' is like
          `scientific', except that the exponent is always a power of
          three, and the mantissa is constrained to be between zero
          inclusive and 1000 exclusive.  If `normal' is specified, the
          number will be printed in positional notation if it is "small
          enough", otherwise it is printed in scientific notation.  A
          number is "small enough" when the number of digits that would
          be printed using positional notation does not exceed the
          number of digits of precision in the underlying floating-point
          number representation; IEEE double-precision floating-point
          numbers have 17 digits of precision.

     This three-element list may be abbreviated in two ways.  First, the
     symbol `normal' may be used, which is equivalent to the list
     `(normal 0 normal)'.  Second, the third element of the list,
     FORMAT-TYPE, may be omitted, in which case it defaults to `normal'.

     The default value for `flonum-unparser-cutoff' is `normal'.  If it
     is bound to a value different from those described here,
     `number->string' issues a warning and acts as though the value had
     been `normal'.

Some examples of `flonum-unparser-cutoff':

     (number->string (* 4 (atan 1 1)))
                                         => "3.141592653589793"
     (fluid-let ((flonum-unparser-cutoff '(relative 5)))
       (number->string (* 4 (atan 1 1))))
                                         => "3.1416"
     (fluid-let ((flonum-unparser-cutoff '(relative 5)))
       (number->string (* 4000 (atan 1 1))))
                                         => "3141.6"
     (fluid-let ((flonum-unparser-cutoff '(relative 5 scientific)))
       (number->string (* 4000 (atan 1 1))))
                                         => "3.1416e3"
     (fluid-let ((flonum-unparser-cutoff '(relative 5 scientific)))
       (number->string (* 40000 (atan 1 1))))
                                         => "3.1416e4"
     (fluid-let ((flonum-unparser-cutoff '(relative 5 engineering)))
       (number->string (* 40000 (atan 1 1))))
                                         => "31.416e3"
     (fluid-let ((flonum-unparser-cutoff '(absolute 5)))
       (number->string (* 4 (atan 1 1))))
                                         => "3.14159"
     (fluid-let ((flonum-unparser-cutoff '(absolute 5)))
       (number->string (* 4000 (atan 1 1))))
                                         => "3141.59265"
     (fluid-let ((flonum-unparser-cutoff '(absolute -4)))
       (number->string (* 4e10 (atan 1 1))))
                                         => "31415930000."
     (fluid-let ((flonum-unparser-cutoff '(absolute -4 scientific)))
       (number->string (* 4e10 (atan 1 1))))
                                         => "3.141593e10"
     (fluid-let ((flonum-unparser-cutoff '(absolute -4 engineering)))
       (number->string (* 4e10 (atan 1 1))))
                                         => "31.41593e9"
     (fluid-let ((flonum-unparser-cutoff '(absolute -5)))
       (number->string (* 4e10 (atan 1 1))))
                                         => "31415900000."

 -- procedure: string->number string [radix]
     Returns a number of the maximally precise representation expressed
     by the given STRING.  RADIX must be an exact integer, either 2, 8,
     10, or 16.  If supplied, RADIX is a default radix that may be
     overridden by an explicit radix prefix in STRING (e.g.
     `"#o177"').  If RADIX is not supplied, then the default radix is
     10.  If STRING is not a syntactically valid notation for a number,
     then `string->number' returns `#f'.

          (string->number "100")        =>  100
          (string->number "100" 16)     =>  256
          (string->number "1e2")        =>  100.0
          (string->number "15##")       =>  1500.0

     Note that a numeric representation using a decimal point or an
     exponent marker is not recognized unless RADIX is `10'.


File: mit-scheme-ref.info,  Node: Fixnum and Flonum Operations,  Next: Random Numbers,  Prev: Numerical input and output,  Up: Numbers

4.7 Fixnum and Flonum Operations
================================

This section describes numerical operations that are restricted forms of
the operations described above.  These operations are useful because
they compile very efficiently.  However, care should be exercised: if
used improperly, these operations can return incorrect answers, or even
malformed objects that confuse the garbage collector.

* Menu:

* Fixnum Operations::
* Flonum Operations::


File: mit-scheme-ref.info,  Node: Fixnum Operations,  Next: Flonum Operations,  Prev: Fixnum and Flonum Operations,  Up: Fixnum and Flonum Operations

4.7.1 Fixnum Operations
-----------------------

A "fixnum" is an exact integer that is small enough to fit in a machine
word.  In MIT/GNU Scheme, fixnums are typically 24 or 26 bits,
depending on the machine; it is reasonable to assume that fixnums are at
least 24 bits.  Fixnums are signed; they are encoded using 2's
complement.

   All exact integers that are small enough to be encoded as fixnums are
always encoded as fixnums -- in other words, any exact integer that is
not a fixnum is too big to be encoded as such.  For this reason, small
constants such as `0' or `1' are guaranteed to be fixnums.

 -- procedure: fix:fixnum? object
     Returns `#t' if OBJECT is a fixnum; otherwise returns `#f'.

   Here is an expression that determines the largest fixnum:

     (let loop ((n 1))
       (if (fix:fixnum? n)
           (loop (* n 2))
           (- n 1)))

A similar expression determines the smallest fixnum.

 -- procedure: fix:= fixnum fixnum
 -- procedure: fix:< fixnum fixnum
 -- procedure: fix:> fixnum fixnum
 -- procedure: fix:<= fixnum fixnum
 -- procedure: fix:>= fixnum fixnum
     These are the standard order and equality predicates on fixnums.
     When compiled, they do not check the types of their arguments.

 -- procedure: fix:zero? fixnum
 -- procedure: fix:positive? fixnum
 -- procedure: fix:negative? fixnum
     These procedures compare their argument to zero.  When compiled,
     they do not check the type of their argument.  The code produced
     by the following expressions is identical:

          (fix:zero? FIXNUM)
          (fix:= FIXNUM 0)

     Similarly, `fix:positive?' and `fix:negative?' produce code
     identical to equivalent expressions using `fix:>' and `fix:<'.

 -- procedure: fix:+ fixnum fixnum
 -- procedure: fix:- fixnum fixnum
 -- procedure: fix:* fixnum fixnum
 -- procedure: fix:quotient fixnum fixnum
 -- procedure: fix:remainder fixnum fixnum
 -- procedure: fix:gcd fixnum fixnum
 -- procedure: fix:1+ fixnum
 -- procedure: fix:-1+ fixnum
     These procedures are the standard arithmetic operations on fixnums.
     When compiled, they do not check the types of their arguments.
     Furthermore, they do not check to see if the result can be encoded
     as a fixnum.  If the result is too large to be encoded as a
     fixnum, a malformed object is returned, with potentially
     disastrous effect on the garbage collector.

 -- procedure: fix:divide fixnum fixnum
     This procedure is like `integer-divide', except that its arguments
     and its results must be fixnums.  It should be used in conjunction
     with `integer-divide-quotient' and `integer-divide-remainder'.

   The following are "bitwise-logical" operations on fixnums.

 -- procedure: fix:not fixnum
     This returns the bitwise-logical inverse of its argument.  When
     compiled, it does not check the type of its argument.

          (fix:not 0)                             =>  -1
          (fix:not -1)                            =>  0
          (fix:not 1)                             =>  -2
          (fix:not -34)                           =>  33

 -- procedure: fix:and fixnum fixnum
     This returns the bitwise-logical "and" of its arguments.  When
     compiled, it does not check the types of its arguments.

          (fix:and #x43 #x0f)                     =>  3
          (fix:and #x43 #xf0)                     =>  #x40

 -- procedure: fix:andc fixnum fixnum
     Returns the bitwise-logical "and" of the first argument with the
     bitwise-logical inverse of the second argument.  When compiled, it
     does not check the types of its arguments.

          (fix:andc #x43 #x0f)                    =>  #x40
          (fix:andc #x43 #xf0)                    =>  3

 -- procedure: fix:or fixnum fixnum
     This returns the bitwise-logical "inclusive or" of its arguments.
     When compiled, it does not check the types of its arguments.

          (fix:or #x40 3)                         => #x43
          (fix:or #x41 3)                         => #x43

 -- procedure: fix:xor fixnum fixnum
     This returns the bitwise-logical "exclusive or" of its arguments.
     When compiled, it does not check the types of its arguments.

          (fix:xor #x40 3)                        => #x43
          (fix:xor #x41 3)                        => #x42

 -- procedure: fix:lsh fixnum1 fixnum2
     This procedure returns the result of logically shifting FIXNUM1 by
     FIXNUM2 bits.  If FIXNUM2 is positive, FIXNUM1 is shifted left; if
     negative, it is shifted right.  When compiled, it does not check
     the types of its arguments, nor the validity of its result.

          (fix:lsh 1 10)                          =>  #x400
          (fix:lsh #x432 -10)                     =>  1
          (fix:lsh -1 3)                          =>  -8
          (fix:lsh -128 -4)                       =>  #x3FFFF8


File: mit-scheme-ref.info,  Node: Flonum Operations,  Prev: Fixnum Operations,  Up: Fixnum and Flonum Operations

4.7.2 Flonum Operations
-----------------------

A "flonum" is an inexact real number that is implemented as a
floating-point number.  In MIT/GNU Scheme, all inexact real numbers are
flonums.  For this reason, constants such as `0.' and `2.3' are
guaranteed to be flonums.

 -- procedure: flo:flonum? object
     Returns `#t' if OBJECT is a flonum; otherwise returns `#f'.

 -- procedure: flo:= flonum1 flonum2
 -- procedure: flo:< flonum1 flonum2
 -- procedure: flo:> flonum1 flonum2
     These procedures are the standard order and equality predicates on
     flonums.  When compiled, they do not check the types of their
     arguments.

 -- procedure: flo:zero? flonum
 -- procedure: flo:positive? flonum
 -- procedure: flo:negative? flonum
     Each of these procedures compares its argument to zero.  When
     compiled, they do not check the type of their argument.

 -- procedure: flo:+ flonum1 flonum2
 -- procedure: flo:- flonum1 flonum2
 -- procedure: flo:* flonum1 flonum2
 -- procedure: flo:/ flonum1 flonum2
     These procedures are the standard arithmetic operations on flonums.
     When compiled, they do not check the types of their arguments.

 -- procedure: flo:finite? flonum
     The IEEE floating-point number specification supports three
     special "numbers": positive infinity (`+inf'), negative infinity
     (`-inf'), and not-a-number (`NaN').  This predicate returns `#f'
     if FLONUM is one of these objects, and `#t' if it is any other
     floating-point number.

 -- procedure: flo:negate flonum
     This procedure returns the negation of its argument.  When
     compiled, it does not check the type of its argument.  Equivalent
     to `(flo:- 0.  FLONUM)'.

 -- procedure: flo:abs flonum
 -- procedure: flo:exp flonum
 -- procedure: flo:log flonum
 -- procedure: flo:sin flonum
 -- procedure: flo:cos flonum
 -- procedure: flo:tan flonum
 -- procedure: flo:asin flonum
 -- procedure: flo:acos flonum
 -- procedure: flo:atan flonum
 -- procedure: flo:sqrt flonum
 -- procedure: flo:expt flonum1 flonum2
 -- procedure: flo:floor flonum
 -- procedure: flo:ceiling flonum
 -- procedure: flo:truncate flonum
 -- procedure: flo:round flonum
 -- procedure: flo:floor->exact flonum
 -- procedure: flo:ceiling->exact flonum
 -- procedure: flo:truncate->exact flonum
 -- procedure: flo:round->exact flonum
     These procedures are flonum versions of the corresponding
     procedures.  When compiled, they do not check the types of their
     arguments.

 -- procedure: flo:atan2 flonum1 flonum2
     This is the flonum version of `atan' with two arguments.  When
     compiled, it does not check the types of its arguments.


File: mit-scheme-ref.info,  Node: Random Numbers,  Prev: Fixnum and Flonum Operations,  Up: Numbers

4.8 Random Numbers
==================

MIT/GNU Scheme provides a facility for generating pseudo-random numbers.
The current implementation is a "subtract-with-carry" random-number
generator, based on the algorithm from `A New Class of Random Number
Generators', George Marsaglia and Arif Zaman, `The Annals of Applied
Probability', Vol. 1, No. 3, 1991.  At the time it was implemented,
this was a good algorithm for general purposes, but the state of the
art in random-number generation is constantly changing.  If necessary,
the implementation will be updated to use a new algorithm while
retaining the same interface.

   The interface described here is very similar to that of Common Lisp.

 -- procedure: random modulus [state]
     MODULUS must be a positive real number.  `random' returns a
     pseudo-random number between zero (inclusive) and MODULUS
     (exclusive).  The exactness of the returned number is the same as
     the exactness of MODULUS.  Additionally, if MODULUS is an exact
     integer, the returned number will be also.  Usually, MODULUS is
     either an exact integer or an inexact real; the current
     implementation has been tuned to make these two cases fast.

     If STATE is given and not `#f', it must be a random-state object;
     otherwise, it defaults to the value of the variable
     `*random-state*'.  This object is used to maintain the state of the
     pseudo-random-number generator and is altered as a side effect of
     the `random' procedure.

          (random 1.0)    => .32744744667719056
          (random 1.0)    => .01668326768172354
          (random 10)     => 3
          (random 10)     => 8
          (random 100)    => 38
          (random 100)    => 63
          (random 100/3)  => 130501475769920525/6755399441055744
          (random 100/3)  => 170571694016427575/13510798882111488

 -- procedure: flo:random-unit state
     STATE must be a random-state object.  `flo:random-unit' returns a
     pseudo-random number between zero inclusive and one exclusive; the
     returned number is always a flonum and therefore an inexact real
     number.  `flo:random-unit' is equivalent to `random' with a
     MODULUS of `1.0', except that it is faster.

   The next three definitions concern random-state objects.  In
addition to these definitions, it is important to know that
random-state objects are specifically designed so that they can be
saved to disk using the `fasdump' procedure, and later restored using
the `fasload' procedure.  This allows a particular random-state object
to be saved in order to replay a particular pseudo-random sequence.

 -- variable: *random-state*
     This variable holds a data structure, a random-state object, that
     encodes the internal state of the random-number generator that
     `random' uses by default.  A call to `random' will perform a side
     effect on this data structure.  This variable may be changed, using
     `set!' or `fluid-let', to hold a new random-state object.

 -- procedure: make-random-state [state]
     This procedure returns a new random-state object, suitable for use
     as the value of the variable `*random-state*', or as the STATE
     argument to `random'.  If STATE is not given or `#f',
     `make-random-state' returns a _copy_ of the current random-number
     state object (the value of the variable `*random-state*').  If
     STATE is a random-state object, a copy of that object is returned.
     If STATE is `#t', then a new random-state object is returned that
     has been "randomly" initialized by some means (such as by a
     time-of-day clock).

 -- procedure: random-state? object
     Returns `#t' if OBJECT is a random-state object, otherwise returns
     `#f'.


File: mit-scheme-ref.info,  Node: Characters,  Next: Strings,  Prev: Numbers,  Up: Top

5 Characters
************

Characters are objects that represent printed characters, such as
letters and digits.

* Menu:

* External Representation of Characters::
* Comparison of Characters::
* Miscellaneous Character Operations::
* Internal Representation of Characters::
* ISO-8859-1 Characters::
* Character Sets::
* Unicode::


File: mit-scheme-ref.info,  Node: External Representation of Characters,  Next: Comparison of Characters,  Prev: Characters,  Up: Characters

5.1 External Representation of Characters
=========================================

Characters are written using the notation `#\CHARACTER' or
`#\CHARACTER-NAME'.  For example:

     #\a                     ; lowercase letter
     #\A                     ; uppercase letter
     #\(                     ; left parenthesis
     #\space                 ; the space character
     #\newline               ; the newline character

Case is significant in `#\CHARACTER', but not in `#\CHARACTER-NAME'.
If CHARACTER in `#\CHARACTER' is a letter, CHARACTER must be followed
by a delimiter character such as a space or parenthesis.  Characters
written in the `#\' notation are self-evaluating; you don't need to
quote them.

   In addition to the standard character syntax, MIT Scheme also
supports a general syntax that denotes any Unicode character by its
scalar value.  This notation is `#\U+SCALAR-VALUE', where SCALAR-VALUE
is a sequence of hexadecimal digits for a valid scalar value.  So the
above examples could also be written like this:

     #\U+61                  ; lowercase letter
     #\U+41                  ; uppercase letter
     #\U+28                  ; left parenthesis
     #\U+20                  ; the space character
     #\U+0A                  ; the newline character

   A character name may include one or more "bucky bit" prefixes to
indicate that the character includes one or more of the keyboard shift
keys Control, Meta, Super, or Hyper (note that the Control bucky bit
prefix is not the same as the ASCII control key).  The bucky bit
prefixes and their meanings are as follows (case is not significant):

     Key             Bucky bit prefix        Bucky bit
     ---             ----------------        ---------

     Meta            M- or Meta-                 1
     Control         C- or Control-              2
     Super           S- or Super-                4
     Hyper           H- or Hyper-                8

For example,

     #\c-a                   ; Control-a
     #\meta-b                ; Meta-b
     #\c-s-m-h-a             ; Control-Meta-Super-Hyper-A

   The following CHARACTER-NAMEs are supported, shown here with their
ASCII equivalents:

     Character Name          ASCII Name
     --------------          ----------

     altmode                 ESC
     backnext                US
     backspace               BS
     call                    SUB
     linefeed                LF
     page                    FF
     return                  CR
     rubout                  DEL
     space
     tab                     HT

In addition, `#\newline' is the same as `#\linefeed' (but this may
change in the future, so you should not depend on it).  All of the
standard ASCII names for non-printing characters are supported:

     NUL     SOH     STX     ETX     EOT     ENQ     ACK     BEL
     BS      HT      LF      VT      FF      CR      SO      SI
     DLE     DC1     DC2     DC3     DC4     NAK     SYN     ETB
     CAN     EM      SUB     ESC     FS      GS      RS      US
     DEL

 -- procedure: char->name char [slashify?]
     Returns a string corresponding to the printed representation of
     CHAR.  This is the CHARACTER or CHARACTER-NAME component of the
     external representation, combined with the appropriate bucky bit
     prefixes.

          (char->name #\a)                        =>  "a"
          (char->name #\space)                    =>  "Space"
          (char->name #\c-a)                      =>  "C-a"
          (char->name #\control-a)                =>  "C-a"

     SLASHIFY?, if specified and true, says to insert the necessary
     backslash characters in the result so that `read' will parse it
     correctly.  In other words, the following generates the external
     representation of CHAR:

          (string-append "#\\" (char->name CHAR #t))

     If SLASHIFY? is not specified, it defaults to `#f'.

 -- procedure: name->char string
     Converts a string that names a character into the character
     specified.  If STRING does not name any character, `name->char'
     signals an error.

          (name->char "a")                        =>  #\a
          (name->char "space")                    =>  #\Space
          (name->char "c-a")                      =>  #\C-a
          (name->char "control-a")                =>  #\C-a


File: mit-scheme-ref.info,  Node: Comparison of Characters,  Next: Miscellaneous Character Operations,  Prev: External Representation of Characters,  Up: Characters

5.2 Comparison of Characters
============================

 -- procedure: char=? char1 char2
 -- procedure: char<? char1 char2
 -- procedure: char>? char1 char2
 -- procedure: char<=? char1 char2
 -- procedure: char>=? char1 char2
 -- procedure: char-ci=? char1 char2
 -- procedure: char-ci<? char1 char2
 -- procedure: char-ci>? char1 char2
 -- procedure: char-ci<=? char1 char2
 -- procedure: char-ci>=? char1 char2
     Returns `#t' if the specified characters are have the appropriate
     order relationship to one another; otherwise returns `#f'.  The
     `-ci' procedures don't distinguish uppercase and lowercase letters.

     Character ordering follows these portability rules:

        * The digits are in order; for example, `(char<? #\0 #\9)'
          returns `#t'.

        * The uppercase characters are in order; for example, `(char<?
          #\A #\B)' returns `#t'.

        * The lowercase characters are in order; for example, `(char<?
          #\a #\b)' returns `#t'.

     MIT/GNU Scheme uses a specific character ordering, in which
     characters have the same order as their corresponding integers.
     See the documentation for `char->integer' for further details.

     *Note*: Although character objects can represent all of Unicode,
     the model of alphabetic case used covers only ASCII letters, which
     means that case-insensitive comparisons and case conversions are
     incorrect for non-ASCII letters.  This will eventually be fixed.


File: mit-scheme-ref.info,  Node: Miscellaneous Character Operations,  Next: Internal Representation of Characters,  Prev: Comparison of Characters,  Up: Characters

5.3 Miscellaneous Character Operations
======================================

 -- procedure: char? object
     Returns `#t' if OBJECT is a character; otherwise returns `#f'.

 -- procedure: char-upcase char
 -- procedure: char-downcase char
     Returns the uppercase or lowercase equivalent of CHAR if CHAR is a
     letter; otherwise returns CHAR.  These procedures return a
     character CHAR2 such that `(char-ci=? CHAR CHAR2)'.

     *Note*: Although character objects can represent all of Unicode,
     the model of alphabetic case used covers only ASCII letters, which
     means that case-insensitive comparisons and case conversions are
     incorrect for non-ASCII letters.  This will eventually be fixed.

 -- procedure: char->digit char [radix]
     If CHAR is a character representing a digit in the given RADIX,
     returns the corresponding integer value.  If you specify RADIX
     (which must be an exact integer between 2 and 36 inclusive), the
     conversion is done in that base, otherwise it is done in base 10.
     If CHAR doesn't represent a digit in base RADIX, `char->digit'
     returns `#f'.

     Note that this procedure is insensitive to the alphabetic case of
     CHAR.

          (char->digit #\8)                       =>  8
          (char->digit #\e 16)                    =>  14
          (char->digit #\e)                       =>  #f

 -- procedure: digit->char digit [radix]
     Returns a character that represents DIGIT in the radix given by
     RADIX.  RADIX must be an exact integer between 2 and 36
     (inclusive), and defaults to 10.  DIGIT, which must be an exact
     non-negative integer, should be less than RADIX; if DIGIT is
     greater than or equal to RADIX, `digit->char' returns `#f'.

          (digit->char 8)                         =>  #\8
          (digit->char 14 16)                     =>  #\E


File: mit-scheme-ref.info,  Node: Internal Representation of Characters,  Next: ISO-8859-1 Characters,  Prev: Miscellaneous Character Operations,  Up: Characters

5.4 Internal Representation of Characters
=========================================

An MIT/GNU Scheme character consists of a "code" part and a "bucky
bits" part.  The MIT/GNU Scheme set of characters can represent more
characters than ASCII can; it includes characters with Super and Hyper
bucky bits, as well as Control and Meta.  Every ASCII character
corresponds to some MIT/GNU Scheme character, but not vice versa.(1)

   MIT/GNU Scheme uses a 21-bit character code with 4 bucky bits.  The
character code contains the Unicode scalar value for the character.
This is a change from earlier versions of the system, which used the
ISO-8859-1 scalar value, but it is upwards compatible with previous
usage, since ISO-8859-1 is a proper subset of Unicode.

 -- procedure: make-char code bucky-bits
     Builds a character from CODE and BUCKY-BITS.  Both CODE and
     BUCKY-BITS must be exact non-negative integers in the appropriate
     range.  Use `char-code' and `char-bits' to extract the code and
     bucky bits from the character.  If `0' is specified for
     BUCKY-BITS, `make-char' produces an ordinary character; otherwise,
     the appropriate bits are turned on as follows:

          1               Meta
          2               Control
          4               Super
          8               Hyper

     For example,

          (make-char 97 0)                        =>  #\a
          (make-char 97 1)                        =>  #\M-a
          (make-char 97 2)                        =>  #\C-a
          (make-char 97 3)                        =>  #\C-M-a

 -- procedure: char-bits char
     Returns the exact integer representation of CHAR's bucky bits.
     For example,

          (char-bits #\a)                         =>  0
          (char-bits #\m-a)                       =>  1
          (char-bits #\c-a)                       =>  2
          (char-bits #\c-m-a)                     =>  3

 -- procedure: char-code char
     Returns the character code of CHAR, an exact integer.  For example,

          (char-code #\a)                         =>  97
          (char-code #\c-a)                       =>  97

     Note that in MIT/GNU Scheme, the value of `char-code' is the
     Unicode scalar value for CHAR.

 -- variable: char-code-limit
 -- variable: char-bits-limit
     These variables define the (exclusive) upper limits for the
     character code and bucky bits (respectively).  The character code
     and bucky bits are always exact non-negative integers, and are
     strictly less than the value of their respective limit variable.

 -- procedure: char->integer char
 -- procedure: integer->char k
     `char->integer' returns the character code representation for
     CHAR.  `integer->char' returns the character whose character code
     representation is K.

     In MIT/GNU Scheme, if `(char-ascii? CHAR)' is true, then

          (eqv? (char->ascii CHAR) (char->integer CHAR))

     However, this behavior is not required by the Scheme standard, and
     code that depends on it is not portable to other implementations.

     These procedures implement order isomorphisms between the set of
     characters under the `char<=?' ordering and some subset of the
     integers under the `<=' ordering.  That is, if

          (char<=? a b)  =>  #t    and    (<= x y)  =>  #t

     and `x' and `y' are in the range of `char->integer', then

          (<= (char->integer a)
              (char->integer b))                  =>  #t
          (char<=? (integer->char x)
                   (integer->char y))             =>  #t

     In MIT/GNU Scheme, the specific relationship implemented by these
     procedures is as follows:

          (define (char->integer c)
            (+ (* (char-bits c) #x200000)
               (char-code c)))

          (define (integer->char n)
            (make-char (remainder n #x200000)
                       (quotient n #x200000)))

     This implies that `char->integer' and `char-code' produce
     identical results for characters that have no bucky bits set, and
     that characters are ordered according to their Unicode scalar
     values.

     Note: If the argument to `char->integer' or `integer->char' is a
     constant, the compiler will constant-fold the call, replacing it
     with the corresponding result.  This is a very useful way to
     denote unusual character constants or ASCII codes.

 -- variable: char-integer-limit
     The range of `char->integer' is defined to be the exact
     non-negative integers that are less than the value of this variable
     (exclusive).  Note, however, that there are some holes in this
     range, because the character code must be a valid Unicode scalar
     value.

   ---------- Footnotes ----------

   (1) Note that the Control bucky bit is different from the ASCII
control key.  This means that `#\SOH' (ASCII ctrl-A) is different from
`#\C-A'.  In fact, the Control bucky bit is completely orthogonal to the
ASCII control key, making possible such characters as `#\C-SOH'.


File: mit-scheme-ref.info,  Node: ISO-8859-1 Characters,  Next: Character Sets,  Prev: Internal Representation of Characters,  Up: Characters

5.5 ISO-8859-1 Characters
=========================

MIT/GNU Scheme internally uses ISO-8859-1 codes for I/O, and stores
character objects in a fashion that makes it convenient to convert
between ISO-8859-1 codes and characters.  Also, character strings are
implemented as byte vectors whose elements are ISO-8859-1 codes; these
codes are converted to character objects when accessed.  For these
reasons it is sometimes desirable to be able to convert between
ISO-8859-1 codes and characters.

   Not all characters can be represented as ISO-8859-1 codes.  A
character that has an equivalent ISO-8859-1 representation is called an
"ISO-8859-1 character".

   For historical reasons, the procedures that manipulate ISO-8859-1
characters use the word "ASCII" rather than "ISO-8859-1".

 -- procedure: char-ascii? char
     Returns the ISO-8859-1 code for CHAR if CHAR has an ISO-8859-1
     representation; otherwise returns `#f'.

     In the current implementation, the characters that satisfy this
     predicate are those in which the bucky bits are turned off, and for
     which the character code is less than 256.

 -- procedure: char->ascii char
     Returns the ISO-8859-1 code for CHAR.  An error
     `condition-type:bad-range-argument' is signalled if CHAR doesn't
     have an ISO-8859-1 representation.  

 -- procedure: ascii->char code
     CODE must be the exact integer representation of an ISO-8859-1
     code.  This procedure returns the character corresponding to CODE.


File: mit-scheme-ref.info,  Node: Character Sets,  Next: Unicode,  Prev: ISO-8859-1 Characters,  Up: Characters

5.6 Character Sets
==================

MIT/GNU Scheme's character-set abstraction is used to represent groups
of characters, such as the letters or digits.  A character set may
contain any Unicode character.

 -- procedure: char-set? object
     Returns `#t' if OBJECT is a character set; otherwise returns `#f'.

 -- variable: char-set:upper-case
 -- variable: char-set:lower-case
 -- variable: char-set:alphabetic
 -- variable: char-set:numeric
 -- variable: char-set:alphanumeric
 -- variable: char-set:whitespace
 -- variable: char-set:not-whitespace
 -- variable: char-set:graphic
 -- variable: char-set:not-graphic
 -- variable: char-set:standard
     These variables contain predefined character sets.  At present,
     these character sets contain only ISO-8859-1 characters; in the
     future they will contain all the relevant Unicode characters.  To
     see the contents of one of these sets, use
     `char-set->scalar-values'.

     "Alphabetic" characters are the 52 upper and lower case letters.
     "Numeric" characters are the 10 decimal digits.  "Alphanumeric"
     characters are those in the union of these two sets.  "Whitespace"
     characters are `#\space', `#\tab', `#\page', `#\linefeed', and
     `#\return'.  GRAPHIC characters are the printing characters and
     `#\space'.  STANDARD characters are the printing characters,
     `#\space', and `#\newline'.  These are the printing characters:

          ! " # $ % & ' ( ) * + , - . /
          0 1 2 3 4 5 6 7 8 9
          : ; < = > ? @
          A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
          [ \ ] ^ _ `
          a b c d e f g h i j k l m n o p q r s t u v w x y z
          { | } ~

 -- procedure: char-upper-case? char
 -- procedure: char-lower-case? char
 -- procedure: char-alphabetic? char
 -- procedure: char-numeric? char
 -- procedure: char-alphanumeric? char
 -- procedure: char-whitespace? char
 -- procedure: char-graphic? char
 -- procedure: char-standard? object
     These predicates are defined in terms of the respective character
     sets defined above.

 -- procedure: char-set-member? char-set char
     Returns `#t' if CHAR is in CHAR-SET; otherwise returns `#f'.

 -- procedure: char-set=? char-set-1 char-set-2
     Returns `#t' if CHAR-SET-1 and CHAR-SET-2 contain exactly the same
     characters; otherwise returns `#f'.

 -- procedure: char-set char ...
     Returns a character set consisting of the specified characters.
     With no arguments, `char-set' returns an empty character set.

 -- procedure: chars->char-set chars
     Returns a character set consisting of CHARS, which must be a list
     of characters.  This is equivalent to `(apply char-set CHARS)'.

 -- procedure: string->char-set string
     Returns a character set consisting of all the characters that
     occur in STRING.

 -- procedure: scalar-values->char-set items
     Returns a character set containing the Unicode scalar values
     described by ITEMS.  ITEMS must satisfy
     `well-formed-scalar-values-list?'.

 -- procedure: char-set->scalar-values char-set
     Returns a well-formed scalar-values list that describes the Unicode
     scalar values represented by CHAR-SET.

 -- procedure: well-formed-scalar-values-list? object
     Returns `#t' if OBJECT is a well-formed scalar-values list,
     otherwise returns `#f'.  A well-formed scalar-values list is a
     proper list, each element of which is either a Unicode scalar
     value or a pair of Unicode scalar values.  A pair of Unicode
     scalar values represents a contiguous range of Unicode scalar
     values.  The CAR of the pair is the inclusive lower limit, and the
     CDR is the exclusive upper limit.  The lower limit must be less
     than or equal to the upper limit.

 -- procedure: char-set-invert char-set
     Returns a character set consisting of the characters that are not
     in CHAR-SET.

 -- procedure: char-set-difference char-set1 char-set ...
     Returns a character set consisting of the characters that are in
     CHAR-SET1 but aren't in any of the CHAR-SETs.

 -- procedure: char-set-intersection char-set ...
     Returns a character set consisting of the characters that are in
     all of the CHAR-SETs.

 -- procedure: char-set-union char-set ...
     Returns a character set consisting of the characters that are in at
     least one o the CHAR-SETs.

 -- procedure: 8-bit-char-set? char-set
     Returns `#t' if CHAR-SET contains only 8-bit scalar values (i.e..
     ISO-8859-1 characters), otherwise returns `#f'.

 -- procedure: ascii-range->char-set lower upper
     This procedure is obsolete.  Instead use

          (scalar-values->char-set (list (cons LOWER UPPER)))

 -- procedure: char-set-members char-set
     This procedure is obsolete; instead use `char-set->scalar-values'.

     Returns a newly allocated list of the ISO-8859-1 characters in
     CHAR-SET.  If CHAR-SET contains any characters outside of the
     ISO-8859-1 range, they will not be in the returned list.


File: mit-scheme-ref.info,  Node: Unicode,  Prev: Character Sets,  Up: Characters

5.7 Unicode
===========

MIT/GNU Scheme provides rudimentary support for Unicode characters.  In
an ideal world, Unicode would be the base character set for MIT/GNU
Scheme.  But MIT/GNU Scheme predates the invention of Unicode, and
converting an application of this size is a considerable undertaking.
So for the time being, the base character set for strings is
ISO-8859-1, and Unicode support is grafted on.

   This Unicode support was implemented as a part of the XML parser
(*note XML Support::) implementation.  XML uses Unicode as its base
character set, and any XML implementation _must_ support Unicode.

   The basic unit in a Unicode implementation is the "scalar value".
The character equivalent of a scalar value is a "Unicode character".

 -- procedure: unicode-scalar-value? object
     Returns `#t' if OBJECT is a Unicode scalar value.  Scalar values
     are implemented as exact non-negative integers.  They are further
     limited, by the Unicode standard, to be strictly less than
     `#x110000', with the values `#xD800' through `#xDFFF', `#xFFFE',
     and `#xFFFF' excluded.

 -- procedure: unicode-char? object
     Returns `#t' if OBJECT is a Unicode character, specifically if
     OBJECT is a character with no bucky bits and whose code satisfies
     `unicode-scalar-value?'.

   The Unicode implementation consists of these parts:

   * An implementation of "wide strings", which are character strings
     that support the full Unicode character set with constant-time
     access.

   * I/O procedures that read and write Unicode characters in several
     external representations, specifically UTF-8, UTF-16, and UTF-32.

* Menu:

* Wide Strings::
* Unicode Representations::


File: mit-scheme-ref.info,  Node: Wide Strings,  Next: Unicode Representations,  Prev: Unicode,  Up: Unicode

5.7.1 Wide Strings
------------------

Wide characters can be combined into "wide strings", which are similar
to strings but can contain any Unicode character sequence.  The
implementation used for wide strings is guaranteed to provide
constant-time access to each character in the string.

 -- procedure: wide-string? object
     Returns `#t' if OBJECT is a wide string.

 -- procedure: make-wide-string k [unicode-char]
     Returns a newly allocated wide string of length K.  If CHAR is
     specified, all elements of the returned string are initialized to
     CHAR; otherwise the contents of the string are unspecified.

 -- procedure: wide-string unicode-char ...
     Returns a newly allocated wide string consisting of the specified
     characters.

 -- procedure: wide-string-length wide-string
     Returns the length of WIDE-STRING as an exact non-negative integer.

 -- procedure: wide-string-ref wide-string k
     Returns character K of WIDE-STRING.  K must be a valid index of
     STRING.

 -- procedure: wide-string-set! wide-string k unicode-char
     Stores CHAR in element K of WIDE-STRING and returns an unspecified
     value.  K must be a valid index of WIDE-STRING.

 -- procedure: string->wide-string string [start [end]]
     Returns a newly allocated wide string with the same contents as
     STRING.  If START and END are supplied, they specify a substring
     of STRING that is to be converted.  START defaults to `0', and END
     defaults to `(string-length STRING)'.

 -- procedure: wide-string->string wide-string [start [end]]
     Returns a newly allocated string with the same contents as
     WIDE-STRING.  The argument WIDE-STRING must satisfy
     `wide-string?'.  If START and END are supplied, they specify a
     substring of WIDE-STRING that is to be converted.  START defaults
     to `0', and END defaults to `(wide-string-length WIDE-STRING)'.

     It is an error if any character in WIDE-STRING fails to satisfy
     `char-ascii?'.

 -- procedure: open-wide-input-string wide-string [start [end]]
     Returns a new input port that sources the characters of
     WIDE-STRING.  The optional arguments START and END may be used to
     specify that the port delivers characters from a substring of
     WIDE-STRING; if not given, START defaults to `0' and END defaults
     to `(wide-string-length WIDE-STRING)'.

 -- procedure: open-wide-output-string
     Returns an output port that accepts Unicode characters and strings
     and accumulates them in a buffer.  Call `get-output-string' on the
     returned port to get a wide string containing the accumulated
     characters.

 -- procedure: call-with-wide-output-string procedure
     Creates a wide-string output port and calls PROCEDURE on that
     port.  The value returned by PROCEDURE is ignored, and the
     accumulated output is returned as a wide string.  This is
     equivalent to:

          (define (call-with-wide-output-string procedure)
            (let ((port (open-wide-output-string)))
              (procedure port)
              (get-output-string port)))


File: mit-scheme-ref.info,  Node: Unicode Representations,  Prev: Wide Strings,  Up: Unicode

5.7.2 Unicode Representations
-----------------------------

The procedures in this section implement transformations that convert
between the internal representation of Unicode characters and several
standard external representations.  These external representations are
all implemented as sequences of bytes, but they differ in their intended
usage.

UTF-8
     Each character is written as a sequence of one to four bytes.

UTF-16
     Each character is written as a sequence of one or two 16-bit
     integers.

UTF-32
     Each character is written as a single 32-bit integer.

   The UTF-16 and UTF-32 representations may be serialized to and from
a byte stream in either "big-endian" or "little-endian" order.  In
big-endian order, the most significant byte is first, the next most
significant byte is second, etc. In little-endian order, the least
significant byte is first, etc. All of the UTF-16 and UTF-32
representation procedures are available in both orders, which are
indicated by names containing `utfNN-be' and `utfNN-le', respectively.
There are also procedures that implement "host-endian" order, which is
either big-endian or little-endian depending on the underlying computer
architecture.

 -- procedure: utf8-string->wide-string string [start [end]]
 -- procedure: utf16-be-string->wide-string string [start [end]]
 -- procedure: utf16-le-string->wide-string string [start [end]]
 -- procedure: utf16-string->wide-string string [start [end]]
 -- procedure: utf32-be-string->wide-string string [start [end]]
 -- procedure: utf32-le-string->wide-string string [start [end]]
 -- procedure: utf32-string->wide-string string [start [end]]
     Each of these procedures converts a byte vector to a wide string,
     treating STRING as a stream of bytes encoded in the corresponding
     `utfNN' representation.  The arguments START and END allow
     specification of a substring; they default to zero and STRING's
     length, respectively.

 -- procedure: utf8-string-length string [start [end]]
 -- procedure: utf16-be-string-length string [start [end]]
 -- procedure: utf16-le-string-length string [start [end]]
 -- procedure: utf16-string-length string [start [end]]
 -- procedure: utf32-be-string-length string [start [end]]
 -- procedure: utf32-le-string-length string [start [end]]
 -- procedure: utf32-string-length string [start [end]]
     Each of these procedures counts the number of Unicode characters
     in a byte vector, treating STRING as a stream of bytes encoded in
     the corresponding `utfNN' representation.  The arguments START and
     END allow specification of a substring; they default to zero and
     STRING's length, respectively.

 -- procedure: wide-string->utf8-string string [start [end]]
 -- procedure: wide-string->utf16-be-string string [start [end]]
 -- procedure: wide-string->utf16-le-string string [start [end]]
 -- procedure: wide-string->utf16-string string [start [end]]
 -- procedure: wide-string->utf32-be-string string [start [end]]
 -- procedure: wide-string->utf32-le-string string [start [end]]
 -- procedure: wide-string->utf32-string string [start [end]]
     Each of these procedures converts a wide string to a stream of
     bytes encoded in the corresponding `utfNN' representation, and
     returns that stream as a byte vector.  The arguments START and END
     allow specification of a substring; they default to zero and
     STRING's length, respectively.


File: mit-scheme-ref.info,  Node: Strings,  Next: Lists,  Prev: Characters,  Up: Top

6 Strings
*********

A "string" is a mutable sequence of characters.  In the current
implementation of MIT/GNU Scheme, the elements of a string must all
satisfy the predicate `char-ascii?'; if someone ports MIT/GNU Scheme to
a non-ASCII operating system this requirement will change.

   A string is written as a sequence of characters enclosed within
double quotes `" "'.  To include a double quote inside a string, precede
the double quote with a backslash `\' (escape it), as in

     "The word \"recursion\" has many meanings."

The printed representation of this string is

     The word "recursion" has many meanings.

To include a backslash inside a string, precede it with another
backslash; for example,

     "Use #\\Control-q to quit."

The printed representation of this string is

     Use #\Control-q to quit.

   The effect of a backslash that doesn't precede a double quote or
backslash is unspecified in standard Scheme, but MIT/GNU Scheme
specifies the effect for three other characters: `\t', `\n', and `\f'.
These escape sequences are respectively translated into the following
characters: `#\tab', `#\newline', and `#\page'.  Finally, a backslash
followed by exactly three octal digits is translated into the character
whose ISO-8859-1 code is those digits.

   If a string literal is continued from one line to another, the string
will contain the newline character (`#\newline') at the line break.
Standard Scheme does not specify what appears in a string literal at a
line break.

   The "length" of a string is the number of characters that it
contains.  This number is an exact non-negative integer that is
established when the string is created (but *note Variable-Length
Strings::).  Each character in a string has an "index", which is a
number that indicates the character's position in the string.  The index
of the first (leftmost) character in a string is 0, and the index of the
last character is one less than the length of the string.  The "valid
indexes" of a string are the exact non-negative integers less than the
length of the string.

   A number of the string procedures operate on substrings.  A
"substring" is a segment of a STRING, which is specified by two
integers START and END satisfying these relationships:

     0 <= START <= END <= (string-length STRING)

START is the index of the first character in the substring, and END is
one greater than the index of the last character in the substring.
Thus if START and END are equal, they refer to an empty substring, and
if START is zero and END is the length of STRING, they refer to all of
STRING.

   Some of the procedures that operate on strings ignore the difference
between uppercase and lowercase.  The versions that ignore case include
`-ci' (for "case insensitive") in their names.

* Menu:

* Construction of Strings::
* Selecting String Components::
* Comparison of Strings::
* Alphabetic Case in Strings::
* Cutting and Pasting Strings::
* Searching Strings::
* Matching Strings::
* Regular Expressions::
* Modification of Strings::
* Variable-Length Strings::
* Byte Vectors::


File: mit-scheme-ref.info,  Node: Construction of Strings,  Next: Selecting String Components,  Prev: Strings,  Up: Strings

6.1 Construction of Strings
===========================

 -- procedure: make-string k [char]
     Returns a newly allocated string of length K.  If you specify
     CHAR, all elements of the string are initialized to CHAR,
     otherwise the contents of the string are unspecified.  CHAR must
     satisfy the predicate `char-ascii?'.

          (make-string 10 #\x)              =>  "xxxxxxxxxx"

 -- procedure: string char ...
     Returns a newly allocated string consisting of the specified
     characters.  The arguments must all satisfy `char-ascii?'.

          (string #\a)                                =>  "a"
          (string #\a #\b #\c)                        =>  "abc"
          (string #\a #\space #\b #\space #\c)        =>  "a b c"
          (string)                                    =>  ""

 -- procedure: list->string char-list
     CHAR-LIST must be a list of ISO-8859-1 characters.  `list->string'
     returns a newly allocated string formed from the elements of
     CHAR-LIST.  This is equivalent to `(apply string CHAR-LIST)'.  The
     inverse of this operation is `string->list'.

          (list->string '(#\a #\b))           =>  "ab"
          (string->list "Hello")              =>  (#\H #\e #\l #\l #\o)

 -- procedure: string-copy string
     Returns a newly allocated copy of STRING.

     Note regarding variable-length strings: the maximum length of the
     result depends only on the length of STRING, not its maximum
     length.  If you wish to copy a string and preserve its maximum
     length, do the following:

          (define (string-copy-preserving-max-length string)
            (let ((length))
              (dynamic-wind
               (lambda ()
                 (set! length (string-length string))
                 (set-string-length! string
                                     (string-maximum-length string)))
               (lambda ()
                 (string-copy string))
               (lambda ()
                 (set-string-length! string length)))))


File: mit-scheme-ref.info,  Node: Selecting String Components,  Next: Comparison of Strings,  Prev: Construction of Strings,  Up: Strings

6.2 Selecting String Components
===============================

 -- procedure: string? object
     Returns `#t' if OBJECT is a string; otherwise returns `#f'.

          (string? "Hi")                  =>  #t
          (string? 'Hi)                   =>  #f

 -- procedure: string-length string
     Returns the length of STRING as an exact non-negative integer.

          (string-length "")              =>  0
          (string-length "The length")    =>  10

 -- procedure: string-null? string
     Returns `#t' if STRING has zero length; otherwise returns `#f'.

          (string-null? "")               =>  #t
          (string-null? "Hi")             =>  #f

 -- procedure: string-ref string k
     Returns character K of STRING.  K must be a valid index of STRING.

          (string-ref "Hello" 1)          =>  #\e
          (string-ref "Hello" 5)          error--> 5 not in correct range

 -- procedure: string-set! string k char
     Stores CHAR in element K of STRING and returns an unspecified
     value.  K must be a valid index of STRING, and CHAR must satisfy
     the predicate `char-ascii?'.

          (define str "Dog")              =>  unspecified
          (string-set! str 0 #\L)         =>  unspecified
          str                             =>  "Log"
          (string-set! str 3 #\t)         error--> 3 not in correct range


File: mit-scheme-ref.info,  Node: Comparison of Strings,  Next: Alphabetic Case in Strings,  Prev: Selecting String Components,  Up: Strings

6.3 Comparison of Strings
=========================

 -- procedure: string=? string1 string2
 -- procedure: substring=? string1 start end string2 start end
 -- procedure: string-ci=? string1 string2
 -- procedure: substring-ci=? string1 start end string2 start end
     Returns `#t' if the two strings (substrings) are the same length
     and contain the same characters in the same (relative) positions;
     otherwise returns `#f'.  `string-ci=?' and `substring-ci=?' don't
     distinguish uppercase and lowercase letters, but `string=?' and
     `substring=?' do.

          (string=? "PIE" "PIE")                  =>  #t
          (string=? "PIE" "pie")                  =>  #f
          (string-ci=? "PIE" "pie")               =>  #t
          (substring=? "Alamo" 1 3 "cola" 2 4)    =>  #t ; compares "la"

 -- procedure: string<? string1 string2
 -- procedure: substring<? string1 start1 end1 string2 start2 end2
 -- procedure: string>? string1 string2
 -- procedure: string<=? string1 string2
 -- procedure: string>=? string1 string2
 -- procedure: string-ci<? string1 string2
 -- procedure: substring-ci<? string1 start1 end1 string2 start2 end2
 -- procedure: string-ci>? string1 string2
 -- procedure: string-ci<=? string1 string2
 -- procedure: string-ci>=? string1 string2
     These procedures compare strings (substrings) according to the
     order of the characters they contain (also *note Comparison of
     Characters::).  The arguments are compared using a lexicographic
     (or dictionary) order.  If two strings differ in length but are
     the same up to the length of the shorter string, the shorter
     string is considered to be less than the longer string.

          (string<? "cat" "dog")          =>  #t
          (string<? "cat" "DOG")          =>  #f
          (string-ci<? "cat" "DOG")       =>  #t
          (string>? "catkin" "cat")       =>  #t ; shorter is lesser

 -- procedure: string-compare string1 string2 if-eq if-lt if-gt
 -- procedure: string-compare-ci string1 string2 if-eq if-lt if-gt
     IF-EQ, IF-LT, and IF-GT are procedures of no arguments (thunks).
     The two strings are compared; if they are equal, IF-EQ is applied,
     if STRING1 is less than STRING2, IF-LT is applied, else if STRING1
     is greater than STRING2, IF-GT is applied.  The value of the
     procedure is the value of the thunk that is applied.

     `string-compare' distinguishes uppercase and lowercase letters;
     `string-compare-ci' does not.

          (define (cheer) (display "Hooray!"))
          (define (boo)   (display "Boo-hiss!"))
          (string-compare "a" "b"  cheer  (lambda() 'ignore)  boo)
                  -|  Hooray!
                  =>  unspecified

 -- procedure: string-hash string
 -- procedure: string-hash-mod string k
     `string-hash' returns an exact non-negative integer that can be
     used for storing the specified STRING in a hash table.  Equal
     strings (in the sense of `string=?') return equal (`=') hash codes,
     and non-equal but similar strings are usually mapped to distinct
     hash codes.

     `string-hash-mod' is like `string-hash', except that it limits the
     result to a particular range based on the exact non-negative
     integer K.  The following are equivalent:

          (string-hash-mod STRING K)
          (modulo (string-hash STRING) K)


File: mit-scheme-ref.info,  Node: Alphabetic Case in Strings,  Next: Cutting and Pasting Strings,  Prev: Comparison of Strings,  Up: Strings

6.4 Alphabetic Case in Strings
==============================

 -- procedure: string-capitalized? string
 -- procedure: substring-capitalized? string start end
     These procedures return `#t' if the first word in the string
     (substring) is capitalized, and any subsequent words are either
     lower case or capitalized.  Otherwise, they return `#f'.  A word is
     defined as a non-null contiguous sequence of alphabetic characters,
     delimited by non-alphabetic characters or the limits of the string
     (substring).  A word is capitalized if its first letter is upper
     case and all its remaining letters are lower case.

          (map string-capitalized? '(""    "A"    "art"  "Art"  "ART"))
                                 => (#f    #t     #f     #t     #f)

 -- procedure: string-upper-case? string
 -- procedure: substring-upper-case? string start end
 -- procedure: string-lower-case? string
 -- procedure: substring-lower-case? string start end
     These procedures return `#t' if all the letters in the string
     (substring) are of the correct case, otherwise they return `#f'.
     The string (substring) must contain at least one letter or the
     procedures return `#f'.

          (map string-upper-case?  '(""    "A"    "art"  "Art"  "ART"))
                                 => (#f    #t     #f     #f     #t)

 -- procedure: string-capitalize string
 -- procedure: string-capitalize! string
 -- procedure: substring-capitalize! string start end
     `string-capitalize' returns a newly allocated copy of STRING in
     which the first alphabetic character is uppercase and the remaining
     alphabetic characters are lowercase.  For example, `"abcDEF"'
     becomes `"Abcdef"'.  `string-capitalize!' is the destructive
     version of `string-capitalize': it alters STRING and returns an
     unspecified value.  `substring-capitalize!' destructively
     capitalizes the specified part of STRING.

 -- procedure: string-downcase string
 -- procedure: string-downcase! string
 -- procedure: substring-downcase! string start end
     `string-downcase' returns a newly allocated copy of STRING in
     which all uppercase letters are changed to lowercase.
     `string-downcase!' is the destructive version of
     `string-downcase': it alters STRING and returns an unspecified
     value.  `substring-downcase!' destructively changes the case of
     the specified part of STRING.

          (define str "ABCDEFG")          =>  unspecified
          (substring-downcase! str 3 5)   =>  unspecified
          str                             =>  "ABCdeFG"

 -- procedure: string-upcase string
 -- procedure: string-upcase! string
 -- procedure: substring-upcase! string start end
     `string-upcase' returns a newly allocated copy of STRING in which
     all lowercase letters are changed to uppercase.  `string-upcase!'
     is the destructive version of `string-upcase': it alters STRING
     and returns an unspecified value.  `substring-upcase!'
     destructively changes the case of the specified part of STRING.


File: mit-scheme-ref.info,  Node: Cutting and Pasting Strings,  Next: Searching Strings,  Prev: Alphabetic Case in Strings,  Up: Strings

6.5 Cutting and Pasting Strings
===============================

 -- procedure: string-append string ...
     Returns a newly allocated string made from the concatenation of
     the given strings.  With no arguments, `string-append' returns the
     empty string (`""').

          (string-append)                         =>  ""
          (string-append "*" "ace" "*")           =>  "*ace*"
          (string-append "" "" "")                =>  ""
          (eq? str (string-append str))           =>  #f ; newly allocated

 -- procedure: substring string start end
     Returns a newly allocated string formed from the characters of
     STRING beginning with index START (inclusive) and ending with END
     (exclusive).

          (substring "" 0 0)              => ""
          (substring "arduous" 2 5)       => "duo"
          (substring "arduous" 2 8)       error--> 8 not in correct range

          (define (string-copy s)
            (substring s 0 (string-length s)))

 -- procedure: string-head string end
     Returns a newly allocated copy of the initial substring of STRING,
     up to but excluding END.  It could have been defined by:

          (define (string-head string end)
            (substring string 0 end))

 -- procedure: string-tail string start
     Returns a newly allocated copy of the final substring of STRING,
     starting at index START and going to the end of STRING.  It could
     have been defined by:

          (define (string-tail string start)
            (substring string start (string-length string)))

          (string-tail "uncommon" 2)      =>  "common"

 -- procedure: string-pad-left string k [char]
 -- procedure: string-pad-right string k [char]
     These procedures return a newly allocated string created by padding
     STRING out to length K, using CHAR.  If CHAR is not given, it
     defaults to `#\space'.  If K is less than the length of STRING,
     the resulting string is a truncated form of STRING.
     `string-pad-left' adds padding characters or truncates from the
     beginning of the string (lowest indices), while `string-pad-right'
     does so at the end of the string (highest indices).

          (string-pad-left "hello" 4)             =>  "ello"
          (string-pad-left "hello" 8)             =>  "   hello"
          (string-pad-left "hello" 8 #\*)         =>  "***hello"
          (string-pad-right "hello" 4)            =>  "hell"
          (string-pad-right "hello" 8)            =>  "hello   "

 -- procedure: string-trim string [char-set]
 -- procedure: string-trim-left string [char-set]
 -- procedure: string-trim-right string [char-set]
     Returns a newly allocated string created by removing all
     characters that are not in CHAR-SET from: (`string-trim') both
     ends of STRING; (`string-trim-left') the beginning of STRING; or
     (`string-trim-right') the end of STRING.  CHAR-SET defaults to
     `char-set:not-whitespace'.

          (string-trim "  in the end  ")          =>  "in the end"
          (string-trim "              ")          =>  ""
          (string-trim "100th" char-set:numeric)  =>  "100"
          (string-trim-left "-.-+-=-" (char-set #\+))
                                                  =>  "+-=-"
          (string-trim "but (+ x y) is" (char-set #\( #\)))
                                                  =>  "(+ x y)"


File: mit-scheme-ref.info,  Node: Searching Strings,  Next: Matching Strings,  Prev: Cutting and Pasting Strings,  Up: Strings

6.6 Searching Strings
=====================

The first few procedures in this section perform "string search", in
which a given string (the "text") is searched to see if it contains
another given string (the "pattern") as a proper substring.  At present
these procedures are implemented using a hybrid strategy.  For short
patterns of less than 4 characters, the naive string-search algorithm
is used.  For longer patterns, the Boyer-Moore string-search algorithm
is used.

 -- procedure: string-search-forward pattern string
 -- procedure: substring-search-forward pattern string start end
     PATTERN must be a string.  Searches STRING for the leftmost
     occurrence of the substring PATTERN.  If successful, the index of
     the first character of the matched substring is returned;
     otherwise, `#f' is returned.

     `substring-search-forward' limits its search to the specified
     substring of STRING; `string-search-forward' searches all of
     STRING.

          (string-search-forward "rat" "pirate")
              => 2
          (string-search-forward "rat" "pirate rating")
              => 2
          (substring-search-forward "rat" "pirate rating" 4 13)
              => 7
          (substring-search-forward "rat" "pirate rating" 9 13)
              => #f

 -- procedure: string-search-backward pattern string
 -- procedure: substring-search-backward pattern string start end
     PATTERN must be a string.  Searches STRING for the rightmost
     occurrence of the substring PATTERN.  If successful, the index to
     the right of the last character of the matched substring is
     returned; otherwise, `#f' is returned.

     `substring-search-backward' limits its search to the specified
     substring of STRING; `string-search-backward' searches all of
     STRING.

          (string-search-backward "rat" "pirate")
              => 5
          (string-search-backward "rat" "pirate rating")
              => 10
          (substring-search-backward "rat" "pirate rating" 1 8)
              => 5
          (substring-search-backward "rat" "pirate rating" 9 13)
              => #f

 -- procedure: string-search-all pattern string
 -- procedure: substring-search-all pattern string start end
     PATTERN must be a string.  Searches STRING to find all occurrences
     of the substring PATTERN.  Returns a list of the occurrences; each
     element of the list is an index pointing to the first character of
     an occurrence.

     `substring-search-all' limits its search to the specified substring
     of STRING; `string-search-all' searches all of STRING.

          (string-search-all "rat" "pirate")
              => (2)
          (string-search-all "rat" "pirate rating")
              => (2 7)
          (substring-search-all "rat" "pirate rating" 4 13)
              => (7)
          (substring-search-all "rat" "pirate rating" 9 13)
              => ()

 -- procedure: substring? pattern string
     PATTERN must be a string.  Searches STRING to see if it contains
     the substring PATTERN.  Returns `#t' if PATTERN is a substring of
     STRING, otherwise returns `#f'.

          (substring? "rat" "pirate")             =>  #t
          (substring? "rat" "outrage")            =>  #f
          (substring? "" any-string)              =>  #t
          (if (substring? "moon" text)
              (process-lunar text)
              'no-moon)

 -- procedure: string-find-next-char string char
 -- procedure: substring-find-next-char string start end char
 -- procedure: string-find-next-char-ci string char
 -- procedure: substring-find-next-char-ci string start end char
     Returns the index of the first occurrence of CHAR in the string
     (substring); returns `#f' if CHAR does not appear in the string.
     For the substring procedures, the index returned is relative to
     the entire string, not just the substring.  The `-ci' procedures
     don't distinguish uppercase and lowercase letters.

          (string-find-next-char "Adam" #\A)              =>  0
          (substring-find-next-char "Adam" 1 4 #\A)       =>  #f
          (substring-find-next-char-ci "Adam" 1 4 #\A)    =>  2

 -- procedure: string-find-next-char-in-set string char-set
 -- procedure: substring-find-next-char-in-set string start end char-set
     Returns the index of the first character in the string (or
     substring) that is also in CHAR-SET, or returns `#f' if none of the
     characters in CHAR-SET occur in STRING.  For the substring
     procedure, only the substring is searched, but the index returned
     is relative to the entire string, not just the substring.

          (string-find-next-char-in-set my-string char-set:alphabetic)
              =>  start position of the first word in my-string
          ; Can be used as a predicate:
          (if (string-find-next-char-in-set my-string
                                            (char-set #\( #\) ))
              'contains-parentheses
              'no-parentheses)

 -- procedure: string-find-previous-char string char
 -- procedure: substring-find-previous-char string start end char
 -- procedure: string-find-previous-char-ci string char
 -- procedure: substring-find-previous-char-ci string start end char
     Returns the index of the last occurrence of CHAR in the string
     (substring); returns `#f' if CHAR doesn't appear in the string.
     For the substring procedures, the index returned is relative to
     the entire string, not just the substring.  The `-ci' procedures
     don't distinguish uppercase and lowercase letters.

 -- procedure: string-find-previous-char-in-set string char-set
 -- procedure: substring-find-previous-char-in-set string start end
          char-set
     Returns the index of the last character in the string (substring)
     that is also in CHAR-SET.  For the substring procedure, the index
     returned is relative to the entire string, not just the substring.


File: mit-scheme-ref.info,  Node: Matching Strings,  Next: Regular Expressions,  Prev: Searching Strings,  Up: Strings

6.7 Matching Strings
====================

 -- procedure: string-match-forward string1 string2
 -- procedure: substring-match-forward string1 start end string2 start
          end
 -- procedure: string-match-forward-ci string1 string2
 -- procedure: substring-match-forward-ci string1 start end string2
          start end
     Compares the two strings (substrings), starting from the
     beginning, and returns the number of characters that are the same.
     If the two strings (substrings) start differently, returns 0.
     The `-ci' procedures don't distinguish uppercase and lowercase
     letters.

          (string-match-forward "mirror" "micro") =>  2  ; matches "mi"
          (string-match-forward "a" "b")          =>  0  ; no match

 -- procedure: string-match-backward string1 string2
 -- procedure: substring-match-backward string1 start end string2 start
          end
 -- procedure: string-match-backward-ci string1 string2
 -- procedure: substring-match-backward-ci string1 start end string2
          start end
     Compares the two strings (substrings), starting from the end and
     matching toward the front, returning the number of characters that
     are the same.  If the two strings (substrings) end differently,
     returns 0.  The `-ci' procedures don't distinguish uppercase and
     lowercase letters.

          (string-match-backward-ci "BULBOUS" "fractious")
                                                  =>  3  ; matches "ous"

 -- procedure: string-prefix? string1 string2
 -- procedure: substring-prefix? string1 start1 end1 string2 start2 end2
 -- procedure: string-prefix-ci? string1 string2
 -- procedure: substring-prefix-ci? string1 start1 end1 string2 start2
          end2
     These procedures return `#t' if the first string (substring) forms
     the prefix of the second; otherwise returns `#f'.  The `-ci'
     procedures don't distinguish uppercase and lowercase letters.

          (string-prefix? "abc" "abcdef")         =>  #t
          (string-prefix? "" any-string)          =>  #t

 -- procedure: string-suffix? string1 string2
 -- procedure: substring-suffix? string1 start1 end1 string2 start2 end2
 -- procedure: string-suffix-ci? string1 string2
 -- procedure: substring-suffix-ci? string1 start1 end1 string2 start2
          end2
     These procedures return `#t' if the first string (substring) forms
     the suffix of the second; otherwise returns `#f'.  The `-ci'
     procedures don't distinguish uppercase and lowercase letters.

          (string-suffix? "ous" "bulbous")        =>  #t
          (string-suffix? "" any-string)          =>  #t


File: mit-scheme-ref.info,  Node: Regular Expressions,  Next: Modification of Strings,  Prev: Matching Strings,  Up: Strings

6.8 Regular Expressions
=======================

MIT/GNU Scheme provides support for using regular expressions to search
and match strings.  This manual does not define regular expressions;
instead see *Note Syntax of Regular Expressions: (emacs)Regexps.

   In addition to providing standard regular-expression support, MIT/GNU
Scheme also provides the REXP abstraction.  This is an alternative way
to write regular expressions that is easier to read and understand than
the standard notation.  Regular expressions written in this notation
can be translated into the standard notation.

   The regular-expression support is a run-time-loadable option.  To use
it, execute

     (load-option 'regular-expression)

once before calling any of the procedures defined here.

* Menu:

* Regular-expression procedures::
* REXP abstraction::


File: mit-scheme-ref.info,  Node: Regular-expression procedures,  Next: REXP abstraction,  Prev: Regular Expressions,  Up: Regular Expressions

6.8.1 Regular-expression procedures
-----------------------------------

Procedures that perform regular-expression match and search accept
standardized arguments.  REGEXP is the regular expression; it is a
string.  STRING is the string being matched or searched.  Procedures
that operate on substrings also accept START and END index arguments
with the usual meaning.  The optional argument CASE-FOLD? says whether
the match/search is case-sensitive; if CASE-FOLD? is `#f', it is
case-sensitive, otherwise it is case-insensitive.  The optional
argument SYNTAX-TABLE is a character syntax table that defines the
character syntax, such as which characters are legal word constituents.
This feature is primarily for Edwin, so character syntax tables will
not be documented here.  Supplying `#f' for (or omitting) SYNTAX-TABLE
will select the default character syntax, equivalent to Edwin's
`fundamental' mode.

 -- procedure: re-string-match regexp string [case-fold? [syntax-table]]
 -- procedure: re-substring-match regexp string start end [case-fold?
          [syntax-table]]
     These procedures match REGEXP against the respective string or
     substring, returning `#f' for no match, or a set of match registers
     (see below) if the match succeeds.  Here is an example showing how
     to extract the matched substring:

          (let ((r (re-substring-match REGEXP STRING START END)))
            (and r
                 (substring STRING START (re-match-end-index 0 r))))

 -- procedure: re-string-search-forward regexp string [case-fold?
          [syntax-table]]
 -- procedure: re-substring-search-forward regexp string start end
          [case-fold? [syntax-table]]
     Searches STRING for the leftmost substring matching REGEXP.
     Returns a set of match registers (see below) if the search is
     successful, or `#f' if it is unsuccessful.

     `re-substring-search-forward' limits its search to the specified
     substring of STRING; `re-string-search-forward' searches all of
     STRING.

 -- procedure: re-string-search-backward regexp string [case-fold?
          [syntax-table]]
 -- procedure: re-substring-search-backward regexp string start end
          [case-fold? [syntax-table]]
     Searches STRING for the rightmost substring matching REGEXP.
     Returns a set of match registers (see below) if the search is
     successful, or `#f' if it is unsuccessful.

     `re-substring-search-backward' limits its search to the specified
     substring of STRING; `re-string-search-backward' searches all of
     STRING.

   When a successful match or search occurs, the above procedures
return a set of "match registers".  The match registers are a set of
index registers that record indexes into the matched string.  Each index
register corresponds to an instance of the regular-expression grouping
operator `\(', and records the start index (inclusive) and end index
(exclusive) of the matched group.  These registers are numbered from
`1' to `9', corresponding left-to-right to the grouping operators in
the expression.  Additionally, register `0' corresponds to the entire
substring matching the regular expression.

 -- procedure: re-match-start-index n registers
 -- procedure: re-match-end-index n registers
     N must be an exact integer between `0' and `9' inclusive.
     REGISTERS must be a match-registers object as returned by one of
     the regular-expression match or search procedures above.
     `re-match-start-index' returns the start index of the corresponding
     regular-expression register, and `re-match-end-index' returns the
     corresponding end index.

 -- procedure: re-match-extract string registers n
     REGISTERS must be a match-registers object as returned by one of
     the regular-expression match or search procedures above.  STRING
     must be the string that was passed as an argument to the procedure
     that returned REGISTERS.  N must be an exact integer between `0'
     and `9' inclusive.  If the matched regular expression contained M
     grouping operators, then the value of this procedure is undefined
     for N strictly greater than M.

     This procedure extracts the substring corresponding to the match
     register specified by REGISTERS and N.  This is equivalent to the
     following expression:

          (substring STRING
                     (re-match-start-index N REGISTERS)
                     (re-match-end-index N REGISTERS))

 -- procedure: regexp-group alternative ...
     Each ALTERNATIVE must be a regular expression.  The returned value
     is a new regular expression that consists of the ALTERNATIVEs
     combined by a grouping operator.  For example:

          (regexp-group "foo" "bar" "baz")
            => "\\(foo\\|bar\\|baz\\)"


File: mit-scheme-ref.info,  Node: REXP abstraction,  Prev: Regular-expression procedures,  Up: Regular Expressions

6.8.2 REXP abstraction
----------------------

In addition to providing standard regular-expression support, MIT/GNU
Scheme also provides the REXP abstraction.  This is an alternative way
to write regular expressions that is easier to read and understand than
the standard notation.  Regular expressions written in this notation
can be translated into the standard notation.

   The REXP abstraction is a set of combinators that are composed into
a complete regular expression.  Each combinator directly corresponds to
a particular piece of regular-expression notation.  For example, the
expression `(rexp-any-char)' corresponds to the `.' character in
standard regular-expression notation, while `(rexp* REXP)' corresponds
to the `*' character.

   The primary advantages of REXP are that it makes the nesting
structure of regular expressions explicit, and that it simplifies the
description of complex regular expressions by allowing them to be built
up using straightforward combinators.

 -- procedure: rexp? object
     Returns `#t' if OBJECT is a REXP expression, or `#f' otherwise.  A
     REXP is one of: a string, which represents the pattern matching
     that string; a character set, which represents the pattern
     matching a character in that set; or an object returned by calling
     one of the procedures defined here.

 -- procedure: rexp->regexp rexp
     Converts REXP to standard regular-expression notation, returning a
     newly-allocated string.

 -- procedure: rexp-compile rexp
     Converts REXP to standard regular-expression notation, then
     compiles it and returns the compiled result.  Equivalent to

          (re-compile-pattern (rexp->regexp REXP) #f)

 -- procedure: rexp-any-char
     Returns a REXP that matches any single character except a newline.
     This is equivalent to the `.' construct.

 -- procedure: rexp-line-start
     Returns a REXP that matches the start of a line.  This is
     equivalent to the `^' construct.

 -- procedure: rexp-line-end
     Returns a REXP that matches the end of a line.  This is equivalent
     to the `$' construct.

 -- procedure: rexp-string-start
     Returns a REXP that matches the start of the text being matched.
     This is equivalent to the `\`' construct.

 -- procedure: rexp-string-end
     Returns a REXP that matches the end of the text being matched.
     This is equivalent to the `\'' construct.

 -- procedure: rexp-word-edge
     Returns a REXP that matches the start or end of a word.  This is
     equivalent to the `\b' construct.

 -- procedure: rexp-not-word-edge
     Returns a REXP that matches anywhere that is not the start or end
     of a word.  This is equivalent to the `\B' construct.

 -- procedure: rexp-word-start
     Returns a REXP that matches the start of a word.  This is
     equivalent to the `\<' construct.

 -- procedure: rexp-word-end
     Returns a REXP that matches the end of a word.  This is equivalent
     to the `\>' construct.

 -- procedure: rexp-word-char
     Returns a REXP that matches any word-constituent character.  This
     is equivalent to the `\w' construct.

 -- procedure: rexp-not-word-char
     Returns a REXP that matches any character that isn't a word
     constituent.  This is equivalent to the `\W' construct.

   The next two procedures accept a SYNTAX-TYPE argument specifying the
syntax class to be matched against.  This argument is a symbol selected
from the following list.  Each symbol is followed by the equivalent
character used in standard regular-expression notation.  `whitespace'
(space character), `punctuation' (`.'), `word' (`w'), `symbol' (`_'),
`open' (`('), `close' (`)'), `quote' (`''), `string-delimiter' (`"'),
`math-delimiter' (`$'), `escape' (`\'), `char-quote' (`/'),
`comment-start' (`<'), `comment-end' (`>').

 -- procedure: rexp-syntax-char syntax-type
     Returns a REXP that matches any character of type SYNTAX-TYPE.
     This is equivalent to the `\s' construct.

 -- procedure: rexp-not-syntax-char syntax-type
     Returns a REXP that matches any character not of type SYNTAX-TYPE.
     This is equivalent to the `\S' construct.

 -- procedure: rexp-sequence rexp ...
     Returns a REXP that matches each REXP argument in sequence.  If no
     REXP argument is supplied, the result matches the null string.
     This is equivalent to concatenating the regular expressions
     corresponding to each REXP argument.

 -- procedure: rexp-alternatives rexp ...
     Returns a REXP that matches any of the REXP arguments.  This is
     equivalent to concatenating the regular expressions corresponding
     to each REXP argument, separating them by the `\|' construct.

 -- procedure: rexp-group rexp ...
     `rexp-group' is like `rexp-sequence', except that the result is
     marked as a match group.  This is equivalent to the `\(' ... `\)'
     construct.

   The next three procedures in principal accept a single REXP
argument.  For convenience, they accept multiple arguments, which are
converted into a single argument by `rexp-group'.  Note, however, that
if only one REXP argument is supplied, and it's very simple, no
grouping occurs.

 -- procedure: rexp* rexp ...
     Returns a REXP that matches zero or more instances of the pattern
     matched by the REXP arguments.  This is equivalent to the `*'
     construct.

 -- procedure: rexp+ rexp ...
     Returns a REXP that matches one or more instances of the pattern
     matched by the REXP arguments.  This is equivalent to the `+'
     construct.

 -- procedure: rexp-optional rexp ...
     Returns a REXP that matches zero or one instances of the pattern
     matched by the REXP arguments.  This is equivalent to the `?'
     construct.

 -- procedure: rexp-case-fold rexp
     Returns a REXP that matches the same pattern as REXP, but is
     insensitive to character case.  This has no equivalent in standard
     regular-expression notation.


File: mit-scheme-ref.info,  Node: Modification of Strings,  Next: Variable-Length Strings,  Prev: Regular Expressions,  Up: Strings

6.9 Modification of Strings
===========================

 -- procedure: string-replace string char1 char2
 -- procedure: substring-replace string start end char1 char2
 -- procedure: string-replace! string char1 char2
 -- procedure: substring-replace! string start end char1 char2
     These procedures replace all occurrences of CHAR1 with CHAR2 in
     the original string (substring).  `string-replace' and
     `substring-replace' return a newly allocated string containing the
     result.  `string-replace!' and `substring-replace!' destructively
     modify STRING and return an unspecified value.

          (define str "a few words")              =>  unspecified
          (string-replace str #\space #\-)        =>  "a-few-words"
          (substring-replace str 2 9 #\space #\-) =>  "a few-words"
          str                                     =>  "a few words"
          (string-replace! str #\space #\-)       =>  unspecified
          str                                     =>  "a-few-words"

 -- procedure: string-fill! string char
     Stores CHAR in every element of STRING and returns an unspecified
     value.

 -- procedure: substring-fill! string start end char
     Stores CHAR in elements START (inclusive) to END (exclusive) of
     STRING and returns an unspecified value.

          (define s (make-string 10 #\space))     =>  unspecified
          (substring-fill! s 2 8 #\*)             =>  unspecified
          s                                       =>  "  ******  "

 -- procedure: substring-move-left! string1 start1 end1 string2 start2
 -- procedure: substring-move-right! string1 start1 end1 string2 start2
     Copies the characters from START1 to END1 of STRING1 into STRING2
     at the START2-th position.  The characters are copied as follows
     (note that this is only important when STRING1 and STRING2 are
     `eqv?'):

    `substring-move-left!'
          The copy starts at the left end and moves toward the right
          (from smaller indices to larger).  Thus if STRING1 and
          STRING2 are the same, this procedure moves the characters
          toward the left inside the string.

    `substring-move-right!'
          The copy starts at the right end and moves toward the left
          (from larger indices to smaller).  Thus if STRING1 and
          STRING2 are the same, this procedure moves the characters
          toward the right inside the string.

     The following example shows how these procedures can be used to
     build up a string (it would have been easier to use
     `string-append'):
          (define answer (make-string 9 #\*))         =>  unspecified
          answer                                      =>  "*********"
          (substring-move-left! "start" 0 5 answer 0) =>  unspecified
          answer                                      =>  "start****"
          (substring-move-left! "-end" 0 4 answer 5)  =>  unspecified
          answer                                      =>  "start-end"

 -- procedure: reverse-string string
 -- procedure: reverse-substring string start end
 -- procedure: reverse-string! string
 -- procedure: reverse-substring! string start end
     Reverses the order of the characters in the given string or
     substring.  `reverse-string' and `reverse-substring' return newly
     allocated strings; `reverse-string!' and `reverse-substring!'
     modify their argument strings and return an unspecified value.

          (reverse-string "foo bar baz")          => "zab rab oof"
          (reverse-substring "foo bar baz" 4 7)   => "rab"
          (let ((foo "foo bar baz"))
            (reverse-string! foo)
            foo)                                  => "zab rab oof"
          (let ((foo "foo bar baz"))
            (reverse-substring! foo 4 7)
            foo)                                  => "foo rab baz"


File: mit-scheme-ref.info,  Node: Variable-Length Strings,  Next: Byte Vectors,  Prev: Modification of Strings,  Up: Strings

6.10 Variable-Length Strings
============================

MIT/GNU Scheme allows the length of a string to be dynamically adjusted
in a limited way.  When a new string is allocated, by whatever method,
it has a specific length.  At the time of allocation, it is also given a
"maximum length", which is guaranteed to be at least as large as the
string's length.  (Sometimes the maximum length will be slightly larger
than the length, but it is a bad idea to count on this.  Programs should
assume that the maximum length is the same as the length at the time of
the string's allocation.)  After the string is allocated, the operation
`set-string-length!' can be used to alter the string's length to any
value between 0 and the string's maximum length, inclusive.

 -- procedure: string-maximum-length string
     Returns the maximum length of STRING.  The following is guaranteed:

          (<= (string-length string)
              (string-maximum-length string))     =>  #t
     
     The maximum length of a string never changes.

 -- procedure: set-string-length! string k
     Alters the length of STRING to be K, and returns an unspecified
     value.  K must be less than or equal to the maximum length of
     STRING.  `set-string-length!' does not change the maximum length
     of STRING.


File: mit-scheme-ref.info,  Node: Byte Vectors,  Prev: Variable-Length Strings,  Up: Strings

6.11 Byte Vectors
=================

MIT/GNU Scheme implements strings as packed vectors of 8-bit ISO-8859-1
bytes.  Most of the string operations, such as `string-ref', coerce
these 8-bit codes into character objects.  However, some lower-level
operations are made available for use.

 -- procedure: vector-8b-ref string k
     Returns character K of STRING as an ISO-8859-1 code.  K must be a
     valid index of STRING.

          (vector-8b-ref "abcde" 2)               =>  99 ;c

 -- procedure: vector-8b-set! string k code
     Stores CODE in element K of STRING and returns an unspecified
     value.  K must be a valid index of STRING, and CODE must be a
     valid ISO-8859-1 code.

 -- procedure: vector-8b-fill! string start end code
     Stores CODE in elements START (inclusive) to END (exclusive) of
     STRING and returns an unspecified value.  CODE must be a valid
     ISO-8859-1 code.

 -- procedure: vector-8b-find-next-char string start end code
 -- procedure: vector-8b-find-next-char-ci string start end code
     Returns the index of the first occurrence of CODE in the given
     substring; returns `#f' if CODE does not appear.  The index
     returned is relative to the entire string, not just the substring.
     CODE must be a valid ISO-8859-1 code.

     `vector-8b-find-next-char-ci' doesn't distinguish uppercase and
     lowercase letters.

 -- procedure: vector-8b-find-previous-char string start end code
 -- procedure: vector-8b-find-previous-char-ci string start end code
     Returns the index of the last occurrence of CODE in the given
     substring; returns `#f' if CODE does not appear.  The index
     returned is relative to the entire string, not just the substring.
     CODE must be a valid ISO-8859-1 code.

     `vector-8b-find-previous-char-ci' doesn't distinguish uppercase and
     lowercase letters.


File: mit-scheme-ref.info,  Node: Lists,  Next: Vectors,  Prev: Strings,  Up: Top

7 Lists
*******

A "pair" (sometimes called a "dotted pair") is a data structure with
two fields called the "car" and "cdr" fields (for historical reasons).
Pairs are created by the procedure `cons'.  The car and cdr fields are
accessed by the procedures `car' and `cdr'.  The car and cdr fields are
assigned by the procedures `set-car!' and `set-cdr!'.

   Pairs are used primarily to represent "lists".  A list can be
defined recursively as either the empty list or a pair whose cdr is a
list.  More precisely, the set of lists is defined as the smallest set
X such that

   * The empty list is in X.

   * If LIST is in X, then any pair whose cdr field contains LIST is
     also in X.

   The objects in the car fields of successive pairs of a list are the
"elements" of the list.  For example, a two-element list is a pair
whose car is the first element and whose cdr is a pair whose car is the
second element and whose cdr is the empty list.  The "length" of a list
is the number of elements, which is the same as the number of pairs.
The "empty list" is a special object of its own type (it is not a
pair); it has no elements and its length is zero.(1)

   The most general notation (external representation) for Scheme pairs
is the "dotted" notation `(C1 . C2)' where C1 is the value of the car
field and C2 is the value of the cdr field.  For example, `(4 . 5)' is
a pair whose car is `4' and whose cdr is `5'.  Note that `(4 . 5)' is
the external representation of a pair, not an expression that evaluates
to a pair.

   A more streamlined notation can be used for lists: the elements of
the list are simply enclosed in parentheses and separated by spaces.
The empty list is written `()'.  For example, the following are
equivalent notations for a list of symbols:

     (a b c d e)
     (a . (b . (c . (d . (e . ())))))

   Whether a given pair is a list depends upon what is stored in the cdr
field.  When the `set-cdr!' procedure is used, an object can be a list
one moment and not the next:

     (define x (list 'a 'b 'c))
     (define y x)
     y                                       => (a b c)
     (list? y)                               => #t
     (set-cdr! x 4)                          => unspecified
     x                                       => (a . 4)
     (eqv? x y)                              => #t
     y                                       => (a . 4)
     (list? y)                               => #f
     (set-cdr! x x)                          => unspecified
     (list? y)                               => #f

   A chain of pairs that doesn't end in the empty list is called an
"improper list".  Note that an improper list is not a list.  The list
and dotted notations can be combined to represent improper lists, as
the following equivalent notations show:

     (a b c . d)
     (a . (b . (c . d)))

   Within literal expressions and representations of objects read by the
`read' procedure, the forms `'DATUM', ``DATUM', `,DATUM', and `,@DATUM'
denote two-element lists whose first elements are the symbols `quote',
`quasiquote', `unquote', and `unquote-splicing', respectively.  The
second element in each case is DATUM.  This convention is supported so
that arbitrary Scheme programs may be represented as lists.  Among
other things, this permits the use of the `read' procedure to parse
Scheme programs.

* Menu:

* Pairs::
* Construction of Lists::
* Selecting List Components::
* Cutting and Pasting Lists::
* Filtering Lists::
* Searching Lists::
* Mapping of Lists::
* Reduction of Lists::
* Miscellaneous List Operations::

   ---------- Footnotes ----------

   (1) The above definitions imply that all lists have finite length
and are terminated by the empty list.


File: mit-scheme-ref.info,  Node: Pairs,  Next: Construction of Lists,  Prev: Lists,  Up: Lists

7.1 Pairs
=========

This section describes the simple operations that are available for
constructing and manipulating arbitrary graphs constructed from pairs.

 -- procedure: pair? object
     Returns `#t' if OBJECT is a pair; otherwise returns `#f'.

          (pair? '(a . b))                        => #t
          (pair? '(a b c))                        => #t
          (pair? '())                             => #f
          (pair? '#(a b))                         => #f

 -- procedure: cons obj1 obj2
     Returns a newly allocated pair whose car is OBJ1 and whose cdr is
     OBJ2.  The pair is guaranteed to be different (in the sense of
     `eqv?') from every previously existing object.

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

 -- procedure: xcons obj1 obj2
     (SRFI 1) Returns a newly allocated pair whose car is OBJ2 and
     whose cdr is OBJ1.

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

 -- procedure: car pair
     Returns the contents of the car field of PAIR.  Note that it is an
     error to take the `car' of the empty list.

          (car '(a b c))                          => a
          (car '((a) b c d))                      => (a)
          (car '(1 . 2))                          => 1
          (car '())                               error--> Illegal datum

 -- procedure: cdr pair
     Returns the contents of the cdr field of PAIR.  Note that it is an
     error to take the `cdr' of the empty list.

          (cdr '((a) b c d))                      => (b c d)
          (cdr '(1 . 2))                          => 2
          (cdr '())                               error--> Illegal datum

 -- procedure: car+cdr pair
     (SRFI 1) The fundamental pair deconstructor:

          (lambda (p) (values (car p) (cdr p)))

          (receive (a b) (car+cdr (cons 1 2))
            (write-line a)
            (write-line b))
          -| 1
          -| 2

 -- procedure: set-car! pair object
     Stores OBJECT in the car field of PAIR.  The value returned by
     `set-car!' is unspecified.

          (define (f) (list 'not-a-constant-list))
          (define (g) '(constant-list))
          (set-car! (f) 3)                        => unspecified
          (set-car! (g) 3)                        error--> Illegal datum

 -- procedure: set-cdr! pair object
     Stores OBJECT in the cdr field of PAIR.  The value returned by
     `set-cdr!' is unspecified.

 -- procedure: caar pair
 -- procedure: cadr pair
 -- procedure: cdar pair
 -- procedure: cddr pair
 -- procedure: caaar pair
 -- procedure: caadr pair
 -- procedure: cadar pair
 -- procedure: caddr pair
 -- procedure: cdaar pair
 -- procedure: cdadr pair
 -- procedure: cddar pair
 -- procedure: cdddr pair
 -- procedure: caaaar pair
 -- procedure: caaadr pair
 -- procedure: caadar pair
 -- procedure: caaddr pair
 -- procedure: cadaar pair
 -- procedure: cadadr pair
 -- procedure: caddar pair
 -- procedure: cadddr pair
 -- procedure: cdaaar pair
 -- procedure: cdaadr pair
 -- procedure: cdadar pair
 -- procedure: cdaddr pair
 -- procedure: cddaar pair
 -- procedure: cddadr pair
 -- procedure: cdddar pair
 -- procedure: cddddr pair
     These procedures are compositions of `car' and `cdr'; for example,
     `caddr' could be defined by

          (define caddr (lambda (x) (car (cdr (cdr x)))))

 -- procedure: general-car-cdr object path
     This procedure is a generalization of `car' and `cdr'.  PATH
     encodes a particular sequence of `car' and `cdr' operations, which
     `general-car-cdr' executes on OBJECT.  PATH is an exact
     non-negative integer that encodes the operations in a bitwise
     fashion: a zero bit represents a `cdr' operation, and a one bit
     represents a `car'.  The bits are executed LSB to MSB, and the
     most significant one bit, rather than being interpreted as an
     operation, signals the end of the sequence.(1)

     For example, the following are equivalent:
          (general-car-cdr OBJECT #b1011)
          (cdr (car (car OBJECT)))

     Here is a partial table of path/operation equivalents:

          #b10    cdr
          #b11    car
          #b100   cddr
          #b101   cdar
          #b110   cadr
          #b111   caar
          #b1000  cdddr

 -- procedure: tree-copy tree
     (SRFI 1) This copies an arbitrary TREE constructed from pairs,
     copying both the car and cdr elements of every pair.  This could
     have been defined by

          (define (tree-copy tree)
            (let loop ((tree tree))
              (if (pair? tree)
                  (cons (loop (car tree)) (loop (cdr tree)))
                  tree)))

   ---------- Footnotes ----------

   (1) Note that PATH is restricted to a machine-dependent range,
usually the size of a machine word.  On many machines, this means that
the maximum length of PATH will be 30 operations (32 bits, less the
sign bit and the "end-of-sequence" bit).


File: mit-scheme-ref.info,  Node: Construction of Lists,  Next: Selecting List Components,  Prev: Pairs,  Up: Lists

7.2 Construction of Lists
=========================

 -- procedure: list object ...
     Returns a list of its arguments.

          (list 'a (+ 3 4) 'c)                    => (a 7 c)
          (list)                                  => ()

     These expressions are equivalent:

          (list OBJ1 OBJ2 ... OBJN)
          (cons OBJ1 (cons OBJ2 ... (cons OBJN '()) ...))

 -- procedure: make-list k [element]
     (SRFI 1) This procedure returns a newly allocated list of length
     K, whose elements are all ELEMENT.  If ELEMENT is not supplied, it
     defaults to the empty list.

          (make-list 4 'c)                        => (c c c c)

 -- procedure: cons* object object ...
     (SRFI 1) `cons*' is similar to `list', except that `cons*' conses
     together the last two arguments rather than consing the last
     argument with the empty list.  If the last argument is not a list
     the result is an improper list.  If the last argument is a list,
     the result is a list consisting of the initial arguments and all
     of the items in the final argument.  If there is only one
     argument, the result is the argument.

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

     These expressions are equivalent:

          (cons* OBJ1 OBJ2 ... OBJN-1 OBJN)
          (cons OBJ1 (cons OBJ2 ... (cons OBJN-1 OBJN) ...))

 -- procedure: list-tabulate k init-proc
 -- procedure: make-initialized-list k init-proc
     Returns a K-element list.  Element I of the list, where 0 <= I <
     K, is produced by (INIT-PROC I).  No guarantee is made about the
     dynamic order in which INIT-PROC is applied to these indices.

          (list-tabulate 4 values) => (0 1 2 3)

     `list-tabulate' is defined by SRFI 1.

 -- procedure: list-copy list
     (SRFI 1) Returns a newly allocated copy of LIST.  This copies each
     of the pairs comprising LIST.  This could have been defined by

          (define (list-copy list)
            (if (null? list)
                '()
                (cons (car list)
                      (list-copy (cdr list)))))

 -- procedure: iota count [start [step]]
     (SRFI 1) Returns a list containing the elements

          (START START+STEP ... START+(COUNT-1)*STEP)

     COUNT must be an exact non-negative integer, while START and STEP
     can be any numbers.  The START and STEP parameters default to 0
     and 1, respectively.

          (iota 5) => (0 1 2 3 4)
          (iota 5 0 -0.1) => (0 -0.1 -0.2 -0.3 -0.4)

 -- procedure: vector->list vector
 -- procedure: subvector->list vector start end
     `vector->list' returns a newly allocated list of the elements of
     VECTOR.
     `subvector->list' returns a newly allocated list of the elements
     of the given subvector.  The inverse of `vector->list' is
     `list->vector'.

          (vector->list '#(dah dah didah))        => (dah dah didah)

 -- procedure: string->list string
 -- procedure: substring->list string start end
     `string->list' returns a newly allocated list of the character
     elements of STRING.
     `substring->list' returns a newly allocated list of the character
     elements of the given substring.  The inverse of `string->list' is
     `list->string'.

          (string->list "abcd")                   => (#\a #\b #\c #\d)
          (substring->list "abcdef" 1 3)          => (#\b #\c)


File: mit-scheme-ref.info,  Node: Selecting List Components,  Next: Cutting and Pasting Lists,  Prev: Construction of Lists,  Up: Lists

7.3 Selecting List Components
=============================

 -- procedure: list? object
     Returns `#t' if OBJECT is a list, otherwise returns `#f'.  By
     definition, all lists have finite length and are terminated by the
     empty list.  This procedure returns an answer even for circular
     structures.

     Any OBJECT satisfying this predicate will also satisfy exactly one
     of `pair?' or `null?'.

          (list? '(a b c))                        => #t
          (list? '())                             => #t
          (list? '(a . b))                        => #f
          (let ((x (list 'a)))
            (set-cdr! x x)
            (list? x))                            => #f

 -- procedure: circular-list? object
     (SRFI 1) Returns `#t' if OBJECT is a circular list, otherwise
     returns `#f'.

          (dotted-list? (list 'a 'b 'c))          => #f
          (dotted-list? (cons* 'a 'b 'c))         => #t
          (dotted-list? (circular-list 'a 'b 'c)) => #f

 -- procedure: dotted-list? object
     (SRFI 1) Returns `#t' if OBJECT is an improper list, otherwise
     returns `#f'.

          (circular-list? (list 'a 'b 'c))        => #f
          (circular-list? (cons* 'a 'b 'c))       => #f
          (circular-list? (circular-list 'a 'b 'c)) => #t

 -- procedure: length list
     Returns the length of LIST.  Signals an error if LIST isn't a
     proper list.

          (length '(a b c))                       => 3
          (length '(a (b) (c d e)))               => 3
          (length '())                            => 0
          (length (circular-list 'a 'b 'c))       error-->

 -- procedure: length+ clist
     (SRFI 1) Returns the length of CLIST, if it is a proper list.
     Returns `#f' if CLIST is a circular list.  Otherwise signals an
     error.

          (length+ (list 'a 'b 'c))               => 3
          (length+ (cons* 'a 'b 'c))              error-->
          (length+ (circular-list 'a 'b 'c))      => #f

 -- procedure: null? object
     Returns `#t' if OBJECT is the empty list; otherwise returns `#f'.

          (null? '(a . b))                        => #f
          (null? '(a b c))                        => #f
          (null? '())                             => #t

 -- procedure: list-ref list k
     Returns the Kth element of LIST, using zero-origin indexing.  The
     "valid indexes" of a list are the exact non-negative integers less
     than the length of the list.  The first element of a list has index
     `0', the second has index `1', and so on.

          (list-ref '(a b c d) 2)                 => c
          (list-ref '(a b c d)
                    (inexact->exact (round 1.8)))
               => c

     `(list-ref LIST K)' is equivalent to `(car (list-tail LIST K))'.

 -- procedure: first list
 -- procedure: second list
 -- procedure: third list
 -- procedure: fourth list
 -- procedure: fifth list
 -- procedure: sixth list
 -- procedure: seventh list
 -- procedure: eighth list
 -- procedure: ninth list
 -- procedure: tenth list
     Returns the specified element of LIST.  It is an error if LIST is
     not long enough to contain the specified element (for example, if
     the argument to `seventh' is a list that contains only six
     elements).

