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

This manual documents MIT/GNU Scheme 10.1.8.

   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, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
2019 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 Reference: (mit-scheme-ref).
                                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 10.1.8.

   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, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
2019 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

* Character implementation::
* Unicode::
* Character Sets::

Strings

* Searching and Matching Strings::
* Regular Expressions::

Regular Expressions

* Regular S-Expressions::
* Regsexp Procedures::

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::
* Parameters::
* Records::
* Promises::
* Streams::
* Weak References::

Weak References

* Weak Pairs::
* Ephemerons::
* Reference barriers::

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::

Environments

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

Input/Output

* Ports::
* File Ports::
* String Ports::
* Bytevector Ports::
* Input Procedures::
* Output Procedures::
* Blocking Mode::
* Terminal Mode::
* Format::
* Custom Output::
* Prompting::
* Textual Port Primitives::
* Parser Buffers::
* Parser Language::
* XML Support::

Textual Port Primitives

* Textual Port Types::
* Constructors and Accessors for Textual Ports::
* Textual Input Port Operations::
* Textual Output Port Operations::

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.

Parameter
     TEMPLATE consists of the parameter's name.  See *note Dynamic
     Binding:: and *note Parameters:: for more information.

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: parameterize ((PARAMETER VALUE) ...) expression
          expression ...
     Note that both PARAMETER and VALUE are expressions.  It is an error
     if the value of any PARAMETER expression is not a parameter object.

     A 'parameterize' expression is used to change the values of
     specified parameter objects during the evaluation of the body
     EXPRESSIONs.

     The PARAMETER and VALUE expressions are evaluated in an unspecified
     order.  The body is evaluated in a dynamic environment in which
     each PARAMETER is bound to the converted VALUE--the result of
     passing VALUE to the conversion procedure specified when the
     PARAMETER was created.  Then the previous value of PARAMETER is
     restored without passing it to the conversion procedure.  The value
     of the parameterize expression is the value of the last body
     EXPRESSION.

     The 'parameterize' special form is standardized by SRFI 39
     (http://srfi.schemers.org/srfi-39/srfi-39.html) and by R7RS
     (http://r7rs.org/).

   Parameter objects can be used to specify configurable settings for a
computation without the need to pass the value to every procedure in the
call chain explicitly.

     (define radix
       (make-parameter
        10
        (lambda (x)
          (if (and (exact-integer?  x) (<= 2 x 16))
              x
              (error "invalid radix")))))

     (define (f n) (number->string n (radix)))

     (f 12)                                  => "12"
     (parameterize ((radix 2))
       (f 12))                               => "1100"
     (f 12)                                  => "12"
     (radix 16)                              error-> Wrong number of arguments
     (parameterize ((radix 0))
       (f 12))                               error-> invalid radix

   A "dynamic binding" changes the value of a parameter (*note
Parameters::) object temporarily, for a "dynamic extent".  The set of
all dynamic bindings at a given time is called the "dynamic
environment".  The new values are only accessible to the thread that
constructed the dynamic environment, and any threads created within that
environment.

   The "extent" of a dynamic binding is defined to be the time period
during which calling the parameter returns the new value.  Normally this
time period begins when the body is entered and ends when it is exited,
a contiguous time period.  However Scheme has first-class continuations
by which it is possible to leave the body and reenter it many times.  In
this situation, the extent is non-contiguous.

   When the body is exited by invoking a continuation, the current
dynamic environment is unwound until it can be re-wound to the
environment captured by the continuation.  When the continuation
returns, the process is reversed, restoring the original dynamic
environment.

   The following example shows the interaction between dynamic binding
and continuations.  Side effects to the binding that occur both inside
and outside of the body are preserved, even if continuations are used to
jump in and out of the body repeatedly.

     (define (complicated-dynamic-parameter)
       (let ((variable (make-settable-parameter 1))
             (inside-continuation))
         (write-line (variable))
         (call-with-current-continuation
          (lambda (outside-continuation)
            (parameterize ((variable 2))
              (write-line (variable))
              (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
               (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 inside 'parameterize''s body.
Immediately after they are written, the binding visible in the body is
set to '3', and 'outside-continuation' is invoked, exiting the body.  At
this point, '1' is written, demonstrating that the original binding of
'variable' is still visible outside 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 binding modified in the body
is still the binding visible in the body.  Finally, we exit the body
normally, and write '4', demonstrating that the binding modified outside
of the body was also preserved.

2.3.1 Fluid-Let
---------------

The 'fluid-let' special form can change the value of _any_ variable for
a dynamic extent, but it is difficult to implement in a multi-processing
(SMP) world.  It and the cell object type (*note Cells::) are now
*deprecated*.  They are still available and functional in a
uni-processing (non-SMP) world, but will signal an error when used in an
SMP world.  The 'parameterize' special form (*note parameterize::)
should be used instead.

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


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 a "print method" (*note Custom Output::).

 -- 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 print method for the
     structure instances (which can be overridden by the
     'print-procedure' option).  If the default print 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 print 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 structure instance
     and a textual output port) 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.


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 '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
     -                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 (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 '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)
          (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 (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.

   The procedures 'exact' and 'inexact' implement the natural one-to-one
correspondence between exact and inexact integers throughout an
implementation-dependent range.

 -- procedure: inexact z
 -- procedure: exact->inexact z
     '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.

     The procedure 'exact->inexact' has been deprecated by R7RS
     (http://r7rs.org/).

 -- procedure: inexact z
 -- procedure: exact->inexact z
     '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.

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

     The procedure 'inexact->exact' has been deprecated by R7RS
     (http://r7rs.org/).

   ---------- 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 is *deprecated*; use 'param:flonum-printer-cutoff'
     instead.

 -- parameter: param:flonum-printer-cutoff
     This parameter controls the action of 'number->string' when NUMBER
     is a flonum (and consequently controls all printing of flonums).
     This parameter may be called with an argument to set its value.

     The value of this parameter 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 significand 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 significand 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 'param:flonum-printer-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 'param:flonum-printer-cutoff':

     (number->string (* 4 (atan 1 1)))
                                         => "3.141592653589793"
     (parameterize ((param:flonum-printer-cutoff '(relative 5)))
       (lambda ()
         (number->string (* 4 (atan 1 1)))))
                                         => "3.1416"
     (parameterize ((param:flonum-printer-cutoff '(relative 5)))
       (lambda ()
         (number->string (* 4000 (atan 1 1)))))
                                         => "3141.6"
     (parameterize ((param:flonum-printer-cutoff '(relative 5 scientific)))
       (lambda ()
         (number->string (* 4000 (atan 1 1)))))
                                         => "3.1416e3"
     (parameterize ((param:flonum-printer-cutoff '(relative 5 scientific)))
       (lambda ()
         (number->string (* 40000 (atan 1 1)))))
                                         => "3.1416e4"
     (parameterize ((param:flonum-printer-cutoff '(relative 5 engineering)))
       (lambda ()
         (number->string (* 40000 (atan 1 1)))))
                                         => "31.416e3"
     (parameterize ((param:flonum-printer-cutoff '(absolute 5)))
       (lambda ()
         (number->string (* 4 (atan 1 1)))))
                                         => "3.14159"
     (parameterize ((param:flonum-printer-cutoff '(absolute 5)))
       (lambda ()
         (number->string (* 4000 (atan 1 1)))))
                                         => "3141.59265"
     (parameterize ((param:flonum-printer-cutoff '(absolute -4)))
       (lambda ()
         (number->string (* 4e10 (atan 1 1)))))
                                         => "31415930000."
     (parameterize ((param:flonum-printer-cutoff '(absolute -4 scientific)))
       (lambda ()
         (number->string (* 4e10 (atan 1 1)))))
                                         => "3.141593e10"
     (parameterize ((param:flonum-printer-cutoff '(absolute -4 engineering)))
       (lambda ()
         (number->string (* 4e10 (atan 1 1)))))
                                         => "31.41593e9"
     (parameterize ((param:flonum-printer-cutoff '(absolute -5)))
       (lambda ()
         (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 'default-random-source'.  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 is *deprecated*; pass an explicit state instead.

 -- procedure: make-random-state [state]
     This procedure returns a new random-state object, suitable for use
     as as the STATE argument to 'random'.  If STATE is not given or
     '#f', 'make-random-state' returns a _copy_ of
     'default-random-source'.  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.  MIT/GNU Scheme supports the full Unicode character
repertoire.

* Menu:

* Character implementation::
* Unicode::
* Character Sets::

   Characters are written using the notation '#\CHARACTER' or
'#\CHARACTER-NAME' or '#\xHEX-SCALAR-VALUE'.

   The following standard character names are supported:

     #\alarm                 ; U+0007
     #\backspace             ; U+0008
     #\delete                ; U+007F
     #\escape                ; U+001B
     #\newline               ; the linefeed character, U+000A
     #\null                  ; the null character, U+0000
     #\return                ; the return character, U+000D
     #\space                 ; the preferred way to write a space, U+0020
     #\tab                   ; the tab character, U+0009

   Here are some additional examples:

     #\a                     ; lowercase letter
     #\A                     ; uppercase letter
     #\(                     ; left parenthesis
     #\                      ; the space character

Case is significant in '#\CHARACTER', and in '#\CHARACTER-NAME', but not
in '#\xHEX-SCALAR-VALUE'.  If CHARACTER in '#\CHARACTER' is alphabetic,
then any character immediately following CHARACTER cannot be one that
can appear in an identifier.  This rule resolves the ambiguous case
where, for example, the sequence of characters '#\space' could be taken
to be either a representation of the space character or a representation
of the character '#\s' followed by a representation of the symbol
'pace'.

   Characters written in the '#\' notation are self-evaluating.  That
is, they do not have to be quoted in programs.

   Some of the procedures that operate on characters ignore the
difference between upper case and lower case.  The procedures that
ignore case have '-ci' (for "case insensitive") embedded in their names.

   MIT/GNU Scheme allows a character name to 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

 -- procedure: char->name char
     Returns a string corresponding to the printed representation of
     CHAR.  This is the CHARACTER, CHARACTER-NAME, or
     'xHEX-SCALAR-VALUE' 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"

 -- 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 "SPACE")                    =>  #\space
          (name->char "c-a")                      =>  #\C-a
          (name->char "control-a")                =>  #\C-a

 -- standard procedure: char? object
     Returns '#t' if OBJECT is a character, otherwise returns '#f'.

 -- standard procedure: char=? char1 char2 char3 ...
 -- standard procedure: char<? char1 char2 char3 ...
 -- standard procedure: char>? char1 char2 char3 ...
 -- standard procedure: char<=? char1 char2 char3 ...
 -- standard procedure: char>=? char1 char2 char3 ...
     These procedures return '#t' if the results of passing their
     arguments to 'char->integer' are respectively equal, monotonically
     increasing, monotonically decreasing, monotonically non-decreasing,
     or monotonically non-increasing.

     These predicates are transitive.

 -- char library procedure: char-ci=? char1 char2 char3 ...
 -- char library procedure: char-ci<? char1 char2 char3 ...
 -- char library procedure: char-ci>? char1 char2 char3 ...
 -- char library procedure: char-ci<=? char1 char2 char3 ...
 -- char library procedure: char-ci>=? char1 char2 char3 ...
     These procedures are similar to 'char=?' et cetera, but they treat
     upper case and lower case letters as the same.  For example,
     '(char-ci=? #\A #\a)' returns '#t'.

     Specifically, these procedures behave as if 'char-foldcase' were
     applied to their arguments before they were compared.

 -- char library procedure: char-alphabetic? char
 -- char library procedure: char-numeric? char
 -- char library procedure: char-whitespace? char
 -- char library procedure: char-upper-case? char
 -- char library procedure: char-lower-case? char
     These procedures return '#t' if their arguments are alphabetic,
     numeric, whitespace, upper case, or lower case characters
     respectively, otherwise they return '#f'.

     Specifically, they return '#t' when applied to characters with the
     Unicode properties Alphabetic, Numeric_Decimal, White_Space,
     Uppercase, or Lowercase respectively, and '#f' when applied to any
     other Unicode characters.  Note that many Unicode characters are
     alphabetic but neither upper nor lower case.

 -- procedure: char-alphanumeric? char
     Returns '#t' if CHAR is either alphabetic or numeric, otherwise it
     returns '#f'.

 -- char library procedure: digit-value char
     This procedure returns the numeric value (0 to 9) of its argument
     if it is a numeric digit (that is, if 'char-numeric?' returns
     '#t'), or '#f' on any other character.

          (digit-value #\3) => 3
          (digit-value #\x0664) => 4
          (digit-value #\x0AE6) => 0
          (digit-value #\x0EA6) => #f

 -- standard procedure: char->integer char
 -- standard procedure: integer->char n
     Given a Unicode character, 'char->integer' returns an exact integer
     between '0' and '#xD7FF' or between '#xE000' and '#x10FFFF' which
     is equal to the Unicode scalar value of that character.  Given a
     non-Unicode character, it returns an exact integer greater than
     '#x10FFFF'.

     Given an exact integer that is the value returned by a character
     when 'char->integer' is applied to it, 'integer->char' returns that
     character.

     Implementation note: MIT/GNU Scheme allows any Unicode code point,
     not just scalar values.

     Implementation note: If the argument to 'char->integer' or
     'integer->char' is a constant, the MIT/GNU Scheme 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.

 -- char library procedure: char-upcase char
 -- char library procedure: char-downcase char
 -- char library procedure: char-foldcase char
     The 'char-upcase' procedure, given an argument that is the
     lowercase part of a Unicode casing pair, returns the uppercase
     member of the pair.  Note that language-sensitive casing pairs are
     not used.  If the argument is not the lowercase member of such a
     pair, it is returned.

     The 'char-downcase' procedure, given an argument that is the
     uppercase part of a Unicode casing pair, returns the lowercase
     member of the pair.  Note that language-sensitive casing pairs are
     not used.  If the argument is not the uppercase member of such a
     pair, it is returned.

     The 'char-foldcase' procedure applies the Unicode simple
     case-folding algorithm to its argument and returns the result.
     Note that language-sensitive folding is not used.  See UAX #44
     (http://www.unicode.org/reports/tr44/) (part of the Unicode
     Standard) for details.

     Note that many Unicode lowercase characters do not have uppercase
     equivalents.

 -- procedure: char->digit char [radix]
     If CHAR is a character representing a digit in the given RADIX,
     returns the corresponding integer value.  If RADIX is specified
     (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.  The RADIX argument, if given, must be an exact integer
     between 2 and 36 (inclusive); it defaults to 10.  The DIGIT
     argument must be an exact non-negative integer strictly less than
     RADIX.

          (digit->char 8)                         =>  #\8
          (digit->char 14 16)                     =>  #\E


File: mit-scheme-ref.info,  Node: Character implementation,  Next: Unicode,  Prev: Characters,  Up: Characters

5.1 Character implementation
============================

An MIT/GNU Scheme character consists of a "code" part and a "bucky bits"
part.  The code part is a Unicode code point, while the bucky bits are
an additional set of bits representing shift keys available on some
keyboards.

   There are 4 bucky bits, named "control", "meta", "super", and
"hyper".  On GNU/Linux systems running a graphical desktop, the control
bit corresponds to the <CTRL> key; the meta bit corresponds to the <ALT>
key; and the super bit corresponds to the "windows" key.  On macOS,
these are the <CONTROL>, <OPTION>, and <COMMAND> keys respectively.

   Characters with bucky bits are not used much outside of graphical
user interfaces (e.g.  Edwin).  They cannot be stored in strings or
character sets, and aren't read or written by textual I/O ports.

 -- procedure: make-char code bucky-bits
     Builds a character from CODE and BUCKY-BITS.  The value of CODE
     must be a Unicode code point; the value of BUCKY-BITS must be an
     exact non-negative integer strictly less than '16'.  If '0' is
     specified for BUCKY-BITS, 'make-char' produces an ordinary
     character; otherwise, the appropriate bits are set 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-code char
     Returns the Unicode code point of CHAR.  Note that if CHAR has no
     bucky bits set, then this is the same value returned by
     'char->integer'.

     For example,
          (char-code #\a)                         =>  97
          (char-code #\c-a)                       =>  97

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

 -- constant: char-code-limit
     This constant is the strict upper limit on a character's CODE
     value.  It is '#x110000' unless some future version of Unicode
     increases the range of code points.

 -- constant: char-bits-limit
     This constant is the strict upper limit on a character's BUCKY-BITS
     value.  It is currently '#x10' and unlikely to change in the
     future.

 -- procedure: bitless-char? object
     Returns '#t' if OBJECT is a character with no bucky bits set,
     otherwise it returns '#f' .

 -- procedure: char-predicate char
     Returns a procedure of one argument that returns '#t' if its
     argument is a character 'char=?' to CHAR, otherwise it returns
     '#f'.

 -- procedure: char-ci-predicate char
     Returns a procedure of one argument that returns '#t' if its
     argument is a character 'char-ci=?' to CHAR, otherwise it returns
     '#f'.


File: mit-scheme-ref.info,  Node: Unicode,  Next: Character Sets,  Prev: Character implementation,  Up: Characters

5.2 Unicode
===========

MIT/GNU Scheme implements the full Unicode character repertoire,
defining predicates for Unicode characters and their associated integer
values.  A "Unicode code point" is an exact non-negative integer
strictly less than '#x110000'.  A "Unicode scalar value" is a Unicode
code point that doesn't fall between '#xD800' inclusive and '#xE000'
exclusive; in other words, any Unicode code point except for the
"surrogate" code points.

 -- procedure: unicode-code-point? object
     Returns '#t' if OBJECT is a Unicode code point, otherwise it
     returns '#f'.

 -- procedure: unicode-scalar-value? object
     Returns '#t' if OBJECT is a Unicode scalar value, otherwise it
     returns '#f'.

 -- procedure: unicode-char? object
     Returns '#t' if OBJECT is any "bitless" character corresponding to
     a Unicode code point, except for those with general category
     'other:surrogate' or 'other:not-assigned'.

 -- procedure: char-general-category char
 -- procedure: code-point-general-category code-point
     Returns the Unicode general category of CHAR (or CODE-POINT) as a
     descriptive symbol:

     CategorySymbol
     --------------------------------------
     Lu      'letter:uppercase'
     Ll      'letter:lowercase'
     Lt      'letter:titlecase'
     Lm      'letter:modifier'
     Lo      'letter:other'
     Mn      'mark:nonspacing'
     Mc      'mark:spacing-combining'
     Me      'mark:enclosing'
     Nd      'number:decimal-digit'
     Nl      'number:letter'
     No      'number:other'
     Pc      'punctuation:connector'
     Pd      'punctuation:dash'
     Ps      'punctuation:open'
     Pe      'punctuation:close'
     Pi      'punctuation:initial-quote'
     Pf      'punctuation:final-quote'
     Po      'punctuation:other'
     Sm      'symbol:math'
     Sc      'symbol:currency'
     Sk      'symbol:modifier'
     So      'symbol:other'
     Zs      'separator:space'
     Zl      'separator:line'
     Zp      'separator:paragraph'
     Cc      'other:control'
     Cf      'other:format'
     Cs      'other:surrogate'
     Co      'other:private-use'
     Cn      'other:not-assigned'


File: mit-scheme-ref.info,  Node: Character Sets,  Prev: Unicode,  Up: Characters

5.3 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 "bitless" character.  Alternatively, a character set can be
treated as a set of code points.

 -- procedure: char-set? object
     Returns '#t' if OBJECT is a character set, otherwise it returns
     '#f'.

 -- procedure: char-in-set? char char-set
     Returns '#t' if CHAR is in CHAR-SET, otherwise it returns '#f'.

 -- procedure: code-point-in-set? code-point char-set
     Returns '#t' if CODE-POINT is in CHAR-SET, otherwise it returns
     '#f'.

 -- procedure: char-set-predicate char-set
     Returns a procedure of one argument that returns '#t' if its
     argument is a character in CHAR-SET, otherwise it returns '#f'.

 -- procedure: compute-char-set predicate
     Calls PREDICATE once on each Unicode code point, and returns a
     character set containing exactly the code points for which
     PREDICATE returns a true value.

   The next procedures represent a character set as a "code-point list",
which is a list of "code-point range" elements.  A code-point range is
either a Unicode code point, or a pair '(START . END)' that specifies a
contiguous range of code points.  Both START and END must be exact
nonnegative integers less than or equal to '#x110000', and START must be
less than or equal to END.  The range specifies all of the code points
greater than or equal to START and strictly less than END.

 -- procedure: char-set element ...
 -- procedure: char-set* elements
     Returns a new character set consisting of the characters specified
     by ELEMENTs.  The procedure 'char-set' takes these elements as
     multiple arguments, while 'char-set*' takes them as a single
     list-valued argument; in all other respects these procedures are
     identical.

     An ELEMENT can take several forms, each of which specifies one or
     more characters to include in the resulting character set: a
     (bitless) character includes itself; a string includes all of the
     characters it contains; a character set includes its members; or a
     code-point range includes the corresponding characters.

     In addition, an ELEMENT may be a symbol from the following table,
     which represents the characters as shown:
     Name           Unicode character specification
     --------------------------------------------------------------------------
     'alphabetic'   Alphabetic = True
     'alphanumeric' Alphabetic = True | Numeric_Type = Decimal
     'cased'        Cased = True
     'lower-case'   Lowercase = True
     'numeric'      Numeric_Type = Decimal
     'unicode'      General_Category != (Cs | Cn)
     'upper-case'   Uppercase = True
     'whitespace'   White_Space = True

 -- procedure: char-set->code-points char-set
     Returns a code-point list specifying the contents of CHAR-SET.  The
     returned list consists of numerically sorted, disjoint, and
     non-abutting code-point ranges.

 -- 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 it returns '#f'.

 -- procedure: char-set-invert char-set
     Returns a character set that's the inverse of CHAR-SET.  That is,
     the returned character set contains exactly those characters that
     aren't in CHAR-SET.

 -- procedure: char-set-union char-set ...
 -- procedure: char-set-intersection char-set ...
 -- procedure: char-set-difference char-set-1 char-set ...
     These procedures compute the respective set union, set
     intersection, and set difference of their arguments.

 -- procedure: char-set-union* char-sets
 -- procedure: char-set-intersection* char-sets
     These procedures correspond to 'char-set-union' and
     'char-set-intersection' but take a single argument that's a list of
     character sets rather than multiple character-set arguments.

 -- constant: char-set:alphabetic
 -- constant: char-set:numeric
 -- constant: char-set:whitespace
 -- constant: char-set:upper-case
 -- constant: char-set:lower-case
 -- constant: char-set:alphanumeric
     These constants are the character sets corresponding to
     'char-alphabetic?', 'char-numeric?', 'char-whitespace?',
     'char-upper-case?', 'char-lower-case?', and 'char-alphanumeric?'
     respectively.

 -- procedure: 8-bit-char-set? char-set
     Returns '#t' if CHAR-SET contains only 8-bit code points (i.e..
     ISO 8859-1 characters), otherwise it returns '#f'.


File: mit-scheme-ref.info,  Node: Strings,  Next: Lists,  Prev: Characters,  Up: Top

6 Strings
*********

* Menu:

* Searching and Matching Strings::
* Regular Expressions::

Strings are sequences of characters.  Strings are written as sequences
of characters enclosed within quotation marks ('"').  Within a string
literal, various escape sequences represent characters other than
themselves.  Escape sequences always start with a backslash ('\'):

     '\a' : alarm, U+0007
     '\b' : backspace, U+0008
     '\t' : character tabulation, U+0009
     '\n' : linefeed, U+000A
     '\r' : return, U+000D
     '\"' : double quote, U+0022
     '\\' : backslash, U+005C
     '\|' : vertical line, U+007C
     '\'INTRALINE-WHITESPACE* LINE-ENDING INTRALINE-WHITESPACE*
          : nothing
     '\x'HEX-SCALAR-VALUE';'
          : specified character (note the terminating semi-colon).

   The result is unspecified if any other character in a string occurs
after a backslash.

   Except for a line ending, any character outside of an escape sequence
stands for itself in the string literal.  A line ending which is
preceded by '\'INTRALINE-WHITESPACE expands to nothing (along with any
trailing intraline whitespace), and can be used to indent strings for
improved legibility.  Any other line ending has the same effect as
inserting a '\n' character into the string.

   Examples:

     "The word \"recursion\" has many meanings."
     "Another example:\ntwo lines of text"
     "Here's text \
        containing just one line"
     "\x03B1; is named GREEK SMALL LETTER ALPHA."

   The _length_ of a string is the number of characters that it
contains.  This number is an exact, non-negative integer that is fixed
when the string is created.  The "valid indexes" of a string are the
exact non-negative integers less than the length of the string.  The
first character of a string has index 0, the second has index 1, and so
on.

   Some of the procedures that operate on strings ignore the difference
between upper and lower case.  The names of the versions that ignore
case end with '-ci' (for "case insensitive").

   Implementations may forbid certain characters from appearing in
strings.  However, with the exception of '#\null', ASCII characters must
not be forbidden.  For example, an implementation might support the
entire Unicode repertoire, but only allow characters U+0001 to U+00FF
(the Latin-1 repertoire without '#\null') in strings.

   Implementation note: MIT/GNU Scheme allows any "bitless" character to
be stored in a string.  In effect this means any character with a
Unicode code point, including surrogates.

   It is an error to pass such a forbidden character to 'make-string',
'string', 'string-set!', or 'string-fill!', as part of the list passed
to 'list->string', or as part of the vector passed to 'vector->string',
or in UTF-8 encoded form within a bytevector passed to 'utf8->string'.
It is also an error for a procedure passed to 'string-map' to return a
forbidden character, or for 'read-string' to attempt to read one.

   MIT/GNU Scheme supports both "mutable" and "immutable" strings.
Procedures that mutate strings, in particular 'string-set!' and
'string-fill!', will signal an error if given an immutable string.
Nearly all procedures that return strings return immutable strings;
notable exceptions are 'make-string' and 'string-copy', which always
return mutable strings, and 'string-builder' which gives the programmer
the ability to choose mutable or immutable results.

 -- standard procedure: string? obj
     Returns '#t' if OBJ is a string, otherwise returns '#f'.

 -- standard procedure: make-string k [char]
     The 'make-string' procedure returns a newly allocated mutable
     string of length K.  If CHAR is given, then all the characters of
     the string are initialized to CHAR, otherwise the contents of the
     string are unspecified.

 -- extended standard procedure: string object ...
 -- procedure: string* objects
     Returns an immutable string whose characters are the concatenation
     of the characters from the given objects.  Each object is converted
     to characters as if passed to the 'display' procedure.

     This is an MIT/GNU Scheme extension to the standard 'string' that
     accepts only characters as arguments.

     The procedure 'string*' is identical to 'string' but takes a single
     argument that's a list of objects, rather than multiple object
     arguments.

 -- standard procedure: string-length string
     Returns the number of characters in the given STRING.

 -- standard procedure: string-ref string k
     It is an error if K is not a valid index of STRING.

     The 'string-ref' procedure returns character K of STRING using
     zero-origin indexing.  There is no requirement for this procedure
     to execute in constant time.

 -- standard procedure: string-set! string k char
     It is an error if 'string' is not a mutable string or if K is not a
     valid index of STRING.

     The 'string-set!' procedure stores CHAR in element K of STRING.
     There is no requirement for this procedure to execute in constant
     time.

          (define (f) (make-string 3 #\*))
          (define (g) "***")
          (string-set! (f) 0 #\?)  =>  unspecified
          (string-set! (g) 0 #\?)  =>  error
          (string-set! (symbol->string 'immutable) 0 #\?)  =>  error

 -- standard procedure: string=? string1 string2 string ...
     Returns '#t' if all the strings are the same length and contain
     exactly the same characters in the same positions, otherwise
     returns '#f'.

 -- char library procedure: string-ci=? string1 string2 string ...
     Returns '#t' if, after case-folding, all the strings are the same
     length and contain the same characters in the same positions,
     otherwise returns '#f'.  Specifically, these procedures behave as
     if 'string-foldcase' were applied to their arguments before
     comparing them.

 -- standard procedure: string<? string1 string2 string ...
 -- char library procedure: string-ci<? string1 string2 string ...
 -- standard procedure: string>? string1 string2 string ...
 -- char library procedure: string-ci>? string1 string2 string ...
 -- standard procedure: string<=? string1 string2 string ...
 -- char library procedure: string-ci<=? string1 string2 string ...
 -- standard procedure: string>=? string1 string2 string ...
 -- char library procedure: string-ci>=? string1 string2 string ...
     These procedures return '#t' if their arguments are (respectively):
     monotonically increasing, monotonically decreasing, monotonically
     non-decreasing, or monotonically non-increasing.

     These predicates are required to be transitive.

     These procedures compare strings in an implementation-defined way.
     One approach is to make them the lexicographic extensions to
     strings of the corresponding orderings on characters.  In that
     case, 'string<?' would be the lexicographic ordering on strings
     induced by the ordering 'char<?' on characters, and if the two
     strings differ in length but are the same up to the length of the
     shorter string, the shorter string would be considered to be
     lexicographically less than the longer string.  However, it is also
     permitted to use the natural ordering imposed by the
     implementation's internal representation of strings, or a more
     complex locale-specific ordering.

     In all cases, a pair of strings must satisfy exactly one of
     'string<?', 'string=?', and 'string>?', and must satisfy
     'string<=?' if and only if they do not satisfy 'string>?' and
     'string>=?' if and only if they do not satisfy 'string<?'.

     The '-ci' procedures behave as if they applied 'string-foldcase' to
     their arguments before invoking the corresponding procedures
     without '-ci'.

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

 -- char library procedure: string-upcase string
 -- char library procedure: string-downcase string
 -- procedure: string-titlecase string
 -- char library procedure: string-foldcase string
     These procedures apply the Unicode full string uppercasing,
     lowercasing, titlecasing, and case-folding algorithms to their
     arguments and return the result.  In certain cases, the result
     differs in length from the argument.  If the result is equal to the
     argument in the sense of 'string=?', the argument may be returned.
     Note that language-sensitive mappings and foldings are not used.

     The Unicode Standard prescribes special treatment of the Greek
     letter \Sigma, whose normal lower-case form is \sigma but which
     becomes \varsigma at the end of a word.  See UAX #44
     (http://www.unicode.org/reports/tr44/) (part of the Unicode
     Standard) for details.  However, implementations of
     'string-downcase' are not required to provide this behavior, and
     may choose to change \Sigma to \sigma in all cases.

 -- procedure: string-upper-case? string
 -- procedure: string-lower-case? string
     These procedures return '#t' if all the letters in the string are
     lower case or upper case, otherwise they return '#f'.  The string
     must contain at least one letter or the procedures return '#f'.

          (map string-upper-case? '(""    "A"    "art"  "Art"  "ART"))
                                 => (#f    #t     #f     #f     #t)

 -- standard procedure: substring string [start [end]]
     Returns an immutable copy of the part of the given STRING between
     START and END.

 -- procedure: string-slice string [start [end]]
     Returns a "slice" of STRING, restricted to the range of characters
     specified by START and END.  The returned slice will be mutable if
     'string' is mutable, or immutable if 'string' is immutable.

     A slice is a kind of string that provides a view into another
     string.  The slice behaves like any other string, but changes to a
     mutable slice are reflected in the original string and vice versa.

          (define foo (string-copy "abcde"))
          foo => "abcde"

          (define bar (string-slice foo 1 4))
          bar => "bcd"

          (string-set! foo 2 #\z)
          foo => "abzde"
          bar => "bzd"

          (string-set! bar 1 #\y)
          bar => "byd"
          foo => "abyde"

 -- standard procedure: string-append string ...
 -- procedure: string-append* strings
     Returns an immutable string whose characters are the concatenation
     of the characters in the given strings.

     The non-standard procedure 'string-append*' is identical to
     'string-append' but takes a single argument that's a list of
     strings, rather than multiple string arguments.

 -- standard procedure: string->list string [start [end]]
 -- standard procedure: list->string list
     It is an error if any element of LIST is not a character.

     The 'string->list' procedure returns a newly allocated list of the
     characters of STRING between START and END.  'list->string' returns
     an immutable string formed from the elements in the list LIST.  In
     both procedures, order is preserved.  'string->list' and
     'list->string' are inverses so far as 'equal?' is concerned.

 -- standard procedure: string-copy string [start [end]]
     Returns a newly allocated mutable copy of the part of the given
     STRING between START and END.

 -- standard procedure: string-copy! to at from [start [end]]
     It is an error if TO is not a mutable string or if AT is less than
     zero or greater than the length of TO.  It is also an error if '(-
     (string-length TO) AT)' is less than '(- END START)'.

     Copies the characters of string FROM between START and END to
     string TO, starting at AT.  The order in which characters are
     copied is unspecified, except that if the source and destination
     overlap, copying takes place as if the source is first copied into
     a temporary string and then into the destination.  This can be
     achieved without allocating storage by making sure to copy in the
     correct direction in such circumstances.

          (define a "12345")
          (define b (string-copy "abcde"))
          (string-copy! b 1 a 0 2) => 3
          b => "a12de"%

     Implementation note: in MIT/GNU Scheme 'string-copy!' returns the
     value '(+ AT (- END START))'.

 -- standard procedure: string-fill! string fill [start [end]]
     It is an error if STRING is not a mutable string or if FILL is not
     a character.

     The 'string-fill!' procedure stores FILL in the elements of STRING
     between START and END.

   The next two procedures treat a given string as a sequence of
"grapheme clusters", a concept defined by the Unicode standard in UAX
#29 (http://www.unicode.org/reports/tr29/tr29-29.html):

     It is important to recognize that what the user thinks of as a
     "character"--a basic unit of a writing system for a language--may
     not be just a single Unicode code point.  Instead, that basic unit
     may be made up of multiple Unicode code points.  To avoid ambiguity
     with the computer use of the term character, this is called a
     user-perceived character.  For example, “G” + acute-accent is a
     user-perceived character: users think of it as a single character,
     yet is actually represented by two Unicode code points.  These
     user-perceived characters are approximated by what is called a
     grapheme cluster, which can be determined programmatically.

 -- procedure: grapheme-cluster-length string
     This procedure returns the number of grapheme clusters in STRING.

     For ASCII strings, this is identical to 'string-length'.

 -- procedure: grapheme-cluster-slice string start end
     This procedure slices STRING at the grapheme-cluster boundaries
     specified by the START and END indices.  These indices are
     grapheme-cluster indices, _not_ normal string indices.

     For ASCII strings, this is identical to 'string-slice'.

 -- procedure: string-word-breaks string
     This procedure returns a list of "word break" indices for STRING,
     ordered from smallest index to largest.  Word breaks are defined by
     the Unicode standard in UAX #29
     (http://www.unicode.org/reports/tr29/tr29-29.html), and generally
     coincide with what we think of as the boundaries of words in
     written text.

   MIT/GNU Scheme supports the Unicode canonical normalization forms NFC
("Normalization Form C") and NFD ("Normalization Form D"). The reason
for these forms is that there can be multiple different Unicode
sequences for a given text; these sequences are semantically identical
and should be treated equivalently for all purposes.  If two such
sequences are normalized to the same form, the resulting normalized
sequences will be identical.

   By default, most procedures that return strings return them in NFC.
Notable exceptions are 'list->string', 'vector->string', and the
'utfX->string' procedures, which do no normalization, and of course
'string->nfd'.

   Generally speaking, NFC is preferred for most purposes, as it is the
minimal-length sequence for the variants.  Consult the Unicode standard
for the details and for information about why one normalization form is
preferable for a specific purpose.

 -- procedure: string-in-nfc? string
 -- procedure: string-in-nfd? string
     These procedures return '#t' if STRING is in Unicode Normalization
     Form C or D respectively.  Otherwise they return '#f'.

     Note that if STRING consists only of code points strictly less than
     '#xC0', then 'string-in-nfd?' returns '#t'.  If STRING consists
     only of code points strictly less than '#x300', then
     'string-in-nfc?' returns '#t'.  Consequently both of these
     procedures will return '#t' for an ASCII string argument.

 -- procedure: string->nfc string
 -- procedure: string->nfd string
     The procedures convert STRING into Unicode Normalization Form C or
     D respectively.  If STRING is already in the correct form, they
     return STRING itself, or an immutable copy if STRING is mutable.

 -- standard procedure: string-map proc string string ...
     It is an error if PROC does not accept as many arguments as there
     are STRINGs and return a single character.

     The 'string-map' procedure applies PROC element-wise to the
     elements of the STRINGs and returns an immutable string of the
     results, in order.  If more than one STRING is given and not all
     strings have the same length, 'string-map' terminates when the
     shortest string runs out.  The dynamic order in which PROC is
     applied to the elements of the STRINGs is unspecified.  If multiple
     returns occur from 'string-map', the values returned by earlier
     returns are not mutated.

          (string-map char-foldcase "AbdEgH")  =>  "abdegh"

          (string-map
           (lambda (c)
             (integer->char (+ 1 (char->integer c))))
           "HAL")                 =>  "IBM"

          (string-map
           (lambda (c k)
             ((if (eqv? k #\u) char-upcase char-downcase) c))
           "studlycaps xxx"
           "ululululul")          =>  "StUdLyCaPs"

 -- standard procedure: string-for-each proc string string ...
     It is an error if PROC does not accept as many arguments as there
     are STRINGs.

     The arguments to 'string-for-each' are like the arguments to
     'string-map', but 'string-for-each' calls PROC for its side effects
     rather than for its values.  Unlike 'string-map', 'string-for-each'
     is guaranteed to call PROC on the elements of the LISTs in order
     from the first element(s) to the last, and the value returned by
     'string-for-each' is unspecified.  If more than one STRING is given
     and not all strings have the same length, 'string-for-each'
     terminates when the shortest string runs out.  It is an error for
     PROC to mutate any of the strings.

          (let ((v '()))
            (string-for-each
             (lambda (c) (set! v (cons (char->integer c) v)))
             "abcde")
            v)                    =>  (101 100 99 98 97)

 -- procedure: string-count proc string string ...
     It is an error if PROC does not accept as many arguments as there
     are STRINGs.

     The 'string-count' procedure applies PROC element-wise to the
     elements of the STRINGs and returns a count of the number of true
     values it returns.  If more than one STRING is given and not all
     strings have the same length, 'string-count' terminates when the
     shortest string runs out.  The dynamic order in which PROC is
     applied to the elements of the STRINGs is unspecified.

 -- procedure: string-any proc string string ...
     It is an error if PROC does not accept as many arguments as there
     are STRINGs.

     The 'string-any' procedure applies PROC element-wise to the
     elements of the STRINGs and returns '#t' if it returns a true
     value.  If PROC doesn't return a true value, 'string-any' returns
     '#f'.

     If more than one STRING is given and not all strings have the same
     length, 'string-any' terminates when the shortest string runs out.
     The dynamic order in which PROC is applied to the elements of the
     STRINGs is unspecified.

 -- procedure: string-every proc string string ...
     It is an error if PROC does not accept as many arguments as there
     are STRINGs.

     The 'string-every' procedure applies PROC element-wise to the
     elements of the STRINGs and returns '#f' if it returns a false
     value.  If PROC doesn't return a false value, 'string-every'
     returns '#t'.

     If more than one STRING is given and not all strings have the same
     length, 'string-every' terminates when the shortest string runs
     out.  The dynamic order in which PROC is applied to the elements of
     the STRINGs is unspecified.

 -- procedure: string-null? string
     Returns '#t' if STRING has zero length; otherwise returns '#f'.

          (string-null? "")       =>  #t
          (string-null? "Hi")     =>  #f

 -- procedure: string-hash string [modulus]
 -- procedure: string-hash-ci string [modulus]
     These procedures return 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=?' and 'string-ci=?' respectively)
     return equal ('=') hash codes, and non-equal but similar strings
     are usually mapped to distinct hash codes.

     If the optional argument MODULUS is specified, it must be an exact
     positive integer, and the result of the hash computation is
     restricted to be less than that value.  This is equivalent to
     calling 'modulo' on the result, but may be faster.

 -- procedure: string-head string end
     Equivalent to '(substring STRING 0 END)'.

 -- procedure: string-tail string start
     Equivalent to '(substring STRING START)'.

 -- procedure: string-builder [buffer-length]
     This procedure returns a "string builder" that can be used to
     incrementally collect characters and later convert that collection
     to a string.  This is similar to a string output port, but is less
     general and significantly faster.

     The optional BUFFER-LENGTH argument, if given, must be an exact
     positive integer.  It controls the size of the internal buffers
     that are used to accumulate characters.  Larger values make the
     builder somewhat faster but use more space.  The default value of
     this argument is '16'.

     The returned string builder is a procedure that accepts zero or one
     arguments as follows:

        * Given a bitless character argument, the string builder appends
          that character to the string being built and returns an
          unspecified value.
        * Given a string argument, the string builder appends that
          string to the string being built and returns an unspecified
          value.
        * Given no arguments, or one of the "result" arguments (see
          below), the string builder returns a copy of the string being
          built.  Note that this does not affect the string being built,
          so immediately calling the builder with no arguments a second
          time returns a new copy of the same string.
        * Given the argument 'empty?', the string builder returns '#t'
          if the string being built is empty and '#f' otherwise.
        * Given the argument 'count', the string builder returns the
          size of the string being built.
        * Given the argument 'reset!', the string builder discards the
          string being built and returns to the state it was in when
          initially created.

     The "result" arguments control the form of the returned string.
     The arguments 'immutable' and 'mutable' are straightforward,
     specifying the mutability of the returned string.  For these
     arguments, the returned string contains exactly the same
     characters, in the same order, as were appended to the builder.

     However, calling with the argument 'nfc', or with no arguments,
     returns an immutable string in Unicode Normalization Form C,
     exactly as if 'string->nfc' were called on one of the other two
     result strings.

 -- procedure: string-joiner infix prefix suffix
 -- procedure: string-joiner* infix prefix suffix
     This procedure's arguments are keyword arguments; that is, each
     argument is a symbol of the same name followed by its value.  The
     order of the arguments doesn't matter, but each argument may appear
     only once.

     These procedures return a "joiner" procedure that takes multiple
     strings and joins them together into an immutable string.  The
     joiner returned by 'string-joiner' accepts these strings as
     multiple string arguments, while 'string-joiner*' accepts the
     strings as a single list-valued argument.

     The joiner produces a result by adding PREFIX before, SUFFIX after,
     and INFIX between each input string, then concatenating everything
     together into a single string.  Each of the PREFIX, SUFFIX, and
     INFIX arguments is optional and defaults to an empty string, so
     normally at least one is specified.

     Some examples:
          ((string-joiner) "a" "b" "c")
            =>  "abc"

          ((string-joiner 'infix " ") "a" "b" "c")
            =>  "a b c"

          ((string-joiner 'infix ", ") "a" "b" "c")
            =>  "a, b, c"

          ((string-joiner* 'infix ", " 'prefix "<" 'suffix ">")
           '("a" "b" "c"))
            =>  "<a>, <b>, <c>"

 -- procedure: string-splitter delimiter allow-runs? copy?
     This procedure's arguments are keyword arguments; that is, each
     argument is a symbol of the same name followed by its value.  The
     order of the arguments doesn't matter, but each argument may appear
     only once.

     This procedure returns a "splitter" procedure that splits a given
     string into parts, returning a list of the parts.  This is done by
     identifying delimiter characters and breaking the string at those
     delimiters.  The splitting process is controlled by the arguments:

        * DELIMITER is either a character, a character set, or more
          generally a procedure that accepts a single character argument
          and returns a boolean value.  The splitter uses this to
          identify delimiters in the string.  The default value of this
          argument is 'char-whitespace?'.
        * ALLOW-RUNS? is a boolean that controls what happens when two
          or more adjacent delimiters are found.  If ALLOW-RUNS? is
          '#t', then all of the adjacent delimiters are treated as if
          they were a single delimiter, and the string is split at the
          beginning and end of the delimiters.  If ALLOW-RUNS? is '#f',
          then adjacent delimiters are treated as if they were separate
          with an empty string between them.  The default value of this
          argument is '#t'.
        * 'copy?' is a boolean: if it is '#t', then the returned strings
          are immutable copies, but if it is '#f' the returned strings
          are slices of the original string.  The default value of this
          argument is '#f'.

     Some examples:
          ((string-splitter) "a b c")
            =>  ("a" "b" "c")

          ((string-splitter) "a\tb\tc")
            =>  ("a" "b" "c")

          ((string-splitter 'delimiter #\space) "a\tb\tc")
            =>  ("a\tb\tc")

          ((string-splitter) " a  b  c ")
            =>  ("a" "b" "c")

          ((string-splitter 'allow-runs? #f) " a  b  c ")
            =>  ("" "a" "" "b" "" "c" "")

 -- procedure: string-padder where fill-with clip?
     This procedure's arguments are keyword arguments; that is, each
     argument is a symbol of the same name followed by its value.  The
     order of the arguments doesn't matter, but each argument may appear
     only once.

     This procedure returns a "padder" procedure that takes a string and
     a grapheme-cluster length as its arguments and returns a new string
     that has been padded to that length.  The padder adds grapheme
     clusters to the string until it has the specified length.  If the
     string's grapheme-cluster length is greater than the given length,
     the string may, depending on the arguments, be reduced to the
     specified length.

     The padding process is controlled by the arguments:

        * WHERE is a symbol: either 'leading' or 'trailing', which
          directs the padder to add/remove leading or trailing grapheme
          clusters.  The default value of this argument is 'leading'.
        * FILL-WITH is a string that contains exactly one grapheme
          cluster, which is used as the padding to increase the size of
          the string.  The default value of this argument is '" "' (a
          single space character).
        * CLIP? is a boolean that controls what happens if the given
          string has a longer grapheme-cluster length than the given
          length.  If 'clip?' is '#t', grapheme clusters are removed (by
          slicing) from the string until it is the correct length; if it
          is '#f' then the string is returned unchanged.  The grapheme
          clusters are removed from the beginning of the string if
          'where' is 'leading', otherwise from the end of the string.
          The default value of this argument is '#t'.

     Some examples:
          ((string-padder) "abc def" 10)
            =>  "   abc def"

          ((string-padder 'where 'trailing) "abc def" 10)
            =>  "abc def   "

          ((string-padder 'fill-with "X") "abc def" 10)
            =>  "XXXabc def"

          ((string-padder) "abc def" 5)
            =>  "c def"

          ((string-padder 'where 'trailing) "abc def" 5)
            =>  "abc d"

          ((string-padder 'clip? #f) "abc def" 5)
            =>  "abc def"

 -- obsolete procedure: string-pad-left string k [char]
 -- obsolete procedure: string-pad-right string k [char]
     These procedures are *deprecated* and should be replaced by use of
     'string-padder' which is more flexible.

     These procedures return an immutable 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-trimmer where to-trim copy?
     This procedure's arguments are keyword arguments; that is, each
     argument is a symbol of the same name followed by its value.  The
     order of the arguments doesn't matter, but each argument may appear
     only once.

     This procedure returns a "trimmer" procedure that takes a string as
     its argument and trims that string, returning the trimmed result.
     The trimming process is controlled by the arguments:

        * WHERE is a symbol: either 'leading', 'trailing', or 'both',
          which directs the trimmer to trim leading characters, trailing
          characters, or both.  The default value of this argument is
          'both'.
        * TO-TRIM is either a character, a character set, or more
          generally a procedure that accepts a single character argument
          and returns a boolean value.  The trimmer uses this to
          identify characters to remove.  The default value of this
          argument is 'char-whitespace?'.
        * COPY? is a boolean: if '#t', the trimmer returns an immutable
          copy of the trimmed string, if '#f' it returns a slice.  The
          default value of this argument is '#f'.

     Some examples:
          ((string-trimmer 'where 'leading) "    ABC   DEF    ")
            =>  "ABC   DEF    "

          ((string-trimmer 'where 'trailing) "    ABC   DEF    ")
            =>  "    ABC   DEF"

          ((string-trimmer 'where 'both) "    ABC   DEF    ")
            =>  "ABC   DEF"

          ((string-trimmer) "    ABC   DEF    ")
            =>  "ABC   DEF"

          ((string-trimmer 'to-trim char-numeric? 'where 'leading)
           "21 East 21st Street #3")
            =>  " East 21st Street #3"

          ((string-trimmer 'to-trim char-numeric? 'where 'trailing)
           "21 East 21st Street #3")
            =>  "21 East 21st Street #"

          ((string-trimmer 'to-trim char-numeric?)
           "21 East 21st Street #3")
            =>  " East 21st Street #"

 -- obsolete procedure: string-trim string [char-set]
 -- obsolete procedure: string-trim-left string [char-set]
 -- obsolete procedure: string-trim-right string [char-set]
     These procedures are *deprecated* and should be replaced by use of
     'string-trimmer' which is more flexible.

     Returns an immutable 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)"

 -- procedure: string-replace string char1 char2
     Returns an immutable string containing the same characters as
     STRING except that all instances of CHAR1 have been replaced by
     CHAR2.


File: mit-scheme-ref.info,  Node: Searching and Matching Strings,  Next: Regular Expressions,  Prev: Strings,  Up: Strings

6.1 Searching and Matching Strings
==================================

This section describes procedures for searching a string, either for a
character or a substring, and matching two strings to one another.

 -- procedure: string-search-forward pattern string [start [end]]
     The arguments PATTERN and STRING must satisfy 'string-in-nfc?'.

     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.

          (string-search-forward "rat" "pirate")
              => 2
          (string-search-forward "rat" "pirate rating")
              => 2
          (string-search-forward "rat" "pirate rating" 4 13)
              => 7
          (string-search-forward "rat" "pirate rating" 9 13)
              => #f

 -- procedure: string-search-backward pattern string [start [end]]
     The arguments PATTERN and STRING must satisfy 'string-in-nfc?'.

     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.

          (string-search-backward "rat" "pirate")
              => 5
          (string-search-backward "rat" "pirate rating")
              => 10
          (string-search-backward "rat" "pirate rating" 1 8)
              => 5
          (string-search-backward "rat" "pirate rating" 9 13)
              => #f

 -- procedure: string-search-all pattern string [start [end]]
     The arguments PATTERN and STRING must satisfy 'string-in-nfc?'.

     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.

          (string-search-all "rat" "pirate")
              => (2)
          (string-search-all "rat" "pirate rating")
              => (2 7)
          (string-search-all "rat" "pirate rating" 4 13)
              => (7)
          (string-search-all "rat" "pirate rating" 9 13)
              => ()

 -- procedure: substring? pattern 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-first-index proc string string ...
 -- procedure: string-find-last-index proc string string ...
     Each STRING must satisfy 'string-in-nfc?', and PROC must accept as
     many arguments as there are STRINGs.

     These procedures apply PROC element-wise to the elements of the
     STRINGs and return the first or last index for which PROC returns a
     true value.  If there is no such index, then '#f' is returned.

     If more than one STRING is given and not all strings have the same
     length, then only the indexes of the shortest string are tested.

 -- procedure: string-find-next-char string char [start [end]]
 -- procedure: string-find-next-char-ci string char [start [end]]
 -- procedure: string-find-next-char-in-set string char-set [start
          [end]]
     The argument STRING must satisfy 'string-in-nfc?'.

     These procedures search STRING for a matching character, starting
     from START and moving forwards to END.  If there is a matching
     character, the procedures stop the search and return the index of
     that character.  If there is no matching character, the procedures
     return '#f'.

     The procedures differ only in how they match characters:
     'string-find-next-char' matches a character that is 'char=?' to
     CHAR; 'string-find-next-char-ci' matches a character that is
     'char-ci=?' to CHAR; and 'string-find-next-char-in-set' matches a
     character that's a member of CHAR-SET.

          (string-find-next-char "Adam" #\A)           =>  0
          (string-find-next-char "Adam" #\A 1 4)       =>  #f
          (string-find-next-char-ci "Adam" #\A 1 4)    =>  2
          (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 [start [end]]
 -- procedure: string-find-previous-char-ci string char [start [end]]
 -- procedure: string-find-previous-char-in-set string char-set [start
          [end]]
     The argument STRING must satisfy 'string-in-nfc?'.

     These procedures search STRING for a matching character, starting
     from END and moving backwards to START.  If there is a matching
     character, the procedures stop the search and return the index of
     that character.  If there is no matching character, the procedures
     return '#f'.

     The procedures differ only in how they match characters:
     'string-find-previous-char' matches a character that is 'char=?' to
     CHAR; 'string-find-previous-char-ci' matches a character that is
     'char-ci=?' to CHAR; and 'string-find-previous-char-in-set' matches
     a character that's a member of CHAR-SET.

 -- procedure: string-match-forward string1 string2
     The arguments STRING1 and STRING2 must satisfy 'string-in-nfc?'.

     Compares the two strings, starting from the beginning, and returns
     the number of characters that are the same.  If the two strings
     start differently, returns 0.

          (string-match-forward "mirror" "micro") =>  2  ; matches "mi"
          (string-match-forward "a" "b")          =>  0  ; no match

 -- procedure: string-match-backward string1 string2
     The arguments STRING1 and STRING2 must satisfy 'string-in-nfc?'.

     Compares the two strings, starting from the end and matching toward
     the front, returning the number of characters that are the same.
     If the two strings end differently, returns 0.

          (string-match-backward "bulbous" "fractious")
                                                  =>  3  ; matches "ous"

 -- procedure: string-prefix? string1 string2
 -- procedure: string-prefix-ci? string1 string2
     These procedures return '#t' if the first string 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: string-suffix-ci? string1 string2
     These procedures return '#t' if the first string 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,  Prev: Searching and Matching Strings,  Up: Strings

6.2 Regular Expressions
=======================

MIT/GNU Scheme provides support for matching and searching strings
against regular expressions.  This is considerably more flexible than
ordinary string matching and searching, but potentially much slower.  On
the other hand it is less powerful than the mechanism described in *note
Parser Language::.

   Traditional regular expressions are defined with string patterns in
which characters like '[' and '*' have special meanings.  Unfortunately,
the syntax of these patterns is not only baroque but also comes in many
different and mutually-incompatible varieties.  As a consequence we have
chosen to specify regular expressions using an s-expression syntax,
which we call a "regular s-expression", abbreviated as "regsexp".

   Previous releases of MIT/GNU Scheme provided a regular-expression
implementation nearly identical to that of GNU Emacs version 18.  This
implementation supported only 8-bit strings, which made it unsuitable
for use with Unicode strings.  This implementation still exists but is
deprecated and will be removed in a future release.

* Menu:

* Regular S-Expressions::
* Regsexp Procedures::


File: mit-scheme-ref.info,  Node: Regular S-Expressions,  Next: Regsexp Procedures,  Prev: Regular Expressions,  Up: Regular Expressions

6.2.1 Regular S-Expressions
---------------------------

A regular s-expression is either a character or a string, which matches
itself, or one of the following forms.

   Examples in this section use the following definitions for brevity:

     (define (try-match pattern string)
       (regsexp-match-string (compile-regsexp pattern) string))

     (define (try-search pattern string)
       (regsexp-search-string-forward (compile-regsexp pattern) string))

   These forms match one or more characters literally:

 -- regsexp: char-ci char
     Matches CHAR without considering case.

 -- regsexp: string-ci string
     Matches STRING without considering case.

 -- regsexp: any-char
     Matches one character other than '#\newline'.

          (try-match '(any-char) "") => #f
          (try-match '(any-char) "a") => (0 1)
          (try-match '(any-char) "\n") => #f
          (try-search '(any-char) "") => #f
          (try-search '(any-char) "ab") => (0 1)
          (try-search '(any-char) "\na") => (1 2)

 -- regsexp: char-in datum ...
 -- regsexp: char-not-in datum ...
     Matches one character in (not in) the character set specified by
     '(char-set DATUM ...)'.

          (try-match '(seq "a" (char-in "ab") "c") "abc") => (0 3)
          (try-match '(seq "a" (char-not-in "ab") "c") "abc") => #f
          (try-match '(seq "a" (char-not-in "ab") "c") "adc") => (0 3)
          (try-match '(seq "a" (+ (char-in numeric)) "c") "a019c") => (0 5)

   These forms match no characters, but only at specific locations in
the input string:

 -- regsexp: line-start
 -- regsexp: line-end
     Matches no characters at the start (end) of a line.

          (try-match '(seq (line-start)
                           (* (any-char))
                           (line-end))
                     "abc") => (0 3)
          (try-match '(seq (line-start)
                           (* (any-char))
                           (line-end))
                     "ab\nc") => (0 2)
          (try-search '(seq (line-start)
                            (* (char-in alphabetic))
                            (line-end))
                      "1abc") => #f
          (try-search '(seq (line-start)
                            (* (char-in alphabetic))
                            (line-end))
                      "1\nabc") => (2 5)

 -- regsexp: string-start
 -- regsexp: string-end
     Matches no characters at the start (end) of the string.

          (try-match '(seq (string-start)
                           (* (any-char))
                           (string-end))
                     "abc") => (0 3)
          (try-match '(seq (string-start)
                           (* (any-char))
                           (string-end))
                     "ab\nc") => #f
          (try-search '(seq (string-start)
                            (* (char-in alphabetic))
                            (string-end))
                      "1abc") => #f
          (try-search '(seq (string-start)
                            (* (char-in alphabetic))
                            (string-end))
                      "1\nabc") => #f

   These forms match repetitions of a given regsexp.  Most of them come
in two forms, one of which is "greedy" and the other "shy".  The greedy
form matches as many repetitions as it can, then uses failure
backtracking to reduce the number of repetitions one at a time.  The shy
form matches the minimum number of repetitions, then uses failure
backtracking to increase the number of repetitions one at a time.  The
shy form is similar to the greedy form except that a '?' is added at the
end of the form's keyword.

 -- regsexp: ? regsexp
 -- regsexp: ?? regsexp
     Matches REGSEXP zero or one time.

          (try-search '(seq (char-in alphabetic)
                            (? (char-in numeric)))
                      "a") => (0 1)
          (try-search '(seq (char-in alphabetic)
                            (?? (char-in numeric)))
                      "a") => (0 1)
          (try-search '(seq (char-in alphabetic)
                            (? (char-in numeric)))
                      "a1") => (0 2)
          (try-search '(seq (char-in alphabetic)
                            (?? (char-in numeric)))
                      "a1") => (0 1)
          (try-search '(seq (char-in alphabetic)
                            (? (char-in numeric)))
                      "1a2") => (1 3)
          (try-search '(seq (char-in alphabetic)
                            (?? (char-in numeric)))
                      "1a2") => (1 2)

 -- regsexp: * regsexp
 -- regsexp: *? regsexp
     Matches REGSEXP zero or more times.

          (try-match '(seq (char-in alphabetic)
                           (* (char-in numeric))
                           (any-char))
                     "aa") => (0 2)
          (try-match '(seq (char-in alphabetic)
                           (*? (char-in numeric))
                           (any-char))
                     "aa") => (0 2)
          (try-match '(seq (char-in alphabetic)
                           (* (char-in numeric))
                           (any-char))
                     "a123a") => (0 5)
          (try-match '(seq (char-in alphabetic)
                           (*? (char-in numeric))
                           (any-char))
                     "a123a") => (0 2)

 -- regsexp: + regsexp
 -- regsexp: +? regsexp
     Matches REGSEXP one or more times.

          (try-match '(seq (char-in alphabetic)
                           (+ (char-in numeric))
                           (any-char))
                     "aa") => #f
          (try-match '(seq (char-in alphabetic)
                           (+? (char-in numeric))
                           (any-char))
                     "aa") => #f
          (try-match '(seq (char-in alphabetic)
                           (+ (char-in numeric))
                           (any-char))
                     "a123a") => (0 5)
          (try-match '(seq (char-in alphabetic)
                           (+? (char-in numeric))
                           (any-char))
                     "a123a") => (0 3)

 -- regsexp: ** n m regsexp
 -- regsexp: **? n m regsexp
     The N argument must be an exact nonnegative integer.  The M
     argument must be either an exact integer greater than or equal to
     N, or else '#f'.

     Matches REGSEXP at least N times and at most M times; if M is '#f'
     then there is no upper limit.

          (try-match '(seq (char-in alphabetic)
                           (** 0 2 (char-in numeric))
                           (any-char))
                     "aa") => (0 2)
          (try-match '(seq (char-in alphabetic)
                           (**? 0 2 (char-in numeric))
                           (any-char))
                     "aa") => (0 2)
          (try-match '(seq (char-in alphabetic)
                           (** 0 2 (char-in numeric))
                           (any-char))
                     "a123a") => (0 4)
          (try-match '(seq (char-in alphabetic)
                           (**? 0 2 (char-in numeric))
                           (any-char))
                     "a123a") => (0 2)

 -- regsexp: ** n regsexp
     This is an abbreviation for '(** N N REGSEXP)'.  This matcher is
     neither greedy nor shy since it matches a fixed number of
     repetitions.

   These forms implement alternatives and sequencing:

 -- regsexp: alt regsexp ...
     Matches one of the REGSEXP arguments, trying each in order from
     left to right.

          (try-match '(alt #\a (char-in numeric)) "a") => (0 1)
          (try-match '(alt #\a (char-in numeric)) "b") => #f
          (try-match '(alt #\a (char-in numeric)) "1") => (0 1)

 -- regsexp: seq regsexp ...
     Matches the first REGSEXP, then continues the match with the next
     REGSEXP, and so on until all of the arguments are matched.

          (try-match '(seq #\a #\b) "a") => #f
          (try-match '(seq #\a #\b) "aa") => #f
          (try-match '(seq #\a #\b) "ab") => (0 2)

   These forms implement named "registers", which store matched segments
of the input string:

 -- regsexp: group key regsexp
     The KEY argument must be a fixnum, a character, or a symbol.

     Matches REGSEXP.  If the match succeeds, the matched segment is
     stored in the register named KEY.

          (try-match '(seq (group a (any-char))
                           (group b (any-char))
                           (any-char))
                     "radar") => (0 3 (a . "r") (b . "a"))

 -- regsexp: group-ref key
     The KEY argument must be a fixnum, a character, or a symbol.

     Matches the characters stored in the register named KEY.  It is an
     error if that register has not been initialized with a
     corresponding 'group' expression.

          (try-match '(seq (group a (any-char))
                           (group b (any-char))
                           (any-char)
                           (group-ref b)
                           (group-ref a))
                     "radar") => (0 5 (a . "r") (b . "a"))


File: mit-scheme-ref.info,  Node: Regsexp Procedures,  Prev: Regular S-Expressions,  Up: Regular Expressions

6.2.2 Regsexp Procedures
------------------------

The regular s-expression implementation has two parts, like many other
regular-expression implementations: a compiler that translates the
pattern into an efficient form, and one or more procedures that use that
pattern to match or search inputs.

 -- procedure: compile-regsexp regsexp
     Compiles REGSEXP by translating it into a procedure that implements
     the specified matcher.

   The match and search procedures each return a list when they are
successful, and '#f' when they fail.  The returned list is of the form
'(S E REGISTER ...)', where S is the index at which the match starts, E
is the index at which the match ends, and each REGISTER is a pair '(KEY
. CONTENTS)' where KEY is the register's name and CONTENTS is the
contents of that register as a string.

   In order to get reliable results, the string arguments to these
procedures must be in Unicode Normalization Form C. The string
implementation keeps most strings in this form by default; in other
cases the caller must convert the string using 'string->nfc'.

 -- procedure: regsexp-match-string crse string [start [end]]
     The CRSE argument must be a value returned by 'compile-regsexp'.
     The STRING argument must satisfy 'string-in-nfc?'.

     Matches STRING against CRSE and returns the result.

 -- procedure: regsexp-search-string-forward crse string [start [end]]
     The CRSE argument must be a value returned by 'compile-regsexp'.
     The STRING argument must satisfy 'string-in-nfc?'.

     Searches STRING from left to right for a match against CRSE and
     returns the result.


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
     (http://srfi.schemers.org/srfi-1/srfi-1.html).

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


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

          (circular-list? (list 'a 'b 'c))        => #f
          (circular-list? (cons* 'a 'b 'c))       => #f
          (circular-list? (circular-list 'a 'b 'c)) => #t

 -- procedure: dotted-list? object
     (SRFI 1) Returns '#t' if OBJECT is an improper 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: 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)
                    (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).


File: mit-scheme-ref.info,  Node: Cutting and Pasting Lists,  Next: Filtering Lists,  Prev: Selecting List Components,  Up: Lists

7.4 Cutting and Pasting Lists
=============================

 -- procedure: sublist list start end
     START and END must be exact integers satisfying

          0 <= START <= END <= (length LIST)

     'sublist' returns a newly allocated list formed from the elements
     of LIST beginning at index START (inclusive) and ending at END
     (exclusive).

 -- procedure: list-head list k
     Returns a newly allocated list consisting of the first K elements
     of LIST.  K must not be greater than the length of LIST.

     We could have defined 'list-head' this way:

          (define (list-head list k)
            (sublist list 0 k))

 -- procedure: list-tail list k
     Returns the sublist of LIST obtained by omitting the first K
     elements.  The result, if it is not the empty list, shares
     structure with LIST.  K must not be greater than the length of
     LIST.

 -- procedure: append list ...
     Returns a list consisting of the elements of the first LIST
     followed by the elements of the other LISTs.

          (append '(x) '(y))                      => (x y)
          (append '(a) '(b c d))                  => (a b c d)
          (append '(a (b)) '((c)))                => (a (b) (c))
          (append)                                => ()

     The resulting list is always newly allocated, except that it shares
     structure with the last LIST argument.  The last argument may
     actually be any object; an improper list results if the last
     argument is not a proper list.

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

 -- procedure: append! list ...
     Returns a list that is the argument LISTs concatenated together.
     The arguments are changed rather than copied.  (Compare this with
     'append', which copies arguments rather than destroying them.)  For
     example:

          (define x '(a b c))
          (define y '(d e f))
          (define z '(g h))
          (append! x y z)                         => (a b c d e f g h)
          x                                       => (a b c d e f g h)
          y                                       => (d e f g h)
          z                                       => (g h)

 -- procedure: last-pair list
     Returns the last pair in LIST, which may be an improper list.
     'last-pair' could have been defined this way:

          (define last-pair
            (lambda (x)
              (if (pair? (cdr x))
                  (last-pair (cdr x))
                  x)))

 -- procedure: except-last-pair list
 -- procedure: except-last-pair! list
     These procedures remove the last pair from LIST.  LIST may be an
     improper list, except that it must consist of at least one pair.
     'except-last-pair' returns a newly allocated copy of LIST that
     omits the last pair.  'except-last-pair!' destructively removes the
     last pair from LIST and returns LIST.  If the cdr of LIST is not a
     pair, the empty list is returned by either procedure.

