   Guile Reference Manual Copyright (C) 1996 Free Software Foundation
Copyright (C) 1997 Free Software Foundation
Copyright (C) 2000 Free Software Foundation
Copyright (C) 2001 Free Software Foundation
Copyright (C) 2002 Free Software Foundation

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Free Software Foundation.

Init Snarfing with guile-snarf
------------------------------

   When writing C code for use with Guile, you typically define a set
of C functions, and then make some of them visible to the Scheme world
by calling the `scm_c_define_gsubr' function; a C function published in
this way is called a "subr".  If you have many subrs to publish, it can
sometimes be annoying to keep the list of calls to `scm_c_define_gsubr'
in sync with the list of function definitions.  Frequently, a
programmer will define a new subr in C, recompile the application, and
then discover that the Scheme interpreter cannot see the subr, because
of a missed call to `scm_c_define_gsubr'.

   Guile provides the `guile-snarf' command to manage this problem.
Using this tool, you can keep all the information needed to define the
subr alongside the function definition itself; `guile-snarf' will
extract this information from your source code, and automatically
generate a file of calls to `scm_c_define_gsubr' which you can
`#include' into an initialization function.

How guile-snarf works
.....................

   Usage: guile-snarf [-o OUTFILE] [CPP-ARGS ...]

   The `guile-snarf' program will extract initialization actions to
OUTFILE or to standard output when no OUTFILE has been specified or
when OUTFILE is `-'.  The C preprocessor is called with CPP-ARGS (which
usually include an input file) and the output is filtered to extract
the initialization actions.

   If there are errors during processing, OUTFILE is deleted and the
program exits with non-zero status.

   During snarfing, the pre-processor macro `SCM_MAGIC_SNARFER' is
defined.  You could use this to avoid including snarfer output files
that don't yet exist by writing code like this:

     #ifndef SCM_MAGIC_SNARFER
     #include "foo.x"
     #endif

   If the environment variable `CPP' is set, use its value instead of
the C pre-processor determined at Guile configure-time.

   See Macros guile-snarf recognizes, for a list of the special
(some would say magic) cpp macros you can use, including the list of
deprecated macros.

   For example, here is how you might define a new subr called
`clear-image', implemented by the C function `clear_image':

     #include <libguile.h>

     SCM_DEFINE (clear_image, "clear-image", 1, 0, 0,
                 (SCM image_smob),
                 "Clear the image.")
     #define FUNC_NAME s_clear_image
     {
       /* C code to clear the image in `image_smob'... */
     }
     #undef FUNC_NAME

     void
     init_image_type ()
     {
     #include "image-type.x"
     }

   The `SCM_DEFINE' declaration says that the C function `clear_image'
implements a Scheme subr called `clear-image', which takes one required
argument (of type `SCM' and named `image_smob'), no optional arguments,
and no rest argument.  See Doc Snarfing, for info on the docstring.

   This works in concert with `FUNC_NAME' to also define a static array
of characters named `s_clear_image', initialized to the string
"clear-image".  The body of `clear_image' may use the array in error
messages, instead of writing out the literal string; this may save
string space on some systems.

   Assuming the text above lives in a file named `image-type.c', you
will need to execute the following command to prepare this file for
compilation:

     guile-snarf -o image-type.x image-type.c

   This scans `image-type.c' for `SCM_DEFINE' declarations, and writes
to `image-type.x' the output:

     scm_c_define_gsubr (s_clear_image, 1, 0, 0, (SCM (*)() ) clear_image);

   When compiled normally, `SCM_DEFINE' is a macro which expands to a
declaration of the `s_clear_image' string and the function header for
`clear_image'.

   Note that the output file name matches the `#include' from the input
file.  Also, you still need to provide all the same information you
would if you were using `scm_c_define_gsubr' yourself, but you can
place the information near the function definition itself, so it is
less likely to become incorrect or out-of-date.

   If you have many files that `guile-snarf' must process, you should
consider using a fragment like the following in your Makefile:

     snarfcppopts = $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS)
     .SUFFIXES: .x
     .c.x:
     	guile-snarf -o $ $< $(snarfcppopts)

   This tells make to run `guile-snarf' to produce each needed `.x'
file from the corresponding `.c' file.

   The program `guile-snarf' passes its command-line arguments directly
to the C preprocessor, which it uses to extract the information it
needs from the source code. this means you can pass normal compilation
flags to `guile-snarf' to define preprocessor symbols, add header file
directories, and so on.

Macros guile-snarf recognizes
.............................

   Here are the macros you can use in your source code from which
`guile-snarf' can construct initialization code:

     /* procedures */
     SCM_DEFINE (FNAME, PRIMNAME, REQ, OPT, VAR, ARGLIST, DOCSTRING)

     SCM_PROC (RANAME, STR, REQ, OPT, VAR, CFN)
     SCM_REGISTER_PROC (RANAME, STR, REQ, OPT, VAR, CFN)

     SCM_GPROC (RANAME, STR, REQ, OPT, VAR, CFN, GF)

     /* everything else */
     SCM_SYMBOL (c_name, scheme_name)
     SCM_GLOBAL_SYMBOL (c_name, scheme_name)

     SCM_KEYWORD (c_name, scheme_name)
     SCM_GLOBAL_KEYWORD (c_name, scheme_name)

     SCM_VARIABLE (c_name, scheme_name)
     SCM_GLOBAL_VARIABLE (c_name, scheme_name)

     SCM_VARIABLE_INIT (c_name, scheme_name, init_val)
     SCM_GLOBAL_VARIABLE_INIT (c_name, scheme_name, init_val)

   REQ and OPT are numbers indicating required and optional argument
counts, respectively; VAR is a number that, if non-zero, means the
function will accept any remaining arguments as a list; DOCSTRING is a
string (use `\n\' at eol for multi-line); FNAME is a C-language
identifier, CFN and GF and C_NAME likewise; PRIMNAME is a string
denoting the name available to Scheme code, STR and SCHEME_NAME
likewise; RANAME is the name of the static string (must match that
declared by the associated definition of cpp macro FUNC_NAME); ARGLIST
is an argument list (in parentheses); and lastly, INIT_VAL is a
expression suitable for initializing a new variable.

   For procedures, you can use `SCM_DEFINE' for most purposes.  Use
`SCM_PROC' along with `SCM_REGISTER_PROC' when you don't want to be
bothered with docstrings.  Use `SCM_GPROC' for generic functions (see
GOOPS (goops)).  All procedures are declared with return type
`SCM'.

   For everything else, use the appropriate macro (`SCM_SYMBOL' for
symbols, and so on).  Without "_GLOBAL_", the declarations are `static'.

   All these macros should be used at top-level, outside function
bodies.  Also, it's a good idea to define FUNC_NAME immediately after
using `SCM_DEFINE' (and similar), and then the function body, and then
`#undef FUNC_NAME'.

   See How guile-snarf works, and also libguile source, for
examples.  See Subrs, for details on argument passing and how to
write C functions.

Writing your own snarfing macros
................................

   When you want to use the general snarfing machanism, but none of the
provided macros fits your need, you can use the macro `SCM_SNARF_INIT'.

   For example, the `SCM_SYMBOL' macro can be defined like this:

     #define SCM_SYMBOL(c_name, scheme_name) \
     static SCM c_name \
     SCM_SNARF_INIT(c_name = scm_permanent_object (scm_str2symbol (scheme_name)))

 - Macro: SCM_SNARF_INIT (code)
     When processed normally, `SCM_SNARF_INIT' expands to nothing; when
     processed by the snarfer, it causes CODE to be included in the
     initialization action file, followed by a semicolon.

Doc Snarfing
------------

   In addition to init snarfing (see Init Snarfing with guile-snarf),
the libguile sources are also subject to doc snarfing,
by programs that are included in the distribution (but not installed at
this time).  The output is the file `guile-procedures.txt' which is
installed, and subsequently used by module `(ice-9 documentation)'.

   Here is a list of what does what according to `libguile/Makefile.am':

   * guile-snarf-docs runs cpp defining SCM_MAGIC_SNARF_DOCS

   * guile_filter_doc_snarfage parses guile-snarf-docs output to
     produce .doc

   * ../scripts/snarf-check-and-output-texi makes guile.texi

   * ../scripts/snarf-check-and-output-texi makes guile-procedures.txt

   * guile-func-name-check checks source snarf-syntax integrity
     (optional?)

   * guile-doc-snarf calls guile-snarf-docs (to make .doc) and
     guile-snarf

   Note that for guile-1.4, a completely different approach was used!
All this is rather byzantine, so for now _NO_ doc snarfing programs are
installed.

   [fixme: Document further once doc snarfing is tamed somewhat. -ttn]

Executable Modules
==================

   When Guile is installed, in addition to the `(ice-9 FOO)' modules, a
set of "executable modules" `(scripts BAR)' is also installed.  Each is
a regular Scheme module that has some additional packaging so that it
can be called as a program in its own right, from the shell.  For this
reason, we sometimes use the term "script" in this context to mean the
same thing.

   As a convenience, the `guile-tools' wrapper program is installed
along w/ `guile'; it knows where a particular module is installed and
calls it passing its args to the program.  The result is that you need
not augment your PATH.  Usage is straightforward:

     guile-tools --help
     guile-tools --version
     guile-tools [OPTION] PROGRAM [ARGS ...]

     If PROGRAM is "list" or omitted, display contents of scripts dir, otherwise
     PROGRAM is run w/ ARGS.  Options (only one of which may be used at a time):
      --scriptsdir DIR    -- Look in DIR for scripts
      --guileversion VERS -- Look in $pkgdatadir/VERS/scripts for scripts
      --source            -- Display PROGRAM source (ignore ARGS) to stdout

   The modules are self-documenting.  For example, to see the
documentation for `lint', use one (or both) of the shell commands:

     guile-tools display-commentary '(scripts lint)'
     guile-tools --source lint

   The rest of this section describes the packaging that goes into
creating an executable module.  Feel free to skip to the next chapter.

Writing Executable Modules
--------------------------

   See template file `PROGRAM' for a quick start.

   Programs must follow the "executable module" convention, documented
here:

   * The file name must not end in ".scm".

   * The file must be executable (chmod +x).

   * The module name must be "(scripts PROGRAM)".  A procedure named
     PROGRAM w/ signature "(PROGRAM . args)" must be exported.
     Basically, use some variant of the form:

          (define-module (scripts PROGRAM)
            :export (PROGRAM))

     Feel free to export other definitions useful in the module context.

   * There must be the alias:

          (define main PROGRAM)

     However, `main' must NOT be exported.

   * The beginning of the file must use the following invocation
     sequence:

          #!/bin/sh
          main='(module-ref (resolve-module '\''(scripts PROGRAM)) '\'main')'
          exec ${GUILE-guile} -l $0 -c "(apply $main (cdr (command-line)))" "$@"
          !#

   Following these conventions allows the program file to be used as
module `(scripts PROGRAM)' in addition to as a standalone executable.
Please also include a helpful Commentary section w/ some usage info.

Basic Ideas in Scheme
*********************

   In this chapter, we introduce the basic concepts that underpin the
elegance and power of the Scheme language.

   Readers who already possess a background knowledge of Scheme may
happily skip this chapter.  For the reader who is new to the language,
however, the following discussions on data, procedures, expressions and
closure are designed to provide a minimum level of Scheme understanding
that is more or less assumed by the reference chapters that follow.

   The style of this introductory material aims about halfway between
the terse precision of R5RS and the discursive randomness of a Scheme
tutorial.

Data Types, Values and Variables
================================

   This section discusses the representation of data types and values,
what it means for Scheme to be a "latently typed" language, and the role
of variables.  We conclude by introducing the Scheme syntaxes for
defining a new variable, and for changing the value of an existing
variable.

Latent Typing
-------------

   The term "latent typing" is used to describe a computer language,
such as Scheme, for which you cannot, _in general_, simply look at a
program's source code and determine what type of data will be
associated with a particular variable, or with the result of a
particular expression.

   Sometimes, of course, you _can_ tell from the code what the type of
an expression will be.  If you have a line in your program that sets the
variable `x' to the numeric value 1, you can be certain that,
immediately after that line has executed (and in the absence of multiple
threads), `x' has the numeric value 1.  Or if you write a procedure
that is designed to concatenate two strings, it is likely that the rest
of your application will always invoke this procedure with two string
parameters, and quite probable that the procedure would go wrong in some
way if it was ever invoked with parameters that were not both strings.

   Nevertheless, the point is that there is nothing in Scheme which
requires the procedure parameters always to be strings, or `x' always
to hold a numeric value, and there is no way of declaring in your
program that such constraints should always be obeyed.  In the same
vein, there is no way to declare the expected type of a procedure's
return value.

   Instead, the types of variables and expressions are only known - in
general - at run time.  If you _need_ to check at some point that a
value has the expected type, Scheme provides run time procedures that
you can invoke to do so.  But equally, it can be perfectly valid for two
separate invocations of the same procedure to specify arguments with
different types, and to return values with different types.

   The next subsection explains what this means in practice, for the
ways that Scheme programs use data types, values and variables.

Values and Variables
--------------------

   Scheme provides many data types that you can use to represent your
data.  Primitive types include characters, strings, numbers and
procedures.  Compound types, which allow a group of primitive and
compound values to be stored together, include lists, pairs, vectors
and multi-dimensional arrays.  In addition, Guile allows applications
to define their own data types, with the same status as the built-in
standard Scheme types.

   As a Scheme program runs, values of all types pop in and out of
existence.  Sometimes values are stored in variables, but more commonly
they pass seamlessly from being the result of one computation to being
one of the parameters for the next.

   Consider an example.  A string value is created because the
interpreter reads in a literal string from your program's source code.
Then a numeric value is created as the result of calculating the length
of the string.  A second numeric value is created by doubling the
calculated length.  Finally the program creates a list with two
elements - the doubled length and the original string itself - and
stores this list in a program variable.

   All of the values involved here - in fact, all values in Scheme -
carry their type with them.  In other words, every value "knows," at
runtime, what kind of value it is.  A number, a string, a list,
whatever.

   A variable, on the other hand, has no fixed type.  A variable - `x',
say - is simply the name of a location - a box - in which you can store
any kind of Scheme value.  So the same variable in a program may hold a
number at one moment, a list of procedures the next, and later a pair
of strings.  The "type" of a variable - insofar as the idea is
meaningful at all - is simply the type of whatever value the variable
happens to be storing at a particular moment.

Defining and Setting Variables
------------------------------

   To define a new variable, you use Scheme's `define' syntax like this:

     (define VARIABLE-NAME VALUE)

   This makes a new variable called VARIABLE-NAME and stores VALUE in
it as the variable's initial value.  For example:

     ;; Make a variable `x' with initial numeric value 1.
     (define x 1)

     ;; Make a variable `organization' with an initial string value.
     (define organization "Free Software Foundation")

   (In Scheme, a semicolon marks the beginning of a comment that
continues until the end of the line.  So the lines beginning `;;' are
comments.)

   Changing the value of an already existing variable is very similar,
except that `define' is replaced by the Scheme syntax `set!', like this:

     (set! VARIABLE-NAME NEW-VALUE)

   Remember that variables do not have fixed types, so NEW-VALUE may
have a completely different type from whatever was previously stored in
the location named by VARIABLE-NAME.  Both of the following examples
are therefore correct.

     ;; Change the value of `x' to 5.
     (set! x 5)

     ;; Change the value of `organization' to the FSF's street number.
     (set! organization 545)

   In these examples, VALUE and NEW-VALUE are literal numeric or string
values.  In general, however, VALUE and NEW-VALUE can be any Scheme
expression.  Even though we have not yet covered the forms that Scheme
expressions can take (see About Expressions), you can probably
guess what the following `set!' example does...

     (set! x (+ x 1))

   (Note: this is not a complete description of `define' and `set!',
because we need to introduce some other aspects of Scheme before the
missing pieces can be filled in.  If, however, you are already familiar
with the structure of Scheme, you may like to read about those missing
pieces immediately by jumping ahead to the following references.

   * See Lambda Alternatives, to read about an alternative form of
     the `define' syntax that can be used when defining new procedures.

   * See Procedures with Setters, to read about an alternative form
     of the `set!' syntax that helps with changing a single value in
     the depths of a compound data structure.)

   * See Internal Definitions, to read about using `define' other
     than at top level in a Scheme program, including a discussion of
     when it works to use `define' rather than `set!' to change the
     value of an existing variable.

The Representation and Use of Procedures
========================================

   This section introduces the basics of using and creating Scheme
procedures.  It discusses the representation of procedures as just
another kind of Scheme value, and shows how procedure invocation
expressions are constructed.  We then explain how `lambda' is used to
create new procedures, and conclude by presenting the various shorthand
forms of `define' that can be used instead of writing an explicit
`lambda' expression.

Procedures as Values
--------------------

   One of the great simplifications of Scheme is that a procedure is
just another type of value, and that procedure values can be passed
around and stored in variables in exactly the same way as, for example,
strings and lists.  When we talk about a built-in standard Scheme
procedure such as `open-input-file', what we actually mean is that
there is a pre-defined top level variable called `open-input-file',
whose value is a procedure that implements what R5RS says that
`open-input-file' should do.

   Note that this is quite different from many dialects of Lisp --
including Emacs Lisp -- in which a program can use the same name with
two quite separate meanings: one meaning identifies a Lisp function,
while the other meaning identifies a Lisp variable, whose value need
have nothing to do with the function that is associated with the first
meaning.  In these dialects, functions and variables are said to live in
different "namespaces".

   In Scheme, on the other hand, all names belong to a single unified
namespace, and the variables that these names identify can hold any kind
of Scheme value, including procedure values.

   One consequence of the "procedures as values" idea is that, if you
don't happen to like the standard name for a Scheme procedure, you can
change it.

   For example, `call-with-current-continuation' is a very important
standard Scheme procedure, but it also has a very long name!  So, many
programmers use the following definition to assign the same procedure
value to the more convenient name `call/cc'.

     (define call/cc call-with-current-continuation)

   Let's understand exactly how this works.  The definition creates a
new variable `call/cc', and then sets its value to the value of the
variable `call-with-current-continuation'; the latter value is a
procedure that implements the behaviour that R5RS specifies under the
name "call-with-current-continuation".  So `call/cc' ends up holding
this value as well.

   Now that `call/cc' holds the required procedure value, you could
choose to use `call-with-current-continuation' for a completely
different purpose, or just change its value so that you will get an
error if you accidentally use `call-with-current-continuation' as a
procedure in your program rather than `call/cc'.  For example:

     (set! call-with-current-continuation "Not a procedure any more!")

   Or you could just leave `call-with-current-continuation' as it was.
It's perfectly fine for more than one variable to hold the same
procedure value.

Simple Procedure Invocation
---------------------------

   A procedure invocation in Scheme is written like this:

     (PROCEDURE [ARG1 [ARG2 ...]])

   In this expression, PROCEDURE can be any Scheme expression whose
value is a procedure.  Most commonly, however, PROCEDURE is simply the
name of a variable whose value is a procedure.

   For example, `string-append' is a standard Scheme procedure whose
behaviour is to concatenate together all the arguments, which are
expected to be strings, that it is given.  So the expression

     (string-append "/home" "/" "andrew")

is a procedure invocation whose result is the string value
`"/home/andrew"'.

   Similarly, `string-length' is a standard Scheme procedure that
returns the length of a single string argument, so

     (string-length "abc")

is a procedure invocation whose result is the numeric value 3.

   Each of the parameters in a procedure invocation can itself be any
Scheme expression.  Since a procedure invocation is itself a type of
expression, we can put these two examples together to get

     (string-length (string-append "/home" "/" "andrew"))

-- a procedure invocation whose result is the numeric value 12.

   (You may be wondering what happens if the two examples are combined
the other way round.  If we do this, we can make a procedure invocation
expression that is _syntactically_ correct:

     (string-append "/home" (string-length "abc"))

but when this expression is executed, it will cause an error, because
the result of `(string-length "abc")' is a numeric value, and
`string-append' is not designed to accept a numeric value as one of its
arguments.)

Creating and Using a New Procedure
----------------------------------

   Scheme has lots of standard procedures, and Guile provides all of
these via predefined top level variables.  All of these standard
procedures are documented in the later chapters of this reference
manual.

   Before very long, though, you will want to create new procedures that
encapsulate aspects of your own applications' functionality.  To do
this, you can use the famous `lambda' syntax.

   For example, the value of the following Scheme expression

     (lambda (name address) EXPRESSION ...)

is a newly created procedure that takes two arguments: `name' and
`address'.  The behaviour of the new procedure is determined by the
sequence of EXPRESSIONs in the "body" of the procedure definition.
(Typically, these EXPRESSIONs would use the arguments in some way, or
else there wouldn't be any point in giving them to the procedure.)
When invoked, the new procedure returns a value that is the value of
the last EXPRESSION in the procedure body.

   To make things more concrete, let's suppose that the two arguments
are both strings, and that the purpose of this procedure is to form a
combined string that includes these arguments.  Then the full lambda
expression might look like this:

     (lambda (name address)
       (string-append "Name=" name ":Address=" address))

   We noted in the previous subsection that the PROCEDURE part of a
procedure invocation expression can be any Scheme expression whose value
is a procedure.  But that's exactly what a lambda expression is!  So we
can use a lambda expression directly in a procedure invocation, like
this:

     ((lambda (name address)
        (string-append "Name=" name ":Address=" address))
      "FSF"
      "Cambridge")

This is a valid procedure invocation expression, and its result is the
string `"Name=FSF:Address=Cambridge"'.

   It is more common, though, to store the procedure value in a
variable --

     (define make-combined-string
       (lambda (name address)
         (string-append "Name=" name ":Address=" address)))

-- and then to use the variable name in the procedure invocation:

     (make-combined-string "FSF" "Cambridge")

Which has exactly the same result.

   It's important to note that procedures created using `lambda' have
exactly the same status as the standard built in Scheme procedures, and
can be invoked, passed around, and stored in variables in exactly the
same ways.

Lambda Alternatives
-------------------

   Since it is so common in Scheme programs to want to create a
procedure and then store it in a variable, there is an alternative form
of the `define' syntax that allows you to do just that.

   A `define' expression of the form

     (define (NAME [ARG1 [ARG2 ...]])
       EXPRESSION ...)

is exactly equivalent to the longer form

     (define NAME
       (lambda ([ARG1 [ARG2 ...]])
         EXPRESSION ...))

   So, for example, the definition of `make-combined-string' in the
previous subsection could equally be written:

     (define (make-combined-string name address)
       (string-append "Name=" name ":Address=" address))

   This kind of procedure definition creates a procedure that requires
exactly the expected number of arguments.  There are two further forms
of the `lambda' expression, which create a procedure that can accept a
variable number of arguments:

     (lambda (ARG1 ... . ARGS) EXPRESSION ...)

     (lambda ARGS EXPRESSION ...)

The corresponding forms of the alternative `define' syntax are:

     (define (NAME ARG1 ... . ARGS) EXPRESSION ...)

     (define (NAME . ARGS) EXPRESSION ...)

For details on how these forms work, see Lambda.

   (It could be argued that the alternative `define' forms are rather
confusing, especially for newcomers to the Scheme language, as they hide
both the role of `lambda' and the fact that procedures are values that
are stored in variables in the some way as any other kind of value.  On
the other hand, they are very convenient, and they are also a good
example of another of Scheme's powerful features: the ability to specify
arbitrary syntactic transformations at run time, which can be applied to
subsequently read input.)

Expressions and Evaluation
==========================

   So far, we have met expressions that _do_ things, such as the
`define' expressions that create and initialize new variables, and we
have also talked about expressions that have _values_, for example the
value of the procedure invocation expression:

     (string-append "/home" "/" "andrew")

but we haven't yet been precise about what causes an expression like
this procedure invocation to be reduced to its "value", or how the
processing of such expressions relates to the execution of a Scheme
program as a whole.

   This section clarifies what we mean by an expression's value, by
introducing the idea of "evaluation".  It discusses the side effects
that evaluation can have, explains how each of the various types of
Scheme expression is evaluated, and describes the behaviour and use of
the Guile REPL as a mechanism for exploring evaluation.  The section
concludes with a very brief summary of Scheme's common syntactic
expressions.

Evaluating Expressions and Executing Programs
---------------------------------------------

   In Scheme, the process of executing an expression is known as
"evaluation".  Evaluation has two kinds of result:

   * the "value" of the evaluated expression

   * the "side effects" of the evaluation, which consist of any effects
     of evaluating the expression that are not represented by the value.

   Of the expressions that we have met so far, `define' and `set!'
expressions have side effects -- the creation or modification of a
variable -- but no value; `lambda' expressions have values -- the newly
constructed procedures -- but no side effects; and procedure invocation
expressions, in general, have either values, or side effects, or both.

   It is tempting to try to define more intuitively what we mean by
"value" and "side effects", and what the difference between them is.
In general, though, this is extremely difficult.  It is also
unnecessary; instead, we can quite happily define the behaviour of a
Scheme program by specifying how Scheme executes a program as a whole,
and then by describing the value and side effects of evaluation for each
type of expression individually.

So, some(1) definitions...

   * A Scheme program consists of a sequence of expressions.

   * A Scheme interpreter executes the program by evaluating these
     expressions in order, one by one.

   * An expression can be

        * a piece of literal data, such as a number `2.3' or a string
          `"Hello world!"'

        * a variable name

        * a procedure invocation expression

        * one of Scheme's special syntactic expressions.

The following subsections describe how each of these types of expression
is evaluated.

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

   (1) These definitions are approximate.  For the whole and detailed
truth, see R5RS syntax (r5rs).

Evaluating Literal Data
.......................

   When a literal data expression is evaluated, the value of the
expression is simply the value that the expression describes.  The
evaluation of a literal data expression has no side effects.

So, for example,

   * the value of the expression `"abc"' is the string value `"abc"'

   * the value of the expression `3+4i' is the complex number 3 + 4i

   * the value of the expression `#(1 2 3)' is a three-element vector
     containing the numeric values 1, 2 and 3.

   For any data type which can be expressed literally like this, the
syntax of the literal data expression for that data type -- in other
words, what you need to write in your code to indicate a literal value
of that type -- is known as the data type's "read syntax".  This manual
specifies the read syntax for each such data type in the section that
describes that data type.

   Some data types do not have a read syntax.  Procedures, for example,
cannot be expressed as literal data; they must be created using a
`lambda' expression (see Creating a Procedure) or implicitly using
the shorthand form of `define' (see Lambda Alternatives).

Evaluating a Variable Reference
...............................

   When an expression that consists simply of a variable name is
evaluated, the value of the expression is the value of the named
variable.  The evaluation of a variable reference expression has no
side effects.

   So, after

     (define key "Paul Evans")

the value of the expression `key' is the string value `"Paul Evans"'.
If KEY is then modified by

     (set! key 3.74)

the value of the expression `key' is the numeric value 3.74.

   If there is no variable with the specified name, evaluation of the
variable reference expression signals an error.

Evaluating a Procedure Invocation Expression
............................................

   This is where evaluation starts getting interesting!  As already
noted, a procedure invocation expression has the form

     (PROCEDURE [ARG1 [ARG2 ...]])

where PROCEDURE must be an expression whose value, when evaluated, is a
procedure.

   The evaluation of a procedure invocation expression like this
proceeds by

   * evaluating individually the expressions PROCEDURE, ARG1, ARG2, and
     so on

   * calling the procedure that is the value of the PROCEDURE
     expression with the list of values obtained from the evaluations of
     ARG1, ARG2 etc. as its parameters.

   For a procedure defined in Scheme, "calling the procedure with the
list of values as its parameters" means binding the values to the
procedure's formal parameters and then evaluating the sequence of
expressions that make up the body of the procedure definition.  The
value of the procedure invocation expression is the value of the last
evaluated expression in the procedure body.  The side effects of calling
the procedure are the combination of the side effects of the sequence of
evaluations of expressions in the procedure body.

   For a built-in procedure, the value and side-effects of calling the
procedure are best described by that procedure's documentation.

   Note that the complete side effects of evaluating a procedure
invocation expression consist not only of the side effects of the
procedure call, but also of any side effects of the preceding
evaluation of the expressions PROCEDURE, ARG1, ARG2, and so on.

   To illustrate this, let's look again at the procedure invocation
expression:

     (string-length (string-append "/home" "/" "andrew"))

   In the outermost expression, PROCEDURE is `string-length' and ARG1
is `(string-append "/home" "/" "andrew")'.

   * Evaluation of `string-length', which is a variable, gives a
     procedure value that implements the expected behaviour for
     "string-length".

   * Evaluation of `(string-append "/home" "/" "andrew")', which is
     another procedure invocation expression, means evaluating each of

        * `string-append', which gives a procedure value that
          implements the expected behaviour for "string-append"

        * `"/home"', which gives the string value `"/home"'

        * `"/"', which gives the string value `"/"'

        * `"andrew"', which gives the string value `"andrew"'

     and then invoking the procedure value with this list of string
     values as its arguments.  The resulting value is a single string
     value that is the concatenation of all the arguments, namely
     `"/home/andrew"'.

   In the evaluation of the outermost expression, the interpreter can
now invoke the procedure value obtained from PROCEDURE with the value
obtained from ARG1 as its arguments.  The resulting value is a numeric
value that is the length of the argument string, which is 12.

Evaluating Special Syntactic Expressions
........................................

   When a procedure invocation expression is evaluated, the procedure
and _all_ the argument expressions must be evaluated before the
procedure can be invoked.  Special syntactic expressions are special
because they are able to manipulate their arguments in an unevaluated
form, and can choose whether to evaluate any or all of the argument
expressions.

   Why is this needed?  Consider a program fragment that asks the user
whether or not to delete a file, and then deletes the file if the user
answers yes.

     (if (string=? (read-answer "Should I delete this file?")
                   "yes")
         (delete-file file))

   If the outermost `(if ...)' expression here was a procedure
invocation expression, the expression `(delete-file file)', whose side
effect is to actually delete a file, would already have been evaluated
before the `if' procedure even got invoked!  Clearly this is no use --
the whole point of an `if' expression is that the "consequent"
expression is only evaluated if the condition of the `if' expression is
"true".

   Therefore `if' must be special syntax, not a procedure.  Other
special syntaxes that we have already met are `define', `set!' and
`lambda'.  `define' and `set!' are syntax because they need to know the
variable _name_ that is given as the first argument in a `define' or
`set!' expression, not that variable's value.  `lambda' is syntax
because it does not immediately evaluate the expressions that define
the procedure body; instead it creates a procedure object that
incorporates these expressions so that they can be evaluated in the
future, when that procedure is invoked.

   The rules for evaluating each special syntactic expression are
specified individually for each special syntax.  For a summary of
standard special syntax, see Syntax Summary.

Using the Guile REPL
--------------------

   If you start Guile without specifying a particular program for it to
execute, Guile enters its standard Read Evaluate Print Loop -- or
"REPL" for short.  In this mode, Guile repeatedly reads in the next
Scheme expression that the user types, evaluates it, and prints the
resulting value.

   The REPL is a useful mechanism for exploring the evaluation behaviour
described in the previous subsection.  If you type `string-append', for
example, the REPL replies `#<primitive-procedure string-append>',
illustrating the relationship between the variable `string-append' and
the procedure value stored in that variable.

   In this manual, the notation => is used to mean "evaluates to".
Wherever you see an example of the form

     EXPRESSION
     =>
     RESULT

feel free to try it out yourself by typing EXPRESSION into the REPL and
checking that it gives the expected RESULT.

Summary of Common Syntax
------------------------

   This subsection lists the most commonly used Scheme syntactic
expressions, simply so that you will recognize common special syntax
when you see it.  For a full description of each of these syntaxes,
follow the appropriate reference.

   `lambda' (see Lambda) is used to construct procedure objects.

   `define' (see Top Level) is used to create a new variable and
set its initial value.

   `set!' (see Top Level) is used to modify an existing variable's
value.

   `let', `let*' and `letrec' (see Local Bindings) create an inner
lexical environment for the evaluation of a sequence of expressions, in
which a specified set of local variables is bound to the values of a
corresponding set of expressions.  For an introduction to environments,
see About Closure.

   `begin' (see begin) executes a sequence of expressions in order
and returns the value of the last expression.  Note that this is not the
same as a procedure which returns its last argument, because the
evaluation of a procedure invocation expression does not guarantee to
evaluate the arguments in order.

   `if' and `cond' (see if cond case) provide conditional
evaluation of argument expressions depending on whether one or more
conditions evaluate to "true" or "false".

   `case' (see if cond case) provides conditional evaluation of
argument expressions depending on whether a variable has one of a
specified group of values.

   `and' (see and or) executes a sequence of expressions in order
until either there are no expressions left, or one of them evaluates to
"false".

   `or' (see and or) executes a sequence of expressions in order
until either there are no expressions left, or one of them evaluates to
"true".

The Concept of Closure
======================

   The concept of "closure" is the idea that a lambda expression
"captures" the variable bindings that are in lexical scope at the point
where the lambda expression occurs.  The procedure created by the
lambda expression can refer to and mutate the captured bindings, and the
values of those bindings persist between procedure calls.

   This section explains and explores the various parts of this idea in
more detail.

Names, Locations, Values and Environments
-----------------------------------------

   We said earlier that a variable name in a Scheme program is
associated with a location in which any kind of Scheme value may be
stored.  (Incidentally, the term "vcell" is often used in Lisp and
Scheme circles as an alternative to "location".)  Thus part of what we
mean when we talk about "creating a variable" is in fact establishing an
association between a name, or identifier, that is used by the Scheme
program code, and the variable location to which that name refers.
Although the value that is stored in that location may change, the
location to which a given name refers is always the same.

   We can illustrate this by breaking down the operation of the
`define' syntax into three parts: `define'

   * creates a new location

   * establishes an association between that location and the name
     specified as the first argument of the `define' expression

   * stores in that location the value obtained by evaluating the second
     argument of the `define' expression.

   A collection of associations between names and locations is called an
"environment".  When you create a top level variable in a program using
`define', the name-location association for that variable is added to
the "top level" environment.  The "top level" environment also includes
name-location associations for all the procedures that are supplied by
standard Scheme.

   It is also possible to create environments other than the top level
one, and to create variable bindings, or name-location associations, in
those environments.  This ability is a key ingredient in the concept of
closure; the next subsection shows how it is done.

Local Variables and Environments
--------------------------------

   We have seen how to create top level variables using the `define'
syntax (see Definition).  It is often useful to create variables
that are more limited in their scope, typically as part of a procedure
body.  In Scheme, this is done using the `let' syntax, or one of its
modified forms `let*' and `letrec'.  These syntaxes are described in
full later in the manual (see Local Bindings).  Here our purpose is
to illustrate their use just enough that we can see how local variables
work.

   For example, the following code uses a local variable `s' to
simplify the computation of the area of a triangle given the lengths of
its three sides.

     (define a 5.3)
     (define b 4.7)
     (define c 2.8)

     (define area
       (let ((s (/ (+ a b c) 2)))
         (sqrt (* s (- s a) (- s b) (- s c)))))

   The effect of the `let' expression is to create a new environment
and, within this environment, an association between the name `s' and a
new location whose initial value is obtained by evaluating `(/ (+ a b
c) 2)'.  The expressions in the body of the `let', namely `(sqrt (* s
(- s a) (- s b) (- s c)))', are then evaluated in the context of the
new environment, and the value of the last expression evaluated becomes
the value of the whole `let' expression, and therefore the value of the
variable `area'.