This is guile.info, produced by makeinfo version 4.5 from guile.texi.

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Guile Reference: (guile).     The Guile reference manual.
END-INFO-DIR-ENTRY

   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.


File: guile.info,  Node: Top,  Next: Guile License,  Prev: (dir),  Up: (dir)

The Guile Reference Manual
**************************

   This reference manual documents Guile, GNU's Ubiquitous Intelligent
Language for Extensions.  It describes how to use Guile in many useful
and interesting ways.

   This Info file contains edition 1.0 of the reference manual,
corresponding to Guile version 1.6.4.

* Menu:

Preface

* Guile License::               Conditions for copying and using Guile.
* Manual Layout::               How to read the rest of this manual.
* Manual Conventions::          Conventional terminology.

Part I: Introduction to Guile

* What is Guile?::              And what does it do?
* Whirlwind Tour::              An introductory whirlwind tour.
* Obtaining and Installing Guile::
* Reporting Bugs::              Reporting bugs in Guile or this manual.

Part II: Writing and Running Guile Scheme

* Running Intro::               Introduction to this part.
* Guile Scheme::                Guile's implementation of Scheme.
* Guile Scripting::             How to write Guile scripts.
* Command Line Handling::       Command line options and arguments.
* Debugging Features::          Features for debugging errors.
* Autoconf Support::            Guile-specific configure.in macros.
* Miscellaneous Tools::         Snarfing, linting, etc.
* Basic Ideas::                 Basic ideas in Scheme.
* Further Reading::             Where to find out more about Scheme.

Part III: Guile as an Extension Language

* Programming Intro::           Introduction to this part.
* Libguile Intro::              Using Guile as an extension language.
* Programming Overview::        An overview of Guile programming.
* Data Representation::         Data representation in Guile.
* GH::                          The deprecated GH interface.

Part IV: Guile API Reference

* Reference Intro::             Introduction to the Guile API reference.
* API Overview::                Overview of the Guile API.
* Simple Data Types::           Numbers, strings, booleans and so on.
* Compound Data Types::         Data types for holding other data.
* Procedures and Macros::       Procedures and macros.
* Utility Functions::           General utility functions.
* Binding Constructs::          Definitions and variable bindings.
* Control Mechanisms::          Controlling the flow of program execution.
* Input and Output::            Ports, reading and writing.
* Read/Load/Eval::              Reading and evaluating Scheme code.
* Memory Management::           Memory management and garbage collection.
* Objects::                     Low level object orientation support.
* Modules::                     Designing reusable code libraries.
* Scheduling::                  Threads, mutexes, asyncs and dynamic roots.
* Options and Config::          Configuration, features and runtime options.
* Translation::                 Support for translating other languages.
* Debugging::                   Internal debugging interface.
* Deprecated::                  Features that are planned to disappear.

Part V: Guile Modules

* SLIB::                        Using the SLIB Scheme library.
* POSIX::                       POSIX system calls and networking.
* SRFI Support::                Support for various SRFIs.
* Readline Support::            Module for using the readline library.
* Value History::               Maintaining a value history in the REPL.
* Pretty Printing::             Nicely formatting Scheme objects for output.
* Formatted Output::            The `format' procedure.
* Rx Regexps::                  The Rx regular expression library.
* Expect::			Controlling interactive programs with Guile.
* The Scheme shell (scsh)::     Using scsh interfaces in Guile.

Indices

* Concept Index::
* Procedure Index::
* Variable Index::
* Type Index::
* R5RS Index::


File: guile.info,  Node: Guile License,  Next: Manual Layout,  Prev: Top,  Up: Top

The Guile License
*****************

   The license of Guile consists of the GNU GPL plus a special statement
giving blanket permission to link with non-free software.  This is the
license statement as found in any individual file that it applies to:

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License as
     published by the Free Software Foundation; either version 2, or
     (at your option) any later version.

     This program is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this software; see the file COPYING.  If not, write to
     the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
     Boston, MA 02111-1307 USA

     As a special exception, the Free Software Foundation gives
     permission for additional uses of the text contained in its
     release of GUILE.

     The exception is that, if you link the GUILE library with other
     files to produce an executable, this does not by itself cause the
     resulting executable to be covered by the GNU General Public
     License.  Your use of that executable is in no way restricted on
     account of linking the GUILE library code into it.

     This exception does not however invalidate any other reasons why
     the executable file might be covered by the GNU General Public
     License.

     This exception applies only to the code released by the Free
     Software Foundation under the name GUILE.  If you copy code from
     other Free Software Foundation releases into a copy of GUILE, as
     the General Public License permits, the exception does not apply
     to the code that you add in this way.  To avoid misleading anyone
     as to the status of such modified files, you must delete this
     exception notice from them.

     If you write modifications of your own for GUILE, it is your choice
     whether to permit this exception to apply to your modifications.
     If you do not wish that, delete this exception notice.


File: guile.info,  Node: Manual Layout,  Next: Manual Conventions,  Prev: Guile License,  Up: Top

Layout of this Manual
*********************

   The manual is divided into five parts.

   *Part I: Introduction to Guile* provides an overview of what Guile
is and how you can use it.  A whirlwind tour shows how Guile can be
used interactively and as a script interpreter, how to link Guile into
your own applications, and how to write modules of interpreted and
compiled code for use with Guile.  Everything introduced here is
documented again and in full by the later parts of the manual.  This
part also explains how to obtain and install new versions of Guile, and
how to report bugs effectively.

   *Part II: Writing and Running Guile Scheme* and *Part III:
Programming with Guile* document all aspects of practical programming
using Guile.  This covers both the Scheme level -- where we provide an
introduction to the key ideas of the Scheme language -- and use of
Guile's `scm' interface to write new primitives and objects in C, and
to incorporate Guile into a C application.  It also covers the use of
Guile as a POSIX compliant script interpreter, and how to use the Guile
debugger.

   *Part IV: Guile API Reference* documents Guile's core API.  Most of
the variables and procedures in Guile's core programming interface are
available in both Scheme and C, and are related systematically such
that the C interface can be inferred from the Scheme interface and vice
versa.  Therefore this part of the manual documents the Guile API in
functionality-based groups with the Scheme and C interfaces presented
side by side.  Where the Scheme and C interfaces for a particular
functional area do differ -- which is sometimes inevitable, given the
differences in the structure of the two languages -- this is pointed
out and explained.  In all cases the overriding principle is that all
the reference documentation for a given functional area is grouped
together.

   *Part V: Guile Modules* describes some important modules,
distributed as part of the Guile distribution, that extend the
functionality provided by the Guile Scheme core.  Two important examples
are:

   * the POSIX module, which provides Scheme level procedures for
     system and network programming that conform to the POSIX standard

   * the SLIB module, which makes Aubrey Jaffer's portable Scheme
     library available for use in Guile.


File: guile.info,  Node: Manual Conventions,  Next: What is Guile?,  Prev: Manual Layout,  Up: Top

Conventions used in this Manual
*******************************

   We use some conventions in this manual.

   * For some procedures, notably type predicates, we use "iff" to mean
     `if and only if'.  The construct is usually something like:
     `Return VAL iff CONDITION', where VAL is usually ``#t'' or
     `non-`#f''.  This typically means that VAL is returned if
     CONDITION holds, and that `#f' is returned otherwise.

   * In examples and procedure descriptions and all other places where
     the evaluation of Scheme expression is shown, we use some notation
     for denoting the output and evaluation results of expressions.

     The symbol `=>' is used to tell which value is returned by an
     evaluation:

          (+ 1 2)
          =>
          3

     Some procedures produce some output besides returning a value.
     This is denoted by the symbol `-|'.

          (begin (display 1) (newline) 'hooray)
          -| 1
          =>
          hooray



File: guile.info,  Node: What is Guile?,  Next: Whirlwind Tour,  Prev: Manual Conventions,  Up: Top

What is Guile?
**************

   Guile is an interpreter for the Scheme programming language, packaged
for use in a wide variety of environments.  Guile implements Scheme as
described in the Revised^5 Report on the Algorithmic Language Scheme
(usually known as R5RS), providing clean and general data and control
structures.  Guile goes beyond the rather austere language presented in
R5RS, extending it with a module system, full access to POSIX system
calls, networking support, multiple threads, dynamic linking, a foreign
function call interface, powerful string processing, and many other
features needed for programming in the real world.

   Like a shell, Guile can run interactively, reading expressions from
the user, evaluating them, and displaying the results, or as a script
interpreter, reading and executing Scheme code from a file.  However,
Guile is also packaged as an object library, allowing other applications
to easily incorporate a complete Scheme interpreter.  An application can
use Guile as an extension language, a clean and powerful configuration
language, or as multi-purpose "glue", connecting primitives provided by
the application.  It is easy to call Scheme code from C code and vice
versa, giving the application designer full control of how and when to
invoke the interpreter.  Applications can add new functions, data types,
control structures, and even syntax to Guile, creating a domain-specific
language tailored to the task at hand, but based on a robust language
design.

   Guile's module system allows one to break up a large program into
manageable sections with well-defined interfaces between them.  Modules
may contain a mixture of interpreted and compiled code; Guile can use
either static or dynamic linking to incorporate compiled code.  Modules
also encourage developers to package up useful collections of routines
for general distribution; as of this writing, one can find Emacs
interfaces, database access routines, compilers, GUI toolkit interfaces,
and HTTP client functions, among others.

   In the future, we hope to expand Guile to support other languages
like Tcl and Perl by translating them to Scheme code.  This means that
users can program applications which use Guile in the language of their
choice, rather than having the tastes of the application's author
imposed on them.


File: guile.info,  Node: Whirlwind Tour,  Next: Obtaining and Installing Guile,  Prev: What is Guile?,  Up: Top

A Whirlwind Tour
****************

   This chapter presents a quick tour of all the ways that Guile can be
used.  There are additional examples in the `examples/' directory in
the Guile source distribution.

* Menu:

* Running Guile Interactively::
* Guile Scripts::
* Linking Programs With Guile::
* Writing Extensions for Guile::
* Guile Modules::


File: guile.info,  Node: Running Guile Interactively,  Next: Guile Scripts,  Up: Whirlwind Tour

Running Guile Interactively
===========================

   In its simplest form, Guile acts as an interactive interpreter for
the Scheme programming language, reading and evaluating Scheme
expressions the user enters from the terminal.  Here is a sample
interaction between Guile and a user; the user's input appears after
the `$' and `guile>' prompts:

     $ guile
     guile> (+ 1 2 3)                ; add some numbers
     6
     guile> (define (factorial n)    ; define a function
              (if (zero? n) 1 (* n (factorial (- n 1)))))
     guile> (factorial 20)
     2432902008176640000
     guile> (getpwnam "jimb")        ; find my entry in /etc/passwd
     #("jimb" ".0krIpK2VqNbU" 4008 10 "Jim Blandy" "/u/jimb"
       "/usr/local/bin/bash")
     guile> C-d
     $


File: guile.info,  Node: Guile Scripts,  Next: Linking Programs With Guile,  Prev: Running Guile Interactively,  Up: Whirlwind Tour

Guile Scripts
=============

   Like AWK, Perl, or any shell, Guile can interpret script files.  A
Guile script is simply a file of Scheme code with some extra
information at the beginning which tells the operating system how to
invoke Guile, and then tells Guile how to handle the Scheme code.

   Before we present the details, here is a trivial Guile script:

     #!/usr/local/bin/guile -s
     !#
     (display "Hello, world!")
     (newline)

* Menu:

* The Top of a Script File::    How to start a Guile script.
* Scripting Examples::          Simple Guile scripts, explained.


File: guile.info,  Node: The Top of a Script File,  Next: Scripting Examples,  Up: Guile Scripts

The Top of a Script File
------------------------

   The first line of a Guile script must tell the operating system to
use Guile to evaluate the script, and then tell Guile how to go about
doing that.  Here is the simplest case:

   * The first two characters of the file must be `#!'.

     The operating system interprets this to mean that the rest of the
     line is the name of an executable that can interpret the script.
     Guile, however, interprets these characters as the beginning of a
     multi-line comment, terminated by the characters `!#' on a line by
     themselves.  (This is an extension to the syntax described in
     R5RS, added to support shell scripts.)

   * Immediately after those two characters must come the full pathname
     to the Guile interpreter.  On most systems, this would be
     `/usr/local/bin/guile'.

   * Then must come a space, followed by a command-line argument to
     pass to Guile; this should be `-s'.  This switch tells Guile to
     run a script, instead of soliciting the user for input from the
     terminal.  There are more elaborate things one can do here; see
     *Note The Meta Switch::.

   * Follow this with a newline.

   * The second line of the script should contain only the characters
     `!#' -- just like the top of the file, but reversed.  The
     operating system never reads this far, but Guile treats this as
     the end of the comment begun on the first line by the `#!'
     characters.

   * The rest of the file should be a Scheme program.


   Guile reads the program, evaluating expressions in the order that
they appear.  Upon reaching the end of the file, Guile exits.

   The function `command-line' returns the name of the script file and
any command-line arguments passed by the user, as a list of strings.

   For example, consider the following script file:
     #!/usr/local/bin/guile -s
     !#
     (write (command-line))
     (newline)

   If you put that text in a file called `foo' in the current
directory, then you could make it executable and try it out like this:
     $ chmod a+x foo
     $ ./foo
     ("./foo")
     $ ./foo bar baz
     ("./foo" "bar" "baz")
     $

   As another example, here is a simple replacement for the POSIX
`echo' command:
     #!/usr/local/bin/guile -s
     !#
     (for-each (lambda (s) (display s) (display " "))
       (cdr (command-line)))
     (newline)

 - Scheme Procedure: command-line
 - Scheme Procedure: program-arguments
     Return a list of the command-line arguments passed to the currently
     running program.  If the program invoked Guile with the `-s', `-c'
     or `--' switches, these procedures ignore everything up to and
     including those switches.


File: guile.info,  Node: Scripting Examples,  Prev: The Top of a Script File,  Up: Guile Scripts

Scripting Examples
------------------

   To start with, here are some examples of invoking Guile directly:

`guile -- a b c'
     Run Guile interactively; `(command-line)' will return
     `("/usr/local/bin/guile" "a" "b" "c")'.

`guile -s /u/jimb/ex2 a b c'
     Load the file `/u/jimb/ex2'; `(command-line)' will return
     `("/u/jimb/ex2" "a" "b" "c")'.

`guile -c '(write %load-path) (newline)''
     Write the value of the variable `%load-path', print a newline, and
     exit.

`guile -e main -s /u/jimb/ex4 foo'
     Load the file `/u/jimb/ex4', and then call the function `main',
     passing it the list `("/u/jimb/ex4" "foo")'.

`guile -l first -ds -l last -s script'
     Load the files `first', `script', and `last', in that order.  The
     `-ds' switch says when to process the `-s' switch.  For a more
     motivated example, see the scripts below.


   Here is a very simple Guile script:
     #!/usr/local/bin/guile -s
     !#
     (display "Hello, world!")
     (newline)
   The first line marks the file as a Guile script.  When the user
invokes it, the system runs `/usr/local/bin/guile' to interpret the
script, passing `-s', the script's filename, and any arguments given to
the script as command-line arguments.  When Guile sees `-s SCRIPT', it
loads SCRIPT.  Thus, running this program produces the output:
     Hello, world!

   Here is a script which prints the factorial of its argument:
     #!/usr/local/bin/guile -s
     !#
     (define (fact n)
       (if (zero? n) 1
         (* n (fact (- n 1)))))
     
     (display (fact (string->number (cadr (command-line)))))
     (newline)
   In action:
     $ fact 5
     120
     $

   However, suppose we want to use the definition of `fact' in this
file from another script.  We can't simply `load' the script file, and
then use `fact''s definition, because the script will try to compute
and display a factorial when we load it.  To avoid this problem, we
might write the script this way:

     #!/usr/local/bin/guile \
     -e main -s
     !#
     (define (fact n)
       (if (zero? n) 1
         (* n (fact (- n 1)))))
     
     (define (main args)
       (display (fact (string->number (cadr args))))
       (newline))
   This version packages the actions the script should perform in a
function, `main'.  This allows us to load the file purely for its
definitions, without any extraneous computation taking place.  Then we
used the meta switch `\' and the entry point switch `-e' to tell Guile
to call `main' after loading the script.
     $ fact 50
     30414093201713378043612608166064768844377641568960512000000000000

   Suppose that we now want to write a script which computes the
`choose' function: given a set of M distinct objects, `(choose N M)' is
the number of distinct subsets containing N objects each.  It's easy to
write `choose' given `fact', so we might write the script this way:
     #!/usr/local/bin/guile \
     -l fact -e main -s
     !#
     (define (choose n m)
       (/ (fact m) (* (fact (- m n)) (fact n))))
     
     (define (main args)
       (let ((n (string->number (cadr args)))
             (m (string->number (caddr args))))
         (display (choose n m))
         (newline)))

   The command-line arguments here tell Guile to first load the file
`fact', and then run the script, with `main' as the entry point.  In
other words, the `choose' script can use definitions made in the `fact'
script.  Here are some sample runs:
     $ choose 0 4
     1
     $ choose 1 4
     4
     $ choose 2 4
     6
     $ choose 3 4
     4
     $ choose 4 4
     1
     $ choose 50 100
     100891344545564193334812497256


File: guile.info,  Node: Linking Programs With Guile,  Next: Writing Extensions for Guile,  Prev: Guile Scripts,  Up: Whirlwind Tour

Linking Programs With Guile
===========================

   The Guile interpreter is available as an object library, to be linked
into applications using Scheme as a configuration or extension
language.  This chapter covers the mechanics of linking your program
with Guile on a typical POSIX system.

   Parts III and IV of this manual describe the C functions Guile
provides.  Furthermore, any Scheme function described in this manual as
a "Primitive" is also callable from C; see *Note Primitives::.

   The header file `<libguile.h>' provides declarations for all of
Guile's functions and constants.  You should `#include' it at the head
of any C source file that uses identifiers described in this manual.
Once you've compiled your source files, you need to link them against
the Guile object code library, `libguile'.

   On most systems, you should not need to tell the compiler and linker
explicitly where they can find `libguile.h' and `libguile'.  When Guile
has been installed in a peculiar way, or when you are on a peculiar
system, things might not be so easy and you might need to pass
additional `-I' or `-L' options to the compiler.  Guile provides the
utility program `guile-config' to help you find the right values for
these options.  You would typically run `guile-config' during the
configuration phase of your program and use the obtained information in
the Makefile.

* Menu:

* Guile Initialization Functions::  What to call first.
* A Sample Guile Main Program::  Sources and makefiles.


File: guile.info,  Node: Guile Initialization Functions,  Next: A Sample Guile Main Program,  Up: Linking Programs With Guile

Guile Initialization Functions
------------------------------

   To initialize Guile, you can use one of two functions.  The first,
`scm_boot_guile', is the most portable way to initialize Guile.  It
should be used whenever you have control over the main function of your
program because it never returns.  The second function,
`scm_init_guile', does return and can thus be used in more situations.
However, `scm_init_guile' is not as widely available as
`scm_boot_guile' because it needs to rely on non-portable code to find
the stack bounds.  When Guile does not know how to find these bounds on
your system, it will not provide `scm_init_guile'.

   When you can tolerate the limits of `scm_boot_guile', you should use
it in favor of `scm_init_guile' since that will make your program more
portable.

 - Function: void scm_boot_guile (int ARGC, char **ARGV, void
          (*MAIN_FUNC) (), void *CLOSURE)
     Initialize the Guile Scheme interpreter.  Then call MAIN_FUNC,
     passing it CLOSURE, ARGC, and ARGV.  MAIN_FUNC should do all the
     work of the program (initializing other packages, defining
     application-specific functions, reading user input, and so on)
     before returning.  When MAIN_FUNC returns, call `exit (0)';
     `scm_boot_guile' never returns.  If you want some other exit value,
     have MAIN_FUNC call exit itself.

     `scm_boot_guile' arranges for the Scheme `command-line' function
     to return the strings given by ARGC and ARGV.  If MAIN_FUNC
     modifies ARGC or ARGV, it should call `scm_set_program_arguments'
     with the final list, so Scheme code will know which arguments have
     been processed.

     Why must the caller do all the real work from MAIN_FUNC?  Guile's
     garbage collector scans the stack to find all local variables that
     reference Scheme objects.  To do this, it needs to know the bounds
     of the stack that might contain such references.  Because there is
     no portable way in C to find the base of the stack,
     `scm_boot_guile' assumes that all references are above its own
     stack frame.  If you try to manipulate Scheme objects after this
     function returns, it's the luck of the draw whether Guile's
     storage manager will be able to find the objects you allocate.
     So, `scm_boot_guile' function exits, rather than returning, to
     discourage you from making that mistake.

     See `scm_init_guile', below, for a function that can find the real
     base of the stack, but not in a portable way.

 - Function: void scm_init_guile ()
     Initialize the Guile Scheme interpreter.

     In contrast to `scm_boot_guile', this function knows how to find
     the true base of the stack and thus does not need to usurp the
     control flow of your program.  However, since finding the stack
     base can not be done portably, this function might not be
     available in all installations of Guile.  If you can, you should
     use `scm_boot_guile' instead.

     Note that `scm_init_guile' does not inform Guile about the command
     line arguments that should be returned by the Scheme function
     `command-line'.  You can use `scm_set_program_arguments' to do
     this.

   One common way to use Guile is to write a set of C functions which
perform some useful task, make them callable from Scheme, and then link
the program with Guile.  This yields a Scheme interpreter just like
`guile', but augmented with extra functions for some specific
application -- a special-purpose scripting language.

   In this situation, the application should probably process its
command-line arguments in the same manner as the stock Guile
interpreter.  To make that straightforward, Guile provides this
function:

 - Function: void scm_shell (int ARGC, char **ARGV)
     Process command-line arguments in the manner of the `guile'
     executable.  This includes loading the normal Guile initialization
     files, interacting with the user or running any scripts or
     expressions specified by `-s' or `-e' options, and then exiting.
     *Note Invoking Guile::, for more details.

     Since this function does not return, you must do all
     application-specific initialization before calling this function.


File: guile.info,  Node: A Sample Guile Main Program,  Prev: Guile Initialization Functions,  Up: Linking Programs With Guile

A Sample Guile Main Program
---------------------------

   Here is `simple-guile.c', source code for a `main' and an
`inner_main' function that will produce a complete Guile interpreter.

     /* simple-guile.c --- how to start up the Guile
        interpreter from C code.  */
     
     /* Get declarations for all the scm_ functions.  */
     #include <libguile.h>
     
     static void
     inner_main (void *closure, int argc, char **argv)
     {
       /* module initializations would go here */
       scm_shell (argc, argv);
     }
     
     int
     main (int argc, char **argv)
     {
       scm_boot_guile (argc, argv, inner_main, 0);
       return 0; /* never reached */
     }

   The `main' function calls `scm_boot_guile' to initialize Guile,
passing it `inner_main'.  Once `scm_boot_guile' is ready, it invokes
`inner_main', which calls `scm_shell' to process the command-line
arguments in the usual way.

   Here is a Makefile which you can use to compile the above program.
It uses `guile-config' to learn about the necessary compiler and linker
flags.
     # Use GCC, if you have it installed.
     CC=gcc
     
     # Tell the C compiler where to find <libguile.h>
     CFLAGS=`guile-config compile`
     
     # Tell the linker what libraries to use and where to find them.
     LIBS=`guile-config link`
     
     simple-guile: simple-guile.o
             ${CC} simple-guile.o ${LIBS} -o simple-guile
     
     simple-guile.o: simple-guile.c
             ${CC} -c ${CFLAGS} simple-guile.c

   If you are using the GNU Autoconf package to make your application
more portable, Autoconf will settle many of the details in the Makefile
above automatically, making it much simpler and more portable; we
recommend using Autoconf with Guile.  Guile also provides the
`GUILE_FLAGS' macro for autoconf that performs all necessary checks.
Here is a `configure.in' file for `simple-guile' that uses this macro.
Autoconf can use as this file as template to generate a `configure'
script.  In order for Autoconf to find the `GUILE_FLAGS' macro, you
will need to run `aclocal' first.  This is not really Guile specific,
so you should refer to the Autoconf documentation REFFIXME when in
doubt.
     AC_INIT(simple-guile.c)
     
     # Find a C compiler.
     AC_PROG_CC
     
     # Check for Guile
     GUILE_FLAGS
     
     # Generate a Makefile, based on the results.
     AC_OUTPUT(Makefile)

   Here is a `Makefile.in' template, from which the `configure' script
produces a Makefile customized for the host system:
     # The configure script fills in these values.
     CC=@CC@
     CFLAGS=@GUILE_CFLAGS@
     LIBS=@GUILE_LDFLAGS@
     
     simple-guile: simple-guile.o
             ${CC} simple-guile.o ${LIBS} -o simple-guile
     simple-guile.o: simple-guile.c
             ${CC} -c ${CFLAGS} simple-guile.c

   The developer should use Autoconf to generate the `configure' script
from the `configure.in' template, and distribute `configure' with the
application.  Here's how a user might go about building the application:

     $ ls
     Makefile.in     configure*      configure.in    simple-guile.c
     $ ./configure
     creating cache ./config.cache
     checking for gcc... (cached) gcc
     checking whether the C compiler (gcc  ) works... yes
     checking whether the C compiler (gcc  ) is a cross-compiler... no
     checking whether we are using GNU C... (cached) yes
     checking whether gcc accepts -g... (cached) yes
     checking for Guile... yes
     creating ./config.status
     creating Makefile
     $ make
     gcc -c -I/usr/local/include simple-guile.c
     gcc simple-guile.o -L/usr/local/lib -lguile -lqthreads -lpthread -lm -o simple-guile
     $ ./simple-guile
     guile> (+ 1 2 3)
     6
     guile> (getpwnam "jimb")
     #("jimb" "83Z7d75W2tyJQ" 4008 10 "Jim Blandy" "/u/jimb"
       "/usr/local/bin/bash")
     guile> (exit)
     $


File: guile.info,  Node: Writing Extensions for Guile,  Next: Guile Modules,  Prev: Linking Programs With Guile,  Up: Whirlwind Tour

Writing Extensions for Guile
============================

   The previous sections have briefly explained how to write programs
that make use of an embedded Guile interpreter.  But sometimes, all you
want to do is make new primitive procedures and data types available to
the Scheme programmer.  Writing a new version of `guile' is
inconvenient in this case and it would in fact make the life of the
users of your new features needlessly hard.

   For example, suppose that there is a program `guile-db' that is a
version of Guile with additional features for accessing a database.
People who want to write Scheme programs that use these features would
have to use `guile-db' instead of the usual `guile' program.  Now
suppose that there is also a program `guile-gtk' that extends Guile
with access to the popular Gtk+ toolkit for graphical user interfaces.
People who want to write GUIs in Scheme would have to use `guile-gtk'.
Now, what happens when you want to write a Scheme application that uses
a GUI to let the user access a database?  You would have to write a
_third_ program that incorporates both the database stuff and the GUI
stuff.  This might not be easy (because `guile-gtk' might be a quite
obscure program, say) and taking this example further makes it easy to
see that this approach can not work in practice.

   It would have been much better if both the database features and the
GUI feature had been provided as libraries that can just be linked with
`guile'.  Guile makes it easy to do just this, and we encourage you to
make your extensions to Guile available as libraries whenever possible.

   You write the new primitive procedures and data types in the normal
fashion, and link them into a shared library instead of into a
stand-alone program.  The shared library can then be loaded dynamically
by Guile.

* Menu:

* A Sample Guile Extension::


File: guile.info,  Node: A Sample Guile Extension,  Up: Writing Extensions for Guile

A Sample Guile Extension
------------------------

   This section explains how to make the Bessel functions of the C
library available to Scheme.  First we need to write the appropriate
glue code to convert the arguments and return values of the functions
from Scheme to C and back.  Additionally, we need a function that will
add them to the set of Guile primitives.  Because this is just an
example, we will only implement this for the `j0' function.

   Consider the following file `bessel.c'.

     #include <math.h>
     #include <libguile.h>
     
     SCM
     j0_wrapper (SCM x)
     {
       return scm_make_real (j0 (scm_num2dbl (x, "j0")));
     }
     
     void
     init_bessel ()
     {
       scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
     }

   This C source file needs to be compiled into a shared library.  Here
is how to do it on GNU/Linux:

     gcc -shared -o libguile-bessel.so -fPIC bessel.c

   For creating shared libraries portably, we recommend the use of `GNU
Libtool'.

   A shared library can be loaded into a running Guile process with the
function `load-extension'.  In addition to the name of the library to
load, this function also expects the name of function from that library
that will be called to initialize it.  For our example, we are going to
call the function `init_bessel' which will make `j0_wrapper' available
to Scheme programs with the name `j0'.  Note that we do not specify a
filename extension such as `.so' when invoking `load-extension'.  The
right extension for the host platform will be provided automatically.

     (load-extension "libguile-bessel" "init_bessel")
     (j0 2)
     => 0.223890779141236

   For this to work, `load-extension' must be able to find
`libguile-bessel', of course.  It will look in the places that are
usual for your operating system, and it will additionally look into the
directories listed in the `LTDL_LIBRARY_PATH' environment variable.

   To see how these Guile extensions via shared libraries relate to the
module system, see below *Note Intro to Modules and Extensions::.


File: guile.info,  Node: Guile Modules,  Prev: Writing Extensions for Guile,  Up: Whirlwind Tour

Guile Modules
=============

   Guile has support for dividing a program into "modules".  By using
modules, you can group related code together and manage the composition
of complete programs from largely independent parts.

   (Although the module system implementation is in flux, feel free to
use it anyway.  Guile will provide reasonable backwards compatibility.)

   Details on the module system beyond this introductory material can
be found in *Note Modules::.

* Menu:

* Intro to Using Guile Modules::
* Intro to Writing New Modules::
* Intro to Modules and Extensions::


File: guile.info,  Node: Intro to Using Guile Modules,  Next: Intro to Writing New Modules,  Up: Guile Modules

Intro to Using Existing Modules
-------------------------------

   Guile comes with a lot of useful modules, for example for string
processing or command line parsing.  Additionally, there exist many
Guile modules written by other Guile hackers, but which have to be
installed manually.

   Existing modules have to be placed in places where Guile looks for
them by default or in colon-separated directories in the environment
variable `GUILE_LOAD_PATH'.  When this variable is set, those
directories are searched first, then the the default.  The following
command shows the complete list of directories searched:

     guile -c '(write %load-path) (newline)'

   Suppose you want to use the procedures and variables exported by the
module `(ice-9 popen)', which provides the means for communicating with
other processes over pipes.  Add the following line to your currently
running Guile REPL or the top of your script file.

     (use-modules (ice-9 popen))

   This will load the module and make the procedures exported by
`(ice-9 popen)' automatically available.  The next step could be to
open a pipe to `ls' and read the contents of the current directory, one
line at a time.

     (define p (open-input-pipe "ls -l"))
     (read-line p)
     =>
     "total 30"
     (read-line p)
     =>
     "drwxr-sr-x    2 mgrabmue mgrabmue     1024 Mar 29 19:57 CVS"


File: guile.info,  Node: Intro to Writing New Modules,  Next: Intro to Modules and Extensions,  Prev: Intro to Using Guile Modules,  Up: Guile Modules

Intro to Writing New Modules
----------------------------

   Of course it is possible to write modules yourself.  Using modules
for structuring your programs makes them more readable and lets you
distribute them more easily.  Also, explicitly defining the procedures
and variables which are exported from a module adds documentation to the
source and specifies the interface a module provides.

   In Guile, you can create new modules and switch to existing modules
in order to add bindings to them using the syntactic form
`define-module'.

     (define-module (foo bar))
     
     (define (frob x) x)

   Will create the module `(foo bar)'.(1) All definitions following
this statement will add bindings to the module `(foo bar)', and these
bindings will not be visible outside of the module.  To make the
bindings accessible to other modules, you have to export them
explicitly using one of the following means:

   * Export them with the `export' form:
          (export frob)

   * Include them into the `define-module' form with the keyword
     `export':
          (define-module (foo bar)
            #:export (frob))

   * Change the definition of `frob' to use `define-public', which is a
     combination of `define' and `export'.
          (define-public (frob x) x)

   After exporting, other modules can access the exported items simply
by using `use-modules' to load the module `(foo bar)'.

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

   (1) It is only convention that the module names in this section have
two elements.  One or more than two elements are perfectly fine, such
as `(foo)' or `(foo bar braz)'


File: guile.info,  Node: Intro to Modules and Extensions,  Prev: Intro to Writing New Modules,  Up: Guile Modules

Intro to Modules and Extensions
-------------------------------

   In addition to Scheme code you can also put things that are defined
in C into a module.

   You do this by writing a small Scheme file that defines the module.
That Scheme file in turn invokes `load-extension' to make the features
defined in C available.  This works since all definitions made by
`scm_c_define_gsubr' etc. go into the _current module_ and
`define-module' causes the newly defined module to be current while the
code that follows it is executed.

   Suppose we want to put the Bessel function `j0' from the example
extension into a module called `(math bessel)'.  We would have to write
a Scheme file with this contents

     (define-module (math bessel))
     
     (export j0)
     
     (load-extension "libguile-bessel" "init_bessel")

   This file should of course be saved in the right place for
autoloading, for example as `/usr/local/share/guile/math/bessel.scm'.

   When `init_bessel' is called, the new `(math bessel)' module is the
current one.  Thus, the call to `scm_c_define_gsubr' will put the new
definition for `j0' into it, just as we want it.

   The definitions made in the C code are not automatically exported
from a module.  You need to explicitly list the ones you want to export
in `export' statements or with the `:export' option of `define-module'.

   There is also a way to manipulate the module system from C but only
Scheme files can be autoloaded.  Thus, we recommend that you define
your modules in Scheme.


File: guile.info,  Node: Obtaining and Installing Guile,  Next: Reporting Bugs,  Prev: Whirlwind Tour,  Up: Top

Obtaining and Installing Guile
******************************

   Here is the information you will need to get and install Guile and
extra packages and documentation you might need or find interesting.

* Menu:

* The Basic Guile Package::
* Packages not shipped with Guile::


File: guile.info,  Node: The Basic Guile Package,  Next: Packages not shipped with Guile,  Up: Obtaining and Installing Guile

The Basic Guile Package
=======================

   Guile can be obtained from the main GNU archive site
<ftp://ftp.gnu.org> or any of its mirrors.  The file will be named
guile-version.tar.gz.  The current version is 1.6.4, so the file you
should grab is:

   <ftp://ftp.gnu.org/pub/gnu/guile-1.6.4.tar.gz>

   To unbundle Guile use the instruction

     zcat guile-1.6.4.tar.gz | tar xvf -

   which will create a directory called `guile-1.6.4' with all the
sources.  You can look at the file `INSTALL' for detailed instructions
on how to build and install Guile, but you should be able to just do

     cd guile-1.6.4
     ./configure
     make
     make install

   This will install the Guile executable `guile', the Guile library
`-lguile' and various associated header files and support libraries. It
will also install the Guile tutorial and reference manual.

   Since this manual frequently refers to the Scheme "standard", also
known as R5RS, or the "Revised^5 Report on the Algorithmic Language
Scheme", we have included the report in the Guile distribution; *Note
Introduction: (r5rs)Top.  This will also be installed in your info
directory.


File: guile.info,  Node: Packages not shipped with Guile,  Prev: The Basic Guile Package,  Up: Obtaining and Installing Guile

Packages not shipped with Guile
===============================

   We ship the Guile tutorial and reference manual with the Guile
distribution.  Since the Scheme standard (R5RS) is a stable document, we
ship that too.

   Here are references (usually World Wide Web URLs) to some other
freely redistributable documents and packages which you might find
useful if you are using Guile.

*SCSH*
     the Scheme Shell.  Gary Houston has ported SCSH to Guile.  The
     relevant chapter (*note The Scheme shell (scsh)::) has references
     to the SCSH web page with all its documentation.

*SLIB*
     a portable Scheme library maintained by Aubrey Jaffer.  SLIB can be
     obtained by ftp from <ftp://prep.ai.mit.edu/pub/gnu/jacal/>.

     The SLIB package should be unpacked somewhere in Guile's load
     path.  It will typically be unpacked in
     `/usr/local/share/guile/site', so that it will be
     `/usr/local/share/guile/site/slib'.

     Guile might have been installed with a different prefix, in which
     case the load path can be checked from inside the interpreter with:

          guile> %load-path
          ("/usr/local/share/guile/site" "/usr/local/share/guile/1.3a" "/usr/local/share/guile" ".")

     The relevant chapter (*note SLIB::) has details on how to use SLIB
     with Guile.

*JACAL*
     a symbolic math package by Aubrey Jaffer.  The latest version of
     Jacal can be obtained from <ftp://prep.ai.mit.edu/pub/gnu/jacal/>,
     and should be unpacked in `/usr/local/share/guile/site/slib' so
     that it will be in `/usr/local/share/guile/site/slib/jacal'.

     The relevant section (*note JACAL::) has details on how to use
     Jacal.


File: guile.info,  Node: Reporting Bugs,  Next: Running Intro,  Prev: Obtaining and Installing Guile,  Up: Top

Reporting Bugs
**************

   Any problems with the installation should be reported to
<bug-guile@gnu.org>.

   Whenever you have found a bug in Guile you are encouraged to report
it to the Guile developers, so they can fix it.  They may also be able
to suggest workarounds when it is not possible for you to apply the
bug-fix or install a new version of Guile yourself.

   Before sending in bug reports, please check with the following list
that you really have found a bug.

   * Whenever documentation and actual behavior differ, you have
     certainly found a bug, either in the documentation or in the
     program.

   * When Guile crashes, it is a bug.

   * When Guile hangs or takes forever to complete a task, it is a bug.

   * When calculations produce wrong results, it is a bug.

   * When Guile signals an error for valid Scheme programs, it is a bug.

   * When Guile does not signal an error for invalid Scheme programs,
     it may be a bug, unless this is explicitly documented.

   * When some part of the documentation is not clear and does not make
     sense to you even after re-reading the section, it is a bug.

   When you write a bug report, please make sure to include as much of
the information described below in the report.  If you can't figure out
some of the items, it is not a problem, but the more information we
get, the more likely we can diagnose and fix the bug.

   * The version number of Guile.  Without this, we won't know whether
     there is any point in looking for the bug in the current version
     of Guile.

     You can get the version number by invoking the command

          $ guile --version
          Guile 1.4.1
          Copyright (c) 1995, 1996, 1997, 2000 Free Software Foundation
          Guile may be distributed under the terms of the GNU General Public License;
          certain other uses are permitted as well.  For details, see the file
          `COPYING', which is included in the Guile distribution.
          There is no warranty, to the extent permitted by law.

   * The type of machine you are using, and the operating system name
     and version number.  On GNU systems, you can get it with `uname'.

          $ uname -a
          Linux tortoise 2.2.17 #1 Thu Dec 21 17:29:05 CET 2000 i586 unknown

   * The operands given to the `configure' command when Guile was
     installed.  It's often useful to augment this with the output of
     the command `guile-config info'.

   * A complete list of any modifications you have made to the Guile
     source.  (We may not have time to investigate the bug unless it
     happens in an unmodified Guile.  But if you've made modifications
     and you don't tell us, you are sending us on a wild goose chase.)

     Be precise about these changes.  A description in English is not
     enough--send a context diff for them.

     Adding files of your own, or porting to another machine, is a
     modification of the source.

   * Details of any other deviations from the standard procedure for
     installing Guile.

   * The complete text of any source files needed to reproduce the bug.

     If you can tell us a way to cause the problem without loading any
     source files, please do so.  This makes it much easier to debug.
     If you do need files, make sure you arrange for us to see their
     exact contents.

   * The precise Guile invocation command line we need to type to
     reproduce the bug.

   * A description of what behavior you observe that you believe is
     incorrect.  For example, "The Guile process gets a fatal signal,"
     or, "The resulting output is as follows, which I think is wrong."

     Of course, if the bug is that Guile gets a fatal signal, then one
     can't miss it.  But if the bug is incorrect results, the
     maintainer might fail to notice what is wrong.  Why leave it to
     chance?

     If the manifestation of the bug is a Guile error message, it is
     important to report the precise text of the error message, and a
     backtrace showing how the Scheme program arrived at the error.

     This can be done using the procedure `backtrace' in the REPL.

   * Check whether any programs you have loaded into Guile, including
     your `.guile' file, set any variables that may affect the
     functioning of Guile.  Also, see whether the problem happens in a
     freshly started Guile without loading your `.guile' file (start
     Guile with the `-q' switch to prevent loading the init file).  If
     the problem does _not_ occur then, you must report the precise
     contents of any programs that you must load into Guile in order to
     cause the problem to occur.

   * If the problem does depend on an init file or other Scheme
     programs that are not part of the standard Guile distribution,
     then you should make sure it is not a bug in those programs by
     complaining to their maintainers first.  After they verify that
     they are using Guile in a way that is supposed to work, they
     should report the bug.

   * If you wish to mention something in the Guile source, show the
     line of code with a few lines of context.  Don't just give a line
     number.

     The line numbers in the development sources might not match those
     in your sources.  It would take extra work for the maintainers to
     determine what code is in your version at a given line number, and
     we could not be certain.

   * Additional information from a C debugger such as GDB might enable
     someone to find a problem on a machine which he does not have
     available.  If you don't know how to use GDB, please read the GDB
     manual--it is not very long, and using GDB is easy.  You can find
     the GDB distribution, including the GDB manual in online form, in
     most of the same places you can find the Guile distribution.  To
     run Guile under GDB, you should switch to the `libguile'
     subdirectory in which Guile was compiled, then do `gdb guile' or
     `gdb .libs/guile' (if using GNU Libtool).

     However, you need to think when you collect the additional
     information if you want it to show what causes the bug.

     For example, many people send just a backtrace, but that is not
     very useful by itself.  A simple backtrace with arguments often
     conveys little about what is happening inside Guile, because most
     of the arguments listed in the backtrace are pointers to Scheme
     objects.  The numeric values of these pointers have no
     significance whatever; all that matters is the contents of the
     objects they point to (and most of the contents are themselves
     pointers).


File: guile.info,  Node: Running Intro,  Next: Guile Scheme,  Prev: Reporting Bugs,  Up: Top

Part II: Writing and Running Guile Scheme
*****************************************

   Guile's core language is Scheme, and an awful lot can be achieved
simply by using Guile to write and run Scheme programs.  In this part
of the manual, we explain how to use Guile in this mode, and describe
the tools that Guile provides to help you with script writing,
debugging and packaging your programs for distribution.

   For readers who are not yet familiar with the Scheme language, this
part includes a chapter that presents the basic concepts of the
language, and gives references to freely available Scheme tutorial
material on the web.

   For detailed reference information on the variables, functions etc.
that make up Guile's application programming interface (API), please
refer to Part IV (*note Part IV -- Guile API Reference: Reference
Intro.).


File: guile.info,  Node: Guile Scheme,  Next: Guile Scripting,  Prev: Running Intro,  Up: Top

Guile's Implementation of Scheme
********************************

   Guile's core language is Scheme, which is specified and described in
the series of reports known as "RnRS".  "RnRS" is shorthand for the
"Revised^n Report on the Algorithmic Language Scheme".  The current
latest revision of RnRS is version 5 (*note R5RS: (r5rs)Top.), and
Guile 1.4 is fully compliant with the Scheme specification in this
revision.

   But Guile, like most Scheme implementations, also goes beyond R5RS in
many ways, because R5RS does not give specifications (or even
recommendations) regarding many issues that are important in practical
programming.  Some of the areas where Guile extends R5RS are:

   * Guile's interactive documentation system

   * Guile's support for POSIX-compliant network programming

   * GOOPS - Guile's framework for object oriented programming.


File: guile.info,  Node: Guile Scripting,  Next: Command Line Handling,  Prev: Guile Scheme,  Up: Top

Guile Scripting
***************

   Like AWK, Perl, or any shell, Guile can interpret script files.  A
Guile script is simply a file of Scheme code with some extra
information at the beginning which tells the operating system how to
invoke Guile, and then tells Guile how to handle the Scheme code.

* Menu:

* Invoking Guile::              How to start a Guile script.
* The Meta Switch::             Passing complex argument lists to Guile
                                from shell scripts.


File: guile.info,  Node: Invoking Guile,  Next: The Meta Switch,  Up: Guile Scripting

Invoking Guile
==============

   Here we describe Guile's command-line processing in detail.  Guile
processes its arguments from left to right, recognizing the switches
described below.  For examples, see *Note Scripting Examples::.

`-s SCRIPT ARG...'
     Read and evaluate Scheme source code from the file SCRIPT, as the
     `load' function would.  After loading SCRIPT, exit.  Any
     command-line arguments ARG... following SCRIPT become the script's
     arguments; the `command-line' function returns a list of strings
     of the form `(SCRIPT ARG...)'.

`-c EXPR ARG...'
     Evaluate EXPR as Scheme code, and then exit.  Any command-line
     arguments ARG... following EXPR become command-line arguments; the
     `command-line' function returns a list of strings of the form
     `(GUILE ARG...)', where GUILE is the path of the Guile executable.

`-- ARG...'
     Run interactively, prompting the user for expressions and
     evaluating them.  Any command-line arguments ARG... following the
     `--' become command-line arguments for the interactive session; the
     `command-line' function returns a list of strings of the form
     `(GUILE ARG...)', where GUILE is the path of the Guile executable.

`-l FILE'
     Load Scheme source code from FILE, and continue processing the
     command line.

`-e FUNCTION'
     Make FUNCTION the "entry point" of the script.  After loading the
     script file (with `-s') or evaluating the expression (with `-c'),
     apply FUNCTION to a list containing the program name and the
     command-line arguments -- the list provided by the `command-line'
     function.

     A `-e' switch can appear anywhere in the argument list, but Guile
     always invokes the FUNCTION as the _last_ action it performs.
     This is weird, but because of the way script invocation works under
     POSIX, the `-s' option must always come last in the list.

     *Note Scripting Examples::.

`-ds'
     Treat a final `-s' option as if it occurred at this point in the
     command line; load the script here.

     This switch is necessary because, although the POSIX script
     invocation mechanism effectively requires the `-s' option to
     appear last, the programmer may well want to run the script before
     other actions requested on the command line.  For examples, see
     *Note Scripting Examples::.

`\'
     Read more command-line arguments, starting from the second line of
     the script file.  *Note The Meta Switch::.

`--emacs'
     Assume Guile is running as an inferior process of Emacs, and use a
     special protocol to communicate with Emacs's Guile interaction
     mode.  This switch sets the global variable use-emacs-interface to
     `#t'.

     This switch is still experimental.

`--use-srfi=LIST'
     The option `--use-srfi' expects a comma-separated list of numbers,
     each representing a SRFI number to be loaded into the interpreter
     before starting evaluating a script file or the REPL.
     Additionally, the feature identifier for the loaded SRFIs is
     recognized by `cond-expand' when using this option.

          guile --use-srfi=8,13

`--debug'
     Start with the debugging evaluator and enable backtraces.  Using
     the debugging evaluator will give you better error messages but it
     will slow down execution.  By default, the debugging evaluator is
     only used when entering an interactive session.  When executing a
     script with `-s' or `-c', the normal, faster evaluator is used by
     default.

`-h, --help'
     Display help on invoking Guile, and then exit.

`-v, --version'
     Display the current version of Guile, and then exit.



File: guile.info,  Node: The Meta Switch,  Prev: Invoking Guile,  Up: Guile Scripting

The Meta Switch
===============

   Guile's command-line switches allow the programmer to describe
reasonably complicated actions in scripts.  Unfortunately, the POSIX
script invocation mechanism only allows one argument to appear on the
`#!' line after the path to the Guile executable, and imposes arbitrary
limits on that argument's length.  Suppose you wrote a script starting
like this:
     #!/usr/local/bin/guile -e main -s
     !#
     (define (main args)
       (map (lambda (arg) (display arg) (display " "))
            (cdr args))
       (newline))
   The intended meaning is clear: load the file, and then call `main'
on the command-line arguments.  However, the system will treat
everything after the Guile path as a single argument -- the string `"-e
main -s"' -- which is not what we want.

   As a workaround, the meta switch `\' allows the Guile programmer to
specify an arbitrary number of options without patching the kernel.  If
the first argument to Guile is `\', Guile will open the script file
whose name follows the `\', parse arguments starting from the file's
second line (according to rules described below), and substitute them
for the `\' switch.

   Working in concert with the meta switch, Guile treats the characters
`#!' as the beginning of a comment which extends through the next line
containing only the characters `!#'.  This sort of comment may appear
anywhere in a Guile program, but it is most useful at the top of a
file, meshing magically with the POSIX script invocation mechanism.

   Thus, consider a script named `/u/jimb/ekko' which starts like this:
     #!/usr/local/bin/guile \
     -e main -s
     !#
     (define (main args)
             (map (lambda (arg) (display arg) (display " "))
                  (cdr args))
             (newline))

   Suppose a user invokes this script as follows:
     $ /u/jimb/ekko a b c

   Here's what happens:
   * the operating system recognizes the `#!' token at the top of the
     file, and rewrites the command line to:
          /usr/local/bin/guile \ /u/jimb/ekko a b c
     This is the usual behavior, prescribed by POSIX.

   * When Guile sees the first two arguments, `\ /u/jimb/ekko', it opens
     `/u/jimb/ekko', parses the three arguments `-e', `main', and `-s'
     from it, and substitutes them for the `\' switch.  Thus, Guile's
     command line now reads:
          /usr/local/bin/guile -e main -s /u/jimb/ekko a b c

   * Guile then processes these switches: it loads `/u/jimb/ekko' as a
     file of Scheme code (treating the first three lines as a comment),
     and then performs the application `(main "/u/jimb/ekko" "a" "b"
     "c")'.


   When Guile sees the meta switch `\', it parses command-line argument
from the script file according to the following rules:
   * Each space character terminates an argument.  This means that two
     spaces in a row introduce an argument `""'.

   * The tab character is not permitted (unless you quote it with the
     backslash character, as described below), to avoid confusion.

   * The newline character terminates the sequence of arguments, and
     will also terminate a final non-empty argument.  (However, a
     newline following a space will not introduce a final empty-string
     argument; it only terminates the argument list.)

   * The backslash character is the escape character.  It escapes
     backslash, space, tab, and newline.  The ANSI C escape sequences
     like `\n' and `\t' are also supported.  These produce argument
     constituents; the two-character combination `\n' doesn't act like
     a terminating newline.  The escape sequence `\NNN' for exactly
     three octal digits reads as the character whose ASCII code is NNN.
     As above, characters produced this way are argument constituents.
     Backslash followed by other characters is not allowed.



File: guile.info,  Node: Command Line Handling,  Next: Debugging Features,  Prev: Guile Scripting,  Up: Top

Handling Command Line Options and Arguments
*******************************************

   The ability to accept and handle command line arguments is very
important when writing Guile scripts to solve particular problems, such
as extracting information from text files or interfacing with existing
command line applications.  This chapter describes how Guile makes
command line arguments available to a Guile script, and the utilities
that Guile provides to help with the processing of command line
arguments.

* Menu:

* Command Line Args::           Using command line arguments.
* getopt-long::                 The (ice-9 getopt-long) module.


File: guile.info,  Node: Command Line Args,  Next: getopt-long,  Up: Command Line Handling

Using Command Line Arguments
============================

   When a Guile script is invoked, Guile makes the command line
arguments accessible via the procedure `command-line', which returns the
arguments as a list of strings.

   For example, if the script

     #! /usr/local/bin/guile -s
     !#
     (write (command-line))
     (newline)

is saved in a file `cmdline-test.scm' and invoked using the command
line `./cmdline-test.scm bar.txt -o foo -frumple grob', the output is

     ("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")

   If the script invocation includes a `-e' option, specifying a
procedure to call after loading the script, Guile will call that
procedure with `(command-line)' as its argument.  So a script that uses
`-e' doesn't need to refer explicitly to `command-line' in its code.
For example, the script above would have identical behaviour if it was
written instead like this:

     #! /usr/local/bin/guile \
     -e main -s
     !#
     (define (main args)
       (write args)
       (newline))

   (Note the use of the meta switch `\' so that the script invocation
can include more than one Guile option: *Note The Meta Switch::.)

   These scripts use the `#!' POSIX convention so that they can be
executed using their own file names directly, as in the example command
line `./cmdline-test.scm bar.txt -o foo -frumple grob'.  But they can
also be executed by typing out the implied Guile command line in full,
as in:

     $ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob

or

     $ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob

   Even when a script is invoked using this longer form, the arguments
that the script receives are the same as if it had been invoked using
the short form.  Guile ensures that the `(command-line)' or `-e'
arguments are independent of how the script is invoked, by stripping off
the arguments that Guile itself processes.


File: guile.info,  Node: getopt-long,  Prev: Command Line Args,  Up: Command Line Handling

The (ice-9 getopt-long) Module
==============================

   A script is free to parse and handle its command line arguments in
any way that it chooses.  Where the set of possible options and
arguments is complex, however, it can get tricky to extract all the
options, check the validity of given arguments, and so on.  This task
can be greatly simplified by taking advantage of the module `(ice-9
getopt-long)', which is distributed with Guile.

   The `(ice-9 getopt-long)' module exports two procedures:
`getopt-long' and `option-ref'.

   * `getopt-long' takes a list of strings -- the command line
     arguments -- and an "option specification".  It parses the command
     line arguments according to the option specification and returns a
     data structure that encapsulates the results of the parsing.

   * `option-ref' then takes the parsed data structure and a specific
     option's name, and returns information about that option in
     particular.

   To make these procedures available to your Guile script, include the
expression `(use-modules (ice-9 getopt-long))' somewhere near the top,
before the first usage of `getopt-long' or `option-ref'.

* Menu:

* getopt-long Example::         A short getopt-long example.
* Option Specification::        How to write an option specification.
* Command Line Format::         The expected command line format.
* getopt-long Reference::       Full documentation for `getopt-long'.
* option-ref Reference::        Full documentation for `option-ref'.


File: guile.info,  Node: getopt-long Example,  Next: Option Specification,  Up: getopt-long

A Short getopt-long Example
---------------------------

   This subsection illustrates how `getopt-long' is used by presenting
and dissecting a simple example.  The first thing that we need is an
"option specification" that tells `getopt-long' how to parse the
command line.  This specification is an association list with the long
option name as the key.  Here is how such a specification might look:

     (define option-spec
       '((version (single-char #\v) (value #f))
         (help    (single-char #\h) (value #f))))

   This alist tells `getopt-long' that it should accept two long
options, called _version_ and _help_, and that these options can also
be selected by the single-letter abbreviations _v_ and _h_,
respectively.  The `(value #f)' clauses indicate that neither of the
options accepts a value.

   With this specification we can use `getopt-long' to parse a given
command line:

     (define options (getopt-long (command-line) option-spec))

   After this call, `options' contains the parsed command line and is
ready to be examined by `option-ref'.  `option-ref' is called like this:

     (option-ref options 'help #f)

It expects the parsed command line, a symbol indicating the option to
examine, and a default value.  The default value is returned if the
option was not present in the command line, or if the option was present
but without a value; otherwise the value from the command line is
returned.  Usually `option-ref' is called once for each possible option
that a script supports.

   The following example shows a main program which puts all this
together to parse its command line and figure out what the user wanted.

     (define (main args)
       (let* ((option-spec '((version (single-char #\v) (value #f))
                             (help    (single-char #\h) (value #f))))
              (options (getopt-long args option-spec))
              (help-wanted (option-ref options 'help #f))
              (version-wanted (option-ref options 'version #f)))
         (if (or version-wanted help-wanted)
             (begin
               (if version-wanted
                   (display "getopt-long-example version 0.3\n"))
               (if help-wanted
                   (display "\
     getopt-long-example [options]
       -v, --version    Display version
       -h, --help       Display this help
     ")))
             (begin
               (display "Hello, World!") (newline)))))


File: guile.info,  Node: Option Specification,  Next: Command Line Format,  Prev: getopt-long Example,  Up: getopt-long

How to Write an Option Specification
------------------------------------

   An option specification is an association list (*note Association
Lists::) with one list element for each supported option. The key of
each list element is a symbol that names the option, while the value is
a list of option properties:

     OPTION-SPEC ::=  '( (OPT-NAME1 (PROP-NAME PROP-VALUE) ...)
                         (OPT-NAME2 (PROP-NAME PROP-VALUE) ...)
                         (OPT-NAME3 (PROP-NAME PROP-VALUE) ...)
                         ...
                       )

   Each OPT-NAME specifies the long option name for that option.  For
example, a list element with OPT-NAME `background' specifies an option
that can be specified on the command line using the long option
`--background'.  Further information about the option -- whether it
takes a value, whether it is required to be present in the command
line, and so on -- is specified by the option properties.

   In the example of the preceding subsection, we already saw that a
long option name can have a equivalent "short option" character.  The
equivalent short option character can be set for an option by specifying
a `single-char' property in that option's property list.  For example,
a list element like `'(output (single-char #\o) ...)' specifies an
option with long name `--output' that can also be specified by the
equivalent short name `-o'.

   The `value' property specifies whether an option requires or accepts
a value.  If the `value' property is set to `#t', the option requires a
value: `getopt-long' will signal an error if the option name is present
without a corresponding value.  If set to `#f', the option does not
take a value; in this case, a non-option word that follows the option
name in the command line will be treated as a non-option argument.  If
set to the symbol `optional', the option accepts a value but does not
require one: a non-option word that follows the option name in the
command line will be interpreted as that option's value.  If the option
name for an option with `'(value optional)' is immediately followed in
the command line by _another_ option name, the value for the first
option is implicitly `#t'.

   The `required?' property indicates whether an option is required to
be present in the command line.  If the `required?'  property is set to
`#t', `getopt-long' will signal an error if the option is not specified.

   Finally, the `predicate' property can be used to constrain the
possible values of an option.  If used, the `predicate' property should
be set to a procedure that takes one argument -- the proposed option
value as a string -- and returns either `#t' or `#f' according as the
proposed value is or is not acceptable.  If the predicate procedure
returns `#f', `getopt-long' will signal an error.

   By default, options do not have single-character equivalents, are not
required, and do not take values.  Where the list element for an option
includes a `value' property but no `predicate' property, the option
values are unconstrained.


File: guile.info,  Node: Command Line Format,  Next: getopt-long Reference,  Prev: Option Specification,  Up: getopt-long

Expected Command Line Format
----------------------------

   In order for `getopt-long' to correctly parse a command line, that
command line must conform to a standard set of rules for how command
line options are specified.  This subsection explains what those rules
are.

   `getopt-long' splits a given command line into several pieces.  All
elements of the argument list are classified to be either options or
normal arguments.  Options consist of two dashes and an option name
(so-called "long" options), or of one dash followed by a single letter
("short" options).

   Options can behave as switches, when they are given without a value,
or they can be used to pass a value to the program.  The value for an
option may be specified using an equals sign, or else is simply the next
word in the command line, so the following two invocations are
equivalent:

     $ ./foo.scm --output=bar.txt
     $ ./foo.scm --output bar.txt

   Short options can be used instead of their long equivalents and can
be grouped together after a single dash.  For example, the following
commands are equivalent.

     $ ./foo.scm --version --help
     $ ./foo.scm -v --help
     $ ./foo.scm -vh

   If an option requires a value, it can only be grouped together with
other short options if it is the last option in the group; the value is
the next argument.  So, for example, with the following option
specification --

     ((apples    (single-char #\a))
      (blimps    (single-char #\b) (value #t))
      (catalexis (single-char #\c) (value #t)))

-- the following command lines would all be acceptable:

     $ ./foo.scm -a -b bang -c couth
     $ ./foo.scm -ab bang -c couth
     $ ./foo.scm -ac couth -b bang

   But the next command line is an error, because `-b' is not the last
option in its combination, and because a group of short options cannot
include two options that both require values:

     $ ./foo.scm -abc couth bang

   If an option's value is optional, `getopt-long' decides whether the
option has a value by looking at what follows it in the argument list.
If the next element is a string, and it does not appear to be an option
itself, then that string is the option's value.

   If the option `--' appears in the argument list, argument parsing
stops there and subsequent arguments are returned as ordinary arguments,
even if they resemble options.  So, with the command line

     $ ./foo.scm --apples "Granny Smith" -- --blimp Goodyear

`getopt-long' will recognize the `--apples' option as having the value
"Granny Smith", but will not treat `--blimp' as an option.  The strings
`--blimp' and `Goodyear' will be returned as ordinary argument strings.


File: guile.info,  Node: getopt-long Reference,  Next: option-ref Reference,  Prev: Command Line Format,  Up: getopt-long

Reference Documentation for `getopt-long'
-----------------------------------------

 - Scheme Procedure: getopt-long args grammar
     Parse the command line given in ARGS (which must be a list of
     strings) according to the option specification GRAMMAR.

     The GRAMMAR argument is expected to be a list of this form:

     `((OPTION (PROPERTY VALUE) ...) ...)'

     where each OPTION is a symbol denoting the long option, but
     without the two leading dashes (e.g. `version' if the option is
     called `--version').

     For each option, there may be list of arbitrarily many
     property/value pairs.  The order of the pairs is not important,
     but every property may only appear once in the property list.  The
     following table lists the possible properties:

    `(single-char CHAR)'
          Accept `-CHAR' as a single-character equivalent to
          `--OPTION'.  This is how to specify traditional Unix-style
          flags.

    `(required? BOOL)'
          If BOOL is true, the option is required.  `getopt-long' will
          raise an error if it is not found in ARGS.

    `(value BOOL)'
          If BOOL is `#t', the option accepts a value; if it is `#f',
          it does not; and if it is the symbol `optional', the option
          may appear in ARGS with or without a value.

    `(predicate FUNC)'
          If the option accepts a value (i.e. you specified `(value
          #t)' for this option), then `getopt-long' will apply FUNC to
          the value, and throw an exception if it returns `#f'.  FUNC
          should be a procedure which accepts a string and returns a
          boolean value; you may need to use quasiquotes to get it into
          GRAMMAR.

   `getopt-long''s ARGS parameter is expected to be a list of strings
like the one returned by `command-line', with the first element being
the name of the command.  Therefore `getopt-long' ignores the first
element in ARGS and starts argument interpretation with the second
element.

   `getopt-long' signals an error if any of the following conditions
hold.

   * The option grammar has an invalid syntax.

   * One of the options in the argument list was not specified by the
     grammar.

   * A required option is omitted.

   * An option which requires an argument did not get one.

   * An option that doesn't accept an argument does get one (this can
     only happen using the long option `--opt=VALUE' syntax).

   * An option predicate fails.


File: guile.info,  Node: option-ref Reference,  Prev: getopt-long Reference,  Up: getopt-long

Reference Documentation for `option-ref'
----------------------------------------

 - Scheme Procedure: option-ref options key default
     Search OPTIONS for a command line option named KEY and return its
     value, if found.  If the option has no value, but was given,
     return `#t'.  If the option was not given, return DEFAULT.
     OPTIONS must be the result of a call to `getopt-long'.

   `option-ref' always succeeds, either by returning the requested
option value from the command line, or the default value.

   The special key `'()' can be used to get a list of all non-option
arguments.


File: guile.info,  Node: Debugging Features,  Next: Autoconf Support,  Prev: Command Line Handling,  Up: Top

Debugging Features
******************

   When debugging a program, programmers often find it helpful to
examine the program's internal status while it runs: the values of
internal variables, the choices made in `if' and `cond' statements, and
so forth.  Guile Scheme provides a debugging interface that programmers
can use to single-step through Scheme functions and examine symbol
bindings.  This is different from the *Note Debugging::, which permits
programmers to debug the Guile interpreter itself.  Most programmers
will be more interested in debugging their own Scheme programs than the
interpreter which evaluates them.

   [FIXME: should we include examples of traditional debuggers and
explain why they can't be used to debug interpreted Scheme or Lisp?]

* Menu:

* Single-Step::         Execute a program or function one step at a time.
* Trace::               Print a report each time a given function is called.
* Backtrace::           See a list of the statements that caused an error.


File: guile.info,  Node: Single-Step,  Next: Trace,  Up: Debugging Features

Single-Step
===========


File: guile.info,  Node: Trace,  Next: Backtrace,  Prev: Single-Step,  Up: Debugging Features

Trace
=====

   When a function is "traced", it means that every call to that
function is reported to the user during a program run.  This can help a
programmer determine whether a function is being called at the wrong
time or with the wrong set of arguments.

 - Function: trace function
     Enable debug tracing on `function'.  While a program is being run,
     Guile will print a brief report at each call to a traced function,
     advising the user which function was called and the arguments that
     were passed to it.

 - Function: untrace function
     Disable debug tracing for `function'.

   Example:

     (define (rev ls)
       (if (null? ls)
           '()
           (append (rev (cdr ls))
                   (cons (car ls) '())))) => rev
     
     (trace rev) => (rev)
     
     (rev '(a b c d e))
     => [rev (a b c d e)]
        |  [rev (b c d e)]
        |  |  [rev (c d e)]
        |  |  |  [rev (d e)]
        |  |  |  |  [rev (e)]
        |  |  |  |  |  [rev ()]
        |  |  |  |  |  ()
        |  |  |  |  (e)
        |  |  |  (e d)
        |  |  (e d c)
        |  (e d c b)
        (e d c b a)
        (e d c b a)

   Note the way Guile indents the output, illustrating the depth of
execution at each function call.  This can be used to demonstrate, for
example, that Guile implements self-tail-recursion properly:

     (define (rev ls sl)
       (if (null? ls)
           sl
           (rev (cdr ls)
                (cons (car ls) sl)))) => rev
     
     (trace rev) => (rev)
     
     (rev '(a b c d e) '())
     => [rev (a b c d e) ()]
        [rev (b c d e) (a)]
        [rev (c d e) (b a)]
        [rev (d e) (c b a)]
        [rev (e) (d c b a)]
        [rev () (e d c b a)]
        (e d c b a)
        (e d c b a)

   Since the tail call is effectively optimized to a `goto' statement,
there is no need for Guile to create a new stack frame for each
iteration.  Using `trace' here helps us see why this is so.


File: guile.info,  Node: Backtrace,  Prev: Trace,  Up: Debugging Features

Backtrace
=========

 - Scheme Procedure: backtrace
 - C Function: scm_backtrace ()
     Display a backtrace of the stack saved by the last error to the
     current output port.


File: guile.info,  Node: Autoconf Support,  Next: Miscellaneous Tools,  Prev: Debugging Features,  Up: Top

Autoconf Support
****************

   When Guile is installed, a set of autoconf macros is also installed
as PREFIX/share/aclocal/guile.m4.  This chapter documents the macros
provided in that file, as well as the high-level guile-tool Autofrisk.
*Note The GNU Autoconf Manual: (autoconf)Top, for more info.

* Menu:

* Autoconf Background::         Why use autoconf?
* Autoconf Macros::             The GUILE_* macros.
* Using Autoconf Macros::       How to use them, plus examples.
* Autofrisk::                   AUTOFRISK_CHECKS and AUTOFRISK_SUMMARY.
* Using Autofrisk::             Example modules.af files.


File: guile.info,  Node: Autoconf Background,  Next: Autoconf Macros,  Up: Autoconf Support

Autoconf Background
===================

   As explained elsewhere (*note The GNU Autoconf Manual:
(autoconf)Top.), any package needs configuration at build-time.  If
your package uses Guile (or uses a package that in turn uses Guile),
you probably need to know what specific Guile features are available
and details about them.

   The way to do this is to write feature tests and arrange for their
execution by the `configure' script, typically by adding the tests to
`configure.ac', and running `autoconf' to create `configure'.  Users of
your package then run `configure' in the normal way.

   Macros are a way to make common feature tests easy to express.
Autoconf provides a wide range of macros (*note Existing Tests:
(autoconf)Existing Tests.), and Guile installation provides
Guile-specific tests in the areas of: program detection, compilation
flags reporting, and Scheme module checks.


File: guile.info,  Node: Autoconf Macros,  Next: Using Autoconf Macros,  Prev: Autoconf Background,  Up: Autoconf Support

Autoconf Macros
===============

   The macro names all begin with "GUILE_".

 - Autoconf Macro: GUILE_PROGS
     This macro looks for programs `guile', `guile-config' and
     `guile-tools', and sets variables GUILE, GUILE_CONFIG and
     GUILE_TOOLS, to their paths, respectively.  If either of the first
     two is not found, signal error.

     The variables are marked for substitution, as by `AC_SUBST'.


 - Autoconf Macro: GUILE_FLAGS
     This macro runs the `guile-config' script, installed with Guile, to
     find out where Guile's header files and libraries are installed.
     It sets two variables, GUILE_CFLAGS and GUILE_LDFLAGS.

     GUILE_CFLAGS: flags to pass to a C or C++ compiler to build code
     that uses Guile header files.  This is almost always just a `-I'
     flag.

     GUILE_LDFLAGS: flags to pass to the linker to link a program
     against Guile.  This includes `-lguile' for the Guile library
     itself, any libraries that Guile itself requires (like
     -lqthreads), and so on.  It may also include a `-L' flag to tell
     the compiler where to find the libraries.

     The variables are marked for substitution, as by `AC_SUBST'.


 - Autoconf Macro: GUILE_SITE_DIR
     This looks for Guile's "site" directory, usually something like
     PREFIX/share/guile/site, and sets var GUILE_SITE to the path.
     Note that the var name is different from the macro name.

     The variable is marked for substitution, as by `AC_SUBST'.


 - Autoconf Macro: GUILE_CHECK_RETVAL var check
     VAR is a shell variable name to be set to the return value.  CHECK
     is a Guile Scheme expression, evaluated with "$GUILE -c", and
     returning either 0 or non-#f to indicate the check passed.
     Non-0 number or #f indicates failure.     Avoid using the
     character "#" since that confuses autoconf.


 - Autoconf Macro: GUILE_MODULE_CHECK var module featuretest description
     VAR is a shell variable name to be set to "yes" or "no".  MODULE
     is a list of symbols, like: (ice-9 common-list).  FEATURETEST is
     an expression acceptable to GUILE_CHECK, q.v.  DESCRIPTION is a
     present-tense verb phrase (passed to AC_MSG_CHECKING).


 - Autoconf Macro: GUILE_MODULE_AVAILABLE var module
     VAR is a shell variable name to be set to "yes" or "no".  MODULE
     is a list of symbols, like: (ice-9 common-list).


 - Autoconf Macro: GUILE_MODULE_REQUIRED symlist
     SYMLIST is a list of symbols, WITHOUT surrounding parens, like:
     ice-9 common-list.


 - Autoconf Macro: GUILE_MODULE_EXPORTS var module modvar
     VAR is a shell variable to be set to "yes" or "no".  MODULE is a
     list of symbols, like: (ice-9 common-list).  MODVAR is the Guile
     Scheme variable to check.


 - Autoconf Macro: GUILE_MODULE_REQUIRED_EXPORT module modvar
     MODULE is a list of symbols, like: (ice-9 common-list).  MODVAR is
     the Guile Scheme variable to check.



File: guile.info,  Node: Using Autoconf Macros,  Next: Autofrisk,  Prev: Autoconf Macros,  Up: Autoconf Support

Using Autoconf Macros
=====================

   Using the autoconf macros is straightforward: Add the macro "calls"
(actually instantiations) to `configure.ac', run `aclocal', and finally,
run `autoconf'.  If your system doesn't have guile.m4 installed, place
the desired macro definitions (`AC_DEFUN' forms) in `acinclude.m4', and
`aclocal' will do the right thing.

   Some of the macros can be used inside normal shell constructs: `if
foo ; then GUILE_BAZ ; fi', but this is not guaranteed.  It's probably
a good idea to instantiate macros at top-level.

   We now include two examples, one simple and one complicated.

   The first example is for a package that uses libguile, and thus
needs to know how to compile and link against it.  So we use
`GUILE_FLAGS' to set the vars `GUILE_CFLAGS' and `GUILE_LDFLAGS', which
are automatically substituted in the Makefile.

     In configure.ac:
     
       GUILE_FLAGS
     
     In Makefile.in:
     
       GUILE_CFLAGS  = @GUILE_CFLAGS@
       GUILE_LDFLAGS = @GUILE_LDFLAGS@
     
       myprog.o: myprog.c
               $(CC) -o $ $(GUILE_CFLAGS) $<
       myprog: myprog.o
               $(CC) -o $ $< $(GUILE_LDFLAGS)

   The second example is for a package of Guile Scheme modules that
uses an external program and other Guile Scheme modules (some might
call this a "pure scheme" package).  So we use the `GUILE_SITE_DIR'
macro, a regular `AC_PATH_PROG' macro, and the `GUILE_MODULE_AVAILABLE'
macro.

     In configure.ac:
     
       GUILE_SITE_DIR
     
       probably_wont_work=""
     
       # pgtype pgtable
       GUILE_MODULE_AVAILABLE(have_guile_pg, (database postgres))
       test $have_guile_pg = no &&
           probably_wont_work="(my pgtype) (my pgtable) $probably_wont_work"
     
       # gpgutils
       AC_PATH_PROG(GNUPG,gpg)
       test x"$GNUPG" = x &&
           probably_wont_work="(my gpgutils) $probably_wont_work"
     
       if test ! "$probably_wont_work" = "" ; then
           p="         ***"
           echo
           echo "$p"
           echo "$p NOTE:"
           echo "$p The following modules probably won't work:"
           echo "$p   $probably_wont_work"
           echo "$p They can be installed anyway, and will work if their"
           echo "$p dependencies are installed later.  Please see README."
           echo "$p"
           echo
       fi
     
     In Makefile.in:
     
       instdir = @GUILE_SITE@/my
     
       install:
             $(INSTALL) my/*.scm $(instdir)


File: guile.info,  Node: Autofrisk,  Next: Using Autofrisk,  Prev: Using Autoconf Macros,  Up: Autoconf Support

Autofrisk
=========

   The "guile-tools autofrisk" command looks for the file `modules.af'
in the current directory and writes out `modules.af.m4' containing
autoconf definitions for `AUTOFRISK_CHECKS' and `AUTOFRISK_SUMMARY'.
*Note Autoconf Background::, and *Note Using Autoconf Macros::, for
more info.

   The modules.af file consists of a series of configuration forms
(Scheme lists), which have one of the following formats:

       (files-glob PATTERN ...)                      ;; required
       (non-critical-external MODULE ...)            ;; optional
       (non-critical-internal MODULE ...)            ;; optional
       (programs (MODULE PROG ...) ...)              ;; optional
       (pww-varname VARNAME)                         ;; optional

   PATTERN is a string that may contain "*" and "?" characters to be
expanded into filenames.  MODULE is a list of symbols naming a module,
such as `(srfi srfi-1)'.  VARNAME is a shell-safe name to use instead of
`probably_wont_work', the default.  This var is passed to `AC_SUBST'.
PROG is a string that names a program, such as "gpg".

   Autofrisk expands the `files-glob' pattern(s) into a list of files,
scans each file's module definition form(s), and constructs a module
dependency graph wherein modules defined by `define-module' are
considered "internal" and the remaining, "external".  For each external
module that has an internal dependency, Autofrisk emits a
`GUILE_MODULE_REQUIRED' check (*note Autoconf Macros::), which
altogether form the body of `AUTOFRISK_CHECKS'.

   `GUILE_MODULE_REQUIRED' causes the `configure' script to exit with
an error message if the specified module is not available; it enforces a
strong dependency.  You can temper dependency strength by using the
`non-critical-external' and `non-critical-internal' configuration forms
in modules.af.  For graph edges that touch such non-critical modules,
Autofrisk uses `GUILE_MODULE_AVAILABLE', and arranges for
`AUTOFRISK_SUMMARY' to display a warning if they are not found.

   The shell code resulting from the expansion of `AUTOFRISK_CHECKS' and
`AUTOFRISK_SUMMARY' uses the shell variable `probably_wont_work' to
collect the names of unfound non-critical modules.  If this bothers
you, use configuration form `(pww-name foo)' in modules.af.

   Although Autofrisk does not detect when a module uses a program (for
example, in a `system' call), it can generate `AC_PATH_PROG' forms
anyway if you use the `programs' configuration form in modules.af.
These are collected into `AUTOCONF_CHECKS'.

   *Note Using Autofrisk::, for some modules.af examples.


File: guile.info,  Node: Using Autofrisk,  Prev: Autofrisk,  Up: Autoconf Support

Using Autofrisk
===============

   Using Autofrisk (*note Autofrisk::) involves writing `modules.af' and
adding two macro calls to `configure.in'.  Here is an example of the
latter:

     AUTOFRISK_CHECKS
     AUTOFRISK_SUMMARY

   Here is an adaptation of the second "GUILE_*" example (*note Using
Autoconf Macros::) that does basically the same thing.

     (files-glob "my/*.scm")
     (non-critical-external (database postgres))
     (programs ((my gpgutils) "gpg"))        ;; (my gpgutils) uses "gpg"

   If the SRFI modules (*note SRFI Support::) were a separate package,
we could use `guile-tools frisk' to find out its dependencies:

     $ guile-tools frisk srfi/*.scm
     13 files, 18 modules (13 internal, 5 external), 9 edges
     
     x (ice-9 and-let-star)
     			 regular	(srfi srfi-2)
     x (ice-9 syncase)
     			 regular	(srfi srfi-11)
     x (ice-9 rdelim)
     			 regular	(srfi srfi-10)
     x (ice-9 receive)
     			 regular	(srfi srfi-8)
     			 regular	(srfi srfi-1)
     x (ice-9 session)
     			 regular	(srfi srfi-1)

   Then, we could use the following modules.af to help configure it:

     (files-glob "srfi/*.scm")
     (non-critical-external          ;; relatively recent
       (ice-9 rdelim)
       (ice-9 receive)
       (ice-9 and-let-star))
     (pww-varname not_fully_supported)


File: guile.info,  Node: Miscellaneous Tools,  Next: Basic Ideas,  Prev: Autoconf Support,  Up: Top

Miscellaneous Tools
*******************

   Programming is more fun with a good tools.  This chapter describes
snarfing tools, and the `guile-tools' program which can be used to
invoke the rest of the tools (which are self-documenting).  Some of
these are used in Guile development, too.  Imagine that!

* Menu:

* Snarfing::                    Grepping the source in various ways.
* Executable Modules::          Modules callable via guile-tools.


File: guile.info,  Node: Snarfing,  Next: Executable Modules,  Up: Miscellaneous Tools

Snarfing
========

   Because it's easier to maintain documentation, code, and other
metainfo in one source file than in many files, there have evolved many
methods for grepping source to lift and separate these kinds of info,
in the process generating docs or fragments of source or what have you.
This is known generally as "snarfing", which comes from the verb "to
snarf", here meaning "to unceremoniously extract information from a
somewhat unwilling source."

   This section documents the installed program `guile-snarf' which does
"init snarfing", and also touches upon guile's doc snarfing process
which is not yet finalized (i.e., doc snarfing programs are not
installed at this time).

* Menu:

* Init Snarfing with guile-snarf::      Exposing C subrs and friends to Scheme.
* Doc Snarfing::                        Generating GDFv2 or texi from source.


File: guile.info,  Node: Init Snarfing with guile-snarf,  Next: Doc Snarfing,  Up: Snarfing

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.

* Menu:

* How guile-snarf works::           Using `guile-snarf', with example.
* Macros guile-snarf recognizes::   How to mark up code for `guile-snarf'.
* Writing your own snarfing macros:: How to define new things to snarf.


File: guile.info,  Node: How guile-snarf works,  Next: Macros guile-snarf recognizes,  Up: Init Snarfing with guile-snarf

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.

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


File: guile.info,  Node: Macros guile-snarf recognizes,  Next: Writing your own snarfing macros,  Prev: How guile-snarf works,  Up: Init Snarfing with guile-snarf

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 (*note
GOOPS: (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'.

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


File: guile.info,  Node: Writing your own snarfing macros,  Prev: Macros guile-snarf recognizes,  Up: Init Snarfing with guile-snarf

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.


File: guile.info,  Node: Doc Snarfing,  Prev: Init Snarfing with guile-snarf,  Up: Snarfing

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

   In addition to init snarfing (*note 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]


File: guile.info,  Node: Executable Modules,  Prev: Snarfing,  Up: Miscellaneous Tools

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.


File: guile.info,  Node: Basic Ideas,  Next: Further Reading,  Prev: Miscellaneous Tools,  Up: Top

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.

* Menu:

* About Data::                  Latent typing, types, values and variables.
* About Procedures::            The representation and use of procedures.
* About Expressions::           All kinds of expressions and their meaning.
* About Closure::               Closure, scoping and environments.


File: guile.info,  Node: About Data,  Next: About Procedures,  Up: Basic Ideas

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.

* Menu:

* Latent Typing::               Scheme as a "latently typed" language.
* Values and Variables::        About data types, values and variables.
* Definition::                  Defining variables and setting their values.


File: guile.info,  Node: Latent Typing,  Next: Values and Variables,  Up: About Data

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.


File: guile.info,  Node: Values and Variables,  Next: Definition,  Prev: Latent Typing,  Up: About Data

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.


File: guile.info,  Node: Definition,  Prev: Values and Variables,  Up: About Data

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 (*note 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.

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

   * *Note 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.)

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


File: guile.info,  Node: About Procedures,  Next: About Expressions,  Prev: About Data,  Up: Basic Ideas

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.

* Menu:

* Procedures as Values::        Procedures are values like everything else.
* Simple Invocation::           How to write a simple procedure invocation.
* Creating a Procedure::        How to create your own procedures.
* Lambda Alternatives::         Other ways of writing procedure definitions.


File: guile.info,  Node: Procedures as Values,  Next: Simple Invocation,  Up: About Procedures

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.


File: guile.info,  Node: Simple Invocation,  Next: Creating a Procedure,  Prev: Procedures as Values,  Up: About Procedures

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


File: guile.info,  Node: Creating a Procedure,  Next: Lambda Alternatives,  Prev: Simple Invocation,  Up: About Procedures

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.


File: guile.info,  Node: Lambda Alternatives,  Prev: Creating a Procedure,  Up: About Procedures

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 *Note 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.)


File: guile.info,  Node: About Expressions,  Next: About Closure,  Prev: About Procedures,  Up: Basic Ideas

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.

* Menu:

* Evaluating::                  How a Scheme program is executed.
* The REPL::                    Interacting with the Guile interpreter.
* Syntax Summary::              Common syntactic expressions -- in brief.


File: guile.info,  Node: Evaluating,  Next: The REPL,  Up: About 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.

* Menu:

* Eval Literal::                Evaluating literal data.
* Eval Variable::               Evaluating variable references.
* Eval Procedure::              Evaluating procedure invocation expressions.
* Eval Special::                Evaluating special syntactic expressions.

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

   (1) These definitions are approximate.  For the whole and detailed
truth, see *Note R5RS syntax: (r5rs)Formal syntax and semantics.


File: guile.info,  Node: Eval Literal,  Next: Eval Variable,  Up: Evaluating

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 (*note Creating a Procedure::) or implicitly using
the shorthand form of `define' (*note Lambda Alternatives::).


File: guile.info,  Node: Eval Variable,  Next: Eval Procedure,  Prev: Eval Literal,  Up: Evaluating

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.


File: guile.info,  Node: Eval Procedure,  Next: Eval Special,  Prev: Eval Variable,  Up: Evaluating

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.


File: guile.info,  Node: Eval Special,  Prev: Eval Procedure,  Up: Evaluating

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 *Note Syntax Summary::.


File: guile.info,  Node: The REPL,  Next: Syntax Summary,  Prev: Evaluating,  Up: About Expressions

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.


File: guile.info,  Node: Syntax Summary,  Prev: The REPL,  Up: About Expressions

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' (*note Lambda::) is used to construct procedure objects.

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

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

   `let', `let*' and `letrec' (*note 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 *Note About Closure::.

   `begin' (*note 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' (*note if cond case::) provide conditional
evaluation of argument expressions depending on whether one or more
conditions evaluate to "true" or "false".

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

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

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


File: guile.info,  Node: About Closure,  Prev: About Expressions,  Up: Basic Ideas

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.

* Menu:

* About Environments::          Names, locations, values and environments.
* Local Variables::             Local variables and local environments.
* Chaining::                    Environment chaining.
* Lexical Scope::               The meaning of lexical scoping.
* Closure::                     Explaining the concept of closure.
* Serial Number::               Example 1: a serial number generator.
* Shared Variable::             Example 2: a shared persistent variable.
* Callback Closure::            Example 3: the callback closure problem.
* OO Closure::                  Example 4: object orientation.


File: guile.info,  Node: About Environments,  Next: Local Variables,  Up: About Closure

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.


File: guile.info,  Node: Local Variables,  Next: Chaining,  Prev: About Environments,  Up: About Closure

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

   We have seen how to create top level variables using the `define'
syntax (*note 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 (*note 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'.


File: guile.info,  Node: Chaining,  Next: Lexical Scope,  Prev: Local Variables,  Up: About Closure

Environment Chaining
--------------------

   In the example of the previous subsection, we glossed over an
important point.  The body of the `let' expression in that example
refers not only to the local variable `s', but also to the top level
variables `a', `b', `c' and `sqrt'.  (`sqrt' is the standard Scheme
procedure for calculating a square root.)  If the body of the `let'
expression is evaluated in the context of the _local_ `let'
environment, how does the evaluation get at the values of these top
level variables?

   The answer is that the local environment created by a `let'
expression automatically has a reference to its containing environment
-- in this case the top level environment -- and that the Scheme
interpreter automatically looks for a variable binding in the containing
environment if it doesn't find one in the local environment.  More
generally, every environment except for the top level one has a
reference to its containing environment, and the interpreter keeps
searching back up the chain of environments -- from most local to top
level -- until it either finds a variable binding for the required
identifier or exhausts the chain.

   This description also determines what happens when there is more than
one variable binding with the same name.  Suppose, continuing the
example of the previous subsection, that there was also a pre-existing
top level variable `s' created by the expression:

     (define s "Some beans, my lord!")

   Then both the top level environment and the local `let' environment
would contain bindings for the name `s'.  When evaluating code within
the `let' body, the interpreter looks first in the local `let'
environment, and so finds the binding for `s' created by the `let'
syntax.  Even though this environment has a reference to the top level
environment, which also has a binding for `s', the interpreter doesn't
get as far as looking there.  When evaluating code outside the `let'
body, the interpreter looks up variable names in the top level
environment, so the name `s' refers to the top level variable.

   Within the `let' body, the binding for `s' in the local environment
is said to "shadow" the binding for `s' in the top level environment.


File: guile.info,  Node: Lexical Scope,  Next: Closure,  Prev: Chaining,  Up: About Closure

Lexical Scope
-------------

   The rules that we have just been describing are the details of how
Scheme implements "lexical scoping".  This subsection takes a brief
diversion to explain what lexical scope means in general and to present
an example of non-lexical scoping.

   "Lexical scope" in general is the idea that

   * an identifier at a particular place in a program always refers to
     the same variable location -- where "always" means "every time
     that the containing expression is executed", and that

   * the variable location to which it refers can be determined by
     static examination of the source code context in which that
     identifier appears, without having to consider the flow of
     execution through the program as a whole.

   In practice, lexical scoping is the norm for most programming
languages, and probably corresponds to what you would intuitively
consider to be "normal".  You may even be wondering how the situation
could possibly -- and usefully -- be otherwise.  To demonstrate that
another kind of scoping is possible, therefore, and to compare it
against lexical scoping, the following subsection presents an example
of non-lexical scoping and examines in detail how its behavior differs
from the corresponding lexically scoped code.

* Menu:

* Scoping Example::             An example of non-lexical scoping.


File: guile.info,  Node: Scoping Example,  Up: Lexical Scope

An Example of Non-Lexical Scoping
.................................

   To demonstrate that non-lexical scoping does exist and can be
useful, we present the following example from Emacs Lisp, which is a
"dynamically scoped" language.

     (defvar currency-abbreviation "USD")
     
     (defun currency-string (units hundredths)
       (concat currency-abbreviation
               (number-to-string units)
               "."
               (number-to-string hundredths)))
     
     (defun french-currency-string (units hundredths)
       (let ((currency-abbreviation "FRF"))
         (currency-string units hundredths)))

   The question to focus on here is: what does the identifier
`currency-abbreviation' refer to in the `currency-string' function?
The answer, in Emacs Lisp, is that all variable bindings go onto a
single stack, and that `currency-abbreviation' refers to the topmost
binding from that stack which has the name "currency-abbreviation".
The binding that is created by the `defvar' form, to the value `"USD"',
is only relevant if none of the code that calls `currency-string'
rebinds the name "currency-abbreviation" in the meanwhile.

   The second function `french-currency-string' works precisely by
taking advantage of this behaviour.  It creates a new binding for the
name "currency-abbreviation" which overrides the one established by the
`defvar' form.

     ;; Note!  This is Emacs Lisp evaluation, not Scheme!
     (french-currency-string 33 44)
     =>
     "FRF33.44"

   Now let's look at the corresponding, _lexically scoped_ Scheme code:

     (define currency-abbreviation "USD")
     
     (define (currency-string units hundredths)
       (string-append currency-abbreviation
                      (number->string units)
                      "."
                      (number->string hundredths)))
     
     (define (french-currency-string units hundredths)
       (let ((currency-abbreviation "FRF"))
         (currency-string units hundredths)))

   According to the rules of lexical scoping, the
`currency-abbreviation' in `currency-string' refers to the variable
location in the innermost environment at that point in the code which
has a binding for `currency-abbreviation', which is the variable
location in the top level environment created by the preceding `(define
currency-abbreviation ...)' expression.

   In Scheme, therefore, the `french-currency-string' procedure does
not work as intended.  The variable binding that it creates for
"currency-abbreviation" is purely local to the code that forms the body
of the `let' expression.  Since this code doesn't directly use the name
"currency-abbreviation" at all, the binding is pointless.

     (french-currency-string 33 44)
     =>
     "USD33.44"

   This begs the question of how the Emacs Lisp behaviour can be
implemented in Scheme.  In general, this is a design question whose
answer depends upon the problem that is being addressed.  In this case,
the best answer may be that `currency-string' should be redesigned so
that it can take an optional third argument.  This third argument, if
supplied, is interpreted as a currency abbreviation that overrides the
default.

   It is possible to change `french-currency-string' so that it mostly
works without changing `currency-string', but the fix is inelegant, and
susceptible to interrupts that could leave the `currency-abbreviation'
variable in the wrong state:

     (define (french-currency-string units hundredths)
       (set! currency-abbreviation "FRF")
       (let ((result (currency-string units hundredths)))
         (set! currency-abbreviation "USD")
         result))

   The key point here is that the code does not create any local binding
for the identifier `currency-abbreviation', so all occurrences of this
identifier refer to the top level variable.


File: guile.info,  Node: Closure,  Next: Serial Number,  Prev: Lexical Scope,  Up: About Closure

Closure
-------

   Consider a `let' expression that doesn't contain any `lambda's:

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

When the Scheme interpreter evaluates this, it

   * creates a new environment with a reference to the environment that
     was current when it encountered the `let'

   * creates a variable binding for `s' in the new environment, with
     value given by `(/ (+ a b c) 2)'

   * evaluates the expression in the body of the `let' in the context of
     the new local environment, and remembers the value `V'

   * forgets the local environment

   * continues evaluating the expression that contained the `let', using
     the value `V' as the value of the `let' expression, in the context
     of the containing environment.

   After the `let' expression has been evaluated, the local environment
that was created is simply forgotten, and there is no longer any way to
access the binding that was created in this environment.  If the same
code is evaluated again, it will follow the same steps again, creating
a second new local environment that has no connection with the first,
and then forgetting this one as well.

   If the `let' body contains a `lambda' expression, however, the local
environment is _not_ forgotten.  Instead, it becomes associated with
the procedure that is created by the `lambda' expression, and is
reinstated every time that that procedure is called.  In detail, this
works as follows.

   * When the Scheme interpreter evaluates a `lambda' expression, to
     create a procedure object, it stores the current environment as
     part of the procedure definition.

   * Then, whenever that procedure is called, the interpreter
     reinstates the environment that is stored in the procedure
     definition and evaluates the procedure body within the context of
     that environment.

   The result is that the procedure body is always evaluated in the
context of the environment that was current when the procedure was
created.

   This is what is meant by "closure".  The next few subsections
present examples that explore the usefulness of this concept.


File: guile.info,  Node: Serial Number,  Next: Shared Variable,  Prev: Closure,  Up: About Closure

Example 1: A Serial Number Generator
------------------------------------

   This example uses closure to create a procedure with a variable
binding that is private to the procedure, like a local variable, but
whose value persists between procedure calls.

     (define (make-serial-number-generator)
       (let ((current-serial-number 0))
         (lambda ()
           (set! current-serial-number (+ current-serial-number 1))
           current-serial-number)))
     
     (define entry-sn-generator (make-serial-number-generator))
     
     (entry-sn-generator)
     =>
     1
     
     (entry-sn-generator)
     =>
     2

   When `make-serial-number-generator' is called, it creates a local
environment with a binding for `current-serial-number' whose initial
value is 0, then, within this environment, creates a procedure.  The
local environment is stored within the created procedure object and so
persists for the lifetime of the created procedure.

   Every time the created procedure is invoked, it increments the value
of the `current-serial-number' binding in the captured environment and
then returns the current value.

   Note that `make-serial-number-generator' can be called again to
create a second serial number generator that is independent of the
first.  Every new invocation of `make-serial-number-generator' creates
a new local `let' environment and returns a new procedure object with
an association to this environment.


File: guile.info,  Node: Shared Variable,  Next: Callback Closure,  Prev: Serial Number,  Up: About Closure

Example 2: A Shared Persistent Variable
---------------------------------------

   This example uses closure to create two procedures, `get-balance'
and `deposit', that both refer to the same captured local environment
so that they can both access the `balance' variable binding inside that
environment.  The value of this variable binding persists between calls
to either procedure.

   Note that the captured `balance' variable binding is private to
these two procedures: it is not directly accessible to any other code.
It can only be accessed indirectly via `get-balance' or `deposit', as
illustrated by the `withdraw' procedure.

     (define get-balance #f)
     (define deposit #f)
     
     (let ((balance 0))
       (set! get-balance
             (lambda ()
               balance))
       (set! deposit
             (lambda (amount)
               (set! balance (+ balance amount))
               balance)))
     
     (define (withdraw amount)
       (deposit (- amount)))
     
     (get-balance)
     =>
     0
     
     (deposit 50)
     =>
     50
     
     (withdraw 75)
     =>
     -25

   An important detail here is that the `get-balance' and `deposit'
variables must be set up by `define'ing them at top level and then
`set!'ing their values inside the `let' body.  Using `define' within
the `let' body would not work: this would create variable bindings
within the local `let' environment that would not be accessible at top
level.


File: guile.info,  Node: Callback Closure,  Next: OO Closure,  Prev: Shared Variable,  Up: About Closure

Example 3: The Callback Closure Problem
---------------------------------------

   A frequently used programming model for library code is to allow an
application to register a callback function for the library to call when
some particular event occurs.  It is often useful for the application to
make several such registrations using the same callback function, for
example if several similar library events can be handled using the same
application code, but the need then arises to distinguish the callback
function calls that are associated with one callback registration from
those that are associated with different callback registrations.

   In languages without the ability to create functions dynamically,
this problem is usually solved by passing a `user_data' parameter on the
registration call, and including the value of this parameter as one of
the parameters on the callback function.  Here is an example of
declarations using this solution in C:

     typedef void (event_handler_t) (int event_type,
                                     void *user_data);
     
     void register_callback (int event_type,
                             event_handler_t *handler,
                             void *user_data);

   In Scheme, closure can be used to achieve the same functionality
without requiring the library code to store a `user-data' for each
callback registration.

     ;; In the library:
     
     (define (register-callback event-type handler-proc)
       ...)
     
     ;; In the application:
     
     (define (make-handler event-type user-data)
       (lambda ()
         ...
         <code referencing event-type and user-data>
         ...))
     
     (register-callback event-type
                        (make-handler event-type ...))

   As far as the library is concerned, `handler-proc' is a procedure
with no arguments, and all the library has to do is call it when the
appropriate event occurs.  From the application's point of view, though,
the handler procedure has used closure to capture an environment that
includes all the context that the handler code needs -- `event-type'
and `user-data' -- to handle the event correctly.


File: guile.info,  Node: OO Closure,  Prev: Callback Closure,  Up: About Closure

Example 4: Object Orientation
-----------------------------

   Closure is the capture of an environment, containing persistent
variable bindings, within the definition of a procedure or a set of
related procedures.  This is rather similar to the idea in some object
oriented languages of encapsulating a set of related data variables
inside an "object", together with a set of "methods" that operate on the
encapsulated data.  The following example shows how closure can be used
to emulate the ideas of objects, methods and encapsulation in Scheme.

     (define (make-account)
       (let ((balance 0))
         (define (get-balance)
           balance)
         (define (deposit amount)
           (set! balance (+ balance amount))
           balance)
         (define (withdraw amount)
           (deposit (- amount)))
     
         (lambda args
           (apply
             (case (car args)
               ((get-balance) get-balance)
               ((deposit) deposit)
               ((withdraw) withdraw)
               (else (error "Invalid method!")))
             (cdr args)))))

   Each call to `make-account' creates and returns a new procedure,
created by the expression in the example code that begins "(lambda
args".

     (define my-account (make-account))
     
     my-account
     =>
     #<procedure args>

   This procedure acts as an account object with methods `get-balance',
`deposit' and `withdraw'.  To apply one of the methods to the account,
you call the procedure with a symbol indicating the required method as
the first parameter, followed by any other parameters that are required
by that method.

     (my-account 'get-balance)
     =>
     0
     
     (my-account 'withdraw 5)
     =>
     -5
     
     (my-account 'deposit 396)
     =>
     391
     
     (my-account 'get-balance)
     =>
     391

   Note how, in this example, both the current balance and the helper
procedures `get-balance', `deposit' and `withdraw', used to implement
the guts of the account object's methods, are all stored in variable
bindings within the private local environment captured by the `lambda'
expression that creates the account object procedure.


File: guile.info,  Node: Further Reading,  Next: Programming Intro,  Prev: Basic Ideas,  Up: Top

Further Reading
***************

   * The website <http://www.schemers.org> is a good starting point for
     all things Scheme.

   * Dorai Sitaram's online Scheme tutorial, "Teach Yourself Scheme in
     Fixnum Days", at
     <http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme.html>.
     Includes a nice explanation of continuations.

   * The complete text of "Structure and Interpretation of Computer
     Programs", the classic introduction to computer science and Scheme
     by Hal Abelson, Jerry Sussman and Julie Sussman, is now available
     online at <http://mitpress.mit.edu/sicp/sicp.html>.  This site
     also provides teaching materials related to the book, and all the
     source code used in the book, in a form suitable for loading and
     running.


File: guile.info,  Node: Programming Intro,  Next: Libguile Intro,  Prev: Further Reading,  Up: Top

Part III: Guile as an Extension Language
****************************************

   In this part of the manual, we aim to present a wide ranging picture
of what it means to use Guile as an application extension language, to
provide guidance, practical guidelines and tips for _how_ to program in
Guile, and to document the tools that are available to help you with
your programming.  For detailed reference information on the variables,
functions etc. that make up Guile's application programming interface
(API), please refer to Part IV (*note Part IV -- Guile API Reference:
Reference Intro.).


File: guile.info,  Node: Libguile Intro,  Next: Programming Overview,  Prev: Programming Intro,  Up: Top

Using Guile as an Extension Language
************************************

   The chapters in this part of the manual explain how to use Guile as a
powerful application extension language.

   An important change for the 1.6.x series of Guile releases is that
the GH interface is now deprecated.  For the reasoning behind this
decision, see *Note GH deprecation::.  The GH interface will continue
to be supported for the 1.6.x and 1.8.x release series, but will be
dropped thereafter, so developers are encouraged to switch
progressively to the scm interface.  The last chapter in this part of
the manual (*note GH::) documents both how to use GH and how to switch
from GH to scm.

   The Guile developers believe that clarification of the GH vs. scm
debate, and the consequent deprecation of the GH interface, are in the
long term interests of the project.  However it does create an
unfortunate situation for developers who want to start a project using
Guile and so read the manual to find out how to proceed.  They will
discover that the GH interface, although quite well documented, is
deprecated, but that there is almost no adequate documentation for its
theoretical replacement, the scm interface.  Moreover, the scm interface
still has the odd few rough edges which need smoothing down.

   Therefore, although deprecated, it is quite OK to continue to use
the GH interface if you feel uncomfortable with the `scm_' interface as
it stands today.  By the time that support for GH is dropped, we plan to
have thoroughly documented the `scm_' interface, and to have enhanced it
such that conversion from GH to the `scm_' interface will be very
straightforward, and probably mostly automated.

   As far as documentation of the scm interface is concerned, the
current position is that it is a bit confused, but that the situation
should improve rapidly once the 1.6.0 release is out.  The plan is to
refocus the bulk of Part II, currently "Guile Scheme", as the "Guile API
Reference" so that it covers both Scheme and C interfaces.  (This makes
sense because almost all of Guile's primitive procedures on the Scheme
level -- e.g. `memq' -- are also available as C level primitives in the
scm interface -- e.g. `scm_memq'.)  There will then remain a certain
amount of Scheme-specific (such as the "Basic Ideas" chapter) and
C-specific documentation (such as SMOB usage and interaction with the
garbage collector) to collect into corresponding chapters.


File: guile.info,  Node: Programming Overview,  Next: Data Representation,  Prev: Libguile Intro,  Up: Top

An Overview of Guile Programming
********************************

   Guile is designed as an extension language interpreter that is
straightforward to integrate with applications written in C (and C++).
The big win here for the application developer is that Guile
integration, as the Guile web page says, "lowers your project's
hacktivation energy."  Lowering the hacktivation energy means that you,
as the application developer, _and your users_, reap the benefits that
flow from being able to extend the application in a high level
extension language rather than in plain old C.

   In abstract terms, it's difficult to explain what this really means
and what the integration process involves, so instead let's begin by
jumping straight into an example of how you might integrate Guile into
an existing program, and what you could expect to gain by so doing.
With that example under our belts, we'll then return to a more general
analysis of the arguments involved and the range of programming options
available.

* Menu:

* Extending Dia::               How one might extend Dia using Guile.
* Scheme vs C::                 Why Scheme is more hackable than C.
* Testbed Example::             Example: using Guile in a testbed.
* Programming Options::         Options for Guile programming.
* User Programming::            How about application users?


File: guile.info,  Node: Extending Dia,  Next: Scheme vs C,  Up: Programming Overview

How One Might Extend Dia Using Guile
====================================

   Dia is a free software program for drawing schematic diagrams like
flow charts and floor plans (REFFIXME).  This section conducts the
thought experiment of adding Guile to Dia.  In so doing, it aims to
illustrate several of the steps and considerations involved in adding
Guile to applications in general.

* Menu:

* Dia Objective::               Deciding why you want to add Guile.
* Dia Steps::                   Four steps required to add Guile.
* Dia Smobs::                   How to represent Dia data in Scheme.
* Dia Primitives::              Writing Guile primitives for Dia.
* Dia Hook::                    Providing a hook for Scheme evaluation.
* Dia Structure::               Overall structure for adding Guile.
* Dia Advanced::                Going further with Dia and Guile.


File: guile.info,  Node: Dia Objective,  Next: Dia Steps,  Up: Extending Dia

Deciding Why You Want to Add Guile
----------------------------------

   First off, you should understand why you want to add Guile to Dia at
all, and that means forming a picture of what Dia does and how it does
it.  So, what are the constituents of the Dia application?

   * Most importantly, the "application domain objects" -- in other
     words, the concepts that differentiate Dia from another
     application such as a word processor or spreadsheet: shapes,
     templates, connectors, pages, plus the properties of all these
     things.

   * The code that manages the graphical face of the application,
     including the layout and display of the objects above.

   * The code that handles input events, which indicate that the
     application user is wanting to do something.

(In other words, a textbook example of the "model - view - controller"
paradigm.)

   Next question: how will Dia benefit once the Guile integration is
complete?  Several (positive!) answers are possible here, and the choice
is obviously up to the application developers.  Still, one answer is
that the main benefit will be the ability to manipulate Dia's
application domain objects from Scheme.

   Suppose that Dia made a set of procedures available in Scheme,
representing the most basic operations on objects such as shapes,
connectors, and so on.  Using Scheme, the application user could then
write code that builds upon these basic operations to create more
complex procedures.  For example, given basic procedures to enumerate
the objects on a page, to determine whether an object is a square, and
to change the fill pattern of a single shape, the user can write a
Scheme procedure to change the fill pattern of all squares on the
current page:

     (define (change-squares'-fill-pattern new-pattern)
       (for-each-shape current-page
         (lambda (shape)
           (if (square? shape)
               (change-fill-pattern shape new-pattern)))))


File: guile.info,  Node: Dia Steps,  Next: Dia Smobs,  Prev: Dia Objective,  Up: Extending Dia

Four Steps Required to Add Guile
--------------------------------

   Assuming this objective, four steps are needed to achieve it.

   First, you need a way of representing your application-specific
objects -- such as `shape' in the previous example -- when they are
passed into the Scheme world.  Unless your objects are so simple that
they map naturally into builtin Scheme data types like numbers and
strings, you will probably want to use Guile's "SMOB" interface to
create a new Scheme data type for your objects.

   Second, you need to write code for the basic operations like
`for-each-shape' and `square?' such that they access and manipulate
your existing data structures correctly, and then make these operations
available as "primitives" on the Scheme level.

   Third, you need to provide some mechanism within the Dia application
that a user can hook into to cause arbitrary Scheme code to be
evaluated.

   Finally, you need to restructure your top-level application C code a
little so that it initializes the Guile interpreter correctly and
declares your "SMOBs" and "primitives" to the Scheme world.

   The following subsections expand on these four points in turn.


File: guile.info,  Node: Dia Smobs,  Next: Dia Primitives,  Prev: Dia Steps,  Up: Extending Dia

How to Represent Dia Data in Scheme
-----------------------------------

   For all but the most trivial applications, you will probably want to
allow some representation of your domain objects to exist on the Scheme
level.  This is where the idea of SMOBs comes in, and with it issues of
lifetime management and garbage collection.

   To get more concrete about this, let's look again at the example we
gave earlier of how application users can use Guile to build
higher-level functions from the primitives that Dia itself provides.

     (define (change-squares'-fill-pattern new-pattern)
       (for-each-shape current-page
         (lambda (shape)
           (if (square? shape)
               (change-fill-pattern shape new-pattern)))))

   Consider what is stored here in the variable `shape'.  For each
shape on the current page, the `for-each-shape' primitive calls
`(lambda (shape) ...)' with an argument representing that shape.
Question is: how is that argument represented on the Scheme level?  The
issues are as follows.

   * Whatever the representation, it has to be decodable again by the C
     code for the `square?' and `change-fill-pattern' primitives.  In
     other words, a primitive like `square?' has somehow to be able to
     turn the value that it receives back into something that points to
     the underlying C structure describing a shape.

   * The representation must also cope with Scheme code holding on to
     the value for later use.  What happens if the Scheme code stores
     `shape' in a global variable, but then that shape is deleted (in a
     way that the Scheme code is not aware of), and later on some other
     Scheme code uses that global variable again in a call to, say,
     `square?'?

   * The lifetime and memory allocation of objects that exist _only_ in
     the Scheme world is managed automatically by Guile's garbage
     collector using one simple rule: when there are no remaining
     references to an object, the object is considered dead and so its
     memory is freed.  But for objects that exist in both C and Scheme,
     the picture is more complicated; in the case of Dia, where the
     `shape' argument passes transiently in and out of the Scheme
     world, it would be quite wrong the *delete* the underlying C shape
     just because the Scheme code has finished evaluation.  How do we
     avoid this happening?

   One resolution of these issues is for the Scheme-level
representation of a shape to be a new, Scheme-specific C structure
wrapped up as a SMOB.  The SMOB is what is passed into and out of
Scheme code, and the Scheme-specific C structure inside the SMOB points
to Dia's underlying C structure so that the code for primitives like
`square?' can get at it.

   To cope with an underlying shape being deleted while Scheme code is
still holding onto a Scheme shape value, the underlying C structure
should have a new field that points to the Scheme-specific SMOB.  When a
shape is deleted, the relevant code chains through to the
Scheme-specific structure and sets its pointer back to the underlying
structure to NULL.  Thus the SMOB value for the shape continues to
exist, but any primitive code that tries to use it will detect that the
underlying shape has been deleted because the underlying structure
pointer is NULL.

   So, to summarize the steps involved in this resolution of the problem
(and assuming that the underlying C structure for a shape is `struct
dia_shape'):

   * Define a new Scheme-specific structure that _points_ to the
     underlying C structure:

          struct dia_guile_shape
          {
            struct dia_shape * c_shape;   /* NULL => deleted */
          }

   * Add a field to `struct dia_shape' that points to its `struct
     dia_guile_shape' if it has one --

          struct dia_shape
          {
            ...
            struct dia_guile_shape * guile_shape;
          }

     -- so that C code can set `guile_shape->c_shape' to NULL when the
     underlying shape is deleted.

   * Wrap `struct dia_guile_shape' as a SMOB type.

   * Whenever you need to represent a C shape onto the Scheme level,
     create a SMOB instance for it, and pass that.

   * In primitive code that receives a shape SMOB instance, check the
     `c_shape' field when decoding it, to find out whether the
     underlying C shape is still there.

   As far as memory management is concerned, the SMOB values and their
Scheme-specific structures are under the control of the garbage
collector, whereas the underlying C structures are explicitly managed in
exactly the same way that Dia managed them before we thought of adding
Guile.

   When the garbage collector decides to free a shape SMOB value, it
calls the "SMOB free" function that was specified when defining the
shape SMOB type.  To maintain the correctness of the `guile_shape' field
in the underlying C structure, this function should chain through to the
underlying C structure (if it still exists) and set its `guile_shape'
field to NULL.

   For full documentation on defining and using SMOB types, see *Note
Defining New Types (Smobs)::.


File: guile.info,  Node: Dia Primitives,  Next: Dia Hook,  Prev: Dia Smobs,  Up: Extending Dia

Writing Guile Primitives for Dia
--------------------------------

   Once the details of object representation are decided, writing the
primitive function code that you need is usually straightforward.

   A primitive is simply a C function whose arguments and return value
are all of type `SCM', and whose body does whatever you want it to do.
As an example, here is a possible implementation of the `square?'
primitive:

     #define FUNC_NAME "square?"
     static SCM square_p (SCM shape)
     {
       struct dia_guile_shape * guile_shape;
     
       /* Check that arg is really a shape SMOB. */
       SCM_VALIDATE_SHAPE (SCM_ARG1, shape);
     
       /* Access Scheme-specific shape structure. */
       guile_shape = SCM_SMOB_DATA (shape);
     
       /* Find out if underlying shape exists and is a
          square; return answer as a Scheme boolean. */
       return SCM_BOOL (guile_shape->c_shape &&
                        (guile_shape->c_shape->type == DIA_SQUARE));
     }
     #undef FUNC_NAME

   Notice how easy it is to chain through from the `SCM shape'
parameter that `square_p' receives -- which is a SMOB -- to the
Scheme-specific structure inside the SMOB, and thence to the underlying
C structure for the shape.

   In this code, `SCM_SMOB_DATA' and `SCM_BOOL' are macros from the
standard Guile API.  `SCM_VALIDATE_SHAPE' is a macro that you should
define as part of your SMOB definition: it checks that the passed
parameter is of the expected type.  This is needed to guard against
Scheme code using the `square?' procedure incorrectly, as in `(square?
"hello")'; Scheme's latent typing means that usage errors like this
must be caught at run time.

   Having written the C code for your primitives, you need to make them
available as Scheme procedures by calling the `scm_c_define_gsubr'
function.  `scm_c_define_gsubr' (REFFIXME) takes arguments that specify
the Scheme-level name for the primitive and how many required, optional
and rest arguments it can accept.  The `square?' primitive always
requires exactly one argument, so the call to make it available in
Scheme reads like this:

     scm_c_define_gsubr ("square?", 1, 0, 0, square_p);

   For where to put this call, see the subsection after next on the
structure of Guile-enabled code (*note Dia Structure::).


File: guile.info,  Node: Dia Hook,  Next: Dia Structure,  Prev: Dia Primitives,  Up: Extending Dia

Providing a Hook for the Evaluation of Scheme Code
--------------------------------------------------

   To make the Guile integration useful, you have to design some kind of
hook into your application that application users can use to cause their
Scheme code to be evaluated.

   Technically, this is straightforward; you just have to decide on a
mechanism that is appropriate for your application.  Think of Emacs, for
example: when you type `<ESC> :', you get a prompt where you can type
in any Elisp code, which Emacs will then evaluate.  Or, again like
Emacs, you could provide a mechanism (such as an init file) to allow
Scheme code to be associated with a particular key sequence, and
evaluate the code when that key sequence is entered.

   In either case, once you have the Scheme code that you want to
evaluate, as a null terminated string, you can tell Guile to evaluate
it by calling the `scm_c_eval_string' function.


File: guile.info,  Node: Dia Structure,  Next: Dia Advanced,  Prev: Dia Hook,  Up: Extending Dia

Top-level Structure of Guile-enabled Dia
----------------------------------------

   Let's assume that the pre-Guile Dia code looks structurally like
this:

   * `main ()'

        * do lots of initialization and setup stuff

        * enter Gtk main loop

   When you add Guile to a program, one (rather technical) requirement
is that Guile's garbage collector needs to know where the bottom of the
C stack is.  The easiest way to ensure this is to use `scm_boot_guile'
like this:

   * `main ()'

        * do lots of initialization and setup stuff

        * `scm_boot_guile (argc, argv, inner_main, NULL)'

   * `inner_main ()'

        * define all SMOB types

        * export primitives to Scheme using `scm_c_define_gsubr'

        * enter Gtk main loop

   In other words, you move the guts of what was previously in your
`main' function into a new function called `inner_main', and then add a
`scm_boot_guile' call, with `inner_main' as a parameter, to the end of
`main'.

   Assuming that you are using SMOBs and have written primitive code as
described in the preceding subsections, you also need to insert calls to
declare your new SMOBs and export the primitives to Scheme.  These
declarations must happen _inside_ the dynamic scope of the
`scm_boot_guile' call, but also _before_ any code is run that could
possibly use them -- the beginning of `inner_main' is an ideal place
for this.


File: guile.info,  Node: Dia Advanced,  Prev: Dia Structure,  Up: Extending Dia

Going Further with Dia and Guile
--------------------------------

   The steps described so far implement an initial Guile integration
that already gives a lot of additional power to Dia application users.
But there are further steps that you could take, and it's interesting to
consider a few of these.

   In general, you could progressively move more of Dia's source code
from C into Scheme.  This might make the code more maintainable and
extensible, and it could open the door to new programming paradigms that
are tricky to effect in C but straightforward in Scheme.

   A specific example of this is that you could use the guile-gtk
package, which provides Scheme-level procedures for most of the Gtk+
library, to move the code that lays out and displays Dia objects from C
to Scheme.

   As you follow this path, it naturally becomes less useful to
maintain a distinction between Dia's original non-Guile-related source
code, and its later code implementing SMOBs and primitives for the
Scheme world.

   For example, suppose that the original source code had a
`dia_change_fill_pattern' function:

     void dia_change_fill_pattern (struct dia_shape * shape,
                                   struct dia_pattern * pattern)
     {
       /* real pattern change work */
     }

   During initial Guile integration, you add a `change_fill_pattern'
primitive for Scheme purposes, which accesses the underlying structures
from its SMOB values and uses `dia_change_fill_pattern' to do the real
work:

     SCM change_fill_pattern (SCM shape, SCM pattern)
     {
       struct dia_shape * d_shape;
       struct dia_pattern * d_pattern;
     
       ...
     
       dia_change_fill_pattern (d_shape, d_pattern);
     
       return SCM_UNSPECIFIED;
     }

   At this point, it makes sense to keep `dia_change_fill_pattern' and
`change_fill_pattern' separate, because `dia_change_fill_pattern' can
also be called without going through Scheme at all, say because the
user clicks a button which causes a C-registered Gtk+ callback to be
called.

   But, if the code for creating buttons and registering their
callbacks is moved into Scheme (using guile-gtk), it may become true
that `dia_change_fill_pattern' can no longer be called other than
through Scheme.  In which case, it makes sense to abolish it and move
its contents directly into `change_fill_pattern', like this:

     SCM change_fill_pattern (SCM shape, SCM pattern)
     {
       struct dia_shape * d_shape;
       struct dia_pattern * d_pattern;
     
       ...
     
       /* real pattern change work */
     
       return SCM_UNSPECIFIED;
     }

   So further Guile integration progressively _reduces_ the amount of
functional C code that you have to maintain over the long term.

   A similar argument applies to data representation.  In the
discussion of SMOBs earlier, issues arose because of the different
memory management and lifetime models that normally apply to data
structures in C and in Scheme.  However, with further Guile
integration, you can resolve this issue in a more radical way by
allowing all your data structures to be under the control of the
garbage collector, and kept alive by references from the Scheme world.
Instead of maintaining an array or linked list of shapes in C, you
would instead maintain a list in Scheme.

   Rather like the coalescing of `dia_change_fill_pattern' and
`change_fill_pattern', the practical upshot of such a change is that
you would no longer have to keep the `dia_shape' and `dia_guile_shape'
structures separate, and so wouldn't need to worry about the pointers
between them.  Instead, you could change the SMOB definition to wrap
the `dia_shape' structure directly, and send `dia_guile_shape' off to
the scrap yard.  Cut out the middle man!

   Finally, we come to the holy grail of Guile's free software /
extension language approach.  Once you have a Scheme representation for
interesting Dia data types like shapes, and a handy bunch of primitives
for manipulating them, it suddenly becomes clear that you have a bundle
of functionality that could have far-ranging use beyond Dia itself.  In
other words, the data types and primitives could now become a library,
and Dia becomes just one of the many possible applications using that
library -- albeit, at this early stage, a rather important one!

   In this model, Guile becomes just the glue that binds everything
together.  Imagine an application that usefully combined functionality
from Dia, Gnumeric and GnuCash -- it's tricky right now, because no
such application yet exists; but it'll happen some day ...


File: guile.info,  Node: Scheme vs C,  Next: Testbed Example,  Prev: Extending Dia,  Up: Programming Overview

Why Scheme is More Hackable Than C
==================================

   Underlying Guile's value proposition is the assumption that
programming in a high level language, specifically Guile's
implementation of Scheme, is necessarily better in some way than
programming in C.  What do we mean by this claim, and how can we be so
sure?

   One class of advantages applies not only to Scheme, but more
generally to any interpretable, high level, scripting language, such as
Emacs Lisp, Python, Ruby, or TeX's macro language.  Common features of
all such languages, when compared to C, are that:

   * They lend themselves to rapid and experimental development cycles,
     owing usually to a combination of their interpretability and the
     integrated development environment in which they are used.

   * They free developers from some of the low level bookkeeping tasks
     associated with C programming, notably memory management.

   * They provide high level features such as container objects and
     exception handling that make common programming tasks easier.

   In the case of Scheme, particular features that make programming
easier -- and more fun! -- are its powerful mechanisms for abstracting
parts of programs (closures -- *note About Closure::) and for iteration
(*note while do::).

   The evidence in support of this argument is empirical: the huge
amount of code that has been written in extension languages for
applications that support this mechanism.  Most notable are extensions
written in Emacs Lisp for GNU Emacs, in TeX's macro language for TeX,
and in Script-Fu for the Gimp, but there is increasingly now a
significant code eco-system for Guile-based applications as well, such
as Lilypond and GnuCash.  It is close to inconceivable that similar
amounts of functionality could have been added to these applications
just by writing new code in their base implementation languages.


File: guile.info,  Node: Testbed Example,  Next: Programming Options,  Prev: Scheme vs C,  Up: Programming Overview

Example: Using Guile for an Application Testbed
===============================================

   As an example of what this means in practice, imagine writing a
testbed for an application that is tested by submitting various
requests (via a C interface) and validating the output received.
Suppose further that the application keeps an idea of its current
state, and that the "correct" output for a given request may depend on
the current application state.  A complete "white box"(1) test plan for
this application would aim to submit all possible requests in each
distinguishable state, and validate the output for all request/state
combinations.

   To write all this test code in C would be very tedious.  Suppose
instead that the testbed code adds a single new C function, to submit an
arbitrary request and return the response, and then uses Guile to export
this function as a Scheme procedure.  The rest of the testbed can then
be written in Scheme, and so benefits from all the advantages of
programming in Scheme that were described in the previous section.

   (In this particular example, there is an additional benefit of
writing most of the testbed in Scheme.  A common problem for white box
testing is that mistakes and mistaken assumptions in the application
under test can easily be reproduced in the testbed code.  It is more
difficult to copy mistakes like this when the testbed is written in a
different language from the application.)

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

   (1) A "white box" test plan is one that incorporates knowledge of
the internal design of the application under test.


File: guile.info,  Node: Programming Options,  Next: User Programming,  Prev: Testbed Example,  Up: Programming Overview

A Choice of Programming Options
===============================

   The preceding arguments and example point to a model of Guile
programming that is applicable in many cases.  According to this model,
Guile programming involves a balance between C and Scheme programming,
with the aim being to extract the greatest possible Scheme level benefit
from the least amount of C level work.

   The C level work required in this model usually consists of packaging
and exporting functions and application objects such that they can be
seen and manipulated on the Scheme level.  To help with this, Guile's C
language interface includes utility features that aim to make this kind
of integration very easy for the application developer.  These features
are documented later in this part of the manual: see REFFIXME.

   This model, though, is really just one of a range of possible
programming options.  If all of the functionality that you need is
available from Scheme, you could choose instead to write your whole
application in Scheme (or one of the other high level languages that
Guile supports through translation), and simply use Guile as an
interpreter for Scheme.  (In the future, we hope that Guile will also be
able to compile Scheme code, so lessening the performance gap between C
and Scheme code.)  Or, at the other end of the C-Scheme scale, you
could write the majority of your application in C, and only call out to
Guile occasionally for specific actions such as reading a configuration
file or executing a user-specified extension.  The choices boil down to
two basic questions:

   * Which parts of the application do you write in C, and which in
     Scheme (or another high level translated language)?

   * How do you design the interface between the C and Scheme parts of
     your application?

   These are of course design questions, and the right design for any
given application will always depend upon the particular requirements
that you are trying to meet.  In the context of Guile, however, there
are some generally applicable considerations that can help you when
designing your answers.

* Menu:

* Available Functionality::     What functionality is already available?
* Basic Constraints::           Functional and performance constraints.
* Style Choices::               Your preferred programming style.
* Program Control::             What controls program execution?


File: guile.info,  Node: Available Functionality,  Next: Basic Constraints,  Up: Programming Options

What Functionality is Already Available?
----------------------------------------

   Suppose, for the sake of argument, that you would prefer to write
your whole application in Scheme.  Then the API available to you
consists of:

   * standard Scheme

   * plus the extensions to standard Scheme provided by Guile in its
     core distribution

   * plus any additional functionality that you or others have packaged
     so that it can be loaded as a Guile Scheme module.

   A module in the last category can either be a pure Scheme module --
in other words a collection of utility procedures coded in Scheme -- or
a module that provides a Scheme interface to an extension library coded
in C -- in other words a nice package where someone else has done the
work of wrapping up some useful C code for you.  The set of available
modules is growing quickly and already includes such useful examples as
`(gtk gtk)', which makes Gtk+ drawing functions available in Scheme,
and `(database postgres)', which provides SQL access to a Postgres
database.

   Given the growing collection of pre-existing modules, it is quite
feasible that your application could be implemented by combining a
selection of these modules together with new application code written in
Scheme.

   If this approach is not enough, because the functionality that your
application needs is not already available in this form, and it is
impossible to write the new functionality in Scheme, you will need to
write some C code.  If the required function is already available in C
(e.g. in a library), all you need is a little glue to connect it to the
world of Guile.  If not, you need both to write the basic code and to
plumb it into Guile.

   In either case, two general considerations are important.  Firstly,
what is the interface by which the functionality is presented to the
Scheme world?  Does the interface consist only of function calls (for
example, a simple drawing interface), or does it need to include
"objects" of some kind that can be passed between C and Scheme and
manipulated by both worlds.  Secondly, how does the lifetime and memory
management of objects in the C code relate to the garbage collection
governed approach of Scheme objects?  In the case where the basic C
code is not already written, most of the difficulties of memory
management can be avoided by using Guile's C interface features from
the start.

   For the full documentation on writing C code for Guile and connecting
existing C code to the Guile world, see REFFIXME.


File: guile.info,  Node: Basic Constraints,  Next: Style Choices,  Prev: Available Functionality,  Up: Programming Options

Functional and Performance Constraints
--------------------------------------


File: guile.info,  Node: Style Choices,  Next: Program Control,  Prev: Basic Constraints,  Up: Programming Options

Your Preferred Programming Style
--------------------------------


File: guile.info,  Node: Program Control,  Prev: Style Choices,  Up: Programming Options

What Controls Program Execution?
--------------------------------


File: guile.info,  Node: User Programming,  Prev: Programming Options,  Up: Programming Overview

How About Application Users?
============================

   So far we have considered what Guile programming means for an
application developer.  But what if you are instead _using_ an existing
Guile-based application, and want to know what your options are for
programming and extending this application?

   The answer to this question varies from one application to another,
because the options available depend inevitably on whether the
application developer has provided any hooks for you to hang your own
code on and, if there are such hooks, what they allow you to do.(1)
For example...

   * If the application permits you to load and execute any Guile code,
     the world is your oyster.  You can extend the application in any
     way that you choose.

   * A more cautious application might allow you to load and execute
     Guile code, but only in a "safe" environment, where the interface
     available is restricted by the application from the standard Guile
     API.

   * Or a really fearful application might not provide a hook to really
     execute user code at all, but just use Scheme syntax as a
     convenient way for users to specify application data or
     configuration options.

   In the last two cases, what you can do is, by definition, restricted
by the application, and you should refer to the application's own
manual to find out your options.

   The most well known example of the first case is Emacs, with its
extension language Emacs Lisp: as well as being a text editor, Emacs
supports the loading and execution of arbitrary Emacs Lisp code.  The
result of such openness has been dramatic: Emacs now benefits from
user-contributed Emacs Lisp libraries that extend the basic editing
function to do everything from reading news to psychoanalysis and
playing adventure games.  The only limitation is that extensions are
restricted to the functionality provided by Emacs's built-in set of
primitive operations.  For example, you can interact and display data by
manipulating the contents of an Emacs buffer, but you can't pop-up and
draw a window with a layout that is totally different to the Emacs
standard.

   This situation with a Guile application that supports the loading of
arbitrary user code is similar, except perhaps even more so, because
Guile also supports the loading of extension libraries written in C.
This last point enables user code to add new primitive operations to
Guile, and so to bypass the limitation present in Emacs Lisp.

   At this point, the distinction between an application developer and
an application user becomes rather blurred.  Instead of seeing yourself
as a user extending an application, you could equally well say that you
are developing a new application of your own using some of the primitive
functionality provided by the original application.  As such, all the
discussions of the preceding sections of this chapter are relevant to
how you can proceed with developing your extension.

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

   (1) Of course, in the world of free software, you always have the
freedom to modify the application's source code to your own
requirements.  Here we are concerned with the extension options that the
application has provided for without your needing to modify its source
code.


File: guile.info,  Node: Data Representation,  Next: GH,  Prev: Programming Overview,  Up: Top

Data Representation in Guile
****************************

   *by Jim Blandy*

   [Due to the rather non-orthogonal and performance-oriented nature of
the SCM interface, you need to understand SCM internals *before* you
can use the SCM API.  That's why this chapter comes first.]

   [NOTE: this is Jim Blandy's essay almost entirely unmodified.  It
has to be adapted to fit this manual smoothly.]

   In order to make sense of Guile's SCM_ functions, or read libguile's
source code, it's essential to have a good grasp of how Guile actually
represents Scheme values.  Otherwise, a lot of the code, and the
conventions it follows, won't make very much sense.  This essay is meant
to provide the background necessary to read and write C code that
manipulates Scheme values in a way that is compatible with libguile.

   We assume you know both C and Scheme, but we do not assume you are
familiar with Guile's implementation.

* Menu:

* Data Representation in Scheme::       Why things aren't just totally
                                        straightforward, in general terms.
* How Guile does it::                   How to write C code that manipulates
                                        Guile values, with an explanation
                                        of Guile's garbage collector.
* Defining New Types (Smobs)::          How to extend Guile with your own
                                        application-specific datatypes.


File: guile.info,  Node: Data Representation in Scheme,  Next: How Guile does it,  Up: Data Representation

Data Representation in Scheme
=============================

   Scheme is a latently-typed language; this means that the system
cannot, in general, determine the type of a given expression at compile
time.  Types only become apparent at run time.  Variables do not have
fixed types; a variable may hold a pair at one point, an integer at the
next, and a thousand-element vector later.  Instead, values, not
variables, have fixed types.

   In order to implement standard Scheme functions like `pair?' and
`string?' and provide garbage collection, the representation of every
value must contain enough information to accurately determine its type
at run time.  Often, Scheme systems also use this information to
determine whether a program has attempted to apply an operation to an
inappropriately typed value (such as taking the `car' of a string).

   Because variables, pairs, and vectors may hold values of any type,
Scheme implementations use a uniform representation for values -- a
single type large enough to hold either a complete value or a pointer
to a complete value, along with the necessary typing information.

   The following sections will present a simple typing system, and then
make some refinements to correct its major weaknesses.  However, this is
not a description of the system Guile actually uses.  It is only an
illustration of the issues Guile's system must address.  We provide all
the information one needs to work with Guile's data in *Note How Guile
does it::.

* Menu:

* A Simple Representation::
* Faster Integers::
* Cheaper Pairs::
* Guile Is Hairier::


File: guile.info,  Node: A Simple Representation,  Next: Faster Integers,  Up: Data Representation in Scheme

A Simple Representation
-----------------------

   The simplest way to meet the above requirements in C would be to
represent each value as a pointer to a structure containing a type
indicator, followed by a union carrying the real value.  Assuming that
`SCM' is the name of our universal type, we can write:

     enum type { integer, pair, string, vector, ... };
     
     typedef struct value *SCM;
     
     struct value {
       enum type type;
       union {
         int integer;
         struct { SCM car, cdr; } pair;
         struct { int length; char *elts; } string;
         struct { int length; SCM  *elts; } vector;
         ...
       } value;
     };
   with the ellipses replaced with code for the remaining Scheme types.

   This representation is sufficient to implement all of Scheme's
semantics.  If X is an `SCM' value:
   *   To test if X is an integer, we can write `X->type == integer'.

   *   To find its value, we can write `X->value.integer'.

   *   To test if X is a vector, we can write `X->type == vector'.

   *   If we know X is a vector, we can write
     `X->value.vector.elts[0]' to refer to its first element.

   *   If we know X is a pair, we can write   `X->value.pair.car' to
     extract its car.


File: guile.info,  Node: Faster Integers,  Next: Cheaper Pairs,  Prev: A Simple Representation,  Up: Data Representation in Scheme

Faster Integers
---------------

   Unfortunately, the above representation has a serious disadvantage.
In order to return an integer, an expression must allocate a `struct
value', initialize it to represent that integer, and return a pointer to
it.  Furthermore, fetching an integer's value requires a memory
reference, which is much slower than a register reference on most
processors.  Since integers are extremely common, this representation is
too costly, in both time and space.  Integers should be very cheap to
create and manipulate.

   One possible solution comes from the observation that, on many
architectures, structures must be aligned on a four-byte boundary.
(Whether or not the machine actually requires it, we can write our own
allocator for `struct value' objects that assures this is true.)  In
this case, the lower two bits of the structure's address are known to
be zero.

   This gives us the room we need to provide an improved representation
for integers.  We make the following rules:
   * If the lower two bits of an `SCM' value are zero, then the SCM
     value is a pointer to a `struct value', and everything proceeds as
     before.

   * Otherwise, the `SCM' value represents an integer, whose value
     appears in its upper bits.

   Here is C code implementing this convention:
     enum type { pair, string, vector, ... };
     
     typedef struct value *SCM;
     
     struct value {
       enum type type;
       union {
         struct { SCM car, cdr; } pair;
         struct { int length; char *elts; } string;
         struct { int length; SCM  *elts; } vector;
         ...
       } value;
     };
     
     #define POINTER_P(x) (((int) (x) & 3) == 0)
     #define INTEGER_P(x) (! POINTER_P (x))
     
     #define GET_INTEGER(x)  ((int) (x) >> 2)
     #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))

   Notice that `integer' no longer appears as an element of `enum
type', and the union has lost its `integer' member.  Instead, we use
the `POINTER_P' and `INTEGER_P' macros to make a coarse classification
of values into integers and non-integers, and do further type testing
as before.

   Here's how we would answer the questions posed above (again, assume
X is an `SCM' value):
   *   To test if X is an integer, we can write `INTEGER_P (X)'.

   *   To find its value, we can write `GET_INTEGER (X)'.

   *   To test if X is a vector, we can write:
            `POINTER_P (X) && X->type == vector'
       Given the new representation, we must make sure X is truly a
     pointer before we dereference it to determine its complete type.

   *   If we know X is a vector, we can write
     `X->value.vector.elts[0]' to refer to its first element, as
     before.

   *   If we know X is a pair, we can write   `X->value.pair.car' to
     extract its car, just as before.

   This representation allows us to operate more efficiently on integers
than the first.  For example, if X and Y are known to be integers, we
can compute their sum as follows:
     MAKE_INTEGER (GET_INTEGER (X) + GET_INTEGER (Y))
   Now, integer math requires no allocation or memory references.  Most
real Scheme systems actually use an even more efficient representation,
but this essay isn't about bit-twiddling.  (Hint: what if pointers had
`01' in their least significant bits, and integers had `00'?)


File: guile.info,  Node: Cheaper Pairs,  Next: Guile Is Hairier,  Prev: Faster Integers,  Up: Data Representation in Scheme

Cheaper Pairs
-------------

   However, there is yet another issue to confront.  Most Scheme heaps
contain more pairs than any other type of object; Jonathan Rees says
that pairs occupy 45% of the heap in his Scheme implementation, Scheme
48.  However, our representation above spends three `SCM'-sized words
per pair -- one for the type, and two for the CAR and CDR.  Is there
any way to represent pairs using only two words?

   Let us refine the convention we established earlier.  Let us assert
that:
   *   If the bottom two bits of an `SCM' value are `#b00', then   it
     is a pointer, as before.

   *   If the bottom two bits are `#b01', then the upper bits are an
     integer.  This is a bit more restrictive than before.

   *   If the bottom two bits are `#b10', then the value, with the
     bottom   two bits masked out, is the address of a pair.

   Here is the new C code:
     enum type { string, vector, ... };
     
     typedef struct value *SCM;
     
     struct value {
       enum type type;
       union {
         struct { int length; char *elts; } string;
         struct { int length; SCM  *elts; } vector;
         ...
       } value;
     };
     
     struct pair {
       SCM car, cdr;
     };
     
     #define POINTER_P(x) (((int) (x) & 3) == 0)
     
     #define INTEGER_P(x)  (((int) (x) & 3) == 1)
     #define GET_INTEGER(x)  ((int) (x) >> 2)
     #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))
     
     #define PAIR_P(x) (((int) (x) & 3) == 2)
     #define GET_PAIR(x) ((struct pair *) ((int) (x) & ~3))

   Notice that `enum type' and `struct value' now only contain
provisions for vectors and strings; both integers and pairs have become
special cases.  The code above also assumes that an `int' is large
enough to hold a pointer, which isn't generally true.

   Our list of examples is now as follows:
   *   To test if X is an integer, we can write `INTEGER_P   (X)'; this
     is as before.

   *   To find its value, we can write `GET_INTEGER (X)', as   before.

   *   To test if X is a vector, we can write:
            `POINTER_P (X) && X->type == vector'
       We must still make sure that X is a pointer to a `struct
     value' before dereferencing it to find its type.

   *   If we know X is a vector, we can write
     `X->value.vector.elts[0]' to refer to its first element, as
     before.

   *   We can write `PAIR_P (X)' to determine if X is a   pair, and
     then write `GET_PAIR (X)->car' to refer to its   car.

   This change in representation reduces our heap size by 15%.  It also
makes it cheaper to decide if a value is a pair, because no memory
references are necessary; it suffices to check the bottom two bits of
the `SCM' value.  This may be significant when traversing lists, a
common activity in a Scheme system.

   Again, most real Scheme systems use a slightly different
implementation; for example, if GET_PAIR subtracts off the low bits of
`x', instead of masking them off, the optimizer will often be able to
combine that subtraction with the addition of the offset of the
structure member we are referencing, making a modified pointer as fast
to use as an unmodified pointer.


File: guile.info,  Node: Guile Is Hairier,  Prev: Cheaper Pairs,  Up: Data Representation in Scheme

Guile Is Hairier
----------------

   We originally started with a very simple typing system -- each object
has a field that indicates its type.  Then, for the sake of efficiency
in both time and space, we moved some of the typing information directly
into the `SCM' value, and left the rest in the `struct value'.  Guile
itself employs a more complex hierarchy, storing finer and finer
gradations of type information in different places, depending on the
object's coarser type.

   In the author's opinion, Guile could be simplified greatly without
significant loss of efficiency, but the simplified system would still be
more complex than what we've presented above.


File: guile.info,  Node: How Guile does it,  Next: Defining New Types (Smobs),  Prev: Data Representation in Scheme,  Up: Data Representation

How Guile does it
=================

   Here we present the specifics of how Guile represents its data.  We
don't go into complete detail; an exhaustive description of Guile's
system would be boring, and we do not wish to encourage people to write
code which depends on its details anyway.  We do, however, present
everything one need know to use Guile's data.

* Menu:

* General Rules::
* Conservative GC::
* Immediates vs Non-immediates::
* Immediate Datatypes::
* Non-immediate Datatypes::
* Signalling Type Errors::
* Unpacking the SCM type::


File: guile.info,  Node: General Rules,  Next: Conservative GC,  Up: How Guile does it

General Rules
-------------

   Any code which operates on Guile datatypes must `#include' the
header file `<libguile.h>'.  This file contains a definition for the
`SCM' typedef (Guile's universal type, as in the examples above), and
definitions and declarations for a host of macros and functions that
operate on `SCM' values.

   All identifiers declared by `<libguile.h>' begin with `scm_' or
`SCM_'.

   The functions described here generally check the types of their
`SCM' arguments, and signal an error if their arguments are of an
inappropriate type.  Macros generally do not, unless that is their
specified purpose.  You must verify their argument types beforehand, as
necessary.

   Macros and functions that return a boolean value have names ending in
`P' or `_p' (for "predicate").  Those that return a negated boolean
value have names starting with `SCM_N'.  For example, `SCM_IMP (X)' is
a predicate which returns non-zero iff X is an immediate value (an
`IM').  `SCM_NCONSP (X)' is a predicate which returns non-zero iff X is
_not_ a pair object (a `CONS').


File: guile.info,  Node: Conservative GC,  Next: Immediates vs Non-immediates,  Prev: General Rules,  Up: How Guile does it

Conservative Garbage Collection
-------------------------------

   Aside from the latent typing, the major source of constraints on a
Scheme implementation's data representation is the garbage collector.
The collector must be able to traverse every live object in the heap, to
determine which objects are not live.

   There are many ways to implement this, but Guile uses an algorithm
called "mark and sweep".  The collector scans the system's global
variables and the local variables on the stack to determine which
objects are immediately accessible by the C code.  It then scans those
objects to find the objects they point to, et cetera.  The collector
sets a "mark bit" on each object it finds, so each object is traversed
only once.  This process is called "tracing".

   When the collector can find no unmarked objects pointed to by marked
objects, it assumes that any objects that are still unmarked will never
be used by the program (since there is no path of dereferences from any
global or local variable that reaches them) and deallocates them.

   In the above paragraphs, we did not specify how the garbage collector
finds the global and local variables; as usual, there are many different
approaches.  Frequently, the programmer must maintain a list of pointers
to all global variables that refer to the heap, and another list
(adjusted upon entry to and exit from each function) of local variables,
for the collector's benefit.

   The list of global variables is usually not too difficult to
maintain, since global variables are relatively rare.  However, an
explicitly maintained list of local variables (in the author's personal
experience) is a nightmare to maintain.  Thus, Guile uses a technique
called "conservative garbage collection", to make the local variable
list unnecessary.

   The trick to conservative collection is to treat the stack as an
ordinary range of memory, and assume that _every_ word on the stack is
a pointer into the heap.  Thus, the collector marks all objects whose
addresses appear anywhere in the stack, without knowing for sure how
that word is meant to be interpreted.

   Obviously, such a system will occasionally retain objects that are
actually garbage, and should be freed.  In practice, this is not a
problem.  The alternative, an explicitly maintained list of local
variable addresses, is effectively much less reliable, due to programmer
error.

   To accommodate this technique, data must be represented so that the
collector can accurately determine whether a given stack word is a
pointer or not.  Guile does this as follows:

   * Every heap object has a two-word header, called a "cell".  Some
     objects, like pairs, fit entirely in a cell's two words; others may
     store pointers to additional memory in either of the words.  For
     example, strings and vectors store their length in the first word,
     and a pointer to their elements in the second.

   * Guile allocates whole arrays of cells at a time, called "heap
     segments".  These segments are always allocated so that the cells
     they contain fall on eight-byte boundaries, or whatever is
     appropriate for the machine's word size.  Guile keeps all cells in
     a heap segment initialized, whether or not they are currently in
     use.

   * Guile maintains a sorted table of heap segments.

   Thus, given any random word W fetched from the stack, Guile's
garbage collector can consult the table to see if W falls within a
known heap segment, and check W's alignment.  If both tests pass, the
collector knows that W is a valid pointer to a cell, intentional or
not, and proceeds to trace the cell.

   Note that heap segments do not contain all the data Guile uses; cells
for objects like vectors and strings contain pointers to other memory
areas.  However, since those pointers are internal, and not shared among
many pieces of code, it is enough for the collector to find the cell,
and then use the cell's type to find more pointers to trace.


File: guile.info,  Node: Immediates vs Non-immediates,  Next: Immediate Datatypes,  Prev: Conservative GC,  Up: How Guile does it

Immediates vs Non-immediates
----------------------------

   Guile classifies Scheme objects into two kinds: those that fit
entirely within an `SCM', and those that require heap storage.

   The former class are called "immediates".  The class of immediates
includes small integers, characters, boolean values, the empty list, the
mysterious end-of-file object, and some others.

   The remaining types are called, not surprisingly, "non-immediates".
They include pairs, procedures, strings, vectors, and all other data
types in Guile.

 - Macro: int SCM_IMP (SCM X)
     Return non-zero iff X is an immediate object.

 - Macro: int SCM_NIMP (SCM X)
     Return non-zero iff X is a non-immediate object.  This is the
     exact complement of `SCM_IMP', above.

   Note that for versions of Guile prior to 1.4 it was necessary to use
the `SCM_NIMP' macro before calling a finer-grained predicate to
determine X's type, such as `SCM_CONSP' or `SCM_VECTORP'.  This is no
longer required: the definitions of all Guile type predicates now
include a call to `SCM_NIMP' where necessary.


File: guile.info,  Node: Immediate Datatypes,  Next: Non-immediate Datatypes,  Prev: Immediates vs Non-immediates,  Up: How Guile does it

Immediate Datatypes
-------------------

   The following datatypes are immediate values; that is, they fit
entirely within an `SCM' value.  The `SCM_IMP' and `SCM_NIMP' macros
will distinguish these from non-immediates; see *Note Immediates vs
Non-immediates:: for an explanation of the distinction.

   Note that the type predicates for immediate values work correctly on
any `SCM' value; you do not need to call `SCM_IMP' first, to establish
that a value is immediate.

* Menu:

* Integer Data::
* Character Data::
* Boolean Data::
* Unique Values::


File: guile.info,  Node: Integer Data,  Next: Character Data,  Up: Immediate Datatypes

Integers
........

   Here are functions for operating on small integers, that fit within
an `SCM'.  Such integers are called "immediate numbers", or "INUMs".
In general, INUMs occupy all but two bits of an `SCM'.

   Bignums and floating-point numbers are non-immediate objects, and
have their own, separate accessors.  The functions here will not work on
them.  This is not as much of a problem as you might think, however,
because the system never constructs bignums that could fit in an INUM,
and never uses floating point values for exact integers.

 - Macro: int SCM_INUMP (SCM X)
     Return non-zero iff X is a small integer value.

 - Macro: int SCM_NINUMP (SCM X)
     The complement of SCM_INUMP.

 - Macro: int SCM_INUM (SCM X)
     Return the value of X as an ordinary, C integer.  If X is not an
     INUM, the result is undefined.

 - Macro: SCM SCM_MAKINUM (int I)
     Given a C integer I, return its representation as an `SCM'.  This
     function does not check for overflow.


File: guile.info,  Node: Character Data,  Next: Boolean Data,  Prev: Integer Data,  Up: Immediate Datatypes

Characters
..........

   Here are functions for operating on characters.

 - Macro: int SCM_CHARP (SCM X)
     Return non-zero iff X is a character value.

 - Macro: unsigned int SCM_CHAR (SCM X)
     Return the value of `x' as a C character.  If X is not a Scheme
     character, the result is undefined.

 - Macro: SCM SCM_MAKE_CHAR (int C)
     Given a C character C, return its representation as a Scheme
     character value.


File: guile.info,  Node: Boolean Data,  Next: Unique Values,  Prev: Character Data,  Up: Immediate Datatypes

Booleans
........

   Here are functions and macros for operating on booleans.

 - Macro: SCM SCM_BOOL_T
 - Macro: SCM SCM_BOOL_F
     The Scheme true and false values.

 - Macro: int SCM_NFALSEP (X)
     Convert the Scheme boolean value to a C boolean.  Since every
     object in Scheme except `#f' is true, this amounts to comparing X
     to `#f'; hence the name.

 - Macro: SCM SCM_BOOL_NOT (X)
     Return the boolean inverse of X.  If X is not a Scheme boolean,
     the result is undefined.


File: guile.info,  Node: Unique Values,  Prev: Boolean Data,  Up: Immediate Datatypes

Unique Values
.............

   The immediate values that are neither small integers, characters, nor
booleans are all unique values -- that is, datatypes with only one
instance.

 - Macro: SCM SCM_EOL
     The Scheme empty list object, or "End Of List" object, usually
     written in Scheme as `'()'.

 - Macro: SCM SCM_EOF_VAL
     The Scheme end-of-file value.  It has no standard written
     representation, for obvious reasons.

 - Macro: SCM SCM_UNSPECIFIED
     The value returned by expressions which the Scheme standard says
     return an "unspecified" value.

     This is sort of a weirdly literal way to take things, but the
     standard read-eval-print loop prints nothing when the expression
     returns this value, so it's not a bad idea to return this when you
     can't think of anything else helpful.

 - Macro: SCM SCM_UNDEFINED
     The "undefined" value.  Its most important property is that is not
     equal to any valid Scheme value.  This is put to various internal
     uses by C code interacting with Guile.

     For example, when you write a C function that is callable from
     Scheme and which takes optional arguments, the interpreter passes
     `SCM_UNDEFINED' for any arguments you did not receive.

     We also use this to mark unbound variables.

 - Macro: int SCM_UNBNDP (SCM X)
     Return true if X is `SCM_UNDEFINED'.  Apply this to a symbol's
     value to see if it has a binding as a global variable.


File: guile.info,  Node: Non-immediate Datatypes,  Next: Signalling Type Errors,  Prev: Immediate Datatypes,  Up: How Guile does it

Non-immediate Datatypes
-----------------------

   A non-immediate datatype is one which lives in the heap, either
because it cannot fit entirely within a `SCM' word, or because it
denotes a specific storage location (in the nomenclature of the
Revised^5 Report on Scheme).

   The `SCM_IMP' and `SCM_NIMP' macros will distinguish these from
immediates; see *Note Immediates vs Non-immediates::.

   Given a cell, Guile distinguishes between pairs and other
non-immediate types by storing special "tag" values in a non-pair
cell's car, that cannot appear in normal pairs.  A cell with a non-tag
value in its car is an ordinary pair.  The type of a cell with a tag in
its car depends on the tag; the non-immediate type predicates test this
value.  If a tag value appears elsewhere (in a vector, for example),
the heap may become corrupted.

   Note how the type information for a non-immediate object is split
between the `SCM' word and the cell that the `SCM' word points to.  The
`SCM' word itself only indicates that the object is non-immediate -- in
other words stored in a heap cell.  The tag stored in the first word of
the heap cell indicates more precisely the type of that object.

   The type predicates for non-immediate values work correctly on any
`SCM' value; you do not need to call `SCM_NIMP' first, to establish
that a value is non-immediate.

* Menu:

* Pair Data::
* Vector Data::
* Procedures::
* Closures::
* Subrs::
* Port Data::


File: guile.info,  Node: Pair Data,  Next: Vector Data,  Up: Non-immediate Datatypes

Pairs
.....

   Pairs are the essential building block of list structure in Scheme.
A pair object has two fields, called the "car" and the "cdr".

   It is conventional for a pair's CAR to contain an element of a list,
and the CDR to point to the next pair in the list, or to contain
`SCM_EOL', indicating the end of the list.  Thus, a set of pairs
chained through their CDRs constitutes a singly-linked list.  Scheme
and libguile define many functions which operate on lists constructed
in this fashion, so although lists chained through the CARs of pairs
will work fine too, they may be less convenient to manipulate, and
receive less support from the community.

   Guile implements pairs by mapping the CAR and CDR of a pair directly
into the two words of the cell.

 - Macro: int SCM_CONSP (SCM X)
     Return non-zero iff X is a Scheme pair object.

 - Macro: int SCM_NCONSP (SCM X)
     The complement of SCM_CONSP.

 - Macro: void SCM_NEWCELL (SCM INTO)
     Allocate a new cell, and set INTO to point to it.  This macro
     expands to a statement, not an expression, and INTO must be an
     lvalue of type SCM.

     This is the most primitive way to allocate a cell; it is quite
     fast.

     The CAR of the cell initially tags it as a "free cell".  If the
     caller intends to use it as an ordinary cons, she must store
     ordinary SCM values in its CAR and CDR.

     If the caller intends to use it as a header for some other type,
     she must store an appropriate magic value in the cell's CAR, to
     mark it as a member of that type, and store whatever value in the
     CDR that type expects.  You should generally not do this, unless
     you are implementing a new datatype, and thoroughly understand the
     code in `<libguile/tags.h>'.

 - Function: SCM scm_cons (SCM CAR, SCM CDR)
     Allocate ("CONStruct") a new pair, with CAR and CDR as its
     contents.

   The macros below perform no type checking.  The results are
undefined if CELL is an immediate.  However, since all non-immediate
Guile objects are constructed from cells, and these macros simply
return the first element of a cell, they actually can be useful on
datatypes other than pairs.  (Of course, it is not very modular to use
them outside of the code which implements that datatype.)

 - Macro: SCM SCM_CAR (SCM CELL)
     Return the CAR, or first field, of CELL.

 - Macro: SCM SCM_CDR (SCM CELL)
     Return the CDR, or second field, of CELL.

 - Macro: void SCM_SETCAR (SCM CELL, SCM X)
     Set the CAR of CELL to X.

 - Macro: void SCM_SETCDR (SCM CELL, SCM X)
     Set the CDR of CELL to X.

 - Macro: SCM SCM_CAAR (SCM CELL)
 - Macro: SCM SCM_CADR (SCM CELL)
 - Macro: SCM SCM_CDAR (SCM CELL) ...
 - Macro: SCM SCM_CDDDDR (SCM CELL)
     Return the CAR of the CAR of CELL, the CAR of the CDR of CELL, et
     cetera.


File: guile.info,  Node: Vector Data,  Next: Procedures,  Prev: Pair Data,  Up: Non-immediate Datatypes

Vectors, Strings, and Symbols
.............................

   Vectors, strings, and symbols have some properties in common.  They
all have a length, and they all have an array of elements.  In the case
of a vector, the elements are `SCM' values; in the case of a string or
symbol, the elements are characters.

   All these types store their length (along with some tagging bits) in
the CAR of their header cell, and store a pointer to the elements in
their CDR.  Thus, the `SCM_CAR' and `SCM_CDR' macros are (somewhat)
meaningful when applied to these datatypes.

 - Macro: int SCM_VECTORP (SCM X)
     Return non-zero iff X is a vector.

 - Macro: int SCM_STRINGP (SCM X)
     Return non-zero iff X is a string.

 - Macro: int SCM_SYMBOLP (SCM X)
     Return non-zero iff X is a symbol.

 - Macro: int SCM_VECTOR_LENGTH (SCM X)
 - Macro: int SCM_STRING_LENGTH (SCM X)
 - Macro: int SCM_SYMBOL_LENGTH (SCM X)
     Return the length of the object X.  The result is undefined if X
     is not a vector, string, or symbol, respectively.

 - Macro: SCM * SCM_VECTOR_BASE (SCM X)
     Return a pointer to the array of elements of the vector X.  The
     result is undefined if X is not a vector.

 - Macro: char * SCM_STRING_CHARS (SCM X)
 - Macro: char * SCM_SYMBOL_CHARS (SCM X)
     Return a pointer to the characters of X.  The result is undefined
     if X is not a symbol or string, respectively.

   There are also a few magic values stuffed into memory before a
symbol's characters, but you don't want to know about those.  What
cruft!


File: guile.info,  Node: Procedures,  Next: Closures,  Prev: Vector Data,  Up: Non-immediate Datatypes

Procedures
..........

   Guile provides two kinds of procedures: "closures", which are the
result of evaluating a `lambda' expression, and "subrs", which are C
functions packaged up as Scheme objects, to make them available to
Scheme programmers.

   (There are actually other sorts of procedures: compiled closures, and
continuations; see the source code for details about them.)

 - Function: SCM scm_procedure_p (SCM X)
     Return `SCM_BOOL_T' iff X is a Scheme procedure object, of any
     sort.  Otherwise, return `SCM_BOOL_F'.


File: guile.info,  Node: Closures,  Next: Subrs,  Prev: Procedures,  Up: Non-immediate Datatypes

Closures
........

   [FIXME: this needs to be further subbed, but texinfo has no
subsubsub]

   A closure is a procedure object, generated as the value of a
`lambda' expression in Scheme.  The representation of a closure is
straightforward -- it contains a pointer to the code of the lambda
expression from which it was created, and a pointer to the environment
it closes over.

   In Guile, each closure also has a property list, allowing the system
to store information about the closure.  I'm not sure what this is used
for at the moment -- the debugger, maybe?

 - Macro: int SCM_CLOSUREP (SCM X)
     Return non-zero iff X is a closure.

 - Macro: SCM SCM_PROCPROPS (SCM X)
     Return the property list of the closure X.  The results are
     undefined if X is not a closure.

 - Macro: void SCM_SETPROCPROPS (SCM X, SCM P)
     Set the property list of the closure X to P.  The results are
     undefined if X is not a closure.

 - Macro: SCM SCM_CODE (SCM X)
     Return the code of the closure X.  The result is undefined if X is
     not a closure.

     This function should probably only be used internally by the
     interpreter, since the representation of the code is intimately
     connected with the interpreter's implementation.

 - Macro: SCM SCM_ENV (SCM X)
     Return the environment enclosed by X.  The result is undefined if
     X is not a closure.

     This function should probably only be used internally by the
     interpreter, since the representation of the environment is
     intimately connected with the interpreter's implementation.


File: guile.info,  Node: Subrs,  Next: Port Data,  Prev: Closures,  Up: Non-immediate Datatypes

Subrs
.....

   [FIXME: this needs to be further subbed, but texinfo has no
subsubsub]

   A subr is a pointer to a C function, packaged up as a Scheme object
to make it callable by Scheme code.  In addition to the function
pointer, the subr also contains a pointer to the name of the function,
and information about the number of arguments accepted by the C
function, for the sake of error checking.

   There is no single type predicate macro that recognizes subrs, as
distinct from other kinds of procedures.  The closest thing is
`scm_procedure_p'; see *Note Procedures::.

 - Macro: char * SCM_SNAME (X)
     Return the name of the subr X.  The result is undefined if X is
     not a subr.

 - Function: SCM scm_c_define_gsubr (char *NAME, int REQ, int OPT, int
          REST, SCM (*FUNCTION)())
     Create a new subr object named NAME, based on the C function
     FUNCTION, make it visible to Scheme the value of as a global
     variable named NAME, and return the subr object.

     The subr object accepts REQ required arguments, OPT optional
     arguments, and a REST argument iff REST is non-zero.  The C
     function FUNCTION should accept `REQ + OPT' arguments, or `REQ +
     OPT + 1' arguments if `rest' is non-zero.

     When a subr object is applied, it must be applied to at least REQ
     arguments, or else Guile signals an error.  FUNCTION receives the
     subr's first REQ arguments as its first REQ arguments.  If there
     are fewer than OPT arguments remaining, then FUNCTION receives the
     value `SCM_UNDEFINED' for any missing optional arguments.  If RST
     is non-zero, then any arguments after the first `REQ + OPT' are
     packaged up as a list as passed as FUNCTION's last argument.

     Note that subrs can actually only accept a predefined set of
     combinations of required, optional, and rest arguments.  For
     example, a subr can take one required argument, or one required
     and one optional argument, but a subr can't take one required and
     two optional arguments.  It's bizarre, but that's the way the
     interpreter was written.  If the arguments to `scm_c_define_gsubr'
     do not fit one of the predefined patterns, then
     `scm_c_define_gsubr' will return a compiled closure object instead
     of a subr object.


File: guile.info,  Node: Port Data,  Prev: Subrs,  Up: Non-immediate Datatypes

Ports
.....

   Haven't written this yet, 'cos I don't understand ports yet.


File: guile.info,  Node: Signalling Type Errors,  Next: Unpacking the SCM type,  Prev: Non-immediate Datatypes,  Up: How Guile does it

Signalling Type Errors
----------------------

   Every function visible at the Scheme level should aggressively check
the types of its arguments, to avoid misinterpreting a value, and
perhaps causing a segmentation fault.  Guile provides some macros to
make this easier.

 - Macro: void SCM_ASSERT (int TEST, SCM OBJ, unsigned int POSITION,
          const char *SUBR)
     If TEST is zero, signal a "wrong type argument" error, attributed
     to the subroutine named SUBR, operating on the value OBJ, which is
     the POSITION'th argument of SUBR.

 - Macro: int SCM_ARG1
 - Macro: int SCM_ARG2
 - Macro: int SCM_ARG3
 - Macro: int SCM_ARG4
 - Macro: int SCM_ARG5
 - Macro: int SCM_ARG6
 - Macro: int SCM_ARG7
     One of the above values can be used for POSITION to indicate the
     number of the argument of SUBR which is being checked.
     Alternatively, a positive integer number can be used, which allows
     to check arguments after the seventh.  However, for parameter
     numbers up to seven it is preferable to use `SCM_ARGN' instead of
     the corresponding raw number, since it will make the code easier to
     understand.

 - Macro: int SCM_ARGn
     Passing a value of zero or `SCM_ARGn' for POSITION allows to leave
     it unspecified which argument's type is incorrect.  Again,
     `SCM_ARGn' should be preferred over a raw zero constant.


File: guile.info,  Node: Unpacking the SCM type,  Prev: Signalling Type Errors,  Up: How Guile does it

Unpacking the SCM Type
----------------------

   The previous sections have explained how `SCM' values can refer to
immediate and non-immediate Scheme objects.  For immediate objects, the
complete object value is stored in the `SCM' word itself, while for
non-immediates, the `SCM' word contains a pointer to a heap cell, and
further information about the object in question is stored in that
cell.  This section describes how the `SCM' type is actually
represented and used at the C level.

   In fact, there are two basic C data types to represent objects in
Guile:

 - Data type: SCM
     `SCM' is the user level abstract C type that is used to represent
     all of Guile's Scheme objects, no matter what the Scheme object
     type is.  No C operation except assignment is guaranteed to work
     with variables of type `SCM', so you should only use macros and
     functions to work with `SCM' values.  Values are converted between
     C data types and the `SCM' type with utility functions and macros.

 - Data type: scm_t_bits
     `scm_t_bits' is an integral data type that is guaranteed to be
     large enough to hold all information that is required to represent
     any Scheme object.  While this data type is mostly used to
     implement Guile's internals, the use of this type is also
     necessary to write certain kinds of extensions to Guile.

* Menu:

* Relationship between SCM and scm_t_bits::
* Immediate objects::
* Non-immediate objects::
* Heap Cell Type Information::
* Accessing Cell Entries::
* Basic Rules for Accessing Cell Entries::


File: guile.info,  Node: Relationship between SCM and scm_t_bits,  Next: Immediate objects,  Up: Unpacking the SCM type

Relationship between `SCM' and `scm_t_bits'
...........................................

   A variable of type `SCM' is guaranteed to hold a valid Scheme
object.  A variable of type `scm_t_bits', on the other hand, may hold a
representation of a `SCM' value as a C integral type, but may also hold
any C value, even if it does not correspond to a valid Scheme object.

   For a variable X of type `SCM', the Scheme object's type information
is stored in a form that is not directly usable.  To be able to work on
the type encoding of the scheme value, the `SCM' variable has to be
transformed into the corresponding representation as a `scm_t_bits'
variable Y by using the `SCM_UNPACK' macro.  Once this has been done,
the type of the scheme object X can be derived from the content of the
bits of the `scm_t_bits' value Y, in the way illustrated by the example
earlier in this chapter (*note Cheaper Pairs::).  Conversely, a valid
bit encoding of a Scheme value as a `scm_t_bits' variable can be
transformed into the corresponding `SCM' value using the `SCM_PACK'
macro.

 - Macro: scm_t_bits SCM_UNPACK (SCM X)
     Transforms the `SCM' value X into its representation as an
     integral type.  Only after applying `SCM_UNPACK' it is possible to
     access the bits and contents of the `SCM' value.

 - Macro: SCM SCM_PACK (scm_t_bits X)
     Takes a valid integral representation of a Scheme object and
     transforms it into its representation as a `SCM' value.


File: guile.info,  Node: Immediate objects,  Next: Non-immediate objects,  Prev: Relationship between SCM and scm_t_bits,  Up: Unpacking the SCM type

Immediate objects
.................

   A Scheme object may either be an immediate, i.e. carrying all
necessary information by itself, or it may contain a reference to a
"cell" with additional information on the heap.  Although in general it
should be irrelevant for user code whether an object is an immediate or
not, within Guile's own code the distinction is sometimes of importance.
Thus, the following low level macro is provided:

 - Macro: int SCM_IMP (SCM X)
     A Scheme object is an immediate if it fulfills the `SCM_IMP'
     predicate, otherwise it holds an encoded reference to a heap cell.
     The result of the predicate is delivered as a C style boolean
     value.  User code and code that extends Guile should normally not
     be required to use this macro.

Summary:
   * Given a Scheme object X of unknown type, check first with `SCM_IMP
     (X)' if it is an immediate object.

   * If so, all of the type and value information can be determined
     from the `scm_t_bits' value that is delivered by `SCM_UNPACK (X)'.


File: guile.info,  Node: Non-immediate objects,  Next: Heap Cell Type Information,  Prev: Immediate objects,  Up: Unpacking the SCM type

Non-immediate objects
.....................

   A Scheme object of type `SCM' that does not fulfill the `SCM_IMP'
predicate holds an encoded reference to a heap cell.  This reference
can be decoded to a C pointer to a heap cell using the `SCM2PTR' macro.
The encoding of a pointer to a heap cell into a `SCM' value is done
using the `PTR2SCM' macro.

 - Macro: (scm_t_cell *) SCM2PTR (SCM X)
     Extract and return the heap cell pointer from a non-immediate `SCM'
     object X.

 - Macro: SCM PTR2SCM (scm_t_cell * X)
     Return a `SCM' value that encodes a reference to the heap cell
     pointer X.

   Note that it is also possible to transform a non-immediate `SCM'
value by using `SCM_UNPACK' into a `scm_t_bits' variable.  However, the
result of `SCM_UNPACK' may not be used as a pointer to a `scm_t_cell':
only `SCM2PTR' is guaranteed to transform a `SCM' object into a valid
pointer to a heap cell.  Also, it is not allowed to apply `PTR2SCM' to
anything that is not a valid pointer to a heap cell.

Summary:
   * Only use `SCM2PTR' on `SCM' values for which `SCM_IMP' is false!

   * Don't use `(scm_t_cell *) SCM_UNPACK (X)'!  Use `SCM2PTR (X)'
     instead!

   * Don't use `PTR2SCM' for anything but a cell pointer!


File: guile.info,  Node: Heap Cell Type Information,  Next: Accessing Cell Entries,  Prev: Non-immediate objects,  Up: Unpacking the SCM type

Heap Cell Type Information
..........................

   Heap cells contain a number of entries, each of which is either a
scheme object of type `SCM' or a raw C value of type `scm_t_bits'.
Which of the cell entries contain Scheme objects and which contain raw C
values is determined by the first entry of the cell, which holds the
cell type information.

 - Macro: scm_t_bits SCM_CELL_TYPE (SCM X)
     For a non-immediate Scheme object X, deliver the content of the
     first entry of the heap cell referenced by X.  This value holds
     the information about the cell type.

 - Macro: void SCM_SET_CELL_TYPE (SCM X, scm_t_bits T)
     For a non-immediate Scheme object X, write the value T into the
     first entry of the heap cell referenced by X.  The value T must
     hold a valid cell type.


File: guile.info,  Node: Accessing Cell Entries,  Next: Basic Rules for Accessing Cell Entries,  Prev: Heap Cell Type Information,  Up: Unpacking the SCM type

Accessing Cell Entries
......................

   For a non-immediate Scheme object X, the object type can be
determined by reading the cell type entry using the `SCM_CELL_TYPE'
macro.  For each different type of cell it is known which cell entries
hold Scheme objects and which cell entries hold raw C data.  To access
the different cell entries appropriately, the following macros are
provided.

 - Macro: scm_t_bits SCM_CELL_WORD (SCM X, unsigned int N)
     Deliver the cell entry N of the heap cell referenced by the
     non-immediate Scheme object X as raw data.  It is illegal, to
     access cell entries that hold Scheme objects by using these
     macros.  For convenience, the following macros are also provided.
        * SCM_CELL_WORD_0 (X) => SCM_CELL_WORD (X, 0)

        * SCM_CELL_WORD_1 (X) => SCM_CELL_WORD (X, 1)

        * ...

        * SCM_CELL_WORD_N (X) => SCM_CELL_WORD (X, N)

 - Macro: SCM SCM_CELL_OBJECT (SCM X, unsigned int N)
     Deliver the cell entry N of the heap cell referenced by the
     non-immediate Scheme object X as a Scheme object.  It is illegal,
     to access cell entries that do not hold Scheme objects by using
     these macros.  For convenience, the following macros are also
     provided.
        * SCM_CELL_OBJECT_0 (X) => SCM_CELL_OBJECT (X, 0)

        * SCM_CELL_OBJECT_1 (X) => SCM_CELL_OBJECT (X, 1)

        * ...

        * SCM_CELL_OBJECT_N (X) => SCM_CELL_OBJECT (X, N)

 - Macro: void SCM_SET_CELL_WORD (SCM X, unsigned int N, scm_t_bits W)
     Write the raw C value W into entry number N of the heap cell
     referenced by the non-immediate Scheme value X.  Values that are
     written into cells this way may only be read from the cells using
     the `SCM_CELL_WORD' macros or, in case cell entry 0 is written,
     using the `SCM_CELL_TYPE' macro.  For the special case of cell
     entry 0 it has to be made sure that W contains a cell type
     information which does not describe a Scheme object.  For
     convenience, the following macros are also provided.
        * SCM_SET_CELL_WORD_0 (X, W) => SCM_SET_CELL_WORD (X, 0, W)

        * SCM_SET_CELL_WORD_1 (X, W) => SCM_SET_CELL_WORD (X, 1, W)

        * ...

        * SCM_SET_CELL_WORD_N (X, W) => SCM_SET_CELL_WORD (X, N, W)

 - Macro: void SCM_SET_CELL_OBJECT (SCM X, unsigned int N, SCM O)
     Write the Scheme object O into entry number N of the heap cell
     referenced by the non-immediate Scheme value X.  Values that are
     written into cells this way may only be read from the cells using
     the `SCM_CELL_OBJECT' macros or, in case cell entry 0 is written,
     using the `SCM_CELL_TYPE' macro.  For the special case of cell
     entry 0 the writing of a Scheme object into this cell is only
     allowed if the cell forms a Scheme pair.  For convenience, the
     following macros are also provided.
        * SCM_SET_CELL_OBJECT_0 (X, O) => SCM_SET_CELL_OBJECT (X, 0, O)

        * SCM_SET_CELL_OBJECT_1 (X, O) => SCM_SET_CELL_OBJECT (X, 1, O)

        * ...

        * SCM_SET_CELL_OBJECT_N (X, O) => SCM_SET_CELL_OBJECT (X, N, O)

Summary:
   * For a non-immediate Scheme object X of unknown type, get the type
     information by using `SCM_CELL_TYPE (X)'.

   * As soon as the cell type information is available, only use the
     appropriate access methods to read and write data to the different
     cell entries.


File: guile.info,  Node: Basic Rules for Accessing Cell Entries,  Prev: Accessing Cell Entries,  Up: Unpacking the SCM type

Basic Rules for Accessing Cell Entries
......................................

   For each cell type it is generally up to the implementation of that
type which of the corresponding cell entries hold Scheme objects and
which hold raw C values.  However, there is one basic rule that has to
be followed: Scheme pairs consist of exactly two cell entries, which
both contain Scheme objects.  Further, a cell which contains a Scheme
object in it first entry has to be a Scheme pair.  In other words, it
is not allowed to store a Scheme object in the first cell entry and a
non Scheme object in the second cell entry.

 - Macro: int SCM_CONSP (SCM X)
     Determine, whether the Scheme object X is a Scheme pair, i.e.
     whether X references a heap cell consisting of exactly two
     entries, where both entries contain a Scheme object.  In this
     case, both entries will have to be accessed using the
     `SCM_CELL_OBJECT' macros.  On the contrary, if the `SCM_CONSP'
     predicate is not fulfilled, the first entry of the Scheme cell is
     guaranteed not to be a Scheme value and thus the first cell entry
     must be accessed using the `SCM_CELL_WORD_0' macro.


File: guile.info,  Node: Defining New Types (Smobs),  Prev: How Guile does it,  Up: Data Representation

Defining New Types (Smobs)
==========================

   "Smobs" are Guile's mechanism for adding new non-immediate types to
the system.(1)  To define a new smob type, the programmer provides
Guile with some essential information about the type -- how to print
it, how to garbage collect it, and so on -- and Guile returns a fresh
type tag for use in the first word of new cells.  The programmer can
then use `scm_c_define_gsubr' to make a set of C functions that create
and operate on these objects visible to Scheme code.

   (You can find a complete version of the example code used in this
section in the Guile distribution, in `doc/example-smob'.  That
directory includes a makefile and a suitable `main' function, so you
can build a complete interactive Guile shell, extended with the
datatypes described here.)

* Menu:

* Describing a New Type::
* Creating Instances::
* Type checking::
* Garbage Collecting Smobs::
* A Common Mistake In Allocating Smobs::
* Garbage Collecting Simple Smobs::
* A Complete Example::

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

   (1) The term "smob" was coined by Aubrey Jaffer, who says it comes
from "small object", referring to the fact that only the CDR and part
of the CAR of a smob's cell are available for use.


File: guile.info,  Node: Describing a New Type,  Next: Creating Instances,  Up: Defining New Types (Smobs)

Describing a New Type
---------------------

   To define a new type, the programmer must write four functions to
manage instances of the type:

`mark'
     Guile will apply this function to each instance of the new type it
     encounters during garbage collection.  This function is
     responsible for telling the collector about any other
     non-immediate objects the object refers to.  The default smob mark
     function is to not mark any data.  *Note Garbage Collecting
     Smobs::, for more details.

`free'
     Guile will apply this function to each instance of the new type it
     could not find any live pointers to.  The function should release
     all resources held by the object and return the number of bytes
     released.  This is analogous to the Java finalization method- it
     is invoked at an unspecified time (when garbage collection occurs)
     after the object is dead.  The default free function frees the
     smob data (if the size of the struct passed to
     `scm_make_smob_type' is non-zero) using `scm_must_free' and
     returns the size of that struct.  *Note Garbage Collecting
     Smobs::, for more details.

`print'
     Guile will apply this function to each instance of the new type to
     print the value, as for `display' or `write'.  The function should
     write a printed representation of EXP on PORT, in accordance with
     the parameters in PSTATE.  (For more information on print states,
     see *Note Port Data::.)  The default print function prints `#<NAME
     ADDRESS>' where `NAME' is the first argument passed to
     `scm_make_smob_type'.

`equalp'
     If Scheme code asks the `equal?' function to compare two instances
     of the same smob type, Guile calls this function.  It should return
     `SCM_BOOL_T' if A and B should be considered `equal?', or
     `SCM_BOOL_F' otherwise.  If `equalp' is `NULL', `equal?' will
     assume that two instances of this type are never `equal?' unless
     they are `eq?'.


   To actually register the new smob type, call `scm_make_smob_type':

 - Function: scm_t_bits scm_make_smob_type (const char *name, size_t
          size)
     This function implements the standard way of adding a new smob
     type, named NAME, with instance size SIZE, to the system.  The
     return value is a tag that is used in creating instances of the
     type.  If SIZE is 0, then no memory will be allocated when
     instances of the smob are created, and nothing will be freed by
     the default free function.  Default values are provided for mark,
     free, print, and, equalp, as described above.  If you want to
     customize any of these functions, the call to `scm_make_smob_type'
     should be immediately followed by calls to one or several of
     `scm_set_smob_mark', `scm_set_smob_free', `scm_set_smob_print',
     and/or `scm_set_smob_equalp'.

   Each of the below `scm_set_smob_XXX' functions registers a smob
special function for a given type.  Each function is intended to be used
only zero or one time per type, and the call should be placed
immediately following the call to `scm_make_smob_type'.

 - Function: void scm_set_smob_mark (scm_t_bits tc, SCM (*mark) (SCM))
     This function sets the smob marking procedure for the smob type
     specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

 - Function: void scm_set_smob_free (scm_t_bits tc, size_t (*free)
          (SCM))
     This function sets the smob freeing procedure for the smob type
     specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

 - Function: void scm_set_smob_print (scm_t_bits tc, int (*print) (SCM,
          SCM, scm_print_state*))
     This function sets the smob printing procedure for the smob type
     specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

 - Function: void scm_set_smob_equalp (scm_t_bits tc, SCM (*equalp)
          (SCM, SCM))
     This function sets the smob equality-testing predicate for the
     smob type specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

   In versions 1.4 and earlier, there was another way of creating smob
types, using `scm_make_smob_type_mfpe'.  This function is now
deprecated and will be removed in a future version of Guile.  You should
use the mechanism described above for new code, and change old code not
to use deprecated features.

   Instead of using `scm_make_smob_type' and calling each of the
individual `scm_set_smob_XXX' functions to register each special
function independently, you could use `scm_make_smob_type_mfpe' to
register all of the special functions at once as you create the smob
type

 - Function: long scm_make_smob_type_mfpe(const char *name, size_t
          size, SCM (*mark) (SCM), size_t (*free) (SCM), int (*print)
          (SCM, SCM, scm_print_state*), SCM (*equalp) (SCM, SCM))
     This function invokes `scm_make_smob_type' on its first two
     arguments to add a new smob type named NAME, with instance size
     SIZE to the system.  It also registers the MARK, FREE, PRINT,
     EQUALP smob special functions for that new type.  Any of these
     parameters can be `NULL' to have that special function use the
     default behavior for guile.  The return value is a tag that is
     used in creating instances of the type.  If SIZE is 0, then no
     memory will be allocated when instances of the smob are created,
     and nothing will be freed by the default free function.

   For example, here is how one might declare and register a new type
representing eight-bit gray-scale images:

     #include <libguile.h>
     
     static scm_t_bits image_tag;
     
     void
     init_image_type (void)
     {
       image_tag = scm_make_smob_type ("image", sizeof (struct image));
       scm_set_smob_mark (image_tag, mark_image);
       scm_set_smob_free (image_tag, free_image);
       scm_set_smob_print (image_tag, print_image);
     }


File: guile.info,  Node: Creating Instances,  Next: Type checking,  Prev: Describing a New Type,  Up: Defining New Types (Smobs)

Creating Instances
------------------

   Like other non-immediate types, smobs start with a cell whose first
word contains typing information, and whose remaining words are free
for any use.

   After the header word containing the type code, smobs can have either
one, two or three additional words of data. These words store either a
pointer to the internal C structure holding the smob-specific data, or
the smob data itself.  To create an instance of a smob type following
these standards, you should use `SCM_NEWSMOB', `SCM_NEWSMOB2' or
`SCM_NEWSMOB3':(1)

 - Macro: void SCM_NEWSMOB(SCM value, scm_t_bits tag, void *data)
 - Macro: void SCM_NEWSMOB2(SCM value, scm_t_bits tag, void *data1,
          void *data2)
 - Macro: void SCM_NEWSMOB3(SCM value, scm_t_bits tag, void *data1,
          void *data2, void *data3)
     Make VALUE contain a smob instance of the type with tag TAG and
     smob data DATA (or DATA1, DATA2, and DATA3).  VALUE must be
     previously declared as C type `SCM'.

   Since it is often the case (e.g., in smob constructors) that you will
create a smob instance and return it, there is also a slightly
specialized macro for this situation:

 - Macro: fn_returns SCM_RETURN_NEWSMOB(scm_t_bits tag, void *data)
 - Macro: fn_returns SCM_RETURN_NEWSMOB2(scm_t_bits tag, void *data1,
          void *data2)
 - Macro: fn_returns SCM_RETURN_NEWSMOB3(scm_t_bits tag, void *data1,
          void *data2, void *data3)
     This macro expands to a block of code that creates a smob instance
     of the type with tag TAG and smob data DATA (or DATA1, DATA2, and
     DATA3), and causes the surrounding function to return that `SCM'
     value.  It should be the last piece of code in a block.

   Guile provides the following functions for managing memory, which are
often helpful when implementing smobs:

 - Function: char * scm_must_malloc (size_t LEN, char *WHAT)
     Allocate LEN bytes of memory, using `malloc', and return a pointer
     to them.

     If there is not enough memory available, invoke the garbage
     collector, and try once more.  If there is still not enough,
     signal an error, reporting that we could not allocate WHAT.

     This function also helps maintain statistics about the size of the
     heap.

 - Function: char * scm_must_realloc (char *ADDR, size_t OLEN, size_t
          LEN, char *WHAT)
     Resize (and possibly relocate) the block of memory at ADDR, to
     have a size of LEN bytes, by calling `realloc'.  Return a pointer
     to the new block.

     If there is not enough memory available, invoke the garbage
     collector, and try once more.  If there is still not enough,
     signal an error, reporting that we could not allocate WHAT.

     The value OLEN should be the old size of the block of memory at
     ADDR; it is only used for keeping statistics on the size of the
     heap.

 - Function: void scm_must_free (char *ADDR)
     Free the block of memory at ADDR, using `free'.  If ADDR is zero,
     signal an error, complaining of an attempt to free something that
     is already free.

     This does no record-keeping; instead, the smob's `free' function
     must take care of that.

     This function isn't usually sufficiently different from the usual
     `free' function to be worth using.

   Continuing the above example, if the global variable `image_tag'
contains a tag returned by `scm_make_smob_type', here is how we could
construct a smob whose CDR contains a pointer to a freshly allocated
`struct image':

     struct image {
       int width, height;
       char *pixels;
     
       /* The name of this image */
       SCM name;
     
       /* A function to call when this image is
          modified, e.g., to update the screen,
          or SCM_BOOL_F if no action necessary */
       SCM update_func;
     };
     
     SCM
     make_image (SCM name, SCM s_width, SCM s_height)
     {
       struct image *image;
       int width, height;
     
       SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image");
       SCM_ASSERT (SCM_INUMP (s_width),  s_width,  SCM_ARG2, "make-image");
       SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
     
       width = SCM_INUM (s_width);
       height = SCM_INUM (s_height);
     
       image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
       image->width = width;
       image->height = height;
       image->pixels = scm_must_malloc (width * height, "image pixels");
       image->name = name;
       image->update_func = SCM_BOOL_F;
     
       SCM_RETURN_NEWSMOB (image_tag, image);
     }

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

   (1) The `SCM_NEWSMOB2' and `SCM_NEWSMOB3' variants will allocate
double cells and thus use twice as much memory as smobs created by
`SCM_NEWSMOB'.


File: guile.info,  Node: Type checking,  Next: Garbage Collecting Smobs,  Prev: Creating Instances,  Up: Defining New Types (Smobs)

Type checking
-------------

   Functions that operate on smobs should aggressively check the types
of their arguments, to avoid misinterpreting some other datatype as a
smob, and perhaps causing a segmentation fault.  Fortunately, this is
pretty simple to do.  The function need only verify that its argument
is a non-immediate, whose first word is the type tag returned by
`scm_make_smob_type'.

   For example, here is a simple function that operates on an image
smob, and checks the type of its argument.  We also present an expanded
version of the `init_image_type' function, to make `clear_image' and
the image constructor function `make_image' visible to Scheme code.

     SCM
     clear_image (SCM image_smob)
     {
       int area;
       struct image *image;
     
       SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
                   image_smob, SCM_ARG1, "clear-image");
     
       image = (struct image *) SCM_SMOB_DATA (image_smob);
       area = image->width * image->height;
       memset (image->pixels, 0, area);
     
       /* Invoke the image's update function.  */
       if (image->update_func != SCM_BOOL_F)
         scm_apply (image->update_func, SCM_EOL, SCM_EOL);
     
       return SCM_UNSPECIFIED;
     }
     
     
     void
     init_image_type (void)
     {
       image_tag = scm_make_smob_type ("image", sizeof (struct image));
       scm_set_smob_mark (image_tag, mark_image);
       scm_set_smob_free (image_tag, free_image);
       scm_set_smob_print (image_tag, print_image);
     
       scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image);
       scm_c_define_gsubr ("make-image", 3, 0, 0, make_image);
     }


File: guile.info,  Node: Garbage Collecting Smobs,  Next: A Common Mistake In Allocating Smobs,  Prev: Type checking,  Up: Defining New Types (Smobs)

Garbage Collecting Smobs
------------------------

   Once a smob has been released to the tender mercies of the Scheme
system, it must be prepared to survive garbage collection.  Guile calls
the `mark' and `free' functions of the `scm_smobfuns' structure to
manage this.

   As described before (*note Conservative GC::), every object in the
Scheme system has a "mark bit", which the garbage collector uses to
tell live objects from dead ones.  When collection starts, every
object's mark bit is clear.  The collector traces pointers through the
heap, starting from objects known to be live, and sets the mark bit on
each object it encounters.  When it can find no more unmarked objects,
the collector walks all objects, live and dead, frees those whose mark
bits are still clear, and clears the mark bit on the others.

   The two main portions of the collection are called the "mark phase",
during which the collector marks live objects, and the "sweep phase",
during which the collector frees all unmarked objects.

   The mark bit of a smob lives in a special memory region.  When the
collector encounters a smob, it sets the smob's mark bit, and uses the
smob's type tag to find the appropriate `mark' function for that smob:
the one listed in that smob's `scm_smobfuns' structure.  It then calls
the `mark' function, passing it the smob as its only argument.

   The `mark' function is responsible for marking any other Scheme
objects the smob refers to.  If it does not do so, the objects' mark
bits will still be clear when the collector begins to sweep, and the
collector will free them.  If this occurs, it will probably break, or at
least confuse, any code operating on the smob; the smob's `SCM' values
will have become dangling references.

   To mark an arbitrary Scheme object, the `mark' function may call
this function:

 - Function: void scm_gc_mark (SCM X)
     Mark the object X, and recurse on any objects X refers to.  If X's
     mark bit is already set, return immediately.

   Thus, here is how we might write the `mark' function for the image
smob type discussed above:

     SCM
     mark_image (SCM image_smob)
     {
       /* Mark the image's name and update function.  */
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
     
       scm_gc_mark (image->name);
       scm_gc_mark (image->update_func);
     
       return SCM_BOOL_F;
     }

   Note that, even though the image's `update_func' could be an
arbitrarily complex structure (representing a procedure and any values
enclosed in its environment), `scm_gc_mark' will recurse as necessary
to mark all its components.  Because `scm_gc_mark' sets an object's
mark bit before it recurses, it is not confused by circular structures.

   As an optimization, the collector will mark whatever value is
returned by the `mark' function; this helps limit depth of recursion
during the mark phase.  Thus, the code above could also be written as:
     SCM
     mark_image (SCM image_smob)
     {
       /* Mark the image's name and update function.  */
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
     
       scm_gc_mark (image->name);
       return image->update_func;
     }

   Finally, when the collector encounters an unmarked smob during the
sweep phase, it uses the smob's tag to find the appropriate `free'
function for the smob.  It then calls the function, passing it the smob
as its only argument.

   The `free' function must release any resources used by the smob.
However, it need not free objects managed by the collector; the
collector will take care of them.  The return type of the `free'
function should be `size_t', an unsigned integral type; the `free'
function should return the number of bytes released, to help the
collector maintain statistics on the size of the heap.

   Here is how we might write the `free' function for the image smob
type:
     size_t
     free_image (SCM image_smob)
     {
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
       size_t size = image->width * image->height + sizeof (*image);
     
       free (image->pixels);
       free (image);
     
       return size;
     }

   During the sweep phase, the garbage collector will clear the mark
bits on all live objects.  The code which implements a smob need not do
this itself.

   There is no way for smob code to be notified when collection is
complete.

   It is usually a good idea to minimize the amount of processing done
during garbage collection; keep `mark' and `free' functions very
simple.  Since collections occur at unpredictable times, it is easy for
any unusual activity to interfere with normal code.


File: guile.info,  Node: A Common Mistake In Allocating Smobs,  Next: Garbage Collecting Simple Smobs,  Prev: Garbage Collecting Smobs,  Up: Defining New Types (Smobs)

A Common Mistake In Allocating Smobs
------------------------------------

   When constructing new objects, you must be careful that the garbage
collector can always find any new objects you allocate.  For example,
suppose we wrote the `make_image' function this way:

     SCM
     make_image (SCM name, SCM s_width, SCM s_height)
     {
       struct image *image;
       SCM image_smob;
       int width, height;
     
       SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image");
       SCM_ASSERT (SCM_INUMP (s_width),  s_width,  SCM_ARG2, "make-image");
       SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
     
       width = SCM_INUM (s_width);
       height = SCM_INUM (s_height);
     
       image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
       image->width = width;
       image->height = height;
       image->pixels = scm_must_malloc (width * height, "image pixels");
     
       /* THESE TWO LINES HAVE CHANGED: */
       image->name = scm_string_copy (name);
       image->update_func = scm_c_define_gsubr (...);
     
       SCM_NEWCELL (image_smob);
       SCM_SET_CELL_WORD_1 (image_smob, image);
       SCM_SET_CELL_TYPE (image_smob, image_tag);
     
       return image_smob;
     }

   This code is incorrect.  The calls to `scm_string_copy' and
`scm_c_define_gsubr' allocate fresh objects.  Allocating any new object
may cause the garbage collector to run.  If `scm_c_define_gsubr'
invokes a collection, the garbage collector has no way to discover that
`image->name' points to the new string object; the `image' structure is
not yet part of any Scheme object, so the garbage collector will not
traverse it.  Since the garbage collector cannot find any references to
the new string object, it will free it, leaving `image' pointing to a
dead object.

   A correct implementation might say, instead:

       image->name = SCM_BOOL_F;
       image->update_func = SCM_BOOL_F;
     
       SCM_NEWCELL (image_smob);
       SCM_SET_CELL_WORD_1 (image_smob, image);
       SCM_SET_CELL_TYPE (image_smob, image_tag);
     
       image->name = scm_string_copy (name);
       image->update_func = scm_c_define_gsubr (...);
     
       return image_smob;

   Now, by the time we allocate the new string and function objects,
`image_smob' points to `image'.  If the garbage collector scans the
stack, it will find a reference to `image_smob' and traverse `image',
so any objects `image' points to will be preserved.


File: guile.info,  Node: Garbage Collecting Simple Smobs,  Next: A Complete Example,  Prev: A Common Mistake In Allocating Smobs,  Up: Defining New Types (Smobs)

Garbage Collecting Simple Smobs
-------------------------------

   It is often useful to define very simple smob types -- smobs which
have no data to mark, other than the cell itself, or smobs whose first
data word is simply an ordinary Scheme object, to be marked recursively.
Guile provides some functions to handle these common cases; you can use
this function as your smob type's `mark' function, if your smob's
structure is simple enough.

   If the smob refers to no other Scheme objects, then no action is
necessary; the garbage collector has already marked the smob cell
itself.  In that case, you can use zero as your mark function.

 - Function: SCM scm_markcdr (SCM X)
     Mark the references in the smob X, assuming that X's first data
     word contains an ordinary Scheme object, and X refers to no other
     objects.  This function simply returns X's first data word.

     This is only useful for simple smobs created by `SCM_NEWSMOB' or
     `SCM_RETURN_NEWSMOB', not for smobs allocated as double cells.

 - Function: size_t scm_free0 (SCM X)
     Do nothing; return zero.  This function is appropriate for smobs
     that use either zero or `scm_markcdr' as their marking functions,
     and refer to no heap storage, including memory managed by `malloc',
     other than the smob's header cell.

     This function should not be needed anymore, because simply passing
     `NULL' as the free function does the same.


File: guile.info,  Node: A Complete Example,  Prev: Garbage Collecting Simple Smobs,  Up: Defining New Types (Smobs)

A Complete Example
------------------

   Here is the complete text of the implementation of the image
datatype, as presented in the sections above.  We also provide a
definition for the smob's `print' function, and make some objects and
functions static, to clarify exactly what the surrounding code is using.

   As mentioned above, you can find this code in the Guile
distribution, in `doc/example-smob'.  That directory includes a
makefile and a suitable `main' function, so you can build a complete
interactive Guile shell, extended with the datatypes described here.)

     /* file "image-type.c" */
     
     #include <stdlib.h>
     #include <libguile.h>
     
     static scm_t_bits image_tag;
     
     struct image {
       int width, height;
       char *pixels;
     
       /* The name of this image */
       SCM name;
     
       /* A function to call when this image is
          modified, e.g., to update the screen,
          or SCM_BOOL_F if no action necessary */
       SCM update_func;
     };
     
     static SCM
     make_image (SCM name, SCM s_width, SCM s_height)
     {
       struct image *image;
       int width, height;
     
       SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image");
       SCM_ASSERT (SCM_INUMP (s_width),  s_width,  SCM_ARG2, "make-image");
       SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");
     
       width = SCM_INUM (s_width);
       height = SCM_INUM (s_height);
     
       image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
       image->width = width;
       image->height = height;
       image->pixels = scm_must_malloc (width * height, "image pixels");
       image->name = name;
       image->update_func = SCM_BOOL_F;
     
       SCM_RETURN_NEWSMOB (image_tag, image);
     }
     
     static SCM
     clear_image (SCM image_smob)
     {
       int area;
       struct image *image;
     
       SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
                   image_smob, SCM_ARG1, "clear-image");
     
       image = (struct image *) SCM_SMOB_DATA (image_smob);
       area = image->width * image->height;
       memset (image->pixels, 0, area);
     
       /* Invoke the image's update function.  */
       if (image->update_func != SCM_BOOL_F)
         scm_apply (image->update_func, SCM_EOL, SCM_EOL);
     
       return SCM_UNSPECIFIED;
     }
     
     static SCM
     mark_image (SCM image_smob)
     {
       /* Mark the image's name and update function.  */
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
     
       scm_gc_mark (image->name);
       return image->update_func;
     }
     
     static size_t
     free_image (SCM image_smob)
     {
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
       size_t size = image->width * image->height + sizeof (struct image);
     
       free (image->pixels);
       free (image);
     
       return size;
     }
     
     static int
     print_image (SCM image_smob, SCM port, scm_print_state *pstate)
     {
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
     
       scm_puts ("#<image ", port);
       scm_display (image->name, port);
       scm_puts (">", port);
     
       /* non-zero means success */
       return 1;
     }
     
     void
     init_image_type (void)
     {
       image_tag = scm_make_smob_type ("image", sizeof (struct image));
       scm_set_smob_mark (image_tag, mark_image);
       scm_set_smob_free (image_tag, free_image);
       scm_set_smob_print (image_tag, print_image);
     
       scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image);
       scm_c_define_gsubr ("make-image", 3, 0, 0, make_image);
     }

   Here is a sample build and interaction with the code from the
`example-smob' directory, on the author's machine:

     zwingli:example-smob$ make CC=gcc
     gcc `guile-config compile`   -c image-type.c -o image-type.o
     gcc `guile-config compile`   -c myguile.c -o myguile.o
     gcc image-type.o myguile.o `guile-config link` -o myguile
     zwingli:example-smob$ ./myguile
     guile> make-image
     #<primitive-procedure make-image>
     guile> (define i (make-image "Whistler's Mother" 100 100))
     guile> i
     #<image Whistler's Mother>
     guile> (clear-image i)
     guile> (clear-image 4)
     ERROR: In procedure clear-image in expression (clear-image 4):
     ERROR: Wrong type argument in position 1: 4
     ABORT: (wrong-type-arg)
     
     Type "(backtrace)" to get more information.
     guile>


File: guile.info,  Node: GH,  Next: Reference Intro,  Prev: Data Representation,  Up: Top

GH: A Portable C to Scheme Interface
************************************

   This chapter shows how to use the GH interface to call Guile from
your application's C code, and to add new Scheme level procedures to
Guile whose behaviour is specified by application specific code written
in C.

   Note, however, that the GH interface is now deprecated, and
developers are encouraged to switch to using the scm interface instead.
Therefore, for each GH feature, this chapter should also document how
to achieve the same result using the scm interface.

* Menu:

* GH deprecation::              Why the GH interface is now deprecated.
* gh preliminaries::
* Data types and constants defined by gh::
* Starting and controlling the interpreter::
* Error messages::
* Executing Scheme code::
* Defining new Scheme procedures in C::
* Converting data between C and Scheme::
* Type predicates::
* Equality predicates::
* Memory allocation and garbage collection::
* Calling Scheme procedures from C::
* Mixing gh and scm APIs::
* scm transition summary::


File: guile.info,  Node: GH deprecation,  Next: gh preliminaries,  Up: GH

Why the GH Interface is Now Deprecated
======================================

   Historically, the GH interface was the product of a practical problem
and a neat idea.  The practical problem was that the interface of the
`scm_' functions with which Guile itself was written (inherited from
Aubrey Jaffer's SCM) was so closely tied to the (rather arcane) details
of the internal data representation that it was extremely difficult to
write a Guile extension using these functions.  The neat idea was to
define a high level language extension interface in such a way that
other extension language projects, not just Guile, would be able to
provide an implementation of that interface; then applications using
this interface could be compiled with whichever of the various
available implementations they chose.  So the GH interface was created,
and advertised both as the recommended interface for application
developers wishing to use Guile, and as a portable high level interface
that could theoretically be implemented by other extension language
projects.

   Time passed, and various things changed.  Crucially, an enormous
number of improvements were made to the `scm_' interface that Guile
itself uses in its implementation, with the result that it is now both
easy and comfortable to write a Guile extension with this interface.
At the same time, the contents of the GH interface were somewhat
neglected by the core Guile developers, such that some key operations
-- such as smob creation and management -- are simply not possible
using GH alone.  Finally, the idea of multiple implementations of the
GH interface did not really crystallize (apart, I believe, from a short
lived implementation by the MzScheme project).

   For all these reasons, the Guile developers have decided to deprecate
the GH interface -- which means that support for GH will be completely
removed after the next few releases -- and to focus only on the `scm_'
interface, with additions to ensure that it is as easy to use in all
respects as GH was.

   It remains an open question whether a deep kind of interface
portability would be useful for extension language-based applications,
and it may still be an interesting project to attempt to define a
corresponding GH-like interface, but the Guile developers no longer
plan to try to do this as part of the core Guile project.


File: guile.info,  Node: gh preliminaries,  Next: Data types and constants defined by gh,  Prev: GH deprecation,  Up: GH

gh preliminaries
================

   To use gh, you must have the following toward the beginning of your C
source:
     #include <guile/gh.h>

   When you link, you will have to add at least `-lguile' to the list
of libraries.  If you are using more of Guile than the basic Scheme
interpreter, you will have to add more libraries.


File: guile.info,  Node: Data types and constants defined by gh,  Next: Starting and controlling the interpreter,  Prev: gh preliminaries,  Up: GH

Data types and constants defined by gh
======================================

   The following C constants and data types are defined in gh:

   `SCM' is a C data type used to store all Scheme data, no matter what
the Scheme type.  Values are converted between C data types and the SCM
type with utility functions described below (*note Converting data
between C and Scheme::).  [FIXME: put in references to Jim's essay and
so forth.]

 - Constant: SCM_BOOL_T
 - Constant: SCM_BOOL_F
     The _Scheme_ values returned by many boolean procedures in
     libguile.

     This can cause confusion because they are different from 0 and 1.
     In testing a boolean function in libguile programming, you must
     always make sure that you check the spec: `gh_' and `scm_'
     functions will usually return `SCM_BOOL_T' and `SCM_BOOL_F', but
     other C functions usually can be tested against 0 and 1, so
     programmers' fingers tend to just type `if (boolean_function()) {
     ... }'

 - Constant: SCM_UNSPECIFIED
     This is a SCM value that is not the same as any legal Scheme
     value.  It is the value that a Scheme function returns when its
     specification says that its return value is unspecified.

 - Constant: SCM_UNDEFINED
     This is another SCM value that is not the same as any legal Scheme
     value.  It is the value used to mark variables that do not yet
     have a value, and it is also used in C to terminate functions with
     variable numbers of arguments, such as `gh_list()'.


File: guile.info,  Node: Starting and controlling the interpreter,  Next: Error messages,  Prev: Data types and constants defined by gh,  Up: GH

Starting and controlling the interpreter
========================================

   In almost every case, your first `gh_' call will be:

 - Function: void gh_enter (int ARGC, char *ARGV[], void (*MAIN_PROG)())
     Starts up a Scheme interpreter with all the builtin Scheme
     primitives.  `gh_enter()' never exits, and the user's code should
     all be in the `MAIN_PROG()' function.  `argc' and `argv' will be
     passed to MAIN_PROG.

      - Function: void main_prog (int ARGC, char *ARGV[])
          This is the user's main program.  It will be invoked by
          `gh_enter()' after Guile has been started up.

     Note that you can use `gh_repl' inside `gh_enter' (in other words,
     inside the code for `main-prog') if you want the program to be
     controlled by a Scheme read-eval-print loop.

   A convenience routine which enters the Guile interpreter with the
standard Guile read-eval-print loop ("REPL") is:

 - Function: void gh_repl (int ARGC, char *ARGV[])
     Enters the Scheme interpreter giving control to the Scheme REPL.
     Arguments are processed as if the Guile program `guile' were being
     invoked.

     Note that `gh_repl' should be used _inside_ `gh_enter', since any
     Guile interpreter calls are meaningless unless they happen in the
     context of the interpreter.

     Also note that when you use `gh_repl', your program will be
     controlled by Guile's REPL (which is written in Scheme and has many
     useful features).  Use straight C code inside `gh_enter' if you
     want to maintain execution control in your C program.

   You will typically use `gh_enter' and `gh_repl' when you want a
Guile interpreter enhanced by your own libraries, but otherwise quite
normal.  For example, to build a Guile-derived program that includes
some random number routines "GSL" (GNU Scientific Library), you would
write a C program that looks like this:

     #include <guile/gh.h>
     #include <gsl_ran.h>
     
     /* random number suite */
     SCM gw_ran_seed(SCM s)
     {
       gsl_ran_seed(gh_scm2int(s));
       return SCM_UNSPECIFIED;
     }
     
     SCM gw_ran_random()
     {
       SCM x;
     
       x = gh_ulong2scm(gsl_ran_random());
       return x;
     }
     
     SCM gw_ran_uniform()
     {
       SCM x;
     
       x = gh_double2scm(gsl_ran_uniform());
       return x;
     }
     SCM gw_ran_max()
     {
       return gh_double2scm(gsl_ran_max());
     }
     
     void
     init_gsl()
     {
       /* random number suite */
       gh_new_procedure("gsl-ran-seed", gw_ran_seed, 1, 0, 0);
       gh_new_procedure("gsl-ran-random", gw_ran_random, 0, 0, 0);
       gh_new_procedure("gsl-ran-uniform", gw_ran_uniform, 0, 0, 0);
       gh_new_procedure("gsl-ran-max", gw_ran_max, 0, 0, 0);
     }
     
     void
     main_prog (int argc, char *argv[])
     {
       init_gsl();
     
       gh_repl(argc, argv);
     }
     
     int
     main (int argc, char *argv[])
     {
       gh_enter (argc, argv, main_prog);
     }

   Then, supposing the C program is in `guile-gsl.c', you could compile
it with `gcc -o guile-gsl guile-gsl.c -lguile -lgsl'.

   The resulting program `guile-gsl' would have new primitive
procedures `gsl-ran-random', `gsl-ran-gaussian' and so forth.


File: guile.info,  Node: Error messages,  Next: Executing Scheme code,  Prev: Starting and controlling the interpreter,  Up: GH

Error messages
==============

   [FIXME: need to fill this based on Jim's new mechanism]


File: guile.info,  Node: Executing Scheme code,  Next: Defining new Scheme procedures in C,  Prev: Error messages,  Up: GH

Executing Scheme code
=====================

   Once you have an interpreter running, you can ask it to evaluate
Scheme code.  There are two calls that implement this:

 - Function: SCM gh_eval_str (char *SCHEME_CODE)
     This asks the interpreter to evaluate a single string of Scheme
     code, and returns the result of the last expression evaluated.

     Note that the line of code in SCHEME_CODE must be a well formed
     Scheme expression.  If you have many lines of code before you
     balance parentheses, you must either concatenate them into one
     string, or use `gh_eval_file()'.

 - Function: SCM gh_eval_file (char *FNAME)
 - Function: SCM gh_load (char *FNAME)
     `gh_eval_file' is completely analogous to `gh_eval_str()', except
     that a whole file is evaluated instead of a string.
     `gh_eval_file' returns `SCM_UNSPECIFIED'.

     `gh_load' is identical to `gh_eval_file' (it's a macro that calls
     `gh_eval_file' on its argument).  It is provided to start making
     the `gh_' interface match the R5RS Scheme procedures closely.


File: guile.info,  Node: Defining new Scheme procedures in C,  Next: Converting data between C and Scheme,  Prev: Executing Scheme code,  Up: GH

Defining new Scheme procedures in C
===================================

   The real interface between C and Scheme comes when you can write new
Scheme procedures in C.  This is done through the routine

 - Libguile high: SCM gh_new_procedure (char *PROC_NAME, SCM (*FN)(),
          int N_REQUIRED_ARGS, int N_OPTIONAL_ARGS, int RESTP)
     `gh_new_procedure' defines a new Scheme procedure.  Its Scheme name
     will be PROC_NAME, it will be implemented by the C function
     (*FN)(), it will take at least N_REQUIRED_ARGS arguments, and at
     most N_OPTIONAL_ARGS extra arguments.

     When the RESTP parameter is 1, the procedure takes a final
     argument: a list of remaining parameters.

     `gh_new_procedure' returns an SCM value representing the procedure.

     The C function FN should have the form

      - Libguile high: SCM fn (SCM REQ1, SCM REQ2, ..., SCM OPT1, SCM
               OPT2, ..., SCM REST_ARGS)
          The arguments are all passed as SCM values, so the user will
          have to use the conversion functions to convert to standard C
          types.

          Examples of C functions used as new Scheme primitives can be
          found in the sample programs `learn0' and `learn1'.


   *Rationale:* this is the correct way to define new Scheme procedures
in C.  The ugly mess of arguments is required because of how C handles
procedures with variable numbers of arguments.

   *Note:* what about documentation strings?

   There are several important considerations to be made when writing
the C routine `(*fn)()'.

   First of all the C routine has to return type `SCM'.

   Second, all arguments passed to the C function will be of type `SCM'.

   Third: the C routine is now subject to Scheme flow control, which
means that it could be interrupted at any point, and then reentered.
This means that you have to be very careful with operations such as
allocating memory, modifying static data ...

   Fourth: to get around the latter issue, you can use `GH_DEFER_INTS'
and `GH_ALLOW_INTS'.

 - Macro: GH_DEFER_INTS
 - Macro: GH_ALLOW_INTS
     These macros disable and re-enable Scheme's flow control.  They


File: guile.info,  Node: Converting data between C and Scheme,  Next: Type predicates,  Prev: Defining new Scheme procedures in C,  Up: GH

Converting data between C and Scheme
====================================

   Guile provides mechanisms to convert data between C and Scheme.  This
allows new builtin procedures to understand their arguments (which are
of type `SCM') and return values of type `SCM'.

* Menu:

* C to Scheme::
* Scheme to C::


File: guile.info,  Node: C to Scheme,  Next: Scheme to C,  Up: Converting data between C and Scheme

C to Scheme
-----------

 - Function: SCM gh_bool2scm (int X)
     Returns `#f' if X is zero, `#t' otherwise.

 - Function: SCM gh_ulong2scm (unsigned long X)
 - Function: SCM gh_long2scm (long X)
 - Function: SCM gh_double2scm (double X)
 - Function: SCM gh_char2scm (char X)
     Returns a Scheme object with the value of the C quantity X.

 - Function: SCM gh_str2scm (char *S, int LEN)
     Returns a new Scheme string with the (not necessarily
     null-terminated) C array S data.

 - Function: SCM gh_str02scm (char *S)
     Returns a new Scheme string with the null-terminated C string S
     data.

 - Function: SCM gh_set_substr (char *SRC, SCM DST, int START, int LEN)
     Copy LEN characters at SRC into the _existing_ Scheme string DST,
     starting at START.  START is an index into DST; zero means the
     beginning of the string.

     If START + LEN is off the end of DST, signal an out-of-range error.

 - Function: SCM gh_symbol2scm (char *NAME)
     Given a null-terminated string NAME, return the symbol with that
     name.

 - Function: SCM gh_ints2scm (int *DPTR, int N)
 - Function: SCM gh_doubles2scm (double *DPTR, int N)
     Make a scheme vector containing the N ints or doubles at memory
     location DPTR.

 - Function: SCM gh_chars2byvect (char *DPTR, int N)
 - Function: SCM gh_shorts2svect (short *DPTR, int N)
 - Function: SCM gh_longs2ivect (long *DPTR, int N)
 - Function: SCM gh_ulongs2uvect (ulong *DPTR, int N)
 - Function: SCM gh_floats2fvect (float *DPTR, int N)
 - Function: SCM gh_doubles2dvect (double *DPTR, int N)
     Make a scheme uniform vector containing the N chars, shorts,
     longs, unsigned longs, floats or doubles at memory location DPTR.


File: guile.info,  Node: Scheme to C,  Prev: C to Scheme,  Up: Converting data between C and Scheme

Scheme to C
-----------

 - Function: int gh_scm2bool (SCM OBJ)
 - Function: unsigned long gh_scm2ulong (SCM OBJ)
 - Function: long gh_scm2long (SCM OBJ)
 - Function: double gh_scm2double (SCM OBJ)
 - Function: int gh_scm2char (SCM OBJ)
     These routines convert the Scheme object to the given C type.

 - Function: char *gh_scm2newstr (SCM STR, int *LENP)
     Given a Scheme string STR, return a pointer to a new copy of its
     contents, followed by a null byte.  If LENP is non-null, set
     `*LENP' to the string's length.

     This function uses malloc to obtain storage for the copy; the
     caller is responsible for freeing it.

     Note that Scheme strings may contain arbitrary data, including null
     characters.  This means that null termination is not a reliable
     way to determine the length of the returned value.  However, the
     function always copies the complete contents of STR, and sets *LENP
     to the true length of the string (when LENP is non-null).

 - Function: void gh_get_substr (SCM str, char *return_str, int *lenp)
     Copy LEN characters at START from the Scheme string SRC to memory
     at DST.  START is an index into SRC; zero means the beginning of
     the string.  DST has already been allocated by the caller.

     If START + LEN is off the end of SRC, signal an out-of-range error.

 - Function: char *gh_symbol2newstr (SCM SYM, int *LENP)
     Takes a Scheme symbol and returns a string of the form
     `"'symbol-name"'.  If LENP is non-null, the string's length is
     returned in `*LENP'.

     This function uses malloc to obtain storage for the returned
     string; the caller is responsible for freeing it.

 - Function: char *gh_scm2chars (SCM VECTOR, chars *RESULT)
 - Function: short *gh_scm2shorts (SCM VECTOR, short *RESULT)
 - Function: long *gh_scm2longs (SCM VECTOR, long *RESULT)
 - Function: float *gh_scm2floats (SCM VECTOR, float *RESULT)
 - Function: double *gh_scm2doubles (SCM VECTOR, double *RESULT)
     Copy the numbers in VECTOR to the array pointed to by RESULT and
     return it.  If RESULT is NULL, allocate a double array large
     enough.

     VECTOR can be an ordinary vector, a weak vector, or a signed or
     unsigned uniform vector of the same type as the result array.  For
     chars, VECTOR can be a string or substring.  For floats and
     doubles, VECTOR can contain a mix of inexact and integer values.

     If VECTOR is of unsigned type and contains values too large to fit
     in the signed destination array, those values will be wrapped
     around, that is, data will be copied as if the destination array
     was unsigned.


File: guile.info,  Node: Type predicates,  Next: Equality predicates,  Prev: Converting data between C and Scheme,  Up: GH

Type predicates
===============

   These C functions mirror Scheme's type predicate procedures with one
important difference.  The C routines return C boolean values (0 and 1)
instead of `SCM_BOOL_T' and `SCM_BOOL_F'.

   The Scheme notational convention of putting a `?' at the end of
predicate procedure names is mirrored in C by placing `_p' at the end
of the procedure.  For example, `(pair? ...)' maps to `gh_pair_p(...)'.

 - Function: int gh_boolean_p (SCM VAL)
     Returns 1 if VAL is a boolean, 0 otherwise.

 - Function: int gh_symbol_p (SCM VAL)
     Returns 1 if VAL is a symbol, 0 otherwise.

 - Function: int gh_char_p (SCM VAL)
     Returns 1 if VAL is a char, 0 otherwise.

 - Function: int gh_vector_p (SCM VAL)
     Returns 1 if VAL is a vector, 0 otherwise.

 - Function: int gh_pair_p (SCM VAL)
     Returns 1 if VAL is a pair, 0 otherwise.

 - Function: int gh_procedure_p (SCM VAL)
     Returns 1 if VAL is a procedure, 0 otherwise.

 - Function: int gh_list_p (SCM VAL)
     Returns 1 if VAL is a list, 0 otherwise.

 - Function: int gh_inexact_p (SCM VAL)
     Returns 1 if VAL is an inexact number, 0 otherwise.

 - Function: int gh_exact_p (SCM VAL)
     Returns 1 if VAL is an exact number, 0 otherwise.


File: guile.info,  Node: Equality predicates,  Next: Memory allocation and garbage collection,  Prev: Type predicates,  Up: GH

Equality predicates
===================

   These C functions mirror Scheme's equality predicate procedures with
one important difference.  The C routines return C boolean values (0
and 1) instead of `SCM_BOOL_T' and `SCM_BOOL_F'.

   The Scheme notational convention of putting a `?' at the end of
predicate procedure names is mirrored in C by placing `_p' at the end
of the procedure.  For example, `(equal? ...)' maps to
`gh_equal_p(...)'.

 - Function: int gh_eq_p (SCM x, SCM y)
     Returns 1 if X and Y are equal in the sense of Scheme's `eq?'
     predicate, 0 otherwise.

 - Function: int gh_eqv_p (SCM x, SCM y)
     Returns 1 if X and Y are equal in the sense of Scheme's `eqv?'
     predicate, 0 otherwise.

 - Function: int gh_equal_p (SCM x, SCM y)
     Returns 1 if X and Y are equal in the sense of Scheme's `equal?'
     predicate, 0 otherwise.

 - Function: int gh_string_equal_p (SCM S1, SCM S2)
     Returns 1 if the strings S1 and S2 are equal, 0 otherwise.

 - Function: int gh_null_p (SCM L)
     Returns 1 if L is an empty list or pair; 0 otherwise.


File: guile.info,  Node: Memory allocation and garbage collection,  Next: Calling Scheme procedures from C,  Prev: Equality predicates,  Up: GH

Memory allocation and garbage collection
========================================


File: guile.info,  Node: Calling Scheme procedures from C,  Next: Mixing gh and scm APIs,  Prev: Memory allocation and garbage collection,  Up: GH

Calling Scheme procedures from C
================================

   Many of the Scheme primitives are available in the `gh_' interface;
they take and return objects of type SCM, and one could basically use
them to write C code that mimics Scheme code.

   I will list these routines here without much explanation, since what
they do is the same as documented in *Note R5RS: (r5rs)Standard
procedures.  But I will point out that when a procedure takes a
variable number of arguments (such as `gh_list'), you should pass the
constant SCM_UNDEFINED from C to signify the end of the list.

 - Function: SCM gh_define (char *NAME, SCM VAL)
     Corresponds to the Scheme `(define name val)': it binds a value to
     the given name (which is a C string).  Returns the new object.

Pairs and lists
===============

 - Function: SCM gh_cons (SCM A, SCM B)
 - Function: SCM gh_list (SCM l0, SCM l1, ... , SCM_UNDEFINED)
     These correspond to the Scheme `(cons a b)' and `(list l0 l1 ...)'
     procedures.  Note that `gh_list()' is a C macro that invokes
     `scm_listify()'.

 - Function: SCM gh_car (SCM OBJ)
 - Function: SCM gh_cdr (SCM OBJ)
     ...

 - Function: SCM gh_c[ad][ad][ad][ad]r (SCM OBJ)
     These correspond to the Scheme `(caadar ls)' procedures etc ...

 - Function: SCM gh_set_car_x(SCM PAIR, SCM VALUE)
     Modifies the CAR of PAIR to be VALUE.  This is equivalent to the
     Scheme procedure `(set-car! ...)'.

 - Function: SCM gh_set_cdr_x(SCM PAIR, SCM VALUE)
     Modifies the CDR of PAIR to be VALUE.  This is equivalent to the
     Scheme procedure `(set-cdr! ...)'.

 - Function: unsigned long gh_length (SCM LS)
     Returns the length of the list.

 - Function: SCM gh_append (SCM ARGS)
 - Function: SCM gh_append2 (SCM L1, SCM L2)
 - Function: SCM gh_append3 (SCM L1, SCM L2, L3)
 - Function: SCM gh_append4 (SCM L1, SCM L2, L3, L4)
     `gh_append()' takes ARGS, which is a list of lists `(list1 list2
     ...)', and returns a list containing all the elements of the
     individual lists.

     A typical invocation of `gh_append()' to append 5 lists together
     would be
            gh_append(gh_list(l1, l2, l3, l4, l5, SCM_UNDEFINED));

     The functions `gh_append2()', `gh_append2()', `gh_append3()' and
     `gh_append4()' are convenience routines to make it easier for C
     programs to form the list of lists that goes as an argument to
     `gh_append()'.

 - Function: SCM gh_reverse (SCM LS)
     Returns a new list that has the same elements as LS but in the
     reverse order.  Note that this is implemented as a macro which
     calls `scm_reverse()'.

 - Function: SCM gh_list_tail (SCM LS, SCM K)
     Returns the sublist of LS with the last K elements.

 - Function: SCM gh_list_ref (SCM LS, SCM K)
     Returns the Kth element of the list LS.

 - Function: SCM gh_memq (SCM X, SCM LS)
 - Function: SCM gh_memv (SCM X, SCM LS)
 - Function: SCM gh_member (SCM X, SCM LS)
     These functions return the first sublist of LS whose CAR is X.
     They correspond to `(memq x ls)', `(memv x ls)' and `(member x
     ls)', and hence use (respectively) `eq?', `eqv?' and `equal?' to
     do comparisons.

     If X does not appear in LS, the value `SCM_BOOL_F' (not the empty
     list) is returned.

     Note that these functions are implemented as macros which call
     `scm_memq()', `scm_memv()' and `scm_member()' respectively.

 - Function: SCM gh_assq (SCM X, SCM ALIST)
 - Function: SCM gh_assv (SCM X, SCM ALIST)
 - Function: SCM gh_assoc (SCM X, SCM ALIST)
     These functions search an "association list" (list of pairs) ALIST
     for the first pair whose CAR is X, and they return that pair.

     If no pair in ALIST has X as its CAR, the value `SCM_BOOL_F' (not
     the empty list) is returned.

     Note that these functions are implemented as macros which call
     `scm_assq()', `scm_assv()' and `scm_assoc()' respectively.

Symbols
=======

Vectors
=======

 - Function: SCM gh_make_vector (SCM N, SCM FILL)
 - Function: SCM gh_vector (SCM LS)
 - Function: SCM gh_vector_ref (SCM V, SCM I)
 - Function: SCM gh_vector_set (SCM V, SCM I, SCM VAL)
 - Function: unsigned long gh_vector_length (SCM V)
 - Function: SCM gh_list_to_vector (SCM LS)
     These correspond to the Scheme `(make-vector n fill)', `(vector a
     b c ...)' `(vector-ref v i)' `(vector-set v i value)'
     `(vector-length v)' `(list->vector ls)' procedures.

     The correspondence is not perfect for `gh_vector': this routine
     takes a list LS instead of the individual list elements, thus
     making it identical to `gh_list_to_vector'.

     There is also a difference in gh_vector_length: the value returned
     is a C `unsigned long' instead of an SCM object.

Procedures
==========

 - Function: SCM gh_apply (SCM proc, SCM args)
     Call the Scheme procedure PROC, with the elements of ARGS as
     arguments.  ARGS must be a proper list.

 - Function: SCM gh_call0 (SCM proc)
 - Function: SCM gh_call1 (SCM proc, SCM arg)
 - Function: SCM gh_call2 (SCM proc, SCM arg1, SCM arg2)
 - Function: SCM gh_call3 (SCM proc, SCM arg1, SCM arg2, SCM arg3)
     Call the Scheme procedure PROC with no arguments (`gh_call0'), one
     argument (`gh_call1'), and so on.  You can get the same effect by
     wrapping the arguments up into a list, and calling `gh_apply';
     Guile provides these functions for convenience.

 - Function: SCM gh_catch (SCM key, SCM thunk, SCM handler)
 - Function: SCM gh_throw (SCM key, SCM args)
     Corresponds to the Scheme `catch' and `throw' procedures, which in
     Guile are provided as primitives.

 - Function: SCM gh_is_eq (SCM a, SCM b)
 - Function: SCM gh_is_eqv (SCM a, SCM b)
 - Function: SCM gh_is_equal (SCM a, SCM b)
     These correspond to the Scheme `eq?', `eqv?' and `equal?'
     predicates.

 - Function: int gh_obj_length (SCM OBJ)
     Returns the raw object length.

Data lookup
===========

   For now I just include Tim Pierce's comments from the `gh_data.c'
file; it should be organized into a documentation of the two functions
here.

     /* Data lookups between C and Scheme
     
        Look up a symbol with a given name, and return the object to which
        it is bound.  gh_lookup examines the Guile top level, and
        gh_module_lookup checks the module name space specified by the
        `vec' argument.
     
        The return value is the Scheme object to which SNAME is bound, or
        SCM_UNDEFINED if SNAME is not bound in the given context. [FIXME:
        should this be SCM_UNSPECIFIED?  Can a symbol ever legitimately be
        bound to SCM_UNDEFINED or SCM_UNSPECIFIED?  What is the difference?
        -twp] */


File: guile.info,  Node: Mixing gh and scm APIs,  Next: scm transition summary,  Prev: Calling Scheme procedures from C,  Up: GH

Mixing gh and scm APIs
======================


File: guile.info,  Node: scm transition summary,  Prev: Mixing gh and scm APIs,  Up: GH

Transitioning to the scm Interface
==================================

   The following table summarizes the available information on how to
transition from the GH to the scm interface.  Where transitioning is not
completely straightforward, the table includes a reference to more
detailed documentation in the preceding sections.

Header file
     Use `#include <libguile.h>' instead of `#include <guile/gh.h>'.

Compiling and Linking
     Use `guile-config' to pick up the flags required to compile C or
     C++ code that uses `libguile', like so

          $(CC) -o prog.o -c prog.c `guile-config compile`

     If you are using libtool to link your executables, just use
     `-lguile' in your link command.  Libtool will expand this into the
     needed linker options automatically.  If you are not using
     libtool, use the `guile-config' program to query the needed
     options explicitly.  A linker command like

          $(CC) -o prog prog.o `guile-config link`

     should be all that is needed.  To link shared libraries that will
     be used as Guile Extensions, use libtool to control both the
     compilation and the link stage.

The `SCM' type
     No change: the scm interface also uses this type to represent an
     arbitrary Scheme value.

`SCM_BOOL_F' and `SCM_BOOL_T'
     No change.

`SCM_UNSPECIFIED' and `SCM_UNDEFINED'
     No change.

`gh_enter'
     Use `scm_boot_guile' instead, but note that `scm_boot_guile' has a
     slightly different calling convention from `gh_enter':
     `scm_boot_guile', and the main program function that you specify
     for `scm_boot_guile' to call, both take an additional CLOSURE
     parameter.  *Note Guile Initialization Functions:: for more
     details.

`gh_repl'
     Use `scm_shell' instead.

`gh_init'
     Use `scm_init_guile' instead.

`gh_eval_str'
     Use `scm_c_eval_string' instead.

`gh_eval_file' or `gh_load'
     Use `scm_c_primitive_load' instead.

`gh_new_procedure'
     Use `scm_c_define_gsubr' instead, but note that the arguments are
     in a different order: for `scm_c_define_gsubr' the C function
     pointer is the last argument.  *Note A Sample Guile Extension::
     for an example.

`gh_defer_ints' and `gh_allow_ints'
     Use `SCM_DEFER_INTS' and `SCM_ALLOW_INTS' instead.  Note that
     these macros are used without parentheses, as in `SCM_DEFER_INTS;'.

`gh_bool2scm'
     Use `SCM_BOOL' instead.

`gh_ulong2scm'
     Use `scm_ulong2num' instead.

`gh_long2scm'
     Use `scm_long2num' instead.

`gh_double2scm'
     Use `scm_make_real' instead.

`gh_char2scm'
     Use `SCM_MAKE_CHAR' instead.

`gh_str2scm'
     Use `scm_mem2string' instead.

`gh_str02scm'
     Use `scm_makfrom0str' instead.

`gh_set_substr'
     No direct scm equivalent.  [FIXME]

`gh_symbol2scm'
     Use `scm_str2symbol' instead.  [FIXME: inconsistent naming, should
     be `scm_str02symbol'.]

`gh_ints2scm' and `gh_doubles2scm'
     No direct scm equivalent.  [FIXME]

`gh_chars2byvect' and `gh_shorts2svect'
     No direct scm equivalent.  [FIXME]

`gh_longs2ivect' and `gh_ulongs2uvect'
     No direct scm equivalent.  [FIXME]

`gh_floats2fvect' and `gh_doubles2dvect'
     No direct scm equivalent.  [FIXME]

`gh_scm2bool'
     Use `SCM_NFALSEP' instead.

`gh_scm2int'
     Replace `gh_scm2int (OBJ)' by
          scm_num2int (OBJ, SCM_ARG1, STR)
     where STR is a C string that describes the context of the call.

`gh_scm2ulong'
     Replace `gh_scm2ulong (OBJ)' by
          scm_num2ulong (OBJ, SCM_ARG1, STR)
     where STR is a C string that describes the context of the call.

`gh_scm2long'
     Replace `gh_scm2long (OBJ)' by
          scm_num2long (OBJ, SCM_ARG1, STR)
     where STR is a C string that describes the context of the call.

`gh_scm2double'
     Replace `gh_scm2double (OBJ)' by
          scm_num2dbl (OBJ, STR)
     where STR is a C string that describes the context of the call.

`gh_scm2char'
     Use the `SCM_CHAR' macro instead, but note that `SCM_CHAR' does
     not check that its argument is actually a character.  To check that
     a `SCM' value is a character before using `SCM_CHAR' to extract
     the character value, use the `SCM_VALIDATE_CHAR' macro.

`gh_scm2newstr'
     No direct scm equivalent.  [FIXME]

`gh_get_substr'
     No direct scm equivalent.  [FIXME]

`gh_symbol2newstr'
     No direct scm equivalent.  [FIXME]

`gh_scm2chars'
     No direct scm equivalent.  [FIXME]

`gh_scm2shorts' and `gh_scm2longs'
     No direct scm equivalent.  [FIXME]

`gh_scm2floats' and `gh_scm2doubles'
     No direct scm equivalent.  [FIXME]

`gh_boolean_p'
     Use the `SCM_BOOLP' macro instead, or replace `gh_boolean_p (OBJ)'
     by
          SCM_NFALSEP (scm_boolean_p (OBJ))

`gh_symbol_p'
     Use the `SCM_SYMBOLP' macro instead, or replace `gh_symbol_p
     (OBJ)' by
          SCM_NFALSEP (scm_symbol_p (OBJ))

`gh_char_p'
     Use the `SCM_CHARP' macro instead, or replace `gh_char_p (OBJ)' by
          SCM_NFALSEP (scm_char_p (OBJ))

`gh_vector_p'
     Use the `SCM_VECTORP' macro instead, or replace `gh_vector_p
     (OBJ)' by
          SCM_NFALSEP (scm_vector_p (OBJ))

`gh_pair_p'
     Use the `SCM_CONSP' macro instead, or replace `gh_pair_p (OBJ)' by
          SCM_NFALSEP (scm_pair_p (OBJ))

`gh_number_p'
     Use the `SCM_NUMBERP' macro instead, or replace `gh_number_p
     (OBJ)' by
          SCM_NFALSEP (scm_number_p (OBJ))

`gh_string_p'
     Use the `SCM_STRINGP' macro instead, or replace `gh_string_p
     (OBJ)' by
          SCM_NFALSEP (scm_string_p (OBJ))

`gh_procedure_p'
     Replace `gh_procedure_p (OBJ)' by
          SCM_NFALSEP (scm_procedure_p (OBJ))

`gh_list_p'
     Replace `gh_list_p (OBJ)' by
          SCM_NFALSEP (scm_list_p (OBJ))

`gh_inexact_p'
     Use the `SCM_INEXACTP' macro instead, or replace `gh_inexact_p
     (OBJ)' by
          SCM_NFALSEP (scm_inexact_p (OBJ))

`gh_exact_p'
     Replace `gh_exact_p (OBJ)' by
          SCM_NFALSEP (scm_exact_p (OBJ))

`gh_eq_p'
     Use the `SCM_EQ_P' macro instead, or replace `gh_eq_p (X, Y)' by
          SCM_NFALSEP (scm_eq_p (X, Y))

`gh_eqv_p'
     Replace `gh_eqv_p (X, Y)' by
          SCM_NFALSEP (scm_eqv_p (X, Y))

`gh_equal_p'
     Replace `gh_equal_p (X, Y)' by
          SCM_NFALSEP (scm_equal_p (X, Y))

`gh_string_equal_p'
     Replace `gh_string_equal_p (X, Y)' by
          SCM_NFALSEP (scm_string_equal_p (X, Y))

`gh_null_p'
     Use the `SCM_NULLP' macro instead, or replace `gh_null_p (OBJ)' by
          SCM_NFALSEP (scm_null_p (OBJ))

`gh_cons'
     Use `scm_cons' instead.

`gh_car' and `gh_cdr'
     Use the `SCM_CAR' and `SCM_CDR' macros instead.

`gh_cxxr' and `gh_cxxxr'
     (Where each x is either `a' or `d'.)  Use the corresponding
     `SCM_CXXR' or `SCM_CXXXR' macro instead.

`gh_set_car_x' and `gh_set_cdr_x'
     Use `scm_set_car_x' and `scm_set_cdr_x' instead.

`gh_list'
     Use `scm_listify' instead.

`gh_length'
     Replace `gh_length (LST)' by
          scm_num2ulong (scm_length (LST), SCM_ARG1, STR)
     where STR is a C string that describes the context of the call.

`gh_append'
     Use `scm_append' instead.

`gh_append2', `gh_append3', `gh_append4'
     Replace `gh_appendN (L1, ..., LN)' by
          scm_append (scm_listify (L1, ..., LN, SCM_UNDEFINED))

`gh_reverse'
     Use `scm_reverse' instead.

`gh_list_tail' and `gh_list_ref'
     Use `scm_list_tail' and `scm_list_ref' instead.

`gh_memq', `gh_memv' and `gh_member'
     Use `scm_memq', `scm_memv' and `scm_member' instead.

`gh_assq', `gh_assv' and `gh_assoc'
     Use `scm_assq', `scm_assv' and `scm_assoc' instead.

`gh_make_vector'
     Use `scm_make_vector' instead.

`gh_vector' or `gh_list_to_vector'
     Use `scm_vector' instead.

`gh_vector_ref' and `gh_vector_set_x'
     Use `scm_vector_ref' and `scm_vector_set_x' instead.

`gh_vector_length'
     Use the `SCM_VECTOR_LENGTH' macro instead.

`gh_apply'
     Use `scm_apply' instead, but note that `scm_apply' takes an
     additional third argument that you should set to `SCM_EOL'.



File: guile.info,  Node: Reference Intro,  Next: API Overview,  Prev: GH,  Up: Top

Part IV: Guile API Reference
****************************

   Guile provides an application programming interface ("API") to
developers in two core languages: Scheme and C.  This part of the manual
contains reference documentation for all of the functionality that is
available through both Scheme and C interfaces.


File: guile.info,  Node: API Overview,  Next: Simple Data Types,  Prev: Reference Intro,  Up: Top

Overview of the Guile API
*************************

   Guile's application programming interface ("API") makes
functionality available that an application developer can use in either
C or Scheme programming.  The interface consists of "elements" that may
be macros, functions or variables in C, and procedures, variables,
syntax or other types of object in Scheme.  Broadly speaking, the
interface as a whole can be divided into three groups.

  1. Elements that are available equivalently as C functions or Scheme
     procedures.

  2. Elements that are only available as macros, functions or variables
     for C programming.

  3. Elements that are only available as procedures or other objects in
     Scheme.

   Functions/procedures in the first group are often known as
"primitives", "subrs" or "builtins".  An example is the `assq' Scheme
procedure, which is also available as `scm_assq' in C.

   Elements in the second and third groups exist because they provide
additional language-specific benefits in either Scheme or C.  Examples
are the C macro `SCM_CONSP', which is faster and more convenient in C
programming than the primitive `scm_pair_p', and the
procedure-with-setter `make-object-property', which provides a more
convenient property handling interface in Scheme than the primitives on
which it is based.

* Menu:

* Primitives::                  Identical function for Scheme and C.
* C Only::                      Elements only available in C.
* Scheme Only::                 Elements only available in Scheme.
* Reference Layout::            The layout of this part of the manual.


File: guile.info,  Node: Primitives,  Next: C Only,  Up: API Overview

Identical Function in both Scheme and C
=======================================

   They form the majority of the API, and allow both C and Scheme
programmers to perform identical operations.

   Scheme procedures marked "primitive functions" have a regular
interface when calling from C, reflected in two areas: the name of a C
function, and the convention for passing non-required arguments to this
function.

* Menu:

* Transforming Scheme name to C name::
* Structuring argument lists for C functions::


File: guile.info,  Node: Transforming Scheme name to C name,  Next: Structuring argument lists for C functions,  Up: Primitives

Transforming Scheme name to C name
----------------------------------

   Normally, the name of a C function can be derived given its Scheme
name, using some simple textual transformations:

   * Replace `-' (hyphen) with `_' (underscore).

   * Replace `?' (question mark) with "_p".

   * Replace `!' (exclamation point) with "_x".

   * Replace internal `->' with "_to_".

   * Replace `<=' (less than or equal) with "_leq".

   * Replace `>=' (greater than or equal) with "_geq".

   * Replace `<' (less than) with "_less".

   * Replace `>' (greater than) with "_gr".

   * Replace `@' with "at". [Omit?]

   * Prefix with "gh_" (or "scm_" if you are ignoring the gh interface).

   * [Anything else?  -ttn, 2000/01/16 15:17:28]


   Here is an Emacs Lisp command that prompts for a Scheme function
name and inserts the corresponding C function name into the buffer.

     (defun insert-scheme-to-C (name &optional use-gh)
       "Transforms Scheme NAME, a string, to its C counterpart, and inserts it.
     Prefix arg non-nil means use \"gh_\" prefix, otherwise use \"scm_\" prefix."
       (interactive "sScheme name: \nP")
       (let ((transforms '(("-"  . "_")
                           ("?"  . "_p")
                           ("!"  . "_x")
                           ("->" . "_to_")
                           ("<=" . "_leq")
                           (">=" . "_geq")
                           ("<"  . "_less")
                           (">"  . "_gr")
                           ("@"  . "at"))))
         (while transforms
           (let ((trigger (concat "\\(.*\\)"
                                  (regexp-quote (caar transforms))
                                  "\\(.*\\)"))
                 (sub (cdar transforms))
                 (m nil))
             (while (setq m (string-match trigger name))
               (setq name (concat (match-string 1 name)
                                  sub
                                  (match-string 2 name)))))
           (setq transforms (cdr transforms))))
       (insert (if use-gh "gh_" "scm_") name))


File: guile.info,  Node: Structuring argument lists for C functions,  Prev: Transforming Scheme name to C name,  Up: Primitives

Structuring argument lists for C functions
------------------------------------------

   The C function's arguments will be all of the Scheme procedure's
arguments, both required and optional; if the Scheme procedure takes a
"rest" argument, that will be a final argument to the C function.  The
C function's arguments, as well as its return type, will be `SCM'.


File: guile.info,  Node: C Only,  Next: Scheme Only,  Prev: Primitives,  Up: API Overview

Elements Available Only in C
============================

   For C this is usually a matter of better performance (e.g. the
`SCM_CONSP' macro) or of accepting C language types rather than the
generic `SCM'.


File: guile.info,  Node: Scheme Only,  Next: Reference Layout,  Prev: C Only,  Up: API Overview

Elements Available Only in Scheme
=================================


File: guile.info,  Node: Reference Layout,  Prev: Scheme Only,  Up: API Overview

Reference Material Layout
=========================

   This part of the reference manual documents all of Guile's core
Scheme-level language and features in functionally-related groups.
Where a particular section of the manual includes both R5RS-compliant
parts and Guile-specific extensions, the text indicates which parts of
the documentation describe R5RS behaviour and which parts describe Guile
extensions.

   For a quick way of identifying the parts of Guile that implement
R5RS-compliant features, see the R5RS index: *Note R5RS Index::.


File: guile.info,  Node: Simple Data Types,  Next: Compound Data Types,  Prev: API Overview,  Up: Top

Simple Generic Data Types
*************************

   This chapter describes those of Guile's simple data types which are
primarily used for their role as items of generic data.  By "simple" we
mean data types that are not primarily used as containers to hold other
data -- i.e. pairs, lists, vectors and so on.  For the documentation of
such "compound" data types, see *Note Compound Data Types::.

   One of the great strengths of Scheme is that there is no
straightforward distinction between "data" and "functionality".  For
example, Guile's support for dynamic linking could be described

   * either in a "data-centric" way, as the behaviour and properties of
     the "dynamically linked object" data type, and the operations that
     may be applied to instances of this type

   * or in a "functionality-centric" way, as the set of procedures that
     constitute Guile's support for dynamic linking, in the context of
     the module system.

   The contents of this chapter are, therefore, a matter of judgment.
By "generic", we mean to select those data types whose typical use as
_data_ in a wide variety of programming contexts is more important than
their use in the implementation of a particular piece of
_functionality_.  The last section of this chapter provides references
for all the data types that are documented not here but in a
"functionality-centric" way elsewhere in the manual.

* Menu:

* Booleans::                    True/false values.
* Numbers::                     Numerical data types.
* Characters::                  New character names.
* Strings::                     Special things about strings.
* Regular Expressions::         Pattern matching and substitution.
* Symbols::                     Symbols.
* Keywords::                    Self-quoting, customizable display keywords.
* Other Types::                 "Functionality-centric" data types.


File: guile.info,  Node: Booleans,  Next: Numbers,  Up: Simple Data Types

Booleans
========

   The two boolean values are `#t' for true and `#f' for false.

   Boolean values are returned by predicate procedures, such as the
general equality predicates `eq?', `eqv?' and `equal?' (*note
Equality::) and numerical and string comparison operators like
`string=?' (*note String Comparison::) and `<=' (*note Comparison::).

     (<= 3 8)
     =>
     #t
     
     (<= 3 -3)
     =>
     #f
     
     (equal? "house" "houses")
     =>
     #f
     
     (eq? #f #f)
     =>
     #t

   In test condition contexts like `if' and `cond' (*note if cond
case::), where a group of subexpressions will be evaluated only if a
CONDITION expression evaluates to "true", "true" means any value at all
except `#f'.

     (if #t "yes" "no")
     =>
     "yes"
     
     (if 0 "yes" "no")
     =>
     "yes"
     
     (if #f "yes" "no")
     =>
     "no"

   A result of this asymmetry is that typical Scheme source code more
often uses `#f' explicitly than `#t': `#f' is necessary to represent an
`if' or `cond' false value, whereas `#t' is not necessary to represent
an `if' or `cond' true value.

   It is important to note that `#f' is *not* equivalent to any other
Scheme value.  In particular, `#f' is not the same as the number 0
(like in C and C++), and not the same as the "empty list" (like in some
Lisp dialects).

   The `not' procedure returns the boolean inverse of its argument:

 - Scheme Procedure: not x
 - C Function: scm_not (x)
     Return `#t' iff X is `#f', else return `#f'.

   The `boolean?' procedure is a predicate that returns `#t' if its
argument is one of the boolean values, otherwise `#f'.

 - Scheme Procedure: boolean? obj
 - C Function: scm_boolean_p (obj)
     Return `#t' iff OBJ is either `#t' or `#f'.


File: guile.info,  Node: Numbers,  Next: Characters,  Prev: Booleans,  Up: Simple Data Types

Numerical data types
====================

   Guile supports a rich "tower" of numerical types -- integer,
rational, real and complex -- and provides an extensive set of
mathematical and scientific functions for operating on numerical data.
This section of the manual documents those types and functions.

   You may also find it illuminating to read R5RS's presentation of
numbers in Scheme, which is particularly clear and accessible: see
*Note Numbers: (r5rs)Numbers.

* Menu:

* Numerical Tower::             Scheme's numerical "tower".
* Integers::                    Whole numbers.
* Reals and Rationals::         Real and rational numbers.
* Complex Numbers::             Complex numbers.
* Exactness::                   Exactness and inexactness.
* Number Syntax::               Read syntax for numerical data.
* Integer Operations::          Operations on integer values.
* Comparison::                  Comparison predicates.
* Conversion::                  Converting numbers to and from strings.
* Complex::                     Complex number operations.
* Arithmetic::                  Arithmetic functions.
* Scientific::                  Scientific functions.
* Primitive Numerics::          Primitive numeric functions.
* Bitwise Operations::          Logical AND, OR, NOT, and so on.
* Random::                      Random number generation.


File: guile.info,  Node: Numerical Tower,  Next: Integers,  Up: Numbers

Scheme's Numerical "Tower"
--------------------------

   Scheme's numerical "tower" consists of the following categories of
numbers:

   * integers (whole numbers)

   * rationals (the set of numbers that can be expressed as P/Q where P
     and Q are integers)

   * real numbers (the set of numbers that describes all possible
     positions along a one dimensional line)

   * complex numbers (the set of numbers that describes all possible
     positions in a two dimensional space)

   It is called a tower because each category "sits on" the one that
follows it, in the sense that every integer is also a rational, every
rational is also real, and every real number is also a complex number
(but with zero imaginary part).

   Of these, Guile implements integers, reals and complex numbers as
distinct types.  Rationals are implemented as regards the read syntax
for rational numbers that is specified by R5RS, but are immediately
converted by Guile to the corresponding real number.

   The `number?' predicate may be applied to any Scheme value to
discover whether the value is any of the supported numerical types.

 - Scheme Procedure: number? obj
 - C Function: scm_number_p (obj)
     Return `#t' if OBJ is any kind of number, else `#f'.

   For example:

     (number? 3)
     =>
     #t
     
     (number? "hello there!")
     =>
     #f
     
     (define pi 3.141592654)
     (number? pi)
     =>
     #t

   The next few subsections document each of Guile's numerical data
types in detail.


File: guile.info,  Node: Integers,  Next: Reals and Rationals,  Prev: Numerical Tower,  Up: Numbers

Integers
--------

   Integers are whole numbers, that is numbers with no fractional part,
such as 2, 83 and -3789.

   Integers in Guile can be arbitrarily big, as shown by the following
example.

     (define (factorial n)
       (let loop ((n n) (product 1))
         (if (= n 0)
             product
             (loop (- n 1) (* product n)))))
     
     (factorial 3)
     =>
     6
     
     (factorial 20)
     =>
     2432902008176640000
     
     (- (factorial 45))
     =>
     -119622220865480194561963161495657715064383733760000000000

   Readers whose background is in programming languages where integers
are limited by the need to fit into just 4 or 8 bytes of memory may find
this surprising, or suspect that Guile's representation of integers is
inefficient.  In fact, Guile achieves a near optimal balance of
convenience and efficiency by using the host computer's native
representation of integers where possible, and a more general
representation where the required number does not fit in the native
form.  Conversion between these two representations is automatic and
completely invisible to the Scheme level programmer.

 - Scheme Procedure: integer? x
 - C Function: scm_integer_p (x)
     Return `#t' if X is an integer number, else `#f'.

          (integer? 487)
          =>
          #t
          
          (integer? -3.4)
          =>
          #f


File: guile.info,  Node: Reals and Rationals,  Next: Complex Numbers,  Prev: Integers,  Up: Numbers

Real and Rational Numbers
-------------------------

   Mathematically, the real numbers are the set of numbers that describe
all possible points along a continuous, infinite, one-dimensional line.
The rational numbers are the set of all numbers that can be written as
fractions P/Q, where P and Q are integers.  All rational numbers are
also real, but there are real numbers that are not rational, for example
the square root of 2, and pi.

   Guile represents both real and rational numbers approximately using a
floating point encoding with limited precision.  Even though the actual
encoding is in binary, it may be helpful to think of it as a decimal
number with a limited number of significant figures and a decimal point
somewhere, since this corresponds to the standard notation for non-whole
numbers.  For example:

     0.34
     -0.00000142857931198
     -5648394822220000000000.0
     4.0

   The limited precision of Guile's encoding means that any "real"
number in Guile can be written in a rational form, by multiplying and
then dividing by sufficient powers of 10 (or in fact, 2).  For example,
`-0.00000142857931198' is the same as `142857931198' divided by
`100000000000000000'.  In Guile's current incarnation, therefore, the
`rational?' and `real?' predicates are equivalent.

   Another aspect of this equivalence is that Guile currently does not
preserve the exactness that is possible with rational arithmetic.  If
such exactness is needed, it is of course possible to implement exact
rational arithmetic at the Scheme level using Guile's arbitrary size
integers.

   A planned future revision of Guile's numerical tower will make it
possible to implement exact representations and arithmetic for both
rational numbers and real irrational numbers such as square roots, and
in such a way that the new kinds of number integrate seamlessly with
those that are already implemented.

 - Scheme Procedure: real? obj
 - C Function: scm_real_p (obj)
     Return `#t' if OBJ is a real number, else `#f'.  Note that the
     sets of integer and rational values form subsets of the set of
     real numbers, so the predicate will also be fulfilled if OBJ is an
     integer number or a rational number.

 - Scheme Procedure: rational? x
 - C Function: scm_real_p (x)
     Return `#t' if X is a rational number, `#f' otherwise.  Note that
     the set of integer values forms a subset of the set of rational
     numbers, i. e. the predicate will also be fulfilled if X is an
     integer number.  Real numbers will also satisfy this predicate,
     because of their limited precision.


File: guile.info,  Node: Complex Numbers,  Next: Exactness,  Prev: Reals and Rationals,  Up: Numbers

Complex Numbers
---------------

   Complex numbers are the set of numbers that describe all possible
points in a two-dimensional space.  The two coordinates of a particular
point in this space are known as the "real" and "imaginary" parts of
the complex number that describes that point.

   In Guile, complex numbers are written in rectangular form as the sum
of their real and imaginary parts, using the symbol `i' to indicate the
imaginary part.

     3+4i
     =>
     3.0+4.0i
     
     (* 3-8i 2.3+0.3i)
     =>
     9.3-17.5i

   Guile represents a complex number as a pair of numbers both of which
are real, so the real and imaginary parts of a complex number have the
same properties of inexactness and limited precision as single real
numbers.

 - Scheme Procedure: complex? x
 - C Function: scm_number_p (x)
     Return `#t' if X is a complex number, `#f' otherwise.  Note that
     the sets of real, rational and integer values form subsets of the
     set of complex numbers, i. e. the predicate will also be fulfilled
     if X is a real, rational or integer number.


File: guile.info,  Node: Exactness,  Next: Number Syntax,  Prev: Complex Numbers,  Up: Numbers

Exact and Inexact Numbers
-------------------------

   R5RS requires that a calculation involving inexact numbers always
produces an inexact result.  To meet this requirement, Guile
distinguishes between an exact integer value such as `5' and the
corresponding inexact real value which, to the limited precision
available, has no fractional part, and is printed as `5.0'.  Guile will
only convert the latter value to the former when forced to do so by an
invocation of the `inexact->exact' procedure.

 - Scheme Procedure: exact? x
 - C Function: scm_exact_p (x)
     Return `#t' if X is an exact number, `#f' otherwise.

 - Scheme Procedure: inexact? x
 - C Function: scm_inexact_p (x)
     Return `#t' if X is an inexact number, `#f' else.

 - Scheme Procedure: inexact->exact z
 - C Function: scm_inexact_to_exact (z)
     Return an exact number that is numerically closest to Z.

 - Scheme Procedure: exact->inexact z
     Convert the number Z to its inexact representation.


File: guile.info,  Node: Number Syntax,  Next: Integer Operations,  Prev: Exactness,  Up: Numbers

Read Syntax for Numerical Data
------------------------------

   The read syntax for integers is a string of digits, optionally
preceded by a minus or plus character, a code indicating the base in
which the integer is encoded, and a code indicating whether the number
is exact or inexact.  The supported base codes are:

   * `#b', `#B' -- the integer is written in binary (base 2)

   * `#o', `#O' -- the integer is written in octal (base 8)

   * `#d', `#D' -- the integer is written in decimal (base 10)

   * `#x', `#X' -- the integer is written in hexadecimal (base 16).

   If the base code is omitted, the integer is assumed to be decimal.
The following examples show how these base codes are used.

     -13
     =>
     -13
     
     #d-13
     =>
     -13
     
     #x-13
     =>
     -19
     
     #b+1101
     =>
     13
     
     #o377
     =>
     255

   The codes for indicating exactness (which can, incidentally, be
applied to all numerical values) are:

   * `#e', `#E' -- the number is exact

   * `#i', `#I' -- the number is inexact.

   If the exactness indicator is omitted, the integer is assumed to be
exact, since Guile's internal representation for integers is always
exact.  Real numbers have limited precision similar to the precision of
the `double' type in C.  A consequence of the limited precision is that
all real numbers in Guile are also rational, since any number R with a
limited number of decimal places, say N, can be made into an integer by
multiplying by 10^N.


File: guile.info,  Node: Integer Operations,  Next: Comparison,  Prev: Number Syntax,  Up: Numbers

Operations on Integer Values
----------------------------

 - Scheme Procedure: odd? n
 - C Function: scm_odd_p (n)
     Return `#t' if N is an odd number, `#f' otherwise.

 - Scheme Procedure: even? n
 - C Function: scm_even_p (n)
     Return `#t' if N is an even number, `#f' otherwise.

 - Scheme Procedure: quotient
     Return the quotient of the numbers X and Y.

 - Scheme Procedure: remainder
     Return the remainder of the numbers X and Y.
          (remainder 13 4) => 1
          (remainder -13 4) => -1

 - Scheme Procedure: modulo
     Return the modulo of the numbers X and Y.
          (modulo 13 4) => 1
          (modulo -13 4) => 3

 - Scheme Procedure: gcd
     Return the greatest common divisor of all arguments.  If called
     without arguments, 0 is returned.

 - Scheme Procedure: lcm
     Return the least common multiple of the arguments.  If called
     without arguments, 1 is returned.


File: guile.info,  Node: Comparison,  Next: Conversion,  Prev: Integer Operations,  Up: Numbers

Comparison Predicates
---------------------

 - Scheme Procedure: =
     Return `#t' if all parameters are numerically equal.

 - Scheme Procedure: <
     Return `#t' if the list of parameters is monotonically increasing.

 - Scheme Procedure: >
     Return `#t' if the list of parameters is monotonically decreasing.

 - Scheme Procedure: <=
     Return `#t' if the list of parameters is monotonically
     non-decreasing.

 - Scheme Procedure: >=
     Return `#t' if the list of parameters is monotonically
     non-increasing.

 - Scheme Procedure: zero?
     Return `#t' if Z is an exact or inexact number equal to zero.

 - Scheme Procedure: positive?
     Return `#t' if X is an exact or inexact number greater than zero.

 - Scheme Procedure: negative?
     Return `#t' if X is an exact or inexact number less than zero.


File: guile.info,  Node: Conversion,  Next: Complex,  Prev: Comparison,  Up: Numbers

Converting Numbers To and From Strings
--------------------------------------

 - Scheme Procedure: number->string n [radix]
 - C Function: scm_number_to_string (n, radix)
     Return a string holding the external representation of the number
     N in the given RADIX.  If N is inexact, a radix of 10 will be used.

 - Scheme Procedure: string->number string [radix]
 - C Function: scm_string_to_number (string, radix)
     Return 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'.


File: guile.info,  Node: Complex,  Next: Arithmetic,  Prev: Conversion,  Up: Numbers

Complex Number Operations
-------------------------

 - Scheme Procedure: make-rectangular real imaginary
 - C Function: scm_make_rectangular (real, imaginary)
     Return a complex number constructed of the given REAL and
     IMAGINARY parts.

 - Scheme Procedure: make-polar x y
 - C Function: scm_make_polar (x, y)
     Return the complex number X * e^(i * Y).

 - Scheme Procedure: real-part
     Return the real part of the number Z.

 - Scheme Procedure: imag-part
     Return the imaginary part of the number Z.

 - Scheme Procedure: magnitude
     Return the magnitude of the number Z. This is the same as `abs'
     for real arguments, but also allows complex numbers.

 - Scheme Procedure: angle
     Return the angle of the complex number Z.


File: guile.info,  Node: Arithmetic,  Next: Scientific,  Prev: Complex,  Up: Numbers

Arithmetic Functions
--------------------

 - Scheme Procedure: + z1 ...
     Return the sum of all parameter values.  Return 0 if called
     without any parameters.

 - Scheme Procedure: - z1 z2 ...
     If called with one argument Z1, -Z1 is returned. Otherwise the sum
     of all but the first argument are subtracted from the first
     argument.

 - Scheme Procedure: * z1 ...
     Return the product of all arguments.  If called without arguments,
     1 is returned.

 - Scheme Procedure: / z1 z2 ...
     Divide the first argument by the product of the remaining
     arguments.  If called with one argument Z1, 1/Z1 is returned.

 - Scheme Procedure: abs x
 - C Function: scm_abs (x)
     Return the absolute value of X.

     X must be a number with zero imaginary part.  To calculate the
     magnitude of a complex number, use `magnitude' instead.

 - Scheme Procedure: max x1 x2 ...
     Return the maximum of all parameter values.

 - Scheme Procedure: min x1 x2 ...
     Return the minimum of all parameter values.

 - Scheme Procedure: truncate
     Round the inexact number X towards zero.

 - Scheme Procedure: round x
     Round the inexact number X towards zero.

 - Scheme Procedure: floor x
     Round the number X towards minus infinity.

 - Scheme Procedure: ceiling x
     Round the number X towards infinity.

   For the `truncate' and `round' procedures, the Guile library exports
equivalent C functions, but taking and returning arguments of type
`double' rather than the usual `SCM'.

 - C Function: double scm_truncate (double x)
 - C Function: double scm_round (double x)

   For `floor' and `ceiling', the equivalent C functions are `floor'
and `ceil' from the standard mathematics library (which also take and
return `double' arguments).


File: guile.info,  Node: Scientific,  Next: Primitive Numerics,  Prev: Arithmetic,  Up: Numbers

Scientific Functions
--------------------

   The following procedures accept any kind of number as arguments,
including complex numbers.

 - Scheme Procedure: sqrt z
     Return the square root of Z.

 - Scheme Procedure: expt z1 z2
     Return Z1 raised to the power of Z2.

 - Scheme Procedure: sin z
     Return the sine of Z.

 - Scheme Procedure: cos z
     Return the cosine of Z.

 - Scheme Procedure: tan z
     Return the tangent of Z.

 - Scheme Procedure: asin z
     Return the arcsine of Z.

 - Scheme Procedure: acos z
     Return the arccosine of Z.

 - Scheme Procedure: atan z
     Return the arctangent of Z.

 - Scheme Procedure: exp z
     Return e to the power of Z, where e is the base of natural
     logarithms (2.71828...).

 - Scheme Procedure: log z
     Return the natural logarithm of Z.

 - Scheme Procedure: log10 z
     Return the base 10 logarithm of Z.

 - Scheme Procedure: sinh z
     Return the hyperbolic sine of Z.

 - Scheme Procedure: cosh z
     Return the hyperbolic cosine of Z.

 - Scheme Procedure: tanh z
     Return the hyperbolic tangent of Z.

 - Scheme Procedure: asinh z
     Return the hyperbolic arcsine of Z.

 - Scheme Procedure: acosh z
     Return the hyperbolic arccosine of Z.

 - Scheme Procedure: atanh z
     Return the hyperbolic arctangent of Z.


File: guile.info,  Node: Primitive Numerics,  Next: Bitwise Operations,  Prev: Scientific,  Up: Numbers

Primitive Numeric Functions
---------------------------

   Many of Guile's numeric procedures which accept any kind of numbers
as arguments, including complex numbers, are implemented as Scheme
procedures that use the following real number-based primitives.  These
primitives signal an error if they are called with complex arguments.

 - Scheme Procedure: $abs x
     Return the absolute value of X.

 - Scheme Procedure: $sqrt x
     Return the square root of X.

 - Scheme Procedure: $expt x y
 - C Function: scm_sys_expt (x, y)
     Return X raised to the power of Y. This procedure does not accept
     complex arguments.

 - Scheme Procedure: $sin x
     Return the sine of X.

 - Scheme Procedure: $cos x
     Return the cosine of X.

 - Scheme Procedure: $tan x
     Return the tangent of X.

 - Scheme Procedure: $asin x
     Return the arcsine of X.

 - Scheme Procedure: $acos x
     Return the arccosine of X.

 - Scheme Procedure: $atan x
     Return the arctangent of X in the range -PI/2 to PI/2.

 - Scheme Procedure: $atan2 x y
 - C Function: scm_sys_atan2 (x, y)
     Return the arc tangent of the two arguments X and Y. This is
     similar to calculating the arc tangent of X / Y, except that the
     signs of both arguments are used to determine the quadrant of the
     result. This procedure does not accept complex arguments.

 - Scheme Procedure: $exp x
     Return e to the power of X, where e is the base of natural
     logarithms (2.71828...).

 - Scheme Procedure: $log x
     Return the natural logarithm of X.

 - Scheme Procedure: $sinh x
     Return the hyperbolic sine of X.

 - Scheme Procedure: $cosh x
     Return the hyperbolic cosine of X.

 - Scheme Procedure: $tanh x
     Return the hyperbolic tangent of X.

 - Scheme Procedure: $asinh x
     Return the hyperbolic arcsine of X.

 - Scheme Procedure: $acosh x
     Return the hyperbolic arccosine of X.

 - Scheme Procedure: $atanh x
     Return the hyperbolic arctangent of X.

   For the hyperbolic arc-functions, the Guile library exports C
functions corresponding to these Scheme procedures, but taking and
returning arguments of type `double' rather than the usual `SCM'.

 - C Function: double scm_asinh (double x)
 - C Function: double scm_acosh (double x)
 - C Function: double scm_atanh (double x)
     Return the hyperbolic arcsine, arccosine or arctangent of X
     respectively.

   For all the other Scheme procedures above, except `expt' and `atan2'
(whose entries specifically mention an equivalent C function), the
equivalent C functions are those provided by the standard mathematics
library.  The mapping is as follows.

     Scheme Procedure   C Function
     `$abs'             `fabs'
     `$sqrt'            `sqrt'
     `$sin'             `sin'
     `$cos'             `cos'
     `$tan'             `tan'
     `$asin'            `asin'
     `$acos'            `acos'
     `$atan'            `atan'
     `$exp'             `exp'
     `$log'             `log'
     `$sinh'            `sinh'
     `$cosh'            `cosh'
     `$tanh'            `tanh'

Naturally, these C functions expect and return `double' arguments.


File: guile.info,  Node: Bitwise Operations,  Next: Random,  Prev: Primitive Numerics,  Up: Numbers

Bitwise Operations
------------------

 - Scheme Procedure: logand n1 n2
     Return the bitwise AND of the integer arguments.

          (logand) => -1
          (logand 7) => 7
          (logand #b111 #b011 #b001) => 1

 - Scheme Procedure: logior n1 n2
     Return the bitwise OR of the integer arguments.

          (logior) => 0
          (logior 7) => 7
          (logior #b000 #b001 #b011) => 3

 - Scheme Procedure: logxor n1 n2
     Return the bitwise XOR of the integer arguments.  A bit is set in
     the result if it is set in an odd number of arguments.
          (logxor) => 0
          (logxor 7) => 7
          (logxor #b000 #b001 #b011) => 2
          (logxor #b000 #b001 #b011 #b011) => 1

 - Scheme Procedure: lognot n
 - C Function: scm_lognot (n)
     Return the integer which is the 2s-complement of the integer
     argument.

          (number->string (lognot #b10000000) 2)
             => "-10000001"
          (number->string (lognot #b0) 2)
             => "-1"

 - Scheme Procedure: logtest j k
 - C Function: scm_logtest (j, k)
          (logtest j k) == (not (zero? (logand j k)))
          
          (logtest #b0100 #b1011) => #f
          (logtest #b0100 #b0111) => #t

 - Scheme Procedure: logbit? index j
 - C Function: scm_logbit_p (index, j)
          (logbit? index j) == (logtest (integer-expt 2 index) j)
          
          (logbit? 0 #b1101) => #t
          (logbit? 1 #b1101) => #f
          (logbit? 2 #b1101) => #t
          (logbit? 3 #b1101) => #t
          (logbit? 4 #b1101) => #f

 - Scheme Procedure: ash n cnt
 - C Function: scm_ash (n, cnt)
     The function ash performs an arithmetic shift left by CNT bits (or
     shift right, if CNT is negative).  'Arithmetic' means, that the
     function does not guarantee to keep the bit structure of N, but
     rather guarantees that the result will always be rounded towards
     minus infinity.  Therefore, the results of ash and a corresponding
     bitwise shift will differ if N is negative.

     Formally, the function returns an integer equivalent to
     `(inexact->exact (floor (* N (expt 2 CNT))))'.

          (number->string (ash #b1 3) 2)     => "1000"
          (number->string (ash #b1010 -1) 2) => "101"

 - Scheme Procedure: logcount n
 - C Function: scm_logcount (n)
     Return the number of bits in integer N.  If integer is positive,
     the 1-bits in its binary representation are counted.  If negative,
     the 0-bits in its two's-complement binary representation are
     counted.  If 0, 0 is returned.

          (logcount #b10101010)
             => 4
          (logcount 0)
             => 0
          (logcount -2)
             => 1

 - Scheme Procedure: integer-length n
 - C Function: scm_integer_length (n)
     Return the number of bits necessary to represent N.

          (integer-length #b10101010)
             => 8
          (integer-length 0)
             => 0
          (integer-length #b1111)
             => 4

 - Scheme Procedure: integer-expt n k
 - C Function: scm_integer_expt (n, k)
     Return N raised to the non-negative integer exponent K.

          (integer-expt 2 5)
             => 32
          (integer-expt -3 3)
             => -27

 - Scheme Procedure: bit-extract n start end
 - C Function: scm_bit_extract (n, start, end)
     Return the integer composed of the START (inclusive) through END
     (exclusive) bits of N.  The STARTth bit becomes the 0-th bit in
     the result.

          (number->string (bit-extract #b1101101010 0 4) 2)
             => "1010"
          (number->string (bit-extract #b1101101010 4 9) 2)
             => "10110"


File: guile.info,  Node: Random,  Prev: Bitwise Operations,  Up: Numbers

Random Number Generation
------------------------

 - Scheme Procedure: copy-random-state [state]
 - C Function: scm_copy_random_state (state)
     Return a copy of the random state STATE.

 - Scheme Procedure: random n [state]
 - C Function: scm_random (n, state)
     Return a number in [0, N).

     Accepts a positive integer or real n and returns a number of the
     same type between zero (inclusive) and N (exclusive). The values
     returned have a uniform distribution.

     The optional argument STATE must be of the type produced by
     `seed->random-state'. It defaults to the value of the variable
     *RANDOM-STATE*. This object is used to maintain the state of the
     pseudo-random-number generator and is altered as a side effect of
     the random operation.

 - Scheme Procedure: random:exp [state]
 - C Function: scm_random_exp (state)
     Return an inexact real in an exponential distribution with mean 1.
     For an exponential distribution with mean u use (* u
     (random:exp)).

 - Scheme Procedure: random:hollow-sphere! v [state]
 - C Function: scm_random_hollow_sphere_x (v, state)
     Fills vect with inexact real random numbers the sum of whose
     squares is equal to 1.0.  Thinking of vect as coordinates in space
     of dimension n = (vector-length vect), the coordinates are
     uniformly distributed over the surface of the unit n-sphere.

 - Scheme Procedure: random:normal [state]
 - C Function: scm_random_normal (state)
     Return an inexact real in a normal distribution.  The distribution
     used has mean 0 and standard deviation 1.  For a normal
     distribution with mean m and standard deviation d use `(+ m (* d
     (random:normal)))'.

 - Scheme Procedure: random:normal-vector! v [state]
 - C Function: scm_random_normal_vector_x (v, state)
     Fills vect with inexact real random numbers that are independent
     and standard normally distributed (i.e., with mean 0 and variance
     1).

 - Scheme Procedure: random:solid-sphere! v [state]
 - C Function: scm_random_solid_sphere_x (v, state)
     Fills vect with inexact real random numbers the sum of whose
     squares is less than 1.0.  Thinking of vect as coordinates in
     space of dimension n = (vector-length vect), the coordinates are
     uniformly distributed within the unit n-sphere.  The sum of the
     squares of the numbers is returned.

 - Scheme Procedure: random:uniform [state]
 - C Function: scm_random_uniform (state)
     Return a uniformly distributed inexact real random number in [0,1).

 - Scheme Procedure: seed->random-state seed
 - C Function: scm_seed_to_random_state (seed)
     Return a new random state using SEED.


File: guile.info,  Node: Characters,  Next: Strings,  Prev: Numbers,  Up: Simple Data Types

Characters
==========

   Most of the characters in the ASCII character set may be referred to
by name: for example, `#\tab', `#\esc', `#\stx', and so on.  The
following table describes the ASCII names for each character.

0 = `#\nul'        1 = `#\soh'        2 = `#\stx'        3 = `#\etx'
4 = `#\eot'        5 = `#\enq'        6 = `#\ack'        7 = `#\bel'
8 = `#\bs'         9 = `#\ht'         10 = `#\nl'        11 = `#\vt'
12 = `#\np'        13 = `#\cr'        14 = `#\so'        15 = `#\si'
16 = `#\dle'       17 = `#\dc1'       18 = `#\dc2'       19 = `#\dc3'
20 = `#\dc4'       21 = `#\nak'       22 = `#\syn'       23 = `#\etb'
24 = `#\can'       25 = `#\em'        26 = `#\sub'       27 = `#\esc'
28 = `#\fs'        29 = `#\gs'        30 = `#\rs'        31 = `#\us'
32 = `#\sp'                                              

   The `delete' character (octal 177) may be referred to with the name
`#\del'.

   Several characters have more than one name:

   * `#\space', `#\sp'

   * `#\newline', `#\nl'

   * `#\tab', `#\ht'

   * `#\backspace', `#\bs'

   * `#\return', `#\cr'

   * `#\page', `#\np'

   * `#\null', `#\nul'

 - Scheme Procedure: char? x
 - C Function: scm_char_p (x)
     Return `#t' iff X is a character, else `#f'.

 - Scheme Procedure: char=? x y
     Return `#t' iff X is the same character as Y, else `#f'.

 - Scheme Procedure: char<? x y
     Return `#t' iff X is less than Y in the ASCII sequence, else `#f'.

 - Scheme Procedure: char<=? x y
     Return `#t' iff X is less than or equal to Y in the ASCII
     sequence, else `#f'.

 - Scheme Procedure: char>? x y
     Return `#t' iff X is greater than Y in the ASCII sequence, else
     `#f'.

 - Scheme Procedure: char>=? x y
     Return `#t' iff X is greater than or equal to Y in the ASCII
     sequence, else `#f'.

 - Scheme Procedure: char-ci=? x y
     Return `#t' iff X is the same character as Y ignoring case, else
     `#f'.

 - Scheme Procedure: char-ci<? x y
     Return `#t' iff X is less than Y in the ASCII sequence ignoring
     case, else `#f'.

 - Scheme Procedure: char-ci<=? x y
     Return `#t' iff X is less than or equal to Y in the ASCII sequence
     ignoring case, else `#f'.

 - Scheme Procedure: char-ci>? x y
     Return `#t' iff X is greater than Y in the ASCII sequence ignoring
     case, else `#f'.

 - Scheme Procedure: char-ci>=? x y
     Return `#t' iff X is greater than or equal to Y in the ASCII
     sequence ignoring case, else `#f'.

 - Scheme Procedure: char-alphabetic? chr
 - C Function: scm_char_alphabetic_p (chr)
     Return `#t' iff CHR is alphabetic, else `#f'.  Alphabetic means
     the same thing as the isalpha C library function.

 - Scheme Procedure: char-numeric? chr
 - C Function: scm_char_numeric_p (chr)
     Return `#t' iff CHR is numeric, else `#f'.  Numeric means the same
     thing as the isdigit C library function.

 - Scheme Procedure: char-whitespace? chr
 - C Function: scm_char_whitespace_p (chr)
     Return `#t' iff CHR is whitespace, else `#f'.  Whitespace means
     the same thing as the isspace C library function.

 - Scheme Procedure: char-upper-case? chr
 - C Function: scm_char_upper_case_p (chr)
     Return `#t' iff CHR is uppercase, else `#f'.  Uppercase means the
     same thing as the isupper C library function.

 - Scheme Procedure: char-lower-case? chr
 - C Function: scm_char_lower_case_p (chr)
     Return `#t' iff CHR is lowercase, else `#f'.  Lowercase means the
     same thing as the islower C library function.

 - Scheme Procedure: char-is-both? chr
 - C Function: scm_char_is_both_p (chr)
     Return `#t' iff CHR is either uppercase or lowercase, else `#f'.
     Uppercase and lowercase are as defined by the isupper and islower
     C library functions.

 - Scheme Procedure: char->integer chr
 - C Function: scm_char_to_integer (chr)
     Return the number corresponding to ordinal position of CHR in the
     ASCII sequence.

 - Scheme Procedure: integer->char n
 - C Function: scm_integer_to_char (n)
     Return the character at position N in the ASCII sequence.

 - Scheme Procedure: char-upcase chr
 - C Function: scm_char_upcase (chr)
     Return the uppercase character version of CHR.

 - Scheme Procedure: char-downcase chr
 - C Function: scm_char_downcase (chr)
     Return the lowercase character version of CHR.


File: guile.info,  Node: Strings,  Next: Regular Expressions,  Prev: Characters,  Up: Simple Data Types

Strings
=======

   Strings are fixed-length sequences of characters.  They can be
created by calling constructor procedures, but they can also literally
get entered at the REPL or in Scheme source files.

   Guile provides a rich set of string processing procedures, because
text handling is very important when Guile is used as a scripting
language.

   Strings always carry the information about how many characters they
are composed of with them, so there is no special end-of-string
character, like in C.  That means that Scheme strings can contain any
character, even the NUL character `'\0''.  But note: Since most
operating system calls dealing with strings (such as for file
operations) expect strings to be zero-terminated, they might do
unexpected things when called with string containing unusual characters.

* Menu:

* String Syntax::               Read syntax for strings.
* String Predicates::           Testing strings for certain properties.
* String Constructors::         Creating new string objects.
* List/String Conversion::      Converting from/to lists of characters.
* String Selection::            Select portions from strings.
* String Modification::         Modify parts or whole strings.
* String Comparison::           Lexicographic ordering predicates.
* String Searching::            Searching in strings.
* Alphabetic Case Mapping::     Convert the alphabetic case of strings.
* Appending Strings::           Appending strings to form a new string.


File: guile.info,  Node: String Syntax,  Next: String Predicates,  Up: Strings

String Read Syntax
------------------

   The read syntax for strings is an arbitrarily long sequence of
characters enclosed in double quotes (`"'). (1)  If you want to insert
a double quote character into a string literal, it must be prefixed
with a backslash `\' character (called an "escape character").

   The following are examples of string literals:

     "foo"
     "bar plonk"
     "Hello World"
     "\"Hi\", he said."

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

   (1) Actually, the current implementation restricts strings to a
length of 2^24 characters.


File: guile.info,  Node: String Predicates,  Next: String Constructors,  Prev: String Syntax,  Up: Strings

String Predicates
-----------------

   The following procedures can be used to check whether a given string
fulfills some specified property.

 - Scheme Procedure: string? obj
 - C Function: scm_string_p (obj)
     Return `#t' if OBJ is a string, else `#f'.

 - Scheme Procedure: string-null? str
 - C Function: scm_string_null_p (str)
     Return `#t' if STR's length is zero, and `#f' otherwise.
          (string-null? "")  => #t
          y                    => "foo"
          (string-null? y)     => #f


File: guile.info,  Node: String Constructors,  Next: List/String Conversion,  Prev: String Predicates,  Up: Strings

String Constructors
-------------------

   The string constructor procedures create new string objects, possibly
initializing them with some specified character data.

 - Scheme Procedure: string . chrs
 - Scheme Procedure: list->string chrs
 - C Function: scm_string (chrs)
     Return a newly allocated string composed of the arguments, CHRS.

 - Scheme Procedure: make-string k [chr]
 - C Function: scm_make_string (k, chr)
     Return a newly allocated string of length K.  If CHR is given,
     then all elements of the string are initialized to CHR, otherwise
     the contents of the STRING are unspecified.


File: guile.info,  Node: List/String Conversion,  Next: String Selection,  Prev: String Constructors,  Up: Strings

List/String conversion
----------------------

   When processing strings, it is often convenient to first convert them
into a list representation by using the procedure `string->list', work
with the resulting list, and then convert it back into a string.  These
procedures are useful for similar tasks.

 - Scheme Procedure: string->list str
 - C Function: scm_string_to_list (str)
     Return a newly allocated list of the characters that make up the
     given string STR. `string->list' and `list->string' are inverses
     as far as `equal?' is concerned.

 - Scheme Procedure: string-split str chr
 - C Function: scm_string_split (str, chr)
     Split the string STR into the a list of the substrings delimited
     by appearances of the character CHR.  Note that an empty substring
     between separator characters will result in an empty string in the
     result list.

          (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
          =>
          ("root" "x" "0" "0" "root" "/root" "/bin/bash")
          
          (string-split "::" #\:)
          =>
          ("" "" "")
          
          (string-split "" #\:)
          =>
          ("")


File: guile.info,  Node: String Selection,  Next: String Modification,  Prev: List/String Conversion,  Up: Strings

String Selection
----------------

   Portions of strings can be extracted by these procedures.
`string-ref' delivers individual characters whereas `substring' can be
used to extract substrings from longer strings.

 - Scheme Procedure: string-length string
 - C Function: scm_string_length (string)
     Return the number of characters in STRING.

 - Scheme Procedure: string-ref str k
 - C Function: scm_string_ref (str, k)
     Return character K of STR using zero-origin indexing. K must be a
     valid index of STR.

 - Scheme Procedure: string-copy str
 - C Function: scm_string_copy (str)
     Return a newly allocated copy of the given STRING.

 - Scheme Procedure: substring str start [end]
 - C Function: scm_substring (str, start, end)
     Return a newly allocated string formed from the characters of STR
     beginning with index START (inclusive) and ending with index END
     (exclusive).  STR must be a string, START and END must be exact
     integers satisfying:

     0 <= START <= END <= (string-length STR).


File: guile.info,  Node: String Modification,  Next: String Comparison,  Prev: String Selection,  Up: Strings

String Modification
-------------------

   These procedures are for modifying strings in-place.  This means
that the result of the operation is not a new string; instead, the
original string's memory representation is modified.

 - Scheme Procedure: string-set! str k chr
 - C Function: scm_string_set_x (str, k, chr)
     Store CHR in element K of STR and return an unspecified value. K
     must be a valid index of STR.

 - Scheme Procedure: string-fill! str chr
 - C Function: scm_string_fill_x (str, chr)
     Store CHAR in every element of the given STRING and return an
     unspecified value.

 - Scheme Procedure: substring-fill! str start end fill
 - C Function: scm_substring_fill_x (str, start, end, fill)
     Change every character in STR between START and END to FILL.

          (define y "abcdefg")
          (substring-fill! y 1 3 #\r)
          y
          => "arrdefg"

 - Scheme Procedure: substring-move! str1 start1 end1 str2 start2
 - C Function: scm_substring_move_x (str1, start1, end1, str2, start2)
     Copy the substring of STR1 bounded by START1 and END1 into STR2
     beginning at position START2.  STR1 and STR2 can be the same
     string.


File: guile.info,  Node: String Comparison,  Next: String Searching,  Prev: String Modification,  Up: Strings

String Comparison
-----------------

   The procedures in this section are similar to the character ordering
predicates (*note Characters::), but are defined on character sequences.
They all return `#t' on success and `#f' on failure.  The predicates
ending in `-ci' ignore the character case when comparing strings.

 - Scheme Procedure: string=? s1 s2
     Lexicographic equality predicate; return `#t' if the two strings
     are the same length and contain the same characters in the same
     positions, otherwise return `#f'.

     The procedure `string-ci=?' treats upper and lower case letters as
     though they were the same character, but `string=?' treats upper
     and lower case as distinct characters.

 - Scheme Procedure: string<? s1 s2
     Lexicographic ordering predicate; return `#t' if S1 is
     lexicographically less than S2.

 - Scheme Procedure: string<=? s1 s2
     Lexicographic ordering predicate; return `#t' if S1 is
     lexicographically less than or equal to S2.

 - Scheme Procedure: string>? s1 s2
     Lexicographic ordering predicate; return `#t' if S1 is
     lexicographically greater than S2.

 - Scheme Procedure: string>=? s1 s2
     Lexicographic ordering predicate; return `#t' if S1 is
     lexicographically greater than or equal to S2.

 - Scheme Procedure: string-ci=? s1 s2
     Case-insensitive string equality predicate; return `#t' if the two
     strings are the same length and their component characters match
     (ignoring case) at each position; otherwise return `#f'.

 - Scheme Procedure: string-ci<? s1 s2
     Case insensitive lexicographic ordering predicate; return `#t' if
     S1 is lexicographically less than S2 regardless of case.

 - Scheme Procedure: string-ci<=? s1 s2
     Case insensitive lexicographic ordering predicate; return `#t' if
     S1 is lexicographically less than or equal to S2 regardless of
     case.

 - Scheme Procedure: string-ci>? s1 s2
     Case insensitive lexicographic ordering predicate; return `#t' if
     S1 is lexicographically greater than S2 regardless of case.

 - Scheme Procedure: string-ci>=? s1 s2
     Case insensitive lexicographic ordering predicate; return `#t' if
     S1 is lexicographically greater than or equal to S2 regardless of
     case.


File: guile.info,  Node: String Searching,  Next: Alphabetic Case Mapping,  Prev: String Comparison,  Up: Strings

String Searching
----------------

   When searching for the index of a character in a string, these
procedures can be used.

 - Scheme Procedure: string-index str chr [frm [to]]
 - C Function: scm_string_index (str, chr, frm, to)
     Return the index of the first occurrence of CHR in STR.  The
     optional integer arguments FRM and TO limit the search to a
     portion of the string.  This procedure essentially implements the
     `index' or `strchr' functions from the C library.

          (string-index "weiner" #\e)
          => 1
          
          (string-index "weiner" #\e 2)
          => 4
          
          (string-index "weiner" #\e 2 4)
          => #f

 - Scheme Procedure: string-rindex str chr [frm [to]]
 - C Function: scm_string_rindex (str, chr, frm, to)
     Like `string-index', but search from the right of the string
     rather than from the left.  This procedure essentially implements
     the `rindex' or `strrchr' functions from the C library.

          (string-rindex "weiner" #\e)
          => 4
          
          (string-rindex "weiner" #\e 2 4)
          => #f
          
          (string-rindex "weiner" #\e 2 5)
          => 4


File: guile.info,  Node: Alphabetic Case Mapping,  Next: Appending Strings,  Prev: String Searching,  Up: Strings

Alphabetic Case Mapping
-----------------------

   These are procedures for mapping strings to their upper- or
lower-case equivalents, respectively, or for capitalizing strings.

 - Scheme Procedure: string-upcase str
 - C Function: scm_string_upcase (str)
     Return a freshly allocated string containing the characters of STR
     in upper case.

 - Scheme Procedure: string-upcase! str
 - C Function: scm_string_upcase_x (str)
     Destructively upcase every character in STR and return STR.
          y                  => "arrdefg"
          (string-upcase! y) => "ARRDEFG"
          y                  => "ARRDEFG"

 - Scheme Procedure: string-downcase str
 - C Function: scm_string_downcase (str)
     Return a freshly allocation string containing the characters in
     STR in lower case.

 - Scheme Procedure: string-downcase! str
 - C Function: scm_string_downcase_x (str)
     Destructively downcase every character in STR and return STR.
          y                     => "ARRDEFG"
          (string-downcase! y)  => "arrdefg"
          y                     => "arrdefg"

 - Scheme Procedure: string-capitalize str
 - C Function: scm_string_capitalize (str)
     Return a freshly allocated string with the characters in STR,
     where the first character of every word is capitalized.

 - Scheme Procedure: string-capitalize! str
 - C Function: scm_string_capitalize_x (str)
     Upcase the first character of every word in STR destructively and
     return STR.

          y                      => "hello world"
          (string-capitalize! y) => "Hello World"
          y                      => "Hello World"


File: guile.info,  Node: Appending Strings,  Prev: Alphabetic Case Mapping,  Up: Strings

Appending Strings
-----------------

   The procedure `string-append' appends several strings together to
form a longer result string.

 - Scheme Procedure: string-append . args
 - C Function: scm_string_append (args)
     Return a newly allocated string whose characters form the
     concatenation of the given strings, ARGS.

          (let ((h "hello "))
            (string-append h "world"))
          => "hello world"


File: guile.info,  Node: Regular Expressions,  Next: Symbols,  Prev: Strings,  Up: Simple Data Types

Regular Expressions
===================

   A "regular expression" (or "regexp") is a pattern that describes a
whole class of strings.  A full description of regular expressions and
their syntax is beyond the scope of this manual; an introduction can be
found in the Emacs manual (*note Syntax of Regular Expressions:
(emacs)Regexps.), or in many general Unix reference books.

   If your system does not include a POSIX regular expression library,
and you have not linked Guile with a third-party regexp library such as
Rx, these functions will not be available.  You can tell whether your
Guile installation includes regular expression support by checking
whether `(provided? 'regex)' returns true.

   The following regexp and string matching features are provided by the
`(ice-9 regex)' module.  Before using the described functions, you
should load this module by executing `(use-modules (ice-9 regex))'.

* Menu:

* Regexp Functions::            Functions that create and match regexps.
* Match Structures::            Finding what was matched by a regexp.
* Backslash Escapes::           Removing the special meaning of regexp
                                meta-characters.


File: guile.info,  Node: Regexp Functions,  Next: Match Structures,  Up: Regular Expressions

Regexp Functions
----------------

   By default, Guile supports POSIX extended regular expressions.  That
means that the characters `(', `)', `+' and `?' are special, and must
be escaped if you wish to match the literal characters.

   This regular expression interface was modeled after that implemented
by SCSH, the Scheme Shell.  It is intended to be upwardly compatible
with SCSH regular expressions.

 - Scheme Procedure: string-match pattern str [start]
     Compile the string PATTERN into a regular expression and compare
     it with STR.  The optional numeric argument START specifies the
     position of STR at which to begin matching.

     `string-match' returns a "match structure" which describes what,
     if anything, was matched by the regular expression.  *Note Match
     Structures::.  If STR does not match PATTERN at all,
     `string-match' returns `#f'.

   Two examples of a match follow.  In the first example, the pattern
matches the four digits in the match string.  In the second, the pattern
matches nothing.

     (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
     => #("blah2002" (4 . 8))
     
     (string-match "[A-Za-z]" "123456")
     => #f

   Each time `string-match' is called, it must compile its PATTERN
argument into a regular expression structure.  This operation is
expensive, which makes `string-match' inefficient if the same regular
expression is used several times (for example, in a loop).  For better
performance, you can compile a regular expression in advance and then
match strings against the compiled regexp.

 - Scheme Procedure: make-regexp pat . flags
 - C Function: scm_make_regexp (pat, flags)
     Compile the regular expression described by PAT, and return the
     compiled regexp structure.  If PAT does not describe a legal
     regular expression, `make-regexp' throws a
     `regular-expression-syntax' error.

     The FLAGS arguments change the behavior of the compiled regular
     expression.  The following flags may be supplied:

    `regexp/icase'
          Consider uppercase and lowercase letters to be the same when
          matching.

    `regexp/newline'
          If a newline appears in the target string, then permit the
          `^' and `$' operators to match immediately after or
          immediately before the newline, respectively.  Also, the `.'
          and `[^...]' operators will never match a newline character.
          The intent of this flag is to treat the target string as a
          buffer containing many lines of text, and the regular
          expression as a pattern that may match a single one of those
          lines.

    `regexp/basic'
          Compile a basic ("obsolete") regexp instead of the extended
          ("modern") regexps that are the default.  Basic regexps do
          not consider `|', `+' or `?' to be special characters, and
          require the `{...}' and `(...)' metacharacters to be
          backslash-escaped (*note Backslash Escapes::).  There are
          several other differences between basic and extended regular
          expressions, but these are the most significant.

    `regexp/extended'
          Compile an extended regular expression rather than a basic
          regexp.  This is the default behavior; this flag will not
          usually be needed.  If a call to `make-regexp' includes both
          `regexp/basic' and `regexp/extended' flags, the one which
          comes last will override the earlier one.

 - Scheme Procedure: regexp-exec rx str [start [flags]]
 - C Function: scm_regexp_exec (rx, str, start, flags)
     Match the compiled regular expression RX against `str'.  If the
     optional integer START argument is provided, begin matching from
     that position in the string.  Return a match structure describing
     the results of the match, or `#f' if no match could be found.

     The FLAGS arguments change the matching behavior.  The following
     flags may be supplied:

    `regexp/notbol'
          Operator `^' always fails (unless `regexp/newline' is used).
          Use this when the beginning of the string should not be
          considered the beginning of a line.

    `regexp/noteol'
          Operator `$' always fails (unless `regexp/newline' is used).
          Use this when the end of the string should not be considered
          the end of a line.

     ;; Regexp to match uppercase letters
     (define r (make-regexp "[A-Z]*"))
     
     ;; Regexp to match letters, ignoring case
     (define ri (make-regexp "[A-Z]*" regexp/icase))
     
     ;; Search for bob using regexp r
     (match:substring (regexp-exec r "bob"))
     => ""                  ; no match
     
     ;; Search for bob using regexp ri
     (match:substring (regexp-exec ri "Bob"))
     => "Bob"               ; matched case insensitive

 - Scheme Procedure: regexp? obj
 - C Function: scm_regexp_p (obj)
     Return `#t' if OBJ is a compiled regular expression, or `#f'
     otherwise.

   Regular expressions are commonly used to find patterns in one string
and replace them with the contents of another string.

 - Scheme Procedure: regexp-substitute port match [item...]
     Write to the output port PORT selected contents of the match
     structure MATCH.  Each ITEM specifies what should be written, and
     may be one of the following arguments:

        * A string.  String arguments are written out verbatim.

        * An integer.  The submatch with that number is written.

        * The symbol `pre'.  The portion of the matched string preceding
          the regexp match is written.

        * The symbol `post'.  The portion of the matched string
          following the regexp match is written.

     The PORT argument may be `#f', in which case nothing is written;
     instead, `regexp-substitute' constructs a string from the
     specified ITEMs and returns that.

   The following example takes a regular expression that matches a
standard YYYYMMDD-format date such as `"20020828"'.  The
`regexp-substitute' call returns a string computed from the information
in the match structure, consisting of the fields and text from the
original string reordered and reformatted.

     (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
     (define s "Date 20020429 12am.")
     (define sm (string-match date-regex s))
     (regexp-substitute #f sm 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
     => "Date 04-29-2002 12am. (20020429)"

 - Scheme Procedure: regexp-substitute/global port regexp target
          [item...]
     Similar to `regexp-substitute', but can be used to perform global
     substitutions on STR.  Instead of taking a match structure as an
     argument, `regexp-substitute/global' takes two string arguments: a
     REGEXP string describing a regular expression, and a TARGET string
     which should be matched against this regular expression.

     Each ITEM behaves as in REGEXP-SUBSTITUTE, with the following
     exceptions:

        * A function may be supplied.  When this function is called, it
          will be passed one argument: a match structure for a given
          regular expression match.  It should return a string to be
          written out to PORT.

        * The `post' symbol causes `regexp-substitute/global' to recurse
          on the unmatched portion of STR.  This _must_ be supplied in
          order to perform global search-and-replace on STR; if it is
          not present among the ITEMs, then `regexp-substitute/global'
          will return after processing a single match.

   The example above for `regexp-substitute' could be rewritten as
follows to remove the `string-match' stage:

     (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
     (define s "Date 20020429 12am.")
     (regexp-substitute/global #f date-regex s
       'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
     => "Date 04-29-2002 12am. (20020429)"


File: guile.info,  Node: Match Structures,  Next: Backslash Escapes,  Prev: Regexp Functions,  Up: Regular Expressions

Match Structures
----------------

   A "match structure" is the object returned by `string-match' and
`regexp-exec'.  It describes which portion of a string, if any, matched
the given regular expression.  Match structures include: a reference to
the string that was checked for matches; the starting and ending
positions of the regexp match; and, if the regexp included any
parenthesized subexpressions, the starting and ending positions of each
submatch.

   In each of the regexp match functions described below, the `match'
argument must be a match structure returned by a previous call to
`string-match' or `regexp-exec'.  Most of these functions return some
information about the original target string that was matched against a
regular expression; we will call that string TARGET for easy reference.

 - Scheme Procedure: regexp-match? obj
     Return `#t' if OBJ is a match structure returned by a previous
     call to `regexp-exec', or `#f' otherwise.

 - Scheme Procedure: match:substring match [n]
     Return the portion of TARGET matched by subexpression number N.
     Submatch 0 (the default) represents the entire regexp match.  If
     the regular expression as a whole matched, but the subexpression
     number N did not match, return `#f'.

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:substring s)
     => "2002"
     
     ;; match starting at offset 6 in the string
     (match:substring
       (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
     => "7654"

 - Scheme Procedure: match:start match [n]
     Return the starting position of submatch number N.

   In the following example, the result is 4, since the match starts at
character index 4:

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:start s)
     => 4

 - Scheme Procedure: match:end match [n]
     Return the ending position of submatch number N.

   In the following example, the result is 8, since the match runs
between characters 4 and 8 (i.e. the "2002").

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:end s)
     => 8

 - Scheme Procedure: match:prefix match
     Return the unmatched portion of TARGET preceding the regexp match.

          (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
          (match:prefix s)
          => "blah"

 - Scheme Procedure: match:suffix match
     Return the unmatched portion of TARGET following the regexp match.

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:suffix s)
     => "foo"

 - Scheme Procedure: match:count match
     Return the number of parenthesized subexpressions from MATCH.
     Note that the entire regular expression match itself counts as a
     subexpression, and failed submatches are included in the count.

 - Scheme Procedure: match:string match
     Return the original TARGET string.

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:string s)
     => "blah2002foo"


File: guile.info,  Node: Backslash Escapes,  Prev: Match Structures,  Up: Regular Expressions

Backslash Escapes
-----------------

   Sometimes you will want a regexp to match characters like `*' or `$'
exactly.  For example, to check whether a particular string represents
a menu entry from an Info node, it would be useful to match it against
a regexp like `^* [^:]*::'.  However, this won't work; because the
asterisk is a metacharacter, it won't match the `*' at the beginning of
the string.  In this case, we want to make the first asterisk un-magic.

   You can do this by preceding the metacharacter with a backslash
character `\'.  (This is also called "quoting" the metacharacter, and
is known as a "backslash escape".)  When Guile sees a backslash in a
regular expression, it considers the following glyph to be an ordinary
character, no matter what special meaning it would ordinarily have.
Therefore, we can make the above example work by changing the regexp to
`^\* [^:]*::'.  The `\*' sequence tells the regular expression engine
to match only a single asterisk in the target string.

   Since the backslash is itself a metacharacter, you may force a
regexp to match a backslash in the target string by preceding the
backslash with itself.  For example, to find variable references in a
TeX program, you might want to find occurrences of the string `\let\'
followed by any number of alphabetic characters.  The regular expression
`\\let\\[A-Za-z]*' would do this: the double backslashes in the regexp
each match a single backslash in the target string.

 - Scheme Procedure: regexp-quote str
     Quote each special character found in STR with a backslash, and
     return the resulting string.

   *Very important:* Using backslash escapes in Guile source code (as
in Emacs Lisp or C) can be tricky, because the backslash character has
special meaning for the Guile reader.  For example, if Guile encounters
the character sequence `\n' in the middle of a string while processing
Scheme code, it replaces those characters with a newline character.
Similarly, the character sequence `\t' is replaced by a horizontal tab.
Several of these "escape sequences" are processed by the Guile reader
before your code is executed.  Unrecognized escape sequences are
ignored: if the characters `\*' appear in a string, they will be
translated to the single character `*'.

   This translation is obviously undesirable for regular expressions,
since we want to be able to include backslashes in a string in order to
escape regexp metacharacters.  Therefore, to make sure that a backslash
is preserved in a string in your Guile program, you must use _two_
consecutive backslashes:

     (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))

   The string in this example is preprocessed by the Guile reader before
any code is executed.  The resulting argument to `make-regexp' is the
string `^\* [^:]*', which is what we really want.

   This also means that in order to write a regular expression that
matches a single backslash character, the regular expression string in
the source code must include _four_ backslashes.  Each consecutive pair
of backslashes gets translated by the Guile reader to a single
backslash, and the resulting double-backslash is interpreted by the
regexp engine as matching a single backslash character.  Hence:

     (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))

   The reason for the unwieldiness of this syntax is historical.  Both
regular expression pattern matchers and Unix string processing systems
have traditionally used backslashes with the special meanings described
above.  The POSIX regular expression specification and ANSI C standard
both require these semantics.  Attempting to abandon either convention
would cause other kinds of compatibility problems, possibly more severe
ones.  Therefore, without extending the Scheme reader to support
strings with different quoting conventions (an ungainly and confusing
extension when implemented in other languages), we must adhere to this
cumbersome escape syntax.


File: guile.info,  Node: Symbols,  Next: Keywords,  Prev: Regular Expressions,  Up: Simple Data Types

Symbols
=======

   Symbols in Scheme are widely used in three ways: as items of discrete
data, as lookup keys for alists and hash tables, and to denote variable
references.

   A "symbol" is similar to a string in that it is defined by a
sequence of characters.  The sequence of characters is known as the
symbol's "name".  In the usual case -- that is, where the symbol's name
doesn't include any characters that could be confused with other
elements of Scheme syntax -- a symbol is written in a Scheme program by
writing the sequence of characters that make up the name, _without_ any
quotation marks or other special syntax.  For example, the symbol whose
name is "multiply-by-2" is written, simply:

     multiply-by-2

   Notice how this differs from a _string_ with contents
"multiply-by-2", which is written with double quotation marks, like
this:

     "multiply-by-2"

   Looking beyond how they are written, symbols are different from
strings in two important respects.

   The first important difference is uniqueness.  If the same-looking
string is read twice from two different places in a program, the result
is two _different_ string objects whose contents just happen to be the
same.  If, on the other hand, the same-looking symbol is read twice
from two different places in a program, the result is the _same_ symbol
object both times.

   Given two read symbols, you can use `eq?' to test whether they are
the same (that is, have the same name).  `eq?' is the most efficient
comparison operator in Scheme, and comparing two symbols like this is
as fast as comparing, for example, two numbers.  Given two strings, on
the other hand, you must use `equal?' or `string=?', which are much
slower comparison operators, to determine whether the strings have the
same contents.

     (define sym1 (quote hello))
     (define sym2 (quote hello))
     (eq? sym1 sym2) => #t
     
     (define str1 "hello")
     (define str2 "hello")
     (eq? str1 str2) => #f
     (equal? str1 str2) => #t

   The second important difference is that symbols, unlike strings, are
not self-evaluating.  This is why we need the `(quote ...)'s in the
example above: `(quote hello)' evaluates to the symbol named "hello"
itself, whereas an unquoted `hello' is _read_ as the symbol named
"hello" and evaluated as a variable reference ... about which more
below (*note Symbol Variables::).

* Menu:

* Symbol Data::                 Symbols as discrete data.
* Symbol Keys::                 Symbols as lookup keys.
* Symbol Variables::            Symbols as denoting variables.
* Symbol Primitives::           Operations related to symbols.
* Symbol Props::                Function slots and property lists.
* Symbol Read Syntax::          Extended read syntax for symbols.


File: guile.info,  Node: Symbol Data,  Next: Symbol Keys,  Up: Symbols

Symbols as Discrete Data
------------------------

   Numbers and symbols are similar to the extent that they both lend
themselves to `eq?' comparison.  But symbols are more descriptive than
numbers, because a symbol's name can be used directly to describe the
concept for which that symbol stands.

   For example, imagine that you need to represent some colours in a
computer program.  Using numbers, you would have to choose arbitrarily
some mapping between numbers and colours, and then take care to use that
mapping consistently:

     ;; 1=red, 2=green, 3=purple
     
     (if (eq? (colour-of car) 1)
         ...)

You can make the mapping more explicit and the code more readable by
defining constants:

     (define red 1)
     (define green 2)
     (define purple 3)
     
     (if (eq? (colour-of car) red)
         ...)

But the simplest and clearest approach is not to use numbers at all, but
symbols whose names specify the colours that they refer to:

     (if (eq? (colour-of car) 'red)
         ...)

   The descriptive advantages of symbols over numbers increase as the
set of concepts that you want to describe grows.  Suppose that a car
object can have other properties as well, such as whether it has or
uses:

   * automatic or manual transmission

   * leaded or unleaded fuel

   * power steering (or not).

Then a car's combined property set could be naturally represented and
manipulated as a list of symbols:

     (properties-of car1)
     =>
     (red manual unleaded power-steering)
     
     (if (memq 'power-steering (properties-of car1))
         (display "Unfit people can drive this car.\n")
         (display "You'll need strong arms to drive this car!\n"))
     -|
     Unfit people can drive this car.

   Remember, the fundamental property of symbols that we are relying on
here is that an occurrence of `'red' in one part of a program is an
_indistinguishable_ symbol from an occurrence of `'red' in another part
of a program; this means that symbols can usefully be compared using
`eq?'.  At the same time, symbols have naturally descriptive names.
This combination of efficiency and descriptive power makes them ideal
for use as discrete data.


File: guile.info,  Node: Symbol Keys,  Next: Symbol Variables,  Prev: Symbol Data,  Up: Symbols

Symbols as Lookup Keys
----------------------

   Given their efficiency and descriptive power, it is natural to use
symbols as the keys in an association list or hash table.

   To illustrate this, consider a more structured representation of the
car properties example from the preceding subsection.  Rather than
mixing all the properties up together in a flat list, we could use an
association list like this:

     (define car1-properties '((colour . red)
                               (transmission . manual)
                               (fuel . unleaded)
                               (steering . power-assisted)))

   Notice how this structure is more explicit and extensible than the
flat list.  For example it makes clear that `manual' refers to the
transmission rather than, say, the windows or the locking of the car.
It also allows further properties to use the same symbols among their
possible values without becoming ambiguous:

     (define car1-properties '((colour . red)
                               (transmission . manual)
                               (fuel . unleaded)
                               (steering . power-assisted)
                               (seat-colour . red)
                               (locking . manual)))

   With a representation like this, it is easy to use the efficient
`assq-XXX' family of procedures (*note Association Lists::) to extract
or change individual pieces of information:

     (assq-ref car1-properties 'fuel) => unleaded
     (assq-ref car1-properties 'transmission) => manual
     
     (assq-set! car1-properties 'seat-colour 'black)
     =>
     ((colour . red)
      (transmission . manual)
      (fuel . unleaded)
      (steering . power-assisted)
      (seat-colour . black)
      (locking . manual)))

   Hash tables also have keys, and exactly the same arguments apply to
the use of symbols in hash tables as in association lists.  The hash
value that Guile uses to decide where to add a symbol-keyed entry to a
hash table can be obtained by calling the `symbol-hash' procedure:

 - Scheme Procedure: symbol-hash symbol
 - C Function: scm_symbol_hash (symbol)
     Return a hash value for SYMBOL.

   See *Note Hash Tables:: for information about hash tables in
general, and for why you might choose to use a hash table rather than
an association list.


File: guile.info,  Node: Symbol Variables,  Next: Symbol Primitives,  Prev: Symbol Keys,  Up: Symbols

Symbols as Denoting Variables
-----------------------------

   When an unquoted symbol in a Scheme program is evaluated, it is
interpreted as a variable reference, and the result of the evaluation is
the appropriate variable's value.

   For example, when the expression `(string-length "abcd")' is read
and evaluated, the sequence of characters `string-length' is read as
the symbol whose name is "string-length".  This symbol is associated
with a variable whose value is the procedure that implements string
length calculation.  Therefore evaluation of the `string-length' symbol
results in that procedure.

   The details of the connection between an unquoted symbol and the
variable to which it refers are explained elsewhere.  See *Note Binding
Constructs::, for how associations between symbols and variables are
created, and *Note Modules::, for how those associations are affected by
Guile's module system.


File: guile.info,  Node: Symbol Primitives,  Next: Symbol Props,  Prev: Symbol Variables,  Up: Symbols

Operations Related to Symbols
-----------------------------

   Given any Scheme value, you can determine whether it is a symbol
using the `symbol?' primitive:

 - Scheme Procedure: symbol? obj
 - C Function: scm_symbol_p (obj)
     Return `#t' if OBJ is a symbol, otherwise return `#f'.

   Once you know that you have a symbol, you can obtain its name as a
string by calling `symbol->string'.  Note that Guile differs by default
from R5RS on the details of `symbol->string' as regards
case-sensitivity:

 - Scheme Procedure: symbol->string s
 - C Function: scm_symbol_to_string (s)
     Return the name of symbol S as a string.  By default, Guile reads
     symbols case-sensitively, so the string returned will have the
     same case variation as the sequence of characters that caused S to
     be created.

     If Guile is set to read symbols case-insensitively (as specified by
     R5RS), and S comes into being as part of a literal expression
     (*note Literal expressions: (r5rs)Literal expressions.) or by a
     call to the `read' or `string-ci->symbol' procedures, Guile
     converts any alphabetic characters in the symbol's name to lower
     case before creating the symbol object, so the string returned
     here will be in lower case.

     If S was created by `string->symbol', the case of characters in
     the string returned will be the same as that in the string that was
     passed to `string->symbol', regardless of Guile's case-sensitivity
     setting at the time S was created.

     It is an error to apply mutation procedures like `string-set!' to
     strings returned by this procedure.

   Most symbols are created by writing them literally in code.  However
it is also possible to create symbols programmatically using the
following `string->symbol' and `string-ci->symbol' procedures:

 - Scheme Procedure: string->symbol string
 - C Function: scm_string_to_symbol (string)
     Return the symbol whose name is STRING.  This procedure can create
     symbols with names containing special characters or letters in the
     non-standard case, but it is usually a bad idea to create such
     symbols because in some implementations of Scheme they cannot be
     read as themselves.

 - Scheme Procedure: string-ci->symbol str
 - C Function: scm_string_ci_to_symbol (str)
     Return the symbol whose name is STR.  If Guile is currently
     reading symbols case-insensitively, STR is converted to lowercase
     before the returned symbol is looked up or created.

   The following examples illustrate Guile's detailed behaviour as
regards the case-sensitivity of symbols:

     (read-enable 'case-insensitive)   ; R5RS compliant behaviour
     
     (symbol->string 'flying-fish)    => "flying-fish"
     (symbol->string 'Martin)         => "martin"
     (symbol->string
        (string->symbol "Malvina"))   => "Malvina"
     
     (eq? 'mISSISSIppi 'mississippi)  => #t
     (string->symbol "mISSISSIppi")   => mISSISSIppi
     (eq? 'bitBlt (string->symbol "bitBlt")) => #f
     (eq? 'LolliPop
       (string->symbol (symbol->string 'LolliPop))) => #t
     (string=? "K. Harper, M.D."
       (symbol->string
         (string->symbol "K. Harper, M.D."))) => #t
     
     (read-disable 'case-insensitive)   ; Guile default behaviour
     
     (symbol->string 'flying-fish)    => "flying-fish"
     (symbol->string 'Martin)         => "Martin"
     (symbol->string
        (string->symbol "Malvina"))   => "Malvina"
     
     (eq? 'mISSISSIppi 'mississippi)  => #f
     (string->symbol "mISSISSIppi")   => mISSISSIppi
     (eq? 'bitBlt (string->symbol "bitBlt")) => #t
     (eq? 'LolliPop
       (string->symbol (symbol->string 'LolliPop))) => #t
     (string=? "K. Harper, M.D."
       (symbol->string
         (string->symbol "K. Harper, M.D."))) => #t

   Finally, some applications, especially those that generate new Scheme
code dynamically, need to generate symbols for use in the generated
code.  The `gensym' primitive meets this need:

 - Scheme Procedure: gensym [prefix]
 - C Function: scm_gensym (prefix)
     Create a new symbol with a name constructed from a prefix and a
     counter value.  The string PREFIX can be specified as an optional
     argument.  Default prefix is ` g'.  The counter is increased by 1
     at each call.  There is no provision for resetting the counter.

   The symbols generated by `gensym' are _likely_ to be unique, since
their names begin with a space and it is only otherwise possible to
generate such symbols if a programmer goes out of their way to do so.
The 1.8 release of Guile will include a way of creating symbols that
are _guaranteed_ to be unique.


File: guile.info,  Node: Symbol Props,  Next: Symbol Read Syntax,  Prev: Symbol Primitives,  Up: Symbols

Function Slots and Property Lists
---------------------------------

   In traditional Lisp dialects, symbols are often understood as having
three kinds of value at once:

   * a "variable" value, which is used when the symbol appears in code
     in a variable reference context

   * a "function" value, which is used when the symbol appears in code
     in a function name position (i.e. as the first element in an
     unquoted list)

   * a "property list" value, which is used when the symbol is given as
     the first argument to Lisp's `put' or `get' functions.

   Although Scheme (as one of its simplifications with respect to Lisp)
does away with the distinction between variable and function namespaces,
Guile currently retains some elements of the traditional structure in
case they turn out to be useful when implementing translators for other
languages, in particular Emacs Lisp.

   Specifically, Guile symbols have two extra slots. for a symbol's
property list, and for its "function value."  The following procedures
are provided to access these slots.

 - Scheme Procedure: symbol-fref symbol
 - C Function: scm_symbol_fref (symbol)
     Return the contents of SYMBOL's "function slot".

 - Scheme Procedure: symbol-fset! symbol value
 - C Function: scm_symbol_fset_x (symbol, value)
     Set the contents of SYMBOL's function slot to VALUE.

 - Scheme Procedure: symbol-pref symbol
 - C Function: scm_symbol_pref (symbol)
     Return the "property list" currently associated with SYMBOL.

 - Scheme Procedure: symbol-pset! symbol value
 - C Function: scm_symbol_pset_x (symbol, value)
     Set SYMBOL's property list to VALUE.

 - Scheme Procedure: symbol-property sym prop
     From SYM's property list, return the value for property PROP.  The
     assumption is that SYM's property list is an association list
     whose keys are distinguished from each other using `equal?'; PROP
     should be one of the keys in that list.  If the property list has
     no entry for PROP, `symbol-property' returns `#f'.

 - Scheme Procedure: set-symbol-property! sym prop val
     In SYM's property list, set the value for property PROP to VAL, or
     add a new entry for PROP, with value VAL, if none already exists.
     For the structure of the property list, see `symbol-property'.

 - Scheme Procedure: symbol-property-remove! sym prop
     From SYM's property list, remove the entry for property PROP, if
     there is one.  For the structure of the property list, see
     `symbol-property'.

   Support for these extra slots may be removed in a future release,
and it is probably better to avoid using them.  (In release 1.6, Guile
itself uses the property list slot sparingly, and the function slot not
at all.)  For a more modern and Schemely approach to properties, see
*Note Object Properties::.


File: guile.info,  Node: Symbol Read Syntax,  Prev: Symbol Props,  Up: Symbols

Extended Read Syntax for Symbols
--------------------------------

   The read syntax for a symbol is a sequence of letters, digits, and
"extended alphabetic characters", beginning with a character that
cannot begin a number.  In addition, the special cases of `+', `-', and
`...' are read as symbols even though numbers can begin with `+', `-'
or `.'.

   Extended alphabetic characters may be used within identifiers as if
they were letters.  The set of extended alphabetic characters is:

     ! $ % & * + - . / : < = > ? @ ^ _ ~

   In addition to the standard read syntax defined above (which is taken
from R5RS (*note Formal syntax: (r5rs)Formal syntax.)), Guile provides
an extended symbol read syntax that allows the inclusion of unusual
characters such as space characters, newlines and parentheses.  If (for
whatever reason) you need to write a symbol containing characters not
mentioned above, you can do so as follows.

   * Begin the symbol with the characters `#{',

   * write the characters of the symbol and

   * finish the symbol with the characters `}#'.

   Here are a few examples of this form of read syntax.  The first
symbol needs to use extended syntax because it contains a space
character, the second because it contains a line break, and the last
because it looks like a number.

     #{foo bar}#
     
     #{what
     ever}#
     
     #{4242}#

   Although Guile provides this extended read syntax for symbols,
widespread usage of it is discouraged because it is not portable and not
very readable.


File: guile.info,  Node: Keywords,  Next: Other Types,  Prev: Symbols,  Up: Simple Data Types

Keywords
========

   Keywords are self-evaluating objects with a convenient read syntax
that makes them easy to type.

   Guile's keyword support conforms to R5RS, and adds a (switchable)
read syntax extension to permit keywords to begin with `:' as well as
`#:'.

* Menu:

* Why Use Keywords?::           Motivation for keyword usage.
* Coding With Keywords::        How to use keywords.
* Keyword Read Syntax::         Read syntax for keywords.
* Keyword Procedures::          Procedures for dealing with keywords.
* Keyword Primitives::          The underlying primitive procedures.


File: guile.info,  Node: Why Use Keywords?,  Next: Coding With Keywords,  Up: Keywords

Why Use Keywords?
-----------------

   Keywords are useful in contexts where a program or procedure wants
to be able to accept a large number of optional arguments without
making its interface unmanageable.

   To illustrate this, consider a hypothetical `make-window' procedure,
which creates a new window on the screen for drawing into using some
graphical toolkit.  There are many parameters that the caller might
like to specify, but which could also be sensibly defaulted, for
example:

   * color depth - Default: the color depth for the screen

   * background color - Default: white

   * width - Default: 600

   * height - Default: 400

   If `make-window' did not use keywords, the caller would have to pass
in a value for each possible argument, remembering the correct argument
order and using a special value to indicate the default value for that
argument:

     (make-window 'default              ;; Color depth
                  'default              ;; Background color
                  800                   ;; Width
                  100                   ;; Height
                  ...)                  ;; More make-window arguments

   With keywords, on the other hand, defaulted arguments are omitted,
and non-default arguments are clearly tagged by the appropriate
keyword.  As a result, the invocation becomes much clearer:

     (make-window #:width 800 #:height 100)

   On the other hand, for a simpler procedure with few arguments, the
use of keywords would be a hindrance rather than a help.  The primitive
procedure `cons', for example, would not be improved if it had to be
invoked as

     (cons #:car x #:cdr y)

   So the decision whether to use keywords or not is purely pragmatic:
use them if they will clarify the procedure invocation at point of call.


File: guile.info,  Node: Coding With Keywords,  Next: Keyword Read Syntax,  Prev: Why Use Keywords?,  Up: Keywords

Coding With Keywords
--------------------

   If a procedure wants to support keywords, it should take a rest
argument and then use whatever means is convenient to extract keywords
and their corresponding arguments from the contents of that rest
argument.

   The following example illustrates the principle: the code for
`make-window' uses a helper procedure called `get-keyword-value' to
extract individual keyword arguments from the rest argument.

     (define (get-keyword-value args keyword default)
       (let ((kv (memq keyword args)))
         (if (and kv (>= (length kv) 2))
             (cadr kv)
             default)))
     
     (define (make-window . args)
       (let ((depth  (get-keyword-value args #:depth  screen-depth))
             (bg     (get-keyword-value args #:bg     "white"))
             (width  (get-keyword-value args #:width  800))
             (height (get-keyword-value args #:height 100))
             ...)
         ...))

   But you don't need to write `get-keyword-value'.  The `(ice-9
optargs)' module provides a set of powerful macros that you can use to
implement keyword-supporting procedures like this:

     (use-modules (ice-9 optargs))
     
     (define (make-window . args)
       (let-keywords args #f ((depth  screen-depth)
                              (bg     "white")
                              (width  800)
                              (height 100))
         ...))

Or, even more economically, like this:

     (use-modules (ice-9 optargs))
     
     (define* (make-window #:key (depth  screen-depth)
                                 (bg     "white")
                                 (width  800)
                                 (height 100))
       ...)

   For further details on `let-keywords', `define*' and other
facilities provided by the `(ice-9 optargs)' module, see *Note Optional
Arguments::.


File: guile.info,  Node: Keyword Read Syntax,  Next: Keyword Procedures,  Prev: Coding With Keywords,  Up: Keywords

Keyword Read Syntax
-------------------

   Guile, by default, only recognizes the keyword syntax specified by
R5RS.  A token of the form `#:NAME', where `NAME' has the same syntax
as a Scheme symbol (*note Symbol Read Syntax::), is the external
representation of the keyword named `NAME'.  Keyword objects print
using this syntax as well, so values containing keyword objects can be
read back into Guile.  When used in an expression, keywords are
self-quoting objects.

   If the `keyword' read option is set to `'prefix', Guile also
recognizes the alternative read syntax `:NAME'.  Otherwise, tokens of
the form `:NAME' are read as symbols, as required by R5RS.

   To enable and disable the alternative non-R5RS keyword syntax, you
use the `read-set!' procedure documented in *Note User level options
interfaces:: and *Note Reader options::.

     (read-set! keywords 'prefix)
     
     #:type
     =>
     #:type
     
     :type
     =>
     #:type
     
     (read-set! keywords #f)
     
     #:type
     =>
     #:type
     
     :type
     -|
     ERROR: In expression :type:
     ERROR: Unbound variable: :type
     ABORT: (unbound-variable)


File: guile.info,  Node: Keyword Procedures,  Next: Keyword Primitives,  Prev: Keyword Read Syntax,  Up: Keywords

Keyword Procedures
------------------

   The following procedures can be used for converting symbols to
keywords and back.

 - Scheme Procedure: symbol->keyword sym
     Return a keyword with the same characters as in SYM.

 - Scheme Procedure: keyword->symbol kw
     Return a symbol with the same characters as in KW.


File: guile.info,  Node: Keyword Primitives,  Prev: Keyword Procedures,  Up: Keywords

Keyword Primitives
------------------

   Internally, a keyword is implemented as something like a tagged
symbol, where the tag identifies the keyword as being self-evaluating,
and the symbol, known as the keyword's "dash symbol" has the same name
as the keyword name but prefixed by a single dash.  For example, the
keyword `#:name' has the corresponding dash symbol `-name'.

   Most keyword objects are constructed automatically by the reader
when it reads a token beginning with `#:'.  However, if you need to
construct a keyword object programmatically, you can do so by calling
`make-keyword-from-dash-symbol' with the corresponding dash symbol (as
the reader does).  The dash symbol for a keyword object can be
retrieved using the `keyword-dash-symbol' procedure.

 - Scheme Procedure: make-keyword-from-dash-symbol symbol
 - C Function: scm_make_keyword_from_dash_symbol (symbol)
     Make a keyword object from a SYMBOL that starts with a dash.

 - Scheme Procedure: keyword? obj
 - C Function: scm_keyword_p (obj)
     Return `#t' if the argument OBJ is a keyword, else `#f'.

 - Scheme Procedure: keyword-dash-symbol keyword
 - C Function: scm_keyword_dash_symbol (keyword)
     Return the dash symbol for KEYWORD.  This is the inverse of
     `make-keyword-from-dash-symbol'.


File: guile.info,  Node: Other Types,  Prev: Keywords,  Up: Simple Data Types

"Functionality-Centric" Data Types
==================================

   Procedures and macros are documented in their own chapter: see *Note
Procedures and Macros::.

   Variable objects are documented as part of the description of Guile's
module system: see *Note Variables::.

   Asyncs, dynamic roots and fluids are described in the chapter on
scheduling: see *Note Scheduling::.

   Hooks are documented in the chapter on general utility functions: see
*Note Hooks::.

   Ports are described in the chapter on I/O: see *Note Input and
Output::.


File: guile.info,  Node: Compound Data Types,  Next: Procedures and Macros,  Prev: Simple Data Types,  Up: Top

Compound Data Types
*******************

   This chapter describes Guile's compound data types.  By "compound"
we mean that the primary purpose of these data types is to act as
containers for other kinds of data (including other compound objects).
For instance, a (non-uniform) vector with length 5 is a container that
can hold five arbitrary Scheme objects.

   The various kinds of container object differ from each other in how
their memory is allocated, how they are indexed, and how particular
values can be looked up within them.

* Menu:

* Pairs::                       Scheme's basic building block.
* Lists::                       Special list functions supported by Guile.
* Vectors::                     One-dimensional arrays of Scheme objects.
* Records::
* Structures::
* Arrays::                      Arrays of values.
* Association Lists and Hash Tables::  Dictionary data types.


File: guile.info,  Node: Pairs,  Next: Lists,  Up: Compound Data Types

Pairs
=====

   Pairs are used to combine two Scheme objects into one compound
object.  Hence the name: A pair stores a pair of objects.

   The data type "pair" is extremely important in Scheme, just like in
any other Lisp dialect.  The reason is that pairs are not only used to
make two values available as one object, but that pairs are used for
constructing lists of values.  Because lists are so important in Scheme,
they are described in a section of their own (*note Lists::).

   Pairs can literally get entered in source code or at the REPL, in the
so-called "dotted list" syntax.  This syntax consists of an opening
parentheses, the first element of the pair, a dot, the second element
and a closing parentheses.  The following example shows how a pair
consisting of the two numbers 1 and 2, and a pair containing the symbols
`foo' and `bar' can be entered.  It is very important to write the
whitespace before and after the dot, because otherwise the Scheme
parser would not be able to figure out where to split the tokens.

     (1 . 2)
     (foo . bar)

   But beware, if you want to try out these examples, you have to
"quote" the expressions.  More information about quotation is available
in the section (REFFIXME).  The correct way to try these examples is as
follows.

     '(1 . 2)
     =>
     (1 . 2)
     '(foo . bar)
     =>
     (foo . bar)

   A new pair is made by calling the procedure `cons' with two
arguments.  Then the argument values are stored into a newly allocated
pair, and the pair is returned.  The name `cons' stands for
"construct".  Use the procedure `pair?' to test whether a given Scheme
object is a pair or not.

 - Scheme Procedure: cons x y
 - C Function: scm_cons (x, y)
     Return a newly allocated pair whose car is X and whose cdr is Y.
     The pair is guaranteed to be different (in the sense of `eq?')
     from every previously existing object.

 - Scheme Procedure: pair? x
 - C Function: scm_pair_p (x)
     Return `#t' if X is a pair; otherwise return `#f'.

   The two parts of a pair are traditionally called "car" and "cdr".
They can be retrieved with procedures of the same name (`car' and
`cdr'), and can be modified with the procedures `set-car!' and
`set-cdr!'.  Since a very common operation in Scheme programs is to
access the car of a pair, or the car of the cdr of a pair, etc., the
procedures called `caar', `cadr' and so on are also predefined.

 - Scheme Procedure: car pair
 - Scheme Procedure: cdr pair
     Return the car or the cdr of PAIR, respectively.

 - Scheme Procedure: caar pair
 - Scheme Procedure: cadr pair ...
 - Scheme Procedure: cdddar pair
 - Scheme Procedure: cddddr pair
     These procedures are compositions of `car' and `cdr', where for
     example `caddr' could be defined by

          (define caddr (lambda (x) (car (cdr (cdr x)))))

 - Scheme Procedure: set-car! pair value
 - C Function: scm_set_car_x (pair, value)
     Stores VALUE in the car field of PAIR.  The value returned by
     `set-car!' is unspecified.

 - Scheme Procedure: set-cdr! pair value
 - C Function: scm_set_cdr_x (pair, value)
     Stores VALUE in the cdr field of PAIR.  The value returned by
     `set-cdr!' is unspecified.


File: guile.info,  Node: Lists,  Next: Vectors,  Prev: Pairs,  Up: Compound Data Types

Lists
=====

   A very important data type in Scheme--as well as in all other Lisp
dialects--is the data type "list".(1)

   This is the short definition of what a list is:

   * Either the empty list `()',

   * or a pair which has a list in its cdr.

* Menu:

* List Syntax::                 Writing literal lists.
* List Predicates::             Testing lists.
* List Constructors::           Creating new lists.
* List Selection::              Selecting from lists, getting their length.
* Append/Reverse::              Appending and reversing lists.
* List Modification::           Modifying existing lists.
* List Searching::              Searching for list elements
* List Mapping::                Applying procedures to lists.

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

   (1) Strictly speaking, Scheme does not have a real datatype "list".
Lists are made up of "chained pairs", and only exist by definition--a
list is a chain of pairs which looks like a list.


File: guile.info,  Node: List Syntax,  Next: List Predicates,  Up: Lists

List Read Syntax
----------------

   The syntax for lists is an opening parentheses, then all the
elements of the list (separated by whitespace) and finally a closing
parentheses.(1).

     (1 2 3)            ; a list of the numbers 1, 2 and 3
     ("foo" bar 3.1415) ; a string, a symbol and a real number
     ()                 ; the empty list

   The last example needs a bit more explanation.  A list with no
elements, called the "empty list", is special in some ways.  It is used
for terminating lists by storing it into the cdr of the last pair that
makes up a list.  An example will clear that up:

     (car '(1))
     =>
     1
     (cdr '(1))
     =>
     ()

   This example also shows that lists have to be quoted (REFFIXME) when
written, because they would otherwise be mistakingly taken as procedure
applications (*note Simple Invocation::).

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

   (1) Note that there is no separation character between the list
elements, like a comma or a semicolon.


File: guile.info,  Node: List Predicates,  Next: List Constructors,  Prev: List Syntax,  Up: Lists

List Predicates
---------------

   Often it is useful to test whether a given Scheme object is a list or
not.  List-processing procedures could use this information to test
whether their input is valid, or they could do different things
depending on the datatype of their arguments.

 - Scheme Procedure: list? x
 - C Function: scm_list_p (x)
     Return `#t' iff X is a proper list, else `#f'.

   The predicate `null?' is often used in list-processing code to tell
whether a given list has run out of elements.  That is, a loop somehow
deals with the elements of a list until the list satisfies `null?'.
Then, the algorithm terminates.

 - Scheme Procedure: null? x
 - C Function: scm_null_p (x)
     Return `#t' iff X is the empty list, else `#f'.


File: guile.info,  Node: List Constructors,  Next: List Selection,  Prev: List Predicates,  Up: Lists

List Constructors
-----------------

   This section describes the procedures for constructing new lists.
`list' simply returns a list where the elements are the arguments,
`cons*' is similar, but the last argument is stored in the cdr of the
last pair of the list.

 - Scheme Procedure: list . objs
 - C Function: scm_list (objs)
     Return a list containing OBJS, the arguments to `list'.

 - Scheme Procedure: cons* arg1 arg2 ...
 - C Function: scm_cons_star (arg1, rest)
     Like `list', but the last arg provides the tail of the constructed
     list, returning `(cons ARG1 (cons ARG2 (cons ... ARGN)))'.
     Requires at least one argument.  If given one argument, that
     argument is returned as result.  This function is called `list*'
     in some other Schemes and in Common LISP.

 - Scheme Procedure: list-copy lst
 - C Function: scm_list_copy (lst)
     Return a (newly-created) copy of LST.

 - Scheme Procedure: make-list n [init]
     Create a list containing of N elements, where each element is
     initialized to INIT.  INIT defaults to the empty list `()' if not
     given.

   Note that `list-copy' only makes a copy of the pairs which make up
the spine of the lists.  The list elements are not copied, which means
that modifying the elements of the new list also modifies the elements
of the old list.  On the other hand, applying procedures like
`set-cdr!' or `delv!' to the new list will not alter the old list.  If
you also need to copy the list elements (making a deep copy), use the
procedure `copy-tree' (*note Copying::).


File: guile.info,  Node: List Selection,  Next: Append/Reverse,  Prev: List Constructors,  Up: Lists

List Selection
--------------

   These procedures are used to get some information about a list, or to
retrieve one or more elements of a list.

 - Scheme Procedure: length lst
 - C Function: scm_length (lst)
     Return the number of elements in list LST.

 - Scheme Procedure: last-pair lst
 - C Function: scm_last_pair (lst)
     Return a pointer to the last pair in LST, signalling an error if
     LST is circular.

 - Scheme Procedure: list-ref list k
 - C Function: scm_list_ref (list, k)
     Return the Kth element from LIST.

 - Scheme Procedure: list-tail lst k
 - Scheme Procedure: list-cdr-ref lst k
 - C Function: scm_list_tail (lst, k)
     Return the "tail" of LST beginning with its Kth element.  The
     first element of the list is considered to be element 0.

     `list-tail' and `list-cdr-ref' are identical.  It may help to
     think of `list-cdr-ref' as accessing the Kth cdr of the list, or
     returning the results of cdring K times down LST.

 - Scheme Procedure: list-head lst k
 - C Function: scm_list_head (lst, k)
     Copy the first K elements from LST into a new list, and return it.


File: guile.info,  Node: Append/Reverse,  Next: List Modification,  Prev: List Selection,  Up: Lists

Append and Reverse
------------------

   `append' and `append!' are used to concatenate two or more lists in
order to form a new list.  `reverse' and `reverse!' return lists with
the same elements as their arguments, but in reverse order.  The
procedure variants with an `!' directly modify the pairs which form the
list, whereas the other procedures create new pairs.  This is why you
should be careful when using the side-effecting variants.

 - Scheme Procedure: append . args
 - C Function: scm_append (args)
     Return a list consisting of the elements the lists passed as
     arguments.
          (append '(x) '(y))          =>  (x y)
          (append '(a) '(b c d))      =>  (a b c d)
          (append '(a (b)) '((c)))    =>  (a (b) (c))
     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

 - Scheme Procedure: append! . lists
 - C Function: scm_append_x (lists)
     A destructive version of `append' (*note Pairs and lists:
     (r5rs)Pairs and lists.).  The cdr field of each list's final pair
     is changed to point to the head of the next list, so no consing is
     performed.  Return a pointer to the mutated list.

 - Scheme Procedure: reverse lst
 - C Function: scm_reverse (lst)
     Return a new list that contains the elements of LST but in reverse
     order.

 - Scheme Procedure: reverse! lst [new_tail]
 - C Function: scm_reverse_x (lst, new_tail)
     A destructive version of `reverse' (*note Pairs and lists:
     (r5rs)Pairs and lists.).  The cdr of each cell in LST is modified
     to point to the previous list element.  Return a pointer to the
     head of the reversed list.

     Caveat: because the list is modified in place, the tail of the
     original list now becomes its head, and the head of the original
     list now becomes the tail.  Therefore, the LST symbol to which the
     head of the original list was bound now points to the tail.  To
     ensure that the head of the modified list is not lost, it is wise
     to save the return value of `reverse!'


File: guile.info,  Node: List Modification,  Next: List Searching,  Prev: Append/Reverse,  Up: Lists

List Modification
-----------------

   The following procedures modify an existing list, either by changing
elements of the list, or by changing the list structure itself.

 - Scheme Procedure: list-set! list k val
 - C Function: scm_list_set_x (list, k, val)
     Set the Kth element of LIST to VAL.

 - Scheme Procedure: list-cdr-set! list k val
 - C Function: scm_list_cdr_set_x (list, k, val)
     Set the Kth cdr of LIST to VAL.

 - Scheme Procedure: delq item lst
 - C Function: scm_delq (item, lst)
     Return a newly-created copy of LST with elements `eq?' to ITEM
     removed.  This procedure mirrors `memq': `delq' compares elements
     of LST against ITEM with `eq?'.

 - Scheme Procedure: delv item lst
 - C Function: scm_delv (item, lst)
     Return a newly-created copy of LST with elements `eqv?'  to ITEM
     removed.  This procedure mirrors `memv': `delv' compares elements
     of LST against ITEM with `eqv?'.

 - Scheme Procedure: delete item lst
 - C Function: scm_delete (item, lst)
     Return a newly-created copy of LST with elements `equal?'  to ITEM
     removed.  This procedure mirrors `member': `delete' compares
     elements of LST against ITEM with `equal?'.

 - Scheme Procedure: delq! item lst
 - Scheme Procedure: delv! item lst
 - Scheme Procedure: delete! item lst
 - C Function: scm_delq_x (item, lst)
 - C Function: scm_delv_x (item, lst)
 - C Function: scm_delete_x (item, lst)
     These procedures are destructive versions of `delq', `delv' and
     `delete': they modify the pointers in the existing LST rather than
     creating a new list.  Caveat evaluator: Like other destructive
     list functions, these functions cannot modify the binding of LST,
     and so cannot be used to delete the first element of LST
     destructively.

 - Scheme Procedure: delq1! item lst
 - C Function: scm_delq1_x (item, lst)
     Like `delq!', but only deletes the first occurrence of ITEM from
     LST.  Tests for equality using `eq?'.  See also `delv1!' and
     `delete1!'.

 - Scheme Procedure: delv1! item lst
 - C Function: scm_delv1_x (item, lst)
     Like `delv!', but only deletes the first occurrence of ITEM from
     LST.  Tests for equality using `eqv?'.  See also `delq1!' and
     `delete1!'.

 - Scheme Procedure: delete1! item lst
 - C Function: scm_delete1_x (item, lst)
     Like `delete!', but only deletes the first occurrence of ITEM from
     LST.  Tests for equality using `equal?'.  See also `delq1!' and
     `delv1!'.


File: guile.info,  Node: List Searching,  Next: List Mapping,  Prev: List Modification,  Up: Lists

List Searching
--------------

   The following procedures search lists for particular elements.  They
use different comparison predicates for comparing list elements with the
object to be searched.  When they fail, they return `#f', otherwise
they return the sublist whose car is equal to the search object, where
equality depends on the equality predicate used.

 - Scheme Procedure: memq x lst
 - C Function: scm_memq (x, lst)
     Return the first sublist of LST whose car is `eq?' to X where the
     sublists of LST are the non-empty lists returned by `(list-tail
     LST K)' for K less than the length of LST.  If X does not occur in
     LST, then `#f' (not the empty list) is returned.

 - Scheme Procedure: memv x lst
 - C Function: scm_memv (x, lst)
     Return the first sublist of LST whose car is `eqv?' to X where the
     sublists of LST are the non-empty lists returned by `(list-tail
     LST K)' for K less than the length of LST.  If X does not occur in
     LST, then `#f' (not the empty list) is returned.

 - Scheme Procedure: member x lst
 - C Function: scm_member (x, lst)
     Return the first sublist of LST whose car is `equal?' to X where
     the sublists of LST are the non-empty lists returned by
     `(list-tail LST K)' for K less than the length of LST.  If X does
     not occur in LST, then `#f' (not the empty list) is returned.


File: guile.info,  Node: List Mapping,  Prev: List Searching,  Up: Lists

List Mapping
------------

   List processing is very convenient in Scheme because the process of
iterating over the elements of a list can be highly abstracted.  The
procedures in this section are the most basic iterating procedures for
lists.  They take a procedure and one or more lists as arguments, and
apply the procedure to each element of the list.  They differ in their
return value.

 - Scheme Procedure: map proc arg1 arg2 ...
 - Scheme Procedure: map-in-order proc arg1 arg2 ...
 - C Function: scm_map (proc, arg1, args)
     Apply PROC to each element of the list ARG1 (if only two arguments
     are given), or to the corresponding elements of the argument lists
     (if more than two arguments are given).  The result(s) of the
     procedure applications are saved and returned in a list.  For
     `map', the order of procedure applications is not specified,
     `map-in-order' applies the procedure from left to right to the list
     elements.

 - Scheme Procedure: for-each proc arg1 arg2 ...
     Like `map', but the procedure is always applied from left to right,
     and the result(s) of the procedure applications are thrown away.
     The return value is not specified.


File: guile.info,  Node: Vectors,  Next: Records,  Prev: Lists,  Up: Compound Data Types

Vectors
=======

   Vectors are sequences of Scheme objects.  Unlike lists, the length
of a vector, once the vector is created, cannot be changed.  The
advantage of vectors over lists is that the time required to access one
element of a vector given its "position" (synonymous with "index"), a
zero-origin number, is constant, whereas lists have an access time
linear to the position of the accessed element in the list.

   Vectors can contain any kind of Scheme object; it is even possible
to have different types of objects in the same vector.  For vectors
containing vectors, you may wish to use arrays, instead.  Note, too,
that some array procedures operate happily on vectors (*note Arrays::).

* Menu:

* Vector Syntax::               Read syntax for vectors.
* Vector Creation::             Dynamic vector creation and validation.
* Vector Accessors::            Accessing and modifying vector contents.


File: guile.info,  Node: Vector Syntax,  Next: Vector Creation,  Up: Vectors

Read Syntax for Vectors
-----------------------

   Vectors can literally be entered in source code, just like strings,
characters or some of the other data types.  The read syntax for vectors
is as follows: A sharp sign (`#'), followed by an opening parentheses,
all elements of the vector in their respective read syntax, and finally
a closing parentheses.  The following are examples of the read syntax
for vectors; where the first vector only contains numbers and the
second three different object types: a string, a symbol and a number in
hexadecimal notation.

     #(1 2 3)
     #("Hello" foo #xdeadbeef)


File: guile.info,  Node: Vector Creation,  Next: Vector Accessors,  Prev: Vector Syntax,  Up: Vectors

Dynamic Vector Creation and Validation
--------------------------------------

   Instead of creating a vector implicitly by using the read syntax just
described, you can create a vector dynamically by calling one of the
`vector' and `list->vector' primitives with the list of Scheme values
that you want to place into a vector.  The size of the vector thus
created is determined implicitly by the number of arguments given.

 - Scheme Procedure: vector . l
 - Scheme Procedure: list->vector l
 - C Function: scm_vector (l)
     Return a newly allocated vector composed of the given arguments.
     Analogous to `list'.

          (vector 'a 'b 'c) => #(a b c)

   (As an aside, an interesting implementation detail is that the Guile
reader reads the `#(...)' syntax by reading everything but the initial
`#' as a _list_, and then passing the list that results to
`list->vector'.  Notice how neatly this fits with the similarity
between the read (and print) syntaxes for lists and vectors.)

   The inverse operation is `vector->list':

 - Scheme Procedure: vector->list v
 - C Function: scm_vector_to_list (v)
     Return a newly allocated list composed of the elements of V.

          (vector->list '#(dah dah didah)) =>  (dah dah didah)
          (list->vector '(dididit dah)) =>  #(dididit dah)

   To allocate a vector with an explicitly specified size, use
`make-vector'.  With this primitive you can also specify an initial
value for the vector elements (the same value for all elements, that
is):

 - Scheme Procedure: make-vector k [fill]
 - C Function: scm_make_vector (k, fill)
     Return a newly allocated vector of K elements.  If a second
     argument is given, then each position is initialized to FILL.
     Otherwise the initial contents of each position is unspecified.

   To check whether an arbitrary Scheme value _is_ a vector, use the
`vector?' primitive:

 - Scheme Procedure: vector? obj
 - C Function: scm_vector_p (obj)
     Return `#t' if OBJ is a vector, otherwise return `#f'.


File: guile.info,  Node: Vector Accessors,  Prev: Vector Creation,  Up: Vectors

Accessing and Modifying Vector Contents
---------------------------------------

   `vector-length' and `vector-ref' return information about a given
vector, respectively its size and the elements that are contained in
the vector.

 - Scheme Procedure: vector-length vector
 - C Function: scm_vector_length vector
     Return the number of elements in VECTOR as an exact integer.

 - Scheme Procedure: vector-ref vector k
 - C Function: scm_vector_ref vector k
     Return the contents of position K of VECTOR.  K must be a valid
     index of VECTOR.
          (vector-ref '#(1 1 2 3 5 8 13 21) 5) => 8
          (vector-ref '#(1 1 2 3 5 8 13 21)
              (let ((i (round (* 2 (acos -1)))))
                (if (inexact? i)
                  (inexact->exact i)
                     i))) => 13

   A vector created by one of the dynamic vector constructor procedures
(*note Vector Creation::) can be modified using the following
procedures.

   _NOTE:_ According to R5RS, it is an error to use any of these
procedures on a literally read vector, because such vectors should be
considered as constants.  Currently, however, Guile does not detect this
error.

 - Scheme Procedure: vector-set! vector k obj
 - C Function: scm_vector_set_x vector k obj
     Store OBJ in position K of VECTOR.  K must be a valid index of
     VECTOR.  The value returned by `vector-set!' is unspecified.
          (let ((vec (vector 0 '(2 2 2 2) "Anna")))
            (vector-set! vec 1 '("Sue" "Sue"))
            vec) =>  #(0 ("Sue" "Sue") "Anna")

 - Scheme Procedure: vector-fill! v fill
 - C Function: scm_vector_fill_x (v, fill)
     Store FILL in every position of VECTOR.  The value returned by
     `vector-fill!' is unspecified.

 - Scheme Procedure: vector-move-left! vec1 start1 end1 vec2 start2
 - C Function: scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
     Copy elements from VEC1, positions START1 to END1, to VEC2
     starting at position START2.  START1 and START2 are inclusive
     indices; END1 is exclusive.

     `vector-move-left!' copies elements in leftmost order.  Therefore,
     in the case where VEC1 and VEC2 refer to the same vector,
     `vector-move-left!' is usually appropriate when START1 is greater
     than START2.

 - Scheme Procedure: vector-move-right! vec1 start1 end1 vec2 start2
 - C Function: scm_vector_move_right_x (vec1, start1, end1, vec2,
          start2)
     Copy elements from VEC1, positions START1 to END1, to VEC2
     starting at position START2.  START1 and START2 are inclusive
     indices; END1 is exclusive.

     `vector-move-right!' copies elements in rightmost order.
     Therefore, in the case where VEC1 and VEC2 refer to the same
     vector, `vector-move-right!' is usually appropriate when START1 is
     less than START2.


File: guile.info,  Node: Records,  Next: Structures,  Prev: Vectors,  Up: Compound Data Types

Records
=======

   A "record type" is a first class object representing a user-defined
data type.  A "record" is an instance of a record type.

 - Scheme Procedure: record? obj
     Return `#t' if OBJ is a record of any type and `#f' otherwise.

     Note that `record?' may be true of any Scheme value; there is no
     promise that records are disjoint with other Scheme types.

 - Scheme Procedure: make-record-type type-name field-names
     Return a "record-type descriptor", a value representing a new data
     type disjoint from all others.  The TYPE-NAME argument must be a
     string, but is only used for debugging purposes (such as the
     printed representation of a record of the new type).  The
     FIELD-NAMES argument is a list of symbols naming the "fields" of a
     record of the new type.  It is an error if the list contains any
     duplicates.  It is unspecified how record-type descriptors are
     represented.

 - Scheme Procedure: record-constructor rtd [field-names]
     Return a procedure for constructing new members of the type
     represented by RTD.  The returned procedure accepts exactly as
     many arguments as there are symbols in the given list,
     FIELD-NAMES; these are used, in order, as the initial values of
     those fields in a new record, which is returned by the constructor
     procedure.  The values of any fields not named in that list are
     unspecified.  The FIELD-NAMES argument defaults to the list of
     field names in the call to `make-record-type' that created the
     type represented by RTD; if the FIELD-NAMES argument is provided,
     it is an error if it contains any duplicates or any symbols not in
     the default list.

 - Scheme Procedure: record-predicate rtd
     Return a procedure for testing membership in the type represented
     by RTD.  The returned procedure accepts exactly one argument and
     returns a true value if the argument is a member of the indicated
     record type; it returns a false value otherwise.

 - Scheme Procedure: record-accessor rtd field-name
     Return a procedure for reading the value of a particular field of a
     member of the type represented by RTD.  The returned procedure
     accepts exactly one argument which must be a record of the
     appropriate type; it returns the current value of the field named
     by the symbol FIELD-NAME in that record.  The symbol FIELD-NAME
     must be a member of the list of field-names in the call to
     `make-record-type' that created the type represented by RTD.

 - Scheme Procedure: record-modifier rtd field-name
     Return a procedure for writing the value of a particular field of a
     member of the type represented by RTD.  The returned procedure
     accepts exactly two arguments: first, a record of the appropriate
     type, and second, an arbitrary Scheme value; it modifies the field
     named by the symbol FIELD-NAME in that record to contain the given
     value.  The returned value of the modifier procedure is
     unspecified.  The symbol FIELD-NAME must be a member of the list
     of field-names in the call to `make-record-type' that created the
     type represented by RTD.

 - Scheme Procedure: record-type-descriptor record
     Return a record-type descriptor representing the type of the given
     record.  That is, for example, if the returned descriptor were
     passed to `record-predicate', the resulting predicate would return
     a true value when passed the given record.  Note that it is not
     necessarily the case that the returned descriptor is the one that
     was passed to `record-constructor' in the call that created the
     constructor procedure that created the given record.

 - Scheme Procedure: record-type-name rtd
     Return the type-name associated with the type represented by rtd.
     The returned value is `eqv?' to the TYPE-NAME argument given in
     the call to `make-record-type' that created the type represented by
     RTD.

 - Scheme Procedure: record-type-fields rtd
     Return a list of the symbols naming the fields in members of the
     type represented by RTD.  The returned value is `equal?' to the
     field-names argument given in the call to `make-record-type' that
     created the type represented by RTD.


File: guile.info,  Node: Structures,  Next: Arrays,  Prev: Records,  Up: Compound Data Types

Structures
==========

   [FIXME: this is pasted in from Tom Lord's original guile.texi and
should be reviewed]

   A "structure type" is a first class user-defined data type.  A
"structure" is an instance of a structure type.  A structure type is
itself a structure.

   Structures are less abstract and more general than traditional
records.  In fact, in Guile Scheme, records are implemented using
structures.

* Menu:

* Structure Concepts::          The structure of Structures
* Structure Layout::            Defining the layout of structure types
* Structure Basics::            make-, -ref and -set! procedures for structs
* Vtables::                     Accessing type-specific data


File: guile.info,  Node: Structure Concepts,  Next: Structure Layout,  Up: Structures

Structure Concepts
------------------

   A structure object consists of a handle, structure data, and a
vtable.  The handle is a Scheme value which points to both the vtable
and the structure's data.  Structure data is a dynamically allocated
region of memory, private to the structure, divided up into typed
fields.  A vtable is another structure used to hold type-specific data.
Multiple structures can share a common vtable.

   Three concepts are key to understanding structures.

   * "layout specifications"

     Layout specifications determine how memory allocated to structures
     is divided up into fields.  Programmers must write a layout
     specification whenever a new type of structure is defined.

   * "structural accessors"

     Structure access is by field number.   There is only one set of
     accessors common to all structure objects.

   * "vtables"

     Vtables, themselves structures, are first class representations of
     disjoint sub-types of structures in general.   In most cases, when
     a new structure is created, programmers must specify a vtable for
     the new structure.   Each vtable has a field describing the layout
     of its instances.   Vtables can have additional, user-defined
     fields as well.


File: guile.info,  Node: Structure Layout,  Next: Structure Basics,  Prev: Structure Concepts,  Up: Structures

Structure Layout
----------------

   When a structure is created, a region of memory is allocated to hold
its state.  The "layout" of the structure's type determines how that
memory is divided into fields.

   Each field has a specified type.  There are only three types
allowed, each corresponding to a one letter code.  The allowed types
are:

   * 'u' - unprotected

     The field holds binary data that is not GC protected.

   * 'p' - protected

     The field holds a Scheme value and is GC protected.

   * 's' - self

     The field holds a Scheme value and is GC protected.  When a
     structure is created with this type of field, the field is
     initialized to refer to the structure's own handle.  This kind of
     field is mainly useful when mixing Scheme and C code in which the
     C code may need to compute a structure's handle given only the
     address of its malloc'd data.

   Each field also has an associated access protection.   There are only
three kinds of protection, each corresponding to a one letter code.
The allowed protections are:

   * 'w' - writable

     The field can be read and written.

   * 'r' - readable

     The field can be read, but not written.

   * 'o' - opaque

     The field can be neither read nor written.   This kind of
     protection is for fields useful only to built-in routines.

   A layout specification is described by stringing together pairs of
letters: one to specify a field type and one to specify a field
protection.    For example, a traditional cons pair type object could
be described as:

     ; cons pairs have two writable fields of Scheme data
     "pwpw"

   A pair object in which the first field is held constant could be:

     "prpw"

   Binary fields, (fields of type "u"), hold one "word" each.  The size
of a word is a machine dependent value defined to be equal to the value
of the C expression: `sizeof (long)'.

   The last field of a structure layout may specify a tail array.  A
tail array is indicated by capitalizing the field's protection code
('W', 'R' or 'O').   A tail-array field is replaced by a read-only
binary data field containing an array size.   The array size is
determined at the time the structure is created.  It is followed by a
corresponding number of fields of the type specified for the tail
array.   For example, a conventional Scheme vector can be described as:

     ; A vector is an arbitrary number of writable fields holding Scheme
     ; values:
     "pW"

   In the above example, field 0 contains the size of the vector and
fields beginning at 1 contain the vector elements.

   A kind of tagged vector (a constant tag followed by conventional
vector elements) might be:

     "prpW"

   Structure layouts are represented by specially interned symbols whose
name is a string of type and protection codes.  To create a new
structure layout, use this procedure:

 - Scheme Procedure: make-struct-layout fields
 - C Function: scm_make_struct_layout (fields)
     Return a new structure layout object.

     FIELDS must be a string made up of pairs of characters strung
     together.  The first character of each pair describes a field
     type, the second a field protection.  Allowed types are 'p' for
     GC-protected Scheme data, 'u' for unprotected binary data, and 's'
     for a field that points to the structure itself.    Allowed
     protections are 'w' for mutable fields, 'r' for read-only fields,
     and 'o' for opaque fields.  The last field protection
     specification may be capitalized to indicate that the field is a
     tail-array.


File: guile.info,  Node: Structure Basics,  Next: Vtables,  Prev: Structure Layout,  Up: Structures

Structure Basics
----------------

   This section describes the basic procedures for creating and
accessing structures.

 - Scheme Procedure: make-struct vtable tail_array_size . init
 - C Function: scm_make_struct (vtable, tail_array_size, init)
     Create a new structure.

     TYPE must be a vtable structure (*note Vtables::).

     TAIL-ELTS must be a non-negative integer.  If the layout
     specification indicated by TYPE includes a tail-array, this is the
     number of elements allocated to that array.

     The INIT1, ... are optional arguments describing how successive
     fields of the structure should be initialized.  Only fields with
     protection 'r' or 'w' can be initialized, except for fields of
     type 's', which are automatically initialized to point to the new
     structure itself; fields with protection 'o' can not be
     initialized by Scheme programs.

     If fewer optional arguments than initializable fields are supplied,
     fields of type 'p' get default value #f while fields of type 'u'
     are initialized to 0.

     Structs are currently the basic representation for record-like data
     structures in Guile.  The plan is to eventually replace them with a
     new representation which will at the same time be easier to use and
     more powerful.

     For more information, see the documentation for
     `make-vtable-vtable'.

 - Scheme Procedure: struct? x
 - C Function: scm_struct_p (x)
     Return `#t' iff X is a structure object, else `#f'.

 - Scheme Procedure: struct-ref handle pos
 - Scheme Procedure: struct-set! struct n value
 - C Function: scm_struct_ref (handle, pos)
 - C Function: scm_struct_set_x (struct, n, value)
     Access (or modify) the Nth field of STRUCT.

     If the field is of type 'p', then it can be set to an arbitrary
     value.

     If the field is of type 'u', then it can only be set to a
     non-negative integer value small enough to fit in one machine word.


File: guile.info,  Node: Vtables,  Prev: Structure Basics,  Up: Structures

Vtables
-------

   Vtables are structures that are used to represent structure types.
Each vtable contains a layout specification in field
`vtable-index-layout' - instances of the type are laid out according to
that specification.  Vtables contain additional fields which are used
only internally to libguile.  The variable `vtable-offset-user' is
bound to a field number.  Vtable fields at that position or greater are
user definable.

 - Scheme Procedure: struct-vtable handle
 - C Function: scm_struct_vtable (handle)
     Return the vtable structure that describes the type of STRUCT.

 - Scheme Procedure: struct-vtable? x
 - C Function: scm_struct_vtable_p (x)
     Return `#t' iff X is a vtable structure.

   If you have a vtable structure, `V', you can create an instance of
the type it describes by using `(make-struct V ...)'.  But where does
`V' itself come from?  One possibility is that `V' is an instance of a
user-defined vtable type, `V'', so that `V' is created by using
`(make-struct V' ...)'.  Another possibility is that `V' is an instance
of the type it itself describes.  Vtable structures of the second sort
are created by this procedure:

 - Scheme Procedure: make-vtable-vtable user_fields tail_array_size .
          init
 - C Function: scm_make_vtable_vtable (user_fields, tail_array_size,
          init)
     Return a new, self-describing vtable structure.

     USER-FIELDS is a string describing user defined fields of the
     vtable beginning at index `vtable-offset-user' (see
     `make-struct-layout').

     TAIL-SIZE specifies the size of the tail-array (if any) of this
     vtable.

     INIT1, ... are the optional initializers for the fields of the
     vtable.

     Vtables have one initializable system field--the struct printer.
     This field comes before the user fields in the initializers passed
     to `make-vtable-vtable' and `make-struct', and thus works as a
     third optional argument to `make-vtable-vtable' and a fourth to
     `make-struct' when creating vtables:

     If the value is a procedure, it will be called instead of the
     standard printer whenever a struct described by this vtable is
     printed.  The procedure will be called with arguments STRUCT and
     PORT.

     The structure of a struct is described by a vtable, so the vtable
     is in essence the type of the struct.  The vtable is itself a
     struct with a vtable.  This could go on forever if it weren't for
     the vtable-vtables which are self-describing vtables, and thus
     terminate the chain.

     There are several potential ways of using structs, but the standard
     one is to use three kinds of structs, together building up a type
     sub-system: one vtable-vtable working as the root and one or
     several "types", each with a set of "instances".  (The
     vtable-vtable should be compared to the class <class> which is the
     class of itself.)

          (define ball-root (make-vtable-vtable "pr" 0))
          
          (define (make-ball-type ball-color)
            (make-struct ball-root 0
          	       (make-struct-layout "pw")
                         (lambda (ball port)
                           (format port "#<a ~A ball owned by ~A>"
                                   (color ball)
                                   (owner ball)))
                         ball-color))
          (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
          (define (owner ball) (struct-ref ball 0))
          
          (define red (make-ball-type 'red))
          (define green (make-ball-type 'green))
          
          (define (make-ball type owner) (make-struct type 0 owner))
          
          (define ball (make-ball green 'Nisse))
          ball => #<a green ball owned by Nisse>

 - Scheme Procedure: struct-vtable-name vtable
 - C Function: scm_struct_vtable_name (vtable)
     Return the name of the vtable VTABLE.

 - Scheme Procedure: set-struct-vtable-name! vtable name
 - C Function: scm_set_struct_vtable_name_x (vtable, name)
     Set the name of the vtable VTABLE to NAME.

 - Scheme Procedure: struct-vtable-tag handle
 - C Function: scm_struct_vtable_tag (handle)
     Return the vtable tag of the structure HANDLE.


File: guile.info,  Node: Arrays,  Next: Association Lists and Hash Tables,  Prev: Structures,  Up: Compound Data Types

Arrays
======

* Menu:

* Conventional Arrays::         Arrays with arbitrary data.
* Array Mapping::               Applying a procedure to the contents of an array.
* Uniform Arrays::              Arrays with data of a single type.
* Bit Vectors::                 Vectors of bits.


File: guile.info,  Node: Conventional Arrays,  Next: Array Mapping,  Up: Arrays

Conventional Arrays
-------------------

   "Conventional arrays" are a collection of cells organized into an
arbitrary number of dimensions.  Each cell can hold any kind of Scheme
value and can be accessed in constant time by supplying an index for
each dimension.  This contrasts with uniform arrays, which use memory
more efficiently but can hold data of only a single type, and lists
where inserting and deleting cells is more efficient, but more time is
usually required to access a particular cell.

   A conventional array is displayed as `#' followed by the "rank"
(number of dimensions) followed by the cells, organized into dimensions
using parentheses.  The nesting depth of the parentheses is equal to
the rank.

   When an array is created, the number of dimensions and range of each
dimension must be specified, e.g., to create a 2x3 array with a
zero-based index:

     (make-array 'ho 2 3) =>
     #2((ho ho ho) (ho ho ho))

   The range of each dimension can also be given explicitly, e.g.,
another way to create the same array:

     (make-array 'ho '(0 1) '(0 2)) =>
     #2((ho ho ho) (ho ho ho))

   A conventional array with one dimension based at zero is identical to
a vector:

     (make-array 'ho 3) =>
     #(ho ho ho)

   The following procedures can be used with conventional arrays (or
vectors).

 - Scheme Procedure: array? v [prot]
 - C Function: scm_array_p (v, prot)
     Return `#t' if the OBJ is an array, and `#f' if not.  The
     PROTOTYPE argument is used with uniform arrays and is described
     elsewhere.

 - Scheme Procedure: make-array initial-value bound1 bound2 ...
     Create and return an array that has as many dimensions as there are
     BOUNDs and fill it with INITIAL-VALUE.  Each BOUND may be a
     positive non-zero integer N, in which case the index for that
     dimension can range from 0 through N-1; or an explicit index range
     specifier in the form `(LOWER UPPER)', where both LOWER and UPPER
     are integers, possibly less than zero, and possibly the same
     number (however, LOWER cannot be greater than UPPER).

 - Scheme Procedure: uniform-vector-ref v args
 - Scheme Procedure: array-ref v . args
 - C Function: scm_uniform_vector_ref (v, args)
     Return the element at the `(index1, index2)' element in ARRAY.

 - Scheme Procedure: array-in-bounds? v . args
 - C Function: scm_array_in_bounds_p (v, args)
     Return `#t' if its arguments would be acceptable to `array-ref'.

 - Scheme Procedure: array-set! v obj . args
 - Scheme Procedure: uniform-array-set1! v obj args
 - C Function: scm_array_set_x (v, obj, args)
     Set the element at the `(index1, index2)' element in ARRAY to
     NEW-VALUE.  The value returned by array-set! is unspecified.

 - Scheme Procedure: make-shared-array oldra mapfunc . dims
 - C Function: scm_make_shared_array (oldra, mapfunc, dims)
     `make-shared-array' can be used to create shared subarrays of other
     arrays.  The MAPPER is a function that translates coordinates in
     the new array into coordinates in the old array.  A MAPPER must be
     linear, and its range must stay within the bounds of the old
     array, but it can be otherwise arbitrary.  A simple example:
          (define fred (make-array #f 8 8))
          (define freds-diagonal
            (make-shared-array fred (lambda (i) (list i i)) 8))
          (array-set! freds-diagonal 'foo 3)
          (array-ref fred 3 3) => foo
          (define freds-center
            (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
          (array-ref freds-center 0 0) => foo

 - Scheme Procedure: shared-array-increments ra
 - C Function: scm_shared_array_increments (ra)
     For each dimension, return the distance between elements in the
     root vector.

 - Scheme Procedure: shared-array-offset ra
 - C Function: scm_shared_array_offset (ra)
     Return the root vector index of the first element in the array.

 - Scheme Procedure: shared-array-root ra
 - C Function: scm_shared_array_root (ra)
     Return the root vector of a shared array.

 - Scheme Procedure: transpose-array ra . args
 - C Function: scm_transpose_array (ra, args)
     Return an array sharing contents with ARRAY, but with dimensions
     arranged in a different order.  There must be one DIM argument for
     each dimension of ARRAY.  DIM0, DIM1, ... should be integers
     between 0 and the rank of the array to be returned.  Each integer
     in that range must appear at least once in the argument list.

     The values of DIM0, DIM1, ... correspond to dimensions in the
     array to be returned, their positions in the argument list to
     dimensions of ARRAY.  Several DIMs may have the same value, in
     which case the returned array will have smaller rank than ARRAY.

          (transpose-array '#2((a b) (c d)) 1 0) => #2((a c) (b d))
          (transpose-array '#2((a b) (c d)) 0 0) => #1(a d)
          (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) =>
                          #2((a 4) (b 5) (c 6))

 - Scheme Procedure: enclose-array ra . axes
 - C Function: scm_enclose_array (ra, axes)
     DIM0, DIM1 ... should be nonnegative integers less than the rank
     of ARRAY.  ENCLOSE-ARRAY returns an array resembling an array of
     shared arrays.  The dimensions of each shared array are the same
     as the DIMth dimensions of the original array, the dimensions of
     the outer array are the same as those of the original array that
     did not match a DIM.

     An enclosed array is not a general Scheme array.  Its elements may
     not be set using `array-set!'.  Two references to the same element
     of an enclosed array will be `equal?' but will not in general be
     `eq?'.  The value returned by ARRAY-PROTOTYPE when given an
     enclosed array is unspecified.

     examples:
          (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) =>
             #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
          
          (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) =>
             #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>

 - Scheme Procedure: array-shape array
     Return a list of inclusive bounds of integers.
          (array-shape (make-array 'foo '(-1 3) 5)) => ((-1 3) (0 4))

 - Scheme Procedure: array-dimensions ra
 - C Function: scm_array_dimensions (ra)
     `Array-dimensions' is similar to `array-shape' but replaces
     elements with a `0' minimum with one greater than the maximum. So:
          (array-dimensions (make-array 'foo '(-1 3) 5)) => ((-1 3) 5)

 - Scheme Procedure: array-rank ra
 - C Function: scm_array_rank (ra)
     Return the number of dimensions of OBJ.  If OBJ is not an array,
     `0' is returned.

 - Scheme Procedure: array->list v
 - C Function: scm_array_to_list (v)
     Return a list consisting of all the elements, in order, of ARRAY.

 - Scheme Procedure: array-copy! src dst
 - Scheme Procedure: array-copy-in-order! src dst
 - C Function: scm_array_copy_x (src, dst)
     Copy every element from vector or array SOURCE to the
     corresponding element of DESTINATION.  DESTINATION must have the
     same rank as SOURCE, and be at least as large in each dimension.
     The order is unspecified.

 - Scheme Procedure: array-fill! ra fill
 - C Function: scm_array_fill_x (ra, fill)
     Store FILL in every element of ARRAY.  The value returned is
     unspecified.

 - Scheme Procedure: array-equal? ra0 ra1
     Return `#t' iff all arguments are arrays with the same shape, the
     same type, and have corresponding elements which are either
     `equal?'  or `array-equal?'.  This function differs from `equal?'
     in that a one dimensional shared array may be ARRAY-EQUAL? but not
     EQUAL? to a vector or uniform vector.

 - Scheme Procedure: array-contents array [strict]
 - C Function: scm_array_contents (array, strict)
     If ARRAY may be "unrolled" into a one dimensional shared array
     without changing their order (last subscript changing fastest),
     then `array-contents' returns that shared array, otherwise it
     returns `#f'.  All arrays made by MAKE-ARRAY and
     MAKE-UNIFORM-ARRAY may be unrolled, some arrays made by
     MAKE-SHARED-ARRAY may not be.

     If the optional argument STRICT is provided, a shared array will
     be returned only if its elements are stored internally contiguous
     in memory.


File: guile.info,  Node: Array Mapping,  Next: Uniform Arrays,  Prev: Conventional Arrays,  Up: Arrays

Array Mapping
-------------

 - Scheme Procedure: array-map! ra0 proc . lra
 - Scheme Procedure: array-map-in-order! ra0 proc . lra
 - C Function: scm_array_map_x (ra0, proc, lra)
     ARRAY1, ... must have the same number of dimensions as ARRAY0 and
     have a range for each index which includes the range for the
     corresponding index in ARRAY0.  PROC is applied to each tuple of
     elements of ARRAY1 ... and the result is stored as the
     corresponding element in ARRAY0.  The value returned is
     unspecified.  The order of application is unspecified.

 - Scheme Procedure: array-for-each proc ra0 . lra
 - C Function: scm_array_for_each (proc, ra0, lra)
     Apply PROC to each tuple of elements of ARRAY0 ...  in row-major
     order.  The value returned is unspecified.

 - Scheme Procedure: array-index-map! ra proc
 - C Function: scm_array_index_map_x (ra, proc)
     Apply PROC to the indices of each element of ARRAY in turn,
     storing the result in the corresponding element.  The value
     returned and the order of application are unspecified.

     One can implement ARRAY-INDEXES as
          (define (array-indexes array)
              (let ((ra (apply make-array #f (array-shape array))))
                (array-index-map! ra (lambda x x))
                ra))
     Another example:
          (define (apl:index-generator n)
              (let ((v (make-uniform-vector n 1)))
                (array-index-map! v (lambda (i) i))
                v))


File: guile.info,  Node: Uniform Arrays,  Next: Bit Vectors,  Prev: Array Mapping,  Up: Arrays

Uniform Arrays
--------------

"Uniform arrays" have elements all of the same type and occupy less
storage than conventional arrays.  Uniform arrays with a single
zero-based dimension are also known as "uniform vectors".  The
procedures in this section can also be used on conventional arrays,
vectors, bit-vectors and strings.

When creating a uniform array, the type of data to be stored is
indicated with a PROTOTYPE argument.  The following table lists the
types available and example prototypes:

     prototype           type                       printing character
     
     #t             boolean (bit-vector)                    b
     #\a            char (string)                           a
     #\nul          byte (integer)                          y
     's             short (integer)                         h
     1              unsigned long (integer)                 u
     -1             signed long (integer)                   e
     'l             signed long long (integer)              l
     1.0            float (single precision)                s
     1/3            double (double precision float)         i
     0+i            complex (double precision)              c
     ()             conventional vector

Unshared uniform arrays of characters with a single zero-based dimension
are identical to strings:

     (make-uniform-array #\a 3) =>
     "aaa"

Unshared uniform arrays of booleans with a single zero-based dimension
are identical to *Note bit-vectors: Bit Vectors.

     (make-uniform-array #t 3) =>
     #*111

Other uniform vectors are written in a form similar to that of vectors,
except that a single character from the above table is put between `#'
and `('.  For example, a uniform vector of signed long integers is
displayed in the form `'#e(3 5 9)'.

 - Scheme Procedure: array? v [prot]
     Return `#t' if the OBJ is an array, and `#f' if not.

     The PROTOTYPE argument is used with uniform arrays and is described
     elsewhere.

 - Scheme Procedure: make-uniform-array prototype bound1 bound2 ...
     Create and return a uniform array of type corresponding to
     PROTOTYPE that has as many dimensions as there are BOUNDs and fill
     it with PROTOTYPE.

 - Scheme Procedure: array-prototype ra
 - C Function: scm_array_prototype (ra)
     Return an object that would produce an array of the same type as
     ARRAY, if used as the PROTOTYPE for `make-uniform-array'.

 - Scheme Procedure: list->uniform-array ndim prot lst
 - Scheme Procedure: list->uniform-vector prot lst
 - C Function: scm_list_to_uniform_array (ndim, prot, lst)
     Return a uniform array of the type indicated by prototype PROT
     with elements the same as those of LST.  Elements must be of the
     appropriate type, no coercions are done.

 - Scheme Procedure: uniform-vector-fill! uve fill
     Store FILL in every element of UVE.  The value returned is
     unspecified.

 - Scheme Procedure: uniform-vector-length v
 - C Function: scm_uniform_vector_length (v)
     Return the number of elements in UVE.

 - Scheme Procedure: dimensions->uniform-array dims prot [fill]
 - Scheme Procedure: make-uniform-vector length prototype [fill]
 - C Function: scm_dimensions_to_uniform_array (dims, prot, fill)
     Create and return a uniform array or vector of type corresponding
     to PROTOTYPE with dimensions DIMS or length LENGTH.  If FILL is
     supplied, it's used to fill the array, otherwise PROTOTYPE is used.

 - Scheme Procedure: uniform-array-read! ra [port_or_fd [start [end]]]
 - Scheme Procedure: uniform-vector-read! uve [port-or-fdes] [start]
          [end]
 - C Function: scm_uniform_array_read_x (ra, port_or_fd, start, end)
     Attempt to read all elements of URA, in lexicographic order, as
     binary objects from PORT-OR-FDES.  If an end of file is
     encountered, the objects up to that point are put into URA
     (starting at the beginning) and the remainder of the array is
     unchanged.

     The optional arguments START and END allow a specified region of a
     vector (or linearized array) to be read, leaving the remainder of
     the vector unchanged.

     `uniform-array-read!' returns the number of objects read.
     PORT-OR-FDES may be omitted, in which case it defaults to the value
     returned by `(current-input-port)'.

 - Scheme Procedure: uniform-array-write v [port_or_fd [start [end]]]
 - Scheme Procedure: uniform-vector-write uve [port-or-fdes] [start]
          [end]
 - C Function: scm_uniform_array_write (v, port_or_fd, start, end)
     Writes all elements of URA as binary objects to PORT-OR-FDES.

     The optional arguments START and END allow a specified region of a
     vector (or linearized array) to be written.

     The number of objects actually written is returned.  PORT-OR-FDES
     may be omitted, in which case it defaults to the value returned by
     `(current-output-port)'.


File: guile.info,  Node: Bit Vectors,  Prev: Uniform Arrays,  Up: Arrays

Bit Vectors
-----------

Bit vectors are a specific type of uniform array: an array of booleans
with a single zero-based index.

They are displayed as a sequence of `0's and `1's prefixed by `#*',
e.g.,

     (make-uniform-vector 8 #t #f) =>
     #*00000000
     
     #b(#t #f #t) =>
     #*101

 - Scheme Procedure: bit-count b bitvector
 - C Function: scm_bit_count (b, bitvector)
     Return the number of occurrences of the boolean B in BITVECTOR.

 - Scheme Procedure: bit-position item v k
 - C Function: scm_bit_position (item, v, k)
     Return the minimum index of an occurrence of BOOL in BV which is
     at least K.  If no BOOL occurs within the specified range `#f' is
     returned.

 - Scheme Procedure: bit-invert! v
 - C Function: scm_bit_invert_x (v)
     Modify BV by replacing each element with its negation.

 - Scheme Procedure: bit-set*! v kv obj
 - C Function: scm_bit_set_star_x (v, kv, obj)
     If uve is a bit-vector BV and uve must be of the same length.  If
     BOOL is `#t', uve is OR'ed into BV; If BOOL is `#f', the inversion
     of uve is AND'ed into BV.

     If uve is a unsigned long integer vector all the elements of uve
     must be between 0 and the `length' of BV.  The bits of BV
     corresponding to the indexes in uve are set to BOOL.  The return
     value is unspecified.

 - Scheme Procedure: bit-count* v kv obj
 - C Function: scm_bit_count_star (v, kv, obj)
     Return
          (bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
     BV is not modified.


File: guile.info,  Node: Association Lists and Hash Tables,  Prev: Arrays,  Up: Compound Data Types

Association Lists and Hash Tables
=================================

   This chapter discusses dictionary objects: data structures that are
useful for organizing and indexing large bodies of information.

* Menu:

* Dictionary Types::            About dictionary types; what they're good for.
* Association Lists::           List-based dictionaries.
* Hash Tables::                 Table-based dictionaries.


File: guile.info,  Node: Dictionary Types,  Next: Association Lists,  Up: Association Lists and Hash Tables

Dictionary Types
----------------

   A "dictionary" object is a data structure used to index information
in a user-defined way.  In standard Scheme, the main aggregate data
types are lists and vectors.  Lists are not really indexed at all, and
vectors are indexed only by number (e.g. `(vector-ref foo 5)').  Often
you will find it useful to index your data on some other type; for
example, in a library catalog you might want to look up a book by the
name of its author.  Dictionaries are used to help you organize
information in such a way.

   An "association list" (or "alist" for short) is a list of key-value
pairs.  Each pair represents a single quantity or object; the `car' of
the pair is a key which is used to identify the object, and the `cdr'
is the object's value.

   A "hash table" also permits you to index objects with arbitrary
keys, but in a way that makes looking up any one object extremely fast.
A well-designed hash system makes hash table lookups almost as fast as
conventional array or vector references.

   Alists are popular among Lisp programmers because they use only the
language's primitive operations (lists, "car", "cdr" and the equality
primitives).  No changes to the language core are necessary.
Therefore, with Scheme's built-in list manipulation facilities, it is
very convenient to handle data stored in an association list.  Also,
alists are highly portable and can be easily implemented on even the
most minimal Lisp systems.

   However, alists are inefficient, especially for storing large
quantities of data.  Because we want Guile to be useful for large
software systems as well as small ones, Guile provides a rich set of
tools for using either association lists or hash tables.


File: guile.info,  Node: Association Lists,  Next: Hash Tables,  Prev: Dictionary Types,  Up: Association Lists and Hash Tables

Association Lists
-----------------

   An association list is a conventional data structure that is often
used to implement simple key-value databases.  It consists of a list of
entries in which each entry is a pair.  The "key" of each entry is the
`car' of the pair and the "value" of each entry is the `cdr'.

     ASSOCIATION LIST ::=  '( (KEY1 . VALUE1)
                              (KEY2 . VALUE2)
                              (KEY3 . VALUE3)
                              ...
                            )

Association lists are also known, for short, as "alists".

   The structure of an association list is just one example of the
infinite number of possible structures that can be built using pairs
and lists.  As such, the keys and values in an association list can be
manipulated using the general list structure procedures `cons', `car',
`cdr', `set-car!', `set-cdr!' and so on.  However, because association
lists are so useful, Guile also provides specific procedures for
manipulating them.

* Menu:

* Alist Key Equality::
* Adding or Setting Alist Entries::
* Retrieving Alist Entries::
* Removing Alist Entries::
* Sloppy Alist Functions::
* Alist Example::


File: guile.info,  Node: Alist Key Equality,  Next: Adding or Setting Alist Entries,  Up: Association Lists

Alist Key Equality
..................

   All of Guile's dedicated association list procedures, apart from
`acons', come in three flavours, depending on the level of equality
that is required to decide whether an existing key in the association
list is the same as the key that the procedure call uses to identify the
required entry.

   * Procedures with "assq" in their name use `eq?' to determine key
     equality.

   * Procedures with "assv" in their name use `eqv?' to determine key
     equality.

   * Procedures with "assoc" in their name use `equal?' to determine
     key equality.

   `acons' is an exception because it is used to build association
lists which do not require their entries' keys to be unique.


File: guile.info,  Node: Adding or Setting Alist Entries,  Next: Retrieving Alist Entries,  Prev: Alist Key Equality,  Up: Association Lists

Adding or Setting Alist Entries
...............................

   `acons' adds a new entry to an association list and returns the
combined association list.  The combined alist is formed by consing the
new entry onto the head of the alist specified in the `acons' procedure
call.  So the specified alist is not modified, but its contents become
shared with the tail of the combined alist that `acons' returns.

   In the most common usage of `acons', a variable holding the original
association list is updated with the combined alist:

     (set! address-list (acons name address address-list))

   In such cases, it doesn't matter that the old and new values of
`address-list' share some of their contents, since the old value is
usually no longer independently accessible.

   Note that `acons' adds the specified new entry regardless of whether
the alist may already contain entries with keys that are, in some
sense, the same as that of the new entry.  Thus `acons' is ideal for
building alists where there is no concept of key uniqueness.

     (set! task-list (acons 3 "pay gas bill" '()))
     task-list
     =>
     ((3 . "pay gas bill"))
     
     (set! task-list (acons 3 "tidy bedroom" task-list))
     task-list
     =>
     ((3 . "tidy bedroom") (3 . "pay gas bill"))

   `assq-set!', `assv-set!' and `assoc-set!' are used to add or replace
an entry in an association list where there _is_ a concept of key
uniqueness.  If the specified association list already contains an
entry whose key is the same as that specified in the procedure call,
the existing entry is replaced by the new one.  Otherwise, the new
entry is consed onto the head of the old association list to create the
combined alist.  In all cases, these procedures return the combined
alist.

   `assq-set!' and friends _may_ destructively modify the structure of
the old association list in such a way that an existing variable is
correctly updated without having to `set!' it to the value returned:

     address-list
     =>
     (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
     
     (assoc-set! address-list "james" "1a London Road")
     =>
     (("mary" . "34 Elm Road") ("james" . "1a London Road"))
     
     address-list
     =>
     (("mary" . "34 Elm Road") ("james" . "1a London Road"))

   Or they may not:

     (assoc-set! address-list "bob" "11 Newington Avenue")
     =>
     (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
      ("james" . "1a London Road"))
     
     address-list
     =>
     (("mary" . "34 Elm Road") ("james" . "1a London Road"))

   The only safe way to update an association list variable when adding
or replacing an entry like this is to `set!' the variable to the
returned value:

     (set! address-list
           (assoc-set! address-list "bob" "11 Newington Avenue"))
     address-list
     =>
     (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
      ("james" . "1a London Road"))

   Because of this slight inconvenience, you may find it more
convenient to use hash tables to store dictionary data.  If your
application will not be modifying the contents of an alist very often,
this may not make much difference to you.

   If you need to keep the old value of an association list in a form
independent from the list that results from modification by `acons',
`assq-set!', `assv-set!' or `assoc-set!', use `list-copy' to copy the
old association list before modifying it.

 - Scheme Procedure: acons key value alist
 - C Function: scm_acons (key, value, alist)
     Add a new key-value pair to ALIST.  A new pair is created whose
     car is KEY and whose cdr is VALUE, and the pair is consed onto
     ALIST, and the new list is returned.  This function is _not_
     destructive; ALIST is not modified.

 - Scheme Procedure: assq-set! alist key val
 - Scheme Procedure: assv-set! alist key value
 - Scheme Procedure: assoc-set! alist key value
 - C Function: scm_assq_set_x (alist, key, val)
 - C Function: scm_assv_set_x (alist, key, val)
 - C Function: scm_assoc_set_x (alist, key, val)
     Reassociate KEY in ALIST with VALUE: find any existing ALIST entry
     for KEY and associate it with the new VALUE.  If ALIST does not
     contain an entry for KEY, add a new one.  Return the (possibly
     new) alist.

     These functions do not attempt to verify the structure of ALIST,
     and so may cause unusual results if passed an object that is not an
     association list.


File: guile.info,  Node: Retrieving Alist Entries,  Next: Removing Alist Entries,  Prev: Adding or Setting Alist Entries,  Up: Association Lists

Retrieving Alist Entries
........................

   `assq', `assv' and `assoc' take an alist and a key as arguments and
return the entry for that key if an entry exists, or `#f' if there is
no entry for that key.  Note that, in the cases where an entry exists,
these procedures return the complete entry, that is `(KEY . VALUE)',
not just the value.

 - Scheme Procedure: assq key alist
 - Scheme Procedure: assv key alist
 - Scheme Procedure: assoc key alist
 - C Function: scm_assq (key, alist)
 - C Function: scm_assv (key, alist)
 - C Function: scm_assoc (key, alist)
     Fetch the entry in ALIST that is associated with KEY.  To decide
     whether the argument KEY matches a particular entry in ALIST,
     `assq' compares keys with `eq?', `assv' uses `eqv?' and `assoc'
     uses `equal?'.  If KEY cannot be found in ALIST (according to
     whichever equality predicate is in use), then return `#f'.  These
     functions return the entire alist entry found (i.e. both the key
     and the value).

   `assq-ref', `assv-ref' and `assoc-ref', on the other hand, take an
alist and a key and return _just the value_ for that key, if an entry
exists.  If there is no entry for the specified key, these procedures
return `#f'.

   This creates an ambiguity: if the return value is `#f', it means
either that there is no entry with the specified key, or that there
_is_ an entry for the specified key, with value `#f'.  Consequently,
`assq-ref' and friends should only be used where it is known that an
entry exists, or where the ambiguity doesn't matter for some other
reason.

 - Scheme Procedure: assq-ref alist key
 - Scheme Procedure: assv-ref alist key
 - Scheme Procedure: assoc-ref alist key
 - C Function: scm_assq_ref (alist, key)
 - C Function: scm_assv_ref (alist, key)
 - C Function: scm_assoc_ref (alist, key)
     Like `assq', `assv' and `assoc', except that only the value
     associated with KEY in ALIST is returned.  These functions are
     equivalent to

          (let ((ent (ASSOCIATOR KEY ALIST)))
            (and ent (cdr ent)))

     where ASSOCIATOR is one of `assq', `assv' or `assoc'.


File: guile.info,  Node: Removing Alist Entries,  Next: Sloppy Alist Functions,  Prev: Retrieving Alist Entries,  Up: Association Lists

Removing Alist Entries
......................

   To remove the element from an association list whose key matches a
specified key, use `assq-remove!', `assv-remove!' or `assoc-remove!'
(depending, as usual, on the level of equality required between the key
that you specify and the keys in the association list).

   As with `assq-set!' and friends, the specified alist may or may not
be modified destructively, and the only safe way to update a variable
containing the alist is to `set!' it to the value that `assq-remove!'
and friends return.

     address-list
     =>
     (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
      ("james" . "1a London Road"))
     
     (set! address-list (assoc-remove! address-list "mary"))
     address-list
     =>
     (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))

   Note that, when `assq/v/oc-remove!' is used to modify an association
list that has been constructed only using the corresponding
`assq/v/oc-set!', there can be at most one matching entry in the alist,
so the question of multiple entries being removed in one go does not
arise.  If `assq/v/oc-remove!' is applied to an association list that
has been constructed using `acons', or an `assq/v/oc-set!' with a
different level of equality, or any mixture of these, it removes only
the first matching entry from the alist, even if the alist might
contain further matching entries.  For example:

     (define address-list '())
     (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
     (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
     address-list
     =>
     (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
     
     (set! address-list (assoc-remove! address-list "mary"))
     address-list
     =>
     (("mary" . "11 Elm Street"))

   In this example, the two instances of the string "mary" are not the
same when compared using `eq?', so the two `assq-set!' calls add two
distinct entries to `address-list'.  When compared using `equal?', both
"mary"s in `address-list' are the same as the "mary" in the
`assoc-remove!' call, but `assoc-remove!' stops after removing the
first matching entry that it finds, and so one of the "mary" entries is
left in place.

 - Scheme Procedure: assq-remove! alist key
 - Scheme Procedure: assv-remove! alist key
 - Scheme Procedure: assoc-remove! alist key
 - C Function: scm_assq_remove_x (alist, key)
 - C Function: scm_assv_remove_x (alist, key)
 - C Function: scm_assoc_remove_x (alist, key)
     Delete the first entry in ALIST associated with KEY, and return
     the resulting alist.


File: guile.info,  Node: Sloppy Alist Functions,  Next: Alist Example,  Prev: Removing Alist Entries,  Up: Association Lists

Sloppy Alist Functions
......................

   `sloppy-assq', `sloppy-assv' and `sloppy-assoc' behave like the
corresponding non-`sloppy-' procedures, except that they return `#f'
when the specified association list is not well-formed, where the
non-`sloppy-' versions would signal an error.

   Specifically, there are two conditions for which the non-`sloppy-'
procedures signal an error, which the `sloppy-' procedures handle
instead by returning `#f'.  Firstly, if the specified alist as a whole
is not a proper list:

     (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
     =>
     ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
     ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
     ABORT: (wrong-type-arg)
     
     (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
     =>
     #f

Secondly, if one of the entries in the specified alist is not a pair:

     (assoc 2 '((1 . 1) 2 (3 . 9)))
     =>
     ERROR: In procedure assoc in expression (assoc 2 (quote #)):
     ERROR: Wrong type argument in position 2 (expecting CONSP): 2
     ABORT: (wrong-type-arg)
     
     (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
     =>
     #f

   Unless you are explicitly working with badly formed association
lists, it is much safer to use the non-`sloppy-' procedures, because
they help to highlight coding and data errors that the `sloppy-'
versions would silently cover up.

 - Scheme Procedure: sloppy-assq key alist
 - C Function: scm_sloppy_assq (key, alist)
     Behaves like `assq' but does not do any error checking.
     Recommended only for use in Guile internals.

 - Scheme Procedure: sloppy-assv key alist
 - C Function: scm_sloppy_assv (key, alist)
     Behaves like `assv' but does not do any error checking.
     Recommended only for use in Guile internals.

 - Scheme Procedure: sloppy-assoc key alist
 - C Function: scm_sloppy_assoc (key, alist)
     Behaves like `assoc' but does not do any error checking.
     Recommended only for use in Guile internals.


File: guile.info,  Node: Alist Example,  Prev: Sloppy Alist Functions,  Up: Association Lists

Alist Example
.............

   Here is a longer example of how alists may be used in practice.

     (define capitals '(("New York" . "Albany")
                        ("Oregon"   . "Salem")
                        ("Florida"  . "Miami")))
     
     ;; What's the capital of Oregon?
     (assoc "Oregon" capitals)       => ("Oregon" . "Salem")
     (assoc-ref capitals "Oregon")   => "Salem"
     
     ;; We left out South Dakota.
     (set! capitals
           (assoc-set! capitals "South Dakota" "Pierre"))
     capitals
     => (("South Dakota" . "Pierre")
         ("New York" . "Albany")
         ("Oregon" . "Salem")
         ("Florida" . "Miami"))
     
     ;; And we got Florida wrong.
     (set! capitals
           (assoc-set! capitals "Florida" "Tallahassee"))
     capitals
     => (("South Dakota" . "Pierre")
         ("New York" . "Albany")
         ("Oregon" . "Salem")
         ("Florida" . "Tallahassee"))
     
     ;; After Oregon secedes, we can remove it.
     (set! capitals
           (assoc-remove! capitals "Oregon"))
     capitals
     => (("South Dakota" . "Pierre")
         ("New York" . "Albany")
         ("Florida" . "Tallahassee"))


File: guile.info,  Node: Hash Tables,  Prev: Association Lists,  Up: Association Lists and Hash Tables

Hash Tables
-----------

   Hash tables are dictionaries which offer similar functionality as
association lists: They provide a mapping from keys to values.  The
difference is that association lists need time linear in the size of
elements when searching for entries, whereas hash tables can normally
search in constant time.  The drawback is that hash tables require a
little bit more memory, and that you can not use the normal list
procedures (*note Lists::) for working with them.

* Menu:

* Hash Table Examples::         Demonstration of hash table usage.
* Hash Table Reference::        Hash table procedure descriptions.


File: guile.info,  Node: Hash Table Examples,  Next: Hash Table Reference,  Up: Hash Tables

Hash Table Examples
...................

   For demonstration purposes, this section gives a few usage examples
of some hash table procedures, together with some explanation what they
do.

   First we start by creating a new hash table with 31 slots, and
populate it with two key/value pairs.

     (define h (make-hash-table 31))
     
     (hashq-create-handle! h 'foo "bar")
     =>
     (foo . "bar")
     
     (hashq-create-handle! h 'braz "zonk")
     =>
     (braz . "zonk")
     
     (hashq-create-handle! h 'frob #f)
     =>
     (frob . #f)

   You can get the value for a given key with the procedure
`hashq-ref', but the problem with this procedure is that you cannot
reliably determine whether a key does exists in the table.  The reason
is that the procedure returns `#f' if the key is not in the table, but
it will return the same value if the key is in the table and just
happens to have the value `#f', as you can see in the following
examples.

     (hashq-ref h 'foo)
     =>
     "bar"
     
     (hashq-ref h 'frob)
     =>
     #f
     
     (hashq-ref h 'not-there)
     =>
     #f

   Better is to use the procedure `hashq-get-handle', which makes a
distinction between the two cases.  Just like `assq', this procedure
returns a key/value-pair on success, and `#f' if the key is not found.

     (hashq-get-handle h 'foo)
     =>
     (foo . "bar")
     
     (hashq-get-handle h 'not-there)
     =>
     #f

   There is no procedure for calculating the number of key/value-pairs
in a hash table, but `hash-fold' can be used for doing exactly that.

     (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
     =>
     3


File: guile.info,  Node: Hash Table Reference,  Prev: Hash Table Examples,  Up: Hash Tables

Hash Table Reference
....................

   Like the association list functions, the hash table functions come
in several varieties: `hashq', `hashv', and `hash'.  The `hashq'
functions use `eq?' to determine whether two keys match.  The `hashv'
functions use `eqv?', and the `hash' functions use `equal?'.

   In each of the functions that follow, the TABLE argument must be a
vector.  The KEY and VALUE arguments may be any Scheme object.

 - Scheme Procedure: make-hash-table size
     Create a new hash table of SIZE slots.  Note that the number of
     slots does not limit the size of the table, it just tells how large
     the underlying vector will be.  The SIZE should be similar to the
     expected number of elements which will be added to the table, but
     they need not match.  For good performance, it might be a good
     idea to use a prime number as the SIZE.

 - Scheme Procedure: hashq-ref table key [dflt]
 - C Function: scm_hashq_ref (table, key, dflt)
     Look up KEY in the hash table TABLE, and return the value (if any)
     associated with it.  If KEY is not found, return DEFAULT (or `#f'
     if no DEFAULT argument is supplied).  Uses `eq?' for equality
     testing.

 - Scheme Procedure: hashv-ref table key [dflt]
 - C Function: scm_hashv_ref (table, key, dflt)
     Look up KEY in the hash table TABLE, and return the value (if any)
     associated with it.  If KEY is not found, return DEFAULT (or `#f'
     if no DEFAULT argument is supplied).  Uses `eqv?' for equality
     testing.

 - Scheme Procedure: hash-ref table key [dflt]
 - C Function: scm_hash_ref (table, key, dflt)
     Look up KEY in the hash table TABLE, and return the value (if any)
     associated with it.  If KEY is not found, return DEFAULT (or `#f'
     if no DEFAULT argument is supplied).  Uses `equal?' for equality
     testing.

 - Scheme Procedure: hashq-set! table key val
 - C Function: scm_hashq_set_x (table, key, val)
     Find the entry in TABLE associated with KEY, and store VALUE
     there. Uses `eq?' for equality testing.

 - Scheme Procedure: hashv-set! table key val
 - C Function: scm_hashv_set_x (table, key, val)
     Find the entry in TABLE associated with KEY, and store VALUE
     there. Uses `eqv?' for equality testing.

 - Scheme Procedure: hash-set! table key val
 - C Function: scm_hash_set_x (table, key, val)
     Find the entry in TABLE associated with KEY, and store VALUE
     there. Uses `equal?' for equality testing.

 - Scheme Procedure: hashq-remove! table key
 - C Function: scm_hashq_remove_x (table, key)
     Remove KEY (and any value associated with it) from TABLE.  Uses
     `eq?' for equality tests.

 - Scheme Procedure: hashv-remove! table key
 - C Function: scm_hashv_remove_x (table, key)
     Remove KEY (and any value associated with it) from TABLE.  Uses
     `eqv?' for equality tests.

 - Scheme Procedure: hash-remove! table key
 - C Function: scm_hash_remove_x (table, key)
     Remove KEY (and any value associated with it) from TABLE.  Uses
     `equal?' for equality tests.

   The standard hash table functions may be too limited for some
applications.  For example, you may want a hash table to store strings
in a case-insensitive manner, so that references to keys named
"foobar", "FOOBAR" and "FooBaR" will all yield the same item.  Guile
provides you with "extended" hash tables that permit you to specify a
hash function and associator function of your choosing.  The functions
described in the rest of this section can be used to implement such
custom hash table structures.

   If you are unfamiliar with the inner workings of hash tables, then
this facility will probably be a little too abstract for you to use
comfortably.  If you are interested in learning more, see an
introductory textbook on data structures or algorithms for an
explanation of how hash tables are implemented.

 - Scheme Procedure: hashq key size
 - C Function: scm_hashq (key, size)
     Determine a hash value for KEY that is suitable for lookups in a
     hash table of size SIZE, where `eq?' is used as the equality
     predicate.  The function returns an integer in the range 0 to SIZE
     - 1.  Note that `hashq' may use internal addresses.  Thus two
     calls to hashq where the keys are `eq?' are not guaranteed to
     deliver the same value if the key object gets garbage collected in
     between.  This can happen, for example with symbols: `(hashq 'foo
     n) (gc) (hashq 'foo n)' may produce two different values, since
     `foo' will be garbage collected.

 - Scheme Procedure: hashv key size
 - C Function: scm_hashv (key, size)
     Determine a hash value for KEY that is suitable for lookups in a
     hash table of size SIZE, where `eqv?' is used as the equality
     predicate.  The function returns an integer in the range 0 to SIZE
     - 1.  Note that `(hashv key)' may use internal addresses.  Thus
     two calls to hashv where the keys are `eqv?' are not guaranteed to
     deliver the same value if the key object gets garbage collected in
     between.  This can happen, for example with symbols: `(hashv 'foo
     n) (gc) (hashv 'foo n)' may produce two different values, since
     `foo' will be garbage collected.

 - Scheme Procedure: hash key size
 - C Function: scm_hash (key, size)
     Determine a hash value for KEY that is suitable for lookups in a
     hash table of size SIZE, where `equal?' is used as the equality
     predicate.  The function returns an integer in the range 0 to SIZE
     - 1.

 - Scheme Procedure: hashx-ref hash assoc table key [dflt]
 - C Function: scm_hashx_ref (hash, assoc, table, key, dflt)
     This behaves the same way as the corresponding `ref' function, but
     uses HASH as a hash function and ASSOC to compare keys.  `hash'
     must be a function that takes two arguments, a key to be hashed
     and a table size.  `assoc' must be an associator function, like
     `assoc', `assq' or `assv'.

     By way of illustration, `hashq-ref table key' is equivalent to
     `hashx-ref hashq assq table key'.

 - Scheme Procedure: hashx-set! hash assoc table key val
 - C Function: scm_hashx_set_x (hash, assoc, table, key, val)
     This behaves the same way as the corresponding `set!' function,
     but uses HASH as a hash function and ASSOC to compare keys.
     `hash' must be a function that takes two arguments, a key to be
     hashed and a table size.  `assoc' must be an associator function,
     like `assoc', `assq' or `assv'.

     By way of illustration, `hashq-set! table key' is equivalent to
     `hashx-set!  hashq assq table key'.

 - Scheme Procedure: hashq-get-handle table key
 - C Function: scm_hashq_get_handle (table, key)
     This procedure returns the `(key . value)' pair from the hash
     table TABLE.  If TABLE does not hold an associated value for KEY,
     `#f' is returned.  Uses `eq?' for equality testing.

 - Scheme Procedure: hashv-get-handle table key
 - C Function: scm_hashv_get_handle (table, key)
     This procedure returns the `(key . value)' pair from the hash
     table TABLE.  If TABLE does not hold an associated value for KEY,
     `#f' is returned.  Uses `eqv?' for equality testing.

 - Scheme Procedure: hash-get-handle table key
 - C Function: scm_hash_get_handle (table, key)
     This procedure returns the `(key . value)' pair from the hash
     table TABLE.  If TABLE does not hold an associated value for KEY,
     `#f' is returned.  Uses `equal?' for equality testing.

 - Scheme Procedure: hashx-get-handle hash assoc table key
 - C Function: scm_hashx_get_handle (hash, assoc, table, key)
     This behaves the same way as the corresponding `-get-handle'
     function, but uses HASH as a hash function and ASSOC to compare
     keys.  `hash' must be a function that takes two arguments, a key
     to be hashed and a table size.  `assoc' must be an associator
     function, like `assoc', `assq' or `assv'.

 - Scheme Procedure: hashq-create-handle! table key init
 - C Function: scm_hashq_create_handle_x (table, key, init)
     This function looks up KEY in TABLE and returns its handle.  If
     KEY is not already present, a new handle is created which
     associates KEY with INIT.

 - Scheme Procedure: hashv-create-handle! table key init
 - C Function: scm_hashv_create_handle_x (table, key, init)
     This function looks up KEY in TABLE and returns its handle.  If
     KEY is not already present, a new handle is created which
     associates KEY with INIT.

 - Scheme Procedure: hash-create-handle! table key init
 - C Function: scm_hash_create_handle_x (table, key, init)
     This function looks up KEY in TABLE and returns its handle.  If
     KEY is not already present, a new handle is created which
     associates KEY with INIT.

 - Scheme Procedure: hashx-create-handle! hash assoc table key init
 - C Function: scm_hashx_create_handle_x (hash, assoc, table, key, init)
     This behaves the same way as the corresponding `-create-handle'
     function, but uses HASH as a hash function and ASSOC to compare
     keys.  `hash' must be a function that takes two arguments, a key
     to be hashed and a table size.  `assoc' must be an associator
     function, like `assoc', `assq' or `assv'.

 - Scheme Procedure: hash-fold proc init table
 - C Function: scm_hash_fold (proc, init, table)
     An iterator over hash-table elements.  Accumulates and returns a
     result by applying PROC successively.  The arguments to PROC are
     "(key value prior-result)" where key and value are successive
     pairs from the hash table TABLE, and prior-result is either INIT
     (for the first application of PROC) or the return value of the
     previous application of PROC.  For example, `(hash-fold acons '()
     tab)' will convert a hash table into an a-list of key-value pairs.


File: guile.info,  Node: Procedures and Macros,  Next: Utility Functions,  Prev: Compound Data Types,  Up: Top

Procedures and Macros
*********************

* Menu:

* Lambda::                      Basic procedure creation using lambda.
* Optional Arguments::          Handling keyword, optional and rest arguments.
* Procedure Properties::        Procedure properties and meta-information.
* Procedures with Setters::     Procedures with setters.
* Macros::                      Lisp style macro definitions.
* Syntax Rules::                Support for R5RS `syntax-rules'.
* Syntax Case::                 Support for the `syntax-case' system.
* Internal Macros::             Guile's internal representation.


File: guile.info,  Node: Lambda,  Next: Optional Arguments,  Up: Procedures and Macros

Lambda: Basic Procedure Creation
================================

   A `lambda' expression evaluates to a procedure.  The environment
which is in effect when a `lambda' expression is evaluated is enclosed
in the newly created procedure, this is referred to as a "closure"
(*note About Closure::).

   When a procedure created by `lambda' is called with some actual
arguments, the environment enclosed in the procedure is extended by
binding the variables named in the formal argument list to new locations
and storing the actual arguments into these locations.  Then the body of
the `lambda' expression is evaluation sequentially.  The result of the
last expression in the procedure body is then the result of the
procedure invocation.

   The following examples will show how procedures can be created using
`lambda', and what you can do with these procedures.

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

   The fact that the environment in effect when creating a procedure is
enclosed in the procedure is shown with this example:

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

 - syntax: lambda formals body
     FORMALS should be a formal argument list as described in the
     following table.

    `(VARIABLE1 ...)'
          The procedure takes a fixed number of arguments; when the
          procedure is called, the arguments will be stored into the
          newly created location for the formal variables.

    `VARIABLE'
          The procedure takes any number of arguments; when the
          procedure is called, the sequence of actual arguments will
          converted into a list and stored into the newly created
          location for the formal variable.

    `(VARIABLE1 ... VARIABLEN . VARIABLEN+1)'
          If a space-delimited period precedes the last variable, then
          the procedure takes N or more variables where N is the number
          of formal arguments before the period.  There must be at
          least one argument before the period.  The first N actual
          arguments will be stored into the newly allocated locations
          for the first N formal arguments and the sequence of the
          remaining actual arguments is converted into a list and the
          stored into the location for the last formal argument.  If
          there are exactly N actual arguments, the empty list is
          stored into the location of the last formal argument.

     BODY is a sequence of Scheme expressions which are evaluated in
     order when the procedure is invoked.


File: guile.info,  Node: Optional Arguments,  Next: Procedure Properties,  Prev: Lambda,  Up: Procedures and Macros

Optional Arguments
==================

   Scheme procedures, as defined in R5RS, can either handle a fixed
number of actual arguments, or a fixed number of actual arguments
followed by arbitrarily many additional arguments.  Writing procedures
of variable arity can be useful, but unfortunately, the syntactic means
for handling argument lists of varying length is a bit inconvenient.
It is possible to give names to the fixed number of argument, but the
remaining (optional) arguments can be only referenced as a list of
values (*note Lambda::).

   Guile comes with the module `(ice-9 optargs)', which makes using
optional arguments much more convenient.  In addition, this module
provides syntax for handling keywords in argument lists (*note
Keywords::).

   Before using any of the procedures or macros defined in this section,
you have to load the module `(ice-9 optargs)' with the statement:

     (use-modules (ice-9 optargs))

* Menu:

* let-optional Reference::      Locally binding optional arguments.
* let-keywords Reference::      Locally binding keywords arguments.
* lambda* Reference::           Creating advanced argument handling procedures.
* define* Reference::           Defining procedures and macros.


File: guile.info,  Node: let-optional Reference,  Next: let-keywords Reference,  Up: Optional Arguments

let-optional Reference
----------------------

   The syntax `let-optional' and `let-optional*' are for destructuring
rest argument lists and giving names to the various list elements.
`let-optional' binds all variables simultaneously, while
`let-optional*' binds them sequentially, consistent with `let' and
`let*' (*note Local Bindings::).

 - library syntax: let-optional rest-arg (binding ...) expr ...
 - library syntax: let-optional* rest-arg (binding ...) expr ...
     These two macros give you an optional argument interface that is
     very "Schemey" and introduces no fancy syntax. They are compatible
     with the scsh macros of the same name, but are slightly extended.
     Each of BINDING may be of one of the forms VAR or `(VAR
     DEFAULT-VALUE)'. REST-ARG should be the rest-argument of the
     procedures these are used from.  The items in REST-ARG are
     sequentially bound to the variable names are given. When REST-ARG
     runs out, the remaining vars are bound either to the default
     values or `#f' if no default value was specified. REST-ARG remains
     bound to whatever may have been left of REST-ARG.

     After binding the variables, the expressions EXPR ... are
     evaluated in order.


File: guile.info,  Node: let-keywords Reference,  Next: lambda* Reference,  Prev: let-optional Reference,  Up: Optional Arguments

let-keywords Reference
----------------------

   `let-keywords' and `let-keywords*' are used for extracting values
from argument lists which use keywords instead of argument position for
binding local variables to argument values.

   `let-keywords' binds all variables simultaneously, while
`let-keywords*' binds them sequentially, consistent with `let' and
`let*' (*note Local Bindings::).

 - library syntax: let-keywords rest-arg allow-other-keys? (binding
          ...) expr ...
 - library syntax: let-keywords rest-arg allow-other-keys? (binding
          ...) expr ...
     These macros pick out keyword arguments from REST-ARG, but do not
     modify it.  This is consistent at least with Common Lisp, which
     duplicates keyword arguments in the rest argument. More
     explanation of what keyword arguments in a lambda list look like
     can be found below in the documentation for `lambda*'  (*note
     lambda* Reference::).  BINDINGs can have the same form as for
     `let-optional'. If ALLOW-OTHER-KEYS? is false, an error will be
     thrown if anything that looks like a keyword argument but does not
     match a known keyword parameter will result in an error.

     After binding the variables, the expressions EXPR ... are
     evaluated in order.


File: guile.info,  Node: lambda* Reference,  Next: define* Reference,  Prev: let-keywords Reference,  Up: Optional Arguments

lambda* Reference
-----------------

   When using optional and keyword argument lists, using `lambda' for
creating procedures and using `let-optional' or `let-keywords' is a bit
lengthy.  Therefore, `lambda*' is provided, which combines the features
of those macros into a single convenient syntax.

   For quick reference, here is the syntax of the formal argument list
for `lambda*' (brackets are used to indicate grouping only):

     ext-param-list ::= [identifier]* [#:optional [ext-var-decl]+]?
       [#:key [ext-var-decl]+ [#:allow-other-keys]?]?
       [[#:rest identifier]|[. identifier]]?
     
     ext-var-decl ::= identifier | ( identifier expression )

   The characters `*', `+' and `?' are not to be taken literally; they
mean respectively, zero or more occurrences, one or more occurrences,
and one or zero occurrences.

 - library syntax: lambda* formals body
     `lambda*' creates a procedure that takes optional arguments. These
     are specified by putting them inside brackets at the end of the
     parameter list, but before any dotted rest argument. For example,

          (lambda* (a b #:optional c d . e) '())

     creates a procedure with fixed arguments A and B, optional
     arguments C and D, and rest argument E. If the optional arguments
     are omitted in a call, the variables for them are bound to `#f'.

     `lambda*' can also take keyword arguments. For example, a procedure
     defined like this:

          (lambda* (#:key xyzzy larch) '())

     can be called with any of the argument lists `(#:xyzzy 11)'
     `(#:larch 13)' `(#:larch 42 #:xyzzy 19)' `()'. Whichever arguments
     are given as keywords are bound to values.

     Optional and keyword arguments can also be given default values
     which they take on when they are not present in a call, by giving a
     two-item list in place of an optional argument, for example in:

          (lambda* (foo #:optional (bar 42) #:key (baz 73))
               (list foo bar baz))

     FOO is a fixed argument, BAR is an optional argument with default
     value 42, and baz is a keyword argument with default value 73.
     Default value expressions are not evaluated unless they are needed
     and until the procedure is called.

     `lambda*' also supports two more special parameter list keywords.

     `lambda*'-defined procedures now throw an error by default if a
     keyword other than one of those specified is found in the actual
     passed arguments. However, specifying `#:allow-other-keys'
     immediately after the keyword argument declarations restores the
     previous behavior of ignoring unknown keywords.  `lambda*' also now
     guarantees that if the same keyword is passed more than once, the
     last one passed is the one that takes effect. For example,

          ((lambda* (#:key (heads 0) (tails 0)) (display (list heads tails)))
              #:heads 37 #:tails 42 #:heads 99)

     would result in (99 47) being displayed.

     `#:rest' is also now provided as a synonym for the dotted syntax
     rest argument. The argument lists `(a . b)' and `(a #:rest b)' are
     equivalent in all respects to `lambda*'. This is provided for more
     similarity to DSSSL, MIT-Scheme and Kawa among others, as well as
     for refugees from other Lisp dialects.


File: guile.info,  Node: define* Reference,  Prev: lambda* Reference,  Up: Optional Arguments

define* Reference
-----------------

   Just like `define' has a shorthand notation for defining procedures
(*note Lambda Alternatives::), `define*' is provided as an abbreviation
of the combination of `define' and `lambda*'.

   `define*-public' is the `lambda*' version of `define-public';
`defmacro*' and `defmacro*-public' exist for defining macros with the
improved argument list handling possibilities.  The `-public' versions
not only define the procedures/macros, but also export them from the
current module.

 - library syntax: define* formals body
 - library syntax: define*-public formals body
     `define*' and `define*-public' support optional arguments with a
     similar syntax to `lambda*'. They also support arbitrary-depth
     currying, just like Guile's define. Some examples:

          (define* (x y #:optional a (z 3) #:key w . u)
             (display (list y z u)))
     defines a procedure `x' with a fixed argument Y, an optional
     argument A, another optional argument Z with default value 3, a
     keyword argument W, and a rest argument U.

          (define-public* ((foo #:optional bar) #:optional baz) '())

     This illustrates currying. A procedure `foo' is defined, which,
     when called with an optional argument BAR, returns a procedure
     that takes an optional argument BAZ.

     Of course, `define*[-public]' also supports `#:rest' and
     `#:allow-other-keys' in the same way as `lambda*'.

 - library syntax: defmacro* name formals body
 - library syntax: defmacro*-public name formals body
     These are just like `defmacro' and `defmacro-public' except that
     they take `lambda*'-style extended parameter lists, where
     `#:optional', `#:key', `#:allow-other-keys' and `#:rest' are
     allowed with the usual semantics. Here is an example of a macro
     with an optional argument:

          (defmacro* transmorgify (a #:optional b)
              (a 1))


File: guile.info,  Node: Procedure Properties,  Next: Procedures with Setters,  Prev: Optional Arguments,  Up: Procedures and Macros

Procedure Properties and Meta-information
=========================================

   Procedures always have attached the environment in which they were
created and information about how to apply them to actual arguments.  In
addition to that, properties and meta-information can be stored with
procedures.  The procedures in this section can be used to test whether
a given procedure satisfies a condition; and to access and set a
procedure's property.

   The first group of procedures are predicates to test whether a Scheme
object is a procedure, or a special procedure, respectively.
`procedure?' is the most general predicates, it returns `#t' for any
kind of procedure.  `closure?' does not return `#t' for primitive
procedures, and `thunk?' only returns `#t' for procedures which do not
accept any arguments.

 - Scheme Procedure: procedure? obj
 - C Function: scm_procedure_p (obj)
     Return `#t' if OBJ is a procedure.

 - Scheme Procedure: closure? obj
 - C Function: scm_closure_p (obj)
     Return `#t' if OBJ is a closure.

 - Scheme Procedure: thunk? obj
 - C Function: scm_thunk_p (obj)
     Return `#t' if OBJ is a thunk.

   Procedure properties are general properties to be attached to
procedures.  These can be the name of a procedure or other relevant
information, such as debug hints.

 - Scheme Procedure: procedure-name proc
 - C Function: scm_procedure_name (proc)
     Return the name of the procedure PROC

 - Scheme Procedure: procedure-source proc
 - C Function: scm_procedure_source (proc)
     Return the source of the procedure PROC.

 - Scheme Procedure: procedure-environment proc
 - C Function: scm_procedure_environment (proc)
     Return the environment of the procedure PROC.

 - Scheme Procedure: procedure-properties proc
 - C Function: scm_procedure_properties (proc)
     Return OBJ's property list.

 - Scheme Procedure: procedure-property obj key
 - C Function: scm_procedure_property (obj, key)
     Return the property of OBJ with name KEY.

 - Scheme Procedure: set-procedure-properties! proc alist
 - C Function: scm_set_procedure_properties_x (proc, alist)
     Set OBJ's property list to ALIST.

 - Scheme Procedure: set-procedure-property! obj key value
 - C Function: scm_set_procedure_property_x (obj, key, value)
     In OBJ's property list, set the property named KEY to VALUE.

   Documentation for a procedure can be accessed with the procedure
`procedure-documentation'.

 - Scheme Procedure: procedure-documentation proc
 - C Function: scm_procedure_documentation (proc)
     Return the documentation string associated with `proc'.  By
     convention, if a procedure contains more than one expression and
     the first expression is a string constant, that string is assumed
     to contain documentation for that procedure.

   Source properties are properties which are related to the source
code of a procedure, such as the line and column numbers, the file name
etc.

 - Scheme Procedure: set-source-properties! obj plist
 - C Function: scm_set_source_properties_x (obj, plist)
     Install the association list PLIST as the source property list for
     OBJ.

 - Scheme Procedure: set-source-property! obj key datum
 - C Function: scm_set_source_property_x (obj, key, datum)
     Set the source property of object OBJ, which is specified by KEY
     to DATUM.  Normally, the key will be a symbol.

 - Scheme Procedure: source-properties obj
 - C Function: scm_source_properties (obj)
     Return the source property association list of OBJ.

 - Scheme Procedure: source-property obj key
 - C Function: scm_source_property (obj, key)
     Return the source property specified by KEY from OBJ's source
     property list.


File: guile.info,  Node: Procedures with Setters,  Next: Macros,  Prev: Procedure Properties,  Up: Procedures and Macros

Procedures with Setters
=======================

   A "procedure with setter" is a special kind of procedure which
normally behaves like any accessor procedure, that is a procedure which
accesses a data structure.  The difference is that this kind of
procedure has a so-called "setter" attached, which is a procedure for
storing something into a data structure.

   Procedures with setters are treated specially when the procedure
appears in the special form `set!' (REFFIXME).  How it works is best
shown by example.

   Suppose we have a procedure called `foo-ref', which accepts two
arguments, a value of type `foo' and an integer.  The procedure returns
the value stored at the given index in the `foo' object.  Let `f' be a
variable containing such a `foo' data structure.(1)

     (foo-ref f 0)       => bar
     (foo-ref f 1)       => braz

   Also suppose that a corresponding setter procedure called `foo-set!'
does exist.

     (foo-set! f 0 'bla)
     (foo-ref f 0)       => bla

   Now we could create a new procedure called `foo', which is a
procedure with setter, by calling `make-procedure-with-setter' with the
accessor and setter procedures `foo-ref' and `foo-set!'.  Let us call
this new procedure `foo'.

     (define foo (make-procedure-with-setter foo-ref foo-set!))

   `foo' can from now an be used to either read from the data structure
stored in `f', or to write into the structure.

     (set! (foo f 0) 'dum)
     (foo f 0)          => dum

 - Scheme Procedure: make-procedure-with-setter procedure setter
 - C Function: scm_make_procedure_with_setter (procedure, setter)
     Create a new procedure which behaves like PROCEDURE, but with the
     associated setter SETTER.

 - Scheme Procedure: procedure-with-setter? obj
 - C Function: scm_procedure_with_setter_p (obj)
     Return `#t' if OBJ is a procedure with an associated setter
     procedure.

 - Scheme Procedure: procedure proc
 - C Function: scm_procedure (proc)
     Return the procedure of PROC, which must be either a procedure
     with setter, or an operator struct.

 - Scheme Procedure: setter proc
     Return the setter of PROC, which must be either a procedure with
     setter or an operator struct.

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

   (1) Working definitions would be:
     (define foo-ref vector-ref)
     (define foo-set! vector-set!)
     (define f (make-vector 2 #f))


File: guile.info,  Node: Macros,  Next: Syntax Rules,  Prev: Procedures with Setters,  Up: Procedures and Macros

Lisp Style Macro Definitions
============================

   Macros are objects which cause the expression that they appear in to
be transformed in some way _before_ being evaluated.  In expressions
that are intended for macro transformation, the identifier that names
the relevant macro must appear as the first element, like this:

     (MACRO-NAME MACRO-ARGS ...)

   In Lisp-like languages, the traditional way to define macros is very
similar to procedure definitions.  The key differences are that the
macro definition body should return a list that describes the
transformed expression, and that the definition is marked as a macro
definition (rather than a procedure definition) by the use of a
different definition keyword: in Lisp, `defmacro' rather than `defun',
and in Scheme, `define-macro' rather than `define'.

   Guile supports this style of macro definition using both `defmacro'
and `define-macro'.  The only difference between them is how the macro
name and arguments are grouped together in the definition:

     (defmacro NAME (ARGS ...) BODY ...)

is the same as

     (define-macro (NAME ARGS ...) BODY ...)

The difference is analogous to the corresponding difference between
Lisp's `defun' and Scheme's `define'.

   `false-if-exception', from the `boot-9.scm' file in the Guile
distribution, is a good example of macro definition using `defmacro':

     (defmacro false-if-exception (expr)
       `(catch #t
               (lambda () ,expr)
               (lambda args #f)))

The effect of this definition is that expressions beginning with the
identifier `false-if-exception' are automatically transformed into a
`catch' expression following the macro definition specification.  For
example:

     (false-if-exception (open-input-file "may-not-exist"))
     ==
     (catch #t
            (lambda () (open-input-file "may-not-exist"))
            (lambda args #f))


File: guile.info,  Node: Syntax Rules,  Next: Syntax Case,  Prev: Macros,  Up: Procedures and Macros

The R5RS `syntax-rules' System
==============================

   R5RS defines an alternative system for macro and syntax
transformations using the keywords `define-syntax', `let-syntax',
`letrec-syntax' and `syntax-rules'.

   The main difference between the R5RS system and the traditional
macros of the previous section is how the transformation is specified.
In R5RS, rather than permitting a macro definition to return an
arbitrary expression, the transformation is specified in a pattern
language that

   * does not require complicated quoting and extraction of components
     of the source expression using `caddr' etc.

   * is designed such that the bindings associated with identifiers in
     the transformed expression are well defined, and such that it is
     impossible for the transformed expression to construct new
     identifiers.

The last point is commonly referred to as being "hygienic": the R5RS
`syntax-case' system provides "hygienic macros".

   For example, the R5RS pattern language for the `false-if-exception'
example of the previous section looks like this:

     (syntax-rules ()
       ((_ expr)
        (catch #t
               (lambda () expr)
               (lambda args #f))))

   In Guile, the `syntax-rules' system is provided by the `(ice-9
syncase)' module.  To make these facilities available in your code,
include the expression `(use-syntax (ice-9 syncase))' (*note Using
Guile Modules::) before the first usage of `define-syntax' etc.  If you
are writing a Scheme module, you can alternatively include the form
`#:use-syntax (ice-9 syncase)' in your `define-module' declaration
(*note Creating Guile Modules::).

* Menu:

* Pattern Language::            The `syntax-rules' pattern language.
* Define-Syntax::               Top level syntax definitions.
* Let-Syntax::                  Local syntax definitions.


File: guile.info,  Node: Pattern Language,  Next: Define-Syntax,  Up: Syntax Rules

The `syntax-rules' Pattern Language
-----------------------------------


File: guile.info,  Node: Define-Syntax,  Next: Let-Syntax,  Prev: Pattern Language,  Up: Syntax Rules

Top Level Syntax Definitions
----------------------------

   define-syntax:  The gist is

   (define-syntax <keyword> <transformer-spec>)

   makes the <keyword> into a macro so that

   (<keyword> ...)

   expands at _compile_ or _read_ time (i.e. before any evaluation
begins) into some expression that is given by the <transformer-spec>.


File: guile.info,  Node: Let-Syntax,  Prev: Define-Syntax,  Up: Syntax Rules

Local Syntax Definitions
------------------------


File: guile.info,  Node: Syntax Case,  Next: Internal Macros,  Prev: Syntax Rules,  Up: Procedures and Macros

Support for the `syntax-case' System
====================================


File: guile.info,  Node: Internal Macros,  Prev: Syntax Case,  Up: Procedures and Macros

Internal Representation of Macros and Syntax
============================================

   Internally, Guile uses three different flavors of macros.  The three
flavors are called "acro" (or "syntax"), "macro" and "mmacro".

   Given the expression

     (foo ...)

with `foo' being some flavor of macro, one of the following things will
happen when the expression is evaluated.

   * When `foo' has been defined to be an "acro", the procedure used in
     the acro definition of `foo' is passed the whole expression and
     the current lexical environment, and whatever that procedure
     returns is the value of evaluating the expression.  You can think
     of this a procedure that receives its argument as an unevaluated
     expression.

   * When `foo' has been defined to be a "macro", the procedure used in
     the macro definition of `foo' is passed the whole expression and
     the current lexical environment, and whatever that procedure
     returns is evaluated again.  That is, the procedure should return
     a valid Scheme expression.

   * When `foo' has been defined to be a "mmacro", the procedure used
     in the mmacro definition of `foo' is passed the whole expression
     and the current lexical environment, and whatever that procedure
     returns replaces the original expression.  Evaluation then starts
     over from the new expression that has just been returned.

   The key difference between a "macro" and a "mmacro" is that the
expression returned by a "mmacro" procedure is remembered (or
"memoized") so that the expansion does not need to be done again next
time the containing code is evaluated.

   The primitives `procedure->syntax', `procedure->macro' and
`procedure->memoizing-macro' are used to construct acros, macros and
mmacros respectively.  However, if you do not have a very special
reason to use one of these primitives, you should avoid them: they are
very specific to Guile's current implementation and therefore likely to
change.  Use `defmacro', `define-macro' (*note Macros::) or
`define-syntax' (*note Syntax Rules::) instead.  (In low level terms,
`defmacro', `define-macro' and `define-syntax' are all implemented as
mmacros.)

 - Scheme Procedure: procedure->syntax code
 - C Function: scm_makacro (code)
     Return a macro which, when a symbol defined to this value appears
     as the first symbol in an expression, returns the result of
     applying CODE to the expression and the environment.

 - Scheme Procedure: procedure->macro code
 - C Function: scm_makmacro (code)
     Return a macro which, when a symbol defined to this value appears
     as the first symbol in an expression, evaluates the result of
     applying CODE to the expression and the environment.  For example:

          (define trace
            (procedure->macro
              (lambda (x env)
                `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
          
          (trace foo)
          ==
          (set! foo (tracef foo 'foo)).

 - Scheme Procedure: procedure->memoizing-macro code
 - C Function: scm_makmmacro (code)
     Return a macro which, when a symbol defined to this value appears
     as the first symbol in an expression, evaluates the result of
     applying CODE to the expression and the environment.
     `procedure->memoizing-macro' is the same as `procedure->macro',
     except that the expression returned by CODE replaces the original
     macro expression in the memoized form of the containing code.

   In the following primitives, "acro" flavor macros are referred to as
"syntax transformers".

 - Scheme Procedure: macro? obj
 - C Function: scm_macro_p (obj)
     Return `#t' if OBJ is a regular macro, a memoizing macro or a
     syntax transformer.

 - Scheme Procedure: macro-type m
 - C Function: scm_macro_type (m)
     Return one of the symbols `syntax', `macro' or `macro!', depending
     on whether M is a syntax transformer, a regular macro, or a
     memoizing macro, respectively.  If M is not a macro, `#f' is
     returned.

 - Scheme Procedure: macro-name m
 - C Function: scm_macro_name (m)
     Return the name of the macro M.

 - Scheme Procedure: macro-transformer m
 - C Function: scm_macro_transformer (m)
     Return the transformer of the macro M.

 - Scheme Procedure: cons-source xorig x y
 - C Function: scm_cons_source (xorig, x, y)
     Create and return a new pair whose car and cdr are X and Y.  Any
     source properties associated with XORIG are also associated with
     the new pair.


File: guile.info,  Node: Utility Functions,  Next: Binding Constructs,  Prev: Procedures and Macros,  Up: Top

General Utility Functions
*************************

   This chapter contains information about procedures which are not
cleanly tied to a specific data type.  Because of their wide range of
applications, they are collected in a "utility" chapter.

* Menu:

* Equality::                    When are two values `the same'?
* Object Properties::           A modern interface to object properties.
* Sorting::                     Sort utility procedures.
* Copying::                     Copying deep structures.
* General Conversion::          Converting objects to strings.
* Hooks::                       User-customizable event lists.


File: guile.info,  Node: Equality,  Next: Object Properties,  Up: Utility Functions

Equality
========

   Three different kinds of "sameness" are defined in Scheme.

   * Two values can refer to exactly the same object.

   * Two objects can have the same "value".

   * Two objects can be structurally equivalent.

   The differentiation between these three kinds is important, because
determining whether two values are the same objects is very efficient,
while determining structural equivalence can be quite expensive
(consider comparing two very long lists).  Therefore, three different
procedures for testing for equality are provided, which correspond to
the three kinds of "sameness" defined above.

 - Scheme Procedure: eq? x y
     Return `#t' iff X references the same object as Y.  `eq?' is
     similar to `eqv?' except that in some cases it is capable of
     discerning distinctions finer than those detectable by `eqv?'.

 - Scheme Procedure: eqv? x y
     The `eqv?' procedure defines a useful equivalence relation on
     objects.  Briefly, it returns `#t' if X and Y should normally be
     regarded as the same object.  This relation is left slightly open
     to interpretation, but works for comparing immediate integers,
     characters, and inexact numbers.

 - Scheme Procedure: equal? x y
     Return `#t' iff X and Y are recursively `eqv?' equivalent.
     `equal?' recursively compares the contents of pairs, vectors, and
     strings, applying `eqv?' on other objects such as numbers and
     symbols.  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.


File: guile.info,  Node: Object Properties,  Next: Sorting,  Prev: Equality,  Up: Utility Functions

Object Properties
=================

   It's often useful to associate a piece of additional information
with a Scheme object even though that object does not have a dedicated
slot available in which the additional information could be stored.
Object properties allow you to do just that.

   An object property is most commonly used to associate one kind of
additional information with each instance of a class of similar Scheme
objects.  For example, all procedures have a `name' property, which
stores the name of the variable in which the procedure was stored by a
`define' expression, or `#f' if the procedure wasn't created by that
kind of expression.

   Guile's representation of an object property is a
procedure-with-setter (*note Procedures with Setters::) that can be
used with the generalized form of `set!' (REFFIXME) to set and retrieve
that property for any Scheme object.  So, setting a property looks like
this:

     (set! (my-property obj1) value-for-obj1)
     (set! (my-property obj2) value-for-obj2)

And retrieving values of the same property looks like this:

     (my-property obj1)
     =>
     value-for-obj1
     
     (my-property obj2)
     =>
     value-for-obj2

   To create an object property in the first place, use the
`make-object-property' procedure:

     (define my-property (make-object-property))

 - Scheme Procedure: make-object-property
     Create and return an object property.  An object property is a
     procedure-with-setter that can be called in two ways.  `(set!
     (PROPERTY OBJ) VAL)' sets OBJ's PROPERTY to VAL.  `(PROPERTY OBJ)'
     returns the current setting of OBJ's PROPERTY.

   A single object property created by `make-object-property' can
associate distinct property values with all Scheme values that are
distinguishable by `eq?' (including, for example, integers).

   Internally, object properties are implemented using a weak key hash
table.  This means that, as long as a Scheme value with property values
is protected from garbage collection, its property values are also
protected.  When the Scheme value is collected, its entry in the
property table is removed and so the (ex-) property values are no longer
protected by the table.

* Menu:

* Property Primitives::         Low level property implementation.
* Old-fashioned Properties::    An older approach to properties.


File: guile.info,  Node: Property Primitives,  Next: Old-fashioned Properties,  Up: Object Properties

Low Level Property Implementation.
----------------------------------

 - Scheme Procedure: primitive-make-property not_found_proc
 - C Function: scm_primitive_make_property (not_found_proc)
     Create a "property token" that can be used with
     `primitive-property-ref' and `primitive-property-set!'.  See
     `primitive-property-ref' for the significance of NOT_FOUND_PROC.

 - Scheme Procedure: primitive-property-ref prop obj
 - C Function: scm_primitive_property_ref (prop, obj)
     Return the property PROP of OBJ.  When no value has yet been
     associated with PROP and OBJ, call NOT-FOUND-PROC instead (see
     `primitive-make-property') and use its return value.  That value
     is also associated with OBJ via `primitive-property-set!'.  When
     NOT-FOUND-PROC is `#f', use `#f' as the default value of PROP.

 - Scheme Procedure: primitive-property-set! prop obj val
 - C Function: scm_primitive_property_set_x (prop, obj, val)
     Associate CODE with PROP and OBJ.

 - Scheme Procedure: primitive-property-del! prop obj
 - C Function: scm_primitive_property_del_x (prop, obj)
     Remove any value associated with PROP and OBJ.


File: guile.info,  Node: Old-fashioned Properties,  Prev: Property Primitives,  Up: Object Properties

An Older Approach to Properties
-------------------------------

   Traditionally, Lisp systems provide a different object property
interface to that provided by `make-object-property', in which the
object property that is being set or retrieved is indicated by a symbol.

   Guile includes this older kind of interface as well, but it may well
be removed in a future release, as it is less powerful than
`make-object-property' and so increases the size of the Guile library
for no benefit.  (And it is trivial to write a compatibility layer in
Scheme.)

 - Scheme Procedure: object-properties obj
 - C Function: scm_object_properties (obj)
     Return OBJ's property list.

 - Scheme Procedure: set-object-properties! obj alist
 - C Function: scm_set_object_properties_x (obj, alist)
     Set OBJ's property list to ALIST.

 - Scheme Procedure: object-property obj key
 - C Function: scm_object_property (obj, key)
     Return the property of OBJ with name KEY.

 - Scheme Procedure: set-object-property! obj key value
 - C Function: scm_set_object_property_x (obj, key, value)
     In OBJ's property list, set the property named KEY to VALUE.


File: guile.info,  Node: Sorting,  Next: Copying,  Prev: Object Properties,  Up: Utility Functions

Sorting
=======

   Sorting is very important in computer programs.  Therefore, Guile
comes with several sorting procedures built-in.  As always, procedures
with names ending in `!' are side-effecting, that means that they may
modify their parameters in order to produce their results.

   The first group of procedures can be used to merge two lists (which
must be already sorted on their own) and produce sorted lists containing
all elements of the input lists.

 - Scheme Procedure: merge alist blist less
 - C Function: scm_merge (alist, blist, less)
     Merge two already sorted lists into one.  Given two lists ALIST
     and BLIST, such that `(sorted? alist less?)' and `(sorted? blist
     less?)', return a new list in which the elements of ALIST and
     BLIST have been stably interleaved so that `(sorted? (merge alist
     blist less?) less?)'.  Note:  this does _not_ accept vectors.

 - Scheme Procedure: merge! alist blist less
 - C Function: scm_merge_x (alist, blist, less)
     Takes two lists ALIST and BLIST such that `(sorted? alist less?)'
     and `(sorted? blist less?)' and returns a new list in which the
     elements of ALIST and BLIST have been stably interleaved so that
     `(sorted? (merge alist blist less?) less?)'.  This is the
     destructive variant of `merge' Note:  this does _not_ accept
     vectors.

   The following procedures can operate on sequences which are either
vectors or list.  According to the given arguments, they return sorted
vectors or lists, respectively.  The first of the following procedures
determines whether a sequence is already sorted, the other sort a given
sequence.  The variants with names starting with `stable-' are special
in that they maintain a special property of the input sequences: If two
or more elements are the same according to the comparison predicate,
they are left in the same order as they appeared in the input.

 - Scheme Procedure: sorted? items less
 - C Function: scm_sorted_p (items, less)
     Return `#t' iff ITEMS is a list or a vector such that for all 1 <=
     i <= m, the predicate LESS returns true when applied to all
     elements i - 1 and i

 - Scheme Procedure: sort items less
 - C Function: scm_sort (items, less)
     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
     used for comparing the sequence elements.  This is not a stable
     sort.

 - Scheme Procedure: sort! items less
 - C Function: scm_sort_x (items, less)
     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
     used for comparing the sequence elements.  The sorting is
     destructive, that means that the input sequence is modified to
     produce the sorted result.  This is not a stable sort.

 - Scheme Procedure: stable-sort items less
 - C Function: scm_stable_sort (items, less)
     Sort the sequence ITEMS, which may be a list or a vector. LESS is
     used for comparing the sequence elements.  This is a stable sort.

 - Scheme Procedure: stable-sort! items less
 - C Function: scm_stable_sort_x (items, less)
     Sort the sequence ITEMS, which may be a list or a vector. LESS is
     used for comparing the sequence elements.  The sorting is
     destructive, that means that the input sequence is modified to
     produce the sorted result.  This is a stable sort.

   The procedures in the last group only accept lists or vectors as
input, as their names indicate.

 - Scheme Procedure: sort-list items less
 - C Function: scm_sort_list (items, less)
     Sort the list ITEMS, using LESS for comparing the list elements.
     This is a stable sort.

 - Scheme Procedure: sort-list! items less
 - C Function: scm_sort_list_x (items, less)
     Sort the list ITEMS, using LESS for comparing the list elements.
     The sorting is destructive, that means that the input list is
     modified to produce the sorted result.  This is a stable sort.

 - Scheme Procedure: restricted-vector-sort! vec less startpos endpos
 - C Function: scm_restricted_vector_sort_x (vec, less, startpos,
          endpos)
     Sort the vector VEC, using LESS for comparing the vector elements.
     STARTPOS and ENDPOS delimit the range of the vector which gets
     sorted.  The return value is not specified.


File: guile.info,  Node: Copying,  Next: General Conversion,  Prev: Sorting,  Up: Utility Functions

Copying Deep Structures
=======================

   The procedures for copying lists (*note Lists::) only produce a flat
copy of the input list, and currently Guile does not even contain
procedures for copying vectors.  `copy-tree' can be used for these
application, as it does not only copy the spine of a list, but also
copies any pairs in the cars of the input lists.

 - Scheme Procedure: copy-tree obj
 - C Function: scm_copy_tree (obj)
     Recursively copy the data tree that is bound to OBJ, and return a
     pointer to the new data structure.  `copy-tree' recurses down the
     contents of both pairs and vectors (since both cons cells and
     vector cells may point to arbitrary objects), and stops recursing
     when it hits any other object.


File: guile.info,  Node: General Conversion,  Next: Hooks,  Prev: Copying,  Up: Utility Functions

General String Conversion
=========================

   When debugging Scheme programs, but also for providing a
human-friendly interface, a procedure for converting any Scheme object
into string format is very useful.  Conversion from/to strings can of
course be done with specialized procedures when the data type of the
object to convert is known, but with this procedure, it is often more
comfortable.

   `object->string' converts an object by using a print procedure for
writing to a string port, and then returning the resulting string.
Converting an object back from the string is only possible if the object
type has a read syntax and the read syntax is preserved by the printing
procedure.

 - Scheme Procedure: object->string obj [printer]
 - C Function: scm_object_to_string (obj, printer)
     Return a Scheme string obtained by printing OBJ.  Printing
     function can be specified by the optional second argument PRINTER
     (default: `write').


File: guile.info,  Node: Hooks,  Prev: General Conversion,  Up: Utility Functions

Hooks
=====

   A hook is a list of procedures to be called at well defined points in
time.  Typically, an application provides a hook H and promises its
users that it will call all of the procedures in H at a defined point
in the application's processing.  By adding its own procedure to H, an
application user can tap into or even influence the progress of the
application.

   Guile itself provides several such hooks for debugging and
customization purposes: these are listed in a subsection below.

   When an application first creates a hook, it needs to know how many
arguments will be passed to the hook's procedures when the hook is run.
The chosen number of arguments (which may be none) is declared when the
hook is created, and all the procedures that are added to that hook must
be capable of accepting that number of arguments.

   A hook is created using `make-hook'.  A procedure can be added to or
removed from a hook using `add-hook!' or `remove-hook!', and all of a
hook's procedures can be removed together using `reset-hook!'.  When an
application wants to run a hook, it does so using `run-hook'.

* Menu:

* Hook Example::                Hook usage by example.
* Hook Reference::              Reference of all hook procedures.
* C Hooks::                     Hooks for use from C code.
* Guile Hooks::                 Hooks provided by Guile.


File: guile.info,  Node: Hook Example,  Next: Hook Reference,  Up: Hooks

Hook Usage by Example
---------------------

   Hook usage is shown by some examples in this section.  First, we will
define a hook of arity 2 -- that is, the procedures stored in the hook
will have to accept two arguments.

     (define hook (make-hook 2))
     hook
     => #<hook 2 40286c90>

   Now we are ready to add some procedures to the newly created hook
with `add-hook!'.  In the following example, two procedures are added,
which print different messages and do different things with their
arguments.

     (add-hook! hook (lambda (x y)
                         (display "Foo: ")
                         (display (+ x y))
                         (newline)))
     (add-hook! hook (lambda (x y)
                         (display "Bar: ")
                         (display (* x y))
                         (newline)))

   Once the procedures have been added, we can invoke the hook using
`run-hook'.

     (run-hook hook 3 4)
     -| Bar: 12
     -| Foo: 7

   Note that the procedures are called in the reverse of the order with
which they were added.  This is because the default behaviour of
`add-hook!' is to add its procedure to the _front_ of the hook's
procedure list.  You can force `add-hook!' to add its procedure to the
_end_ of the list instead by providing a third `#t' argument on the
second call to `add-hook!'.

     (add-hook! hook (lambda (x y)
                         (display "Foo: ")
                         (display (+ x y))
                         (newline)))
     (add-hook! hook (lambda (x y)
                         (display "Bar: ")
                         (display (* x y))
                         (newline))
                         #t)             ; <- Change here!
     
     (run-hook hook 3 4)
     -| Foo: 7
     -| Bar: 12


File: guile.info,  Node: Hook Reference,  Next: C Hooks,  Prev: Hook Example,  Up: Hooks

Hook Reference
--------------

   When you create a hook with `make-hook', you must specify the arity
of the procedures which can be added to the hook.  If the arity is not
given explicitly as an argument to `make-hook', it defaults to zero.
All procedures of a given hook must have the same arity, and when the
procedures are invoked using `run-hook', the number of arguments passed
must match the arity specified at hook creation time.

   The order in which procedures are added to a hook matters.  If the
third parameter to `add-hook!' is omitted or is equal to `#f', the
procedure is added in front of the procedures which might already be on
that hook, otherwise the procedure is added at the end.  The procedures
are always called from the front to the end of the list when they are
invoked via `run-hook'.

   The ordering of the list of procedures returned by `hook->list'
matches the order in which those procedures would be called if the hook
was run using `run-hook'.

   Note that the C functions in the following entries are for handling
"Scheme-level" hooks in C.  There are also "C-level" hooks which have
their own interface (*note C Hooks::).

 - Scheme Procedure: make-hook [n_args]
 - C Function: scm_make_hook (n_args)
     Create a hook for storing procedure of arity N_ARGS.  N_ARGS
     defaults to zero.  The returned value is a hook object to be used
     with the other hook procedures.

 - Scheme Procedure: hook? x
 - C Function: scm_hook_p (x)
     Return `#t' if X is a hook, `#f' otherwise.

 - Scheme Procedure: hook-empty? hook
 - C Function: scm_hook_empty_p (hook)
     Return `#t' if HOOK is an empty hook, `#f' otherwise.

 - Scheme Procedure: add-hook! hook proc [append_p]
 - C Function: scm_add_hook_x (hook, proc, append_p)
     Add the procedure PROC to the hook HOOK. The procedure is added to
     the end if APPEND_P is true, otherwise it is added to the front.
     The return value of this procedure is not specified.

 - Scheme Procedure: remove-hook! hook proc
 - C Function: scm_remove_hook_x (hook, proc)
     Remove the procedure PROC from the hook HOOK.  The return value of
     this procedure is not specified.

 - Scheme Procedure: reset-hook! hook
 - C Function: scm_reset_hook_x (hook)
     Remove all procedures from the hook HOOK.  The return value of
     this procedure is not specified.

 - Scheme Procedure: hook->list hook
 - C Function: scm_hook_to_list (hook)
     Convert the procedure list of HOOK to a list.

 - Scheme Procedure: run-hook hook . args
 - C Function: scm_run_hook (hook, args)
     Apply all procedures from the hook HOOK to the arguments ARGS.
     The order of the procedure application is first to last.  The
     return value of this procedure is not specified.

   If, in C code, you are certain that you have a hook object and well
formed argument list for that hook, you can also use `scm_c_run_hook',
which is identical to `scm_run_hook' but does no type checking.

 - C Function: void scm_c_run_hook (SCM hook, SCM args)
     The same as `scm_run_hook' but without any type checking to confirm
     that HOOK is actually a hook object and that ARGS is a well-formed
     list matching the arity of the hook.

   For C code, `SCM_HOOKP' is a faster alternative to `scm_hook_p':

 - C Macro: int SCM_HOOKP (x)
     Return 1 if X is a Scheme-level hook, 0 otherwise.

Handling Scheme-level hooks from C code
---------------------------------------

   Here is an example of how to handle Scheme-level hooks from C code
using the above functions.

     if (SCM_NFALSEP (scm_hook_p (obj)))
       /* handle Scheme-level hook using C functions */
       scm_reset_hook_x (obj);
     else
       /* do something else (obj is not a hook) */


File: guile.info,  Node: C Hooks,  Next: Guile Hooks,  Prev: Hook Reference,  Up: Hooks

Hooks For C Code.
-----------------

   The hooks already described are intended to be populated by
Scheme-level procedures.  In addition to this, the Guile library
provides an independent set of interfaces for the creation and
manipulation of hooks that are designed to be populated by functions
implemented in C.

   The original motivation here was to provide a kind of hook that could
safely be invoked at various points during garbage collection.
Scheme-level hooks are unsuitable for this purpose as running them could
itself require memory allocation, which would then invoke garbage
collection recursively ...  However, it is also the case that these
hooks are easier to work with than the Scheme-level ones if you only
want to register C functions with them.  So if that is mainly what your
code needs to do, you may prefer to use this interface.

   To create a C hook, you should allocate storage for a structure of
type `scm_t_c_hook' and then initialize it using `scm_c_hook_init'.

 - C Type: scm_t_c_hook
     Data type for a C hook.  The internals of this type should be
     treated as opaque.

 - C Enum: scm_t_c_hook_type
     Enumeration of possible hook types, which are:

    `SCM_C_HOOK_NORMAL'
          Type of hook for which all the registered functions will
          always be called.

    `SCM_C_HOOK_OR'
          Type of hook for which the sequence of registered functions
          will be called only until one of them returns C true (a
          non-NULL pointer).

    `SCM_C_HOOK_AND'
          Type of hook for which the sequence of registered functions
          will be called only until one of them returns C false (a NULL
          pointer).

 - C Function: void scm_c_hook_init (scm_t_c_hook *hook, void
          *hook_data, scm_t_c_hook_type type)
     Initialize the C hook at memory pointed to by HOOK.  TYPE should
     be one of the values of the `scm_t_c_hook_type' enumeration, and
     controls how the hook functions will be called.  HOOK_DATA is a
     closure parameter that will be passed to all registered hook
     functions when they are called.

   To add or remove a C function from a C hook, use `scm_c_hook_add' or
`scm_c_hook_remove'.  A hook function must expect three `void *'
parameters which are, respectively:

HOOK_DATA
     The hook closure data that was specified at the time the hook was
     initialized by `scm_c_hook_init'.

FUNC_DATA
     The function closure data that was specified at the time that that
     function was registered with the hook by `scm_c_hook_add'.

DATA
     The call closure data specified by the `scm_c_hook_run' call that
     runs the hook.

 - C Type: scm_t_c_hook_function
     Function type for a C hook function: takes three `void *'
     parameters and returns a `void *' result.

 - C Function: void scm_c_hook_add (scm_t_c_hook *hook,
          scm_t_c_hook_function func, void *func_data, int appendp)
     Add function FUNC, with function closure data FUNC_DATA, to the C
     hook HOOK.  The new function is appended to the hook's list of
     functions if APPENDP is non-zero, otherwise prepended.

 - C Function: void scm_c_hook_remove (scm_t_c_hook *hook,
          scm_t_c_hook_function func, void *func_data)
     Remove function FUNC, with function closure data FUNC_DATA, from
     the C hook HOOK.  `scm_c_hook_remove' checks both FUNC and
     FUNC_DATA so as to allow for the same FUNC being registered
     multiple times with different closure data.

   Finally, to invoke a C hook, call the `scm_c_hook_run' function
specifying the hook and the call closure data for this run:

 - C Function: void * scm_c_hook_run (scm_t_c_hook *hook, void *data)
     Run the C hook HOOK will call closure data DATA.  Subject to the
     variations for hook types `SCM_C_HOOK_OR' and `SCM_C_HOOK_AND',
     `scm_c_hook_run' calls HOOK's registered functions in turn,
     passing them the hook's closure data, each function's closure
     data, and the call closure data.

     `scm_c_hook_run''s return value is the return value of the last
     function to be called.


File: guile.info,  Node: Guile Hooks,  Prev: C Hooks,  Up: Hooks

Hooks Provided by Guile
-----------------------

* Menu:

* GC Hooks::                    Garbage collection hooks.
* REPL Hooks::                  Hooks into the Guile REPL.


File: guile.info,  Node: GC Hooks,  Next: REPL Hooks,  Up: Guile Hooks

Hooks for Garbage Collection
............................

   Whenever Guile performs a garbage collection, it calls the following
hooks in the order shown.

 - C Hook: scm_before_gc_c_hook
     C hook called at the very start of a garbage collection, after
     setting `scm_gc_running_p' to 1, but before entering the GC
     critical section.

     If garbage collection is blocked because `scm_block_gc' is
     non-zero, GC exits early soon after calling this hook, and no
     further hooks will be called.

 - C Hook: scm_before_mark_c_hook
     C hook called before beginning the mark phase of garbage
     collection, after the GC thread has entered a critical section.

 - C Hook: scm_before_sweep_c_hook
     C hook called before beginning the sweep phase of garbage
     collection.  This is the same as at the end of the mark phase,
     since nothing else happens between marking and sweeping.

 - C Hook: scm_after_sweep_c_hook
     C hook called after the end of the sweep phase of garbage
     collection, but while the GC thread is still inside its critical
     section.

 - C Hook: scm_after_gc_c_hook
     C hook called at the very end of a garbage collection, after the GC
     thread has left its critical section.

 - Scheme Hook: after-gc-hook
     Scheme hook with arity 0.  This hook is run asynchronously (*note
     Asyncs::) soon after the GC has completed and any other events
     that were deferred during garbage collection have been processed.
     (Also accessible from C with the name `scm_after_gc_hook'.)

   All the C hooks listed here have type `SCM_C_HOOK_NORMAL', are
initialized with hook closure data NULL, are are invoked by
`scm_c_hook_run' with call closure data NULL.

   The Scheme hook `after-gc-hook' is particularly useful in
conjunction with guardians (*note Guardians::).  Typically, if you are
using a guardian, you want to call the guardian after garbage collection
to see if any of the objects added to the guardian have been collected.
By adding a thunk that performs this call to `after-gc-hook', you can
ensure that your guardian is tested after every garbage collection
cycle.


File: guile.info,  Node: REPL Hooks,  Prev: GC Hooks,  Up: Guile Hooks

Hooks into the Guile REPL
.........................


File: guile.info,  Node: Binding Constructs,  Next: Control Mechanisms,  Prev: Utility Functions,  Up: Top

Definitions and Variable Bindings
*********************************

   Scheme supports the definition of variables in different contexts.
Variables can be defined at the top level, so that they are visible in
the entire program, and variables can be defined locally to procedures
and expressions.  This is important for modularity and data abstraction.

* Menu:

* Top Level::                   Top level variable definitions.
* Local Bindings::              Local variable bindings.
* Internal Definitions::        Internal definitions.
* Binding Reflection::          Querying variable bindings.


File: guile.info,  Node: Top Level,  Next: Local Bindings,  Up: Binding Constructs

Top Level Variable Definitions
==============================

   On the top level of a program (i.e. when not inside the body of a
procedure definition or a `let', `let*' or `letrec' expression), a
definition of the form

     (define a VALUE)

defines a variable called `a' and sets it to the value VALUE.

   If the variable already exists, because it has already been created
by a previous `define' expression with the same name, its value is
simply changed to the new VALUE.  In this case, then, the above form is
completely equivalent to

     (set! a VALUE)

This equivalence means that `define' can be used interchangeably with
`set!' to change the value of variables at the top level of the REPL or
a Scheme source file.  It is useful during interactive development when
reloading a Scheme file that you have modified, because it allows the
`define' expressions in that file to work as expected both the first
time that the file is loaded and on subsequent occasions.

   Note, though, that `define' and `set!' are not always equivalent.
For example, a `set!' is not allowed if the named variable does not
already exist, and the two expressions can behave differently in the
case where there are imported variables visible from another module.

 - Scheme Syntax: define name value
     Create a top level variable named NAME with value VALUE.  If the
     named variable already exists, just change its value.  The return
     value of a `define' expression is unspecified.

   The C API equivalents of `define' are `scm_define' and
`scm_c_define', which differ from each other in whether the variable
name is specified as a `SCM' symbol or as a null-terminated C string.

 - C Function: scm_define (sym, value)
 - C Function: scm_c_define (const char *name, value)
     C equivalents of `define', with variable name specified either by
     SYM, a symbol, or by NAME, a null-terminated C string.  Both
     variants return the new or preexisting variable object.

   `define' (when it occurs at top level), `scm_define' and
`scm_c_define' all create or set the value of a variable in the top
level environment of the current module.  If there was not already a
variable with the specified name belonging to the current module, but a
similarly named variable from another module was visible through having
been imported, the newly created variable in the current module will
shadow the imported variable, such that the imported variable is no
longer visible.

   Attention: Scheme definitions inside local binding constructs (*note
Local Bindings::) act differently (*note Internal Definitions::).


File: guile.info,  Node: Local Bindings,  Next: Internal Definitions,  Prev: Top Level,  Up: Binding Constructs

Local Variable Bindings
=======================

   As opposed to definitions at the top level, which are visible in the
whole program (or current module, when Guile modules are used), it is
also possible to define variables which are only visible in a
well-defined part of the program.  Normally, this part of a program
will be a procedure or a subexpression of a procedure.

   With the constructs for local binding (`let', `let*' and `letrec'),
the Scheme language has a block structure like most other programming
languages since the days of ALGOL 60.  Readers familiar to languages
like C or Java should already be used to this concept, but the family
of `let' expressions has a few properties which are well worth knowing.

   The first local binding construct is `let'.  The other constructs
`let*' and `letrec' are specialized versions for usage where using
plain `let' is a bit inconvenient.

 - syntax: let bindings body
     BINDINGS has the form

          ((VARIABLE1 INIT1) ...)

     that is zero or more two-element lists of a variable and an
     arbitrary expression each.  All VARIABLE names must be distinct.

     A `let' expression is evaluated as follows.

        * All INIT expressions are evaluated.

        * New storage is allocated for the VARIABLES.

        * The values of the INIT expressions are stored into the
          variables.

        * The expressions in BODY are evaluated in order, and the value
          of the last expression is returned as the value of the `let'
          expression.

        * The storage for the VARIABLES is freed.

     The INIT expressions are not allowed to refer to any of the
     VARIABLES.

 - syntax: let* bindings body
     Similar to `let', but the variable bindings are performed
     sequentially, that means that all INIT expression are allowed to
     use the variables defined on their left in the binding list.

     A `let*' expression can always be expressed with nested `let'
     expressions.

          (let* ((a 1) (b a))
             b)
          ==
          (let ((a 1))
            (let ((b a))
              b))

 - syntax: letrec bindings body
     Similar to `let', but it is possible to refer to the VARIABLE from
     lambda expression created in any of the INITS.  That is,
     procedures created in the INIT expression can recursively refer to
     the defined variables.

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

   There is also an alternative form of the `let' form, which is used
for expressing iteration.  Because of the use as a looping construct,
this form (the "named let") is documented in the section about
iteration (*note Iteration: while do.)


File: guile.info,  Node: Internal Definitions,  Next: Binding Reflection,  Prev: Local Bindings,  Up: Binding Constructs

Internal definitions
====================

   A `define' form which appears inside the body of a `lambda', `let',
`let*', `letrec' or equivalent expression is called an "internal
definition".  An internal definition differs from a top level
definition (*note Top Level::), because the definition is only visible
inside the complete body of the enclosing form.  Let us examine the
following example.

     (let ((frumble "froz"))
        (define banana (lambda () (apple 'peach)))
        (define apple (lambda (x) x))
        (banana))
     =>
     peach

   Here the enclosing form is a `let', so the `define's in the
`let'-body are internal definitions.  Because the scope of the internal
definitions is the *complete* body of the `let'-expression, the
`lambda'-expression which gets bound to the variable `banana' may refer
to the variable `apple', even though it's definition appears lexically
_after_ the definition of `banana'.  This is because a sequence of
internal definition acts as if it were a `letrec' expression.

     (let ()
       (define a 1)
       (define b 2)
       (+ a b))

is equivalent to

     (let ()
       (letrec ((a 1) (b 2))
         (+ a b)))

   Another noteworthy difference to top level definitions is that within
one group of internal definitions all variable names must be distinct.
That means where on the top level a second define for a given variable
acts like a `set!', an exception is thrown for internal definitions
with duplicate bindings.


File: guile.info,  Node: Binding Reflection,  Prev: Internal Definitions,  Up: Binding Constructs

Querying variable bindings
==========================

   Guile provides a procedure for checking whether a symbol is bound in
the top level environment.

 - Scheme Procedure: defined? sym [env]
 - C Function: scm_definedp (sym, env)
     Return `#t' if SYM is defined in the lexical environment ENV.
     When ENV is not specified, look in the top-level environment as
     defined by the current module.


File: guile.info,  Node: Control Mechanisms,  Next: Input and Output,  Prev: Binding Constructs,  Up: Top

Controlling the Flow of Program Execution
*****************************************

* Menu:

* begin::                       Evaluating a sequence of expressions.
* if cond case::                Simple conditional evaluation.
* and or::                      Conditional evaluation of a sequence.
* while do::                    Iteration mechanisms.
* Continuations::               Continuations.
* Multiple Values::             Returning and accepting multiple values.
* Exceptions::                  Throwing and catching exceptions.
* Error Reporting::             Procedures for signaling errors.
* Dynamic Wind::                Guarding against non-local entrance/exit.
* Handling Errors::             How to handle errors in C code.


File: guile.info,  Node: begin,  Next: if cond case,  Up: Control Mechanisms

Evaluating a Sequence of Expressions
====================================

   `begin' is used for grouping several expression together so that
they syntactically are treated as if they were one expression.  This is
particularly important when syntactic expressions are used which only
allow one expression, but the programmer wants to use more than one
expression in that place.  As an example, consider the conditional
expression below:

     (if (> x 0)
         (begin (display "greater") (newline)))

   If the two calls to `display' and `newline' were not embedded in a
`begin'-statement, the call to `newline' would get misinterpreted as
the else-branch of the `if'-expression.

 - syntax: begin expr1 expr2 ...
     The expression(s) are evaluated in left-to-right order and the
     value of the last expression is returned as the value of the
     `begin'-expression.  This expression type is used when the
     expressions before the last one are evaluated for their side
     effects.


File: guile.info,  Node: if cond case,  Next: and or,  Prev: begin,  Up: Control Mechanisms

Simple Conditional Evaluation
=============================

   Guile provides three syntactic constructs for conditional evaluation.
`if' is the normal if-then-else expression (with an optional else
branch), `cond' is a conditional expression with multiple branches and
`case' branches if an expression has one of a set of constant values.

 - syntax: if test consequent [alternate]
     All arguments may be arbitrary expressions.  First, TEST is
     evaluated.  If it returns a true value, the expression CONSEQUENT
     is evaluated and ALTERNATE is ignored.  If TEST evaluates to `#f',
     ALTERNATE is evaluated instead.  The value of the evaluated branch
     (CONSEQUENT or ALTERNATE) is returned as the value of the `if'
     expression.

     When ALTERNATE is omitted and the TEST evaluates to `#f', the
     value of the expression is not specified.

 - syntax: cond clause1 clause2 ...
     Each `cond'-clause must look like this:

          (TEST EXPRESSION ...)

     where TEST and EXPRESSION are arbitrary expression, or like this

          (TEST => EXPRESSION

     where EXPRESSION must evaluate to a procedure.

     The TESTs of the clauses are evaluated in order and as soon as one
     of them evaluates to a true values, the corresponding EXPRESSIONs
     are evaluated in order and the last value is returned as the value
     of the `cond'-expression.  For the `=>' clause type, EXPRESSION is
     evaluated and the resulting procedure is applied to the value of
     TEST.  The result of this procedure application is then the result
     of the `cond'-expression.

     The TEST of the last CLAUSE may be the keyword `else'.  Then, if
     none of the preceding TESTs is true, the EXPRESSIONs following the
     `else' are evaluated to produce the result of the
     `cond'-expression.

 - syntax: case key clause1 clause2 ...
     KEY may be any expression, the CLAUSEs must have the form

          ((DATUM1 ...) EXPR1 EXPR2 ...)

     and the last CLAUSE may have the form

          (else EXPR1 EXPR2 ...)

     All DATUMs must be distinct.  First, KEY is evaluated.  The the
     result of this evaluation is compared against all DATUMs using
     `eqv?'.  When this comparison succeeds, the expression(s) following
     the DATUM are evaluated from left to right, returning the value of
     the last expression as the result of the `case' expression.

     If the KEY matches no DATUM and there is an `else'-clause, the
     expressions following the `else' are evaluated.  If there is no
     such clause, the result of the expression is unspecified.


File: guile.info,  Node: and or,  Next: while do,  Prev: if cond case,  Up: Control Mechanisms

Conditional Evaluation of a Sequence of Expressions
===================================================

   `and' and `or' evaluate all their arguments, similar to `begin', but
evaluation stops as soon as one of the expressions evaluates to false
or true, respectively.

 - syntax: and expr ...
     Evaluate the EXPRs from left to right and stop evaluation as soon
     as one expression evaluates to `#f'; the remaining expressions are
     not evaluated.  The value of the last evaluated expression is
     returned.  If no expression evaluates to `#f', the value of the
     last expression is returned.

     If used without expressions, `#t' is returned.

 - syntax: or expr ...
     Evaluate the EXPRs from left to right and stop evaluation as soon
     as one expression evaluates to a true value (that is, a value
     different from `#f'); the remaining expressions are not evaluated.
     The value of the last evaluated expression is returned.  If all
     expressions evaluate to `#f', `#f' is returned.

     If used without expressions, `#f' is returned.


File: guile.info,  Node: while do,  Next: Continuations,  Prev: and or,  Up: Control Mechanisms

Iteration mechanisms
====================

   Scheme has only few iteration mechanisms, mainly because iteration in
Scheme programs is normally expressed using recursion.  Nevertheless,
R5RS defines a construct for programming loops, calling `do'.  In
addition, Guile has an explicit looping syntax called `while'.

 - syntax: do ((variable1 init1 step1) ...) (test expr ...) command ...
     The INIT expressions are evaluated and the VARIABLES are bound to
     their values. Then looping starts with testing the TEST
     expression.  If TEST evaluates to a true value, the EXPR following
     the TEST are evaluated and the value of the last EXPR is returned
     as the value of the `do' expression.  If TEST evaluates to false,
     the COMMANDs are evaluated in order, the STEPs are evaluated and
     stored into the VARIABLES and the next iteration starts.

     Any of the STEP expressions may be omitted, so that the
     corresponding variable is not changed during looping.

 - syntax: while cond body ...
     Evaluate all expressions in BODY in order, as long as COND
     evaluates to a true value.  The COND expression is tested before
     every iteration, so that the body is not evaluated at all if COND
     is `#f' right from the start.

   Another very common way of expressing iteration in Scheme programs is
the use of the so-called "named let".

   Named let is a variant of `let' which creates a procedure and calls
it in one step.  Because of the newly created procedure, named let is
more powerful than `do'-it can be used for iteration, but also for
arbitrary recursion.

 - syntax: let variable bindings body
     For the definition of BINDINGS see the documentation about `let'
     (*note Local Bindings::).

     Named `let' works as follows:

        * A new procedure which accepts as many arguments as are in
          BINDINGS is created and bound locally (using `let') to
          VARIABLE.  The new procedure's formal argument names are the
          name of the VARIABLES.

        * The BODY expressions are inserted into the newly created
          procedure.

        * The procedure is called with the INIT expressions as the
          formal arguments.

     The next example implements a loop which iterates (by recursion)
     1000 times.

          (let lp ((x 1000))
            (if (positive? x)
                (lp (- x 1))
                x))
          =>
          0


File: guile.info,  Node: Continuations,  Next: Multiple Values,  Prev: while do,  Up: Control Mechanisms

Continuations
=============

   The ability to explicitly capture continuations using
`call-with-current-continuation' (also often called `call/cc' for
short), and to invoke such continuations later any number of times, and
from any other point in a program, provides maybe the most powerful
control structure known.  All other control structures, such as loops
and coroutines, can be emulated using continuations.

   The implementation of continuations in Guile is not as efficient as
one might hope, because it is constrained by the fact that Guile is
designed to cooperate with programs written in other languages, such as
C, which do not know about continuations.  So continuations should be
used when there is no other simple way of achieving the desired
behaviour, or where the advantages of the elegant continuation
mechanism outweigh the need for optimum performance.  If you find
yourself using `call/cc' for escape procedures and your program is
running too slow, you might want to use exceptions (*note Exceptions::)
instead.

 - Scheme Procedure: call-with-current-continuation proc
     Capture the current continuation and call PROC with the captured
     continuation as the single argument.  This continuation can then be
     called with arbitrarily many arguments.  Such a call will work
     like a goto to the invocation location of
     `call-with-current-continuation', passing the arguments in a way
     that they are returned by the call to
     `call-with-current-continuation'.  Since it is legal to store the
     captured continuation in a variable or to pass it to other
     procedures, it is possible that a procedure returns more than
     once, even if it is called only one time.  This can be confusing
     at times.

     (define kont #f)
     (call-with-current-continuation
       (lambda (k)
          (set! kont k)
          1))
     =>
     1
     
     (kont 2)
     =>
     2


File: guile.info,  Node: Multiple Values,  Next: Exceptions,  Prev: Continuations,  Up: Control Mechanisms

Returning and Accepting Multiple Values
=======================================

   Scheme allows a procedure to return more than one value to its
caller.  This is quite different to other languages which only allow
single-value returns.  Returning multiple values is different from
returning a list (or pair or vector) of values to the caller, because
conceptually not _one_ compound object is returned, but several
distinct values.

   The primitive procedures for handling multiple values are `values'
and `call-with-values'.  `values' is used for returning multiple values
from a procedure.  This is done by placing a call to `values' with zero
or more arguments in tail position in a procedure body.
`call-with-values' combines a procedure returning multiple values with
a procedure which accepts these values as parameters.

 - Scheme Procedure: values . args
 - C Function: scm_values (args)
     Delivers all of its arguments to its continuation.  Except for
     continuations created by the `call-with-values' procedure, all
     continuations take exactly one value.  The effect of passing no
     value or more than one value to continuations that were not
     created by `call-with-values' is unspecified.

 - Scheme Procedure: call-with-values producer consumer
     Calls its PRODUCER argument with no values and a continuation
     that, when passed some values, calls the CONSUMER procedure with
     those values as arguments.  The continuation for the call to
     CONSUMER is the continuation of the call to `call-with-values'.

          (call-with-values (lambda () (values 4 5))
                            (lambda (a b) b))
                                                       ==>  5

          (call-with-values * -)                             ==>  -1

   In addition to the fundamental procedures described above, Guile has
a module which exports a syntax called `receive', which is much more
convenient.  If you want to use it in your programs, you have to load
the module `(ice-9 receive)' with the statement

     (use-modules (ice-9 receive))

 - library syntax: receive formals expr body ...
     Evaluate the expression EXPR, and bind the result values (zero or
     more) to the formal arguments in the formal argument list FORMALS.
     FORMALS must have the same syntax like the formal argument list
     used in `lambda' (*note Lambda::).  After binding the variables,
     the expressions in BODY ... are evaluated in order.


File: guile.info,  Node: Exceptions,  Next: Error Reporting,  Prev: Multiple Values,  Up: Control Mechanisms

Exceptions
==========

   A common requirement in applications is to want to jump
"non-locally" from the depths of a computation back to, say, the
application's main processing loop.  Usually, the place that is the
target of the jump is somewhere in the calling stack of procedures that
called the procedure that wants to jump back.  For example, typical
logic for a key press driven application might look something like this:

     main-loop:
       read the next key press and call dispatch-key
     
     dispatch-key:
       lookup the key in a keymap and call an appropriate procedure,
       say find-file
     
     find-file:
       interactively read the required file name, then call
       find-specified-file
     
     find-specified-file:
       check whether file exists; if not, jump back to main-loop
       ...

   The jump back to `main-loop' could be achieved by returning through
the stack one procedure at a time, using the return value of each
procedure to indicate the error condition, but Guile (like most modern
programming languages) provides an additional mechanism called
"exception handling" that can be used to implement such jumps much more
conveniently.

* Menu:

* Exception Terminology::       Different ways to say the same thing.
* Catch::                       Setting up to catch exceptions.
* Throw::                       Throwing an exception.
* Lazy Catch::                  Catch without unwinding the stack.
* Exception Implementation::    How Guile implements exceptions.


File: guile.info,  Node: Exception Terminology,  Next: Catch,  Up: Exceptions

Exception Terminology
---------------------

   There are several variations on the terminology for dealing with
non-local jumps.  It is useful to be aware of them, and to realize that
they all refer to the same basic mechanism.

   * Actually making a non-local jump may be called "raising an
     exception", "raising a signal", "throwing an exception" or "doing
     a long jump".  When the jump indicates an error condition, people
     may talk about "signalling", "raising" or "throwing" "an error".

   * Handling the jump at its target may be referred to as "catching" or
     "handling" the "exception", "signal" or, where an error condition
     is involved, "error".

   Where "signal" and "signalling" are used, special care is needed to
avoid the risk of confusion with POSIX signals.  (Especially
considering that Guile handles POSIX signals by throwing a corresponding
kind of exception: REFFIXME.)

   This manual prefers to speak of throwing and catching exceptions,
since this terminology matches the corresponding Guile primitives.


File: guile.info,  Node: Catch,  Next: Throw,  Prev: Exception Terminology,  Up: Exceptions

Catching Exceptions
-------------------

   `catch' is used to set up a target for a possible non-local jump.
The arguments of a `catch' expression are a "key", which restricts the
set of exceptions to which this `catch' applies, a thunk that specifies
the "normal case" code -- i.e. what should happen if no exceptions are
thrown -- and a "handler" procedure that says what to do if an
exception is thrown.  Note that if the "normal case" thunk executes
"normally", which means without throwing any exceptions, the handler
procedure is not executed at all.

   When an exception is thrown using the `throw' primitive, the first
argument of the `throw' is a symbol that indicates the type of the
exception.  For example, Guile throws an exception using the symbol
`numerical-overflow' to indicate numerical overflow errors such as
division by zero:

     (/ 1 0)
     =>
     ABORT: (numerical-overflow)

   The KEY argument in a `catch' expression corresponds to this symbol.
KEY may be a specific symbol, such as `numerical-overflow', in which
case the `catch' applies specifically to exceptions of that type; or it
may be `#t', which means that the `catch' applies to all exceptions,
irrespective of their type.

   The second argument of a `catch' expression should be a thunk (i.e.
a procedure that accepts no arguments) that specifies the normal case
code.  The `catch' is active for the execution of this thunk, including
any code called directly or indirectly by the thunk's body.  Evaluation
of the `catch' expression activates the catch and then calls this thunk.

   The third argument of a `catch' expression is a handler procedure.
If an exception is thrown, this procedure is called with exactly the
arguments specified by the `throw'.  Therefore, the handler procedure
must be designed to accept a number of arguments that corresponds to
the number of arguments in all `throw' expressions that can be caught
by this `catch'.

 - Scheme Procedure: catch key thunk handler
 - C Function: scm_catch (key, thunk, handler)
     Invoke THUNK in the dynamic context of HANDLER for exceptions
     matching KEY.  If thunk throws to the symbol KEY, then HANDLER is
     invoked this way:
          (handler key args ...)

     KEY is a symbol or `#t'.

     THUNK takes no arguments.  If THUNK returns normally, that is the
     return value of `catch'.

     Handler is invoked outside the scope of its own `catch'.  If
     HANDLER again throws to the same key, a new handler from further
     up the call chain is invoked.

     If the key is `#t', then a throw to _any_ symbol will match this
     call to `catch'.

   If the handler procedure needs to match a variety of `throw'
expressions with varying numbers of arguments, you should write it like
this:

     (lambda (key . args)
       ...)

The KEY argument is guaranteed always to be present, because a `throw'
without a KEY is not valid.  The number and interpretation of the ARGS
varies from one type of exception to another, but should be specified
by the documentation for each exception type.

   Note that, once the handler procedure is invoked, the catch that led
to the handler procedure being called is no longer active.  Therefore,
if the handler procedure itself throws an exception, that exception can
only be caught by another active catch higher up the call stack, if
there is one.


File: guile.info,  Node: Throw,  Next: Lazy Catch,  Prev: Catch,  Up: Exceptions

Throwing Exceptions
-------------------

   The `throw' primitive is used to throw an exception.  One argument,
the KEY, is mandatory, and must be a symbol; it indicates the type of
exception that is being thrown.  Following the KEY, `throw' accepts any
number of additional arguments, whose meaning depends on the exception
type.  The documentation for each possible type of exception should
specify the additional arguments that are expected for that kind of
exception.

 - Scheme Procedure: throw key . args
 - C Function: scm_throw (key, args)
     Invoke the catch form matching KEY, passing ARGS to the HANDLER.

     KEY is a symbol.  It will match catches of the same symbol or of
     `#t'.

     If there is no handler at all, Guile prints an error and then
     exits.

   When an exception is thrown, it will be caught by the innermost
`catch' expression that applies to the type of the thrown exception; in
other words, the innermost `catch' whose KEY is `#t' or is the same
symbol as that used in the `throw' expression.  Once Guile has
identified the appropriate `catch', it handles the exception by
applying that `catch' expression's handler procedure to the arguments
of the `throw'.

   If there is no appropriate `catch' for a thrown exception, Guile
prints an error to the current error port indicating an uncaught
exception, and then exits.  In practice, it is quite difficult to
observe this behaviour, because Guile when used interactively installs a
top level `catch' handler that will catch all exceptions and print an
appropriate error message _without_ exiting.  For example, this is what
happens if you try to throw an unhandled exception in the standard
Guile REPL; note that Guile's command loop continues after the error
message:

     guile> (throw 'badex)
     <unnamed port>:3:1: In procedure gsubr-apply ...
     <unnamed port>:3:1: unhandled-exception: badex
     ABORT: (misc-error)
     guile>

   The default uncaught exception behaviour can be observed by
evaluating a `throw' expression from the shell command line:

     $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
     guile: uncaught throw to badex: ()
     $

That Guile exits immediately following the uncaught exception is shown
by the absence of any output from the `display' expression, because
Guile never gets to the point of evaluating that expression.


File: guile.info,  Node: Lazy Catch,  Next: Exception Implementation,  Prev: Throw,  Up: Exceptions

Catch Without Unwinding
-----------------------

   A "lazy catch" is used in the same way as a normal `catch', with
KEY, THUNK and HANDLER arguments specifying the exception type, normal
case code and handler procedure, but differs in one important respect:
the handler procedure is executed without unwinding the call stack from
the context of the `throw' expression that caused the handler to be
invoked.

 - Scheme Procedure: lazy-catch key thunk handler
 - C Function: scm_lazy_catch (key, thunk, handler)
     This behaves exactly like `catch', except that it does not unwind
     the stack before invoking HANDLER.  The HANDLER procedure is not
     allowed to return: it must throw to another catch, or otherwise
     exit non-locally.

   Typically, HANDLER should save any desired state associated with the
stack at the point where the corresponding `throw' occurred, and then
throw an exception itself -- usually the same exception as the one it
caught.  If HANDLER is invoked and does _not_ throw an exception, Guile
itself throws an exception with key `misc-error'.

   Not unwinding the stack means that throwing an exception that is
caught by a `lazy-catch' is _almost_ equivalent to calling the
`lazy-catch''s handler inline instead of each `throw', and then
omitting the surrounding `lazy-catch'.  In other words,

     (lazy-catch 'key
       (lambda () ... (throw 'key args ...) ...)
       handler)

is _almost_ equivalent to

     ((lambda () ... (handler 'key args ...) ...))

But why only _almost_?  The difference is that with `lazy-catch' (as
with normal `catch'), the dynamic context is unwound back to just
outside the `lazy-catch' expression before invoking the handler.  (For
an introduction to what is meant by dynamic context, *Note Dynamic
Wind::.)

   Then, when the handler _itself_ throws an exception, that exception
must be caught by some kind of `catch' (including perhaps another
`lazy-catch') higher up the call stack.

   The dynamic context also includes `with-fluids' blocks (REFFIXME),
so the effect of unwinding the dynamic context can also be seen in fluid
variable values.  This is illustrated by the following code, in which
the normal case thunk uses `with-fluids' to temporarily change the
value of a fluid:

     (define f (make-fluid))
     (fluid-set! f "top level value")
     
     (define (handler . args)
       (cons (fluid-ref f) args))
     
     (lazy-catch 'foo
                 (lambda ()
                   (with-fluids ((f "local value"))
                     (throw 'foo)))
                 handler)
     =>
     ("top level value" foo)
     
     ((lambda ()
        (with-fluids ((f "local value"))
          (handler 'foo))))
     =>
     ("local value" foo)

In the `lazy-catch' version, the unwinding of dynamic context restores
`f' to its value outside the `with-fluids' block before the handler is
invoked, so the handler's `(fluid-ref f)' returns the external value.

   `lazy-catch' is useful because it permits the implementation of
debuggers and other reflective programming tools that need to access the
state of the call stack at the exact point where an exception or an
error is thrown.  For an example of this, see REFFIXME:stack-catch.


File: guile.info,  Node: Exception Implementation,  Prev: Lazy Catch,  Up: Exceptions

How Guile Implements Exceptions
-------------------------------

   It is traditional in Scheme to implement exception systems using
`call-with-current-continuation'.  Continuations (*note
Continuations::) are such a powerful concept that any other control
mechanism -- including `catch' and `throw' -- can be implemented in
terms of them.

   Guile does not implement `catch' and `throw' like this, though.  Why
not?  Because Guile is specifically designed to be easy to integrate
with applications written in C.  In a mixed Scheme/C environment, the
concept of "continuation" must logically include "what happens next" in
the C parts of the application as well as the Scheme parts, and it
turns out that the only reasonable way of implementing continuations
like this is to save and restore the complete C stack.

   So Guile's implementation of `call-with-current-continuation' is a
stack copying one.  This allows it to interact well with ordinary C
code, but means that creating and calling a continuation is slowed down
by the time that it takes to copy the C stack.

   The more targeted mechanism provided by `catch' and `throw' does not
need to save and restore the C stack because the `throw' always jumps
to a location higher up the stack of the code that executes the
`throw'.  Therefore Guile implements the `catch' and `throw' primitives
independently of `call-with-current-continuation', in a way that takes
advantage of this _upwards only_ nature of exceptions.


File: guile.info,  Node: Error Reporting,  Next: Dynamic Wind,  Prev: Exceptions,  Up: Control Mechanisms

Procedures for Signaling Errors
===============================

   Guile provides a set of convenience procedures for signaling error
conditions that are implemented on top of the exception primitives just
described.

 - Scheme Procedure: error msg args ...
     Raise an error with key `misc-error' and a message constructed by
     displaying MSG and writing ARGS.

 - Scheme Procedure: scm-error key subr message args data
 - C Function: scm_error_scm (key, subr, message, args, data)
     Raise an error with key KEY.  SUBR can be a string naming the
     procedure associated with the error, or `#f'.  MESSAGE is the
     error message string, possibly containing `~S' and `~A' escapes.
     When an error is reported, these are replaced by formatting the
     corresponding members of ARGS: `~A' (was `%s' in older versions of
     Guile) formats using `display' and `~S' (was `%S') formats using
     `write'.  DATA is a list or `#f' depending on KEY: if KEY is
     `system-error' then it should be a list containing the Unix
     `errno' value; If KEY is `signal' then it should be a list
     containing the Unix signal number; otherwise it will usually be
     `#f'.

 - Scheme Procedure: strerror err
 - C Function: scm_strerror (err)
     Return the Unix error message corresponding to ERR, which must be
     an integer value.

 - syntax: false-if-exception expr
     Returns the result of evaluating its argument; however if an
     exception occurs then `#f' is returned instead.


File: guile.info,  Node: Dynamic Wind,  Next: Handling Errors,  Prev: Error Reporting,  Up: Control Mechanisms

Dynamic Wind
============

   [FIXME: this is pasted in from Tom Lord's original guile.texi and
should be reviewed]

 - Scheme Procedure: dynamic-wind in_guard thunk out_guard
 - C Function: scm_dynamic_wind (in_guard, thunk, out_guard)
     All three arguments must be 0-argument procedures.  IN_GUARD is
     called, then THUNK, then OUT_GUARD.

     If, any time during the execution of THUNK, the continuation of
     the `dynamic_wind' expression is escaped non-locally, OUT_GUARD is
     called.  If the continuation of the dynamic-wind is re-entered,
     IN_GUARD is called.  Thus IN_GUARD and OUT_GUARD may be called any
     number of times.
          (define x 'normal-binding)
          => x
          (define a-cont  (call-with-current-continuation
          		  (lambda (escape)
          		     (let ((old-x x))
          		       (dynamic-wind
          			  ;; in-guard:
          			  ;;
          			  (lambda () (set! x 'special-binding))
          
          			  ;; thunk
          			  ;;
          		 	  (lambda () (display x) (newline)
          				     (call-with-current-continuation escape)
          				     (display x) (newline)
          				     x)
          
          			  ;; out-guard:
          			  ;;
          			  (lambda () (set! x old-x)))))))
          
          ;; Prints:
          special-binding
          ;; Evaluates to:
          => a-cont
          x
          => normal-binding
          (a-cont #f)
          ;; Prints:
          special-binding
          ;; Evaluates to:
          => a-cont  ;; the value of the (define a-cont...)
          x
          => normal-binding
          a-cont
          => special-binding


File: guile.info,  Node: Handling Errors,  Prev: Dynamic Wind,  Up: Control Mechanisms

How to Handle Errors in C Code
==============================

   Error handling is based on `catch' and `throw'.  Errors are always
thrown with a KEY and four arguments:

   * KEY: a symbol which indicates the type of error.  The symbols used
     by libguile are listed below.

   * SUBR: the name of the procedure from which the error is thrown, or
     `#f'.

   * MESSAGE: a string (possibly language and system dependent)
     describing the error.  The tokens `~A' and `~S' can be embedded
     within the message: they will be replaced with members of the ARGS
     list when the message is printed.  `~A' indicates an argument
     printed using `display', while `~S' indicates an argument printed
     using `write'.  MESSAGE can also be `#f', to allow it to be
     derived from the KEY by the error handler (may be useful if the
     KEY is to be thrown from both C and Scheme).

   * ARGS: a list of arguments to be used to expand `~A' and `~S'
     tokens in MESSAGE.  Can also be `#f' if no arguments are required.

   * REST: a list of any additional objects required. e.g., when the
     key is `'system-error', this contains the C errno value.  Can also
     be `#f' if no additional objects are required.

   In addition to `catch' and `throw', the following Scheme facilities
are available:

 - Scheme Procedure: scm-error key subr message args rest
     Throw an error, with arguments as described above.

 - Scheme Procedure: error msg arg ...
     Throw an error using the key `'misc-error'.  The error message is
     created by displaying MSG and writing the ARGS.

 - Scheme Procedure: display-error stack port subr message args rest
 - C Function: scm_display_error (stack, port, subr, message, args,
          rest)
     Display an error message to the output port PORT.  STACK is the
     saved stack for the error, SUBR is the name of the procedure in
     which the error occurred and MESSAGE is the actual error message,
     which may contain formatting instructions. These will format the
     arguments in the list ARGS accordingly.  REST is currently ignored.

   The following are the error keys defined by libguile and the
situations in which they are used:

   * `error-signal': thrown after receiving an unhandled fatal signal
     such as SIGSEGV, SIGBUS, SIGFPE etc.  The REST argument in the
     throw contains the coded signal number (at present this is not the
     same as the usual Unix signal number).

   * `system-error': thrown after the operating system indicates an
     error condition.  The REST argument in the throw contains the
     errno value.

   * `numerical-overflow': numerical overflow.

   * `out-of-range': the arguments to a procedure do not fall within the
     accepted domain.

   * `wrong-type-arg': an argument to a procedure has the wrong type.

   * `wrong-number-of-args': a procedure was called with the wrong
     number of arguments.

   * `memory-allocation-error': memory allocation error.

   * `stack-overflow': stack overflow error.

   * `regex-error': errors generated by the regular expression library.

   * `misc-error': other errors.

C Support
---------

   SCM scm_error (SCM key, char *subr, char *message, SCM args, SCM
rest)

   Throws an error, after converting the char * arguments to Scheme
strings.  subr is the Scheme name of the procedure, NULL is converted
to #f.  Likewise a NULL message is converted to #f.

   The following procedures invoke scm_error with various error keys and
arguments.  The first three call scm_error with the system-error key
and automatically supply errno in the "rest" argument:  scm_syserror
generates messages using strerror,  scm_sysmissing is used when
facilities are not available.  Care should be taken that the errno
value is not reset (e.g. due to an interrupt).

   * void scm_syserror (char *subr);

   * void scm_syserror_msg (char *subr, char *message, SCM args);

   * void scm_sysmissing (char *subr);

   * void scm_num_overflow (char *subr);

   * void scm_out_of_range (char *subr, SCM bad_value);

   * void scm_wrong_num_args (SCM proc);

   * void scm_wrong_type_arg (char *subr, int pos, SCM bad_value);

   * void scm_memory_error (char *subr);

   * static void scm_regex_error (char *subr, int code); (only used in
     rgx.c).

   Exception handlers can also be installed from C, using
scm_internal_catch, scm_lazy_catch, or scm_stack_catch from
libguile/throw.c.  These have not yet been documented, however the
source contains some useful comments.


File: guile.info,  Node: Input and Output,  Next: Read/Load/Eval,  Prev: Control Mechanisms,  Up: Top

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

* Menu:

* Ports::                       The idea of the port abstraction.
* Reading::                     Procedures for reading from a port.
* Writing::                     Procedures for writing to a port.
* Closing::                     Procedures to close a port.
* Random Access::               Moving around a random access port.
* Line/Delimited::              Read and write lines or delimited text.
* Block Reading and Writing::   Reading and writing blocks of text.
* Default Ports::               Defaults for input, output and errors.
* Port Types::                  Types of port and how to make them.
* I/O Extensions::              Using and extending ports in C.


File: guile.info,  Node: Ports,  Next: Reading,  Up: Input and Output

Ports
=====

   [Concept of the port abstraction.]

   Sequential input/output in Scheme is represented by operations on a
"port".  Characters can be read from an input port and written to an
output port.  This chapter explains the operations that Guile provides
for working with ports.

   The formal definition of a port is very generic: an input port is
simply "an object which can deliver characters on command," and an
output port is "an object which can accept characters."  Because this
definition is so loose, it is easy to write functions that simulate
ports in software.  "Soft ports" and "string ports" are two interesting
and powerful examples of this technique.

 - Scheme Procedure: input-port? x
 - C Function: scm_input_port_p (x)
     Return `#t' if X is an input port, otherwise return `#f'.  Any
     object satisfying this predicate also satisfies `port?'.

 - Scheme Procedure: output-port? x
 - C Function: scm_output_port_p (x)
     Return `#t' if X is an output port, otherwise return `#f'.  Any
     object satisfying this predicate also satisfies `port?'.

 - Scheme Procedure: port? x
 - C Function: scm_port_p (x)
     Return a boolean indicating whether X is a port.  Equivalent to
     `(or (input-port? X) (output-port?  X))'.


File: guile.info,  Node: Reading,  Next: Writing,  Prev: Ports,  Up: Input and Output

Reading
=======

   [Generic procedures for reading from ports.]

 - Scheme Procedure: eof-object? x
 - C Function: scm_eof_object_p (x)
     Return `#t' if X is an end-of-file object; otherwise return `#f'.

 - Scheme Procedure: char-ready? [port]
 - C Function: scm_char_ready_p (port)
     Return `#t' if a character is ready on input PORT and return `#f'
     otherwise.  If `char-ready?' returns `#t' then the next
     `read-char' operation on PORT is guaranteed not to hang.  If PORT
     is a file port at end of file then `char-ready?' returns `#t'.  (1)

 - Scheme Procedure: read-char [port]
 - C Function: scm_read_char (port)
     Return the next character available from PORT, updating PORT to
     point to the following character.  If no more characters are
     available, the end-of-file object is returned.

 - Scheme Procedure: peek-char [port]
 - C Function: scm_peek_char (port)
     Return the next character available from PORT, _without_ updating
     PORT to point to the following character.  If no more characters
     are available, the end-of-file object is returned.(2)

 - Scheme Procedure: unread-char cobj [port]
 - C Function: scm_unread_char (cobj, port)
     Place CHAR in PORT so that it will be read by the next read
     operation.  If called multiple times, the unread characters will
     be read again in last-in first-out order.  If PORT is not
     supplied, the current input port is used.

 - Scheme Procedure: unread-string str port
 - C Function: scm_unread_string (str, port)
     Place the string STR in PORT so that its characters will be read
     in subsequent read operations.  If called multiple times, the
     unread characters will be read again in last-in first-out order.
     If PORT is not supplied, the current-input-port is used.

 - Scheme Procedure: drain-input port
 - C Function: scm_drain_input (port)
     This procedure clears a port's input buffers, similar to the way
     that force-output clears the output buffer.  The contents of the
     buffers are returned as a single string, e.g.,

          (define p (open-input-file ...))
          (drain-input p) => empty string, nothing buffered yet.
          (unread-char (read-char p) p)
          (drain-input p) => initial chars from p, up to the buffer size.

     Draining the buffers may be useful for cleanly finishing buffered
     I/O so that the file descriptor can be used directly for further
     input.

 - Scheme Procedure: port-column port
 - Scheme Procedure: port-line port
 - C Function: scm_port_column (port)
 - C Function: scm_port_line (port)
     Return the current column number or line number of PORT, using the
     current input port if none is specified.  If the number is
     unknown, the result is #f.  Otherwise, the result is a 0-origin
     integer - i.e. the first character of the first line is line 0,
     column 0.  (However, when you display a file position, for example
     in an error message, we recommend you add 1 to get 1-origin
     integers.  This is because lines and column numbers traditionally
     start with 1, and that is what non-programmers will find most
     natural.)

 - Scheme Procedure: set-port-column! port column
 - Scheme Procedure: set-port-line! port line
 - C Function: scm_set_port_column_x (port, column)
 - C Function: scm_set_port_line_x (port, line)
     Set the current column or line number of PORT, using the current
     input port if none is specified.

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

   (1) `char-ready?' exists to make it possible for a program to accept
characters from interactive ports without getting stuck waiting for
input.  Any input editors associated with such ports must make sure
that characters whose existence has been asserted by `char-ready?'
cannot be rubbed out.  If `char-ready?' were to return `#f' at end of
file, a port at end of file would be indistinguishable from an
interactive port that has no ready characters.

   (2) The value returned by a call to `peek-char' is the same as the
value that would have been returned by a call to `read-char' on the same
port.  The only difference is that the very next call to `read-char' or
`peek-char' on that PORT will return the value returned by the
preceding call to `peek-char'.  In particular, a call to `peek-char' on
an interactive port will hang waiting for input whenever a call to
`read-char' would have hung.


File: guile.info,  Node: Writing,  Next: Closing,  Prev: Reading,  Up: Input and Output

Writing
=======

   [Generic procedures for writing to ports.]

 - Scheme Procedure: get-print-state port
 - C Function: scm_get_print_state (port)
     Return the print state of the port PORT. If PORT has no associated
     print state, `#f' is returned.

 - Scheme Procedure: display obj [port]
     Send a representation of OBJ to CURRENT-OUTPUT-PORT.  Optional
     second arg PORT specifies an alternative output port.  The
     representation is similar to that produced by `write' (REFFIXME),
     the differences being strings are not quoted (and their characters
     are not escaped), and characters are rendered as if with
     `write-char'.

 - Scheme Procedure: newline [port]
 - C Function: scm_newline (port)
     Send a newline to PORT.  If PORT is omitted, send to the current
     output port.

 - Scheme Procedure: port-with-print-state port pstate
 - C Function: scm_port_with_print_state (port, pstate)
     Create a new port which behaves like PORT, but with an included
     print state PSTATE.

 - Scheme Procedure: print-options-interface [setting]
 - C Function: scm_print_options (setting)
     Option interface for the print options. Instead of using this
     procedure directly, use the procedures `print-enable',
     `print-disable', `print-set!' and `print-options'.

 - Scheme Procedure: simple-format destination message . args
 - C Function: scm_simple_format (destination, message, args)
     Write MESSAGE to DESTINATION, defaulting to the current output
     port.  MESSAGE can contain `~A' (was `%s') and `~S' (was `%S')
     escapes.  When printed, the escapes are replaced with
     corresponding members of ARGS: `~A' formats using `display' and
     `~S' formats using `write'.  If DESTINATION is `#t', then use the
     current output port, if DESTINATION is `#f', then return a string
     containing the formatted text. Does not add a trailing newline.

 - Scheme Procedure: write-char chr [port]
 - C Function: scm_write_char (chr, port)
     Send character CHR to PORT.

 - Scheme Procedure: force-output [port]
 - C Function: scm_force_output (port)
     Flush the specified output port, or the current output port if PORT
     is omitted.  The current output buffer contents are passed to the
     underlying port implementation (e.g., in the case of fports, the
     data will be written to the file and the output buffer will be
     cleared.)  It has no effect on an unbuffered port.

     The return value is unspecified.

 - Scheme Procedure: flush-all-ports
 - C Function: scm_flush_all_ports ()
     Equivalent to calling `force-output' on all open output ports.
     The return value is unspecified.


File: guile.info,  Node: Closing,  Next: Random Access,  Prev: Writing,  Up: Input and Output

Closing
=======

 - Scheme Procedure: close-port port
 - C Function: scm_close_port (port)
     Close the specified port object.  Return `#t' if it successfully
     closes a port or `#f' if it was already closed.  An exception may
     be raised if an error occurs, for example when flushing buffered
     output.  See also *Note close: Ports and File Descriptors, for a
     procedure which can close file descriptors.

 - Scheme Procedure: close-input-port port
 - C Function: scm_close_input_port (port)
     Close the specified input port object.  The routine has no effect
     if the file has already been closed.  An exception may be raised
     if an error occurs.  The value returned is unspecified.

     See also *Note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 - Scheme Procedure: close-output-port port
 - C Function: scm_close_output_port (port)
     Close the specified output port object.  The routine has no effect
     if the file has already been closed.  An exception may be raised
     if an error occurs.  The value returned is unspecified.

     See also *Note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 - Scheme Procedure: port-closed? port
 - C Function: scm_port_closed_p (port)
     Return `#t' if PORT is closed or `#f' if it is open.


File: guile.info,  Node: Random Access,  Next: Line/Delimited,  Prev: Closing,  Up: Input and Output

Random Access
=============

 - Scheme Procedure: seek fd_port offset whence
 - C Function: scm_seek (fd_port, offset, whence)
     Sets the current position of FD/PORT to the integer OFFSET, which
     is interpreted according to the value of WHENCE.

     One of the following variables should be supplied for WHENCE:

      - Variable: SEEK_SET
          Seek from the beginning of the file.

      - Variable: SEEK_CUR
          Seek from the current position.

      - Variable: SEEK_END
          Seek from the end of the file.
     If FD/PORT is a file descriptor, the underlying system call is
     `lseek'.  PORT may be a string port.

     The value returned is the new position in the file.  This means
     that the current position of a port can be obtained using:
          (seek port 0 SEEK_CUR)

 - Scheme Procedure: ftell fd_port
 - C Function: scm_ftell (fd_port)
     Return an integer representing the current position of FD/PORT,
     measured from the beginning.  Equivalent to:

          (seek port 0 SEEK_CUR)

 - Scheme Procedure: truncate-file object [length]
 - C Function: scm_truncate_file (object, length)
     Truncates the object referred to by OBJECT to at most LENGTH
     bytes.  OBJECT can be a string containing a file name or an
     integer file descriptor or a port.  LENGTH may be omitted if
     OBJECT is not a file name, in which case the truncation occurs at
     the current port.  position.  The return value is unspecified.


File: guile.info,  Node: Line/Delimited,  Next: Block Reading and Writing,  Prev: Random Access,  Up: Input and Output

Line Oriented and Delimited Text
================================

   The delimited-I/O module can be accessed with:

     (use-modules (ice-9 rdelim))

   It can be used to read or write lines of text, or read text
delimited by a specified set of characters.  It's similar to the `(scsh
rdelim)' module from guile-scsh, but does not use multiple values or
character sets and has an extra procedure `write-line'.

 - Scheme Procedure: read-line [port] [handle-delim]
     Return a line of text from PORT if specified, otherwise from the
     value returned by `(current-input-port)'.  Under Unix, a line of
     text is terminated by the first end-of-line character or by
     end-of-file.

     If HANDLE-DELIM is specified, it should be one of the following
     symbols:
    `trim'
          Discard the terminating delimiter.  This is the default, but
          it will be impossible to tell whether the read terminated
          with a delimiter or end-of-file.

    `concat'
          Append the terminating delimiter (if any) to the returned
          string.

    `peek'
          Push the terminating delimiter (if any) back on to the port.

    `split'
          Return a pair containing the string read from the port and the
          terminating delimiter or end-of-file object.

 - Scheme Procedure: read-line! buf [port]
     Read a line of text into the supplied string BUF and return the
     number of characters added to BUF.  If BUF is filled, then `#f' is
     returned.  Read from PORT if specified, otherwise from the value
     returned by `(current-input-port)'.

 - Scheme Procedure: read-delimited delims [port] [handle-delim]
     Read text until one of the characters in the string DELIMS is found
     or end-of-file is reached.  Read from PORT if supplied, otherwise
     from the value returned by `(current-input-port)'.  HANDLE-DELIM
     takes the same values as described for `read-line'.

 - Scheme Procedure: read-delimited! delims buf [port] [handle-delim]
          [start] [end]
     Read text into the supplied string BUF and return the number of
     characters added to BUF (subject to HANDLE-DELIM, which takes the
     same values specified for `read-line'.  If BUF is filled, `#f' is
     returned for both the number of characters read and the delimiter.
     Also terminates if one of the characters in the string DELIMS is
     found or end-of-file is reached.  Read from PORT if supplied,
     otherwise from the value returned by `(current-input-port)'.

 - Scheme Procedure: write-line obj [port]
 - C Function: scm_write_line (obj, port)
     Display OBJ and a newline character to PORT.  If PORT is not
     specified, `(current-output-port)' is used.  This function is
     equivalent to:
          (display obj [port])
          (newline [port])

   Some of the abovementioned I/O functions rely on the following C
primitives.  These will mainly be of interest to people hacking Guile
internals.

 - Scheme Procedure: %read-delimited! delims str gobble [port [start
          [end]]]
 - C Function: scm_read_delimited_x (delims, str, gobble, port, start,
          end)
     Read characters from PORT into STR until one of the characters in
     the DELIMS string is encountered.  If GOBBLE is true, discard the
     delimiter character; otherwise, leave it in the input stream for
     the next read.  If PORT is not specified, use the value of
     `(current-input-port)'.  If START or END are specified, store data
     only into the substring of STR bounded by START and END (which
     default to the beginning and end of the string, respectively).

     Return a pair consisting of the delimiter that terminated the
     string and the number of characters read.  If reading stopped at
     the end of file, the delimiter returned is the EOF-OBJECT; if the
     string was filled without encountering a delimiter, this value is
     `#f'.

 - Scheme Procedure: %read-line [port]
 - C Function: scm_read_line (port)
     Read a newline-terminated line from PORT, allocating storage as
     necessary.  The newline terminator (if any) is removed from the
     string, and a pair consisting of the line and its delimiter is
     returned.  The delimiter may be either a newline or the
     EOF-OBJECT; if `%read-line' is called at the end of file, it
     returns the pair `(#<eof> . #<eof>)'.


File: guile.info,  Node: Block Reading and Writing,  Next: Default Ports,  Prev: Line/Delimited,  Up: Input and Output

Block reading and writing
=========================

   The Block-string-I/O module can be accessed with:

     (use-modules (ice-9 rw))

   It currently contains procedures that help to implement the `(scsh
rw)' module in guile-scsh.

 - Scheme Procedure: read-string!/partial str [port_or_fdes [start
          [end]]]
 - C Function: scm_read_string_x_partial (str, port_or_fdes, start, end)
     Read characters from a port or file descriptor into a string STR.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently read
     large strings.  It will:

        * attempt to fill the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and
          END defaults to `(string-length str)'

        * use the current input port if PORT_OR_FDES is not supplied.

        * return fewer than the requested number of characters in some
          cases, e.g., on end of file, if interrupted by a signal, or if
          not all the characters are immediately available.

        * wait indefinitely for some input if no characters are
          currently available, unless the port is in non-blocking mode.

        * read characters from the port's input buffers if available,
          instead from the underlying file descriptor.

        * return `#f' if end-of-file is encountered before reading any
          characters, otherwise return the number of characters read.

        * return 0 if the port is in non-blocking mode and no characters
          are immediately available.

        * return 0 if the request is for 0 bytes, with no end-of-file
          check.

 - Scheme Procedure: write-string/partial str [port_or_fdes [start
          [end]]]
 - C Function: scm_write_string_partial (str, port_or_fdes, start, end)
     Write characters from a string STR to a port or file descriptor.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently
     write large strings.  It will:

        * attempt to write the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and
          END defaults to `(string-length str)'

        * use the current output port if PORT_OF_FDES is not supplied.

        * in the case of a buffered port, store the characters in the
          port's output buffer, if all will fit.  If they will not fit
          then any existing buffered characters will be flushed before
          attempting to write the new characters directly to the
          underlying file descriptor.  If the port is in non-blocking
          mode and buffered characters can not be flushed immediately,
          then an `EAGAIN' system-error exception will be raised (Note:
          scsh does not support the use of non-blocking buffered ports.)

        * write fewer than the requested number of characters in some
          cases, e.g., if interrupted by a signal or if not all of the
          output can be accepted immediately.

        * wait indefinitely for at least one character from STR to be
          accepted by the port, unless the port is in non-blocking mode.

        * return the number of characters accepted by the port.

        * return 0 if the port is in non-blocking mode and can not
          accept at least one character from STR immediately

        * return 0 immediately if the request size is 0 bytes.


File: guile.info,  Node: Default Ports,  Next: Port Types,  Prev: Block Reading and Writing,  Up: Input and Output

Default Ports for Input, Output and Errors
==========================================

 - Scheme Procedure: current-input-port
 - C Function: scm_current_input_port ()
     Return the current input port.  This is the default port used by
     many input procedures.  Initially, `current-input-port' returns
     the "standard input" in Unix and C terminology.

 - Scheme Procedure: current-output-port
 - C Function: scm_current_output_port ()
     Return the current output port.  This is the default port used by
     many output procedures.  Initially, `current-output-port' returns
     the "standard output" in Unix and C terminology.

 - Scheme Procedure: current-error-port
 - C Function: scm_current_error_port ()
     Return the port to which errors and warnings should be sent (the
     "standard error" in Unix and C terminology).

 - Scheme Procedure: set-current-input-port port
 - Scheme Procedure: set-current-output-port port
 - Scheme Procedure: set-current-error-port port
 - C Function: scm_set_current_input_port (port)
 - C Function: scm_set_current_output_port (port)
 - C Function: scm_set_current_error_port (port)
     Change the ports returned by `current-input-port',
     `current-output-port' and `current-error-port', respectively, so
     that they use the supplied PORT for input or output.

 - Scheme Procedure: set-current-output-port port
     Set the current default output port to PORT.

 - Scheme Procedure: set-current-error-port port
     Set the current default error port to PORT.


File: guile.info,  Node: Port Types,  Next: I/O Extensions,  Prev: Default Ports,  Up: Input and Output

Types of Port
=============

   [Types of port; how to make them.]

* Menu:

* File Ports:: Ports on an operating system file.
* String Ports:: Ports on a Scheme string.
* Soft Ports:: Ports on arbitrary Scheme procedures.
* Void Ports:: Ports on nothing at all.


File: guile.info,  Node: File Ports,  Next: String Ports,  Up: Port Types

File Ports
----------

   The following procedures are used to open file ports.  See also
*Note open: Ports and File Descriptors, for an interface to the Unix
`open' system call.

 - Scheme Procedure: open-file filename mode
 - C Function: scm_open_file (filename, mode)
     Open the file whose name is FILENAME, and return a port
     representing that file.  The attributes of the port are determined
     by the MODE string.  The way in which this is interpreted is
     similar to C stdio.  The first character must be one of the
     following:
    `r'
          Open an existing file for input.

    `w'
          Open a file for output, creating it if it doesn't already
          exist or removing its contents if it does.

    `a'
          Open a file for output, creating it if it doesn't already
          exist.  All writes to the port will go to the end of the file.
          The "append mode" can be turned off while the port is in use
          *note fcntl: Ports and File Descriptors.
     The following additional characters can be appended:
    `+'
          Open the port for both input and output.  E.g., `r+': open an
          existing file for both input and output.

    `0'
          Create an "unbuffered" port.  In this case input and output
          operations are passed directly to the underlying port
          implementation without additional buffering.  This is likely
          to slow down I/O operations.  The buffering mode can be
          changed while a port is in use *note setvbuf: Ports and File
          Descriptors.

    `l'
          Add line-buffering to the port.  The port output buffer will
          be automatically flushed whenever a newline character is
          written.
     In theory we could create read/write ports which were buffered in
     one direction only.  However this isn't included in the current
     interfaces.  If a file cannot be opened with the access requested,
     `open-file' throws an exception.

 - Scheme Procedure: open-input-file filename
     Open FILENAME for input.  Equivalent to
          (open-file FILENAME "r")

 - Scheme Procedure: open-output-file filename
     Open FILENAME for output.  Equivalent to
          (open-file FILENAME "w")

 - Scheme Procedure: call-with-input-file file proc
     PROC should be a procedure of one argument, and FILE should be a
     string naming a file.  The file must already exist. These
     procedures call PROC with one argument: the port obtained by
     opening the named file for input or output.  If the file cannot be
     opened, an error is signalled.  If the procedure returns, then the
     port is closed automatically and the value yielded by the
     procedure is returned.  If the procedure does not return, then the
     port will not be closed automatically unless it is possible to
     prove that the port will never again be used for a read or write
     operation.

 - Scheme Procedure: call-with-output-file file proc
     PROC should be a procedure of one argument, and FILE should be a
     string naming a file.  The behaviour is unspecified if the file
     already exists. These procedures call PROC with one argument: the
     port obtained by opening the named file for input or output.  If
     the file cannot be opened, an error is signalled.  If the
     procedure returns, then the port is closed automatically and the
     value yielded by the procedure is returned.  If the procedure does
     not return, then the port will not be closed automatically unless
     it is possible to prove that the port will never again be used for
     a read or write operation.

 - Scheme Procedure: with-input-from-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The file must already exist. The file is
     opened for input, an input port connected to it is made the
     default value returned by `current-input-port', and the THUNK is
     called with no arguments.  When the THUNK returns, the port is
     closed and the previous default is restored.  Returns the value
     yielded by THUNK.  If an escape procedure is used to escape from
     the continuation of these procedures, their behavior is
     implementation dependent.

 - Scheme Procedure: with-output-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The effect is unspecified if the file
     already exists.  The file is opened for output, an output port
     connected to it is made the default value returned by
     `current-output-port', and the THUNK is called with no arguments.
     When the THUNK returns, the port is closed and the previous
     default is restored.  Returns the value yielded by THUNK.  If an
     escape procedure is used to escape from the continuation of these
     procedures, their behavior is implementation dependent.

 - Scheme Procedure: with-error-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The effect is unspecified if the file
     already exists.  The file is opened for output, an output port
     connected to it is made the default value returned by
     `current-error-port', and the THUNK is called with no arguments.
     When the THUNK returns, the port is closed and the previous
     default is restored.  Returns the value yielded by THUNK.  If an
     escape procedure is used to escape from the continuation of these
     procedures, their behavior is implementation dependent.

 - Scheme Procedure: port-mode port
 - C Function: scm_port_mode (port)
     Return the port modes associated with the open port PORT.  These
     will not necessarily be identical to the modes used when the port
     was opened, since modes such as "append" which are used only
     during port creation are not retained.

 - Scheme Procedure: port-filename port
 - C Function: scm_port_filename (port)
     Return the filename associated with PORT.  This function returns
     the strings "standard input", "standard output" and "standard
     error" when called on the current input, output and error ports
     respectively.

 - Scheme Procedure: set-port-filename! port filename
 - C Function: scm_set_port_filename_x (port, filename)
     Change the filename associated with PORT, using the current input
     port if none is specified.  Note that this does not change the
     port's source of data, but only the value that is returned by
     `port-filename' and reported in diagnostic output.

 - Scheme Procedure: file-port? obj
 - C Function: scm_file_port_p (obj)
     Determine whether OBJ is a port that is related to a file.


File: guile.info,  Node: String Ports,  Next: Soft Ports,  Prev: File Ports,  Up: Port Types

String Ports
------------

   The following allow string ports to be opened by analogy to R4R*
file port facilities:

 - Scheme Procedure: call-with-output-string proc
 - C Function: scm_call_with_output_string (proc)
     Calls the one-argument procedure PROC with a newly created output
     port.  When the function returns, the string composed of the
     characters written into the port is returned.

 - Scheme Procedure: call-with-input-string string proc
 - C Function: scm_call_with_input_string (string, proc)
     Calls the one-argument procedure PROC with a newly created input
     port from which STRING's contents may be read.  The value yielded
     by the PROC is returned.

 - Scheme Procedure: with-output-to-string thunk
     Calls the zero-argument procedure THUNK with the current output
     port set temporarily to a new string port.  It returns a string
     composed of the characters written to the current output.

 - Scheme Procedure: with-input-from-string string thunk
     Calls the zero-argument procedure THUNK with the current input
     port set temporarily to a string port opened on the specified
     STRING.  The value yielded by THUNK is returned.

 - Scheme Procedure: open-input-string str
 - C Function: scm_open_input_string (str)
     Take a string and return an input port that delivers characters
     from the string. The port can be closed by `close-input-port',
     though its storage will be reclaimed by the garbage collector if
     it becomes inaccessible.

 - Scheme Procedure: open-output-string
 - C Function: scm_open_output_string ()
     Return an output port that will accumulate characters for
     retrieval by `get-output-string'. The port can be closed by the
     procedure `close-output-port', though its storage will be
     reclaimed by the garbage collector if it becomes inaccessible.

 - Scheme Procedure: get-output-string port
 - C Function: scm_get_output_string (port)
     Given an output port created by `open-output-string', return a
     string consisting of the characters that have been output to the
     port so far.

   A string port can be used in many procedures which accept a port but
which are not dependent on implementation details of fports.  E.g.,
seeking and truncating will work on a string port, but trying to
extract the file descriptor number will fail.


File: guile.info,  Node: Soft Ports,  Next: Void Ports,  Prev: String Ports,  Up: Port Types

Soft Ports
----------

   A "soft-port" is a port based on a vector of procedures capable of
accepting or delivering characters.  It allows emulation of I/O ports.

 - Scheme Procedure: make-soft-port pv modes
 - C Function: scm_make_soft_port (pv, modes)
     Return a port capable of receiving or delivering characters as
     specified by the MODES string (*note open-file: File Ports.).  PV
     must be a vector of length 5.  Its components are as follows:

       0. procedure accepting one character for output

       1. procedure accepting a string for output

       2. thunk for flushing output

       3. thunk for getting one character

       4. thunk for closing port (not by garbage collection)

     For an output-only port only elements 0, 1, 2, and 4 need be
     procedures.  For an input-only port only elements 3 and 4 need be
     procedures.  Thunks 2 and 4 can instead be `#f' if there is no
     useful operation for them to perform.

     If thunk 3 returns `#f' or an `eof-object' (*note eof-object?:
     (r5rs)Input.) it indicates that the port has reached end-of-file.
     For example:

          (define stdout (current-output-port))
          (define p (make-soft-port
                     (vector
                      (lambda (c) (write c stdout))
                      (lambda (s) (display s stdout))
                      (lambda () (display "." stdout))
                      (lambda () (char-upcase (read-char)))
                      (lambda () (display "@" stdout)))
                     "rw"))
          
          (write p p) => #<input-output: soft 8081e20>


File: guile.info,  Node: Void Ports,  Prev: Soft Ports,  Up: Port Types

Void Ports
----------

   This kind of port causes any data to be discarded when written to,
and always returns the end-of-file object when read from.

 - Scheme Procedure: %make-void-port mode
 - C Function: scm_sys_make_void_port (mode)
     Create and return a new void port.  A void port acts like
     `/dev/null'.  The MODE argument specifies the input/output modes
     for this port: see the documentation for `open-file' in *Note File
     Ports::.


File: guile.info,  Node: I/O Extensions,  Prev: Port Types,  Up: Input and Output

Using and Extending Ports in C
==============================

* Menu:

* C Port Interface:: Using ports from C.
* Port Implementation:: How to implement a new port type in C.


File: guile.info,  Node: C Port Interface,  Next: Port Implementation,  Up: I/O Extensions

C Port Interface
----------------

   This section describes how to use Scheme ports from C.

Port basics
...........

   There are two main data structures.  A port type object (ptob) is of
type `scm_ptob_descriptor'.  A port instance is of type `scm_port'.
Given an `SCM' variable which points to a port, the corresponding C
port object can be obtained using the `SCM_PTAB_ENTRY' macro.  The ptob
can be obtained by using `SCM_PTOBNUM' to give an index into the
`scm_ptobs' global array.

Port buffers
............

   An input port always has a read buffer and an output port always has
a write buffer.  However the size of these buffers is not guaranteed to
be more than one byte (e.g., the `shortbuf' field in `scm_port' which
is used when no other buffer is allocated).  The way in which the
buffers are allocated depends on the implementation of the ptob.  For
example in the case of an fport, buffers may be allocated with malloc
when the port is created, but in the case of an strport the underlying
string is used as the buffer.

The `rw_random' flag
....................

   Special treatment is required for ports which can be seeked at
random.  Before various operations, such as seeking the port or
changing from input to output on a bidirectional port or vice versa,
the port implementation must be given a chance to update its state.
The write buffer is updated by calling the `flush' ptob procedure and
the input buffer is updated by calling the `end_input' ptob procedure.
In the case of an fport, `flush' causes buffered output to be written
to the file descriptor, while `end_input' causes the descriptor
position to be adjusted to account for buffered input which was never
read.

   The special treatment must be performed if the `rw_random' flag in
the port is non-zero.

The `rw_active' variable
........................

   The `rw_active' variable in the port is only used if `rw_random' is
set.  It's defined as an enum with the following values:

`SCM_PORT_READ'
     the read buffer may have unread data.

`SCM_PORT_WRITE'
     the write buffer may have unwritten data.

`SCM_PORT_NEITHER'
     neither the write nor the read buffer has data.

Reading from a port.
....................

   To read from a port, it's possible to either call existing libguile
procedures such as `scm_getc' and `scm_read_line' or to read data from
the read buffer directly.  Reading from the buffer involves the
following steps:

  1. Flush output on the port, if `rw_active' is `SCM_PORT_WRITE'.

  2. Fill the read buffer, if it's empty, using `scm_fill_input'.

  3. Read the data from the buffer and update the read position in the
     buffer.  Steps 2) and 3) may be repeated as many times as required.

  4. Set rw_active to `SCM_PORT_READ' if `rw_random' is set.

  5. update the port's line and column counts.

Writing to a port.
..................

   To write data to a port, calling `scm_lfwrite' should be sufficient
for most purposes.  This takes care of the following steps:

  1. End input on the port, if `rw_active' is `SCM_PORT_READ'.

  2. Pass the data to the ptob implementation using the `write' ptob
     procedure.  The advantage of using the ptob `write' instead of
     manipulating the write buffer directly is that it allows the data
     to be written in one operation even if the port is using the
     single-byte `shortbuf'.

  3. Set `rw_active' to `SCM_PORT_WRITE' if `rw_random' is set.


File: guile.info,  Node: Port Implementation,  Prev: C Port Interface,  Up: I/O Extensions

Port Implementation
-------------------

   This section describes how to implement a new port type in C.

   As described in the previous section, a port type object (ptob) is a
structure of type `scm_ptob_descriptor'.  A ptob is created by calling
`scm_make_port_type'.

   All of the elements of the ptob, apart from `name', are procedures
which collectively implement the port behaviour.  Creating a new port
type mostly involves writing these procedures.

   `scm_make_port_type' initializes three elements of the structure
(`name', `fill_input' and `write') from its arguments.  The remaining
elements are initialized with default values and can be set later if
required.

`name'
     A pointer to a NUL terminated string: the name of the port type.
     This is the only element of `scm_ptob_descriptor' which is not a
     procedure.  Set via the first argument to `scm_make_port_type'.

`mark'
     Called during garbage collection to mark any SCM objects that a
     port object may contain.  It doesn't need to be set unless the
     port has `SCM' components.  Set using `scm_set_port_mark'.

`free'
     Called when the port is collected during gc.  It should free any
     resources used by the port.  Set using `scm_set_port_free'.

`print'
     Called when `write' is called on the port object, to print a port
     description.  e.g., for an fport it may produce something like:
     `#<input: /etc/passwd 3>'.   Set using `scm_set_port_print'.

`equalp'
     Not used at present.  Set using `scm_set_port_equalp'.

`close'
     Called when the port is closed, unless it was collected during gc.
     It should free any resources used by the port.  Set using
     `scm_set_port_close'.

`write'
     Accept data which is to be written using the port.  The port
     implementation may choose to buffer the data instead of processing
     it directly.  Set via the third argument to `scm_make_port_type'.

`flush'
     Complete the processing of buffered output data.  Reset the value
     of `rw_active' to `SCM_PORT_NEITHER'.  Set using
     `scm_set_port_flush'.

`end_input'
     Perform any synchronization required when switching from input to
     output on the port.  Reset the value of `rw_active' to
     `SCM_PORT_NEITHER'.  Set using `scm_set_port_end_input'.

`fill_input'
     Read new data into the read buffer and return the first character.
     It can be assumed that the read buffer is empty when this
     procedure is called.  Set via the second argument to
     `scm_make_port_type'.

`input_waiting'
     Return a lower bound on the number of bytes that could be read
     from the port without blocking.  It can be assumed that the
     current state of `rw_active' is `SCM_PORT_NEITHER'.  Set using
     `scm_set_port_input_waiting'.

`seek'
     Set the current position of the port.  The procedure can not make
     any assumptions about the value of `rw_active' when it's called.
     It can reset the buffers first if desired by using something like:

                if (pt->rw_active == SCM_PORT_READ)
          	scm_end_input (object);
                else if (pt->rw_active == SCM_PORT_WRITE)
          	ptob->flush (object);

     However note that this will have the side effect of discarding any
     data in the unread-char buffer, in addition to any side effects
     from the `end_input' and `flush' ptob procedures.  This is
     undesirable when seek is called to measure the current position of
     the port, i.e., `(seek p 0 SEEK_CUR)'.  The libguile fport and
     string port implementations take care to avoid this problem.

     The procedure is set using `scm_set_port_seek'.

`truncate'
     Truncate the port data to be specified length.  It can be assumed
     that the current state of `rw_active' is `SCM_PORT_NEITHER'.  Set
     using `scm_set_port_truncate'.



File: guile.info,  Node: Read/Load/Eval,  Next: Memory Management,  Prev: Input and Output,  Up: Top

Reading and Evaluating Scheme Code
**********************************

   This chapter describes Guile functions that are concerned with
reading, loading and evaluating Scheme code at run time.

* Menu:

* Scheme Syntax::               Standard and extended Scheme syntax.
* Scheme Read::                 Reading Scheme code.
* Fly Evaluation::              Procedures for on the fly evaluation.
* Loading::                     Loading Scheme code from file.
* Delayed Evaluation::          Postponing evaluation until it is needed.
* Local Evaluation::            Evaluation in a local environment.
* Evaluator Behaviour::         Modifying Guile's evaluator.


File: guile.info,  Node: Scheme Syntax,  Next: Scheme Read,  Up: Read/Load/Eval

Scheme Syntax: Standard and Guile Extensions
============================================

* Menu:

* Expression Syntax::
* Comments::
* Block Comments::
* Case Sensitivity::
* Keyword Syntax::
* Reader Extensions::


File: guile.info,  Node: Expression Syntax,  Next: Comments,  Up: Scheme Syntax

Expression Syntax
-----------------


File: guile.info,  Node: Comments,  Next: Block Comments,  Prev: Expression Syntax,  Up: Scheme Syntax

Comments
--------

   Comments in Scheme source files are written by starting them with a
semicolon character (`;').  The comment then reaches up to the end of
the line.  Comments can begin at any column, and the may be inserted on
the same line as Scheme code.

     ; Comment
     ;; Comment too
     (define x 1)        ; Comment after expression
     (let ((y 1))
       ;; Display something.
       (display y)
     ;;; Comment at left margin.
       (display (+ y 1)))

   It is common to use a single semicolon for comments following
expressions on a line, to use two semicolons for comments which are
indented like code, and three semicolons for comments which start at
column 0, even if they are inside an indented code block.  This
convention is used when indenting code in Emacs' Scheme mode.


File: guile.info,  Node: Block Comments,  Next: Case Sensitivity,  Prev: Comments,  Up: Scheme Syntax

Block Comments
--------------

   In addition to the standard line comments defined by R5RS, Guile has
another comment type for multiline comments, called "block comments".
This type of comment begins with the character sequence `#!' and ends
with the characters `!#', which must appear on a line of their own.
These comments are compatible with the block comments in the Scheme
Shell `scsh' (*note The Scheme shell (scsh)::).  The characters `#!'
were chosen because they are the magic characters used in shell scripts
for indicating that the name of the program for executing the script
follows on the same line.

   Thus a Guile script often starts like this.

     #! /usr/local/bin/guile -s
     !#

   More details on Guile scripting can be found in the scripting section
(*note Guile Scripting::).


File: guile.info,  Node: Case Sensitivity,  Next: Keyword Syntax,  Prev: Block Comments,  Up: Scheme Syntax

Case Sensitivity
----------------

   Scheme as defined in R5RS is not case sensitive when reading symbols.
Guile, on the contrary is case sensitive by default, so the identifiers

     guile-whuzzy
     Guile-Whuzzy

   are the same in R5RS Scheme, but are different in Guile.

   It is possible to turn off case sensitivity in Guile by setting the
reader option `case-insensitive'.  More on reader options can be found
at (*note Reader options::).

     (read-enable 'case-insensitive)

   Note that this is seldom a problem, because Scheme programmers tend
not to use uppercase letters in their identifiers anyway.


File: guile.info,  Node: Keyword Syntax,  Next: Reader Extensions,  Prev: Case Sensitivity,  Up: Scheme Syntax

Keyword Syntax
--------------


File: guile.info,  Node: Reader Extensions,  Prev: Keyword Syntax,  Up: Scheme Syntax

Reader Extensions
-----------------

 - Scheme Procedure: read-hash-extend chr proc
 - C Function: scm_read_hash_extend (chr, proc)
     Install the procedure PROC for reading expressions starting with
     the character sequence `#' and CHR.  PROC will be called with two
     arguments:  the character CHR and the port to read further data
     from. The object returned will be the return value of `read'.


File: guile.info,  Node: Scheme Read,  Next: Fly Evaluation,  Prev: Scheme Syntax,  Up: Read/Load/Eval

Reading Scheme Code
===================

 - Scheme Procedure: read [port]
 - C Function: scm_read (port)
     Read an s-expression from the input port PORT, or from the current
     input port if PORT is not specified.  Any whitespace before the
     next token is discarded.

   The behaviour of Guile's Scheme reader can be modified by
manipulating its read options.  For more information about options,
*Note User level options interfaces::.  If you want to know which
reader options are available, *Note Reader options::.

 - Scheme Procedure: read-options [setting]
     Display the current settings of the read options.  If SETTING is
     omitted, only a short form of the current read options is printed.
     Otherwise, SETTING should be one of the following symbols:
    `help'
          Display the complete option settings.

    `full'
          Like `help', but also print programmer options.

 - Scheme Procedure: read-enable option-name
 - Scheme Procedure: read-disable option-name
 - Scheme Procedure: read-set! option-name value
     Modify the read options.  `read-enable' should be used with boolean
     options and switches them on, `read-disable' switches them off.
     `read-set!' can be used to set an option to a specific value.

 - Scheme Procedure: read-options-interface [setting]
 - C Function: scm_read_options (setting)
     Option interface for the read options. Instead of using this
     procedure directly, use the procedures `read-enable',
     `read-disable', `read-set!' and `read-options'.


File: guile.info,  Node: Fly Evaluation,  Next: Loading,  Prev: Scheme Read,  Up: Read/Load/Eval

Procedures for On the Fly Evaluation
====================================

   *Note Environments::.

 - Scheme Procedure: eval exp module
 - C Function: scm_eval (exp, module)
     Evaluate EXP, a list representing a Scheme expression, in the
     top-level environment specified by MODULE.  While EXP is evaluated
     (using `primitive-eval'), MODULE is made the current module.  The
     current module is reset to its previous value when EVAL returns.

 - Scheme Procedure: interaction-environment
 - C Function: scm_interaction_environment ()
     Return a specifier for the environment that contains
     implementation-defined bindings, typically a superset of those
     listed in the report.  The intent is that this procedure will
     return the environment in which the implementation would evaluate
     expressions dynamically typed by the user.

 - Scheme Procedure: eval-string string
 - C Function: scm_eval_string (string)
     Evaluate STRING as the text representation of a Scheme form or
     forms, and return whatever value they produce.  Evaluation takes
     place in the environment returned by the procedure
     `interaction-environment'.

 - Scheme Procedure: apply:nconc2last lst
 - C Function: scm_nconc2last (lst)
     Given a list (ARG1 ... ARGS), this function conses the ARG1 ...
     arguments onto the front of ARGS, and returns the resulting list.
     Note that ARGS is a list; thus, the argument to this function is a
     list whose last element is a list.  Note: Rather than do new
     consing, `apply:nconc2last' destroys its argument, so use with
     care.

 - Scheme Procedure: apply proc arg1 ... args
     PROC must be a procedure and ARGS must be a list.  Call PROC with
     the elements of the list `(append (list ARG1 ...) ARGS)' as the
     actual arguments.

 - Scheme Procedure: primitive-eval exp
 - C Function: scm_primitive_eval (exp)
     Evaluate EXP in the top-level environment specified by the current
     module.


File: guile.info,  Node: Loading,  Next: Delayed Evaluation,  Prev: Fly Evaluation,  Up: Read/Load/Eval

Loading Scheme Code from File
=============================

 - Scheme Procedure: load filename
     Load FILENAME and evaluate its contents in the top-level
     environment.  The load paths are not searched.  If the variable
     `%load-hook' is defined, it should be bound to a procedure that
     will be called before any code is loaded.  See documentation for
     `%load-hook' later in this section.

 - Scheme Procedure: load-from-path filename
     Similar to `load', but searches for FILENAME in the load paths.

 - Scheme Procedure: primitive-load filename
 - C Function: scm_primitive_load (filename)
     Load the file named FILENAME and evaluate its contents in the
     top-level environment. The load paths are not searched; FILENAME
     must either be a full pathname or be a pathname relative to the
     current directory.  If the  variable `%load-hook' is defined, it
     should be bound to a procedure that will be called before any code
     is loaded.  See the documentation for `%load-hook' later in this
     section.

 - Scheme Procedure: primitive-load-path filename
 - C Function: scm_primitive_load_path (filename)
     Search %LOAD-PATH for the file named FILENAME and load it into the
     top-level environment.  If FILENAME is a relative pathname and is
     not found in the list of search paths, an error is signalled.

 - Scheme Procedure: %search-load-path filename
 - C Function: scm_sys_search_load_path (filename)
     Search %LOAD-PATH for the file named FILENAME, which must be
     readable by the current user.  If FILENAME is found in the list of
     paths to search or is an absolute pathname, return its full
     pathname.  Otherwise, return `#f'.  Filenames may have any of the
     optional extensions in the `%load-extensions' list;
     `%search-load-path' will try each extension automatically.

 - Variable: %load-hook
     A procedure to be run whenever `primitive-load' is called.  If this
     procedure is defined, it will be called with the filename argument
     that was passed to `primitive-load'.

          (define %load-hook (lambda (file)
                               (display "Loading ")
                               (display file)
                               (write-line "...."))) => undefined
          (load-from-path "foo.scm")
          -| Loading /usr/local/share/guile/site/foo.scm....


 - Scheme Procedure: current-load-port
 - C Function: scm_current_load_port ()
     Return the current-load-port.  The load port is used internally by
     `primitive-load'.

 - Variable: %load-extensions
     A list of default file extensions for files containing Scheme code.
     `%search-load-path' tries each of these extensions when looking for
     a file to load.  By default, `%load-extensions' is bound to the
     list `("" ".scm")'.


File: guile.info,  Node: Delayed Evaluation,  Next: Local Evaluation,  Prev: Loading,  Up: Read/Load/Eval

Delayed Evaluation
==================

   [delay]

 - Scheme Procedure: promise? obj
 - C Function: scm_promise_p (obj)
     Return true if OBJ is a promise, i.e. a delayed computation (*note
     Delayed evaluation: (r5rs.info)Delayed evaluation.).

 - Scheme Procedure: force x
 - C Function: scm_force (x)
     If the promise X has not been computed yet, compute and return X,
     otherwise just return the previously computed value.


File: guile.info,  Node: Local Evaluation,  Next: Evaluator Behaviour,  Prev: Delayed Evaluation,  Up: Read/Load/Eval

Local Evaluation
================

   [the-environment]

 - Scheme Procedure: local-eval exp [env]
 - C Function: scm_local_eval (exp, env)
     Evaluate EXP in its environment.  If ENV is supplied, it is the
     environment in which to evaluate EXP.  Otherwise, EXP must be a
     memoized code object (in which case, its environment is implicit).


File: guile.info,  Node: Evaluator Behaviour,  Prev: Local Evaluation,  Up: Read/Load/Eval

Evaluator Behaviour
===================

   The behaviour of Guile's evaluator can be modified by manipulating
the evaluator options.  For more information about options, *Note User
level options interfaces::.  If you want to know which evaluator
options are available, *Note Evaluator options::.

 - Scheme Procedure: eval-options [setting]
     Display the current settings of the evaluator options.  If SETTING
     is omitted, only a short form of the current evaluator options is
     printed.  Otherwise, SETTING should be one of the following
     symbols:
    `help'
          Display the complete option settings.

    `full'
          Like `help', but also print programmer options.

 - Scheme Procedure: eval-enable option-name
 - Scheme Procedure: eval-disable option-name
 - Scheme Procedure: eval-set! option-name value
     Modify the evaluator options.  `eval-enable' should be used with
     boolean options and switches them on, `eval-disable' switches them
     off.  `eval-set!' can be used to set an option to a specific value.

 - Scheme Procedure: eval-options-interface [setting]
 - C Function: scm_eval_options_interface (setting)
     Option interface for the evaluation options. Instead of using this
     procedure directly, use the procedures `eval-enable',
     `eval-disable', `eval-set!' and `eval-options'.

 - Scheme Procedure: traps [setting]
     Display the current settings of the evaluator traps options.  If
     SETTING is omitted, only a short form of the current evaluator
     traps options is printed.  Otherwise, SETTING should be one of the
     following symbols:
    `help'
          Display the complete option settings.

    `full'
          Like `help', but also print programmer options.

 - Scheme Procedure: trap-enable option-name
 - Scheme Procedure: trap-disable option-name
 - Scheme Procedure: trap-set! option-name value
     Modify the evaluator options.  `trap-enable' should be used with
     boolean options and switches them on, `trap-disable' switches them
     off.  `trap-set!' can be used to set an option to a specific value.

 - Scheme Procedure: evaluator-traps-interface [setting]
 - C Function: scm_evaluator_traps (setting)
     Option interface for the evaluator trap options.


File: guile.info,  Node: Memory Management,  Next: Objects,  Prev: Read/Load/Eval,  Up: Top

Memory Management and Garbage Collection
****************************************

   Guile uses a _garbage collector_ to manage most of its objects.
This means that the memory used to store a Scheme string, say, is
automatically reclaimed when no one is using this string any longer.
This can work because Guile knows enough about its objects at run-time
to be able to trace all references between them.  Thus, it can find all
'live' objects (objects that are still in use) by starting from a known
set of 'root' objects and following the links that these objects have
to other objects, and so on.  The objects that are not reached by this
recursive process can be considered 'dead' and their memory can be
reused for new objects.

   When you are programming in Scheme, you don't need to worry about the
garbage collector.  When programming in C, there are a few rules that
you must follow so that the garbage collector can do its job.

* Menu:

* Garbage Collection::
* Weak References::
* Guardians::


File: guile.info,  Node: Garbage Collection,  Next: Weak References,  Up: Memory Management

Garbage Collection
==================

 - Scheme Procedure: gc
 - C Function: scm_gc ()
     Scans all of SCM objects and reclaims for further use those that
     are no longer accessible.  You normally don't need to call this
     function explicitly.  It is called automatically when appropriate.

 - Scheme Procedure: gc-stats
 - C Function: scm_gc_stats ()
     Return an association list of statistics about Guile's current use
     of storage.

 - Scheme Procedure: object-address obj
 - C Function: scm_object_address (obj)
     Return an integer that for the lifetime of OBJ is uniquely
     returned by this function for OBJ

 - Scheme Procedure: unhash-name name
     Flushes the glocs for NAME, or all glocs if NAME is `#t'.

 - Scheme Procedure: malloc-stats
     Return an alist ((WHAT . N) ...) describing number of malloced
     objects.  WHAT is the second argument to `scm_must_malloc', N is
     the number of objects of that type currently allocated.


File: guile.info,  Node: Weak References,  Next: Guardians,  Prev: Garbage Collection,  Up: Memory Management

Weak References
===============

   [FIXME: This chapter is based on Mikael Djurfeldt's answer to a
question by Michael Livshin. Any mistakes are not theirs, of course. ]

   Weak references let you attach bookkeeping information to data so
that the additional information automatically disappears when the
original data is no longer in use and gets garbage collected. In a weak
key hash, the hash entry for that key disappears as soon as the key is
no longer referenced from anywhere else. For weak value hashes, the
same happens as soon as the value is no longer in use. Entries in a
doubly weak hash disappear when either the key or the value are not
used anywhere else anymore.

   Object properties offer the same kind of functionality as weak key
hashes in many situations. (*note Object Properties::)

   Here's an example (a little bit strained perhaps, but one of the
examples is actually used in Guile):

   Assume that you're implementing a debugging system where you want to
associate information about filename and position of source code
expressions with the expressions themselves.

   Hashtables can be used for that, but if you use ordinary hash tables
it will be impossible for the scheme interpreter to "forget" old source
when, for example, a file is reloaded.

   To implement the mapping from source code expressions to positional
information it is necessary to use weak-key tables since we don't want
the expressions to be remembered just because they are in our table.

   To implement a mapping from source file line numbers to source code
expressions you would use a weak-value table.

   To implement a mapping from source code expressions to the procedures
they constitute a doubly-weak table has to be used.

* Menu:

* Weak key hashes::
* Weak vectors::


File: guile.info,  Node: Weak key hashes,  Next: Weak vectors,  Up: Weak References

Weak key hashes
---------------

 - Scheme Procedure: make-weak-key-hash-table size
 - Scheme Procedure: make-weak-value-hash-table size
 - Scheme Procedure: make-doubly-weak-hash-table size
 - C Function: scm_make_weak_key_hash_table (size)
 - C Function: scm_make_weak_value_hash_table (size)
 - C Function: scm_make_doubly_weak_hash_table (size)
     Return a weak hash table with SIZE buckets. As with any hash
     table, choosing a good size for the table requires some caution.

     You can modify weak hash tables in exactly the same way you would
     modify regular hash tables. (*note Hash Tables::)

 - Scheme Procedure: weak-key-hash-table? obj
 - Scheme Procedure: weak-value-hash-table? obj
 - Scheme Procedure: doubly-weak-hash-table? obj
 - C Function: scm_weak_key_hash_table_p (obj)
 - C Function: scm_weak_value_hash_table_p (obj)
 - C Function: scm_doubly_weak_hash_table_p (obj)
     Return `#t' if OBJ is the specified weak hash table. Note that a
     doubly weak hash table is neither a weak key nor a weak value hash
     table.

 - Scheme Procedure: make-weak-value-hash-table k

 - Scheme Procedure: weak-value-hash-table? x

 - Scheme Procedure: make-doubly-weak-hash-table k

 - Scheme Procedure: doubly-weak-hash-table? x


File: guile.info,  Node: Weak vectors,  Prev: Weak key hashes,  Up: Weak References

Weak vectors
------------

   Weak vectors are mainly useful in Guile's implementation of weak hash
tables.

 - Scheme Procedure: make-weak-vector size [fill]
 - C Function: scm_make_weak_vector (size, fill)
     Return a weak vector with SIZE elements. If the optional argument
     FILL is given, all entries in the vector will be set to FILL. The
     default value for FILL is the empty list.

 - Scheme Procedure: weak-vector . l
 - Scheme Procedure: list->weak-vector l
 - C Function: scm_weak_vector (l)
     Construct a weak vector from a list: `weak-vector' uses the list
     of its arguments while `list->weak-vector' uses its only argument
     L (a list) to construct a weak vector the same way `list->vector'
     would.

 - Scheme Procedure: weak-vector? obj
 - C Function: scm_weak_vector_p (obj)
     Return `#t' if OBJ is a weak vector. Note that all weak hashes are
     also weak vectors.


File: guile.info,  Node: Guardians,  Prev: Weak References,  Up: Memory Management

Guardians
=========

 - Scheme Procedure: make-guardian [greedy?]
 - C Function: scm_make_guardian (greedy_p)
     Create a new guardian.  A guardian protects a set of objects from
     garbage collection, allowing a program to apply cleanup or other
     actions.

     `make-guardian' returns a procedure representing the guardian.
     Calling the guardian procedure with an argument adds the argument
     to the guardian's set of protected objects.  Calling the guardian
     procedure without an argument returns one of the protected objects
     which are ready for garbage collection, or `#f' if no such object
     is available.  Objects which are returned in this way are removed
     from the guardian.

     `make-guardian' takes one optional argument that says whether the
     new guardian should be greedy or sharing.  If there is any chance
     that any object protected by the guardian may be resurrected, then
     you should make the guardian greedy (this is the default).

     See R. Kent Dybvig, Carl Bruggeman, and David Eby (1993)
     "Guardians in a Generation-Based Garbage Collector".  ACM SIGPLAN
     Conference on Programming Language Design and Implementation, June
     1993.

     (the semantics are slightly different at this point, but the paper
     still (mostly) accurately describes the interface).

 - Scheme Procedure: destroy-guardian! guardian
 - C Function: scm_destroy_guardian_x (guardian)
     Destroys GUARDIAN, by making it impossible to put any more objects
     in it or get any objects from it.  It also unguards any objects
     guarded by GUARDIAN.

 - Scheme Procedure: guardian-greedy? guardian
 - C Function: scm_guardian_greedy_p (guardian)
     Return `#t' if GUARDIAN is a greedy guardian, otherwise `#f'.

 - Scheme Procedure: guardian-destroyed? guardian
 - C Function: scm_guardian_destroyed_p (guardian)
     Return `#t' if GUARDIAN has been destroyed, otherwise `#f'.


File: guile.info,  Node: Objects,  Next: Modules,  Prev: Memory Management,  Up: Top

Objects
*******

 - Scheme Procedure: entity? obj
 - C Function: scm_entity_p (obj)
     Return `#t' if OBJ is an entity.

 - Scheme Procedure: operator? obj
 - C Function: scm_operator_p (obj)
     Return `#t' if OBJ is an operator.

 - Scheme Procedure: set-object-procedure! obj proc
 - C Function: scm_set_object_procedure_x (obj, proc)
     Set the object procedure of OBJ to PROC.  OBJ must be either an
     entity or an operator.

 - Scheme Procedure: make-class-object metaclass layout
 - C Function: scm_make_class_object (metaclass, layout)
     Create a new class object of class METACLASS, with the slot layout
     specified by LAYOUT.

 - Scheme Procedure: make-subclass-object class layout
 - C Function: scm_make_subclass_object (class, layout)
     Create a subclass object of CLASS, with the slot layout specified
     by LAYOUT.


File: guile.info,  Node: Modules,  Next: Scheduling,  Prev: Objects,  Up: Top

Modules
*******

   When programs become large, naming conflicts can occur when a
function or global variable defined in one file has the same name as a
function or global variable in another file.  Even just a _similarity_
between function names can cause hard-to-find bugs, since a programmer
might type the wrong function name.

   The approach used to tackle this problem is called _information
encapsulation_, which consists of packaging functional units into a
given name space that is clearly separated from other name spaces.

   The language features that allow this are usually called _the module
system_ because programs are broken up into modules that are compiled
separately (or loaded separately in an interpreter).

   Older languages, like C, have limited support for name space
manipulation and protection.  In C a variable or function is public by
default, and can be made local to a module with the `static' keyword.
But you cannot reference public variables and functions from another
module with different names.

   More advanced module systems have become a common feature in recently
designed languages: ML, Python, Perl, and Modula 3 all allow the
_renaming_ of objects from a foreign module, so they will not clutter
the global name space.

   In addition, Guile offers variables as first-class objects.  They can
be used for interacting with the module system.

* Menu:

* provide and require::         The SLIB feature mechanism.
* Environments::                R5RS top-level environments.
* The Guile module system::     How Guile does it.
* Dynamic Libraries::           Loading libraries of compiled code at run time.
* Variables::                   First-class variables.


File: guile.info,  Node: provide and require,  Next: Environments,  Up: Modules

provide and require
===================

   Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
implemented a provide/require mechanism for many Scheme implementations.
Library files in SLIB _provide_ a feature, and when user programs
_require_ that feature, the library file is loaded in.

   For example, the file `random.scm' in the SLIB package contains the
line

     (provide 'random)

   so to use its procedures, a user would type

     (require 'random)

   and they would magically become available, _but still have the same
names!_  So this method is nice, but not as good as a full-featured
module system.

   When SLIB is used with Guile, provide and require can be used to
access its facilities.


File: guile.info,  Node: Environments,  Next: The Guile module system,  Prev: provide and require,  Up: Modules

Environments
============

   Scheme, as defined in R5RS, does _not_ have a full module system.
However it does define the concept of a top-level "environment".  Such
an environment maps identifiers (symbols) to Scheme objects such as
procedures and lists: *Note About Closure::.  In other words, it
implements a set of "bindings".

   Environments in R5RS can be passed as the second argument to `eval'
(*note Fly Evaluation::).  Three procedures are defined to return
environments: `scheme-report-environment', `null-environment' and
`interaction-environment' (*note Fly Evaluation::).

   In addition, in Guile any module can be used as an R5RS environment,
i.e., passed as the second argument to `eval'.

 - Scheme Procedure: scheme-report-environment version
 - Scheme Procedure: null-environment version
     VERSION must be the exact integer `5', corresponding to revision 5
     of the Scheme report (the Revised^5 Report on Scheme).
     `scheme-report-environment' returns a specifier for an environment
     that is empty except for all bindings defined in the report that
     are either required or both optional and supported by the
     implementation. `null-environment' returns a specifier for an
     environment that is empty except for the (syntactic) bindings for
     all syntactic keywords defined in the report that are either
     required or both optional and supported by the implementation.

     Currently Guile does not support values of VERSION for other
     revisions of the report.

     The effect of assigning (through the use of `eval') a variable
     bound in a `scheme-report-environment' (for example `car') is
     unspecified.  Currently the environments specified by
     `scheme-report-environment' are not immutable in Guile.


File: guile.info,  Node: The Guile module system,  Next: Dynamic Libraries,  Prev: Environments,  Up: Modules

The Guile module system
=======================

   The Guile module system extends the concept of environments,
discussed in the previous section, with mechanisms to define, use and
customise sets of bindings.

   In 1996 Tom Lord implemented a full-featured module system for Guile
which allows loading Scheme source files into a private name space.
This system has been in available since at least Guile version 1.1.

   For Guile version 1.5.0 and later, the system has been improved to
have better integration from C code, more fine-grained user control
over interfaces, and documentation.

   Although it is anticipated that the module system implementation will
change in the future, the Scheme programming interface described in this
manual should be considered stable.  The C programming interface is
considered relatively stable, although at the time of this writing,
there is still some flux.

* Menu:

* General Information about Modules::  Guile module basics.
* Using Guile Modules::         How to use existing modules.
* Creating Guile Modules::      How to package your code into modules.
* Module System Quirks::        Strange things to be aware of.
* Included Guile Modules::      Which modules come with Guile?
* Accessing Modules from C::    How to work with modules with C code.


File: guile.info,  Node: General Information about Modules,  Next: Using Guile Modules,  Up: The Guile module system

General Information about Modules
---------------------------------

   A Guile module can be thought of as a collection of named procedures,
variables and macros.  More precisely, it is a set of "bindings" of
symbols (names) to Scheme objects.

   An environment is a mapping from identifiers (or symbols) to
locations, i.e., a set of bindings.  There are top-level environments
and lexical environments.  The environment in which a lambda is
executed is remembered as part of its definition.

   Within a module, all bindings are visible.  Certain bindings can be
declared "public", in which case they are added to the module's
so-called "export list"; this set of public bindings is called the
module's "public interface" (*note Creating Guile Modules::).

   A client module "uses" a providing module's bindings by either
accessing the providing module's public interface, or by building a
custom interface (and then accessing that).  In a custom interface, the
client module can "select" which bindings to access and can also
algorithmically "rename" bindings.  In contrast, when using the
providing module's public interface, the entire export list is available
without renaming (*note Using Guile Modules::).

   To use a module, it must be found and loaded.  All Guile modules
have a unique "module name", which is a list of one or more symbols.
Examples are `(ice-9 popen)' or `(srfi srfi-11)'.  When Guile searches
for the code of a module, it constructs the name of the file to load by
concatenating the name elements with slashes between the elements and
appending a number of file name extensions from the list
`%load-extensions' (*note Loading::).  The resulting file name is then
searched in all directories in the variable `%load-path' (*note Build
Config::).  For example, the `(ice-9 popen)' module would result in the
filename `ice-9/popen.scm' and searched in the installation directories
of Guile and in all other directories in the load path.

   Every module has a so-called syntax transformer associated with it.
This is a procedure which performs all syntax transformation for the
time the module is read in and evaluated.  When working with modules,
you can manipulate the current syntax transformer using the
`use-syntax' syntactic form or the `#:use-syntax' module definition
option (*note Creating Guile Modules::).

   Please note that there are some problems with the current module
system you should keep in mind (*note Module System Quirks::).  We hope
to address these eventually.


File: guile.info,  Node: Using Guile Modules,  Next: Creating Guile Modules,  Prev: General Information about Modules,  Up: The Guile module system

Using Guile Modules
-------------------

   To use a Guile module is to access either its public interface or a
custom interface (*note General Information about Modules::).  Both
types of access are handled by the syntactic form `use-modules', which
accepts one or more interface specifications and, upon evaluation,
arranges for those interfaces to be available to the current module.
This process may include locating and loading code for a given module if
that code has not yet been loaded, following %load-path (*note Build
Config::).

   An "interface specification" has one of two forms.  The first
variation is simply to name the module, in which case its public
interface is the one accessed.  For example:

     (use-modules (ice-9 popen))

   Here, the interface specification is `(ice-9 popen)', and the result
is that the current module now has access to `open-pipe', `close-pipe',
`open-input-pipe', and so on (*note Included Guile Modules::).

   Note in the previous example that if the current module had already
defined `open-pipe', that definition would be overwritten by the
definition in `(ice-9 popen)'.  For this reason (and others), there is
a second variation of interface specification that not only names a
module to be accessed, but also selects bindings from it and renames
them to suit the current module's needs.  For example:

     (use-modules ((ice-9 popen)
                   :select ((open-pipe . pipe-open) close-pipe)
                   :renamer (symbol-prefix-proc 'unixy:)))

   Here, the interface specification is more complex than before, and
the result is that a custom interface with only two bindings is created
and subsequently accessed by the current module.  The mapping of old to
new names is as follows:

     (ice-9 popen) sees:             current module sees:
     open-pipe                       unixy:pipe-open
     close-pipe                      unixy:close-pipe

   This example also shows how to use the convenience procedure
`symbol-prefix-proc'.

 - Scheme Procedure: symbol-prefix-proc prefix-sym
     Return a procedure that prefixes its arg (a symbol) with
     PREFIX-SYM.

 - syntax: use-modules spec ...
     Resolve each interface specification SPEC into an interface and
     arrange for these to be accessible by the current module.  The
     return value is unspecified.

     SPEC can be a list of symbols, in which case it names a module
     whose public interface is found and used.

     SPEC can also be of the form:

           (MODULE-NAME [:select SELECTION] [:renamer RENAMER])

     in which case a custom interface is newly created and used.
     MODULE-NAME is a list of symbols, as above; SELECTION is a list of
     selection-specs; and RENAMER is a procedure that takes a symbol
     and returns its new name.  A selection-spec is either a symbol or
     a pair of symbols `(ORIG . SEEN)', where ORIG is the name in the
     used module and SEEN is the name in the using module.  Note that
     SEEN is also passed through RENAMER.

     The `:select' and `:renamer' clauses are optional.  If both are
     omitted, the returned interface has no bindings.  If the `:select'
     clause is omitted, RENAMER operates on the used module's public
     interface.

     Signal error if module name is not resolvable.

 - syntax: use-syntax module-name
     Load the module `module-name' and use its system transformer as
     the system transformer for the currently defined module, as well
     as installing it as the current system transformer.


File: guile.info,  Node: Creating Guile Modules,  Next: Module System Quirks,  Prev: Using Guile Modules,  Up: The Guile module system

Creating Guile Modules
----------------------

   When you want to create your own modules, you have to take the
following steps:

   * Create a Scheme source file and add all variables and procedures
     you wish to export, or which are required by the exported
     procedures.

   * Add a `define-module' form at the beginning.

   * Export all bindings which should be in the public interface, either
     by using `define-public' or `export' (both documented below).

 - syntax: define-module module-name [options ...]
     MODULE-NAME is of the form `(hierarchy file)'.  One example of
     this is

          (define-module (ice-9 popen))

     `define-module' makes this module available to Guile programs under
     the given MODULE-NAME.

     The OPTIONS are keyword/value pairs which specify more about the
     defined module.  The recognized options and their meaning is shown
     in the following table.

    `#:use-module INTERFACE-SPECIFICATION'
          Equivalent to a `(use-modules INTERFACE-SPECIFICATION)'
          (*note Using Guile Modules::).

    `#:use-syntax MODULE'
          Use MODULE when loading the currently defined module, and
          install it as the syntax transformer.

    `#:autoload MODULE SYMBOL'
          Load MODULE whenever SYMBOL is accessed.

    `#:export LIST'
          Export all identifiers in LIST, which must be a list of
          symbols.  This is equivalent to `(export LIST)' in the module
          body.

    `#:no-backtrace'
          Tell Guile not to record information for procedure backtraces
          when executing the procedures in this module.

    `#:pure'
          Create a "pure" module, that is a module which does not
          contain any of the standard procedure bindings except for the
          syntax forms.  This is useful if you want to create "safe"
          modules, that is modules which do not know anything about
          dangerous procedures.


 - syntax: export variable ...
     Add all VARIABLEs (which must be symbols) to the list of exported
     bindings of the current module.

 - syntax: define-public ...
     Equivalent to `(begin (define foo ...) (export foo))'.


File: guile.info,  Node: Module System Quirks,  Next: Included Guile Modules,  Prev: Creating Guile Modules,  Up: The Guile module system

Module System Quirks
--------------------

   Although the programming interfaces are relatively stable, the Guile
module system itself is still evolving.  Here are some situations where
usage surpasses design.

   * When using a module which exports a macro definition, the other
     module must export all bindings the macro expansion uses, too,
     because the expanded code would otherwise not be able to see these
     definitions and issue a "variable unbound" error, or worse, would
     use another binding which might be present in the scope of the
     expansion.

   * When two or more used modules export bindings with the same names,
     the last accessed module wins, and the exported binding of that
     last module will silently be used.  This might lead to
     hard-to-find errors because wrong procedures or variables are
     used.  To avoid this kind of "name-clash" situation, use a custom
     interface specification (*note Using Guile Modules::).  (We
     include this entry for the possible benefit of users of Guile
     versions previous to 1.5.0, when custom interfaces were added to
     the module system.)

   * [Add other quirks here.]



File: guile.info,  Node: Included Guile Modules,  Next: Accessing Modules from C,  Prev: Module System Quirks,  Up: The Guile module system

Included Guile Modules
----------------------

   Some modules are included in the Guile distribution; here are
references to the entries in this manual which describe them in more
detail:

*boot-9*
     boot-9 is Guile's initialization module, and it is always loaded
     when Guile starts up.

*(ice-9 debug)*
     Mikael Djurfeldt's source-level debugging support for Guile (*note
     Debugging Features::).

*(ice-9 threads)*
     Guile's support for multi threaded execution (*note Scheduling::).

*(ice-9 rdelim)*
     Line- and character-delimited input (*note Line/Delimited::).

*(ice-9 rw)*
     Block string input/output (*note Block Reading and Writing::).

*(ice-9 documentation)*
     Online documentation (REFFIXME).

*(srfi srfi-1)*
     A library providing a lot of useful list and pair processing
     procedures (*note SRFI-1::).

*(srfi srfi-2)*
     Support for `and-let*' (*note SRFI-2::).

*(srfi srfi-4)*
     Support for homogeneous numeric vectors (*note SRFI-4::).

*(srfi srfi-6)*
     Support for some additional string port procedures (*note
     SRFI-6::).

*(srfi srfi-8)*
     Multiple-value handling with `receive' (*note SRFI-8::).

*(srfi srfi-9)*
     Record definition with `define-record-type' (*note SRFI-9::).

*(srfi srfi-10)*
     Read hash extension `#,()' (*note SRFI-10::).

*(srfi srfi-11)*
     Multiple-value handling with `let-values' and `let-values*' (*note
     SRFI-11::).

*(srfi srfi-13)*
     String library (*note SRFI-13::).

*(srfi srfi-14)*
     Character-set library (*note SRFI-14::).

*(srfi srfi-17)*
     Getter-with-setter support (*note SRFI-17::).

*(ice-9 slib)*
     This module contains hooks for using Aubrey Jaffer's portable
     Scheme library SLIB from Guile (*note SLIB::).

*(ice-9 jacal)*
     This module contains hooks for using Aubrey Jaffer's symbolic math
     package Jacal from Guile (*note JACAL::).


File: guile.info,  Node: Accessing Modules from C,  Prev: Included Guile Modules,  Up: The Guile module system

Accessing Modules from C
------------------------

   The last sections have described how modules are used in Scheme code,
which is the recommended way of creating and accessing modules.  You
can also work with modules from C, but it is more cumbersome.

   The following procedures are available.

 - C Procedure: SCM scm_current_module ()
     Return the module that is the _current module_.

 - C Procedure: SCM scm_set_current_module (SCM MODULE)
     Set the current module to MODULE and return the previous current
     module.

 - C Procedure: SCM scm_c_call_with_current_module (SCM MODULE, SCM
          (*FUNC)(void *), void *DATA)
     Call FUNC and make MODULE the current module during the call.  The
     argument DATA is passed to FUNC.  The return value of
     `scm_c_call_with_current_module' is the return value of FUNC.

 - C Procedure: SCM scm_c_lookup (const char *NAME)
     Return the variable bound to the symbol indicated by NAME in the
     current module.  If there is no such binding or the symbol is not
     bound to a variable, signal an error.

 - C Procedure: SCM scm_lookup (SCM NAME)
     Like `scm_c_lookup', but the symbol is specified directly.

 - C Procedure: SCM scm_c_module_lookup (SCM MODULE, const char *NAME)
 - C Procedure: SCM scm_module_lookup (SCM MODULE, SCM NAME)
     Like `scm_c_lookup' and `scm_lookup', but the specified module is
     used instead of the current one.

 - C Procedure: SCM scm_c_define (const char *NAME, SCM VAL)
     Bind the symbol indicated by NAME to a variable in the current
     module and set that variable to VAL.  When NAME is already bound
     to a variable, use that.  Else create a new variable.

 - C Procedure: SCM scm_define (SCM NAME, SCM VAL)
     Like `scm_c_define', but the symbol is specified directly.

 - C Procedure: SCM scm_c_module_define (SCM MODULE, const char *NAME,
          SCM VAL)
 - C Procedure: SCM scm_module_define (SCM MODULE, SCM NAME, SCM VAL)
     Like `scm_c_define' and `scm_define', but the specified module is
     used instead of the current one.

 - C Procedure: SCM scm_module_reverse_lookup (SCM MODULE, SCM VARIABLE)
     Find the symbol that is bound to VARIABLE in MODULE.  When no such
     binding is found, return #F.

 - C Procedure: SCM scm_c_define_module (const char *NAME, void
          (*INIT)(void *), void *DATA)
     Define a new module named NAME and make it current while INIT is
     called, passing it DATA.  Return the module.

     The parameter NAME is a string with the symbols that make up the
     module name, separated by spaces.  For example, `"foo bar"' names
     the module `(foo bar)'.

     When there already exists a module named NAME, it is used
     unchanged, otherwise, an empty module is created.

 - C Procedure: SCM scm_c_resolve_module (const char *NAME)
     Find the module name NAME and return it.  When it has not already
     been defined, try to auto-load it.  When it can't be found that
     way either, create an empty module.  The name is interpreted as
     for `scm_c_define_module'.

 - C Procedure: SCM scm_resolve_module (SCM NAME)
     Like `scm_c_resolve_module', but the name is given as a real list
     of symbols.

 - C Procedure: SCM scm_c_use_module (const char *NAME)
     Add the module named NAME to the uses list of the current module,
     as with `(use-modules NAME)'.  The name is interpreted as for
     `scm_c_define_module'.

 - C Procedure: SCM scm_c_export (const char *NAME, ...)
     Add the bindings designated by NAME, ... to the public interface
     of the current module.  The list of names is terminated by `NULL'.


File: guile.info,  Node: Dynamic Libraries,  Next: Variables,  Prev: The Guile module system,  Up: Modules

Dynamic Libraries
=================

   Most modern Unices have something called "shared libraries".  This
ordinarily means that they have the capability to share the executable
image of a library between several running programs to save memory and
disk space.  But generally, shared libraries give a lot of additional
flexibility compared to the traditional static libraries.  In fact,
calling them `dynamic' libraries is as correct as calling them `shared'.

   Shared libraries really give you a lot of flexibility in addition to
the memory and disk space savings.  When you link a program against a
shared library, that library is not closely incorporated into the final
executable.  Instead, the executable of your program only contains
enough information to find the needed shared libraries when the program
is actually run.  Only then, when the program is starting, is the final
step of the linking process performed.  This means that you need not
recompile all programs when you install a new, only slightly modified
version of a shared library.  The programs will pick up the changes
automatically the next time they are run.

   Now, when all the necessary machinery is there to perform part of the
linking at run-time, why not take the next step and allow the programmer
to explicitly take advantage of it from within his program?  Of course,
many operating systems that support shared libraries do just that, and
chances are that Guile will allow you to access this feature from within
your Scheme programs.  As you might have guessed already, this feature
is called "dynamic linking".(1)

   As with many aspects of Guile, there is a low-level way to access the
dynamic linking apparatus, and a more high-level interface that
integrates dynamically linked libraries into the module system.

* Menu:

* Low level dynamic linking::
* Extensions::

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

   (1) Some people also refer to the final linking stage at program
startup as `dynamic linking', so if you want to make yourself perfectly
clear, it is probably best to use the more technical term "dlopening",
as suggested by Gordon Matzigkeit in his libtool documentation.


File: guile.info,  Node: Low level dynamic linking,  Next: Extensions,  Up: Dynamic Libraries

Low level dynamic linking
-------------------------

   When using the low level procedures to do your dynamic linking, you
have complete control over which library is loaded when and what gets
done with it.

 - Scheme Procedure: dynamic-link library
 - C Function: scm_dynamic_link (library)
     Find the shared library denoted by LIBRARY (a string) and link it
     into the running Guile application.  When everything works out,
     return a Scheme object suitable for representing the linked object
     file.  Otherwise an error is thrown.  How object files are
     searched is system dependent.

     Normally, LIBRARY is just the name of some shared library file
     that will be searched for in the places where shared libraries
     usually reside, such as in `/usr/lib' and `/usr/local/lib'.

 - Scheme Procedure: dynamic-object? obj
 - C Function: scm_dynamic_object_p (obj)
     Return `#t' if OBJ is a dynamic library handle, or `#f' otherwise.

 - Scheme Procedure: dynamic-unlink dobj
 - C Function: scm_dynamic_unlink (dobj)
     Unlink the indicated object file from the application.  The
     argument DOBJ must have been obtained by a call to `dynamic-link'.
     After `dynamic-unlink' has been called on DOBJ, its content is no
     longer accessible.

 - Scheme Procedure: dynamic-func name dobj
 - C Function: scm_dynamic_func (name, dobj)
     Search the dynamic object DOBJ for the C function indicated by the
     string NAME and return some Scheme handle that can later be used
     with `dynamic-call' to actually call the function.

     Regardless whether your C compiler prepends an underscore `_' to
     the global names in a program, you should *not* include this
     underscore in FUNCTION.  Guile knows whether the underscore is
     needed or not and will add it when necessary.

 - Scheme Procedure: dynamic-call func dobj
 - C Function: scm_dynamic_call (func, dobj)
     Call the C function indicated by FUNC and DOBJ.  The function is
     passed no arguments and its return value is ignored.  When
     FUNCTION is something returned by `dynamic-func', call that
     function and ignore DOBJ.  When FUNC is a string , look it up in
     DYNOBJ; this is equivalent to
          (dynamic-call (dynamic-func FUNC DOBJ) #f)

     Interrupts are deferred while the C function is executing (with
     `SCM_DEFER_INTS'/`SCM_ALLOW_INTS').

 - Scheme Procedure: dynamic-args-call func dobj args
 - C Function: scm_dynamic_args_call (func, dobj, args)
     Call the C function indicated by FUNC and DOBJ, just like
     `dynamic-call', but pass it some arguments and return its return
     value.  The C function is expected to take two arguments and
     return an `int', just like `main':
          int c_func (int argc, char **argv);

     The parameter ARGS must be a list of strings and is converted into
     an array of `char *'.  The array is passed in ARGV and its size in
     ARGC.  The return value is converted to a Scheme number and
     returned from the call to `dynamic-args-call'.

   When dynamic linking is disabled or not supported on your system,
the above functions throw errors, but they are still available.

   Here is a small example that works on GNU/Linux:

     (define libc-obj (dynamic-link "libc.so"))
     libc-obj
     => #<dynamic-object "libc.so">
     (dynamic-args-call 'rand libc-obj '())
     => 269167349
     (dynamic-unlink libc-obj)
     libc-obj
     => #<dynamic-object "libc.so" (unlinked)>

   As you can see, after calling `dynamic-unlink' on a dynamically
linked library, it is marked as `(unlinked)' and you are no longer able
to use it with `dynamic-call', etc.  Whether the library is really
removed from you program is system-dependent and will generally not
happen when some other parts of your program still use it.  In the
example above, `libc' is almost certainly not removed from your program
because it is badly needed by almost everything.

   The functions to call a function from a dynamically linked library,
`dynamic-call' and `dynamic-args-call', are not very powerful.  They
are mostly intended to be used for calling specially written
initialization functions that will then add new primitives to Guile.
For example, we do not expect that you will dynamically link `libX11'
with `dynamic-link' and then construct a beautiful graphical user
interface just by using `dynamic-call' and `dynamic-args-call'.
Instead, the usual way would be to write a special Guile<->X11 glue
library that has intimate knowledge about both Guile and X11 and does
whatever is necessary to make them inter-operate smoothly.  This glue
library could then be dynamically linked into a vanilla Guile
interpreter and activated by calling its initialization function.  That
function would add all the new types and primitives to the Guile
interpreter that it has to offer.

   From this setup the next logical step is to integrate these glue
libraries into the module system of Guile so that you can load new
primitives into a running system just as you can load new Scheme code.

   There is, however, another possibility to get a more thorough access
to the functions contained in a dynamically linked library.  Anthony
Green has written `libffi', a library that implements a "foreign
function interface" for a number of different platforms.  With it, you
can extend the Spartan functionality of `dynamic-call' and
`dynamic-args-call' considerably.  There is glue code available in the
Guile contrib archive to make `libffi' accessible from Guile.


File: guile.info,  Node: Extensions,  Prev: Low level dynamic linking,  Up: Dynamic Libraries

Writing Dynamically Loadable Extensions
---------------------------------------

   XXX - document `load-extension', `scm_register_extension'


File: guile.info,  Node: Variables,  Prev: Dynamic Libraries,  Up: Modules

Variables
=========

   Each module has its own hash table, sometimes known as an "obarray",
that maps the names defined in that module to their corresponding
variable objects.

   A variable is a box-like object that can hold any Scheme value.  It
is said to be "undefined" if its box holds a special Scheme value that
denotes undefined-ness (which is different from all other Scheme values,
including for example `#f'); otherwise the variable is "defined".

   On its own, a variable object is anonymous.  A variable is said to be
"bound" when it is associated with a name in some way, usually a symbol
in a module obarray.  When this happens, the relationship is mutual:
the variable is bound to the name (in that module), and the name (in
that module) is bound to the variable.

   (That's the theory, anyway.  In practice, defined-ness and bound-ness
sometimes get confused, because Lisp and Scheme implementations have
often conflated -- or deliberately drawn no distinction between -- a
name that is unbound and a name that is bound to a variable whose value
is undefined.  We will try to be clear about the difference and explain
any confusion where it is unavoidable.)

   Variables do not have a read syntax.  Most commonly they are created
and bound implicitly by `define' expressions: a top-level `define'
expression of the form

     (define NAME VALUE)

creates a variable with initial value VALUE and binds it to the name
NAME in the current module.  But they can also be created dynamically
by calling one of the constructor procedures `make-variable' and
`make-undefined-variable'.

   First-class variables are especially useful for interacting with the
current module system (*note The Guile module system::).

 - Scheme Procedure: make-undefined-variable
 - C Function: scm_make_undefined_variable ()
     Return a variable that is initially unbound.

 - Scheme Procedure: make-variable init
 - C Function: scm_make_variable (init)
     Return a variable initialized to value INIT.

 - Scheme Procedure: variable-bound? var
 - C Function: scm_variable_bound_p (var)
     Return `#t' iff VAR is bound to a value.  Throws an error if VAR
     is not a variable object.

 - Scheme Procedure: variable-ref var
 - C Function: scm_variable_ref (var)
     Dereference VAR and return its value.  VAR must be a variable
     object; see `make-variable' and `make-undefined-variable'.

 - Scheme Procedure: variable-set! var val
 - C Function: scm_variable_set_x (var, val)
     Set the value of the variable VAR to VAL.  VAR must be a variable
     object, VAL can be any value. Return an unspecified value.

 - Scheme Procedure: variable? obj
 - C Function: scm_variable_p (obj)
     Return `#t' iff OBJ is a variable object, else return `#f'.


File: guile.info,  Node: Scheduling,  Next: Options and Config,  Prev: Modules,  Up: Top

Threads, Mutexes, Asyncs and Dynamic Roots
******************************************

   [FIXME: This is pasted in from Tom Lord's original guile.texi chapter
plus the Cygnus programmer's manual; it should be *very* carefully
reviewed and largely reorganized.]

* Menu:

* Arbiters::            Synchronization primitives.
* Asyncs::              Asynchronous procedure invocation.
* Dynamic Roots::       Root frames of execution.
* Threads::             Multiple threads of execution.
* Fluids::              Dynamically scoped variables.


File: guile.info,  Node: Arbiters,  Next: Asyncs,  Up: Scheduling

Arbiters
========

   Arbiters are synchronization objects.  They are created with
`make-arbiter'.  Two or more threads can synchronize on an arbiter by
trying to lock it using `try-arbiter'.  This call will succeed if no
other thread has called `try-arbiter' on the arbiter yet, otherwise it
will fail and return `#f'.  Once an arbiter is successfully locked, it
cannot be locked by another thread until the thread holding the arbiter
calls `release-arbiter' to unlock it.

 - Scheme Procedure: make-arbiter name
 - C Function: scm_make_arbiter (name)
     Return an object of type arbiter and name NAME. Its state is
     initially unlocked.  Arbiters are a way to achieve process
     synchronization.

 - Scheme Procedure: try-arbiter arb
 - C Function: scm_try_arbiter (arb)
     Return `#t' and lock the arbiter ARB if the arbiter was unlocked.
     Otherwise, return `#f'.

 - Scheme Procedure: release-arbiter arb
 - C Function: scm_release_arbiter (arb)
     Return `#t' and unlock the arbiter ARB if the arbiter was locked.
     Otherwise, return `#f'.


File: guile.info,  Node: Asyncs,  Next: Dynamic Roots,  Prev: Arbiters,  Up: Scheduling

Asyncs
======

   An async is a pair of one thunk (a parameterless procedure) and a
mark.  Setting the mark on an async guarantees that the thunk will be
executed somewhen in the future ("asynchronously").  Setting the mark
more than once is satisfied by one execution of the thunk.

   Guile supports two types of asyncs: Normal asyncs and system asyncs.
They differ in that marked system asyncs are executed implicitly as soon
as possible, whereas normal asyncs have to be invoked explicitly.
System asyncs are held in an internal data structure and are maintained
by Guile.

   Normal asyncs are created with `async', system asyncs with
`system-async'.  They are marked with `async-mark' or
`system-async-mark', respectively.

 - Scheme Procedure: async thunk
 - C Function: scm_async (thunk)
     Create a new async for the procedure THUNK.

 - Scheme Procedure: system-async thunk
 - C Function: scm_system_async (thunk)
     Create a new async for the procedure THUNK.  Also add it to the
     system's list of active async objects.

 - Scheme Procedure: async-mark a
 - C Function: scm_async_mark (a)
     Mark the async A for future execution.

 - Scheme Procedure: system-async-mark a
 - C Function: scm_system_async_mark (a)
     Mark the async A for future execution.

   As already mentioned above, system asyncs are executed automatically.
Normal asyncs have to be explicitly invoked by storing one or more of
them into a list and passing them to `run-asyncs'.

 - Scheme Procedure: run-asyncs list_of_a
 - C Function: scm_run_asyncs (list_of_a)
     Execute all thunks from the asyncs of the list LIST_OF_A.

   Automatic invocation of system asyncs can be temporarily disabled by
calling `mask-signals' and `unmask-signals'.  Setting the mark while
async execution is disabled will nevertheless cause the async to run
once execution is enabled again.  Please note that calls to these
procedures should always be paired, and they must not be nested, e.g. no
`mask-signals' is allowed if another one is still active.

 - Scheme Procedure: mask-signals
 - C Function: scm_mask_signals ()
     Mask signals. The returned value is not specified.

 - Scheme Procedure: unmask-signals
 - C Function: scm_unmask_signals ()
     Unmask signals. The returned value is not specified.

 - Scheme Procedure: noop . args
 - C Function: scm_noop (args)
     Do nothing.  When called without arguments, return `#f', otherwise
     return the first argument.


File: guile.info,  Node: Dynamic Roots,  Next: Threads,  Prev: Asyncs,  Up: Scheduling

Dynamic Roots
=============

   A "dynamic root" is a root frame of Scheme evaluation.  The
top-level repl, for example, is an instance of a dynamic root.

   Each dynamic root has its own chain of dynamic-wind information.
Each has its own set of continuations, jump-buffers, and pending CATCH
statements which are inaccessible from the dynamic scope of any other
dynamic root.

   In a thread-based system, each thread has its own dynamic root.
Therefore, continuations created by one thread may not be invoked by
another.

   Even in a single-threaded system, it is sometimes useful to create a
new dynamic root.  For example, if you want to apply a procedure, but to
not allow that procedure to capture the current continuation, calling
the procedure under a new dynamic root will do the job.

 - Scheme Procedure: call-with-dynamic-root thunk handler
 - C Function: scm_call_with_dynamic_root (thunk, handler)
     Evaluate `(thunk)' in a new dynamic context, returning its value.

     If an error occurs during evaluation, apply HANDLER to the
     arguments to the throw, just as `throw' would.  If this happens,
     HANDLER is called outside the scope of the new root - it is called
     in the same dynamic context in which `call-with-dynamic-root' was
     evaluated.

     If THUNK captures a continuation, the continuation is rooted at
     the call to THUNK.  In particular, the call to
     `call-with-dynamic-root' is not captured.  Therefore,
     `call-with-dynamic-root' always returns at most one time.

     Before calling THUNK, the dynamic-wind chain is un-wound back to
     the root and a new chain started for THUNK.  Therefore, this call
     may not do what you expect:

          ;; Almost certainly a bug:
          (with-output-to-port
           some-port
          
           (lambda ()
             (call-with-dynamic-root
              (lambda ()
                (display 'fnord)
                (newline))
              (lambda (errcode) errcode))))

     The problem is, on what port will `fnord' be displayed?  You might
     expect that because of the `with-output-to-port' that it will be
     displayed on the port bound to `some-port'.  But it probably won't
     - before evaluating the thunk, dynamic winds are unwound,
     including those created by `with-output-to-port'.  So, the
     standard output port will have been re-set to its default value
     before `display' is evaluated.

     (This function was added to Guile mostly to help calls to
     functions in C libraries that can not tolerate non-local exits or
     calls that return multiple times.  If such functions call back to
     the interpreter, it should be under a new dynamic root.)

 - Scheme Procedure: dynamic-root
 - C Function: scm_dynamic_root ()
     Return an object representing the current dynamic root.

     These objects are only useful for comparison using `eq?'.  They
     are currently represented as numbers, but your code should in no
     way depend on this.

 - Scheme Procedure: quit [exit_val]
     Throw back to the error handler of the current dynamic root.

     If integer EXIT_VAL is specified and if Guile is being used
     stand-alone and if quit is called from the initial dynamic-root,
     EXIT_VAL becomes the exit status of the Guile process and the
     process exits.

   When Guile is run interactively, errors are caught from within the
read-eval-print loop.  An error message will be printed and `abort'
called.  A default set of signal handlers is installed, e.g., to allow
user interrupt of the interpreter.

   It is possible to switch to a "batch mode", in which the interpreter
will terminate after an error and in which all signals cause their
default actions.  Switching to batch mode causes any handlers installed
from Scheme code to be removed.  An example of where this is useful is
after forking a new process intended to run non-interactively.

 - Scheme Procedure: batch-mode?
     Returns a boolean indicating whether the interpreter is in batch
     mode.

 - Scheme Procedure: set-batch-mode?! arg
     If ARG is true, switches the interpreter to batch mode.  The `#f'
     case has not been implemented.


File: guile.info,  Node: Threads,  Next: Fluids,  Prev: Dynamic Roots,  Up: Scheduling

Threads
=======

   *[NOTE: this chapter was written for Cygnus Guile and has not yet
been updated for the Guile 1.x release.]*

   Here is a the reference for Guile's threads.  In this chapter I
simply quote verbatim Tom Lord's description of the low-level primitives
written in C (basically an interface to the POSIX threads library) and
Anthony Green's description of the higher-level thread procedures
written in scheme.

   When using Guile threads, keep in mind that each guile thread is
executed in a new dynamic root.

* Menu:

* Low level thread primitives::
* Higher level thread procedures::


File: guile.info,  Node: Low level thread primitives,  Next: Higher level thread procedures,  Up: Threads

Low level thread primitives
---------------------------

 - Scheme Procedure: call-with-new-thread thunk error-handler
     Evaluate `(thunk)' in a new thread, and new dynamic context,
     returning a new thread object representing the thread.

     If an error occurs during evaluation, call error-handler, passing
     it an error code describing the condition.  [Error codes are
     currently meaningless integers.  In the future, real values will
     be specified.]  If this happens, the error-handler is called
     outside the scope of the new root - it is called in the same
     dynamic context in which with-new-thread was evaluated, but not in
     the caller's thread.

     All the evaluation rules for dynamic roots apply to threads.

 - Scheme Procedure: join-thread thread
     Suspend execution of the calling thread until the target THREAD
     terminates, unless the target THREAD has already terminated.

 - Scheme Procedure: yield
     If one or more threads are waiting to execute, calling yield
     forces an immediate context switch to one of them. Otherwise,
     yield has no effect.

 - Scheme Procedure: make-mutex
     Create a new mutex object.

 - Scheme Procedure: lock-mutex mutex
     Lock MUTEX. If the mutex is already locked, the calling thread
     blocks until the mutex becomes available. The function returns when
     the calling thread owns the lock on MUTEX.

 - Scheme Procedure: unlock-mutex mutex
     Unlocks MUTEX if the calling thread owns the lock on MUTEX.
     Calling unlock-mutex on a mutex not owned by the current thread
     results in undefined behaviour. Once a mutex has been unlocked,
     one thread blocked on MUTEX is awakened and grabs the mutex lock.

 - Scheme Procedure: make-condition-variable

 - Scheme Procedure: wait-condition-variable cond-var mutex

 - Scheme Procedure: signal-condition-variable cond-var


File: guile.info,  Node: Higher level thread procedures,  Prev: Low level thread primitives,  Up: Threads

Higher level thread procedures
------------------------------

   Higher level thread procedures are available by loading the `(ice-9
threads)' module.  These provide standardized thread creation and mutex
interaction.

 - Scheme Procedure: %thread-handler tag args...
     This procedure is specified as the standard error-handler for
     `make-thread' and `begin-thread'.  If the number of ARGS is three
     or more, use `display-error', otherwise display a message
     "uncaught throw to TAG".  All output is sent to the port specified
     by `current-error-port'.

     Before display, global var `the-last-stack' is set to `#f' and
     signals are unmasked with `unmask-signals'.

     [FIXME: Why distinguish based on number of args?!  Cue voodoo
     music here.]

 - macro: make-thread proc [args...]
     Apply PROC to ARGS in a new thread formed by
     `call-with-new-thread' using `%thread-handler' as the error
     handler.

 - macro: begin-thread first [rest...]
     Evaluate forms FIRST and REST in a new thread formed by
     `call-with-new-thread' using `%thread-handler' as the error
     handler.

 - macro: with-mutex m [body...]
     Lock mutex M, evaluate BODY, and then unlock M.  These
     sub-operations form the branches of a `dynamic-wind'.

 - macro: monitor first [rest...]
     Evaluate forms FIRST and REST under a newly created anonymous
     mutex, using `with-mutex'.

     [FIXME: Is there any way to access the mutex?]


File: guile.info,  Node: Fluids,  Prev: Threads,  Up: Scheduling

Fluids
======

   Fluids are objects to store values in.  They have a few properties
which make them useful in certain situations: Fluids can have one value
per dynamic root (*note Dynamic Roots::), so that changes to the value
in a fluid are only visible in the same dynamic root.  Since threads are
executed in separate dynamic roots, fluids can be used for thread local
storage (*note Threads::).

   Fluids can be used to simulate dynamically scoped variables.  These
are used in several (especially in older) dialects of lisp, such as in
Emacs Lisp, and they work a bit like global variables in that they can
be modified by the caller of a procedure, and the called procedure will
see the changes.  With lexically scoped variables--which are normally
used in Scheme--this cannot happen.  See the description of
`with-fluids*' below for details.

   New fluids are created with `make-fluid' and `fluid?' is used for
testing whether an object is actually a fluid.

 - Scheme Procedure: make-fluid
 - C Function: scm_make_fluid ()
     Return a newly created fluid.  Fluids are objects of a certain
     type (a smob) that can hold one SCM value per dynamic root.  That
     is, modifications to this value are only visible to code that
     executes within the same dynamic root as the modifying code.  When
     a new dynamic root is constructed, it inherits the values from its
     parent.  Because each thread executes in its own dynamic root, you
     can use fluids for thread local storage.

 - Scheme Procedure: fluid? obj
 - C Function: scm_fluid_p (obj)
     Return `#t' iff OBJ is a fluid; otherwise, return `#f'.

   The values stored in a fluid can be accessed with `fluid-ref' and
`fluid-set!'.

 - Scheme Procedure: fluid-ref fluid
 - C Function: scm_fluid_ref (fluid)
     Return the value associated with FLUID in the current dynamic
     root.  If FLUID has not been set, then return `#f'.

 - Scheme Procedure: fluid-set! fluid value
 - C Function: scm_fluid_set_x (fluid, value)
     Set the value associated with FLUID in the current dynamic root.

   `with-fluids*' temporarily changes the values of one or more fluids,
so that the given procedure and each procedure called by it access the
given values.  After the procedure returns, the old values are restored.

 - Scheme Procedure: with-fluids* fluids values thunk
 - C Function: scm_with_fluids (fluids, values, thunk)
     Set FLUIDS to VALUES temporary, and call THUNK.  FLUIDS must be a
     list of fluids and VALUES must be the same number of their values
     to be applied.  Each substitution is done one after another.
     THUNK must be a procedure with no argument.


File: guile.info,  Node: Options and Config,  Next: Translation,  Prev: Scheduling,  Up: Top

Configuration, Features and Runtime Options
*******************************************

   Why is my Guile different from your Guile?  There are three kinds of
possible variation:

   * build differences -- different versions of the Guile source code,
     installation directories, configuration flags that control pieces
     of functionality being included or left out, etc.

   * differences in dynamically loaded code -- behaviour and features
     provided by modules that can be dynamically loaded into a running
     Guile

   * different runtime options -- some of the options that are provided
     for controlling Guile's behaviour may be set differently.

   Guile provides "introspective" variables and procedures to query all
of these possible variations at runtime.  For runtime options, it also
provides procedures to change the settings of options and to obtain
documentation on what the options mean.

* Menu:

* Build Config::                Build and installation configuration.
* Feature Tracking::            Available features in the Guile process.
* Runtime Options::             Controlling Guile's runtime behaviour.


File: guile.info,  Node: Build Config,  Next: Feature Tracking,  Up: Options and Config

Configuration, Build and Installation
=====================================

   The following procedures and variables provide information about how
Guile was configured, built and installed on your system.

 - Scheme Procedure: version
 - Scheme Procedure: effective-version
 - Scheme Procedure: major-version
 - Scheme Procedure: minor-version
 - Scheme Procedure: micro-version
 - C Function: scm_version ()
 - C Function: scm_effective_version ()
 - C Function: scm_major_version ()
 - C Function: scm_minor_version ()
 - C Function: scm_micro_version ()
     Return a string describing Guile's full version number, effective
     version number, major, minor or micro version number, respectively.
     The `effective-version' function returns the version name that
     should remain unchanged during a stable series.  Currently that
     means that it omits the micro version.  The effective version
     should be used for items like the versioned share directory name
     i.e. `/usr/share/guile/1.6/'

          (version) => "1.6.0"
          (effective-version) => "1.6"
          (major-version) => "1"
          (minor-version) => "6"
          (micro-version) => "0"

 - Scheme Procedure: %package-data-dir
 - C Function: scm_sys_package_data_dir ()
     Return the name of the directory under which Guile Scheme files in
     general are stored.  On Unix-like systems, this is usually
     `/usr/local/share/guile' or `/usr/share/guile'.

 - Scheme Procedure: %library-dir
 - C Function: scm_sys_library_dir ()
     Return the name of the directory where the Guile Scheme files that
     belong to the core Guile installation (as opposed to files from a
     3rd party package) are installed.  On Unix-like systems, this is
     usually `/usr/local/share/guile/<GUILE_EFFECTIVE_VERSION>' or
     `/usr/share/guile/<GUILE_EFFECTIVE_VERSION>', for example:
     `/usr/local/share/guile/1.6'.

 - Scheme Procedure: %site-dir
 - C Function: scm_sys_site_dir ()
     Return the name of the directory where Guile Scheme files specific
     to your site should be installed.  On Unix-like systems, this is
     usually `/usr/local/share/guile/site' or `/usr/share/guile/site'.

 - Variable: %load-path
     List of directories which should be searched for Scheme modules and
     libraries.  `%load-path' is initialized when Guile starts up to
     `(list (%site-dir) (%library-dir) (%package-data-dir) ".")',
     prepended with the contents of the GUILE_LOAD_PATH environment
     variable, if it is set.

 - Scheme Procedure: parse-path path [tail]
 - C Function: scm_parse_path (path, tail)
     Parse PATH, which is expected to be a colon-separated string, into
     a list and return the resulting list with TAIL appended. If PATH
     is `#f', TAIL is returned.

 - Scheme Procedure: search-path path filename [extensions]
 - C Function: scm_search_path (path, filename, extensions)
     Search PATH for a directory containing a file named FILENAME. The
     file must be readable, and not a directory.  If we find one,
     return its full filename; otherwise, return `#f'.  If FILENAME is
     absolute, return it unchanged.  If given, EXTENSIONS is a list of
     strings; for each directory in PATH, we search for FILENAME
     concatenated with each EXTENSION.

 - Variable: %guile-build-info
     Alist of information collected during the building of a particular
     Guile.  Entries can be grouped into one of several categories:
     directories, env vars, and versioning info.

     Briefly, here are the keys in `%guile-build-info', by group:

    directories
          srcdir, top_srcdir, prefix, exec_prefix, bindir, sbindir,
          libexecdir, datadir, sysconfdir, sharedstatedir,
          localstatedir, libdir, infodir, mandir, includedir,
          pkgdatadir, pkglibdir, pkgincludedir

    env vars
          LIBS

    versioning info
          guileversion, libguileinterface, buildstamp

     Values are all strings.  The value for `LIBS' is typically found
     also as a part of "guile-config link" output.  The value for
     `guileversion' has form X.Y.Z, and should be the same as returned
     by `(version)'.  The value for `libguileinterface' is libtool
     compatible and has form CURRENT:REVISION:AGE.  The value for
     `buildstamp' is the output of the date(1) command.

     In the source, `%guile-build-info' is initialized from
     libguile/libpath.h, which is completely generated, so deleting
     this file before a build guarantees up-to-date values for that
     build.


File: guile.info,  Node: Feature Tracking,  Next: Runtime Options,  Prev: Build Config,  Up: Options and Config

Feature Tracking
================

   Guile has a Scheme level variable `*features*' that keeps track to
some extent of the features that are available in a running Guile.
`*features*' is a list of symbols, for example `threads', each of which
describes a feature of the running Guile process.

 - Variable: *features*
     A list of symbols describing available features of the Guile
     process.

   You shouldn't modify the `*features*' variable directly using
`set!'.  Instead, see the procedures that are provided for this purpose
in the following subsection.

* Menu:

* Feature Manipulation::        Checking for and advertising features.
* Common Feature Symbols::      Commonly available features.


File: guile.info,  Node: Feature Manipulation,  Next: Common Feature Symbols,  Up: Feature Tracking

Feature Manipulation
--------------------

   To check whether a particular feature is available, use the
`provided?' procedure:

 - Scheme Procedure: provided? feature
 - Deprecated Scheme Procedure: feature? feature
     Return `#t' if the specified FEATURE is available, otherwise `#f'.

   To advertise a feature from your own Scheme code, you can use the
`provide' procedure:

 - Scheme Procedure: provide feature
     Add FEATURE to the list of available features in this Guile
     process.

   For C code, the equivalent function takes its feature name as a
`char *' argument for convenience:

 - C Function: void scm_add_feature (const char *str)
     Add a symbol with name STR to the list of available features in
     this Guile process.


File: guile.info,  Node: Common Feature Symbols,  Prev: Feature Manipulation,  Up: Feature Tracking

Common Feature Symbols
----------------------

   In general, a particular feature may be available for one of two
reasons.  Either because the Guile library was configured and compiled
with that feature enabled -- i.e. the feature is built into the library
on your system.  Or because some C or Scheme code that was dynamically
loaded by Guile has added that feature to the list.

   In the first category, here are the features that the current
version of Guile may define (depending on how it is built), and what
they mean.

`array'
     Indicates support for arrays (*note Arrays::).

`array-for-each'
     Indicates availability of `array-for-each' and other array mapping
     procedures (*note Array Mapping::).

`char-ready?'
     Indicates that the `char-ready?' function is available (*note
     Reading::).

`complex'
     Indicates support for complex numbers.

`current-time'
     Indicates availability of time-related functions: `times',
     `get-internal-run-time' and so on (*note Time::).

`debug-extensions'
     Indicates that the debugging evaluator is available, together with
     the options for controlling it.

`delay'
     Indicates support for promises (*note Delayed Evaluation::).

`EIDs'
     Indicates that the `geteuid' and `getegid' really return effective
     user and group IDs (*note Processes::).

`inexact'
     Indicates support for inexact numbers.

`i/o-extensions'
     Indicates availability of the following extended I/O procedures:
     `ftell', `redirect-port', `dup->fdes', `dup2', `fileno',
     `isatty?', `fdopen', `primitive-move->fdes' and `fdes->ports'
     (*note Ports and File Descriptors::).

`net-db'
     Indicates availability of network database functions:
     `scm_gethost', `scm_getnet', `scm_getproto', `scm_getserv',
     `scm_sethost', `scm_setnet', `scm_setproto', `scm_setserv', and
     their `byXXX' variants (*note Network Databases::).

`posix'
     Indicates support for POSIX functions: `pipe', `getgroups',
     `kill', `execl' and so on (*note POSIX::).

`random'
     Indicates availability of random number generation functions:
     `random', `copy-random-state', `random-uniform' and so on (*note
     Random::).

`reckless'
     Indicates that Guile was built with important checks omitted -- you
     should never see this!

`regex'
     Indicates support for POSIX regular expressions using
     `make-regexp', `regexp-exec' and friends (*note Regexp
     Functions::).

`socket'
     Indicates availability of socket-related functions: `socket',
     `bind', `connect' and so on (*note Network Sockets and
     Communication::).

`sort'
     Indicates availability of sorting and merging functions (*note
     Sorting::).

`system'
     Indicates that the `system' function is available (*note
     Processes::).

`threads'
     Indicates support for multithreading (*note Threads::).

`values'
     Indicates support for multiple return values using `values' and
     `call-with-values' (*note Multiple Values::).

   Available features in the second category depend, by definition, on
what additional code your Guile process has loaded in.  The following
table lists features that you might encounter for this reason.

`defmacro'
     Indicates that the `defmacro' macro is available (*note Macros::).

`describe'
     Indicates that the `(oop goops describe)' module has been loaded,
     which provides a procedure for describing the contents of GOOPS
     instances.

`readline'
     Indicates that Guile has loaded in Readline support, for command
     line editing (*note Readline Support::).

`record'
     Indicates support for record definition using `make-record-type'
     and friends (*note Records::).

   Although these tables may seem exhaustive, it is probably unwise in
practice to rely on them, as the correspondences between feature symbols
and available procedures/behaviour are not strictly defined.  If you are
writing code that needs to check for the existence of some procedure, it
is probably safer to do so directly using the `defined?' procedure than
to test for the corresponding feature using `feature?'.


File: guile.info,  Node: Runtime Options,  Prev: Feature Tracking,  Up: Options and Config

Runtime Options
===============

   Guile's runtime behaviour can be modified by setting options.  For
example, is the language that Guile accepts case sensitive, or should
the debugger automatically show a backtrace on error?

   Guile has two levels of interface for managing options: a low-level
control interface, and a user-level interface which allows the enabling
or disabling of options.

   Moreover, the options are classified in groups according to whether
they configure _reading_, _printing_, _debugging_ or _evaluating_.

* Menu:

* Low level options interfaces::
* User level options interfaces::
* Reader options::
* Printing options::
* Debugger options::
* Evaluator options::
* Evaluator trap options::
* Examples of option use::


File: guile.info,  Node: Low level options interfaces,  Next: User level options interfaces,  Up: Runtime Options

Low Level Options Interfaces
----------------------------

 - Scheme Procedure: read-options-interface [setting]
 - Scheme Procedure: eval-options-interface [setting]
 - Scheme Procedure: print-options-interface [setting]
 - Scheme Procedure: debug-options-interface [setting]
 - Scheme Procedure: evaluator-traps-interface [setting]
 - C Function: scm_read_options (setting)
 - C Function: scm_eval_options_interface (setting)
 - C Function: scm_print_options (setting)
 - C Function: scm_debug_options (setting)
 - C Function: scm_evaluator_traps (setting)
     If one of these procedures is called with no arguments (or with
     `setting == SCM_UNDEFINED' in C code), it returns a list describing
     the current setting of the read, eval, print, debug or evaluator
     traps options respectively.  The setting of a boolean option is
     indicated simply by the presence or absence of the option symbol
     in the list.  The setting of a non-boolean option is indicated by
     the presence of the option symbol immediately followed by the
     option's current value.

     If called with a list argument, these procedures interpret the
     list as an option setting and modify the relevant options
     accordingly.  [FIXME -- this glosses over a lot of details!]

     If called with any other argument, such as `'help', these
     procedures return a list of entries like `(OPTION-SYMBOL
     DEFAULT-VALUE DOC-STRING)', with each entry giving the default
     value and documentation for each option symbol in the relevant set
     of options.


File: guile.info,  Node: User level options interfaces,  Next: Reader options,  Prev: Low level options interfaces,  Up: Runtime Options

User Level Options Interfaces
-----------------------------

 - Scheme Procedure: <group>-options [arg]
 - Scheme Procedure: read-options [arg]
 - Scheme Procedure: print-options [arg]
 - Scheme Procedure: debug-options [arg]
 - Scheme Procedure: traps [arg]
     These functions list the options in their group.  The optional
     argument ARG is a symbol which modifies the form in which the
     options are presented.

     With no arguments, `<group>-options' returns the values of the
     options in that particular group.  If ARG is `'help', a
     description of each option is given.  If ARG is `'full',
     programmers' options are also shown.

     ARG can also be a list representing the state of all options.  In
     this case, the list contains single symbols (for enabled boolean
     options) and symbols followed by values.
   [FIXME: I don't think 'full is ever any different from 'help.  What's
up?]

 - Scheme Procedure: <group>-enable option-symbol
 - Scheme Procedure: read-enable option-symbol
 - Scheme Procedure: print-enable option-symbol
 - Scheme Procedure: debug-enable option-symbol
 - Scheme Procedure: trap-enable option-symbol
     These functions set the specified OPTION-SYMBOL in their options
     group.  They only work if the option is boolean, and throw an error
     otherwise.

 - Scheme Procedure: <group>-disable option-symbol
 - Scheme Procedure: read-disable option-symbol
 - Scheme Procedure: print-disable option-symbol
 - Scheme Procedure: debug-disable option-symbol
 - Scheme Procedure: trap-disable option-symbol
     These functions turn off the specified OPTION-SYMBOL in their
     options group.  They only work if the option is boolean, and throw
     an error otherwise.

 - syntax: <group>-set! option-symbol value
 - syntax: read-set! option-symbol value
 - syntax: print-set! option-symbol value
 - syntax: debug-set! option-symbol value
 - syntax: trap-set! option-symbol value
     These functions set a non-boolean OPTION-SYMBOL to the specified
     VALUE.


File: guile.info,  Node: Reader options,  Next: Printing options,  Prev: User level options interfaces,  Up: Runtime Options

Reader options
--------------

   Here is the list of reader options generated by typing
`(read-options 'full)' in Guile.  You can also see the default values.

     keywords         #f      Style of keyword recognition: #f or 'prefix
     case-insensitive no      Convert symbols to lower case.
     positions        yes     Record positions of source code expressions.
     copy             no      Copy source code expressions.

   Notice that while Standard Scheme is case insensitive, to ease
translation of other Lisp dialects, notably Emacs Lisp, into Guile,
Guile is case-sensitive by default.

   To make Guile case insensitive, you can type

     (read-enable 'case-insensitive)


File: guile.info,  Node: Printing options,  Next: Debugger options,  Prev: Reader options,  Up: Runtime Options

Printing options
----------------

   Here is the list of print options generated by typing
`(print-options 'full)' in Guile.  You can also see the default values.

     source          no      Print closures with source.
     closure-hook    #f      Hook for printing closures.


File: guile.info,  Node: Evaluator options,  Next: Evaluator trap options,  Prev: Debugger options,  Up: Runtime Options

Evaluator options
-----------------

   These are the evaluator options with their default values, as they
are printed by typing `(eval-options 'full)' in Guile.

     stack           22000   Size of thread stacks (in machine words).


File: guile.info,  Node: Evaluator trap options,  Next: Examples of option use,  Prev: Evaluator options,  Up: Runtime Options

Evaluator trap options
----------------------

   [FIXME: These flags, together with their corresponding handlers, are
not user level options.  Probably this entire section should be moved
to the documentation about the low-level programmer debugging
interface.]

   Here is the list of evaluator trap options generated by typing
`(traps 'full)' in Guile.  You can also see the default values.

     exit-frame      no      Trap when exiting eval or apply.
     apply-frame     no      Trap when entering apply.
     enter-frame     no      Trap when eval enters new frame.
     traps		yes	Enable evaluator traps.

 - apply-frame-handler: key cont tailp
     Called when a procedure is being applied.

     Called if:

        * evaluator traps are enabled [traps interface], and

        * either
             - `apply-frame' is enabled [traps interface], or

             - trace mode is on [debug-options interface], and the
               procedure being called has the trace property enabled.

     If cheap traps are enabled [debug-options interface], CONT is a
     debug object, otherwise it is a restartable continuation.

     TAILP is true if this is a tail call

 - exit-frame-handler: key cont retval
     Called when a value is returned from a procedure.

     Called if:

        * evaluator traps are enabled [traps interface], and

        * either
             -  `exit-frame' is enabled [traps interface], or

             - trace mode is on [debug-options interface], and the
               procedure being called has the trace property enabled.

     If cheap traps are enabled [debug-options interface], CONT is a
     debug object, otherwise it is a restartable continuation.

     RETVAL is the return value.


File: guile.info,  Node: Debugger options,  Next: Evaluator options,  Prev: Printing options,  Up: Runtime Options

Debugger options
----------------

   Here is the list of print options generated by typing
`(debug-options 'full)' in Guile.  You can also see the default values.

     stack           20000   Stack size limit (0 = no check).
     debug           yes     Use the debugging evaluator.
     backtrace       no      Show backtrace on error.
     depth           20      Maximal length of printed backtrace.
     maxdepth        1000    Maximal number of stored backtrace frames.
     frames          3       Maximum number of tail-recursive frames in backtrace.
     indent          10      Maximal indentation in backtrace.
     backwards       no      Display backtrace in anti-chronological order.
     procnames       yes     Record procedure names at definition.
     trace           no      *Trace mode.
     breakpoints     no      *Check for breakpoints.
     cheap           yes     *Flyweight representation of the stack at traps.

Stack overflow
..............

   Stack overflow errors are caused by a computation trying to use more
stack space than has been enabled by the `stack' option.  They are
reported like this:

     (non-tail-recursive-factorial 500)
     -|
     ERROR: Stack overflow
     ABORT: (stack-overflow)

   If you get an error like this, you can either try rewriting your
code to use less stack space, or increase the maximum stack size.  To
increase the maximum stack size, use `debug-set!', for example:

     (debug-set! stack 200000)
     =>
     (show-file-name #t stack 200000 debug backtrace depth 20 maxdepth 1000 frames 3 indent 10 width 79 procnames cheap)
     
     (non-tail-recursive-factorial 500)
     =>
     122013682599111006870123878542304692625357434...

   If you prefer to try rewriting your code, you may be able to save
stack space by making some of your procedures "tail recursive".  For a
description of what this means, see *Note Proper tail recursion:
(r5rs)Proper tail recursion.


File: guile.info,  Node: Examples of option use,  Prev: Evaluator trap options,  Up: Runtime Options

Examples of option use
----------------------

   Here is an example of a session in which some read and debug option
handling procedures are used.  In this example, the user

  1. Notices that the symbols `abc' and `aBc' are not the same

  2. Examines the `read-options', and sees that `case-insensitive' is
     set to "no".

  3. Enables `case-insensitive'

  4. Verifies that now `aBc' and `abc' are the same

  5. Disables `case-insensitive' and enables debugging `backtrace'

  6. Reproduces the error of displaying `aBc' with backtracing enabled
     [FIXME: this last example is lame because there is no depth in the
     backtrace.  Need to give a better example, possibly putting
     debugging option examples in a separate session.]

     guile> (define abc "hello")
     guile> abc
     "hello"
     guile> aBc
     ERROR: In expression aBc:
     ERROR: Unbound variable: aBc
     ABORT: (misc-error)
     
     Type "(backtrace)" to get more information.
     guile> (read-options 'help)
     keywords	#f	Style of keyword recognition: #f or 'prefix
     case-insensitive	no	Convert symbols to lower case.
     positions	yes	Record positions of source code expressions.
     copy		no	Copy source code expressions.
     guile> (debug-options 'help)
     stack		20000	Stack size limit (0 = no check).
     debug		yes	Use the debugging evaluator.
     backtrace	no	Show backtrace on error.
     depth		20	Maximal length of printed backtrace.
     maxdepth	1000	Maximal number of stored backtrace frames.
     frames		3	Maximum number of tail-recursive frames in backtrace.
     indent		10	Maximal indentation in backtrace.
     backwards	no	Display backtrace in anti-chronological order.
     procnames	yes	Record procedure names at definition.
     trace		no	*Trace mode.
     breakpoints	no	*Check for breakpoints.
     cheap		yes	*Flyweight representation of the stack at traps.
     guile> (read-enable 'case-insensitive)
     (keywords #f case-insensitive positions)
     guile> aBc
     "hello"
     guile> (read-disable 'case-insensitive)
     (keywords #f positions)
     guile> (debug-enable 'backtrace)
     (stack 20000 debug backtrace depth 20 maxdepth 1000 frames 3 indent 10 procnames cheap)
     guile> aBc
     
     Backtrace:
     0* aBc
     
     ERROR: In expression aBc:
     ERROR: Unbound variable: aBc
     ABORT: (misc-error)
     guile>


File: guile.info,  Node: Translation,  Next: Debugging,  Prev: Options and Config,  Up: Top

Support for Translating Other Languages
***************************************

   [Describe translation framework.]

* Menu:

* Emacs Lisp Support::          Helper primitives for Emacs Lisp.


File: guile.info,  Node: Emacs Lisp Support,  Up: Translation

Emacs Lisp Support
==================

 - Scheme Procedure: nil-car x
 - C Function: scm_nil_car (x)
     Return the car of X, but convert it to LISP nil if it is Scheme's
     end-of-list.

 - Scheme Procedure: nil-cdr x
 - C Function: scm_nil_cdr (x)
     Return the cdr of X, but convert it to LISP nil if it is Scheme's
     end-of-list.

 - Scheme Procedure: nil-cons x y
 - C Function: scm_nil_cons (x, y)
     Create a new cons cell with X as the car and Y as the cdr, but
     convert Y to Scheme's end-of-list if it is a Lisp nil.

 - Scheme Procedure: nil-eq x y
     Compare X and Y and return Lisp's t if they are `eq?', return
     Lisp's nil otherwise.

 - Scheme Procedure: null x
 - C Function: scm_null (x)
     Return Lisp's `t' if X is nil in the LISP sense, return Lisp's nil
     otherwise.


File: guile.info,  Node: Debugging,  Next: Deprecated,  Prev: Translation,  Up: Top

Debugging Infrastructure
************************

* Menu:

* Source Properties::           Remembering the source of an expression.
* Using Traps::
* Capturing the Stack or Innermost Stack Frame::
* Examining the Stack::
* Examining Stack Frames::
* Decoding Memoized Source Expressions::
* Starting a New Stack::


File: guile.info,  Node: Source Properties,  Next: Using Traps,  Up: Debugging

Source Properties
=================

   As Guile reads in Scheme code from file or from standard input, it
remembers the file name, line number and column number where each
expression begins.  These pieces of information are known as the
"source properties" of the expression.  If an expression undergoes
transformation -- for example, if there is a syntax transformer in
effect, or the expression is a macro call -- the source properties are
copied from the untransformed to the transformed expression so that, if
an error occurs when evaluating the transformed expression, Guile's
debugger can point back to the file and location where the expression
originated.

   The way that source properties are stored means that Guile can only
associate source properties with parenthesized expressions, and not, for
example, with individual symbols, numbers or strings.  The difference
can be seen by typing `(xxx)' and `xxx' at the Guile prompt (where the
variable `xxx' has not been defined):

     guile> (xxx)
     standard input:2:1: In expression (xxx):
     standard input:2:1: Unbound variable: xxx
     ABORT: (unbound-variable)
     guile> xxx
     <unnamed port>: In expression xxx:
     <unnamed port>: Unbound variable: xxx
     ABORT: (unbound-variable)

In the latter case, no source properties were stored, so the best that
Guile could say regarding the location of the problem was "<unnamed
port>".

   The recording of source properties is controlled by the read option
named "positions" (*note Reader options::).  This option is switched
_on_ by default, together with the debug options "debug" and
"backtrace" (*note Debugger options::), when Guile is run
interactively; all these options are _off_ by default when Guile runs a
script non-interactively.


File: guile.info,  Node: Using Traps,  Next: Capturing the Stack or Innermost Stack Frame,  Prev: Source Properties,  Up: Debugging

Using Traps
===========

 - Scheme Procedure: with-traps thunk
 - C Function: scm_with_traps (thunk)
     Call THUNK with traps enabled.

 - Scheme Procedure: debug-object? obj
 - C Function: scm_debug_object_p (obj)
     Return `#t' if OBJ is a debug object.


File: guile.info,  Node: Capturing the Stack or Innermost Stack Frame,  Next: Examining the Stack,  Prev: Using Traps,  Up: Debugging

Capturing the Stack or Innermost Stack Frame
============================================

   When an error occurs in a running program, or the program hits a
breakpoint, its state at that point can be represented by a "stack" of
all the evaluations and procedure applications that are logically in
progress at that time, each of which is known as a "frame".  The
programmer can learn more about the program's state at the point of
interruption or error by inspecting the stack and its frames.

 - Scheme Procedure: make-stack obj . args
 - C Function: scm_make_stack (obj, args)
     Create a new stack. If OBJ is `#t', the current evaluation stack
     is used for creating the stack frames, otherwise the frames are
     taken from OBJ (which must be either a debug object or a
     continuation).

     ARGS should be a list containing any combination of integer,
     procedure and `#t' values.

     These values specify various ways of cutting away uninteresting
     stack frames from the top and bottom of the stack that
     `make-stack' returns.  They come in pairs like this: `(INNER_CUT_1
     OUTER_CUT_1 INNER_CUT_2 OUTER_CUT_2 ...)'.

     Each INNER_CUT_N can be `#t', an integer, or a procedure.  `#t'
     means to cut away all frames up to but excluding the first user
     module frame.  An integer means to cut away exactly that number of
     frames.  A procedure means to cut away all frames up to but
     excluding the application frame whose procedure matches the
     specified one.

     Each OUTER_CUT_N can be an integer or a procedure.  An integer
     means to cut away that number of frames.  A procedure means to cut
     away frames down to but excluding the application frame whose
     procedure matches the specified one.

     If the OUTER_CUT_N of the last pair is missing, it is taken as 0.

 - Scheme Procedure: last-stack-frame obj
 - C Function: scm_last_stack_frame (obj)
     Return a stack which consists of a single frame, which is the last
     stack frame for OBJ. OBJ must be either a debug object or a
     continuation.


File: guile.info,  Node: Examining the Stack,  Next: Examining Stack Frames,  Prev: Capturing the Stack or Innermost Stack Frame,  Up: Debugging

Examining the Stack
===================

 - Scheme Procedure: stack? obj
 - C Function: scm_stack_p (obj)
     Return `#t' if OBJ is a calling stack.

 - Scheme Procedure: stack-id stack
 - C Function: scm_stack_id (stack)
     Return the identifier given to STACK by `start-stack'.

 - Scheme Procedure: stack-length stack
 - C Function: scm_stack_length (stack)
     Return the length of STACK.

 - Scheme Procedure: stack-ref stack index
 - C Function: scm_stack_ref (stack, index)
     Return the INDEX'th frame from STACK.

 - Scheme Procedure: display-backtrace stack port [first [depth]]
 - C Function: scm_display_backtrace (stack, port, first, depth)
     Display a backtrace to the output port PORT. STACK is the stack to
     take the backtrace from, FIRST specifies where in the stack to
     start and DEPTH how much frames to display. Both FIRST and DEPTH
     can be `#f', which means that default values will be used.


File: guile.info,  Node: Examining Stack Frames,  Next: Decoding Memoized Source Expressions,  Prev: Examining the Stack,  Up: Debugging

Examining Stack Frames
======================

 - Scheme Procedure: frame? obj
 - C Function: scm_frame_p (obj)
     Return `#t' if OBJ is a stack frame.

 - Scheme Procedure: frame-number frame
 - C Function: scm_frame_number (frame)
     Return the frame number of FRAME.

 - Scheme Procedure: frame-previous frame
 - C Function: scm_frame_previous (frame)
     Return the previous frame of FRAME, or `#f' if FRAME is the first
     frame in its stack.

 - Scheme Procedure: frame-next frame
 - C Function: scm_frame_next (frame)
     Return the next frame of FRAME, or `#f' if FRAME is the last frame
     in its stack.

 - Scheme Procedure: frame-source frame
 - C Function: scm_frame_source (frame)
     Return the source of FRAME.

 - Scheme Procedure: frame-procedure? frame
 - C Function: scm_frame_procedure_p (frame)
     Return `#t' if a procedure is associated with FRAME.

 - Scheme Procedure: frame-procedure frame
 - C Function: scm_frame_procedure (frame)
     Return the procedure for FRAME, or `#f' if no procedure is
     associated with FRAME.

 - Scheme Procedure: frame-arguments frame
 - C Function: scm_frame_arguments (frame)
     Return the arguments of FRAME.

 - Scheme Procedure: frame-evaluating-args? frame
 - C Function: scm_frame_evaluating_args_p (frame)
     Return `#t' if FRAME contains evaluated arguments.

 - Scheme Procedure: frame-overflow? frame
 - C Function: scm_frame_overflow_p (frame)
     Return `#t' if FRAME is an overflow frame.

 - Scheme Procedure: frame-real? frame
 - C Function: scm_frame_real_p (frame)
     Return `#t' if FRAME is a real frame.

 - Scheme Procedure: display-application frame [port [indent]]
 - C Function: scm_display_application (frame, port, indent)
     Display a procedure application FRAME to the output port PORT.
     INDENT specifies the indentation of the output.


File: guile.info,  Node: Decoding Memoized Source Expressions,  Next: Starting a New Stack,  Prev: Examining Stack Frames,  Up: Debugging

Decoding Memoized Source Expressions
====================================

 - Scheme Procedure: memoized? obj
 - C Function: scm_memoized_p (obj)
     Return `#t' if OBJ is memoized.

 - Scheme Procedure: unmemoize m
 - C Function: scm_unmemoize (m)
     Unmemoize the memoized expression M,

 - Scheme Procedure: memoized-environment m
 - C Function: scm_memoized_environment (m)
     Return the environment of the memoized expression M.


File: guile.info,  Node: Starting a New Stack,  Prev: Decoding Memoized Source Expressions,  Up: Debugging

Starting a New Stack
====================

 - Scheme Syntax: start-stack id exp
     Evaluate EXP on a new calling stack with identity ID.  If EXP is
     interrupted during evaluation, backtraces will not display frames
     farther back than EXP's top-level form.  This macro is a way of
     artificially limiting backtraces and stack procedures, largely as
     a convenience to the user.


File: guile.info,  Node: Deprecated,  Next: SLIB,  Prev: Debugging,  Up: Top

Deprecated
**********

* Menu:

* Shared And Read Only Strings::
* Sloppy Membership::           `Sloppy' list membership procedures.
* Strange Eval::                Strange variations on `eval'.
* Close All Ports::             Closing all ports except some ...
* C Module Reg::                Old method for registering C modules.
* Obarray Symbols::             Obarray symbol manipulation.
* Removed Items::               Previously deprecated, now removed.


File: guile.info,  Node: Shared And Read Only Strings,  Next: Sloppy Membership,  Up: Deprecated

Shared And Read Only Strings
============================

   The procedures described in this section are deprecated because
explicit shared substrings are planned to disappear from Guile.

   Instead, all strings will be implemented using sharing internally,
combined with a copy-on-write strategy.  Once internal string sharing
and copy-on-write have been implemented, it will be unnecessary to
preserve the concept of read only strings.

* Menu:

* Shared Substrings::           Strings which share memory with each other.
* Read Only Strings::           Treating certain non-strings as strings.


File: guile.info,  Node: Shared Substrings,  Next: Read Only Strings,  Up: Shared And Read Only Strings

Shared Substrings
-----------------

   Whenever you extract a substring using `substring', the Scheme
interpreter allocates a new string and copies data from the old string.
This is expensive, but `substring' is so convenient for manipulating
text that programmers use it often.

   Guile Scheme provides the concept of the "shared substring" to
improve performance of many substring-related operations.  A shared
substring is an object that mostly behaves just like an ordinary
substring, except that it actually shares storage space with its parent
string.

 - Deprecated Scheme Procedure: make-shared-substring str [start [end]]
 - Deprecated C Function: scm_make_shared_substring (str, start, end)
     Return a shared substring of STR.  The arguments are the same as
     for the `substring' function: the shared substring returned
     includes all of the text from STR between indexes START
     (inclusive) and END (exclusive).  If END is omitted, it defaults
     to the end of STR.  The shared substring returned by
     `make-shared-substring' occupies the same storage space as STR.

   Example:

     (define foo "the quick brown fox")
     (define bar (make-shared-substring some-string 4 9))
     
     foo => "t h e   q u i c k   b r o w n   f o x"
     bar =========> |---------|

   The shared substring BAR is not given its own storage space.
Instead, the Guile interpreter notes internally that BAR points to a
portion of the memory allocated to FOO.  However, BAR behaves like an
ordinary string in most respects: it may be used with string primitives
like `string-length', `string-ref', `string=?'.  Guile makes the
necessary translation between indices of BAR and indices of FOO
automatically.

     (string-length? bar) => 5	; bar only extends from indices 4 to 9
     (string-ref bar 3)  => #\c	; same as (string-ref foo 7)
     (make-shared-substring bar 2)
       => "ick"			; can even make a shared substring!

   Because creating a shared substring does not require allocating new
storage from the heap, it is a very fast operation.  However, because it
shares memory with its parent string, a change to the contents of the
parent string will implicitly change the contents of its shared
substrings.

     (string-set! foo 7 #\r)
     bar => "quirk"

   Guile considers shared substrings to be immutable.  This is because
programmers might not always be aware that a given string is really a
shared substring, and might innocently try to mutate it without
realizing that the change would affect its parent string.  (We are
currently considering a "copy-on-write" strategy that would permit
modifying shared substrings without affecting the parent string.)

   In general, shared substrings are useful in circumstances where it is
important to divide a string into smaller portions, but you do not
expect to change the contents of any of the strings involved.


File: guile.info,  Node: Read Only Strings,  Prev: Shared Substrings,  Up: Shared And Read Only Strings

Read Only Strings
-----------------

   In previous versions of Guile, there was the idea that some
string-based primitives such as `string-append' could equally accept
symbols as arguments.  For example, one could write

     (string-append '/home/ 'vigilia)

and get `"/home/vigilia"' as the result.  The term "read only string"
was adopted to describe the argument type expected by such primitives.

   This idea has now been removed.  The predicate `read-only-string?'
still exists, but deprecated, and is equivalent to

     (lambda (x) (or (string? x) (symbol? x)))

But no Guile primitives now use `read-only-string?' to validate their
arguments.

   String-based primitives such as `string-append' now require strings:

     (string-append '/home/ 'vigilia)
     =>
     ERROR: Wrong type argument (expecting STRINGP): /home/

 - Deprecated Scheme Procedure: read-only-string? obj
 - Deprecated C Function: scm_read_only_string_p (obj)
     Return `#t' if OBJ is either a string or a symbol, otherwise
     return `#f'.


File: guile.info,  Node: Sloppy Membership,  Next: Strange Eval,  Prev: Shared And Read Only Strings,  Up: Deprecated

`Sloppy' List Membership Procedures
===================================

   The following are equivalent to `memq', `memv' and `member'
respectively, except that they do not fully type-check the arguments
that they are given.  They are deprecated because the lack of proper
type-checking makes them dangerous.

 - Deprecated Scheme Procedure: sloppy-memq x lst
 - Deprecated C Function: scm_sloppy_memq (x, lst)
     This procedure behaves like `memq', but does no type or error
     checking.  Its use is recommended only in writing Guile internals,
     not for high-level Scheme programs.

 - Deprecated Scheme Procedure: sloppy-memv x lst
 - Deprecated C Function: scm_sloppy_memv (x, lst)
     This procedure behaves like `memv', but does no type or error
     checking.  Its use is recommended only in writing Guile internals,
     not for high-level Scheme programs.

 - Deprecated Scheme Procedure: sloppy-member x lst
 - Deprecated C Function: scm_sloppy_member (x, lst)
     This procedure behaves like `member', but does no type or error
     checking.  Its use is recommended only in writing Guile internals,
     not for high-level Scheme programs.


File: guile.info,  Node: Strange Eval,  Next: Close All Ports,  Prev: Sloppy Membership,  Up: Deprecated

Strange Variations on `eval'
============================

   `eval2' was useful in previous Guile releases because the `eval' in
those releases was a single argument `eval' that did not conform to
R5RS.  Guile's standard `eval' now requires a second
environment-specifier argument (which Guile interprets as the module in
which to evaluate the specified code expression).  Hence `eval' is now
R5RS-compliant, and `eval2' is obsolete and therefore deprecated.

 - Deprecated Scheme Procedure: eval2 obj env_thunk
 - Deprecated C Function: scm_eval2 (obj, env_thunk)
     Evaluate EXP, a Scheme expression, in the environment designated
     by LOOKUP, a symbol-lookup function.  Do not use this version of
     eval, it does not play well with the module system.  Use `eval' or
     `primitive-eval' instead.

   In previous Guile releases, the implementation of expressions like
`(eval (read port))' was deficient in that source properties associated
with the expression returned by the `read' would be lost during the
`eval'.  To provide a way of performing a read and evaluation without
losing source properties, `read-and-eval!' was invented.

   In this Guile release, evaluation always preserves source property
information.  So `read-and-eval!' is now unnecessary.

 - Deprecated Scheme Procedure: read-and-eval! [port]
 - Deprecated C Function: scm_read_and_eval_x (port)
     Read a form from PORT (standard input by default), and evaluate it
     (memoizing it in the process) in the top-level environment.  If no
     data is left to be read from PORT, an `end-of-file' error is
     signalled.


File: guile.info,  Node: Close All Ports,  Next: C Module Reg,  Prev: Strange Eval,  Up: Deprecated

Closing All Ports Except Some ...
=================================

 - Deprecated Scheme Procedure: close-all-ports-except . ports
 - Deprecated C Function: scm_close_all_ports_except (ports)
     [DEPRECATED] Close all open file ports used by the interpreter
     except for those supplied as arguments.  This procedure was
     intended to be used before an exec call to close file descriptors
     which are not needed in the new process.  However it has the
     undesirable side effect of flushing buffers, so it's deprecated.
     Use port-for-each instead.


File: guile.info,  Node: C Module Reg,  Next: Obarray Symbols,  Prev: Close All Ports,  Up: Deprecated

Old Method for Registering C Modules.
=====================================

   ** Auto-loading of compiled-code modules is deprecated.

   Guile used to be able to automatically find and link a shared
library to satisfy requests for a module.  For example, the module
`(foo bar)' could be implemented by placing a shared library named
"foo/libbar.so" (or with a different extension) in a directory on the
load path of Guile.

   This has been found to be too tricky, and is no longer supported.
The shared libraries are now called "extensions".  You should now write
a small Scheme file that calls `load-extension' to load the shared
library and initialize it explicitely.

   The shared libraries themselves should be installed in the usual
places for shared libraries, with names like "libguile-foo-bar".

   For example, place this into a file "foo/bar.scm"

   (define-module (foo bar))

   (load-extension "libguile-foo-bar" "foobar_init")


File: guile.info,  Node: Obarray Symbols,  Next: Removed Items,  Prev: C Module Reg,  Up: Deprecated

Obarray Symbol Manipulation
===========================

   Guile's module mechanism uses "obarrays", which are hash tables that
map symbols to variables.  Guile 1.4 included a group of primitives that
could be used for the manipulation of the symbol-variable mappings in
such obarrays.

   However, considering the availability both of low-level procedures
for operating on hash tables in general (*note Hash Tables::), and of a
dedicated API for module-related operations (*note Modules::), the
intermediate set of obarray primitives is no longer useful, and --
which is worse -- makes it more difficult to evolve the implementation
of Guile's module system.  Hence this set of primitives has now been
deprecated.

   If you have code using these functions, please change it to use
either hash table or module-related operations.

 - Deprecated Scheme Procedure: gentemp [prefix [obarray]]
 - Deprecated C Function: scm_gentemp (prefix, obarray)
     Create a new symbol with a name unique in an obarray.  The name is
     constructed from an optional string PREFIX and a counter value.
     The default prefix is `t'.  The OBARRAY is specified as a second
     optional argument.  Default is the system obarray where all normal
     symbols are interned.  The counter is increased by 1 at each call.
     There is no provision for resetting the counter.

 - Deprecated Scheme Procedure: intern-symbol obarray string
 - Deprecated C Function: scm_intern_symbol (obarray, string)
     Add a new symbol to OBARRAY with name STRING, bound to an
     unspecified initial value.  The symbol table is not modified if a
     symbol with this name is already present.

 - Deprecated Scheme Procedure: symbol-interned? obarray string
 - Deprecated C Function: scm_symbol_interned_p (obarray, string)
     Return `#t' if OBARRAY contains a symbol with name STRING, and
     `#f' otherwise.

 - Deprecated Scheme Procedure: unintern-symbol obarray string
 - Deprecated C Function: scm_unintern_symbol (obarray, string)
     Remove the symbol with name STRING from OBARRAY.  This function
     returns `#t' if the symbol was present and `#f' otherwise.

 - Deprecated Scheme Procedure: string->obarray-symbol obarray string
          [soft?]
 - Deprecated C Function: scm_string_to_obarray_symbol (obarray,
          string, soft_p)
     Intern a new symbol in OBARRAY, a symbol table, with name STRING.

     If OBARRAY is `#f', use the default system symbol table.  If
     OBARRAY is `#t', the symbol should not be interned in any symbol
     table; merely return the pair (SYMBOL . #<UNDEFINED>).

     The SOFT? argument determines whether new symbol table entries
     should be created when the specified symbol is not already present
     in OBARRAY.  If SOFT? is specified and is a true value, then new
     entries should not be added for symbols not already present in the
     table; instead, simply return `#f'.

 - Deprecated Scheme Procedure: symbol-binding obarray string
 - Deprecated C Function: scm_symbol_binding (obarray, string)
     Look up in OBARRAY the symbol whose name is STRING, and return the
     value to which it is bound.  If OBARRAY is `#f', use the global
     symbol table.  If STRING is not interned in OBARRAY, an error is
     signalled.

 - Deprecated Scheme Procedure: symbol-bound? obarray string
 - Deprecated C Function: scm_symbol_bound_p (obarray, string)
     Return `#t' if OBARRAY contains a symbol with name STRING bound to
     a defined value.  This differs from SYMBOL-INTERNED? in that the
     mere mention of a symbol usually causes it to be interned;
     `symbol-bound?' determines whether a symbol has been given any
     meaningful value.

 - Deprecated Scheme Procedure: symbol-set! obarray string value
 - Deprecated C Function: scm_symbol_set_x (obarray, string, value)
     Find the symbol in OBARRAY whose name is STRING, and rebind it to
     VALUE.  An error is signalled if STRING is not present in OBARRAY.

 - Deprecated Scheme Procedure: builtin-bindings
 - Deprecated C Function: scm_builtin_bindings
     Create and return a copy of the global symbol table, removing all
     unbound symbols.


File: guile.info,  Node: Removed Items,  Prev: Obarray Symbols,  Up: Deprecated

Previously Deprecated Items Now Removed
=======================================

   tag fseek list*


File: guile.info,  Node: SLIB,  Next: POSIX,  Prev: Deprecated,  Up: Top

SLIB
****

   Before the SLIB facilities can be used, the following Scheme
expression must be executed:

     (use-modules (ice-9 slib))

   `require' can then be used as described in *Note SLIB: (slib)Top.

   For example:

     guile> (use-modules (ice-9 slib))
     guile> (require 'primes)
     guile> (probably-prime? 13)

* Menu:

* SLIB installation::
* JACAL::


File: guile.info,  Node: SLIB installation,  Next: JACAL,  Up: SLIB

SLIB installation
=================

   The following seems to work (e.g., with slib versions 2c7 and 2d2):

  1. Unpack slib somewhere, e.g., /usr/local/share/slib.

  2. Create a symlink in the Guile site directory to slib, e.g.,:

          ln -s /usr/local/share/slib /usr/local/share/guile/site/slib

  3. Use Guile to create the catalog file, e.g.,:

          # guile
          guile> (use-modules (ice-9 slib))
          guile> (load "/usr/local/share/slib/mklibcat.scm")
          guile> (quit)

     The catalog data should now be in
     `/usr/local/share/guile/site/slibcat'.

     If instead you get an error such as:

          Unbound variable: scheme-implementation-type

     then a solution is to get a newer version of Guile, or to modify
     ice-9/slib.scm to use define-public for the offending variables.

  4. Install the documentation:

          cd /usr/local/share/slib
          rm /usr/local/info/slib.info*
          cp slib.info /usr/local/info
          install-info slib.info /usr/local/info/dir


File: guile.info,  Node: JACAL,  Prev: SLIB installation,  Up: SLIB

JACAL
=====

   Jacal is a symbolic math package written in Scheme by Aubrey Jaffer.
It is usually installed as an extra package in SLIB (*note Packages
not shipped with Guile::).

   You can use Guile's interface to SLIB to invoke Jacal:

     (use-modules (ice-9 slib))
     (slib:load "math")
     (math)

For complete documentation on Jacal, please read the Jacal manual.  If
it has been installed on line, you can look at *Note Jacal: (jacal)Top.
Otherwise you can find it on the web at
<http://www-swiss.ai.mit.edu/~jaffer/JACAL.html>


File: guile.info,  Node: POSIX,  Next: SRFI Support,  Prev: SLIB,  Up: Top

POSIX System Calls and Networking
*********************************

* Menu:

* Conventions::                 Conventions employed by the POSIX interface.
* Ports and File Descriptors::  Scheme ``ports'' and Unix file descriptors
				  have different representations.
* File System::                 stat, chown, chmod, etc.
* User Information::            Retrieving a user's GECOS (/etc/passwd) entry.
* Time::                        gettimeofday, localtime, strftime, etc.
* Runtime Environment::         Accessing and modifying Guile's environment.
* Processes::                   getuid, getpid, etc.
* Signals::                     sigaction, kill, pause, alarm, setitimer, etc.
* Terminals and Ptys::          ttyname, tcsetpgrp, etc.
* Pipes::                       Communicating data between processes.
* Networking::                  gethostbyaddr, getnetent, socket, bind, listen.
* System Identification::       Obtaining information about the system.
* Locales::                     setlocale, etc.
* Encryption::


File: guile.info,  Node: Conventions,  Next: Ports and File Descriptors,  Up: POSIX

POSIX Interface Conventions
===========================

   These interfaces provide access to operating system facilities.
They provide a simple wrapping around the underlying C interfaces to
make usage from Scheme more convenient.  They are also used to
implement the Guile port of *Note The Scheme shell (scsh)::.

   Generally there is a single procedure for each corresponding Unix
facility.  There are some exceptions, such as procedures implemented for
speed and convenience in Scheme with no primitive Unix equivalent,
e.g., `copy-file'.

   The interfaces are intended as far as possible to be portable across
different versions of Unix.  In some cases procedures which can't be
implemented on particular systems may become no-ops, or perform limited
actions.  In other cases they may throw errors.

   General naming conventions are as follows:

   * The Scheme name is often identical to the name of the underlying
     Unix facility.

   * Underscores in Unix procedure names are converted to hyphens.

   * Procedures which destructively modify Scheme data have exclamation
     marks appended, e.g., `recv!'.

   * Predicates (returning only `#t' or `#f') have question marks
     appended, e.g., `access?'.

   * Some names are changed to avoid conflict with dissimilar interfaces
     defined by scsh, e.g., `primitive-fork'.

   * Unix preprocessor names such as `EPERM' or `R_OK' are converted to
     Scheme variables of the same name (underscores are not replaced
     with hyphens).

   Unexpected conditions are generally handled by raising exceptions.
There are a few procedures which return a special value if they don't
succeed, e.g., `getenv' returns `#f' if it the requested string is not
found in the environment.  These cases are noted in the documentation.

   For ways to deal with exceptions, *Note Exceptions::.

   Errors which the C-library would report by returning a NULL pointer
or through some other means are reported by raising a `system-error'
exception.  The value of the Unix `errno' variable is available in the
data passed by the exception.

   It can be extracted with the function `system-error-errno':

     (catch
      'system-error
      (lambda ()
        (mkdir "/this-ought-to-fail-if-I'm-not-root"))
      (lambda stuff
        (let ((errno (system-error-errno stuff)))
          (cond
           ((= errno EACCES)
            (display "You're not allowed to do that."))
           ((= errno EEXIST)
            (display "Already exists."))
           (#t
            (display (strerror errno))))
          (newline))))


File: guile.info,  Node: Ports and File Descriptors,  Next: File System,  Prev: Conventions,  Up: POSIX

Ports and File Descriptors
==========================

   Conventions generally follow those of scsh, *Note The Scheme shell
(scsh)::.

   File ports are implemented using low-level operating system I/O
facilities, with optional buffering to improve efficiency *note File
Ports::

   Note that some procedures (e.g., `recv!') will accept ports as
arguments, but will actually operate directly on the file descriptor
underlying the port.  Any port buffering is ignored, including the
buffer which implements `peek-char' and `unread-char'.

   The `force-output' and `drain-input' procedures can be used to clear
the buffers.

   Each open file port has an associated operating system file
descriptor.  File descriptors are generally not useful in Scheme
programs; however they may be needed when interfacing with foreign code
and the Unix environment.

   A file descriptor can be extracted from a port and a new port can be
created from a file descriptor.  However a file descriptor is just an
integer and the garbage collector doesn't recognize it as a reference
to the port.  If all other references to the port were dropped, then
it's likely that the garbage collector would free the port, with the
side-effect of closing the file descriptor prematurely.

   To assist the programmer in avoiding this problem, each port has an
associated "revealed count" which can be used to keep track of how many
times the underlying file descriptor has been stored in other places.
If a port's revealed count is greater than zero, the file descriptor
will not be closed when the port is garbage collected.  A programmer
can therefore ensure that the revealed count will be greater than zero
if the file descriptor is needed elsewhere.

   For the simple case where a file descriptor is "imported" once to
become a port, it does not matter if the file descriptor is closed when
the port is garbage collected.  There is no need to maintain a revealed
count.  Likewise when "exporting" a file descriptor to the external
environment, setting the revealed count is not required provided the
port is kept open (i.e., is pointed to by a live Scheme binding) while
the file descriptor is in use.

   To correspond with traditional Unix behaviour, the three file
descriptors (0, 1 and 2) are automatically imported when a program
starts up and assigned to the initial values of the current input,
output and error ports.  The revealed count for each is initially set to
one, so that dropping references to one of these ports will not result
in its garbage collection: it could be retrieved with fdopen or
fdes->ports.

 - Scheme Procedure: port-revealed port
 - C Function: scm_port_revealed (port)
     Return the revealed count for PORT.

 - Scheme Procedure: set-port-revealed! port rcount
 - C Function: scm_set_port_revealed_x (port, rcount)
     Sets the revealed count for a port to a given value.  The return
     value is unspecified.

 - Scheme Procedure: fileno port
 - C Function: scm_fileno (port)
     Return the integer file descriptor underlying PORT.  Does not
     change its revealed count.

 - Scheme Procedure: port->fdes port
     Returns the integer file descriptor underlying PORT.  As a side
     effect the revealed count of PORT is incremented.

 - Scheme Procedure: fdopen fdes modes
 - C Function: scm_fdopen (fdes, modes)
     Return a new port based on the file descriptor FDES.  Modes are
     given by the string MODES.  The revealed count of the port is
     initialized to zero.  The modes string is the same as that
     accepted by *Note open-file: File Ports.

 - Scheme Procedure: fdes->ports fd
 - C Function: scm_fdes_to_ports (fd)
     Return a list of existing ports which have FDES as an underlying
     file descriptor, without changing their revealed counts.

 - Scheme Procedure: fdes->inport fdes
     Returns an existing input port which has FDES as its underlying
     file descriptor, if one exists, and increments its revealed count.
     Otherwise, returns a new input port with a revealed count of 1.

 - Scheme Procedure: fdes->outport fdes
     Returns an existing output port which has FDES as its underlying
     file descriptor, if one exists, and increments its revealed count.
     Otherwise, returns a new output port with a revealed count of 1.

 - Scheme Procedure: primitive-move->fdes port fd
 - C Function: scm_primitive_move_to_fdes (port, fd)
     Moves the underlying file descriptor for PORT to the integer value
     FDES without changing the revealed count of PORT.  Any other ports
     already using this descriptor will be automatically shifted to new
     descriptors and their revealed counts reset to zero.  The return
     value is `#f' if the file descriptor already had the required
     value or `#t' if it was moved.

 - Scheme Procedure: move->fdes port fdes
     Moves the underlying file descriptor for PORT to the integer value
     FDES and sets its revealed count to one.  Any other ports already
     using this descriptor will be automatically shifted to new
     descriptors and their revealed counts reset to zero.  The return
     value is unspecified.

 - Scheme Procedure: release-port-handle port
     Decrements the revealed count for a port.

 - Scheme Procedure: fsync object
 - C Function: scm_fsync (object)
     Copies any unwritten data for the specified output file descriptor
     to disk.  If PORT/FD is a port, its buffer is flushed before the
     underlying file descriptor is fsync'd.  The return value is
     unspecified.

 - Scheme Procedure: open path flags [mode]
 - C Function: scm_open (path, flags, mode)
     Open the file named by PATH for reading and/or writing.  FLAGS is
     an integer specifying how the file should be opened.  MODE is an
     integer specifying the permission bits of the file, if it needs to
     be created, before the umask is applied.  The default is 666 (Unix
     itself has no default).

     FLAGS can be constructed by combining variables using `logior'.
     Basic flags are:

      - Variable: O_RDONLY
          Open the file read-only.

      - Variable: O_WRONLY
          Open the file write-only.

      - Variable: O_RDWR
          Open the file read/write.

      - Variable: O_APPEND
          Append to the file instead of truncating.

      - Variable: O_CREAT
          Create the file if it does not already exist.

     See the Unix documentation of the `open' system call for
     additional flags.

 - Scheme Procedure: open-fdes path flags [mode]
 - C Function: scm_open_fdes (path, flags, mode)
     Similar to `open' but return a file descriptor instead of a port.

 - Scheme Procedure: close fd_or_port
 - C Function: scm_close (fd_or_port)
     Similar to close-port (*note close-port: Closing.), but also works
     on file descriptors.  A side effect of closing a file descriptor
     is that any ports using that file descriptor are moved to a
     different file descriptor and have their revealed counts set to
     zero.

 - Scheme Procedure: close-fdes fd
 - C Function: scm_close_fdes (fd)
     A simple wrapper for the `close' system call.  Close file
     descriptor FD, which must be an integer.  Unlike close (*note
     close: Ports and File Descriptors.), the file descriptor will be
     closed even if a port is using it.  The return value is
     unspecified.

 - Scheme Procedure: unread-char char [port]
 - C Function: scm_unread_char (char, port)
     Place CHAR in PORT so that it will be read by the next read
     operation.  If called multiple times, the unread characters will
     be read again in last-in first-out order.  If PORT is not
     supplied, the current input port is used.

 - Scheme Procedure: unread-string str port
     Place the string STR in PORT so that its characters will be read
     in subsequent read operations.  If called multiple times, the
     unread characters will be read again in last-in first-out order.
     If PORT is not supplied, the current-input-port is used.

 - Scheme Procedure: pipe
 - C Function: scm_pipe ()
     Return a newly created pipe: a pair of ports which are linked
     together on the local machine.  The _car_ is the input port and
     the _cdr_ is the output port.  Data written (and flushed) to the
     output port can be read from the input port.  Pipes are commonly
     used for communication with a newly forked child process.  The
     need to flush the output port can be avoided by making it
     unbuffered using `setvbuf'.

     Writes occur atomically provided the size of the data in bytes is
     not greater than the value of `PIPE_BUF'.  Note that the output
     port is likely to block if too much data (typically equal to
     `PIPE_BUF') has been written but not yet read from the input port.

   The next group of procedures perform a `dup2' system call, if NEWFD
(an integer) is supplied, otherwise a `dup'.  The file descriptor to be
duplicated can be supplied as an integer or contained in a port.  The
type of value returned varies depending on which procedure is used.

   All procedures also have the side effect when performing `dup2' that
any ports using NEWFD are moved to a different file descriptor and have
their revealed counts set to zero.

 - Scheme Procedure: dup->fdes fd_or_port [fd]
 - C Function: scm_dup_to_fdes (fd_or_port, fd)
     Return a new integer file descriptor referring to the open file
     designated by FD_OR_PORT, which must be either an open file port
     or a file descriptor.

 - Scheme Procedure: dup->inport port/fd [newfd]
     Returns a new input port using the new file descriptor.

 - Scheme Procedure: dup->outport port/fd [newfd]
     Returns a new output port using the new file descriptor.

 - Scheme Procedure: dup port/fd [newfd]
     Returns a new port if PORT/FD is a port, with the same mode as the
     supplied port, otherwise returns an integer file descriptor.

 - Scheme Procedure: dup->port port/fd mode [newfd]
     Returns a new port using the new file descriptor.  MODE supplies a
     mode string for the port (*note open-file: File Ports.).

 - Scheme Procedure: duplicate-port port modes
     Returns a new port which is opened on a duplicate of the file
     descriptor underlying PORT, with mode string MODES as for *Note
     open-file: File Ports.  The two ports will share a file position
     and file status flags.

     Unexpected behaviour can result if both ports are subsequently used
     and the original and/or duplicate ports are buffered.  The mode
     string can include `0' to obtain an unbuffered duplicate port.

     This procedure is equivalent to `(dup->port PORT MODES)'.

 - Scheme Procedure: redirect-port old new
 - C Function: scm_redirect_port (old, new)
     This procedure takes two ports and duplicates the underlying file
     descriptor from OLD-PORT into NEW-PORT.  The current file
     descriptor in NEW-PORT will be closed.  After the redirection the
     two ports will share a file position and file status flags.

     The return value is unspecified.

     Unexpected behaviour can result if both ports are subsequently used
     and the original and/or duplicate ports are buffered.

     This procedure does not have any side effects on other ports or
     revealed counts.

 - Scheme Procedure: dup2 oldfd newfd
 - C Function: scm_dup2 (oldfd, newfd)
     A simple wrapper for the `dup2' system call.  Copies the file
     descriptor OLDFD to descriptor number NEWFD, replacing the
     previous meaning of NEWFD.  Both OLDFD and NEWFD must be integers.
     Unlike for dup->fdes or primitive-move->fdes, no attempt is made
     to move away ports which are using NEWFD.  The return value is
     unspecified.

 - Scheme Procedure: port-mode port
     Return the port modes associated with the open port PORT.  These
     will not necessarily be identical to the modes used when the port
     was opened, since modes such as "append" which are used only
     during port creation are not retained.

 - Scheme Procedure: port-for-each proc
 - C Function: scm_port_for_each (proc)
     Apply PROC to each port in the Guile port table in turn.  The
     return value is unspecified.  More specifically, PROC is applied
     exactly once to every port that exists in the system at the time
     PORT-FOR-EACH is invoked.  Changes to the port table while
     PORT-FOR-EACH is running have no effect as far as PORT-FOR-EACH is
     concerned.

 - Scheme Procedure: setvbuf port mode [size]
 - C Function: scm_setvbuf (port, mode, size)
     Set the buffering mode for PORT.  MODE can be:
    `_IONBF'
          non-buffered

    `_IOLBF'
          line buffered

    `_IOFBF'
          block buffered, using a newly allocated buffer of SIZE bytes.
          If SIZE is omitted, a default size will be used.

 - Scheme Procedure: fcntl object cmd [value]
 - C Function: scm_fcntl (object, cmd, value)
     Apply COMMAND to the specified file descriptor or the underlying
     file descriptor of the specified port.  VALUE is an optional
     integer argument.

     Values for COMMAND are:

    `F_DUPFD'
          Duplicate a file descriptor

    `F_GETFD'
          Get flags associated with the file descriptor.

    `F_SETFD'
          Set flags associated with the file descriptor to VALUE.

    `F_GETFL'
          Get flags associated with the open file.

    `F_SETFL'
          Set flags associated with the open file to VALUE

    `F_GETOWN'
          Get the process ID of a socket's owner, for `SIGIO' signals.

    `F_SETOWN'
          Set the process that owns a socket to VALUE, for `SIGIO'
          signals.

    `FD_CLOEXEC'
          The value used to indicate the "close on exec" flag with
          `F_GETFL' or `F_SETFL'.

 - Scheme Procedure: flock file operation
 - C Function: scm_flock (file, operation)
     Apply or remove an advisory lock on an open file.  OPERATION
     specifies the action to be done:
    `LOCK_SH'
          Shared lock.  More than one process may hold a shared lock
          for a given file at a given time.

    `LOCK_EX'
          Exclusive lock.  Only one process may hold an exclusive lock
          for a given file at a given time.

    `LOCK_UN'
          Unlock the file.

    `LOCK_NB'
          Don't block when locking.  May be specified by bitwise OR'ing
          it to one of the other operations.
     The return value is not specified. FILE may be an open file
     descriptor or an open file descriptor port.

 - Scheme Procedure: select reads writes excepts [secs [usecs]]
 - C Function: scm_select (reads, writes, excepts, secs, usecs)
     This procedure has a variety of uses: waiting for the ability to
     provide input, accept output, or the existence of exceptional
     conditions on a collection of ports or file descriptors, or
     waiting for a timeout to occur.  It also returns if interrupted by
     a signal.

     READS, WRITES and EXCEPTS can be lists or vectors, with each
     member a port or a file descriptor.  The value returned is a list
     of three corresponding lists or vectors containing only the
     members which meet the specified requirement.  The ability of port
     buffers to provide input or accept output is taken into account.
     Ordering of the input lists or vectors is not preserved.

     The optional arguments SECS and USECS specify the timeout.  Either
     SECS can be specified alone, as either an integer or a real
     number, or both SECS and USECS can be specified as integers, in
     which case USECS is an additional timeout expressed in
     microseconds.  If SECS is omitted or is `#f' then select will wait
     for as long as it takes for one of the other conditions to be
     satisfied.

     The scsh version of `select' differs as follows: Only vectors are
     accepted for the first three arguments.  The USECS argument is not
     supported.  Multiple values are returned instead of a list.
     Duplicates in the input vectors appear only once in output.  An
     additional `select!' interface is provided.


File: guile.info,  Node: File System,  Next: User Information,  Prev: Ports and File Descriptors,  Up: POSIX

File System
===========

   These procedures allow querying and setting file system attributes
(such as owner, permissions, sizes and types of files); deleting,
copying, renaming and linking files; creating and removing directories
and querying their contents; syncing the file system and creating
special files.

 - Scheme Procedure: access? path how
 - C Function: scm_access (path, how)
     Return `#t' if PATH corresponds to an existing file and the
     current process has the type of access specified by HOW, otherwise
     `#f'.  HOW should be specified using the values of the variables
     listed below.  Multiple values can be combined using a bitwise or,
     in which case `#t' will only be returned if all accesses are
     granted.

     Permissions are checked using the real id of the current process,
     not the effective id, although it's the effective id which
     determines whether the access would actually be granted.

      - Variable: R_OK
          test for read permission.

      - Variable: W_OK
          test for write permission.

      - Variable: X_OK
          test for execute permission.

      - Variable: F_OK
          test for existence of the file.

 - Scheme Procedure: stat object
 - C Function: scm_stat (object)
     Return an object containing various information about the file
     determined by OBJ.  OBJ can be a string containing a file name or
     a port or integer file descriptor which is open on a file (in
     which case `fstat' is used as the underlying system call).

     The object returned by `stat' can be passed as a single parameter
     to the following procedures, all of which return integers:

    `stat:dev'
          The device containing the file.

    `stat:ino'
          The file serial number, which distinguishes this file from all
          other files on the same device.

    `stat:mode'
          The mode of the file.  This includes file type information and
          the file permission bits.  See `stat:type' and `stat:perms'
          below.

    `stat:nlink'
          The number of hard links to the file.

    `stat:uid'
          The user ID of the file's owner.

    `stat:gid'
          The group ID of the file.

    `stat:rdev'
          Device ID; this entry is defined only for character or block
          special files.

    `stat:size'
          The size of a regular file in bytes.

    `stat:atime'
          The last access time for the file.

    `stat:mtime'
          The last modification time for the file.

    `stat:ctime'
          The last modification time for the attributes of the file.

    `stat:blksize'
          The optimal block size for reading or writing the file, in
          bytes.

    `stat:blocks'
          The amount of disk space that the file occupies measured in
          units of 512 byte blocks.

     In addition, the following procedures return the information from
     stat:mode in a more convenient form:

    `stat:type'
          A symbol representing the type of file.  Possible values are
          regular, directory, symlink, block-special, char-special,
          fifo, socket and unknown

    `stat:perms'
          An integer representing the access permission bits.

 - Scheme Procedure: lstat str
 - C Function: scm_lstat (str)
     Similar to `stat', but does not follow symbolic links, i.e., it
     will return information about a symbolic link itself, not the file
     it points to.  PATH must be a string.

 - Scheme Procedure: readlink path
 - C Function: scm_readlink (path)
     Return the value of the symbolic link named by PATH (a string),
     i.e., the file that the link points to.

 - Scheme Procedure: chown object owner group
 - C Function: scm_chown (object, owner, group)
     Change the ownership and group of the file referred to by OBJECT to
     the integer values OWNER and GROUP.  OBJECT can be a string
     containing a file name or, if the platform supports fchown, a port
     or integer file descriptor which is open on the file.  The return
     value is unspecified.

     If OBJECT is a symbolic link, either the ownership of the link or
     the ownership of the referenced file will be changed depending on
     the operating system (lchown is unsupported at present).  If OWNER
     or GROUP is specified as `-1', then that ID is not changed.

 - Scheme Procedure: chmod object mode
 - C Function: scm_chmod (object, mode)
     Changes the permissions of the file referred to by OBJ.  OBJ can
     be a string containing a file name or a port or integer file
     descriptor which is open on a file (in which case `fchmod' is used
     as the underlying system call).  MODE specifies the new
     permissions as a decimal number, e.g., `(chmod "foo" #o755)'.  The
     return value is unspecified.

 - Scheme Procedure: utime pathname [actime [modtime]]
 - C Function: scm_utime (pathname, actime, modtime)
     `utime' sets the access and modification times for the file named
     by PATH.  If ACTIME or MODTIME is not supplied, then the current
     time is used.  ACTIME and MODTIME must be integer time values as
     returned by the `current-time' procedure.
          (utime "foo" (- (current-time) 3600))
     will set the access time to one hour in the past and the
     modification time to the current time.

 - Scheme Procedure: delete-file str
 - C Function: scm_delete_file (str)
     Deletes (or "unlinks") the file specified by PATH.

 - Scheme Procedure: copy-file oldfile newfile
 - C Function: scm_copy_file (oldfile, newfile)
     Copy the file specified by PATH-FROM to PATH-TO.  The return value
     is unspecified.

 - Scheme Procedure: rename-file oldname newname
 - C Function: scm_rename (oldname, newname)
     Renames the file specified by OLDNAME to NEWNAME.  The return
     value is unspecified.

 - Scheme Procedure: link oldpath newpath
 - C Function: scm_link (oldpath, newpath)
     Creates a new name NEWPATH in the file system for the file named
     by OLDPATH.  If OLDPATH is a symbolic link, the link may or may
     not be followed depending on the system.

 - Scheme Procedure: symlink oldpath newpath
 - C Function: scm_symlink (oldpath, newpath)
     Create a symbolic link named PATH-TO with the value (i.e.,
     pointing to) PATH-FROM.  The return value is unspecified.

 - Scheme Procedure: mkdir path [mode]
 - C Function: scm_mkdir (path, mode)
     Create a new directory named by PATH.  If MODE is omitted then the
     permissions of the directory file are set using the current umask.
     Otherwise they are set to the decimal value specified with MODE.
     The return value is unspecified.

 - Scheme Procedure: rmdir path
 - C Function: scm_rmdir (path)
     Remove the existing directory named by PATH.  The directory must
     be empty for this to succeed.  The return value is unspecified.

 - Scheme Procedure: opendir dirname
 - C Function: scm_opendir (dirname)
     Open the directory specified by PATH and return a directory stream.

 - Scheme Procedure: directory-stream? obj
 - C Function: scm_directory_stream_p (obj)
     Return a boolean indicating whether OBJECT is a directory stream
     as returned by `opendir'.

 - Scheme Procedure: readdir port
 - C Function: scm_readdir (port)
     Return (as a string) the next directory entry from the directory
     stream STREAM.  If there is no remaining entry to be read then the
     end of file object is returned.

 - Scheme Procedure: rewinddir port
 - C Function: scm_rewinddir (port)
     Reset the directory port STREAM so that the next call to `readdir'
     will return the first directory entry.

 - Scheme Procedure: closedir port
 - C Function: scm_closedir (port)
     Close the directory stream STREAM.  The return value is
     unspecified.

   Here is an example showing how to display all the entries in a
directory:

     (define dir (opendir "/usr/lib"))
     (do ((entry (readdir dir) (readdir dir)))
         ((eof-object? entry))
       (display entry)(newline))
     (closedir dir)

 - Scheme Procedure: sync
 - C Function: scm_sync ()
     Flush the operating system disk buffers.  The return value is
     unspecified.

 - Scheme Procedure: mknod path type perms dev
 - C Function: scm_mknod (path, type, perms, dev)
     Creates a new special file, such as a file corresponding to a
     device.  PATH specifies the name of the file.  TYPE should be one
     of the following symbols: regular, directory, symlink,
     block-special, char-special, fifo, or socket.  PERMS (an integer)
     specifies the file permissions.  DEV (an integer) specifies which
     device the special file refers to.  Its exact interpretation
     depends on the kind of special file being created.

     E.g.,
          (mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))

     The return value is unspecified.

 - Scheme Procedure: tmpnam
 - C Function: scm_tmpnam ()
     Return a name in the file system that does not match any existing
     file.  However there is no guarantee that another process will not
     create the file after `tmpnam' is called.  Care should be taken if
     opening the file, e.g., use the `O_EXCL' open flag or use
     `mkstemp!' instead.

 - Scheme Procedure: mkstemp! tmpl
 - C Function: scm_mkstemp (tmpl)
     Create a new unique file in the file system and returns a new
     buffered port open for reading and writing to the file.  TMPL is a
     string specifying where the file should be created: it must end
     with `XXXXXX' and will be changed in place to return the name of
     the temporary file.

 - Scheme Procedure: dirname filename
 - C Function: scm_dirname (filename)
     Return the directory name component of the file name FILENAME. If
     FILENAME does not contain a directory component, `.' is returned.

 - Scheme Procedure: basename filename [suffix]
 - C Function: scm_basename (filename, suffix)
     Return the base name of the file name FILENAME. The base name is
     the file name without any directory components.  If SUFFIX is
     provided, and is equal to the end of BASENAME, it is removed also.

          (basename "/tmp/test.xml" ".xml")
          => "test"


File: guile.info,  Node: User Information,  Next: Time,  Prev: File System,  Up: POSIX

User Information
================

   The facilities in this section provide an interface to the user and
group database.  They should be used with care since they are not
reentrant.

   The following functions accept an object representing user
information and return a selected component:

`passwd:name'
     The name of the userid.

`passwd:passwd'
     The encrypted passwd.

`passwd:uid'
     The user id number.

`passwd:gid'
     The group id number.

`passwd:gecos'
     The full name.

`passwd:dir'
     The home directory.

`passwd:shell'
     The login shell.

 - Scheme Procedure: getpwuid uid
     Look up an integer userid in the user database.

 - Scheme Procedure: getpwnam name
     Look up a user name string in the user database.

 - Scheme Procedure: setpwent
     Initializes a stream used by `getpwent' to read from the user
     database.  The next use of `getpwent' will return the first entry.
     The return value is unspecified.

 - Scheme Procedure: getpwent
     Return the next entry in the user database, using the stream set by
     `setpwent'.

 - Scheme Procedure: endpwent
     Closes the stream used by `getpwent'.  The return value is
     unspecified.

 - Scheme Procedure: setpw [arg]
 - C Function: scm_setpwent (arg)
     If called with a true argument, initialize or reset the password
     data stream.  Otherwise, close the stream.  The `setpwent' and
     `endpwent' procedures are implemented on top of this.

 - Scheme Procedure: getpw [user]
 - C Function: scm_getpwuid (user)
     Look up an entry in the user database.  OBJ can be an integer, a
     string, or omitted, giving the behaviour of getpwuid, getpwnam or
     getpwent respectively.

   The following functions accept an object representing group
information and return a selected component:

`group:name'
     The group name.

`group:passwd'
     The encrypted group password.

`group:gid'
     The group id number.

`group:mem'
     A list of userids which have this group as a supplementary group.

 - Scheme Procedure: getgrgid gid
     Look up an integer group id in the group database.

 - Scheme Procedure: getgrnam name
     Look up a group name in the group database.

 - Scheme Procedure: setgrent
     Initializes a stream used by `getgrent' to read from the group
     database.  The next use of `getgrent' will return the first entry.
     The return value is unspecified.

 - Scheme Procedure: getgrent
     Return the next entry in the group database, using the stream set
     by `setgrent'.

 - Scheme Procedure: endgrent
     Closes the stream used by `getgrent'.  The return value is
     unspecified.

 - Scheme Procedure: setgr [arg]
 - C Function: scm_setgrent (arg)
     If called with a true argument, initialize or reset the group data
     stream.  Otherwise, close the stream.  The `setgrent' and
     `endgrent' procedures are implemented on top of this.

 - Scheme Procedure: getgr [name]
 - C Function: scm_getgrgid (name)
     Look up an entry in the group database.  OBJ can be an integer, a
     string, or omitted, giving the behaviour of getgrgid, getgrnam or
     getgrent respectively.

   In addition to the accessor procedures for the user database, the
following shortcut procedures are also available.

 - Scheme Procedure: cuserid
 - C Function: scm_cuserid ()
     Return a string containing a user name associated with the
     effective user id of the process.  Return `#f' if this information
     cannot be obtained.

 - Scheme Procedure: getlogin
 - C Function: scm_getlogin ()
     Return a string containing the name of the user logged in on the
     controlling terminal of the process, or `#f' if this information
     cannot be obtained.


File: guile.info,  Node: Time,  Next: Runtime Environment,  Prev: User Information,  Up: POSIX

Time
====

 - Scheme Procedure: current-time
 - C Function: scm_current_time ()
     Return the number of seconds since 1970-01-01 00:00:00 UTC,
     excluding leap seconds.

 - Scheme Procedure: gettimeofday
 - C Function: scm_gettimeofday ()
     Return a pair containing the number of seconds and microseconds
     since 1970-01-01 00:00:00 UTC, excluding leap seconds.  Note:
     whether true microsecond resolution is available depends on the
     operating system.

   The following procedures either accept an object representing a
broken down time and return a selected component, or accept an object
representing a broken down time and a value and set the component to
the value.  The numbers in parentheses give the usual range.

`tm:sec, set-tm:sec'
     Seconds (0-59).

`tm:min, set-tm:min'
     Minutes (0-59).

`tm:hour, set-tm:hour'
     Hours (0-23).

`tm:mday, set-tm:mday'
     Day of the month (1-31).

`tm:mon, set-tm:mon'
     Month (0-11).

`tm:year, set-tm:year'
     Year (70-), the year minus 1900.

`tm:wday, set-tm:wday'
     Day of the week (0-6) with Sunday represented as 0.

`tm:yday, set-tm:yday'
     Day of the year (0-364, 365 in leap years).

`tm:isdst, set-tm:isdst'
     Daylight saving indicator (0 for "no", greater than 0 for "yes",
     less than 0 for "unknown").

`tm:gmtoff, set-tm:gmtoff'
     Time zone offset in seconds west of UTC (-46800 to 43200).

`tm:zone, set-tm:zone'
     Time zone label (a string), not necessarily unique.

 - Scheme Procedure: localtime time [zone]
 - C Function: scm_localtime (time, zone)
     Return an object representing the broken down components of TIME,
     an integer like the one returned by `current-time'.  The time zone
     for the calculation is optionally specified by ZONE (a string),
     otherwise the `TZ' environment variable or the system default is
     used.

 - Scheme Procedure: gmtime time
 - C Function: scm_gmtime (time)
     Return an object representing the broken down components of TIME,
     an integer like the one returned by `current-time'.  The values
     are calculated for UTC.

 - Scheme Procedure: mktime sbd_time [zone]
 - C Function: scm_mktime (sbd_time, zone)
     BD-TIME is an object representing broken down time and `zone' is
     an optional time zone specifier (otherwise the TZ environment
     variable or the system default is used).

     Returns a pair: the car is a corresponding integer time value like
     that returned by `current-time'; the cdr is a broken down time
     object, similar to as BD-TIME but with normalized values.

 - Scheme Procedure: tzset
 - C Function: scm_tzset ()
     Initialize the timezone from the TZ environment variable or the
     system default.  It's not usually necessary to call this procedure
     since it's done automatically by other procedures that depend on
     the timezone.

 - Scheme Procedure: strftime format stime
 - C Function: scm_strftime (format, stime)
     Formats a time specification TIME using TEMPLATE.  TIME is an
     object with time components in the form returned by `localtime' or
     `gmtime'.  TEMPLATE is a string which can include formatting
     specifications introduced by a `%' character.  The formatting of
     month and day names is dependent on the current locale.  The value
     returned is the formatted string.  *Note Formatting Date and Time:
     (libc)Formatting Date and Time.)

          (strftime "%c" (localtime (current-time)))
          => "Mon Mar 11 20:17:43 2002"

 - Scheme Procedure: strptime format string
 - C Function: scm_strptime (format, string)
     Performs the reverse action to `strftime', parsing STRING
     according to the specification supplied in TEMPLATE.  The
     interpretation of month and day names is dependent on the current
     locale.  The value returned is a pair.  The car has an object with
     time components in the form returned by `localtime' or `gmtime',
     but the time zone components are not usefully set.  The cdr
     reports the number of characters from STRING which were used for
     the conversion.

 - Variable: internal-time-units-per-second
     The value of this variable is the number of time units per second
     reported by the following procedures.

 - Scheme Procedure: times
 - C Function: scm_times ()
     Return an object with information about real and processor time.
     The following procedures accept such an object as an argument and
     return a selected component:

    `tms:clock'
          The current real time, expressed as time units relative to an
          arbitrary base.

    `tms:utime'
          The CPU time units used by the calling process.

    `tms:stime'
          The CPU time units used by the system on behalf of the calling
          process.

    `tms:cutime'
          The CPU time units used by terminated child processes of the
          calling process, whose status has been collected (e.g., using
          `waitpid').

    `tms:cstime'
          Similarly, the CPU times units used by the system on behalf of
          terminated child processes.

 - Scheme Procedure: get-internal-real-time
 - C Function: scm_get_internal_real_time ()
     Return the number of time units since the interpreter was started.

 - Scheme Procedure: get-internal-run-time
 - C Function: scm_get_internal_run_time ()
     Return the number of time units of processor time used by the
     interpreter.  Both _system_ and _user_ time are included but
     subprocesses are not.


File: guile.info,  Node: Runtime Environment,  Next: Processes,  Prev: Time,  Up: POSIX

Runtime Environment
===================

 - Scheme Procedure: program-arguments
 - Scheme Procedure: command-line
 - C Function: scm_program_arguments ()
     Return the list of command line arguments passed to Guile, as a
     list of strings.  The list includes the invoked program name,
     which is usually `"guile"', but excludes switches and parameters
     for command line options like `-e' and `-l'.

 - Scheme Procedure: getenv nam
 - C Function: scm_getenv (nam)
     Looks up the string NAME in the current environment.  The return
     value is `#f' unless a string of the form `NAME=VALUE' is found,
     in which case the string `VALUE' is returned.

 - Scheme Procedure: setenv name value
     Modifies the environment of the current process, which is also the
     default environment inherited by child processes.

     If VALUE is `#f', then NAME is removed from the environment.
     Otherwise, the string NAME=VALUE is added to the environment,
     replacing any existing string with name matching NAME.

     The return value is unspecified.

 - Scheme Procedure: environ [env]
 - C Function: scm_environ (env)
     If ENV is omitted, return the current environment (in the Unix
     sense) as a list of strings.  Otherwise set the current
     environment, which is also the default environment for child
     processes, to the supplied list of strings.  Each member of ENV
     should be of the form `NAME=VALUE' and values of `NAME' should not
     be duplicated.  If ENV is supplied then the return value is
     unspecified.

 - Scheme Procedure: putenv str
 - C Function: scm_putenv (str)
     Modifies the environment of the current process, which is also the
     default environment inherited by child processes.

     If STRING is of the form `NAME=VALUE' then it will be written
     directly into the environment, replacing any existing environment
     string with name matching `NAME'.  If STRING does not contain an
     equal sign, then any existing string with name matching STRING will
     be removed.

     The return value is unspecified.


File: guile.info,  Node: Processes,  Next: Signals,  Prev: Runtime Environment,  Up: POSIX

Processes
=========

 - Scheme Procedure: chdir str
 - C Function: scm_chdir (str)
     Change the current working directory to PATH.  The return value is
     unspecified.

 - Scheme Procedure: getcwd
 - C Function: scm_getcwd ()
     Return the name of the current working directory.

 - Scheme Procedure: umask [mode]
 - C Function: scm_umask (mode)
     If MODE is omitted, returns a decimal number representing the
     current file creation mask.  Otherwise the file creation mask is
     set to MODE and the previous value is returned.

     E.g., `(umask #o022)' sets the mask to octal 22, decimal 18.

 - Scheme Procedure: chroot path
 - C Function: scm_chroot (path)
     Change the root directory to that specified in PATH.  This
     directory will be used for path names beginning with `/'.  The
     root directory is inherited by all children of the current
     process.  Only the superuser may change the root directory.

 - Scheme Procedure: getpid
 - C Function: scm_getpid ()
     Return an integer representing the current process ID.

 - Scheme Procedure: getgroups
 - C Function: scm_getgroups ()
     Return a vector of integers representing the current supplementary
     group IDs.

 - Scheme Procedure: getppid
 - C Function: scm_getppid ()
     Return an integer representing the process ID of the parent
     process.

 - Scheme Procedure: getuid
 - C Function: scm_getuid ()
     Return an integer representing the current real user ID.

 - Scheme Procedure: getgid
 - C Function: scm_getgid ()
     Return an integer representing the current real group ID.

 - Scheme Procedure: geteuid
 - C Function: scm_geteuid ()
     Return an integer representing the current effective user ID.  If
     the system does not support effective IDs, then the real ID is
     returned.  `(feature? 'EIDs)' reports whether the system supports
     effective IDs.

 - Scheme Procedure: getegid
 - C Function: scm_getegid ()
     Return an integer representing the current effective group ID.  If
     the system does not support effective IDs, then the real ID is
     returned.  `(feature? 'EIDs)' reports whether the system supports
     effective IDs.

 - Scheme Procedure: setuid id
 - C Function: scm_setuid (id)
     Sets both the real and effective user IDs to the integer ID,
     provided the process has appropriate privileges.  The return value
     is unspecified.

 - Scheme Procedure: setgid id
 - C Function: scm_setgid (id)
     Sets both the real and effective group IDs to the integer ID,
     provided the process has appropriate privileges.  The return value
     is unspecified.

 - Scheme Procedure: seteuid id
 - C Function: scm_seteuid (id)
     Sets the effective user ID to the integer ID, provided the process
     has appropriate privileges.  If effective IDs are not supported,
     the real ID is set instead - `(feature? 'EIDs)' reports whether the
     system supports effective IDs.  The return value is unspecified.

 - Scheme Procedure: setegid id
 - C Function: scm_setegid (id)
     Sets the effective group ID to the integer ID, provided the process
     has appropriate privileges.  If effective IDs are not supported,
     the real ID is set instead - `(feature? 'EIDs)' reports whether the
     system supports effective IDs.  The return value is unspecified.

 - Scheme Procedure: getpgrp
 - C Function: scm_getpgrp ()
     Return an integer representing the current process group ID.  This
     is the POSIX definition, not BSD.

 - Scheme Procedure: setpgid pid pgid
 - C Function: scm_setpgid (pid, pgid)
     Move the process PID into the process group PGID.  PID or PGID
     must be integers: they can be zero to indicate the ID of the
     current process.  Fails on systems that do not support job control.
     The return value is unspecified.

 - Scheme Procedure: setsid
 - C Function: scm_setsid ()
     Creates a new session.  The current process becomes the session
     leader and is put in a new process group.  The process will be
     detached from its controlling terminal if it has one.  The return
     value is an integer representing the new process group ID.

 - Scheme Procedure: waitpid pid [options]
 - C Function: scm_waitpid (pid, options)
     This procedure collects status information from a child process
     which has terminated or (optionally) stopped.  Normally it will
     suspend the calling process until this can be done.  If more than
     one child process is eligible then one will be chosen by the
     operating system.

     The value of PID determines the behaviour:

    PID greater than 0
          Request status information from the specified child process.

    PID equal to -1 or WAIT_ANY
          Request status information for any child process.

    PID equal to 0 or WAIT_MYPGRP
          Request status information for any child process in the
          current process group.

    PID less than -1
          Request status information for any child process whose
          process group ID is -PID.

     The OPTIONS argument, if supplied, should be the bitwise OR of the
     values of zero or more of the following variables:

      - Variable: WNOHANG
          Return immediately even if there are no child processes to be
          collected.

      - Variable: WUNTRACED
          Report status information for stopped processes as well as
          terminated processes.

     The return value is a pair containing:

       1. The process ID of the child process, or 0 if `WNOHANG' was
          specified and no process was collected.

       2. The integer status value.

   The following three functions can be used to decode the process
status code returned by `waitpid'.

 - Scheme Procedure: status:exit-val status
 - C Function: scm_status_exit_val (status)
     Return the exit status value, as would be set if a process ended
     normally through a call to `exit' or `_exit', if any, otherwise
     `#f'.

 - Scheme Procedure: status:term-sig status
 - C Function: scm_status_term_sig (status)
     Return the signal number which terminated the process, if any,
     otherwise `#f'.

 - Scheme Procedure: status:stop-sig status
 - C Function: scm_status_stop_sig (status)
     Return the signal number which stopped the process, if any,
     otherwise `#f'.

 - Scheme Procedure: system [cmd]
 - C Function: scm_system (cmd)
     Execute CMD using the operating system's "command processor".
     Under Unix this is usually the default shell `sh'.  The value
     returned is CMD's exit status as returned by `waitpid', which can
     be interpreted using the functions above.

     If `system' is called without arguments, return a boolean
     indicating whether the command processor is available.

 - Scheme Procedure: primitive-exit [status]
 - C Function: scm_primitive_exit (status)
     Terminate the current process without unwinding the Scheme stack.
     This is would typically be useful after a fork.  The exit status
     is STATUS if supplied, otherwise zero.

 - Scheme Procedure: execl filename . args
 - C Function: scm_execl (filename, args)
     Executes the file named by PATH as a new process image.  The
     remaining arguments are supplied to the process; from a C program
     they are accessible as the `argv' argument to `main'.
     Conventionally the first ARG is the same as PATH.  All arguments
     must be strings.

     If ARG is missing, PATH is executed with a null argument list,
     which may have system-dependent side-effects.

     This procedure is currently implemented using the `execv' system
     call, but we call it `execl' because of its Scheme calling
     interface.

 - Scheme Procedure: execlp filename . args
 - C Function: scm_execlp (filename, args)
     Similar to `execl', however if FILENAME does not contain a slash
     then the file to execute will be located by searching the
     directories listed in the `PATH' environment variable.

     This procedure is currently implemented using the `execvp' system
     call, but we call it `execlp' because of its Scheme calling
     interface.

 - Scheme Procedure: execle filename env . args
 - C Function: scm_execle (filename, env, args)
     Similar to `execl', but the environment of the new process is
     specified by ENV, which must be a list of strings as returned by
     the `environ' procedure.

     This procedure is currently implemented using the `execve' system
     call, but we call it `execle' because of its Scheme calling
     interface.

 - Scheme Procedure: primitive-fork
 - C Function: scm_fork ()
     Creates a new "child" process by duplicating the current "parent"
     process.  In the child the return value is 0.  In the parent the
     return value is the integer process ID of the child.

     This procedure has been renamed from `fork' to avoid a naming
     conflict with the scsh fork.

 - Scheme Procedure: nice incr
 - C Function: scm_nice (incr)
     Increment the priority of the current process by INCR.  A higher
     priority value means that the process runs less often.  The return
     value is unspecified.

 - Scheme Procedure: setpriority which who prio
 - C Function: scm_setpriority (which, who, prio)
     Set the scheduling priority of the process, process group or user,
     as indicated by WHICH and WHO. WHICH is one of the variables
     `PRIO_PROCESS', `PRIO_PGRP' or `PRIO_USER', and WHO is interpreted
     relative to WHICH (a process identifier for `PRIO_PROCESS',
     process group identifier for `PRIO_PGRP', and a user identifier
     for `PRIO_USER'.  A zero value of WHO denotes the current process,
     process group, or user.  PRIO is a value in the range -20 and 20,
     the default priority is 0; lower priorities cause more favorable
     scheduling.  Sets the priority of all of the specified processes.
     Only the super-user may lower priorities.  The return value is not
     specified.

 - Scheme Procedure: getpriority which who
 - C Function: scm_getpriority (which, who)
     Return the scheduling priority of the process, process group or
     user, as indicated by WHICH and WHO. WHICH is one of the variables
     `PRIO_PROCESS', `PRIO_PGRP' or `PRIO_USER', and WHO is interpreted
     relative to WHICH (a process identifier for `PRIO_PROCESS',
     process group identifier for `PRIO_PGRP', and a user identifier
     for `PRIO_USER'.  A zero value of WHO denotes the current process,
     process group, or user.  Return the highest priority (lowest
     numerical value) of any of the specified processes.


File: guile.info,  Node: Signals,  Next: Terminals and Ptys,  Prev: Processes,  Up: POSIX

Signals
=======

   Procedures to raise, handle and wait for signals.

 - Scheme Procedure: kill pid sig
 - C Function: scm_kill (pid, sig)
     Sends a signal to the specified process or group of processes.

     PID specifies the processes to which the signal is sent:

    PID greater than 0
          The process whose identifier is PID.

    PID equal to 0
          All processes in the current process group.

    PID less than -1
          The process group whose identifier is -PID

    PID equal to -1
          If the process is privileged, all processes except for some
          special system processes.  Otherwise, all processes with the
          current effective user ID.

     SIG should be specified using a variable corresponding to the Unix
     symbolic name, e.g.,

      - Variable: SIGHUP
          Hang-up signal.

      - Variable: SIGINT
          Interrupt signal.

 - Scheme Procedure: raise sig
 - C Function: scm_raise (sig)
     Sends a specified signal SIG to the current process, where SIG is
     as described for the kill procedure.

 - Scheme Procedure: sigaction signum [handler [flags]]
 - C Function: scm_sigaction (signum, handler, flags)
     Install or report the signal handler for a specified signal.

     SIGNUM is the signal number, which can be specified using the value
     of variables such as `SIGINT'.

     If ACTION is omitted, `sigaction' returns a pair: the CAR is the
     current signal hander, which will be either an integer with the
     value `SIG_DFL' (default action) or `SIG_IGN' (ignore), or the
     Scheme procedure which handles the signal, or `#f' if a non-Scheme
     procedure handles the signal.  The CDR contains the current
     `sigaction' flags for the handler.

     If ACTION is provided, it is installed as the new handler for
     SIGNUM.  ACTION can be a Scheme procedure taking one argument, or
     the value of `SIG_DFL' (default action) or `SIG_IGN' (ignore), or
     `#f' to restore whatever signal handler was installed before
     `sigaction' was first used.  Flags can optionally be specified for
     the new handler (`SA_RESTART' will always be added if it's
     available and the system is using restartable system calls.)  The
     return value is a pair with information about the old handler as
     described above.

     This interface does not provide access to the "signal blocking"
     facility.  Maybe this is not needed, since the thread support may
     provide solutions to the problem of consistent access to data
     structures.

 - Scheme Procedure: restore-signals
 - C Function: scm_restore_signals ()
     Return all signal handlers to the values they had before any call
     to `sigaction' was made.  The return value is unspecified.

 - Scheme Procedure: alarm i
 - C Function: scm_alarm (i)
     Set a timer to raise a `SIGALRM' signal after the specified number
     of seconds (an integer).  It's advisable to install a signal
     handler for `SIGALRM' beforehand, since the default action is to
     terminate the process.

     The return value indicates the time remaining for the previous
     alarm, if any.  The new value replaces the previous alarm.  If
     there was no previous alarm, the return value is zero.

 - Scheme Procedure: pause
 - C Function: scm_pause ()
     Pause the current process (thread?) until a signal arrives whose
     action is to either terminate the current process or invoke a
     handler procedure.  The return value is unspecified.

 - Scheme Procedure: sleep i
 - C Function: scm_sleep (i)
     Wait for the given number of seconds (an integer) or until a signal
     arrives.  The return value is zero if the time elapses or the
     number of seconds remaining otherwise.

 - Scheme Procedure: usleep i
 - C Function: scm_usleep (i)
     Sleep for I microseconds.  `usleep' is not available on all
     platforms.

 - Scheme Procedure: setitimer which_timer interval_seconds
          interval_microseconds value_seconds value_microseconds
 - C Function: scm_setitimer (which_timer, interval_seconds,
          interval_microseconds, value_seconds, value_microseconds)
     Set the timer specified by WHICH_TIMER according to the given
     INTERVAL_SECONDS, INTERVAL_MICROSECONDS, VALUE_SECONDS, and
     VALUE_MICROSECONDS values.

     Return information about the timer's previous setting.  Errors are
     handled as described in the guile info pages under "POSIX
     Interface Conventions".

     The timers available are: `ITIMER_REAL', `ITIMER_VIRTUAL', and
     `ITIMER_PROF'.

     The return value will be a list of two cons pairs representing the
     current state of the given timer.  The first pair is the seconds
     and microseconds of the timer `it_interval', and the second pair is
     the seconds and microseconds of the timer `it_value'.

 - Scheme Procedure: getitimer which_timer
 - C Function: scm_getitimer (which_timer)
     Return information about the timer specified by WHICH_TIMER Errors
     are handled as described in the guile info pages under "POSIX
     Interface Conventions".

     The timers available are: `ITIMER_REAL', `ITIMER_VIRTUAL', and
     `ITIMER_PROF'.

     The return value will be a list of two cons pairs representing the
     current state of the given timer.  The first pair is the seconds
     and microseconds of the timer `it_interval', and the second pair is
     the seconds and microseconds of the timer `it_value'.


File: guile.info,  Node: Terminals and Ptys,  Next: Pipes,  Prev: Signals,  Up: POSIX

Terminals and Ptys
==================

 - Scheme Procedure: isatty? port
 - C Function: scm_isatty_p (port)
     Return `#t' if PORT is using a serial non-file device, otherwise
     `#f'.

 - Scheme Procedure: ttyname port
 - C Function: scm_ttyname (port)
     Return a string with the name of the serial terminal device
     underlying PORT.

 - Scheme Procedure: ctermid
 - C Function: scm_ctermid ()
     Return a string containing the file name of the controlling
     terminal for the current process.

 - Scheme Procedure: tcgetpgrp port
 - C Function: scm_tcgetpgrp (port)
     Return the process group ID of the foreground process group
     associated with the terminal open on the file descriptor
     underlying PORT.

     If there is no foreground process group, the return value is a
     number greater than 1 that does not match the process group ID of
     any existing process group.  This can happen if all of the
     processes in the job that was formerly the foreground job have
     terminated, and no other job has yet been moved into the
     foreground.

 - Scheme Procedure: tcsetpgrp port pgid
 - C Function: scm_tcsetpgrp (port, pgid)
     Set the foreground process group ID for the terminal used by the
     file descriptor underlying PORT to the integer PGID.  The calling
     process must be a member of the same session as PGID and must have
     the same controlling terminal.  The return value is unspecified.


File: guile.info,  Node: Pipes,  Next: Networking,  Prev: Terminals and Ptys,  Up: POSIX

Pipes
=====

   The following procedures provide an interface to the `popen' and
`pclose' system routines.  The code is in a separate "popen" module:

     (use-modules (ice-9 popen))

 - Scheme Procedure: open-pipe command modes
     Executes the shell command COMMAND (a string) in a subprocess.  A
     pipe to the process is created and returned.  MODES specifies
     whether an input or output pipe to the process is created: it
     should be the value of `OPEN_READ' or `OPEN_WRITE'.

 - Scheme Procedure: open-input-pipe command
     Equivalent to `open-pipe' with mode `OPEN_READ'.

          (read-line (open-input-pipe "date"))
          => "Mon Mar 11 20:10:44 GMT 2002"
          
          (waitpid WAIT_ANY)
          => (24160 . 0)

 - Scheme Procedure: open-output-pipe command
     Equivalent to `open-pipe' with mode `OPEN_WRITE'.

 - Scheme Procedure: close-pipe port
     Closes the pipe created by `open-pipe', then waits for the process
     to terminate and returns its status value, *Note waitpid:
     Processes, for information on how to interpret this value.

     `close-port' (*note close-port: Closing.) can also be used to
     close a pipe, but doesn't return the status.


File: guile.info,  Node: Networking,  Next: System Identification,  Prev: Pipes,  Up: POSIX

Networking
==========

* Menu:

* Network Address Conversion::
* Network Databases::
* Network Sockets and Communication::
* Internet Socket Examples::


File: guile.info,  Node: Network Address Conversion,  Next: Network Databases,  Up: Networking

Network Address Conversion
--------------------------

   This section describes procedures which convert internet addresses
between numeric and string formats.

IPv4 Address Conversion
.......................

 - Scheme Procedure: inet-aton address
 - C Function: scm_inet_aton (address)
     Convert an IPv4 Internet address from printable string (dotted
     decimal notation) to an integer.  E.g.,

          (inet-aton "127.0.0.1") => 2130706433

 - Scheme Procedure: inet-ntoa inetid
 - C Function: scm_inet_ntoa (inetid)
     Convert an IPv4 Internet address to a printable (dotted decimal
     notation) string.  E.g.,

          (inet-ntoa 2130706433) => "127.0.0.1"

 - Scheme Procedure: inet-netof address
 - C Function: scm_inet_netof (address)
     Return the network number part of the given IPv4 Internet address.
     E.g.,

          (inet-netof 2130706433) => 127

 - Scheme Procedure: inet-lnaof address
 - C Function: scm_lnaof (address)
     Return the local-address-with-network part of the given IPv4
     Internet address, using the obsolete class A/B/C system.  E.g.,

          (inet-lnaof 2130706433) => 1

 - Scheme Procedure: inet-makeaddr net lna
 - C Function: scm_inet_makeaddr (net, lna)
     Make an IPv4 Internet address by combining the network number NET
     with the local-address-within-network number LNA.  E.g.,

          (inet-makeaddr 127 1) => 2130706433

IPv6 Address Conversion
.......................

 - Scheme Procedure: inet-ntop family address
 - C Function: scm_inet_ntop (family, address)
     Convert a network address into a printable string.  Note that
     unlike the C version of this function, the input is an integer
     with normal host byte ordering.  FAMILY can be `AF_INET' or
     `AF_INET6'.  E.g.,

          (inet-ntop AF_INET 2130706433) => "127.0.0.1"
          (inet-ntop AF_INET6 (- (expt 2 128) 1)) =>
          ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff

 - Scheme Procedure: inet-pton family address
 - C Function: scm_inet_pton (family, address)
     Convert a string containing a printable network address to an
     integer address.  Note that unlike the C version of this function,
     the result is an integer with normal host byte ordering.  FAMILY
     can be `AF_INET' or `AF_INET6'.  E.g.,

          (inet-pton AF_INET "127.0.0.1") => 2130706433
          (inet-pton AF_INET6 "::1") => 1


File: guile.info,  Node: Network Databases,  Next: Network Sockets and Communication,  Prev: Network Address Conversion,  Up: Networking

Network Databases
-----------------

   This section describes procedures which query various network
databases.  Care should be taken when using the database routines since
they are not reentrant.

The Host Database
.................

   A "host object" is a structure that represents what is known about a
network host, and is the usual way of representing a system's network
identity inside software.

   The following functions accept a host object and return a selected
component:

 - Scheme Procedure: hostent:name host
     The "official" hostname for HOST.

 - Scheme Procedure: hostent:aliases host
     A list of aliases for HOST.

 - Scheme Procedure: hostent:addrtype host
     The host address type.  For hosts with Internet addresses, this
     will return `AF_INET'.

 - Scheme Procedure: hostent:length host
     The length of each address for HOST, in bytes.

 - Scheme Procedure: hostent:addr-list host
     The list of network addresses associated with HOST.

   The following procedures are used to search the host database:

 - Scheme Procedure: gethost [host]
 - Scheme Procedure: gethostbyname hostname
 - Scheme Procedure: gethostbyaddr address
 - C Function: scm_gethost (host)
     Look up a host by name or address, returning a host object.  The
     `gethost' procedure will accept either a string name or an integer
     address; if given no arguments, it behaves like `gethostent' (see
     below).  If a name or address is supplied but the address can not
     be found, an error will be thrown to one of the keys:
     `host-not-found', `try-again', `no-recovery' or `no-data',
     corresponding to the equivalent `h_error' values.  Unusual
     conditions may result in errors thrown to the `system-error' or
     `misc_error' keys.

          (gethost "www.gnu.org")
          => #("www.gnu.org" () 2 4 (3353880842))
          
          (gethostbyname "www.emacs.org")
          => #("emacs.org" ("www.emacs.org") 2 4 (1073448978))

   The following procedures may be used to step through the host
database from beginning to end.

 - Scheme Procedure: sethostent [stayopen]
     Initialize an internal stream from which host objects may be read.
     This procedure must be called before any calls to `gethostent',
     and may also be called afterward to reset the host entry stream.
     If STAYOPEN is supplied and is not `#f', the database is not
     closed by subsequent `gethostbyname' or `gethostbyaddr' calls,
     possibly giving an efficiency gain.

 - Scheme Procedure: gethostent
     Return the next host object from the host database, or `#f' if
     there are no more hosts to be found (or an error has been
     encountered).  This procedure may not be used before `sethostent'
     has been called.

 - Scheme Procedure: endhostent
     Close the stream used by `gethostent'.  The return value is
     unspecified.

 - Scheme Procedure: sethost [stayopen]
 - C Function: scm_sethost (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endhostent'.
     Otherwise it is equivalent to `sethostent stayopen'.

The Network Database
....................

   The following functions accept an object representing a network and
return a selected component:

 - Scheme Procedure: netent:name net
     The "official" network name.

 - Scheme Procedure: netent:aliases net
     A list of aliases for the network.

 - Scheme Procedure: netent:addrtype net
     The type of the network number.  Currently, this returns only
     `AF_INET'.

 - Scheme Procedure: netent:net net
     The network number.

   The following procedures are used to search the network database:

 - Scheme Procedure: getnet [net]
 - Scheme Procedure: getnetbyname net-name
 - Scheme Procedure: getnetbyaddr net-number
 - C Function: scm_getnet (net)
     Look up a network by name or net number in the network database.
     The NET-NAME argument must be a string, and the NET-NUMBER
     argument must be an integer.  `getnet' will accept either type of
     argument, behaving like `getnetent' (see below) if no arguments are
     given.

   The following procedures may be used to step through the network
database from beginning to end.

 - Scheme Procedure: setnetent [stayopen]
     Initialize an internal stream from which network objects may be
     read.  This procedure must be called before any calls to
     `getnetent', and may also be called afterward to reset the net
     entry stream.  If STAYOPEN is supplied and is not `#f', the
     database is not closed by subsequent `getnetbyname' or
     `getnetbyaddr' calls, possibly giving an efficiency gain.

 - Scheme Procedure: getnetent
     Return the next entry from the network database.

 - Scheme Procedure: endnetent
     Close the stream used by `getnetent'.  The return value is
     unspecified.

 - Scheme Procedure: setnet [stayopen]
 - C Function: scm_setnet (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endnetent'.
     Otherwise it is equivalent to `setnetent stayopen'.

The Protocol Database
.....................

   The following functions accept an object representing a protocol and
return a selected component:

 - Scheme Procedure: protoent:name protocol
     The "official" protocol name.

 - Scheme Procedure: protoent:aliases protocol
     A list of aliases for the protocol.

 - Scheme Procedure: protoent:proto protocol
     The protocol number.

   The following procedures are used to search the protocol database:

 - Scheme Procedure: getproto [protocol]
 - Scheme Procedure: getprotobyname name
 - Scheme Procedure: getprotobynumber number
 - C Function: scm_getproto (protocol)
     Look up a network protocol by name or by number.  `getprotobyname'
     takes a string argument, and `getprotobynumber' takes an integer
     argument.  `getproto' will accept either type, behaving like
     `getprotoent' (see below) if no arguments are supplied.

   The following procedures may be used to step through the protocol
database from beginning to end.

 - Scheme Procedure: setprotoent [stayopen]
     Initialize an internal stream from which protocol objects may be
     read.  This procedure must be called before any calls to
     `getprotoent', and may also be called afterward to reset the
     protocol entry stream.  If STAYOPEN is supplied and is not `#f',
     the database is not closed by subsequent `getprotobyname' or
     `getprotobynumber' calls, possibly giving an efficiency gain.

 - Scheme Procedure: getprotoent
     Return the next entry from the protocol database.

 - Scheme Procedure: endprotoent
     Close the stream used by `getprotoent'.  The return value is
     unspecified.

 - Scheme Procedure: setproto [stayopen]
 - C Function: scm_setproto (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endprotoent'.
     Otherwise it is equivalent to `setprotoent stayopen'.

The Service Database
....................

   The following functions accept an object representing a service and
return a selected component:

 - Scheme Procedure: servent:name serv
     The "official" name of the network service.

 - Scheme Procedure: servent:aliases serv
     A list of aliases for the network service.

 - Scheme Procedure: servent:port serv
     The Internet port used by the service.

 - Scheme Procedure: servent:proto serv
     The protocol used by the service.  A service may be listed many
     times in the database under different protocol names.

   The following procedures are used to search the service database:

 - Scheme Procedure: getserv [name [protocol]]
 - Scheme Procedure: getservbyname name protocol
 - Scheme Procedure: getservbyport port protocol
 - C Function: scm_getserv (name, protocol)
     Look up a network service by name or by service number, and return
     a network service object.  The PROTOCOL argument specifies the name
     of the desired protocol; if the protocol found in the network
     service database does not match this name, a system error is
     signalled.

     The `getserv' procedure will take either a service name or number
     as its first argument; if given no arguments, it behaves like
     `getservent' (see below).

          (getserv "imap" "tcp")
          => #("imap2" ("imap") 143 "tcp")
          
          (getservbyport 88 "udp")
          => #("kerberos" ("kerberos5" "krb5") 88 "udp")

   The following procedures may be used to step through the service
database from beginning to end.

 - Scheme Procedure: setservent [stayopen]
     Initialize an internal stream from which service objects may be
     read.  This procedure must be called before any calls to
     `getservent', and may also be called afterward to reset the
     service entry stream.  If STAYOPEN is supplied and is not `#f',
     the database is not closed by subsequent `getservbyname' or
     `getservbyport' calls, possibly giving an efficiency gain.

 - Scheme Procedure: getservent
     Return the next entry from the services database.

 - Scheme Procedure: endservent
     Close the stream used by `getservent'.  The return value is
     unspecified.

 - Scheme Procedure: setserv [stayopen]
 - C Function: scm_setserv (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endservent'.
     Otherwise it is equivalent to `setservent stayopen'.


File: guile.info,  Node: Network Sockets and Communication,  Next: Internet Socket Examples,  Prev: Network Databases,  Up: Networking

Network Sockets and Communication
---------------------------------

   Socket ports can be created using `socket' and `socketpair'.  The
ports are initially unbuffered, to make reading and writing to the same
port more reliable.  A buffer can be added to the port using `setvbuf',
*Note Ports and File Descriptors::.

   The convention used for "host" vs "network" addresses is that
addresses are always held in host order at the Scheme level.  The
procedures in this section automatically convert between host and
network order when required.  The arguments and return values are thus
in host order.

 - Scheme Procedure: socket family style proto
 - C Function: scm_socket (family, style, proto)
     Return a new socket port of the type specified by FAMILY, STYLE
     and PROTO.  All three parameters are integers.  Supported values
     for FAMILY are `AF_UNIX', `AF_INET' and `AF_INET6'.  Typical
     values for STYLE are `SOCK_STREAM', `SOCK_DGRAM' and `SOCK_RAW'.

     PROTO can be obtained from a protocol name using `getprotobyname'.
     A value of zero specifies the default protocol, which is usually
     right.

     A single socket port cannot by used for communication until it has
     been connected to another socket.

 - Scheme Procedure: socketpair family style proto
 - C Function: scm_socketpair (family, style, proto)
     Return a pair of connected (but unnamed) socket ports of the type
     specified by FAMILY, STYLE and PROTO.  Many systems support only
     socket pairs of the `AF_UNIX' family.  Zero is likely to be the
     only meaningful value for PROTO.

 - Scheme Procedure: getsockopt sock level optname
 - C Function: scm_getsockopt (sock, level, optname)
     Return the value of a particular socket option for the socket port
     SOCK.  LEVEL is an integer code for type of option being
     requested, e.g., `SOL_SOCKET' for socket-level options.  OPTNAME
     is an integer code for the option required and should be specified
     using one of the symbols `SO_DEBUG', `SO_REUSEADDR' etc.

     The returned value is typically an integer but `SO_LINGER' returns
     a pair of integers.

 - Scheme Procedure: setsockopt sock level optname value
 - C Function: scm_setsockopt (sock, level, optname, value)
     Set the value of a particular socket option for the socket port
     SOCK.  LEVEL is an integer code for type of option being set,
     e.g., `SOL_SOCKET' for socket-level options.  OPTNAME is an
     integer code for the option to set and should be specified using
     one of the symbols `SO_DEBUG', `SO_REUSEADDR' etc.  VALUE is the
     value to which the option should be set.  For most options this
     must be an integer, but for `SO_LINGER' it must be a pair.

     The return value is unspecified.

 - Scheme Procedure: shutdown sock how
 - C Function: scm_shutdown (sock, how)
     Sockets can be closed simply by using `close-port'. The `shutdown'
     procedure allows reception or transmission on a connection to be
     shut down individually, according to the parameter HOW:

    0
          Stop receiving data for this socket.  If further data
          arrives,  reject it.

    1
          Stop trying to transmit data from this socket.  Discard any
          data waiting to be sent.  Stop looking for acknowledgement of
          data already sent; don't retransmit it if it is lost.

    2
          Stop both reception and transmission.

     The return value is unspecified.

 - Scheme Procedure: connect sock fam address . args
 - C Function: scm_connect (sock, fam, address, args)
     Initiate a connection from a socket using a specified address
     family to the address specified by ADDRESS and possibly ARGS.  The
     format required for ADDRESS and ARGS depends on the family of the
     socket.

     For a socket of family `AF_UNIX', only ADDRESS is specified and
     must be a string with the filename where the socket is to be
     created.

     For a socket of family `AF_INET', ADDRESS must be an integer IPv4
     host address and ARGS must be a single integer port number.

     For a socket of family `AF_INET6', ADDRESS must be an integer IPv6
     host address and ARGS may be up to three integers: port [flowinfo]
     [scope_id], where flowinfo and scope_id default to zero.

     The return value is unspecified.

 - Scheme Procedure: bind sock fam address . args
 - C Function: scm_bind (sock, fam, address, args)
     Assign an address to the socket port SOCK.  Generally this only
     needs to be done for server sockets, so they know where to look
     for incoming connections.  A socket without an address will be
     assigned one automatically when it starts communicating.

     The format of ADDRESS and ARGS depends on the family of the socket.

     For a socket of family `AF_UNIX', only ADDRESS is specified and
     must be a string with the filename where the socket is to be
     created.

     For a socket of family `AF_INET', ADDRESS must be an integer IPv4
     address and ARGS must be a single integer port number.

     The values of the following variables can also be used for ADDRESS:

      - Variable: INADDR_ANY
          Allow connections from any address.

      - Variable: INADDR_LOOPBACK
          The address of the local host using the loopback device.

      - Variable: INADDR_BROADCAST
          The broadcast address on the local network.

      - Variable: INADDR_NONE
          No address.

     For a socket of family `AF_INET6', ADDRESS must be an integer IPv6
     address and ARGS may be up to three integers: port [flowinfo]
     [scope_id], where flowinfo and scope_id default to zero.

     The return value is unspecified.

 - Scheme Procedure: listen sock backlog
 - C Function: scm_listen (sock, backlog)
     Enable SOCK to accept connection requests.  BACKLOG is an integer
     specifying the maximum length of the queue for pending connections.
     If the queue fills, new clients will fail to connect until the
     server calls `accept' to accept a connection from the queue.

     The return value is unspecified.

 - Scheme Procedure: accept sock
 - C Function: scm_accept (sock)
     Accept a connection on a bound, listening socket.  If there are no
     pending connections in the queue, wait until one is available
     unless the non-blocking option has been set on the socket.

     The return value is a pair in which the _car_ is a new socket port
     for the connection and the _cdr_ is an object with address
     information about the client which initiated the connection.

     SOCK does not become part of the connection and will continue to
     accept new requests.

   The following functions take a socket address object, as returned by
`accept' and other procedures, and return a selected component.

`sockaddr:fam'
     The socket family, typically equal to the value of `AF_UNIX' or
     `AF_INET'.

`sockaddr:path'
     If the socket family is `AF_UNIX', returns the path of the
     filename the socket is based on.

`sockaddr:addr'
     If the socket family is `AF_INET', returns the Internet host
     address.

`sockaddr:port'
     If the socket family is `AF_INET', returns the Internet port
     number.

 - Scheme Procedure: getsockname sock
 - C Function: scm_getsockname (sock)
     Return the address of SOCK, in the same form as the object
     returned by `accept'.  On many systems the address of a socket in
     the `AF_FILE' namespace cannot be read.

 - Scheme Procedure: getpeername sock
 - C Function: scm_getpeername (sock)
     Return the address that SOCK is connected to, in the same form as
     the object returned by `accept'.  On many systems the address of a
     socket in the `AF_FILE' namespace cannot be read.

 - Scheme Procedure: recv! sock buf [flags]
 - C Function: scm_recv (sock, buf, flags)
     Receive data from a socket port.  SOCK must already be bound to
     the address from which data is to be received.  BUF is a string
     into which the data will be written.  The size of BUF limits the
     amount of data which can be received: in the case of packet
     protocols, if a packet larger than this limit is encountered then
     some data will be irrevocably lost.

     The optional FLAGS argument is a value or bitwise OR of MSG_OOB,
     MSG_PEEK, MSG_DONTROUTE etc.

     The value returned is the number of bytes read from the socket.

     Note that the data is read directly from the socket file
     descriptor: any unread buffered port data is ignored.

 - Scheme Procedure: send sock message [flags]
 - C Function: scm_send (sock, message, flags)
     Transmit the string MESSAGE on a socket port SOCK.  SOCK must
     already be bound to a destination address.  The value returned is
     the number of bytes transmitted - it's possible for this to be
     less than the length of MESSAGE if the socket is set to be
     non-blocking.  The optional FLAGS argument is a value or bitwise
     OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

     Note that the data is written directly to the socket file
     descriptor: any unflushed buffered port data is ignored.

 - Scheme Procedure: recvfrom! sock str [flags [start [end]]]
 - C Function: scm_recvfrom (sock, str, flags, start, end)
     Return data from the socket port SOCK and also information about
     where the data was received from.  SOCK must already be bound to
     the address from which data is to be received.  `str', is a string
     into which the data will be written.  The size of STR limits the
     amount of data which can be received: in the case of packet
     protocols, if a packet larger than this limit is encountered then
     some data will be irrevocably lost.

     The optional FLAGS argument is a value or bitwise OR of `MSG_OOB',
     `MSG_PEEK', `MSG_DONTROUTE' etc.

     The value returned is a pair: the _car_ is the number of bytes
     read from the socket and the _cdr_ an address object in the same
     form as returned by `accept'.  The address will given as `#f' if
     not available, as is usually the case for stream sockets.

     The START and END arguments specify a substring of STR to which
     the data should be written.

     Note that the data is read directly from the socket file
     descriptor: any unread buffered port data is ignored.

 - Scheme Procedure: sendto sock message fam address . args_and_flags
 - C Function: scm_sendto (sock, message, fam, address, args_and_flags)
     Transmit the string MESSAGE on the socket port SOCK.  The
     destination address is specified using the FAM, ADDRESS and
     ARGS_AND_FLAGS arguments, in a similar way to the `connect'
     procedure.  ARGS_AND_FLAGS contains the usual connection arguments
     optionally followed by a flags argument, which is a value or
     bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

     The value returned is the number of bytes transmitted - it's
     possible for this to be less than the length of MESSAGE if the
     socket is set to be non-blocking.  Note that the data is written
     directly to the socket file descriptor: any unflushed buffered
     port data is ignored.

   The following functions can be used to convert short and long
integers between "host" and "network" order.  Although the procedures
above do this automatically for addresses, the conversion will still
need to be done when sending or receiving encoded integer data from the
network.

 - Scheme Procedure: htons value
 - C Function: scm_htons (value)
     Convert a 16 bit quantity from host to network byte ordering.
     VALUE is packed into 2 bytes, which are then converted and
     returned as a new integer.

 - Scheme Procedure: ntohs value
 - C Function: scm_ntohs (value)
     Convert a 16 bit quantity from network to host byte ordering.
     VALUE is packed into 2 bytes, which are then converted and
     returned as a new integer.

 - Scheme Procedure: htonl value
 - C Function: scm_htonl (value)
     Convert a 32 bit quantity from host to network byte ordering.
     VALUE is packed into 4 bytes, which are then converted and
     returned as a new integer.

 - Scheme Procedure: ntohl value
 - C Function: scm_ntohl (value)
     Convert a 32 bit quantity from network to host byte ordering.
     VALUE is packed into 4 bytes, which are then converted and
     returned as a new integer.

   These procedures are inconvenient to use at present, but consider:

     (define write-network-long
       (lambda (value port)
         (let ((v (make-uniform-vector 1 1 0)))
           (uniform-vector-set! v 0 (htonl value))
           (uniform-vector-write v port))))
     
     (define read-network-long
       (lambda (port)
         (let ((v (make-uniform-vector 1 1 0)))
           (uniform-vector-read! v port)
           (ntohl (uniform-vector-ref v 0)))))


File: guile.info,  Node: Internet Socket Examples,  Prev: Network Sockets and Communication,  Up: Networking

Network Socket Examples
-----------------------

   The following sections give examples of how to use network sockets.

* Menu:

* Internet Socket Client::
* Internet Socket Server::


File: guile.info,  Node: Internet Socket Client,  Next: Internet Socket Server,  Up: Internet Socket Examples

Internet Socket Client Example
..............................

   The following example demonstrates an Internet socket client.  It
connects to the HTTP daemon running on the local machine and returns
the contents of the root index URL.

     (let ((s (socket AF_INET SOCK_STREAM 0)))
       (connect s AF_INET (inet-aton "127.0.0.1") 80)
       (display "GET / HTTP/1.0\r\n\r\n" s)
     
       (do ((line (read-line s) (read-line s)))
           ((eof-object? line))
         (display line)
         (newline)))


File: guile.info,  Node: Internet Socket Server,  Prev: Internet Socket Client,  Up: Internet Socket Examples

Internet Socket Server Example
..............................

   The following example shows a simple Internet server which listens on
port 2904 for incoming connections and sends a greeting back to the
client.

     (let ((s (socket AF_INET SOCK_STREAM 0)))
       (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
       ;; Specific address?
       ;; (bind s AF_INET (inet-aton "127.0.0.1") 2904)
       (bind s AF_INET INADDR_ANY 2904)
       (listen s 5)
     
       (simple-format #t "Listening for clients in pid: ~S" (getpid))
       (newline)
     
       (while #t
              (let* ((client-connection (accept s))
                     (client-details (cdr client-connection))
                     (client (car client-connection)))
                (simple-format #t "Got new client connection: ~S"
                               client-details)
                (newline)
                (simple-format #t "Client address: ~S"
                               (gethostbyaddr
                                (sockaddr:addr client-details)))
                (newline)
                ;; Send back the greeting to the client port
                (display "Hello client\r\n" client)
                (close client))))


File: guile.info,  Node: System Identification,  Next: Locales,  Prev: Networking,  Up: POSIX

System Identification
=====================

   This section lists the various procedures Guile provides for
accessing information about the system it runs on.

 - Scheme Procedure: uname
 - C Function: scm_uname ()
     Return an object with some information about the computer system
     the program is running on.

   The following procedures accept an object as returned by `uname' and
return a selected component.

`utsname:sysname'
     The name of the operating system.

`utsname:nodename'
     The network name of the computer.

`utsname:release'
     The current release level of the operating system implementation.

`utsname:version'
     The current version level within the release of the operating
     system.

`utsname:machine'
     A description of the hardware.

 - Scheme Procedure: gethostname
 - C Function: scm_gethostname ()
     Return the host name of the current processor.

 - Scheme Procedure: sethostname name
 - C Function: scm_sethostname (name)
     Set the host name of the current processor to NAME. May only be
     used by the superuser.  The return value is not specified.

 - Scheme Procedure: software-type
     Return a symbol describing the current platform's operating system.
     This may be one of AIX, VMS, UNIX, COHERENT, WINDOWS, MS-DOS, OS/2,
     THINKC, AMIGA, ATARIST, MACH, or ACORN.

     Note that most varieties of Unix are considered to be simply
     "UNIX".  That is because when a program depends on features that
     are not present on every operating system, it is usually better to
     test for the presence or absence of that specific feature.  The
     return value of `software-type' should only be used for this
     purpose when there is no other easy or unambiguous way of
     detecting such features.


File: guile.info,  Node: Locales,  Next: Encryption,  Prev: System Identification,  Up: POSIX

Locales
=======

 - Scheme Procedure: setlocale category [locale]
 - C Function: scm_setlocale (category, locale)
     If LOCALE is omitted, return the current value of the specified
     locale category as a system-dependent string.  CATEGORY should be
     specified using the values `LC_COLLATE', `LC_ALL' etc.

     Otherwise the specified locale category is set to the string
     LOCALE and the new value is returned as a system-dependent string.
     If LOCALE is an empty string, the locale will be set using
     environment variables.


File: guile.info,  Node: Encryption,  Prev: Locales,  Up: POSIX

Encryption
==========

   Please note that the procedures in this section are not suited for
strong encryption, they are only interfaces to the well-known and
common system library functions of the same name.  They are just as good
(or bad) as the underlying functions, so you should refer to your system
documentation before using them.

 - Scheme Procedure: crypt key salt
 - C Function: scm_crypt (key, salt)
     Encrypt KEY using SALT as the salt value to the crypt(3) library
     call.

   Although `getpass' is not an encryption procedure per se, it appears
here because it is often used in combination with `crypt':

 - Scheme Procedure: getpass prompt
 - C Function: scm_getpass (prompt)
     Display PROMPT to the standard error output and read a password
     from `/dev/tty'.  If this file is not accessible, it reads from
     standard input.  The password may be up to 127 characters in
     length.  Additional characters and the terminating newline
     character are discarded.  While reading the password, echoing and
     the generation of signals by special characters is disabled.


File: guile.info,  Node: SRFI Support,  Next: Readline Support,  Prev: POSIX,  Up: Top

SRFI Support Modules
********************

   SRFI is an acronym for Scheme Request For Implementation.  The SRFI
documents define a lot of syntactic and procedure extensions to standard
Scheme as defined in R5RS.

   Guile has support for a number of SRFIs.  This chapter gives an
overview over the available SRFIs and some usage hints.  For complete
documentation, design rationales and further examples, we advise you to
get the relevant SRFI documents from the SRFI home page
<http://srfi.schemers.org>.

* Menu:

* About SRFI Usage::            What to know about Guile's SRFI support.
* SRFI-0::                      cond-expand
* SRFI-1::                      List library.
* SRFI-2::                      and-let*.
* SRFI-4::                      Homogeneous numeric vector datatypes.
* SRFI-6::                      Basic String Ports.
* SRFI-8::                      receive.
* SRFI-9::                      define-record-type.
* SRFI-10::                     Hash-Comma Reader Extension.
* SRFI-11::                     let-values and let-values*.
* SRFI-13::                     String library.
* SRFI-14::                     Character-set library.
* SRFI-16::                     case-lambda
* SRFI-17::                     Generalized set!
* SRFI-19::                     Time/Date library.


File: guile.info,  Node: About SRFI Usage,  Next: SRFI-0,  Up: SRFI Support

About SRFI Usage
================

   SRFI support in Guile is currently implemented partly in the core
library, and partly as add-on modules.  That means that some SRFIs are
automatically available when the interpreter is started, whereas the
other SRFIs require you to use the appropriate support module
explicitly.

   There are several reasons for this inconsistency.  First, the feature
checking syntactic form `cond-expand' (*note SRFI-0::) must be
available immediately, because it must be there when the user wants to
check for the Scheme implementation, that is, before she can know that
it is safe to use `use-modules' to load SRFI support modules.  The
second reason is that some features defined in SRFIs had been
implemented in Guile before the developers started to add SRFI
implementations as modules (for example SRFI-6 (*note SRFI-6::)).  In
the future, it is possible that SRFIs in the core library might be
factored out into separate modules, requiring explicit module loading
when they are needed.  So you should be prepared to have to use
`use-modules' someday in the future to access SRFI-6 bindings.  If you
want, you can do that already.  We have included the module `(srfi
srfi-6)' in the distribution, which currently does nothing, but ensures
that you can write future-safe code.

   Generally, support for a specific SRFI is made available by using
modules named `(srfi srfi-NUMBER)', where NUMBER is the number of the
SRFI needed.  Another possibility is to use the command line option
`--use-srfi', which will load the necessary modules automatically
(*note Invoking Guile::).


File: guile.info,  Node: SRFI-0,  Next: SRFI-1,  Prev: About SRFI Usage,  Up: SRFI Support

SRFI-0 - cond-expand
====================

   SRFI-0 defines a means for checking whether a Scheme implementation
has support for a specified feature.  The syntactic form `cond-expand',
which implements this means, has the following syntax.

     <cond-expand>
       --> (cond-expand <cond-expand-clause>+)
         | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
     <cond-expand-clause>
       --> (<feature-requirement> <command-or-definition>*)
     <feature-requirement>
       --> <feature-identifier>
         | (and <feature-requirement>*)
         | (or <feature-requirement>*)
         | (not <feature-requirement>)
     <feature-identifier>
       --> <a symbol which is the name or alias of a SRFI>

   When evaluated, this form checks all clauses in order, until it finds
one whose feature requirement is satisfied.  Then the form expands into
the commands or definitions in the clause.  A requirement is tested as
follows:

   * If it is a symbol, it is satisfied if the feature identifier is
     supported.

   * If it is an `and' form, all requirements must be satisfied.  If no
     requirements are given, it is satisfied, too.

   * If it is an `or' form, at least one of the requirements must be
     satisfied.  If no requirements are given, it is not satisfied.

   * If it is a `not' form, the feature requirement must _not_ be
     satisfied.

   * If the feature requirement is the keyword `else' and it is the last
     clause, it is satisfied if no prior clause matched.

   If no clause is satisfied, an error is signalled.

   Since `cond-expand' is needed to tell what a Scheme implementation
provides, it must be accessible without using any
implementation-dependent operations, such as `use-modules' in Guile.
Thus, it is not necessary to use any module to get access to this form.

   Currently, the feature identifiers `guile', `r5rs' and `srfi-0' are
supported.  The other SRFIs are not in that list by default, because
the SRFI modules must be explicitly used before their exported bindings
can be used.

   So if a Scheme program wishes to use SRFI-8, it has two
possibilities: First, it can check whether the running Scheme
implementation is Guile, and if it is, it can use the appropriate
module:

     (cond-expand
       (guile
         (use-modules (srfi srfi-8)))
       (srfi-8
         #t))
       ;; otherwise fail.

   The other possibility is to use the `--use-srfi' command line option
when invoking Guile (*note Invoking Guile::).  When you do that, the
specified SRFI support modules will be loaded and add their feature
identifier to the list of symbols checked by `cond-expand'.

   So, if you invoke Guile like this:

     $ guile --use-srfi=8

   the following snippet will expand to `'hooray'.

     (cond-expand (srfi-8 'hooray))


File: guile.info,  Node: SRFI-1,  Next: SRFI-2,  Prev: SRFI-0,  Up: SRFI Support

SRFI-1 - List library
=====================

   The list library defined in SRFI-1 contains a lot of useful list
processing procedures for construction, examining, destructuring and
manipulating lists and pairs.

   Since SRFI-1 also defines some procedures which are already contained
in R5RS and thus are supported by the Guile core library, some list and
pair procedures which appear in the SRFI-1 document may not appear in
this section.  So when looking for a particular list/pair processing
procedure, you should also have a look at the sections *Note Lists::
and *Note Pairs::.

* Menu:

* SRFI-1 Constructors::         Constructing new lists.
* SRFI-1 Predicates::           Testing list for specific properties.
* SRFI-1 Selectors::            Selecting elements from lists.
* SRFI-1 Length Append etc::    Length calculation and list appending.
* SRFI-1 Fold and Map::         Higher-order list processing.
* SRFI-1 Filtering and Partitioning::  Filter lists based on predicates.
* SRFI-1 Searching::            Search for elements.
* SRFI-1 Deleting::             Delete elements from lists.
* SRFI-1 Association Lists::    Handle association lists.
* SRFI-1 Set Operations::       Use lists for representing sets.


File: guile.info,  Node: SRFI-1 Constructors,  Next: SRFI-1 Predicates,  Up: SRFI-1

Constructors
------------

   New lists can be constructed by calling one of the following
procedures.

 - Scheme Procedure: xcons d a
     Like `cons', but with interchanged arguments.  Useful mostly when
     passed to higher-order procedures.

 - Scheme Procedure: list-tabulate n init-proc
     Return an N-element list, where each list element is produced by
     applying the procedure INIT-PROC to the corresponding list index.
     The order in which INIT-PROC is applied to the indices is not
     specified.

 - Scheme Procedure: circular-list elt1 elt2 ...
     Return a circular list containing the given arguments ELT1 ELT2
     ....

 - Scheme Procedure: iota count [start step]
     Return a list containing COUNT elements, where each element is
     calculated as follows:

     START + (COUNT - 1) * STEP

     START defaults to 0 and STEP defaults to 1.


File: guile.info,  Node: SRFI-1 Predicates,  Next: SRFI-1 Selectors,  Prev: SRFI-1 Constructors,  Up: SRFI-1

Predicates
----------

   The procedures in this section test specific properties of lists.

 - Scheme Procedure: proper-list? obj
     Return `#t' if OBJ is a proper list, that is a finite list,
     terminated with the empty list.  Otherwise, return `#f'.

 - Scheme Procedure: circular-list? obj
     Return `#t' if OBJ is a circular list, otherwise return `#f'.

 - Scheme Procedure: dotted-list? obj
     Return `#t' if OBJ is a dotted list, return `#f' otherwise.  A
     dotted list is a finite list which is not terminated by the empty
     list, but some other value.

 - Scheme Procedure: null-list? lst
     Return `#t' if LST is the empty list `()', `#f' otherwise.  If
     something else than a proper or circular list is passed as LST, an
     error is signalled.  This procedure is recommended for checking
     for the end of a list in contexts where dotted lists are not
     allowed.

 - Scheme Procedure: not-pair? obj
     Return `#t' is OBJ is not a pair, `#f' otherwise.  This is
     shorthand notation `(not (pair? OBJ))' and is supposed to be used
     for end-of-list checking in contexts where dotted lists are
     allowed.

 - Scheme Procedure: list= elt= list1 ...
     Return `#t' if all argument lists are equal, `#f' otherwise.  List
     equality is determined by testing whether all lists have the same
     length and the corresponding elements are equal in the sense of the
     equality predicate ELT=.  If no or only one list is given, `#t' is
     returned.


File: guile.info,  Node: SRFI-1 Selectors,  Next: SRFI-1 Length Append etc,  Prev: SRFI-1 Predicates,  Up: SRFI-1

Selectors
---------

 - Scheme Procedure: first pair
 - Scheme Procedure: second pair
 - Scheme Procedure: third pair
 - Scheme Procedure: fourth pair
 - Scheme Procedure: fifth pair
 - Scheme Procedure: sixth pair
 - Scheme Procedure: seventh pair
 - Scheme Procedure: eighth pair
 - Scheme Procedure: ninth pair
 - Scheme Procedure: tenth pair
     These are synonyms for `car', `cadr', `caddr', ....

 - Scheme Procedure: car+cdr pair
     Return two values, the CAR and the CDR of PAIR.

 - Scheme Procedure: take lst i
 - Scheme Procedure: take! lst i
     Return a list containing the first I elements of LST.

     `take!' may modify the structure of the argument list LST in order
     to produce the result.

 - Scheme Procedure: drop lst i
     Return a list containing all but the first I elements of LST.

 - Scheme Procedure: take-right lst i
     Return the a list containing the I last elements of LST.

 - Scheme Procedure: drop-right lst i
 - Scheme Procedure: drop-right! lst i
     Return the a list containing all but the I last elements of LST.

     `drop-right!' may modify the structure of the argument list LST in
     order to produce the result.

 - Scheme Procedure: split-at lst i
 - Scheme Procedure: split-at! lst i
     Return two values, a list containing the first I elements of the
     list LST and a list containing the remaining elements.

     `split-at!' may modify the structure of the argument list LST in
     order to produce the result.

 - Scheme Procedure: last lst
     Return the last element of the non-empty, finite list LST.


File: guile.info,  Node: SRFI-1 Length Append etc,  Next: SRFI-1 Fold and Map,  Prev: SRFI-1 Selectors,  Up: SRFI-1

Length, Append, Concatenate, etc.
---------------------------------

 - Scheme Procedure: length+ lst
     Return the length of the argument list LST.  When LST is a
     circular list, `#f' is returned.

 - Scheme Procedure: concatenate list-of-lists
 - Scheme Procedure: concatenate! list-of-lists
     Construct a list by appending all lists in LIST-OF-LISTS.

     `concatenate!' may modify the structure of the given lists in
     order to produce the result.

 - Scheme Procedure: append-reverse rev-head tail
 - Scheme Procedure: append-reverse! rev-head tail
     Reverse REV-HEAD, append TAIL and return the result.  This is
     equivalent to `(append (reverse REV-HEAD) TAIL)', but more
     efficient.

     `append-reverse!' may modify REV-HEAD in order to produce the
     result.

 - Scheme Procedure: zip lst1 lst2 ...
     Return a list as long as the shortest of the argument lists, where
     each element is a list.  The first list contains the first
     elements of the argument lists, the second list contains the
     second elements, and so on.

 - Scheme Procedure: unzip1 lst
 - Scheme Procedure: unzip2 lst
 - Scheme Procedure: unzip3 lst
 - Scheme Procedure: unzip4 lst
 - Scheme Procedure: unzip5 lst
     `unzip1' takes a list of lists, and returns a list containing the
     first elements of each list, `unzip2' returns two lists, the first
     containing the first elements of each lists and the second
     containing the second elements of each lists, and so on.


File: guile.info,  Node: SRFI-1 Fold and Map,  Next: SRFI-1 Filtering and Partitioning,  Prev: SRFI-1 Length Append etc,  Up: SRFI-1

Fold, Unfold & Map
------------------

 - Scheme Procedure: fold kons knil lst1 lst2 ...
     Fold the procedure KONS across all elements of LST1, LST2, ....
     Produce the result of

     `(KONS EN1 EN2 ... (KONS E21 E22 (KONS E11 E12 KNIL)))',

     if ENM are the elements of the lists LST1, LST2, ....

 - Scheme Procedure: fold-right kons knil lst1 lst2 ...
     Similar to `fold', but applies KONS in right-to-left order to the
     list elements, that is:

     `(KONS E11 E12(KONS E21 E22  ... (KONS EN1 EN2 KNIL)))',

 - Scheme Procedure: pair-fold kons knil lst1 lst2 ...
     Like `fold', but apply KONS to the pairs of the list instead of
     the list elements.

 - Scheme Procedure: pair-fold-right kons knil lst1 lst2 ...
     Like `fold-right', but apply KONS to the pairs of the list instead
     of the list elements.

 - Scheme Procedure: reduce f ridentity lst
     `reduce' is a variant of `reduce'.  If LST is `()', RIDENTITY is
     returned.  Otherwise, `(fold (car LST) (cdr LST))' is returned.

 - Scheme Procedure: reduce-right f ridentity lst
     This is the `fold-right' variant of REDUCE.

 - Scheme Procedure: unfold p f g seed [tail-gen]
     `unfold' is defined as follows:

          (unfold p f g seed) =
             (if (p seed) (tail-gen seed)
                 (cons (f seed)
                       (unfold p f g (g seed))))

    P
          Determines when to stop unfolding.

    F
          Maps each seed value to the corresponding list element.

    G
          Maps each seed value to next seed valu.

    SEED
          The state value for the unfold.

    TAIL-GEN
          Creates the tail of the list; defaults to `(lambda (x) '())'.

     G produces a series of seed values, which are mapped to list
     elements by F.  These elements are put into a list in
     left-to-right order, and P tells when to stop unfolding.

 - Scheme Procedure: unfold-right p f g seed [tail]
     Construct a list with the following loop.

          (let lp ((seed seed) (lis tail))
             (if (p seed) lis
                 (lp (g seed)
                     (cons (f seed) lis))))

    P
          Determines when to stop unfolding.

    F
          Maps each seed value to the corresponding list element.

    G
          Maps each seed value to next seed valu.

    SEED
          The state value for the unfold.

    TAIL-GEN
          Creates the tail of the list; defaults to `(lambda (x) '())'.


 - Scheme Procedure: map f lst1 lst2 ...
     Map the procedure over the list(s) LST1, LST2, ... and return a
     list containing the results of the procedure applications.  This
     procedure is extended with respect to R5RS, because the argument
     lists may have different lengths.  The result list will have the
     same length as the shortest argument lists.  The order in which F
     will be applied to the list element(s) is not specified.

 - Scheme Procedure: for-each f lst1 lst2 ...
     Apply the procedure F to each pair of corresponding elements of
     the list(s) LST1, LST2, ....  The return value is not specified.
     This procedure is extended with respect to R5RS, because the
     argument lists may have different lengths.  The shortest argument
     list determines the number of times F is called.  F will be
     applied to the list elements in left-to-right order.


 - Scheme Procedure: append-map f lst1 lst2 ...
 - Scheme Procedure: append-map! f lst1 lst2 ...
     Equivalent to

          (apply append (map f clist1 clist2 ...))

     and

          (apply append! (map f clist1 clist2 ...))

     Map F over the elements of the lists, just as in the `map'
     function. However, the results of the applications are appended
     together to make the final result. `append-map' uses `append' to
     append the results together; `append-map!' uses `append!'.

     The dynamic order in which the various applications of F are made
     is not specified.

 - Scheme Procedure: map! f lst1 lst2 ...
     Linear-update variant of `map' - `map!' is allowed, but not
     required, to alter the cons cells of LST1 to construct the result
     list.

     The dynamic order in which the various applications of F are made
     is not specified. In the n-ary case, LST2, LST3, ... must have at
     least as many elements as LST1.

 - Scheme Procedure: pair-for-each f lst1 lst2 ...
     Like `for-each', but applies the procedure F to the pairs from
     which the argument lists are constructed, instead of the list
     elements.  The return value is not specified.

 - Scheme Procedure: filter-map f lst1 lst2 ...
     Like `map', but only results from the applications of F which are
     true are saved in the result list.


File: guile.info,  Node: SRFI-1 Filtering and Partitioning,  Next: SRFI-1 Searching,  Prev: SRFI-1 Fold and Map,  Up: SRFI-1

Filtering and Partitioning
--------------------------

   Filtering means to collect all elements from a list which satisfy a
specific condition.  Partitioning a list means to make two groups of
list elements, one which contains the elements satisfying a condition,
and the other for the elements which don't.

 - Scheme Procedure: filter pred lst
 - Scheme Procedure: filter! pred lst
     Return a list containing all elements from LST which satisfy the
     predicate PRED.  The elements in the result list have the same
     order as in LST.  The order in which PRED is applied to the list
     elements is not specified.

     `filter!' is allowed, but not required to modify the structure of

 - Scheme Procedure: partition pred lst
 - Scheme Procedure: partition! pred lst
     Return two lists, one containing all elements from LST which
     satisfy the predicate PRED, and one list containing the elements
     which do not satisfy the predicated.  The elements in the result
     lists have the same order as in LST.  The order in which PRED is
     applied to the list elements is not specified.

     `partition!' is allowed, but not required to modify the structure
     of the input list.

 - Scheme Procedure: remove pred lst
 - Scheme Procedure: remove! pred lst
     Return a list containing all elements from LST which do not
     satisfy the predicate PRED.  The elements in the result list have
     the same order as in LST.  The order in which PRED is applied to
     the list elements is not specified.

     `remove!' is allowed, but not required to modify the structure of
     the input list.


File: guile.info,  Node: SRFI-1 Searching,  Next: SRFI-1 Deleting,  Prev: SRFI-1 Filtering and Partitioning,  Up: SRFI-1

Searching
---------

   The procedures for searching elements in lists either accept a
predicate or a comparison object for determining which elements are to
be searched.

 - Scheme Procedure: find pred lst
     Return the first element of LST which satisfies the predicate PRED
     and `#f' if no such element is found.

 - Scheme Procedure: find-tail pred lst
     Return the first pair of LST whose CAR satisfies the predicate
     PRED and `#f' if no such element is found.

 - Scheme Procedure: take-while pred lst
 - Scheme Procedure: take-while! pred lst
     Return the longest initial prefix of LST whose elements all
     satisfy the predicate PRED.

     `take-while!' is allowed, but not required to modify the input
     list while producing the result.

 - Scheme Procedure: drop-while pred lst
     Drop the longest initial prefix of LST whose elements all satisfy
     the predicate PRED.

 - Scheme Procedure: span pred lst
 - Scheme Procedure: span! pred lst
 - Scheme Procedure: break pred lst
 - Scheme Procedure: break! pred lst
     `span' splits the list LST into the longest initial prefix whose
     elements all satisfy the predicate PRED, and the remaining tail.
     `break' inverts the sense of the predicate.

     `span!' and `break!' are allowed, but not required to modify the
     structure of the input list LST in order to produce the result.

 - Scheme Procedure: any pred lst1 lst2 ...
     Apply PRED across the lists and return a true value if the
     predicate returns true for any of the list elements(s); return
     `#f' otherwise.  The true value returned is always the result of
     the first successful application of PRED.

 - Scheme Procedure: every pred lst1 lst2 ...
     Apply PRED across the lists and return a true value if the
     predicate returns true for every of the list elements(s); return
     `#f' otherwise.  The true value returned is always the result of
     the final successful application of PRED.

 - Scheme Procedure: list-index pred lst1 lst2 ...
     Return the index of the leftmost element that satisfies PRED.

 - Scheme Procedure: member x lst [=]
     Return the first sublist of LST whose CAR is equal to X.  If X
     does no appear in LST, return `#f'.  Equality is determined by the
     equality predicate =, or `equal?' if = is not given.


File: guile.info,  Node: SRFI-1 Deleting,  Next: SRFI-1 Association Lists,  Prev: SRFI-1 Searching,  Up: SRFI-1

Deleting
--------

   The procedures for deleting elements from a list either accept a
predicate or a comparison object for determining which elements are to
be removed.

 - Scheme Procedure: delete x lst [=]
 - Scheme Procedure: delete! x lst [=]
     Return a list containing all elements from LST, but without the
     elements equal to X.  Equality is determined by the equality
     predicate =, which defaults to `equal?' if not given.

     `delete!' is allowed, but not required to modify the structure of
     the argument list in order to produce the result.

 - Scheme Procedure: delete-duplicates lst [=]
 - Scheme Procedure: delete-duplicates! lst [=]
     Return a list containing all elements from LST, but without
     duplicate elements.  Equality of elements is determined by the
     equality predicate =, which defaults to `equal?' if not given.

     `delete-duplicates!' is allowed, but not required to modify the
     structure of the argument list in order to produce the result.


File: guile.info,  Node: SRFI-1 Association Lists,  Next: SRFI-1 Set Operations,  Prev: SRFI-1 Deleting,  Up: SRFI-1

Association Lists
-----------------

   Association lists are described in detail in section *Note
Association Lists::.  The present section only documents the additional
procedures for dealing with association lists defined by SRFI-1.

 - Scheme Procedure: assoc key alist [=]
     Return the pair from ALIST which matches KEY.  Equality is
     determined by =, which defaults to `equal?' if not given.  ALIST
     must be an association lists--a list of pairs.

 - Scheme Procedure: alist-cons key datum alist
     Equivalent to

          (cons (cons KEY DATUM) ALIST)

     This procedure is used to coons a new pair onto an existing
     association list.

 - Scheme Procedure: alist-copy alist
     Return a newly allocated copy of ALIST, that means that the spine
     of the list as well as the pairs are copied.

 - Scheme Procedure: alist-delete key alist [=]
 - Scheme Procedure: alist-delete! key alist [=]
     Return a list containing the pairs of ALIST, but without the pairs
     whose CARS are equal to KEY.  Equality is determined by =, which
     defaults to `equal?' if not given.

     `alist-delete!' is allowed, but not required to modify the
     structure of the list ALIST in order to produce the result.


File: guile.info,  Node: SRFI-1 Set Operations,  Prev: SRFI-1 Association Lists,  Up: SRFI-1

Set Operations on Lists
-----------------------

   Lists can be used for representing sets of objects.  The procedures
documented in this section can be used for such set representations.
Man combining several sets or adding elements, they make sure that no
object is contained more than once in a given list.  Please note that
lists are not a too efficient implementation method for sets, so if you
need high performance, you should think about implementing a custom
data structure for representing sets, such as trees, bitsets, hash
tables or something similar.

   All these procedures accept an equality predicate as the first
argument.  This predicate is used for testing the objects in the list
sets for sameness.

 - Scheme Procedure: lset<= = list1 ...
     Return `#t' if every LISTI is a subset of LISTI+1, otherwise
     return `#f'.  Returns `#t' if called with less than two arguments.
     = is used for testing element equality.

 - Scheme Procedure: lset= = list1 list2 ...
     Return `#t' if all argument lists are equal. = is used for testing
     element equality.

 - Scheme Procedure: lset-adjoin = list elt1 ...
 - Scheme Procedure: lset-adjoin! = list elt1 ...
     Add all ELTS to the list LIST, suppressing duplicates and return
     the resulting list.  `lset-adjoin!' is allowed, but not required
     to modify its first argument. = is used for testing element
     equality.

 - Scheme Procedure: lset-union = list1 ...
 - Scheme Procedure: lset-union! = list1 ...
     Return the union of all argument list sets.  The union is the set
     of all elements which appear in any of the argument sets.
     `lset-union!' is allowed, but not required to modify its first
     argument. = is used for testing element equality.

 - Scheme Procedure: lset-intersection = list1 list2 ...
 - Scheme Procedure: lset-intersection! = list1 list2 ...
     Return the intersection of all argument list sets.  The
     intersection is the set containing all elements which appear in
     all argument sets.  `lset-intersection!' is allowed, but not
     required to modify its first argument. = is used for testing
     element equality.

 - Scheme Procedure: lset-difference = list1 list2 ...
 - Scheme Procedure: lset-difference! = list1 list2 ...
     Return the difference of all argument list sets.  The difference is
     the the set containing all elements of the first list which do not
     appear in the other lists.  `lset-difference!'  is allowed, but
     not required to modify its first argument. = is used for testing
     element equality.

 - Scheme Procedure: lset-xor = list1 ...
 - Scheme Procedure: lset-xor! = list1 ...
     Return the set containing all elements which appear in the first
     argument list set, but not in the second; or, more generally: which
     appear in an odd number of sets.  `lset-xor!'  is allowed, but not
     required to modify its first argument. = is used for testing
     element equality.

 - Scheme Procedure: lset-diff+intersection = list1 list2 ...
 - Scheme Procedure: lset-diff+intersection! = list1 list2 ...
     Return two values, the difference and the intersection of the
     argument list sets. This works like a combination of
     `lset-difference' and `lset-intersection', but is more efficient.
     `lset-diff+intersection!'  is allowed, but not required to modify
     its first argument. = is used for testing element equality.  You
     have to use some means to deal with the multiple values these
     procedures return (*note Multiple Values::).


File: guile.info,  Node: SRFI-2,  Next: SRFI-4,  Prev: SRFI-1,  Up: SRFI Support

SRFI-2 - and-let*
=================

   The syntactic form `and-let*' combines the conditional evaluation
form `and' with the binding form LET*.  Each argument expression will
be evaluated sequentially, bound to a variable (if a variable name is
given), but only as long as no expression returns the false value `#f'.

   Use `(use-modules (srfi srfi-2)' to access this syntax form.

   A short example will demonstrate how it works.  In the first
expression, X will get bound to 1, but the next expression (`#f') is
false, so evaluation of the form is stopped, and `#f' is returned.  In
the next expression, X is bound to 1, Y is bound to `#t' and since no
expression in the binding section was false, the body of the `and-let*'
expression is evaluated, which in this case returns the value of X.

     (and-let* ((x 1) (y #f)) 42)
     =>
     #f
     (and-let* ((x 1) (y #t)) x)
     =>
     1


File: guile.info,  Node: SRFI-4,  Next: SRFI-6,  Prev: SRFI-2,  Up: SRFI Support

SRFI-4 - Homogeneous numeric vector datatypes.
==============================================

   SRFI-4 defines a set of datatypes for vectors whose elements are all
of the same numeric type.  Vectors for signed and unsigned exact
integer or inexact real numbers in several precisions are available.

   Procedures similar to the vector procedures (*note Vectors::) are
provided for handling these homogeneous vectors, but they are distinct
datatypes.

   The reason for providing this set of datatypes is that with the
limitation (all elements must have the same type), it is possible to
implement them much more memory-efficient than normal, heterogenous
vectors.

   If you want to use these datatypes and the corresponding procedures,
you have to use the module `(srfi srfi-4)'.

   Ten vector data types are provided: Unsigned and signed integer
values with 8, 16, 32 and 64 bits and floating point values with 32 and
64 bits.  In the following descriptions, the tags `u8', `s8', `u16',
`s16', `u32', `s32', `u64', `s64', `f32', `f64', respectively, are used
for denoting the various types.

* Menu:

* SRFI-4 - Read Syntax::        How to write homogeneous vector literals.
* SRFI-4 - Procedures::         Available homogeneous vector procedures.


File: guile.info,  Node: SRFI-4 - Read Syntax,  Next: SRFI-4 - Procedures,  Up: SRFI-4

SRFI-4 - Read Syntax
--------------------

   Homogeneous numeric vectors have an external representation (read
syntax) similar to normal Scheme vectors, but with an additional tag
telling the vector's type.

     #u16(1 2 3)

   denotes a homogeneous numeric vector of three elements, which are the
values 1, 2 and 3, represented as 16-bit unsigned integers.
Correspondingly,

     #f64(3.1415 2.71)

   denotes a vector of two elements, which are the values 3.1415 and
2.71, represented as floating-point values of 64 bit precision.

   Please note that the read syntax for floating-point vectors conflicts
with Standard Scheme, because there `#f' is defined to be the literal
false value.  That means, that with the loaded SRFI-4 module, it is not
possible to enter some list like

     '(1 #f3)

   and hope that it will be parsed as a three-element list with the
elements 1, `#f' and 3.  In normal use, this should be no problem,
because people tend to terminate tokens sensibly when writing Scheme
expressions.


File: guile.info,  Node: SRFI-4 - Procedures,  Prev: SRFI-4 - Read Syntax,  Up: SRFI-4

SRFI-4 Procedures
-----------------

   The procedures listed in this section are provided for all
homogeneous numeric vector datatypes.  For brevity, they are not all
documented, but a summary of the procedures is given.  In the following
descriptions, you can replace `TAG' by any of the datatype indicators
`u8', `s8', `u16', `s16', `u32', `s32', `u64', `s64', `f32' and `f64'.

   For example, you can use the procedures `u8vector?',
`make-s8vector', `u16vector', `u32vector-length', `s64vector-ref',
`f32vector-set!' or `f64vector->list'.

 - Scheme Procedure: TAGvector? obj
     Return `#t' if OBJ is a homogeneous numeric vector of type `TAG'.

 - Scheme Procedure: make-TAGvector n [value]
     Create a newly allocated homogeneous numeric vector of type `TAG',
     which can hold N elements.  If VALUE is given, the vector is
     initialized with the value, otherwise, the contents of the
     returned vector is not specified.

 - Scheme Procedure: TAGvector value1 ...
     Create a newly allocated homogeneous numeric vector of type `TAG'.
     The returned vector is as long as the number of arguments given,
     and is initialized with the argument values.

 - Scheme Procedure: TAGvector-length TAGvec
     Return the number of elements in TAGVEC.

 - Scheme Procedure: TAGvector-ref TAGvec i
     Return the element at index I in TAGVEC.

 - Scheme Procedure: TAGvector-ref TAGvec i value
     Set the element at index I in TAGVEC to VALUE.  The return value
     is not specified.

 - Scheme Procedure: TAGvector->list TAGvec
     Return a newly allocated list holding all elements of TAGVEC.

 - Scheme Procedure: list->TAGvector lst
     Return a newly allocated homogeneous numeric vector of type `TAG',
     initialized with the elements of the list LST.


File: guile.info,  Node: SRFI-6,  Next: SRFI-8,  Prev: SRFI-4,  Up: SRFI Support

SRFI-6 - Basic String Ports
===========================

   SRFI-6 defines the procedures `open-input-string',
`open-output-string' and `get-output-string'.  These procedures are
included in the Guile core, so using this module does not make any
difference at the moment.  But it is possible that support for SRFI-6
will be factored out of the core library in the future, so using this
module does not hurt, after all.


File: guile.info,  Node: SRFI-8,  Next: SRFI-9,  Prev: SRFI-6,  Up: SRFI Support

SRFI-8 - receive
================

   `receive' is a syntax for making the handling of multiple-value
procedures easier.  It is documented in *Note Multiple Values::.


File: guile.info,  Node: SRFI-9,  Next: SRFI-10,  Prev: SRFI-8,  Up: SRFI Support

SRFI-9 - define-record-type
===========================

   This is the SRFI way for defining record types.  The Guile
implementation is a layer above Guile's normal record construction
procedures (*note Records::).  The nice thing about this kind of record
definition method is that no new names are implicitly created, all
constructor, accessor and predicates are explicitly given.  This reduces
the risk of variable capture.

   The syntax of a record type definition is:

     <record type definition>
       -> (define-record-type <type name>
            (<constructor name> <field tag> ...)
            <predicate name>
            <field spec> ...)
     <field spec> -> (<field tag> <accessor name>)
                  -> (<field tag> <accessor name> <modifier name>)
     <field tag>  -> <identifier>
     <... name>   -> <identifier>

   Usage example:

     guile> (use-modules (srfi srfi-9))
     guile> (define-record-type :foo (make-foo x) foo?
                                (x get-x) (y get-y set-y!))
     guile> (define f (make-foo 1))
     guile> f
     #<:foo x: 1 y: #f>
     guile> (get-x f)
     1
     guile> (set-y! f 2)
     2
     guile> (get-y f)
     2
     guile> f
     #<:foo x: 1 y: 2>
     guile> (foo? f)
     #t
     guile> (foo? 1)
     #f


File: guile.info,  Node: SRFI-10,  Next: SRFI-11,  Prev: SRFI-9,  Up: SRFI Support

SRFI-10 - Hash-Comma Reader Extension
=====================================

   The module `(srfi srfi-10)' implements the syntax extension `#,()',
also called hash-comma, which is defined in SRFI-10.

   The support for SRFI-10 consists of the procedure
`define-reader-ctor' for defining new reader constructors and the read
syntax form

     #,(CTOR DATUM ...)

   where CTOR must be a symbol for which a read constructor was defined
previously, using `define-reader-ctor'.

   Example:

     (define-reader-ctor 'file open-input-file)
     (define f '#,(file "/etc/passwd"))
     (read-line f)
     =>
     "root:x:0:0:root:/root:/bin/bash"

   Please note the quote before the `#,(file ...)' expression.  This is
necessary because ports are not self-evaluating in Guile.

 - Scheme Procedure: define-reader-ctor symbol proc
     Define PROC as the reader constructor for hash-comma forms with a
     tag SYMBOL.  PROC will be applied to the datum(s) following the
     tag in the hash-comma expression after the complete form has been
     read in.  The result of PROC is returned by the Scheme reader.


File: guile.info,  Node: SRFI-11,  Next: SRFI-13,  Prev: SRFI-10,  Up: SRFI Support

SRFI-11 - let-values
====================

   This module implements the binding forms for multiple values
`let-values' and `let-values*'.  These forms are similar to `let' and
`let*' (*note Local Bindings::), but they support binding of the values
returned by multiple-valued expressions.

   Write `(use-modules (srfi srfi-11))' to make the bindings available.

     (let-values (((x y) (values 1 2))
                  ((z f) (values 3 4)))
        (+ x y z f))
     =>
     10

   `let-values' performs all bindings simultaneously, which means that
no expression in the binding clauses may refer to variables bound in the
same clause list.  `let-values*', on the other hand, performs the
bindings sequentially, just like `let*' does for single-valued
expressions.


File: guile.info,  Node: SRFI-13,  Next: SRFI-14,  Prev: SRFI-11,  Up: SRFI Support

SRFI-13 - String Library
========================

   In this section, we will describe all procedures defined in SRFI-13
(string library) and implemented by the module `(srfi srfi-13)'.

   Note that only the procedures from SRFI-13 are documented here which
are not already contained in Guile.  For procedures not documented here
please refer to the relevant chapters in the Guile Reference Manual, for
example the documentation of strings and string procedures (*note
Strings::).

   All of the procedures defined in SRFI-13, which are not already
included in the Guile core library, are implemented in the module
`(srfi srfi-13)'.  The procedures which are both in Guile and in
SRFI-13 are slightly extended in this module.  Their bindings overwrite
those in the Guile core.

   The procedures which are defined in the section _Low-level
procedures_ of SRFI-13 for parsing optional string indices, substring
specification checking and Knuth-Morris-Pratt-Searching are not
implemented.

   The procedures `string-contains' and `string-contains-ci' are not
implemented very efficiently at the moment.  This will be changed as
soon as possible.

* Menu:

* Loading SRFI-13::             How to load SRFI-13 support.
* SRFI-13 Predicates::          String predicates.
* SRFI-13 Constructors::        String constructing procedures.
* SRFI-13 List/String Conversion::  Conversion from/to lists.
* SRFI-13 Selection::           Selection portions of strings.
* SRFI-13 Modification::        Modify strings in-place.
* SRFI-13 Comparison::          Compare strings.
* SRFI-13 Prefixes/Suffixes::   Detect common pre-/suffixes.
* SRFI-13 Searching::           Searching for substrings.
* SRFI-13 Case Mapping::        Mapping to lower-/upper-case.
* SRFI-13 Reverse/Append::      Reverse and append strings.
* SRFI-13 Fold/Unfold/Map::     Construct/deconstruct strings.
* SRFI-13 Replicate/Rotate::    Replicate and rotate portions of strings.
* SRFI-13 Miscellaneous::       Left-over string procedures.
* SRFI-13 Filtering/Deleting::  Filter and delete characters from strings.


File: guile.info,  Node: Loading SRFI-13,  Next: SRFI-13 Predicates,  Up: SRFI-13

Loading SRFI-13
---------------

   When Guile is properly installed, SRFI-13 support can be loaded into
a running Guile by using the `(srfi srfi-13)' module.

     $ guile
     guile> (use-modules (srfi srfi-13))
     guile>

   When this step causes any errors, Guile is not properly installed.

   One possible reason is that Guile cannot find either the Scheme
module file `srfi-13.scm', or it cannot find the shared object file
`libguile-srfi-srfi-13-14.so'.  Make sure that the former is in the
Guile load path and that the latter is either installed in some default
location like `/usr/local/lib' or that the directory it was installed
to is in your `LTDL_LIBRARY_PATH'.  The same applies to `srfi-14.scm'.

   Now you can test whether the SRFI-13 procedures are working by
calling the `string-concatenate' procedure.

     guile> (string-concatenate '("Hello" " " "World!"))
     "Hello World!"


File: guile.info,  Node: SRFI-13 Predicates,  Next: SRFI-13 Constructors,  Prev: Loading SRFI-13,  Up: SRFI-13

Predicates
----------

   In addition to the primitives `string?' and `string-null?', which
are already in the Guile core, the string predicates `string-any' and
`string-every' are defined by SRFI-13.

 - Scheme Procedure: string-any pred s [start end]
     Check if the predicate PRED is true for any character in the
     string S, proceeding from left (index START) to right (index END).
     If `string-any' returns true, the returned true value is the one
     produced by the first successful application of PRED.

 - Scheme Procedure: string-every pred s [start end]
     Check if the predicate PRED is true for every character in the
     string S, proceeding from left (index START) to right (index END).
     If `string-every' returns true, the returned true value is the
     one produced by the final application of PRED to the last
     character of S.


File: guile.info,  Node: SRFI-13 Constructors,  Next: SRFI-13 List/String Conversion,  Prev: SRFI-13 Predicates,  Up: SRFI-13

Constructors
------------

   SRFI-13 defines several procedures for constructing new strings.  In
addition to `make-string' and `string' (available in the Guile core
library), the procedure `string-tabulate' does exist.

 - Scheme Procedure: string-tabulate proc len
     PROC is an integer->char procedure.  Construct a string of size
     LEN by applying PROC to each index to produce the corresponding
     string element.  The order in which PROC is applied to the indices
     is not specified.


File: guile.info,  Node: SRFI-13 List/String Conversion,  Next: SRFI-13 Selection,  Prev: SRFI-13 Constructors,  Up: SRFI-13

List/String Conversion
----------------------

   The procedure `string->list' is extended by SRFI-13, that is why it
is included in `(srfi srfi-13)'.  The other procedures are new.  The
Guile core already contains the procedure `list->string' for converting
a list of characters into a string (*note List/String Conversion::).

 - Scheme Procedure: string->list str [start end]
     Convert the string STR into a list of characters.

 - Scheme Procedure: reverse-list->string chrs
     An efficient implementation of `(compose string->list reverse)':

          (reverse-list->string '(#\a #\B #\c)) => "cBa"

 - Scheme Procedure: string-join ls [delimiter grammar]
     Append the string in the string list LS, using the string DELIM as
     a delimiter between the elements of LS.  GRAMMAR is a symbol which
     specifies how the delimiter is placed between the strings, and
     defaults to the symbol `infix'.

    `infix'
          Insert the separator between list elements.  An empty string
          will produce an empty list.

    `string-infix'
          Like `infix', but will raise an error if given the empty list.

    `suffix'
          Insert the separator after every list element.

    `prefix'
          Insert the separator before each list element.


File: guile.info,  Node: SRFI-13 Selection,  Next: SRFI-13 Modification,  Prev: SRFI-13 List/String Conversion,  Up: SRFI-13

Selection
---------

   These procedures are called "selectors", because they access
information about the string or select pieces of a given string.

   Additional selector procedures are documented in the Strings section
(*note String Selection::), like `string-length' or `string-ref'.

   `string-copy' is also available in core Guile, but this version
accepts additional start/end indices.

 - Scheme Procedure: string-copy str [start end]
     Return a freshly allocated copy of the string STR.  If given,
     START and END delimit the portion of STR which is copied.

 - Scheme Procedure: substring/shared str start [end]
     Like `substring', but the result may share memory with the
     argument STR.

 - Scheme Procedure: string-copy! target tstart s [start end]
     Copy the sequence of characters from index range [START, END) in
     string S to string TARGET, beginning at index TSTART.  The
     characters are copied left-to-right or right-to-left as needed -
     the copy is guaranteed to work, even if TARGET and S are the same
     string.  It is an error if the copy operation runs off the end of
     the target string.

 - Scheme Procedure: string-take s n
 - Scheme Procedure: string-take-right s n
     Return the N first/last characters of S.

 - Scheme Procedure: string-drop s n
 - Scheme Procedure: string-drop-right s n
     Return all but the first/last N characters of S.

 - Scheme Procedure: string-pad s len [chr start end]
 - Scheme Procedure: string-pad-right s len [chr start end]
     Take that characters from START to END from the string S and
     return a new string, right(left)-padded by the character CHR to
     length LEN.  If the resulting string is longer than LEN, it is
     truncated on the right (left).

 - Scheme Procedure: string-trim s [char_pred start end]
 - Scheme Procedure: string-trim-right s [char_pred start end]
 - Scheme Procedure: string-trim-both s [char_pred start end]
     Trim S by skipping over all characters on the left/right/both
     sides of the string that satisfy the parameter CHAR_PRED:

        * if it is the character CH, characters equal to CH are trimmed,

        * if it is a procedure PRED characters that satisfy PRED are
          trimmed,

        * if it is a character set, characters in that set are trimmed.

     If called without a CHAR_PRED argument, all whitespace is trimmed.


File: guile.info,  Node: SRFI-13 Modification,  Next: SRFI-13 Comparison,  Prev: SRFI-13 Selection,  Up: SRFI-13

Modification
------------

   The procedure `string-fill!' is extended from R5RS because it
accepts optional start/end indices.  This bindings shadows the procedure
of the same name in the Guile core.  The second modification procedure
`string-set!' is documented in the Strings section (*note String
Modification::).

 - Scheme Procedure: string-fill! str chr [start end]
     Stores CHR in every element of the given STR and returns an
     unspecified value.


File: guile.info,  Node: SRFI-13 Comparison,  Next: SRFI-13 Prefixes/Suffixes,  Prev: SRFI-13 Modification,  Up: SRFI-13

Comparison
----------

   The procedures in this section are used for comparing strings in
different ways.  The comparison predicates differ from those in R5RS in
that they do not only return `#t' or `#f', but the mismatch index in
the case of a true return value.

   `string-hash' and `string-hash-ci' are for calculating hash values
for strings, useful for implementing fast lookup mechanisms.

 - Scheme Procedure: string-compare s1 s2 proc_lt proc_eq proc_gt
          [start1 end1 start2 end2]
 - Scheme Procedure: string-compare-ci s1 s2 proc_lt proc_eq proc_gt
          [start1 end1 start2 end2]
     Apply PROC_LT, PROC_EQ, PROC_GT to the mismatch index, depending
     upon whether S1 is less than, equal to, or greater than S2.  The
     mismatch index is the largest index I such that for every 0 <= J <
     I, S1[J] = S2[J] - that is, I is the first position that does not
     match.  The character comparison is done case-insensitively.

 - Scheme Procedure: string= s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string<> s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string< s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string> s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string<= s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string>= s1 s2 [start1 end1 start2 end2]
     Compare S1 and S2 and return `#f' if the predicate fails.
     Otherwise, the mismatch index is returned (or END1 in the case of
     `string='.

 - Scheme Procedure: string-ci= s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-ci<> s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-ci< s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-ci> s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-ci<= s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-ci>= s1 s2 [start1 end1 start2 end2]
     Compare S1 and S2 and return `#f' if the predicate fails.
     Otherwise, the mismatch index is returned (or END1 in the case of
     `string='.  These are the case-insensitive variants.

 - Scheme Procedure: string-hash s [bound start end]
 - Scheme Procedure: string-hash-ci s [bound start end]
     Return a hash value of the string S in the range 0 ...  BOUND - 1.
     `string-hash-ci' is the case-insensitive variant.


File: guile.info,  Node: SRFI-13 Prefixes/Suffixes,  Next: SRFI-13 Searching,  Prev: SRFI-13 Comparison,  Up: SRFI-13

Prefixes/Suffixes
-----------------

   Using these procedures you can determine whether a given string is a
prefix or suffix of another string or how long a common prefix/suffix
is.

 - Scheme Procedure: string-prefix-length s1 s2 [start1 end1 start2
          end2]
 - Scheme Procedure: string-prefix-length-ci s1 s2 [start1 end1 start2
          end2]
 - Scheme Procedure: string-suffix-length s1 s2 [start1 end1 start2
          end2]
 - Scheme Procedure: string-suffix-length-ci s1 s2 [start1 end1 start2
          end2]
     Return the length of the longest common prefix/suffix of the two
     strings. `string-prefix-length-ci' and `string-suffix-length-ci'
     are the case-insensitive variants.

 - Scheme Procedure: string-prefix? s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-prefix-ci? s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-suffix? s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-suffix-ci? s1 s2 [start1 end1 start2 end2]
     Is S1 a prefix/suffix of S2. `string-prefix-ci?' and
     `string-suffix-ci?' are the case-insensitive variants.


File: guile.info,  Node: SRFI-13 Searching,  Next: SRFI-13 Case Mapping,  Prev: SRFI-13 Prefixes/Suffixes,  Up: SRFI-13

Searching
---------

   Use these procedures to find out whether a string contains a given
character or a given substring, or a character from a set of characters.

 - Scheme Procedure: string-index s char_pred [start end]
 - Scheme Procedure: string-index-right s char_pred [start end]
     Search through the string S from left to right (right to left),
     returning the index of the first (last) occurrence of a character
     which

        * equals CHAR_PRED, if it is character,

        * satisfies the predicate CHAR_PRED, if it is a procedure,

        * is in the set CHAR_PRED, if it is a character set.

 - Scheme Procedure: string-skip s char_pred [start end]
 - Scheme Procedure: string-skip-right s char_pred [start end]
     Search through the string S from left to right (right to left),
     returning the index of the first (last) occurrence of a character
     which

        * does not equal CHAR_PRED, if it is character,

        * does not satisfy the predicate CHAR_PRED, if it is a
          procedure.

        * is not in the set if CHAR_PRED is a character set.

 - Scheme Procedure: string-count s char_pred [start end]
     Return the count of the number of characters in the string S which

        * equals CHAR_PRED, if it is character,

        * satisfies the predicate CHAR_PRED, if it is a procedure.

        * is in the set CHAR_PRED, if it is a character set.

 - Scheme Procedure: string-contains s1 s2 [start1 end1 start2 end2]
 - Scheme Procedure: string-contains-ci s1 s2 [start1 end1 start2 end2]
     Does string S1 contain string S2?  Return the index in S1 where S2
     occurs as a substring, or false.  The optional start/end indices
     restrict the operation to the indicated substrings.

     `string-contains-ci' is the case-insensitive variant.


File: guile.info,  Node: SRFI-13 Case Mapping,  Next: SRFI-13 Reverse/Append,  Prev: SRFI-13 Searching,  Up: SRFI-13

Alphabetic Case Mapping
-----------------------

   These procedures convert the alphabetic case of strings.  They are
similar to the procedures in the Guile core, but are extended to handle
optional start/end indices.

 - Scheme Procedure: string-upcase s [start end]
 - Scheme Procedure: string-upcase! s [start end]
     Upcase every character in S.  `string-upcase!' is the
     side-effecting variant.

 - Scheme Procedure: string-downcase s [start end]
 - Scheme Procedure: string-downcase! s [start end]
     Downcase every character in S.  `string-downcase!' is the
     side-effecting variant.

 - Scheme Procedure: string-titlecase s [start end]
 - Scheme Procedure: string-titlecase! s [start end]
     Upcase every first character in every word in S, downcase the
     other characters.  `string-titlecase!' is the side-effecting
     variant.


File: guile.info,  Node: SRFI-13 Reverse/Append,  Next: SRFI-13 Fold/Unfold/Map,  Prev: SRFI-13 Case Mapping,  Up: SRFI-13

Reverse/Append
--------------

   One appending procedure, `string-append' is the same in R5RS and in
SRFI-13, so it is not redefined.

 - Scheme Procedure: string-reverse str [start end]
 - Scheme Procedure: string-reverse! str [start end]
     Reverse the string STR.  The optional arguments START and END
     delimit the region of STR to operate on.

     `string-reverse!' modifies the argument string and returns an
     unspecified value.

 - Scheme Procedure: string-append/shared ls ...
     Like `string-append', but the result may share memory with the
     argument strings.

 - Scheme Procedure: string-concatenate ls
     Append the elements of LS (which must be strings) together into a
     single string.  Guaranteed to return a freshly allocated string.

 - Scheme Procedure: string-concatenate/shared ls
     Like `string-concatenate', but the result may share memory with
     the strings in the list LS.

 - Scheme Procedure: string-concatenate-reverse ls final_string end
     Without optional arguments, this procedure is equivalent to

          (string-concatenate (reverse ls))

     If the optional argument FINAL_STRING is specified, it is consed
     onto the beginning to LS before performing the list-reverse and
     string-concatenate operations.  If END is given, only the
     characters of FINAL_STRING up to index END are used.

     Guaranteed to return a freshly allocated string.

 - Scheme Procedure: string-concatenate-reverse/shared ls final_string
          end
     Like `string-concatenate-reverse', but the result may share memory
     with the the strings in the LS arguments.


File: guile.info,  Node: SRFI-13 Fold/Unfold/Map,  Next: SRFI-13 Replicate/Rotate,  Prev: SRFI-13 Reverse/Append,  Up: SRFI-13

Fold/Unfold/Map
---------------

   `string-map', `string-for-each' etc. are for iterating over the
characters a string is composed of.  The fold and unfold procedures are
list iterators and constructors.

 - Scheme Procedure: string-map proc s [start end]
     PROC is a char->char procedure, it is mapped over S.  The order in
     which the procedure is applied to the string elements is not
     specified.

 - Scheme Procedure: string-map! proc s [start end]
     PROC is a char->char procedure, it is mapped over S.  The order in
     which the procedure is applied to the string elements is not
     specified.  The string S is modified in-place, the return value is
     not specified.

 - Scheme Procedure: string-fold kons knil s [start end]
 - Scheme Procedure: string-fold-right kons knil s [start end]
     Fold KONS over the characters of S, with KNIL as the terminating
     element, from left to right (or right to left, for
     `string-fold-right').  KONS must expect two arguments: The actual
     character and the last result of KONS' application.

 - Scheme Procedure: string-unfold p f g seed [base make_final]
 - Scheme Procedure: string-unfold-right p f g seed [base make_final]
     These are the fundamental string constructors.
        * G is used to generate a series of _seed_ values from the
          initial SEED: SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...

        * P tells us when to stop - when it returns true when applied
          to one of these seed values.

        * F maps each seed value to the corresponding character in the
          result string.  These chars are assembled into the string in
          a left-to-right (right-to-left) order.

        * BASE is the optional initial/leftmost (rightmost)  portion of
          the constructed string; it default to the empty string.

        * MAKE_FINAL is applied to the terminal seed value (on which P
          returns true) to produce the final/rightmost (leftmost)
          portion of the constructed string.  It defaults to `(lambda
          (x) "")'.

 - Scheme Procedure: string-for-each proc s [start end]
     PROC is mapped over S in left-to-right order.  The return value is
     not specified.


File: guile.info,  Node: SRFI-13 Replicate/Rotate,  Next: SRFI-13 Miscellaneous,  Prev: SRFI-13 Fold/Unfold/Map,  Up: SRFI-13

Replicate/Rotate
----------------

   These procedures are special substring procedures, which can also be
used for replicating strings.  They are a bit tricky to use, but
consider this code fragment, which replicates the input string `"foo"'
so often that the resulting string has a length of six.

     (xsubstring "foo" 0 6)
     =>
     "foofoo"

 - Scheme Procedure: xsubstring s from [to start end]
     This is the _extended substring_ procedure that implements
     replicated copying of a substring of some string.

     S is a string, START and END are optional arguments that demarcate
     a substring of S, defaulting to 0 and the length of S.  Replicate
     this substring up and down index space, in both the positive and
     negative directions.  `xsubstring' returns the substring of this
     string beginning at index FROM, and ending at TO, which defaults
     to FROM + (END - START).

 - Scheme Procedure: string-xcopy! target tstart s sfrom [sto start end]
     Exactly the same as `xsubstring', but the extracted text is
     written into the string TARGET starting at index TSTART.  The
     operation is not defined if `(eq?  TARGET S)' or these arguments
     share storage - you cannot copy a string on top of itself.


File: guile.info,  Node: SRFI-13 Miscellaneous,  Next: SRFI-13 Filtering/Deleting,  Prev: SRFI-13 Replicate/Rotate,  Up: SRFI-13

Miscellaneous
-------------

   `string-replace' is for replacing a portion of a string with another
string and `string-tokenize' splits a string into a list of strings,
breaking it up at a specified character.

 - Scheme Procedure: string-replace s1 s2 [start1 end1 start2 end2]
     Return the string S1, but with the characters START1 ... END1
     replaced by the characters START2 ... END2 from S2.

 - Scheme Procedure: string-tokenize s [token_char start end]
     Split the string S into a list of substrings, where each substring
     is a maximal non-empty contiguous sequence of characters equal to
     the character TOKEN_CHAR, or whitespace, if TOKEN_CHAR is not
     given.  If TOKEN_CHAR is a character set, it is used for finding
     the token borders.


File: guile.info,  Node: SRFI-13 Filtering/Deleting,  Prev: SRFI-13 Miscellaneous,  Up: SRFI-13

Filtering/Deleting
------------------

   "Filtering" means to remove all characters from a string which do
not match a given criteria, "deleting" means the opposite.

 - Scheme Procedure: string-filter s char_pred [start end]
     Filter the string S, retaining only those characters that satisfy
     the CHAR_PRED argument.  If the argument is a procedure, it is
     applied to each character as a predicate, if it is a character, it
     is tested for equality and if it is a character set, it is tested
     for membership.

 - Scheme Procedure: string-delete s char_pred [start end]
     Filter the string S, retaining only those characters that do not
     satisfy the CHAR_PRED argument.  If the argument is a procedure,
     it is applied to each character as a predicate, if it is a
     character, it is tested for equality and if it is a character set,
     it is tested for membership.


File: guile.info,  Node: SRFI-14,  Next: SRFI-16,  Prev: SRFI-13,  Up: SRFI Support

SRFI-14 - Character-set Library
===============================

   SRFI-14 defines the data type "character set", and also defines a
lot of procedures for handling this character type, and a few standard
character sets like whitespace, alphabetic characters and others.

   All procedures from SRFI-14 (character-set library) are implemented
in the module `(srfi srfi-14)', as well as the standard variables
`char-set:letter', `char-set:digit' etc.

* Menu:

* Loading SRFI-14::             How to make charsets available.
* SRFI-14 Character Set Data Type::  Underlying data type for charsets.
* SRFI-14 Predicates/Comparison::  Charset predicates.
* SRFI-14 Iterating Over Character Sets::  Enumerate charset elements.
* SRFI-14 Creating Character Sets::  Making new charsets.
* SRFI-14 Querying Character Sets::  Test charsets for membership etc.
* SRFI-14 Character-Set Algebra::  Calculating new charsets.
* SRFI-14 Standard Character Sets::  Variables containing predefined charsets.


File: guile.info,  Node: Loading SRFI-14,  Next: SRFI-14 Character Set Data Type,  Up: SRFI-14

Loading SRFI-14
---------------

   When Guile is properly installed, SRFI-14 support can be loaded into
a running Guile by using the `(srfi srfi-14)' module.

     $ guile
     guile> (use-modules (srfi srfi-14))
     guile> (char-set-union (char-set #\f #\o #\o) (string->char-set "bar"))
     #<charset {#\a #\b #\f #\o #\r}>
     guile>


File: guile.info,  Node: SRFI-14 Character Set Data Type,  Next: SRFI-14 Predicates/Comparison,  Prev: Loading SRFI-14,  Up: SRFI-14

Character Set Data Type
-----------------------

   The data type "charset" implements sets of characters (*note
Characters::).  Because the internal representation of character sets
is not visible to the user, a lot of procedures for handling them are
provided.

   Character sets can be created, extended, tested for the membership
of a characters and be compared to other character sets.

   The Guile implementation of character sets deals with 8-bit
characters.  In the standard variables, only the ASCII part of the
character range is really used, so that for example "Umlaute" and other
accented characters are not considered to be letters.  In the future,
as Guile may get support for international character sets, this will
change, so don't rely on these "features".


File: guile.info,  Node: SRFI-14 Predicates/Comparison,  Next: SRFI-14 Iterating Over Character Sets,  Prev: SRFI-14 Character Set Data Type,  Up: SRFI-14

Predicates/Comparison
---------------------

   Use these procedures for testing whether an object is a character
set, or whether several character sets are equal or subsets of each
other.  `char-set-hash' can be used for calculating a hash value, maybe
for usage in fast lookup procedures.

 - Scheme Procedure: char-set? obj
     Return `#t' if OBJ is a character set, `#f' otherwise.

 - Scheme Procedure: char-set= cs1 ...
     Return `#t' if all given character sets are equal.

 - Scheme Procedure: char-set<= cs1 ...
     Return `#t' if every character set CSi is a subset of character
     set CSi+1.

 - Scheme Procedure: char-set-hash cs [bound]
     Compute a hash value for the character set CS.  If BOUND is given
     and not `#f', it restricts the returned value to the range 0 ...
     BOUND - 1.


File: guile.info,  Node: SRFI-14 Iterating Over Character Sets,  Next: SRFI-14 Creating Character Sets,  Prev: SRFI-14 Predicates/Comparison,  Up: SRFI-14

Iterating Over Character Sets
-----------------------------

   Character set cursors are a means for iterating over the members of a
character sets.  After creating a character set cursor with
`char-set-cursor', a cursor can be dereferenced with `char-set-ref',
advanced to the next member with `char-set-cursor-next'.  Whether a
cursor has passed past the last element of the set can be checked with
`end-of-char-set?'.

   Additionally, mapping and (un-)folding procedures for character sets
are provided.

 - Scheme Procedure: char-set-cursor cs
     Return a cursor into the character set CS.

 - Scheme Procedure: char-set-ref cs cursor
     Return the character at the current cursor position CURSOR in the
     character set CS.  It is an error to pass a cursor for which
     `end-of-char-set?' returns true.

 - Scheme Procedure: char-set-cursor-next cs cursor
     Advance the character set cursor CURSOR to the next character in
     the character set CS.  It is an error if the cursor given
     satisfies `end-of-char-set?'.

 - Scheme Procedure: end-of-char-set? cursor
     Return `#t' if CURSOR has reached the end of a character set, `#f'
     otherwise.

 - Scheme Procedure: char-set-fold kons knil cs
     Fold the procedure KONS over the character set CS, initializing it
     with KNIL.

 - Scheme Procedure: char-set-unfold p f g seed [base_cs]
 - Scheme Procedure: char-set-unfold! p f g seed base_cs
     This is a fundamental constructor for character sets.
        * G is used to generate a series of "seed" values from the
          initial seed: SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...

        * P tells us when to stop - when it returns true when applied
          to one of the seed values.

        * F maps each seed value to a character. These characters are
          added to the base character set BASE_CS to form the result;
          BASE_CS defaults to the empty set.

     `char-set-unfold!' is the side-effecting variant.

 - Scheme Procedure: char-set-for-each proc cs
     Apply PROC to every character in the character set CS.  The return
     value is not specified.

 - Scheme Procedure: char-set-map proc cs
     Map the procedure PROC over every character in CS.  PROC must be a
     character -> character procedure.


File: guile.info,  Node: SRFI-14 Creating Character Sets,  Next: SRFI-14 Querying Character Sets,  Prev: SRFI-14 Iterating Over Character Sets,  Up: SRFI-14

Creating Character Sets
-----------------------

   New character sets are produced with these procedures.

 - Scheme Procedure: char-set-copy cs
     Return a newly allocated character set containing all characters
     in CS.

 - Scheme Procedure: char-set char1 ...
     Return a character set containing all given characters.

 - Scheme Procedure: list->char-set char_list [base_cs]
 - Scheme Procedure: list->char-set! char_list base_cs
     Convert the character list LIST to a character set.  If the
     character set BASE_CS is given, the character in this set are also
     included in the result.

     `list->char-set!' is the side-effecting variant.

 - Scheme Procedure: string->char-set s [base_cs]
 - Scheme Procedure: string->char-set! s base_cs
     Convert the string STR to a character set.  If the character set
     BASE_CS is given, the characters in this set are also included in
     the result.

     `string->char-set!' is the side-effecting variant.

 - Scheme Procedure: char-set-filter pred cs [base_cs]
 - Scheme Procedure: char-set-filter! pred cs base_cs
     Return a character set containing every character from CS so that
     it satisfies PRED.  If provided, the characters from BASE_CS are
     added to the result.

     `char-set-filter!' is the side-effecting variant.

 - Scheme Procedure: ucs-range->char-set lower upper [error? base_cs]
 - Scheme Procedure: uce-range->char-set! lower upper error? base_cs
     Return a character set containing all characters whose character
     codes lie in the half-open range [LOWER,UPPER).

     If ERROR is a true value, an error is signalled if the specified
     range contains characters which are not contained in the
     implemented character range.  If ERROR is `#f', these characters
     are silently left out of the resulting character set.

     The characters in BASE_CS are added to the result, if given.

     `ucs-range->char-set!' is the side-effecting variant.

 - Scheme Procedure: ->char-set x
     Coerce X into a character set.  X may be a string, a character or
     a character set.


File: guile.info,  Node: SRFI-14 Querying Character Sets,  Next: SRFI-14 Character-Set Algebra,  Prev: SRFI-14 Creating Character Sets,  Up: SRFI-14

Querying Character Sets
-----------------------

   Access the elements and other information of a character set with
these procedures.

 - Scheme Procedure: char-set-size cs
     Return the number of elements in character set CS.

 - Scheme Procedure: char-set-count pred cs
     Return the number of the elements int the character set CS which
     satisfy the predicate PRED.

 - Scheme Procedure: char-set->list cs
     Return a list containing the elements of the character set CS.

 - Scheme Procedure: char-set->string cs
     Return a string containing the elements of the character set CS.
     The order in which the characters are placed in the string is not
     defined.

 - Scheme Procedure: char-set-contains? cs char
     Return `#t' iff the character CH is contained in the character set
     CS.

 - Scheme Procedure: char-set-every pred cs
     Return a true value if every character in the character set CS
     satisfies the predicate PRED.

 - Scheme Procedure: char-set-any pred cs
     Return a true value if any character in the character set CS
     satisfies the predicate PRED.


File: guile.info,  Node: SRFI-14 Character-Set Algebra,  Next: SRFI-14 Standard Character Sets,  Prev: SRFI-14 Querying Character Sets,  Up: SRFI-14

Character-Set Algebra
---------------------

   Character sets can be manipulated with the common set algebra
operation, such as union, complement, intersection etc.  All of these
procedures provide side-effecting variants, which modify their
character set argument(s).

 - Scheme Procedure: char-set-adjoin cs char1 ...
 - Scheme Procedure: char-set-adjoin! cs char1 ...
     Add all character arguments to the first argument, which must be a
     character set.

 - Scheme Procedure: char-set-delete cs char1 ...
 - Scheme Procedure: char-set-delete! cs char1 ...
     Delete all character arguments from the first argument, which must
     be a character set.

 - Scheme Procedure: char-set-complement cs
 - Scheme Procedure: char-set-complement! cs
     Return the complement of the character set CS.

 - Scheme Procedure: char-set-union cs1 ...
 - Scheme Procedure: char-set-union! cs1 ...
     Return the union of all argument character sets.

 - Scheme Procedure: char-set-intersection cs1 ...
 - Scheme Procedure: char-set-intersection! cs1 ...
     Return the intersection of all argument character sets.

 - Scheme Procedure: char-set-difference cs1 ...
 - Scheme Procedure: char-set-difference! cs1 ...
     Return the difference of all argument character sets.

 - Scheme Procedure: char-set-xor cs1 ...
 - Scheme Procedure: char-set-xor! cs1 ...
     Return the exclusive-or of all argument character sets.

 - Scheme Procedure: char-set-diff+intersection cs1 ...
 - Scheme Procedure: char-set-diff+intersection! cs1 ...
     Return the difference and the intersection of all argument
     character sets.


File: guile.info,  Node: SRFI-14 Standard Character Sets,  Prev: SRFI-14 Character-Set Algebra,  Up: SRFI-14

Standard Character Sets
-----------------------

   In order to make the use of the character set data type and
procedures useful, several predefined character set variables exist.

 - Variable: char-set:lower-case
     All lower-case characters.

 - Variable: char-set:upper-case
     All upper-case characters.

 - Variable: char-set:title-case
     This is empty, because ASCII has no titlecase characters.

 - Variable: char-set:letter
     All letters, e.g. the union of `char-set:lower-case' and
     `char-set:upper-case'.

 - Variable: char-set:digit
     All digits.

 - Variable: char-set:letter+digit
     The union of `char-set:letter' and `char-set:digit'.

 - Variable: char-set:graphic
     All characters which would put ink on the paper.

 - Variable: char-set:printing
     The union of `char-set:graphic' and `char-set:whitespace'.

 - Variable: char-set:whitespace
     All whitespace characters.

 - Variable: char-set:blank
     All horizontal whitespace characters, that is `#\space' and
     `#\tab'.

 - Variable: char-set:iso-control
     The ISO control characters with the codes 0-31 and 127.

 - Variable: char-set:punctuation
     The characters `!"#%&'()*,-./:;?@[\\]_{}'

 - Variable: char-set:symbol
     The characters `$+<=>^`|~'.

 - Variable: char-set:hex-digit
     The hexadecimal digits `0123456789abcdefABCDEF'.

 - Variable: char-set:ascii
     All ASCII characters.

 - Variable: char-set:empty
     The empty character set.

 - Variable: char-set:full
     This character set contains all possible characters.


File: guile.info,  Node: SRFI-16,  Next: SRFI-17,  Prev: SRFI-14,  Up: SRFI Support

SRFI-16 - case-lambda
=====================

   The syntactic form `case-lambda' creates procedures, just like
`lambda', but has syntactic extensions for writing procedures of
varying arity easier.

   The syntax of the `case-lambda' form is defined in the following
EBNF grammar.

     <case-lambda>
        --> (case-lambda <case-lambda-clause>)
     <case-lambda-clause>
        --> (<formals> <definition-or-command>*)
     <formals>
        --> (<identifier>*)
          | (<identifier>* . <identifier>)
          | <identifier>

   The value returned by a `case-lambda' form is a procedure which
matches the number of actual arguments against the formals in the
various clauses, in order.  "Formals" means a formal argument list just
like with `lambda' (*note Lambda::). The first matching clause is
selected, the corresponding values from the actual parameter list are
bound to the variable names in the clauses and the body of the clause is
evaluated.  If no clause matches, an error is signalled.

   The following (silly) definition creates a procedure FOO which acts
differently, depending on the number of actual arguments.  If one
argument is given, the constant `#t' is returned, two arguments are
added and if more arguments are passed, their product is calculated.

     (define foo (case-lambda
                   ((x) #t)
                   ((x y) (+ x y))
                   (z
                     (apply * z))))
     (foo 'bar)
     =>
     #t
     (foo 2 4)
     =>
     6
     (foo 3 3 3)
     =>
     27
     (foo)
     =>
     1

   The last expression evaluates to 1 because the last clause is
matched, Z is bound to the empty list and the following multiplication,
applied to zero arguments, yields 1.


File: guile.info,  Node: SRFI-17,  Next: SRFI-19,  Prev: SRFI-16,  Up: SRFI Support

SRFI-17 - Generalized set!
==========================

   This is an implementation of SRFI-17: Generalized set!

   It exports the Guile procedure `make-procedure-with-setter' under
the SRFI name `getter-with-setter' and exports the standard procedures
`car', `cdr', ..., `cdddr', `string-ref' and `vector-ref' as procedures
with setters, as required by the SRFI.

   SRFI-17 was heavily criticized during its discussion period but it
was finalized anyway.  One issue was its concept of globally associating
setter "properties" with (procedure) values, which is non-Schemy.  For
this reason, this implementation chooses not to provide a way to set
the setter of a procedure.  In fact, `(set!  (setter PROC) SETTER)'
signals an error.  The only way to attach a setter to a procedure is to
create a new object (a "procedure with setter") via the
`getter-with-setter' procedure. This procedure is also specified in the
SRFI.  Using it avoids the described problems.


File: guile.info,  Node: SRFI-19,  Prev: SRFI-17,  Up: SRFI Support

SRFI-19 - Time/Date Library
===========================

   This is an implementation of SRFI-19: Time/Date Library

   It depends on SRFIs: 6 (*note SRFI-6::), 8 (*note SRFI-8::), 9
(*note SRFI-9::).

   This section documents constants and procedure signatures.

* Menu:

* SRFI-19 Constants::
* SRFI-19 Current time and clock resolution::
* SRFI-19 Time object and accessors::
* SRFI-19 Time comparison procedures::
* SRFI-19 Time arithmetic procedures::
* SRFI-19 Date object and accessors::
* SRFI-19 Time/Date/Julian Day/Modified Julian Day converters::
* SRFI-19 Date to string/string to date converters::


File: guile.info,  Node: SRFI-19 Constants,  Next: SRFI-19 Current time and clock resolution,  Up: SRFI-19

SRFI-19 Constants
-----------------

   All these are bound to their symbol names:

                time-duration
                time-monotonic
                time-process
                time-tai
                time-thread
                time-utc


File: guile.info,  Node: SRFI-19 Current time and clock resolution,  Next: SRFI-19 Time object and accessors,  Prev: SRFI-19 Constants,  Up: SRFI-19

SRFI-19 Current time and clock resolution
-----------------------------------------

                (current-date . tz-offset)
                (current-julian-day)
                (current-modified-julian-day)
                (current-time . clock-type)
                (time-resolution . clock-type)


File: guile.info,  Node: SRFI-19 Time object and accessors,  Next: SRFI-19 Time comparison procedures,  Prev: SRFI-19 Current time and clock resolution,  Up: SRFI-19

SRFI-19 Time object and accessors
---------------------------------

                (make-time type nanosecond second)
                (time? obj)
                (time-type time)
                (time-nanosecond time)
                (time-second time)
                (set-time-type! time type)
                (set-time-nanosecond! time nsec)
                (set-time-second! time sec)
                (copy-time time)


File: guile.info,  Node: SRFI-19 Time comparison procedures,  Next: SRFI-19 Time arithmetic procedures,  Prev: SRFI-19 Time object and accessors,  Up: SRFI-19

SRFI-19 Time comparison procedures
----------------------------------

   Args are all `time' values.

                (time<=? t1 t2)
                (time<? t1 t2)
                (time=? t1 t2)
                (time>=? t1 t2)
                (time>? t1 t2)


File: guile.info,  Node: SRFI-19 Time arithmetic procedures,  Next: SRFI-19 Date object and accessors,  Prev: SRFI-19 Time comparison procedures,  Up: SRFI-19

SRFI-19 Time arithmetic procedures
----------------------------------

   The `foo!' variants modify in place.  Time difference is expressed
in `time-duration' values.

                (time-difference t1 t2)
                (time-difference! t1 t2)
                (add-duration time duration)
                (add-duration! time duration)
                (subtract-duration time duration)
                (subtract-duration! time duration)


File: guile.info,  Node: SRFI-19 Date object and accessors,  Next: SRFI-19 Time/Date/Julian Day/Modified Julian Day converters,  Prev: SRFI-19 Time arithmetic procedures,  Up: SRFI-19

SRFI-19 Date object and accessors
---------------------------------

                (make-date nsecs seconds minutes hours
                           date month year offset)
                (date? obj)
                (date-nanosecond date)
                (date-second date)
                (date-minute date)
                (date-hour date)
                (date-day date)
                (date-month date)
                (date-year date)
                (date-zone-offset date)
                (date-year-day date)
                (date-week-day date)
                (date-week-number date day-of-week-starting-week)


File: guile.info,  Node: SRFI-19 Time/Date/Julian Day/Modified Julian Day converters,  Next: SRFI-19 Date to string/string to date converters,  Prev: SRFI-19 Date object and accessors,  Up: SRFI-19

SRFI-19 Time/Date/Julian Day/Modified Julian Day converters
-----------------------------------------------------------

                (date->julian-day date)
                (date->modified-julian-day date)
                (date->time-monotonic date)
                (date->time-tai date)
                (date->time-utc date)
                (julian-day->date jdn . tz-offset)
                (julian-day->time-monotonic jdn)
                (julian-day->time-tai jdn)
                (julian-day->time-utc jdn)
                (modified-julian-day->date jdn . tz-offset)
                (modified-julian-day->time-monotonic jdn)
                (modified-julian-day->time-tai jdn)
                (modified-julian-day->time-utc jdn)
                (time-monotonic->date time . tz-offset)
                (time-monotonic->time-tai time-in)
                (time-monotonic->time-tai! time-in)
                (time-monotonic->time-utc time-in)
                (time-monotonic->time-utc! time-in)
                (time-tai->date time . tz-offset)
                (time-tai->julian-day time)
                (time-tai->modified-julian-day time)
                (time-tai->time-monotonic time-in)
                (time-tai->time-monotonic! time-in)
                (time-tai->time-utc time-in)
                (time-tai->time-utc! time-in)
                (time-utc->date time . tz-offset)
                (time-utc->julian-day time)
                (time-utc->modified-julian-day time)
                (time-utc->time-monotonic time-in)
                (time-utc->time-monotonic! time-in)
                (time-utc->time-tai time-in)
                (time-utc->time-tai! time-in)


File: guile.info,  Node: SRFI-19 Date to string/string to date converters,  Prev: SRFI-19 Time/Date/Julian Day/Modified Julian Day converters,  Up: SRFI-19

SRFI-19 Date to string/string to date converters
------------------------------------------------

                (date->string date . format-string)
                (string->date input-string template-string)


File: guile.info,  Node: Readline Support,  Next: Value History,  Prev: SRFI Support,  Up: Top

Readline Support
****************

   Guile comes with an interface module to the readline library.  This
makes interactive use much more convenient, because of the command-line
editing features of readline.  Using `(ice-9 readline)', you can
navigate through the current input line with the cursor keys, retrieve
older command lines from the input history and even search through the
history entries.

* Menu:

* Loading Readline Support::    How to load readline support into Guile.
* Readline Options::            How to modify readline's behaviour.


File: guile.info,  Node: Loading Readline Support,  Next: Readline Options,  Up: Readline Support

Loading Readline Support
========================

   The module is not loaded by default and so has to be loaded and
activated explicitly.  This is done with two simple lines of code:

     (use-modules (ice-9 readline))
     (activate-readline)

   The first line will load the necessary code, and the second will
activate readline's features for the REPL.  If you plan to use this
module often, you should save these to lines to your `.guile' personal
startup file.

   You will notice that the REPL's behaviour changes a bit when you have
loaded the readline module.  For example, when you press Enter before
typing in the closing parentheses of a list, you will see the
"continuation" prompt, three dots: `...'  This gives you a nice visual
feedback when trying to match parentheses.  To make this even easier,
"bouncing parentheses" are implemented.  That means that when you type
in a closing parentheses, the cursor will jump to the corresponding
opening parenthesis for a short time, making it trivial to make them
match.

   Once the readline module is activated, all lines entered
interactively will be stored in a history and can be recalled later
using the cursor-up and -down keys.  Readline also understands the
Emacs keys for navigating through the command line and history.

   When you quit your Guile session by evaluating `(quit)' or pressing
Ctrl-D, the history will be saved to the file `.guile_history' and read
in when you start Guile for the next time.  Thus you can start a new
Guile session and still have the (probably long-winded) definition
expressions available.


File: guile.info,  Node: Readline Options,  Prev: Loading Readline Support,  Up: Readline Support

Readline Options
================

   The readline interface module can be configured in several ways to
better suit the user's needs.  Configuration is done via the readline
module's options interface, in a similar way to the evaluator and
debugging options (*note User level options interfaces::.)

   Here is the list of readline options generated by typing
`(readline-options 'full)' in Guile.  You can also see the default
values.

     bounce-parens   500   Time (ms) to show matching opening parenthesis (0 = off).
     history-length  200   History length.
     history-file    yes   Use history file.

   The history length specifies how many input lines will be remembered.
If the history contains that many lines and additional lines are
entered, the oldest lines will be lost.  You can switch on/off the
usage of the history file using the following call.

     (readline-disable 'history)

   The readline options interface can only be used _after_ loading the
readline module, because it is defined in that module.


File: guile.info,  Node: Value History,  Next: Pretty Printing,  Prev: Readline Support,  Up: Top

Value History
*************

   Another module which makes command line usage more convenient is
`(ice-9 history)'.  This module will change the REPL so that each value
which is evaluated and printed will be remembered under a name
constructed from the dollar character (`$') and the number of the
evaluated expression.

   Consider an example session.

     guile> (use-modules (ice-9 history))
     guile> 1
     $1 = 1
     guile> (+ $1 $1)
     $2 = 2
     guile> (* $2 $2)
     $3 = 4

   After loading the value history module `(ice-9 history)', one
(trivial) expression is evaluated.  The result is stored into the
variable `$1'.  This fact is indicated by the output `$1 = ', which is
also caused by `(ice-9 history)'.  In the next line, this variable is
used two times, to produce the value `$2', which in turn is used in the
calculation for `$3'.


File: guile.info,  Node: Pretty Printing,  Next: Formatted Output,  Prev: Value History,  Up: Top

Pretty Printing
***************

   The module `(ice-9 pretty-print)' provides the procedure
`pretty-print', which provides nicely formatted output of Scheme
objects.  This is especially useful for deeply nested or complex data
structures, such as lists and vectors.

   The module is loaded by simply saying.

     (use-modules (ice-9 pretty-print))

   This makes the procedure `pretty-print' available.  As an example
how `pretty-print' will format the output, see the following:

     (pretty-print '(define (foo) (lambda (x)
     (cond ((zero? x) #t) ((negative? x) -x) (else (if (= x 1) 2 (* x x x)))))))
     -|
     (define (foo)
       (lambda (x)
         (cond ((zero? x) #t)
               ((negative? x) -x)
               (else (if (= x 1) 2 (* x x x))))))

 - Scheme Procedure: pretty-print obj [port]
     Print the textual representation of the Scheme object OBJ to PORT.
     PORT defaults to the current output port, if not given.

   Beware: Since `pretty-print' uses it's own write procedure, it's
output will not be the same as for example the output of `write'.
Consider the following example.

     (write (lambda (x) x))
     -|
     #<procedure #f (x)>
     
     (pretty-print (lambda (x) x))
     -|
     #[procedure]

   The reason is that `pretty-print' does not know as much about
Guile's object types as the builtin procedures.  This is particularly
important for smobs, for which a write procedure can be defined and be
used by `write', but not by `pretty-print'.


File: guile.info,  Node: Formatted Output,  Next: Rx Regexps,  Prev: Pretty Printing,  Up: Top

Formatted Output
****************

   Outputting messages or other texts which are composed of literal
strings, variable contents, newlines and other formatting can be
cumbersome, when only the standard procedures like `display', `write'
and `newline' are available.  Additionally, one often wants to collect
the output in strings.  With the standard routines, the user is
required to set up a string port, add this port as a parameter to the
output procedure calls and then retrieve the resulting string from the
string port.

   The `format' procedure, to be found in module `(ice-9 format)', can
do all this, and even more.  If you are a C programmer, you can think
of this procedure as Guile's `fprintf'.

 - Scheme Procedure: format destination format-string args ...
     The first parameter is the DESTINATION, it determines where the
     output of `format' will go.

    `#t'
          Send the formatted output to the current output port and
          return `#t'.

    `#f'
          Return the formatted output as a string.

    Any number value
          Send the formatted output to the current error port and return
          `#t'.

    A valid output port
          Send the formatted output to the port DESTINATION and return
          `#t'.

     The second parameter is the format string.  It has a similar
     function to the format string in calls to `printf' or `fprintf' in
     C.  It is output to the specified destination, but all escape
     sequences are replaced by the results of formatting the
     corresponding sequence.

     Note that escape sequences are marked with the character `~'
     (tilde), and not with a `%' (percent sign), as in C.

     The escape sequences in the following table are supported.  When
     there appears "corresponding ARG', that means any of the additional
     arguments, after dropping all arguments which have been used up by
     escape sequences which have been processed earlier.  Some of the
     format characters (the characters following the tilde) can be
     prefixed by `:', `@', or `:@', to modify the behaviour of the
     format character.  How the modified behaviour differs from the
     default behaviour is described for every character in the table
     where appropriate.

    `~~'
          Output a single `~' (tilde) character.

    `~%'
          Output a newline character, thus advancing to the next output
          line.

    `~&'
          Start a new line, that is, output a newline character if not
          already at the start of a line.

    `~_'
          Output a single space character.

    `~/'
          Output a single tabulator character.

    `~|'
          Output a page separator (formfeed) character.

    `~t'
          Advance to the next tabulator position.

    `~y'
          Pretty-print the corresponding ARG.

    `~a'
          Output the corresponding ARG like `display'.

    `~s'
          Output the corresponding ARG like `write'.

    `~d'
          Output the corresponding ARG as a decimal number.

    `~x'
          Output the corresponding ARG as a hexadecimal number.

    `~o'
          Output the corresponding ARG as an octal number.

    `~b'
          Output the corresponding ARG as a binary number.

    `~r'
          Output the corresponding ARG as a number word, e.g. 10 prints
          as `ten'.  If prefixed with `:', `tenth' is printed, if
          prefixed with `:@', Roman numbers are printed.

    `~f'
          Output the corresponding ARG as a fixed format floating point
          number, such as `1.34'.

    `~e'
          Output the corresponding ARG in exponential notation, such as
          `1.34E+0'.

    `~g'
          This works either like `~f' or like `~e', whichever produces
          less characters to be written.

    `~$'
          Like `~f', but only with two digits after the decimal point.

    `~i'
          Output the corresponding ARG as a complex number.

    `~c'
          Output the corresponding ARG as a character.  If prefixed with
          `@', it is printed like with `write'.  If prefixed with `:',
          control characters are treated specially, for example
          `#\newline' will be printed as `^J'.

    `~p'
          "Plural".  If the corresponding ARG is 1, nothing is printed
          (or `y' if prefixed with `@' or `:@'), otherwise `s' is
          printed (or `ies' if prefixed with `@' or `:@').

    `~?, ~k'
          Take the corresponding argument as a format string, and the
          following argument as a list of values.  Then format the
          values with respect to the format string.

    `~!'
          Flush the output to the output port.

    `~#\newline (tilde-newline)'
          Continuation lines.

    `~*'
          Argument jumping. Navigate in the argument list as specified
          by the corresponding argument.  If prefixed with `:', jump
          backwards in the argument list, if prefixed by `:@', jump to
          the parameter with the absolute index, otherwise jump forward
          in the argument list.

    `~('
          Case conversion begin.  If prefixed by `:', the following
          output string will be capitalized, if prefixed by `@', the
          first character will be capitalized, if prefixed by `:@' it
          will be upcased and otherwise it will be downcased.
          Conversion stops when the "Case conversion end" `~)'sequence
          is encountered.

    `~)'
          Case conversion end.  Stop any case conversion currently in
          effect.

    `~['
          Conditional begin.

    `~;'
          Conditional separator.

    `~]'
          Conditional end.

    `~{'
          Iteration begin.

    `~}'
          Iteration end.

    `~^'
          Up and out.

    `~''
          Character parameter.

    `~0 ... ~9, ~-, ~+'
          Numeric parameter.

    `~v'
          Variable parameter from next argument.

    `~#'
          Parameter is number of remaining args.  The number of the
          remaining arguments is prepended to the list of unprocessed
          arguments.

    `~,'
          Parameter separators.

    `~q'
          Inquiry message.  Insert a copyright message into the output.

     If any type conversions should fail (for example when using an
     escape sequence for number output, but the argument is a string),
     an error will be signalled.

   You may have noticed that Guile contains a `format' procedure even
when the module `(ice-9 format)' is not loaded.  The default `format'
procedure does not support all escape sequences documented in this
chapter, and will signal an error if you try to use one of them.  The
reason for providing two versions of `format' is that the full-featured
module is fairly large and requires some time to get loaded.  So the
Guile maintainers decided not to load the large version of `format' by
default, so that the start-up time of the interpreter is not
unnecessarily increased.


File: guile.info,  Node: Rx Regexps,  Next: Expect,  Prev: Formatted Output,  Up: Top

The Rx Regular Expression Library
*********************************

   [FIXME: this is taken from Gary and Mark's quick summaries and
should be reviewed and expanded.  Rx is pretty stable, so could already
be done!]

   The `guile-lang-allover' package provides an interface to Tom Lord's
Rx library (currently only to POSIX regular expressions).  Use of the
library requires a two step process: compile a regular expression into
an efficient structure, then use the structure in any number of string
comparisons.

   For example, given the regular expression `abc.' (which matches any
string containing `abc' followed by any single character):

     guile> (define r (regcomp "abc."))
     guile> r
     #<rgx abc.>
     guile> (regexec r "abc")
     #f
     guile> (regexec r "abcd")
     #((0 . 4))
     guile>

   The definitions of `regcomp' and `regexec' are as follows:

 - Scheme Procedure: regcomp pattern [flags]
     Compile the regular expression pattern using POSIX rules.  Flags is
     optional and should be specified using symbolic names:

      - Variable: REG_EXTENDED
          use extended POSIX syntax

      - Variable: REG_ICASE
          use case-insensitive matching

      - Variable: REG_NEWLINE
          allow anchors to match after newline characters in the string
          and prevents `.' or `[^...]' from matching newlines.

     The `logior' procedure can be used to combine multiple flags.  The
     default is to use POSIX basic syntax, which makes `+' and `?'
     literals and `\+' and `\?' operators.  Backslashes in PATTERN must
     be escaped if specified in a literal string e.g., `"\\(a\\)\\?"'.

 - Scheme Procedure: regexec regex string [match-pick] [flags]
     Match STRING against the compiled POSIX regular expression REGEX.
     MATCH-PICK and FLAGS are optional.  Possible flags (which can be
     combined using the logior procedure) are:

      - Variable: REG_NOTBOL
          The beginning of line operator won't match the beginning of
          STRING (presumably because it's not the beginning of a line)

      - Variable: REG_NOTEOL
          Similar to REG_NOTBOL, but prevents the end of line operator
          from matching the end of STRING.

     If no match is possible, regexec returns #f.  Otherwise MATCH-PICK
     determines the return value:

     `#t' or unspecified: a newly-allocated vector is returned,
     containing pairs with the indices of the matched part of STRING
     and any substrings.

     `""': a list is returned: the first element contains a nested list
     with the matched part of STRING surrounded by the the unmatched
     parts.  Remaining elements are matched substrings (if any).  All
     returned substrings share memory with STRING.

     `#f': regexec returns #t if a match is made, otherwise #f.

     vector: the supplied vector is returned, with the first element
     replaced by a pair containing the indices of the matched portion
     of STRING and further elements replaced by pairs containing the
     indices of matched substrings (if any).

     list: a list will be returned, with each member of the list
     specified by a code in the corresponding position of the supplied
     list:

     a number: the numbered matching substring (0 for the entire match).

     `#\<': the beginning of STRING to the beginning of the part matched
     by regex.

     `#\>': the end of the matched part of STRING to the end of STRING.

     `#\c': the "final tag", which seems to be associated with the "cut
     operator", which doesn't seem to be available through the posix
     interface.

     e.g., `(list #\< 0 1 #\>)'.  The returned substrings share memory
     with STRING.

   Here are some other procedures that might be used when using regular
expressions:

 - Scheme Procedure: compiled-regexp? obj
     Test whether obj is a compiled regular expression.

 - Scheme Procedure: regexp->dfa regex [flags]

 - Scheme Procedure: dfa-fork dfa

 - Scheme Procedure: reset-dfa! dfa

 - Scheme Procedure: dfa-final-tag dfa

 - Scheme Procedure: dfa-continuable? dfa

 - Scheme Procedure: advance-dfa! dfa string


File: guile.info,  Node: Expect,  Next: The Scheme shell (scsh),  Prev: Rx Regexps,  Up: Top

Expect
******

   The macros in this section are made available with:

     (use-modules (ice-9 expect))

   `expect' is a macro for selecting actions based on the output from a
port.  The name comes from a tool of similar functionality by Don Libes.
Actions can be taken when a particular string is matched, when a timeout
occurs, or when end-of-file is seen on the port.  The `expect' macro is
described below; `expect-strings' is a front-end to `expect' based on
regexec (see the regular expression documentation).

 - Macro: expect-strings clause ...
     By default, `expect-strings' will read from the current input port.
     The first term in each clause consists of an expression evaluating
     to a string pattern (regular expression).  As characters are read
     one-by-one from the port, they are accumulated in a buffer string
     which is matched against each of the patterns.  When a pattern
     matches, the remaining expression(s) in the clause are evaluated
     and the value of the last is returned.  For example:

          (with-input-from-file "/etc/passwd"
            (lambda ()
              (expect-strings
                ("^nobody" (display "Got a nobody user.\n")
                           (display "That's no problem.\n"))
                ("^daemon" (display "Got a daemon user.\n")))))

     The regular expression is compiled with the `REG_NEWLINE' flag, so
     that the ^ and $ anchors will match at any newline, not just at
     the start and end of the string.

     There are two other ways to write a clause:

     The expression(s) to evaluate can be omitted, in which case the
     result of the regular expression match (converted to strings, as
     obtained from regexec with match-pick set to "") will be returned
     if the pattern matches.

     The symbol `=>' can be used to indicate that the expression is a
     procedure which will accept the result of a successful regular
     expression match.  E.g.,

          ("^daemon" => write)
          ("^d\\(aemon\\)" => (lambda args (for-each write args)))
          ("^da\\(em\\)on" => (lambda (all sub)
                                   (write all) (newline)
                                   (write sub) (newline)))

     The order of the substrings corresponds to the order in which the
     opening brackets occur.

     A number of variables can be used to control the behaviour of
     `expect' (and `expect-strings').  Most have default top-level
     bindings to the value `#f', which produces the default behaviour.
     They can be redefined at the top level or locally bound in a form
     enclosing the expect expression.

    `expect-port'
          A port to read characters from, instead of the current input
          port.

    `expect-timeout'
          `expect' will terminate after this number of seconds,
          returning `#f' or the value returned by expect-timeout-proc.

    `expect-timeout-proc'
          A procedure called if timeout occurs.  The procedure takes a
          single argument: the accumulated string.

    `expect-eof-proc'
          A procedure called if end-of-file is detected on the input
          port.  The procedure takes a single argument: the accumulated
          string.

    `expect-char-proc'
          A procedure to be called every time a character is read from
          the port.  The procedure takes a single argument: the
          character which was read.

    `expect-strings-compile-flags'
          Flags to be used when compiling a regular expression, which
          are passed to `make-regexp' *Note Regexp Functions::.  The
          default value is `regexp/newline'.

    `expect-strings-exec-flags'
          Flags to be used when executing a regular expression, which
          are passed to regexp-exec *Note Regexp Functions::.  The
          default value is `regexp/noteol', which prevents `$' from
          matching the end of the string while it is still accumulating,
          but still allows it to match after a line break or at the end
          of file.

     Here's an example using all of the variables:

          (let ((expect-port (open-input-file "/etc/passwd"))
                (expect-timeout 1)
                (expect-timeout-proc
                  (lambda (s) (display "Times up!\n")))
                (expect-eof-proc
                  (lambda (s) (display "Reached the end of the file!\n")))
                (expect-char-proc display)
                (expect-strings-compile-flags (logior regexp/newline regexp/icase))
                (expect-strings-exec-flags 0))
             (expect-strings
               ("^nobody"  (display "Got a nobody user\n"))))

 - Macro: expect clause ...
     `expect' is used in the same way as `expect-strings', but tests
     are specified not as patterns, but as procedures.  The procedures
     are called in turn after each character is read from the port,
     with two arguments: the value of the accumulated string and a flag
     to indicate whether end-of-file has been reached.  The flag will
     usually be `#f', but if end-of-file is reached, the procedures are
     called an additional time with the final accumulated string and
     `#t'.

     The test is successful if the procedure returns a non-false value.

     If the `=>' syntax is used, then if the test succeeds it must
     return a list containing the arguments to be provided to the
     corresponding expression.

     In the following example, a string will only be matched at the
     beginning of the file:

          (let ((expect-port (open-input-file "/etc/passwd")))
            (expect
               ((lambda (s eof?) (string=? s "fnord!"))
                  (display "Got a nobody user!\n"))))

     The control variables described for `expect-strings' also
     influence the behaviour of `expect', with the exception of
     variables whose names begin with `expect-strings-'.


File: guile.info,  Node: The Scheme shell (scsh),  Next: Concept Index,  Prev: Expect,  Up: Top

The Scheme shell (scsh)
***********************

   An incomplete port of the Scheme shell (scsh) is available for Guile
as a separate package.  The current status of guile-scsh can be found at
<http://arglist.com/guile/>.

   For information about scsh see
<http://www-swiss.ai.mit.edu/ftpdir/scsh/>.

   The closest emulation of scsh can be obtained by running:

     (load-from-path "scsh/init")

   See the USAGE file supplied with guile-scsh for more details.


File: guile.info,  Node: Concept Index,  Next: Procedure Index,  Prev: The Scheme shell (scsh),  Up: Top

Concept Index
*************

   This index contains concepts, keywords and non-Schemey names for
several features, to make it easier to locate the desired sections.

* Menu:

* #,():                                  SRFI-10.
* Alist:                                 Association Lists.
* arbiters:                              Arbiters.
* Association List:                      Association Lists.
* asyncs:                                Asyncs.
* begin:                                 begin.
* call-with-current-continuation:        Continuations.
* call/cc:                               Continuations.
* case:                                  if cond case.
* chaining environments:                 Chaining.
* closure:                               About Closure.
* command line history:                  Readline Support.
* cond:                                  if cond case.
* conditional evaluation:                if cond case.
* converting data:                       Converting data between C and Scheme.
* data conversion:                       Converting data between C and Scheme.
* Database:                              Association Lists.
* dynamic roots:                         Dynamic Roots.
* emacs regexp:                          Regular Expressions.
* encapsulation:                         Modules.
* environment <1>:                       Environments.
* environment:                           About Environments.
* environment, local:                    Local Variables.
* environment, top level:                About Environments.
* equality:                              Equality.
* error handling:                        Exceptions.
* error messages in libguile:            Error messages.
* exception handling:                    Exceptions.
* executable modules:                    Executable Modules.
* executing Scheme:                      Executing Scheme code.
* expression sequencing:                 begin.
* finite automaton:                      Rx Regexps.
* fluids:                                Fluids.
* format:                                Formatted Output.
* formatted output:                      Formatted Output.
* gh:                                    GH.
* gh - headers:                          gh preliminaries.
* gh - linking:                          gh preliminaries.
* gh - reference manual:                 GH.
* Green, Anthony:                        Threads.
* guardians, testing for GC'd objects:   GC Hooks.
* Guile threads:                         Threads.
* guile-snarf deprecated macros:         Macros guile-snarf recognizes.
* guile-snarf example:                   How guile-snarf works.
* guile-snarf invocation:                How guile-snarf works.
* guile-snarf recognized macros:         Macros guile-snarf recognizes.
* guile-tools:                           Executable Modules.
* GUILE_LOAD_PATH:                       Build Config.
* hash-comma:                            SRFI-10.
* if:                                    if cond case.
* iff:                                   Manual Conventions.
* information encapsulation:             Modules.
* iteration:                             while do.
* Jaffer, Aubrey:                        JACAL.
* libguile - converting data:            Converting data between C and Scheme.
* libguile - data types:                 Data types and constants defined by gh.
* libguile - error messages:             Error messages.
* libguile - executing Scheme:           Executing Scheme code.
* libguile - gh:                         GH.
* libguile - new procedures:             Defining new Scheme procedures in C.
* libguile - start interpreter:          Starting and controlling the interpreter.
* local bindings:                        Local Bindings.
* local environment:                     Local Variables.
* local variable:                        Local Variables.
* local variables:                       Local Bindings.
* location:                              About Environments.
* looping:                               while do.
* Lord, Tom:                             Threads.
* macros:                                Macros.
* match structures:                      Match Structures.
* math - symbolic:                       JACAL.
* modules:                               Modules.
* modules, executable:                   Executable Modules.
* multiline comments:                    Block Comments.
* multiple values:                       Multiple Values.
* name space:                            Modules.
* name space - private:                  Modules.
* named let:                             while do.
* new primitives:                        Defining new Scheme procedures in C.
* new procedures:                        Defining new Scheme procedures in C.
* options - read:                        Reader options.
* overflow, stack:                       Debugger options.
* posix threads:                         Threads.
* pretty printing:                       Pretty Printing.
* primitive functions:                   Init Snarfing with guile-snarf.
* primitives, new:                       Defining new Scheme procedures in C.
* procedure documentation:               Procedure Properties.
* procedure properties:                  Procedure Properties.
* procedure with setter:                 Procedures with Setters.
* procedures, new:                       Defining new Scheme procedures in C.
* R5RS syntax-rules system:              Syntax Rules.
* read eval print loop - from the gh_ interface: Starting and controlling the interpreter.
* read options:                          Reader options.
* readline:                              Readline Support.
* readline options:                      Readline Options.
* receive:                               Multiple Values.
* regex:                                 Regular Expressions.
* regular expressions:                   Regular Expressions.
* REPL - from the gh_ interface:         Starting and controlling the interpreter.
* rx:                                    Rx Regexps.
* sameness:                              Equality.
* SCM data type:                         Unpacking the SCM type.
* scripts:                               Executable Modules.
* sequencing:                            begin.
* setter:                                Procedures with Setters.
* shadowing an imported variable binding: Chaining.
* snarfing:                              Snarfing.
* snarfing, init:                        Init Snarfing with guile-snarf.
* socket client example:                 Internet Socket Client.
* socket server example:                 Internet Socket Server.
* sorting:                               Sorting.
* sorting lists:                         Sorting.
* sorting vectors:                       Sorting.
* source properties <1>:                 Procedure Properties.
* source properties:                     Source Properties.
* stack overflow:                        Debugger options.
* subrs, defining:                       Init Snarfing with guile-snarf.
* symbolic math:                         JACAL.
* system asyncs:                         Asyncs.
* threads:                               Threads.
* top level environment:                 About Environments.
* transformation:                        Macros.
* value history:                         Value History.
* variable definition:                   Top Level.
* variable, local:                       Local Variables.
* vcell:                                 About Environments.


File: guile.info,  Node: Procedure Index,  Next: Variable Index,  Prev: Concept Index,  Up: Top

Procedure Index
***************

   This is an alphabetical list of all the procedures and macros in
Guile.

   When looking for a particular procedure, please look under its Scheme
name as well as under its C name.  The C name can be constructed from
the Scheme names by a simple transformation described in the section
*Note Transforming Scheme name to C name::.

* Menu:

* $abs:                                  Primitive Numerics.
* $acos:                                 Primitive Numerics.
* $acosh:                                Primitive Numerics.
* $asin:                                 Primitive Numerics.
* $asinh:                                Primitive Numerics.
* $atan:                                 Primitive Numerics.
* $atan2:                                Primitive Numerics.
* $atanh:                                Primitive Numerics.
* $cos:                                  Primitive Numerics.
* $cosh:                                 Primitive Numerics.
* $exp:                                  Primitive Numerics.
* $expt:                                 Primitive Numerics.
* $log:                                  Primitive Numerics.
* $sin:                                  Primitive Numerics.
* $sinh:                                 Primitive Numerics.
* $sqrt:                                 Primitive Numerics.
* $tan:                                  Primitive Numerics.
* $tanh:                                 Primitive Numerics.
* %library-dir:                          Build Config.
* %make-void-port:                       Void Ports.
* %package-data-dir:                     Build Config.
* %read-delimited!:                      Line/Delimited.
* %read-line:                            Line/Delimited.
* %search-load-path:                     Loading.
* %site-dir:                             Build Config.
* %thread-handler:                       Higher level thread procedures.
* * <1>:                                 C Hooks.
* *:                                     Arithmetic.
* *gh_scm2chars:                         Scheme to C.
* *gh_scm2doubles:                       Scheme to C.
* *gh_scm2floats:                        Scheme to C.
* *gh_scm2longs:                         Scheme to C.
* *gh_scm2newstr:                        Scheme to C.
* *gh_scm2shorts:                        Scheme to C.
* *gh_symbol2newstr:                     Scheme to C.
* +:                                     Arithmetic.
* -:                                     Arithmetic.
* ->char-set:                            SRFI-14 Creating Character Sets.
* /:                                     Arithmetic.
* <:                                     Comparison.
* <=:                                    Comparison.
* <group>-disable:                       User level options interfaces.
* <group>-enable:                        User level options interfaces.
* <group>-options:                       User level options interfaces.
* <group>-set!:                          User level options interfaces.
* =:                                     Comparison.
* >:                                     Comparison.
* >=:                                    Comparison.
* abs:                                   Arithmetic.
* accept:                                Network Sockets and Communication.
* access?:                               File System.
* acons:                                 Adding or Setting Alist Entries.
* acos:                                  Scientific.
* acosh:                                 Scientific.
* add-hook!:                             Hook Reference.
* advance-dfa!:                          Rx Regexps.
* alarm:                                 Signals.
* alist-cons:                            SRFI-1 Association Lists.
* alist-copy:                            SRFI-1 Association Lists.
* alist-delete:                          SRFI-1 Association Lists.
* alist-delete!:                         SRFI-1 Association Lists.
* and:                                   and or.
* angle:                                 Complex.
* any:                                   SRFI-1 Searching.
* append:                                Append/Reverse.
* append!:                               Append/Reverse.
* append-map:                            SRFI-1 Fold and Map.
* append-map!:                           SRFI-1 Fold and Map.
* append-reverse:                        SRFI-1 Length Append etc.
* append-reverse!:                       SRFI-1 Length Append etc.
* apply:                                 Fly Evaluation.
* apply:nconc2last:                      Fly Evaluation.
* array->list:                           Conventional Arrays.
* array-contents:                        Conventional Arrays.
* array-copy!:                           Conventional Arrays.
* array-copy-in-order!:                  Conventional Arrays.
* array-dimensions:                      Conventional Arrays.
* array-equal?:                          Conventional Arrays.
* array-fill!:                           Conventional Arrays.
* array-for-each:                        Array Mapping.
* array-in-bounds?:                      Conventional Arrays.
* array-index-map!:                      Array Mapping.
* array-map!:                            Array Mapping.
* array-map-in-order!:                   Array Mapping.
* array-prototype:                       Uniform Arrays.
* array-rank:                            Conventional Arrays.
* array-ref:                             Conventional Arrays.
* array-set!:                            Conventional Arrays.
* array-shape:                           Conventional Arrays.
* array? <1>:                            Uniform Arrays.
* array?:                                Conventional Arrays.
* ash:                                   Bitwise Operations.
* asin:                                  Scientific.
* asinh:                                 Scientific.
* assoc <1>:                             Retrieving Alist Entries.
* assoc:                                 SRFI-1 Association Lists.
* assoc-ref:                             Retrieving Alist Entries.
* assoc-remove!:                         Removing Alist Entries.
* assoc-set!:                            Adding or Setting Alist Entries.
* assq:                                  Retrieving Alist Entries.
* assq-ref:                              Retrieving Alist Entries.
* assq-remove!:                          Removing Alist Entries.
* assq-set!:                             Adding or Setting Alist Entries.
* assv:                                  Retrieving Alist Entries.
* assv-ref:                              Retrieving Alist Entries.
* assv-remove!:                          Removing Alist Entries.
* assv-set!:                             Adding or Setting Alist Entries.
* async:                                 Asyncs.
* async-mark:                            Asyncs.
* atan:                                  Scientific.
* atanh:                                 Scientific.
* backtrace:                             Backtrace.
* basename:                              File System.
* batch-mode?:                           Dynamic Roots.
* begin:                                 begin.
* begin-thread:                          Higher level thread procedures.
* bind:                                  Network Sockets and Communication.
* bit-count:                             Bit Vectors.
* bit-count*:                            Bit Vectors.
* bit-extract:                           Bitwise Operations.
* bit-invert!:                           Bit Vectors.
* bit-position:                          Bit Vectors.
* bit-set*!:                             Bit Vectors.
* boolean?:                              Booleans.
* break:                                 SRFI-1 Searching.
* break!:                                SRFI-1 Searching.
* builtin-bindings:                      Obarray Symbols.
* caar:                                  Pairs.
* cadr:                                  Pairs.
* call-with-current-continuation:        Continuations.
* call-with-dynamic-root:                Dynamic Roots.
* call-with-input-file:                  File Ports.
* call-with-input-string:                String Ports.
* call-with-new-thread:                  Low level thread primitives.
* call-with-output-file:                 File Ports.
* call-with-output-string:               String Ports.
* call-with-values:                      Multiple Values.
* car:                                   Pairs.
* car+cdr:                               SRFI-1 Selectors.
* case:                                  if cond case.
* catch:                                 Catch.
* cd:                                    Processes.
* cdddar:                                Pairs.
* cddddr:                                Pairs.
* cdr:                                   Pairs.
* ceiling:                               Arithmetic.
* char->integer:                         Characters.
* char-alphabetic?:                      Characters.
* char-ci<=?:                            Characters.
* char-ci<?:                             Characters.
* char-ci=?:                             Characters.
* char-ci>=?:                            Characters.
* char-ci>?:                             Characters.
* char-downcase:                         Characters.
* char-is-both?:                         Characters.
* char-lower-case?:                      Characters.
* char-numeric?:                         Characters.
* char-ready?:                           Reading.
* char-set:                              SRFI-14 Creating Character Sets.
* char-set->list:                        SRFI-14 Querying Character Sets.
* char-set->string:                      SRFI-14 Querying Character Sets.
* char-set-adjoin:                       SRFI-14 Character-Set Algebra.
* char-set-adjoin!:                      SRFI-14 Character-Set Algebra.
* char-set-any:                          SRFI-14 Querying Character Sets.
* char-set-complement:                   SRFI-14 Character-Set Algebra.
* char-set-complement!:                  SRFI-14 Character-Set Algebra.
* char-set-contains?:                    SRFI-14 Querying Character Sets.
* char-set-copy:                         SRFI-14 Creating Character Sets.
* char-set-count:                        SRFI-14 Querying Character Sets.
* char-set-cursor:                       SRFI-14 Iterating Over Character Sets.
* char-set-cursor-next:                  SRFI-14 Iterating Over Character Sets.
* char-set-delete:                       SRFI-14 Character-Set Algebra.
* char-set-delete!:                      SRFI-14 Character-Set Algebra.
* char-set-diff+intersection:            SRFI-14 Character-Set Algebra.
* char-set-diff+intersection!:           SRFI-14 Character-Set Algebra.
* char-set-difference:                   SRFI-14 Character-Set Algebra.
* char-set-difference!:                  SRFI-14 Character-Set Algebra.
* char-set-every:                        SRFI-14 Querying Character Sets.
* char-set-filter:                       SRFI-14 Creating Character Sets.
* char-set-filter!:                      SRFI-14 Creating Character Sets.
* char-set-fold:                         SRFI-14 Iterating Over Character Sets.
* char-set-for-each:                     SRFI-14 Iterating Over Character Sets.
* char-set-hash:                         SRFI-14 Predicates/Comparison.
* char-set-intersection:                 SRFI-14 Character-Set Algebra.
* char-set-intersection!:                SRFI-14 Character-Set Algebra.
* char-set-map:                          SRFI-14 Iterating Over Character Sets.
* char-set-ref:                          SRFI-14 Iterating Over Character Sets.
* char-set-size:                         SRFI-14 Querying Character Sets.
* char-set-unfold:                       SRFI-14 Iterating Over Character Sets.
* char-set-unfold!:                      SRFI-14 Iterating Over Character Sets.
* char-set-union:                        SRFI-14 Character-Set Algebra.
* char-set-union!:                       SRFI-14 Character-Set Algebra.
* char-set-xor:                          SRFI-14 Character-Set Algebra.
* char-set-xor!:                         SRFI-14 Character-Set Algebra.
* char-set<=:                            SRFI-14 Predicates/Comparison.
* char-set=:                             SRFI-14 Predicates/Comparison.
* char-set?:                             SRFI-14 Predicates/Comparison.
* char-upcase:                           Characters.
* char-upper-case?:                      Characters.
* char-whitespace?:                      Characters.
* char<=?:                               Characters.
* char<?:                                Characters.
* char=?:                                Characters.
* char>=?:                               Characters.
* char>?:                                Characters.
* char?:                                 Characters.
* chdir:                                 Processes.
* chmod:                                 File System.
* chown:                                 File System.
* chroot:                                Processes.
* circular-list:                         SRFI-1 Constructors.
* circular-list?:                        SRFI-1 Predicates.
* close:                                 Ports and File Descriptors.
* close-all-ports-except:                Close All Ports.
* close-fdes:                            Ports and File Descriptors.
* close-input-port:                      Closing.
* close-output-port:                     Closing.
* close-pipe:                            Pipes.
* close-port:                            Closing.
* closedir:                              File System.
* closure?:                              Procedure Properties.
* command-line <1>:                      The Top of a Script File.
* command-line:                          Runtime Environment.
* compiled-regexp?:                      Rx Regexps.
* complex?:                              Complex Numbers.
* concatenate:                           SRFI-1 Length Append etc.
* concatenate!:                          SRFI-1 Length Append etc.
* cond:                                  if cond case.
* connect:                               Network Sockets and Communication.
* cons:                                  Pairs.
* cons*:                                 List Constructors.
* cons-source:                           Internal Macros.
* copy-file:                             File System.
* copy-random-state:                     Random.
* copy-tree:                             Copying.
* cos:                                   Scientific.
* cosh:                                  Scientific.
* crypt:                                 Encryption.
* ctermid:                               Terminals and Ptys.
* current-error-port:                    Default Ports.
* current-input-port:                    Default Ports.
* current-load-port:                     Loading.
* current-output-port:                   Default Ports.
* current-time:                          Time.
* cuserid:                               User Information.
* debug-disable:                         User level options interfaces.
* debug-enable:                          User level options interfaces.
* debug-object?:                         Using Traps.
* debug-options:                         User level options interfaces.
* debug-options-interface:               Low level options interfaces.
* debug-set!:                            User level options interfaces.
* define:                                Top Level.
* define*:                               define* Reference.
* define*-public:                        define* Reference.
* define-macro:                          Macros.
* define-module:                         Creating Guile Modules.
* define-public:                         Creating Guile Modules.
* define-reader-ctor:                    SRFI-10.
* defined?:                              Binding Reflection.
* defmacro:                              Macros.
* defmacro*:                             define* Reference.
* defmacro*-public:                      define* Reference.
* delete <1>:                            List Modification.
* delete:                                SRFI-1 Deleting.
* delete! <1>:                           List Modification.
* delete!:                               SRFI-1 Deleting.
* delete-duplicates:                     SRFI-1 Deleting.
* delete-duplicates!:                    SRFI-1 Deleting.
* delete-file:                           File System.
* delete1!:                              List Modification.
* delq:                                  List Modification.
* delq!:                                 List Modification.
* delq1!:                                List Modification.
* delv:                                  List Modification.
* delv!:                                 List Modification.
* delv1!:                                List Modification.
* destroy-guardian!:                     Guardians.
* dfa-continuable?:                      Rx Regexps.
* dfa-final-tag:                         Rx Regexps.
* dfa-fork:                              Rx Regexps.
* dimensions->uniform-array:             Uniform Arrays.
* directory-stream?:                     File System.
* dirname:                               File System.
* display:                               Writing.
* display-application:                   Examining Stack Frames.
* display-backtrace:                     Examining the Stack.
* display-error:                         Handling Errors.
* do:                                    while do.
* dotted-list?:                          SRFI-1 Predicates.
* doubly-weak-hash-table?:               Weak key hashes.
* drain-input:                           Reading.
* drop:                                  SRFI-1 Selectors.
* drop-right:                            SRFI-1 Selectors.
* drop-right!:                           SRFI-1 Selectors.
* drop-while:                            SRFI-1 Searching.
* dup:                                   Ports and File Descriptors.
* dup->fdes:                             Ports and File Descriptors.
* dup->inport:                           Ports and File Descriptors.
* dup->outport:                          Ports and File Descriptors.
* dup->port:                             Ports and File Descriptors.
* dup2:                                  Ports and File Descriptors.
* duplicate-port:                        Ports and File Descriptors.
* dynamic-args-call:                     Low level dynamic linking.
* dynamic-call:                          Low level dynamic linking.
* dynamic-func:                          Low level dynamic linking.
* dynamic-link:                          Low level dynamic linking.
* dynamic-object?:                       Low level dynamic linking.
* dynamic-root:                          Dynamic Roots.
* dynamic-unlink:                        Low level dynamic linking.
* dynamic-wind:                          Dynamic Wind.
* effective-version:                     Build Config.
* eighth:                                SRFI-1 Selectors.
* enclose-array:                         Conventional Arrays.
* end-of-char-set?:                      SRFI-14 Iterating Over Character Sets.
* endgrent:                              User Information.
* endhostent:                            Network Databases.
* endnetent:                             Network Databases.
* endprotoent:                           Network Databases.
* endpwent:                              User Information.
* endservent:                            Network Databases.
* entity?:                               Objects.
* environ:                               Runtime Environment.
* eof-object?:                           Reading.
* eq?:                                   Equality.
* equal?:                                Equality.
* eqv?:                                  Equality.
* error <1>:                             Handling Errors.
* error:                                 Error Reporting.
* eval:                                  Fly Evaluation.
* eval-disable:                          Evaluator Behaviour.
* eval-enable:                           Evaluator Behaviour.
* eval-options:                          Evaluator Behaviour.
* eval-options-interface <1>:            Low level options interfaces.
* eval-options-interface:                Evaluator Behaviour.
* eval-set!:                             Evaluator Behaviour.
* eval-string:                           Fly Evaluation.
* eval2:                                 Strange Eval.
* evaluator-traps-interface <1>:         Low level options interfaces.
* evaluator-traps-interface:             Evaluator Behaviour.
* even?:                                 Integer Operations.
* every:                                 SRFI-1 Searching.
* exact->inexact:                        Exactness.
* exact?:                                Exactness.
* execl:                                 Processes.
* execle:                                Processes.
* execlp:                                Processes.
* exp:                                   Scientific.
* expect:                                Expect.
* expect-strings:                        Expect.
* export:                                Creating Guile Modules.
* expt:                                  Scientific.
* false-if-exception:                    Error Reporting.
* fchmod:                                File System.
* fchown:                                File System.
* fcntl:                                 Ports and File Descriptors.
* fdes->inport:                          Ports and File Descriptors.
* fdes->outport:                         Ports and File Descriptors.
* fdes->ports:                           Ports and File Descriptors.
* fdopen:                                Ports and File Descriptors.
* feature?:                              Feature Manipulation.
* fflush:                                Writing.
* fifth:                                 SRFI-1 Selectors.
* file-port?:                            File Ports.
* fileno:                                Ports and File Descriptors.
* filter:                                SRFI-1 Filtering and Partitioning.
* filter!:                               SRFI-1 Filtering and Partitioning.
* filter-map:                            SRFI-1 Fold and Map.
* find:                                  SRFI-1 Searching.
* find-tail:                             SRFI-1 Searching.
* first:                                 SRFI-1 Selectors.
* flock:                                 Ports and File Descriptors.
* floor:                                 Arithmetic.
* fluid-ref:                             Fluids.
* fluid-set!:                            Fluids.
* fluid?:                                Fluids.
* flush-all-ports:                       Writing.
* fn:                                    Defining new Scheme procedures in C.
* fold:                                  SRFI-1 Fold and Map.
* fold-right:                            SRFI-1 Fold and Map.
* for-each <1>:                          List Mapping.
* for-each:                              SRFI-1 Fold and Map.
* force:                                 Delayed Evaluation.
* force-output:                          Writing.
* format:                                Formatted Output.
* fourth:                                SRFI-1 Selectors.
* frame-arguments:                       Examining Stack Frames.
* frame-evaluating-args?:                Examining Stack Frames.
* frame-next:                            Examining Stack Frames.
* frame-number:                          Examining Stack Frames.
* frame-overflow?:                       Examining Stack Frames.
* frame-previous:                        Examining Stack Frames.
* frame-procedure:                       Examining Stack Frames.
* frame-procedure?:                      Examining Stack Frames.
* frame-real?:                           Examining Stack Frames.
* frame-source:                          Examining Stack Frames.
* frame?:                                Examining Stack Frames.
* fstat:                                 File System.
* fsync:                                 Ports and File Descriptors.
* ftell:                                 Random Access.
* ftruncate:                             Random Access.
* gc:                                    Garbage Collection.
* gc-stats:                              Garbage Collection.
* gcd:                                   Integer Operations.
* gensym:                                Symbol Primitives.
* gentemp:                               Obarray Symbols.
* get-internal-real-time:                Time.
* get-internal-run-time:                 Time.
* get-output-string:                     String Ports.
* get-print-state:                       Writing.
* getcwd:                                Processes.
* getegid:                               Processes.
* getenv:                                Runtime Environment.
* geteuid:                               Processes.
* getgid:                                Processes.
* getgr:                                 User Information.
* getgrent:                              User Information.
* getgrgid:                              User Information.
* getgrnam:                              User Information.
* getgroups:                             Processes.
* gethost:                               Network Databases.
* gethostbyaddr:                         Network Databases.
* gethostbyname:                         Network Databases.
* gethostent:                            Network Databases.
* gethostname:                           System Identification.
* getitimer:                             Signals.
* getlogin:                              User Information.
* getnet:                                Network Databases.
* getnetbyaddr:                          Network Databases.
* getnetbyname:                          Network Databases.
* getnetent:                             Network Databases.
* getopt-long:                           getopt-long Reference.
* getpass:                               Encryption.
* getpeername:                           Network Sockets and Communication.
* getpgrp:                               Processes.
* getpid:                                Processes.
* getppid:                               Processes.
* getpriority:                           Processes.
* getproto:                              Network Databases.
* getprotobyname:                        Network Databases.
* getprotobynumber:                      Network Databases.
* getprotoent:                           Network Databases.
* getpw:                                 User Information.
* getpwent:                              User Information.
* getpwnam:                              User Information.
* getpwuid:                              User Information.
* getserv:                               Network Databases.
* getservbyname:                         Network Databases.
* getservbyport:                         Network Databases.
* getservent:                            Network Databases.
* getsockname:                           Network Sockets and Communication.
* getsockopt:                            Network Sockets and Communication.
* gettimeofday:                          Time.
* getuid:                                Processes.
* GH_ALLOW_INTS:                         Defining new Scheme procedures in C.
* gh_append:                             Calling Scheme procedures from C.
* gh_append2:                            Calling Scheme procedures from C.
* gh_append3:                            Calling Scheme procedures from C.
* gh_append4:                            Calling Scheme procedures from C.
* gh_apply:                              Calling Scheme procedures from C.
* gh_assoc:                              Calling Scheme procedures from C.
* gh_assq:                               Calling Scheme procedures from C.
* gh_assv:                               Calling Scheme procedures from C.
* gh_bool2scm:                           C to Scheme.
* gh_boolean_p:                          Type predicates.
* gh_c:                                  Calling Scheme procedures from C.
* gh_call0:                              Calling Scheme procedures from C.
* gh_call1:                              Calling Scheme procedures from C.
* gh_call2:                              Calling Scheme procedures from C.
* gh_call3:                              Calling Scheme procedures from C.
* gh_car:                                Calling Scheme procedures from C.
* gh_catch:                              Calling Scheme procedures from C.
* gh_cdr:                                Calling Scheme procedures from C.
* gh_char2scm:                           C to Scheme.
* gh_char_p:                             Type predicates.
* gh_chars2byvect:                       C to Scheme.
* gh_cons:                               Calling Scheme procedures from C.
* GH_DEFER_INTS:                         Defining new Scheme procedures in C.
* gh_define:                             Calling Scheme procedures from C.
* gh_double2scm:                         C to Scheme.
* gh_doubles2dvect:                      C to Scheme.
* gh_doubles2scm:                        C to Scheme.
* gh_enter:                              Starting and controlling the interpreter.
* gh_eq_p:                               Equality predicates.
* gh_equal_p:                            Equality predicates.
* gh_eqv_p:                              Equality predicates.
* gh_eval_file:                          Executing Scheme code.
* gh_eval_str:                           Executing Scheme code.
* gh_exact_p:                            Type predicates.
* gh_floats2fvect:                       C to Scheme.
* gh_get_substr:                         Scheme to C.
* gh_inexact_p:                          Type predicates.
* gh_ints2scm:                           C to Scheme.
* gh_is_eq:                              Calling Scheme procedures from C.
* gh_is_equal:                           Calling Scheme procedures from C.
* gh_is_eqv:                             Calling Scheme procedures from C.
* gh_length:                             Calling Scheme procedures from C.
* gh_list:                               Calling Scheme procedures from C.
* gh_list_p:                             Type predicates.
* gh_list_ref:                           Calling Scheme procedures from C.
* gh_list_tail:                          Calling Scheme procedures from C.
* gh_list_to_vector:                     Calling Scheme procedures from C.
* gh_load:                               Executing Scheme code.
* gh_long2scm:                           C to Scheme.
* gh_longs2ivect:                        C to Scheme.
* gh_make_vector:                        Calling Scheme procedures from C.
* gh_member:                             Calling Scheme procedures from C.
* gh_memq:                               Calling Scheme procedures from C.
* gh_memv:                               Calling Scheme procedures from C.
* gh_new_procedure:                      Defining new Scheme procedures in C.
* gh_null_p:                             Equality predicates.
* gh_obj_length:                         Calling Scheme procedures from C.
* gh_pair_p:                             Type predicates.
* gh_procedure_p:                        Type predicates.
* gh_repl:                               Starting and controlling the interpreter.
* gh_reverse:                            Calling Scheme procedures from C.
* gh_scm2bool:                           Scheme to C.
* gh_scm2char:                           Scheme to C.
* gh_scm2double:                         Scheme to C.
* gh_scm2long:                           Scheme to C.
* gh_scm2ulong:                          Scheme to C.
* gh_set_car_x:                          Calling Scheme procedures from C.
* gh_set_cdr_x:                          Calling Scheme procedures from C.
* gh_set_substr:                         C to Scheme.
* gh_shorts2svect:                       C to Scheme.
* gh_str02scm:                           C to Scheme.
* gh_str2scm:                            C to Scheme.
* gh_string_equal_p:                     Equality predicates.
* gh_symbol2scm:                         C to Scheme.
* gh_symbol_p:                           Type predicates.
* gh_throw:                              Calling Scheme procedures from C.
* gh_ulong2scm:                          C to Scheme.
* gh_ulongs2uvect:                       C to Scheme.
* gh_vector:                             Calling Scheme procedures from C.
* gh_vector_length:                      Calling Scheme procedures from C.
* gh_vector_p:                           Type predicates.
* gh_vector_ref:                         Calling Scheme procedures from C.
* gh_vector_set:                         Calling Scheme procedures from C.
* gmtime:                                Time.
* guardian-destroyed?:                   Guardians.
* guardian-greedy?:                      Guardians.
* GUILE_CHECK_RETVAL:                    Autoconf Macros.
* GUILE_FLAGS:                           Autoconf Macros.
* GUILE_MODULE_AVAILABLE:                Autoconf Macros.
* GUILE_MODULE_CHECK:                    Autoconf Macros.
* GUILE_MODULE_EXPORTS:                  Autoconf Macros.
* GUILE_MODULE_REQUIRED:                 Autoconf Macros.
* GUILE_MODULE_REQUIRED_EXPORT:          Autoconf Macros.
* GUILE_PROGS:                           Autoconf Macros.
* GUILE_SITE_DIR:                        Autoconf Macros.
* hash:                                  Hash Table Reference.
* hash-create-handle!:                   Hash Table Reference.
* hash-fold:                             Hash Table Reference.
* hash-get-handle:                       Hash Table Reference.
* hash-ref:                              Hash Table Reference.
* hash-remove!:                          Hash Table Reference.
* hash-set!:                             Hash Table Reference.
* hashq:                                 Hash Table Reference.
* hashq-create-handle!:                  Hash Table Reference.
* hashq-get-handle:                      Hash Table Reference.
* hashq-ref:                             Hash Table Reference.
* hashq-remove!:                         Hash Table Reference.
* hashq-set!:                            Hash Table Reference.
* hashv:                                 Hash Table Reference.
* hashv-create-handle!:                  Hash Table Reference.
* hashv-get-handle:                      Hash Table Reference.
* hashv-ref:                             Hash Table Reference.
* hashv-remove!:                         Hash Table Reference.
* hashv-set!:                            Hash Table Reference.
* hashx-create-handle!:                  Hash Table Reference.
* hashx-get-handle:                      Hash Table Reference.
* hashx-ref:                             Hash Table Reference.
* hashx-set!:                            Hash Table Reference.
* hook->list:                            Hook Reference.
* hook-empty?:                           Hook Reference.
* hook?:                                 Hook Reference.
* hostent:addr-list:                     Network Databases.
* hostent:addrtype:                      Network Databases.
* hostent:aliases:                       Network Databases.
* hostent:length:                        Network Databases.
* hostent:name:                          Network Databases.
* htonl:                                 Network Sockets and Communication.
* htons:                                 Network Sockets and Communication.
* if:                                    if cond case.
* imag-part:                             Complex.
* inet-aton:                             Network Address Conversion.
* inet-lnaof:                            Network Address Conversion.
* inet-makeaddr:                         Network Address Conversion.
* inet-netof:                            Network Address Conversion.
* inet-ntoa:                             Network Address Conversion.
* inet-ntop:                             Network Address Conversion.
* inet-pton:                             Network Address Conversion.
* inexact->exact:                        Exactness.
* inexact?:                              Exactness.
* input-port?:                           Ports.
* integer->char:                         Characters.
* integer-expt:                          Bitwise Operations.
* integer-length:                        Bitwise Operations.
* integer?:                              Integers.
* interaction-environment:               Fly Evaluation.
* intern-symbol:                         Obarray Symbols.
* iota:                                  SRFI-1 Constructors.
* isatty?:                               Terminals and Ptys.
* join-thread:                           Low level thread primitives.
* key:                                   Evaluator trap options.
* keyword->symbol:                       Keyword Procedures.
* keyword-dash-symbol:                   Keyword Primitives.
* keyword?:                              Keyword Primitives.
* kill:                                  Signals.
* lambda:                                Lambda.
* lambda*:                               lambda* Reference.
* last:                                  SRFI-1 Selectors.
* last-pair:                             List Selection.
* last-stack-frame:                      Capturing the Stack or Innermost Stack Frame.
* lazy-catch:                            Lazy Catch.
* lchown:                                File System.
* lcm:                                   Integer Operations.
* length:                                List Selection.
* length+:                               SRFI-1 Length Append etc.
* let <1>:                               while do.
* let:                                   Local Bindings.
* let*:                                  Local Bindings.
* let-keywords:                          let-keywords Reference.
* let-optional:                          let-optional Reference.
* let-optional*:                         let-optional Reference.
* letrec:                                Local Bindings.
* link:                                  File System.
* list:                                  List Constructors.
* list->char-set:                        SRFI-14 Creating Character Sets.
* list->char-set!:                       SRFI-14 Creating Character Sets.
* list->string:                          String Constructors.
* list->TAGvector:                       SRFI-4 - Procedures.
* list->uniform-array:                   Uniform Arrays.
* list->uniform-vector:                  Uniform Arrays.
* list->vector:                          Vector Creation.
* list->weak-vector:                     Weak vectors.
* list-cdr-ref:                          List Selection.
* list-cdr-set!:                         List Modification.
* list-copy:                             List Constructors.
* list-head:                             List Selection.
* list-index:                            SRFI-1 Searching.
* list-ref:                              List Selection.
* list-set!:                             List Modification.
* list-tabulate:                         SRFI-1 Constructors.
* list-tail:                             List Selection.
* list=:                                 SRFI-1 Predicates.
* list?:                                 List Predicates.
* listen:                                Network Sockets and Communication.
* load:                                  Loading.
* load-from-path:                        Loading.
* local-eval:                            Local Evaluation.
* localtime:                             Time.
* lock-mutex:                            Low level thread primitives.
* log:                                   Scientific.
* log10:                                 Scientific.
* logand:                                Bitwise Operations.
* logbit?:                               Bitwise Operations.
* logcount:                              Bitwise Operations.
* logior:                                Bitwise Operations.
* lognot:                                Bitwise Operations.
* logtest:                               Bitwise Operations.
* logxor:                                Bitwise Operations.
* lset-adjoin:                           SRFI-1 Set Operations.
* lset-adjoin!:                          SRFI-1 Set Operations.
* lset-diff+intersection:                SRFI-1 Set Operations.
* lset-diff+intersection!:               SRFI-1 Set Operations.
* lset-difference:                       SRFI-1 Set Operations.
* lset-difference!:                      SRFI-1 Set Operations.
* lset-intersection:                     SRFI-1 Set Operations.
* lset-intersection!:                    SRFI-1 Set Operations.
* lset-union:                            SRFI-1 Set Operations.
* lset-union!:                           SRFI-1 Set Operations.
* lset-xor:                              SRFI-1 Set Operations.
* lset-xor!:                             SRFI-1 Set Operations.
* lset<=:                                SRFI-1 Set Operations.
* lset=:                                 SRFI-1 Set Operations.
* lstat:                                 File System.
* macro-name:                            Internal Macros.
* macro-transformer:                     Internal Macros.
* macro-type:                            Internal Macros.
* macro?:                                Internal Macros.
* magnitude:                             Complex.
* main_prog:                             Starting and controlling the interpreter.
* major-version:                         Build Config.
* make-arbiter:                          Arbiters.
* make-array:                            Conventional Arrays.
* make-class-object:                     Objects.
* make-condition-variable:               Low level thread primitives.
* make-doubly-weak-hash-table:           Weak key hashes.
* make-fluid:                            Fluids.
* make-guardian:                         Guardians.
* make-hash-table:                       Hash Table Reference.
* make-hook:                             Hook Reference.
* make-keyword-from-dash-symbol:         Keyword Primitives.
* make-list:                             List Constructors.
* make-mutex:                            Low level thread primitives.
* make-object-property:                  Object Properties.
* make-polar:                            Complex.
* make-procedure-with-setter:            Procedures with Setters.
* make-record-type:                      Records.
* make-rectangular:                      Complex.
* make-regexp:                           Regexp Functions.
* make-shared-array:                     Conventional Arrays.
* make-shared-substring:                 Shared Substrings.
* make-soft-port:                        Soft Ports.
* make-stack:                            Capturing the Stack or Innermost Stack Frame.
* make-string:                           String Constructors.
* make-struct:                           Structure Basics.
* make-struct-layout:                    Structure Layout.
* make-subclass-object:                  Objects.
* make-TAGvector:                        SRFI-4 - Procedures.
* make-thread:                           Higher level thread procedures.
* make-undefined-variable:               Variables.
* make-uniform-array:                    Uniform Arrays.
* make-uniform-vector:                   Uniform Arrays.
* make-variable:                         Variables.
* make-vector:                           Vector Creation.
* make-vtable-vtable:                    Vtables.
* make-weak-key-hash-table:              Weak key hashes.
* make-weak-value-hash-table:            Weak key hashes.
* make-weak-vector:                      Weak vectors.
* malloc-stats:                          Garbage Collection.
* map <1>:                               List Mapping.
* map:                                   SRFI-1 Fold and Map.
* map!:                                  SRFI-1 Fold and Map.
* map-in-order:                          List Mapping.
* mask-signals:                          Asyncs.
* match:count:                           Match Structures.
* match:end:                             Match Structures.
* match:prefix:                          Match Structures.
* match:start:                           Match Structures.
* match:string:                          Match Structures.
* match:substring:                       Match Structures.
* match:suffix:                          Match Structures.
* max:                                   Arithmetic.
* member <1>:                            List Searching.
* member:                                SRFI-1 Searching.
* memoized-environment:                  Decoding Memoized Source Expressions.
* memoized?:                             Decoding Memoized Source Expressions.
* memq:                                  List Searching.
* memv:                                  List Searching.
* merge:                                 Sorting.
* merge!:                                Sorting.
* micro-version:                         Build Config.
* min:                                   Arithmetic.
* minor-version:                         Build Config.
* mkdir:                                 File System.
* mknod:                                 File System.
* mkstemp!:                              File System.
* mktime:                                Time.
* modulo:                                Integer Operations.
* monitor:                               Higher level thread procedures.
* move->fdes:                            Ports and File Descriptors.
* negative?:                             Comparison.
* netent:addrtype:                       Network Databases.
* netent:aliases:                        Network Databases.
* netent:name:                           Network Databases.
* netent:net:                            Network Databases.
* newline:                               Writing.
* nice:                                  Processes.
* nil-car:                               Emacs Lisp Support.
* nil-cdr:                               Emacs Lisp Support.
* nil-cons:                              Emacs Lisp Support.
* nil-eq:                                Emacs Lisp Support.
* ninth:                                 SRFI-1 Selectors.
* noop:                                  Asyncs.
* not:                                   Booleans.
* not-pair?:                             SRFI-1 Predicates.
* ntohl:                                 Network Sockets and Communication.
* ntohs:                                 Network Sockets and Communication.
* null:                                  Emacs Lisp Support.
* null-environment:                      Environments.
* null-list?:                            SRFI-1 Predicates.
* null?:                                 List Predicates.
* number->string:                        Conversion.
* number?:                               Numerical Tower.
* object->string:                        General Conversion.
* object-address:                        Garbage Collection.
* object-properties:                     Old-fashioned Properties.
* object-property:                       Old-fashioned Properties.
* odd?:                                  Integer Operations.
* open:                                  Ports and File Descriptors.
* open-fdes:                             Ports and File Descriptors.
* open-file:                             File Ports.
* open-input-file:                       File Ports.
* open-input-pipe:                       Pipes.
* open-input-string:                     String Ports.
* open-output-file:                      File Ports.
* open-output-pipe:                      Pipes.
* open-output-string:                    String Ports.
* open-pipe:                             Pipes.
* opendir:                               File System.
* operator?:                             Objects.
* option-ref:                            option-ref Reference.
* or:                                    and or.
* output-port?:                          Ports.
* pair-fold:                             SRFI-1 Fold and Map.
* pair-fold-right:                       SRFI-1 Fold and Map.
* pair-for-each:                         SRFI-1 Fold and Map.
* pair?:                                 Pairs.
* parse-path:                            Build Config.
* partition:                             SRFI-1 Filtering and Partitioning.
* partition!:                            SRFI-1 Filtering and Partitioning.
* pause:                                 Signals.
* pclose:                                Pipes.
* peek-char:                             Reading.
* pipe:                                  Ports and File Descriptors.
* popen:                                 Pipes.
* port->fdes:                            Ports and File Descriptors.
* port-closed?:                          Closing.
* port-column:                           Reading.
* port-filename:                         File Ports.
* port-for-each:                         Ports and File Descriptors.
* port-line:                             Reading.
* port-mode <1>:                         File Ports.
* port-mode:                             Ports and File Descriptors.
* port-revealed:                         Ports and File Descriptors.
* port-with-print-state:                 Writing.
* port?:                                 Ports.
* positive?:                             Comparison.
* pretty-print:                          Pretty Printing.
* primitive-eval:                        Fly Evaluation.
* primitive-exit:                        Processes.
* primitive-fork:                        Processes.
* primitive-load:                        Loading.
* primitive-load-path:                   Loading.
* primitive-make-property:               Property Primitives.
* primitive-move->fdes:                  Ports and File Descriptors.
* primitive-property-del!:               Property Primitives.
* primitive-property-ref:                Property Primitives.
* primitive-property-set!:               Property Primitives.
* print-disable:                         User level options interfaces.
* print-enable:                          User level options interfaces.
* print-options:                         User level options interfaces.
* print-options-interface <1>:           Low level options interfaces.
* print-options-interface:               Writing.
* print-set!:                            User level options interfaces.
* procedure:                             Procedures with Setters.
* procedure->macro:                      Internal Macros.
* procedure->memoizing-macro:            Internal Macros.
* procedure->syntax:                     Internal Macros.
* procedure-documentation:               Procedure Properties.
* procedure-environment:                 Procedure Properties.
* procedure-name:                        Procedure Properties.
* procedure-properties:                  Procedure Properties.
* procedure-property:                    Procedure Properties.
* procedure-source:                      Procedure Properties.
* procedure-with-setter?:                Procedures with Setters.
* procedure?:                            Procedure Properties.
* program-arguments <1>:                 The Top of a Script File.
* program-arguments:                     Runtime Environment.
* promise?:                              Delayed Evaluation.
* proper-list?:                          SRFI-1 Predicates.
* protoent:aliases:                      Network Databases.
* protoent:name:                         Network Databases.
* protoent:proto:                        Network Databases.
* provide:                               Feature Manipulation.
* provided?:                             Feature Manipulation.
* PTR2SCM:                               Non-immediate objects.
* putenv:                                Runtime Environment.
* pwd:                                   Processes.
* quit:                                  Dynamic Roots.
* quotient:                              Integer Operations.
* raise:                                 Signals.
* random:                                Random.
* random:exp:                            Random.
* random:hollow-sphere!:                 Random.
* random:normal:                         Random.
* random:normal-vector!:                 Random.
* random:solid-sphere!:                  Random.
* random:uniform:                        Random.
* rational?:                             Reals and Rationals.
* read:                                  Scheme Read.
* read-and-eval!:                        Strange Eval.
* read-char:                             Reading.
* read-delimited:                        Line/Delimited.
* read-delimited!:                       Line/Delimited.
* read-disable <1>:                      User level options interfaces.
* read-disable:                          Scheme Read.
* read-enable <1>:                       User level options interfaces.
* read-enable:                           Scheme Read.
* read-hash-extend:                      Reader Extensions.
* read-line:                             Line/Delimited.
* read-line!:                            Line/Delimited.
* read-only-string?:                     Read Only Strings.
* read-options <1>:                      Scheme Read.
* read-options:                          User level options interfaces.
* read-options-interface <1>:            Scheme Read.
* read-options-interface:                Low level options interfaces.
* read-set! <1>:                         Scheme Read.
* read-set!:                             User level options interfaces.
* read-string!/partial:                  Block Reading and Writing.
* readdir:                               File System.
* readlink:                              File System.
* real-part:                             Complex.
* real?:                                 Reals and Rationals.
* receive:                               Multiple Values.
* record-accessor:                       Records.
* record-constructor:                    Records.
* record-modifier:                       Records.
* record-predicate:                      Records.
* record-type-descriptor:                Records.
* record-type-fields:                    Records.
* record-type-name:                      Records.
* record?:                               Records.
* recv!:                                 Network Sockets and Communication.
* recvfrom!:                             Network Sockets and Communication.
* redirect-port:                         Ports and File Descriptors.
* reduce:                                SRFI-1 Fold and Map.
* reduce-right:                          SRFI-1 Fold and Map.
* regcomp:                               Rx Regexps.
* regexec:                               Rx Regexps.
* regexp->dfa:                           Rx Regexps.
* regexp-exec:                           Regexp Functions.
* regexp-match?:                         Match Structures.
* regexp-quote:                          Backslash Escapes.
* regexp-substitute:                     Regexp Functions.
* regexp-substitute/global:              Regexp Functions.
* regexp?:                               Regexp Functions.
* release-arbiter:                       Arbiters.
* release-port-handle:                   Ports and File Descriptors.
* remainder:                             Integer Operations.
* remove:                                SRFI-1 Filtering and Partitioning.
* remove!:                               SRFI-1 Filtering and Partitioning.
* remove-hook!:                          Hook Reference.
* rename:                                File System.
* rename-file:                           File System.
* reset-dfa!:                            Rx Regexps.
* reset-hook!:                           Hook Reference.
* restore-signals:                       Signals.
* restricted-vector-sort!:               Sorting.
* reverse:                               Append/Reverse.
* reverse!:                              Append/Reverse.
* reverse-list->string:                  SRFI-13 List/String Conversion.
* rewinddir:                             File System.
* rmdir:                                 File System.
* round:                                 Arithmetic.
* run-asyncs:                            Asyncs.
* run-hook:                              Hook Reference.
* scheme-report-environment:             Environments.
* scm-error <1>:                         Error Reporting.
* scm-error:                             Handling Errors.
* SCM2PTR:                               Non-immediate objects.
* scm_abs:                               Arithmetic.
* scm_accept:                            Network Sockets and Communication.
* scm_access:                            File System.
* scm_acons:                             Adding or Setting Alist Entries.
* scm_acosh:                             Primitive Numerics.
* scm_add_feature:                       Feature Manipulation.
* scm_add_hook_x:                        Hook Reference.
* scm_alarm:                             Signals.
* scm_append:                            Append/Reverse.
* scm_append_x:                          Append/Reverse.
* SCM_ARG1:                              Signalling Type Errors.
* SCM_ARG2:                              Signalling Type Errors.
* SCM_ARG3:                              Signalling Type Errors.
* SCM_ARG4:                              Signalling Type Errors.
* SCM_ARG5:                              Signalling Type Errors.
* SCM_ARG6:                              Signalling Type Errors.
* SCM_ARG7:                              Signalling Type Errors.
* SCM_ARGn:                              Signalling Type Errors.
* scm_array_contents:                    Conventional Arrays.
* scm_array_copy_x:                      Conventional Arrays.
* scm_array_dimensions:                  Conventional Arrays.
* scm_array_fill_x:                      Conventional Arrays.
* scm_array_for_each:                    Array Mapping.
* scm_array_in_bounds_p:                 Conventional Arrays.
* scm_array_index_map_x:                 Array Mapping.
* scm_array_map_x:                       Array Mapping.
* scm_array_p:                           Conventional Arrays.
* scm_array_prototype:                   Uniform Arrays.
* scm_array_rank:                        Conventional Arrays.
* scm_array_set_x:                       Conventional Arrays.
* scm_array_to_list:                     Conventional Arrays.
* scm_ash:                               Bitwise Operations.
* scm_asinh:                             Primitive Numerics.
* SCM_ASSERT:                            Signalling Type Errors.
* scm_assoc:                             Retrieving Alist Entries.
* scm_assoc_ref:                         Retrieving Alist Entries.
* scm_assoc_remove_x:                    Removing Alist Entries.
* scm_assoc_set_x:                       Adding or Setting Alist Entries.
* scm_assq:                              Retrieving Alist Entries.
* scm_assq_ref:                          Retrieving Alist Entries.
* scm_assq_remove_x:                     Removing Alist Entries.
* scm_assq_set_x:                        Adding or Setting Alist Entries.
* scm_assv:                              Retrieving Alist Entries.
* scm_assv_ref:                          Retrieving Alist Entries.
* scm_assv_remove_x:                     Removing Alist Entries.
* scm_assv_set_x:                        Adding or Setting Alist Entries.
* scm_async:                             Asyncs.
* scm_async_mark:                        Asyncs.
* scm_atanh:                             Primitive Numerics.
* scm_backtrace:                         Backtrace.
* scm_basename:                          File System.
* scm_bind:                              Network Sockets and Communication.
* scm_bit_count:                         Bit Vectors.
* scm_bit_count_star:                    Bit Vectors.
* scm_bit_extract:                       Bitwise Operations.
* scm_bit_invert_x:                      Bit Vectors.
* scm_bit_position:                      Bit Vectors.
* scm_bit_set_star_x:                    Bit Vectors.
* SCM_BOOL_F:                            Boolean Data.
* SCM_BOOL_NOT:                          Boolean Data.
* SCM_BOOL_T:                            Boolean Data.
* scm_boolean_p:                         Booleans.
* scm_boot_guile:                        Guile Initialization Functions.
* scm_builtin_bindings:                  Obarray Symbols.
* scm_c_call_with_current_module:        Accessing Modules from C.
* scm_c_define <1>:                      Top Level.
* scm_c_define:                          Accessing Modules from C.
* scm_c_define_gsubr:                    Subrs.
* scm_c_define_module:                   Accessing Modules from C.
* scm_c_export:                          Accessing Modules from C.
* scm_c_hook_add:                        C Hooks.
* scm_c_hook_init:                       C Hooks.
* scm_c_hook_remove:                     C Hooks.
* scm_c_lookup:                          Accessing Modules from C.
* scm_c_module_define:                   Accessing Modules from C.
* scm_c_module_lookup:                   Accessing Modules from C.
* scm_c_resolve_module:                  Accessing Modules from C.
* scm_c_run_hook:                        Hook Reference.
* scm_c_use_module:                      Accessing Modules from C.
* SCM_CAAR:                              Pair Data.
* SCM_CADR:                              Pair Data.
* scm_call_with_dynamic_root:            Dynamic Roots.
* scm_call_with_input_string:            String Ports.
* scm_call_with_output_string:           String Ports.
* SCM_CAR:                               Pair Data.
* scm_catch:                             Catch.
* SCM_CDAR:                              Pair Data.
* SCM_CDDDDR:                            Pair Data.
* SCM_CDR:                               Pair Data.
* SCM_CELL_OBJECT:                       Accessing Cell Entries.
* SCM_CELL_TYPE:                         Heap Cell Type Information.
* SCM_CELL_WORD:                         Accessing Cell Entries.
* SCM_CHAR:                              Character Data.
* scm_char_alphabetic_p:                 Characters.
* scm_char_downcase:                     Characters.
* scm_char_is_both_p:                    Characters.
* scm_char_lower_case_p:                 Characters.
* scm_char_numeric_p:                    Characters.
* scm_char_p:                            Characters.
* scm_char_ready_p:                      Reading.
* scm_char_to_integer:                   Characters.
* scm_char_upcase:                       Characters.
* scm_char_upper_case_p:                 Characters.
* scm_char_whitespace_p:                 Characters.
* SCM_CHARP:                             Character Data.
* scm_chdir:                             Processes.
* scm_chmod:                             File System.
* scm_chown:                             File System.
* scm_chroot:                            Processes.
* scm_close:                             Ports and File Descriptors.
* scm_close_all_ports_except:            Close All Ports.
* scm_close_fdes:                        Ports and File Descriptors.
* scm_close_input_port:                  Closing.
* scm_close_output_port:                 Closing.
* scm_close_port:                        Closing.
* scm_closedir:                          File System.
* scm_closure_p:                         Procedure Properties.
* SCM_CLOSUREP:                          Closures.
* SCM_CODE:                              Closures.
* scm_connect:                           Network Sockets and Communication.
* scm_cons <1>:                          Pairs.
* scm_cons:                              Pair Data.
* scm_cons_source:                       Internal Macros.
* scm_cons_star:                         List Constructors.
* SCM_CONSP <1>:                         Basic Rules for Accessing Cell Entries.
* SCM_CONSP:                             Pair Data.
* scm_copy_file:                         File System.
* scm_copy_random_state:                 Random.
* scm_copy_tree:                         Copying.
* scm_crypt:                             Encryption.
* scm_ctermid:                           Terminals and Ptys.
* scm_current_error_port:                Default Ports.
* scm_current_input_port:                Default Ports.
* scm_current_load_port:                 Loading.
* scm_current_module:                    Accessing Modules from C.
* scm_current_output_port:               Default Ports.
* scm_current_time:                      Time.
* scm_cuserid:                           User Information.
* scm_debug_object_p:                    Using Traps.
* scm_debug_options:                     Low level options interfaces.
* scm_define <1>:                        Accessing Modules from C.
* scm_define:                            Top Level.
* scm_definedp:                          Binding Reflection.
* scm_delete:                            List Modification.
* scm_delete1_x:                         List Modification.
* scm_delete_file:                       File System.
* scm_delete_x:                          List Modification.
* scm_delq:                              List Modification.
* scm_delq1_x:                           List Modification.
* scm_delq_x:                            List Modification.
* scm_delv:                              List Modification.
* scm_delv1_x:                           List Modification.
* scm_delv_x:                            List Modification.
* scm_destroy_guardian_x:                Guardians.
* scm_dimensions_to_uniform_array:       Uniform Arrays.
* scm_directory_stream_p:                File System.
* scm_dirname:                           File System.
* scm_display_application:               Examining Stack Frames.
* scm_display_backtrace:                 Examining the Stack.
* scm_display_error:                     Handling Errors.
* scm_doubly_weak_hash_table_p:          Weak key hashes.
* scm_drain_input:                       Reading.
* scm_dup2:                              Ports and File Descriptors.
* scm_dup_to_fdes:                       Ports and File Descriptors.
* scm_dynamic_args_call:                 Low level dynamic linking.
* scm_dynamic_call:                      Low level dynamic linking.
* scm_dynamic_func:                      Low level dynamic linking.
* scm_dynamic_link:                      Low level dynamic linking.
* scm_dynamic_object_p:                  Low level dynamic linking.
* scm_dynamic_root:                      Dynamic Roots.
* scm_dynamic_unlink:                    Low level dynamic linking.
* scm_dynamic_wind:                      Dynamic Wind.
* scm_effective_version:                 Build Config.
* scm_enclose_array:                     Conventional Arrays.
* scm_entity_p:                          Objects.
* SCM_ENV:                               Closures.
* scm_environ:                           Runtime Environment.
* scm_eof_object_p:                      Reading.
* SCM_EOF_VAL:                           Unique Values.
* SCM_EOL:                               Unique Values.
* scm_error_scm:                         Error Reporting.
* scm_eval:                              Fly Evaluation.
* scm_eval2:                             Strange Eval.
* scm_eval_options_interface <1>:        Evaluator Behaviour.
* scm_eval_options_interface:            Low level options interfaces.
* scm_eval_string:                       Fly Evaluation.
* scm_evaluator_traps <1>:               Evaluator Behaviour.
* scm_evaluator_traps:                   Low level options interfaces.
* scm_even_p:                            Integer Operations.
* scm_exact_p:                           Exactness.
* scm_execl:                             Processes.
* scm_execle:                            Processes.
* scm_execlp:                            Processes.
* scm_fcntl:                             Ports and File Descriptors.
* scm_fdes_to_ports:                     Ports and File Descriptors.
* scm_fdopen:                            Ports and File Descriptors.
* scm_file_port_p:                       File Ports.
* scm_fileno:                            Ports and File Descriptors.
* scm_flock:                             Ports and File Descriptors.
* scm_fluid_p:                           Fluids.
* scm_fluid_ref:                         Fluids.
* scm_fluid_set_x:                       Fluids.
* scm_flush_all_ports:                   Writing.
* scm_force:                             Delayed Evaluation.
* scm_force_output:                      Writing.
* scm_fork:                              Processes.
* scm_frame_arguments:                   Examining Stack Frames.
* scm_frame_evaluating_args_p:           Examining Stack Frames.
* scm_frame_next:                        Examining Stack Frames.
* scm_frame_number:                      Examining Stack Frames.
* scm_frame_overflow_p:                  Examining Stack Frames.
* scm_frame_p:                           Examining Stack Frames.
* scm_frame_previous:                    Examining Stack Frames.
* scm_frame_procedure:                   Examining Stack Frames.
* scm_frame_procedure_p:                 Examining Stack Frames.
* scm_frame_real_p:                      Examining Stack Frames.
* scm_frame_source:                      Examining Stack Frames.
* scm_free0:                             Garbage Collecting Simple Smobs.
* scm_fsync:                             Ports and File Descriptors.
* scm_ftell:                             Random Access.
* scm_gc:                                Garbage Collection.
* scm_gc_mark:                           Garbage Collecting Smobs.
* scm_gc_stats:                          Garbage Collection.
* scm_gensym:                            Symbol Primitives.
* scm_gentemp:                           Obarray Symbols.
* scm_get_internal_real_time:            Time.
* scm_get_internal_run_time:             Time.
* scm_get_output_string:                 String Ports.
* scm_get_print_state:                   Writing.
* scm_getcwd:                            Processes.
* scm_getegid:                           Processes.
* scm_getenv:                            Runtime Environment.
* scm_geteuid:                           Processes.
* scm_getgid:                            Processes.
* scm_getgrgid:                          User Information.
* scm_getgroups:                         Processes.
* scm_gethost:                           Network Databases.
* scm_gethostname:                       System Identification.
* scm_getitimer:                         Signals.
* scm_getlogin:                          User Information.
* scm_getnet:                            Network Databases.
* scm_getpass:                           Encryption.
* scm_getpeername:                       Network Sockets and Communication.
* scm_getpgrp:                           Processes.
* scm_getpid:                            Processes.
* scm_getppid:                           Processes.
* scm_getpriority:                       Processes.
* scm_getproto:                          Network Databases.
* scm_getpwuid:                          User Information.
* scm_getserv:                           Network Databases.
* scm_getsockname:                       Network Sockets and Communication.
* scm_getsockopt:                        Network Sockets and Communication.
* scm_gettimeofday:                      Time.
* scm_getuid:                            Processes.
* scm_gmtime:                            Time.
* scm_guardian_destroyed_p:              Guardians.
* scm_guardian_greedy_p:                 Guardians.
* scm_hash:                              Hash Table Reference.
* scm_hash_create_handle_x:              Hash Table Reference.
* scm_hash_fold:                         Hash Table Reference.
* scm_hash_get_handle:                   Hash Table Reference.
* scm_hash_ref:                          Hash Table Reference.
* scm_hash_remove_x:                     Hash Table Reference.
* scm_hash_set_x:                        Hash Table Reference.
* scm_hashq:                             Hash Table Reference.
* scm_hashq_create_handle_x:             Hash Table Reference.
* scm_hashq_get_handle:                  Hash Table Reference.
* scm_hashq_ref:                         Hash Table Reference.
* scm_hashq_remove_x:                    Hash Table Reference.
* scm_hashq_set_x:                       Hash Table Reference.
* scm_hashv:                             Hash Table Reference.
* scm_hashv_create_handle_x:             Hash Table Reference.
* scm_hashv_get_handle:                  Hash Table Reference.
* scm_hashv_ref:                         Hash Table Reference.
* scm_hashv_remove_x:                    Hash Table Reference.
* scm_hashv_set_x:                       Hash Table Reference.
* scm_hashx_create_handle_x:             Hash Table Reference.
* scm_hashx_get_handle:                  Hash Table Reference.
* scm_hashx_ref:                         Hash Table Reference.
* scm_hashx_set_x:                       Hash Table Reference.
* scm_hook_empty_p:                      Hook Reference.
* scm_hook_p:                            Hook Reference.
* scm_hook_to_list:                      Hook Reference.
* SCM_HOOKP:                             Hook Reference.
* scm_htonl:                             Network Sockets and Communication.
* scm_htons:                             Network Sockets and Communication.
* SCM_IMP <1>:                           Immediate objects.
* SCM_IMP:                               Immediates vs Non-immediates.
* scm_inet_aton:                         Network Address Conversion.
* scm_inet_makeaddr:                     Network Address Conversion.
* scm_inet_netof:                        Network Address Conversion.
* scm_inet_ntoa:                         Network Address Conversion.
* scm_inet_ntop:                         Network Address Conversion.
* scm_inet_pton:                         Network Address Conversion.
* scm_inexact_p:                         Exactness.
* scm_inexact_to_exact:                  Exactness.
* scm_init_guile:                        Guile Initialization Functions.
* scm_input_port_p:                      Ports.
* scm_integer_expt:                      Bitwise Operations.
* scm_integer_length:                    Bitwise Operations.
* scm_integer_p:                         Integers.
* scm_integer_to_char:                   Characters.
* scm_interaction_environment:           Fly Evaluation.
* scm_intern_symbol:                     Obarray Symbols.
* SCM_INUM:                              Integer Data.
* SCM_INUMP:                             Integer Data.
* scm_isatty_p:                          Terminals and Ptys.
* scm_keyword_dash_symbol:               Keyword Primitives.
* scm_keyword_p:                         Keyword Primitives.
* scm_kill:                              Signals.
* scm_last_pair:                         List Selection.
* scm_last_stack_frame:                  Capturing the Stack or Innermost Stack Frame.
* scm_lazy_catch:                        Lazy Catch.
* scm_length:                            List Selection.
* scm_link:                              File System.
* scm_list:                              List Constructors.
* scm_list_cdr_set_x:                    List Modification.
* scm_list_copy:                         List Constructors.
* scm_list_head:                         List Selection.
* scm_list_p:                            List Predicates.
* scm_list_ref:                          List Selection.
* scm_list_set_x:                        List Modification.
* scm_list_tail:                         List Selection.
* scm_list_to_uniform_array:             Uniform Arrays.
* scm_listen:                            Network Sockets and Communication.
* scm_lnaof:                             Network Address Conversion.
* scm_local_eval:                        Local Evaluation.
* scm_localtime:                         Time.
* scm_logbit_p:                          Bitwise Operations.
* scm_logcount:                          Bitwise Operations.
* scm_lognot:                            Bitwise Operations.
* scm_logtest:                           Bitwise Operations.
* scm_lookup:                            Accessing Modules from C.
* scm_lstat:                             File System.
* scm_macro_name:                        Internal Macros.
* scm_macro_p:                           Internal Macros.
* scm_macro_transformer:                 Internal Macros.
* scm_macro_type:                        Internal Macros.
* scm_major_version:                     Build Config.
* scm_makacro:                           Internal Macros.
* scm_make_arbiter:                      Arbiters.
* SCM_MAKE_CHAR:                         Character Data.
* scm_make_class_object:                 Objects.
* scm_make_doubly_weak_hash_table:       Weak key hashes.
* scm_make_fluid:                        Fluids.
* scm_make_guardian:                     Guardians.
* scm_make_hook:                         Hook Reference.
* scm_make_keyword_from_dash_symbol:     Keyword Primitives.
* scm_make_polar:                        Complex.
* scm_make_procedure_with_setter:        Procedures with Setters.
* scm_make_rectangular:                  Complex.
* scm_make_regexp:                       Regexp Functions.
* scm_make_shared_array:                 Conventional Arrays.
* scm_make_shared_substring:             Shared Substrings.
* scm_make_smob_type:                    Describing a New Type.
* scm_make_smob_type_mfpe:               Describing a New Type.
* scm_make_soft_port:                    Soft Ports.
* scm_make_stack:                        Capturing the Stack or Innermost Stack Frame.
* scm_make_string:                       String Constructors.
* scm_make_struct:                       Structure Basics.
* scm_make_struct_layout:                Structure Layout.
* scm_make_subclass_object:              Objects.
* scm_make_undefined_variable:           Variables.
* scm_make_variable:                     Variables.
* scm_make_vector:                       Vector Creation.
* scm_make_vtable_vtable:                Vtables.
* scm_make_weak_key_hash_table:          Weak key hashes.
* scm_make_weak_value_hash_table:        Weak key hashes.
* scm_make_weak_vector:                  Weak vectors.
* SCM_MAKINUM:                           Integer Data.
* scm_makmacro:                          Internal Macros.
* scm_makmmacro:                         Internal Macros.
* scm_map:                               List Mapping.
* scm_markcdr:                           Garbage Collecting Simple Smobs.
* scm_mask_signals:                      Asyncs.
* scm_member:                            List Searching.
* scm_memoized_environment:              Decoding Memoized Source Expressions.
* scm_memoized_p:                        Decoding Memoized Source Expressions.
* scm_memq:                              List Searching.
* scm_memv:                              List Searching.
* scm_merge:                             Sorting.
* scm_merge_x:                           Sorting.
* scm_micro_version:                     Build Config.
* scm_minor_version:                     Build Config.
* scm_mkdir:                             File System.
* scm_mknod:                             File System.
* scm_mkstemp:                           File System.
* scm_mktime:                            Time.
* scm_module_define:                     Accessing Modules from C.
* scm_module_lookup:                     Accessing Modules from C.
* scm_module_reverse_lookup:             Accessing Modules from C.
* scm_must_free:                         Creating Instances.
* scm_must_malloc:                       Creating Instances.
* scm_must_realloc:                      Creating Instances.
* scm_nconc2last:                        Fly Evaluation.
* SCM_NCONSP:                            Pair Data.
* SCM_NEWCELL:                           Pair Data.
* scm_newline:                           Writing.
* SCM_NEWSMOB:                           Creating Instances.
* SCM_NEWSMOB2:                          Creating Instances.
* SCM_NEWSMOB3:                          Creating Instances.
* SCM_NFALSEP:                           Boolean Data.
* scm_nice:                              Processes.
* scm_nil_car:                           Emacs Lisp Support.
* scm_nil_cdr:                           Emacs Lisp Support.
* scm_nil_cons:                          Emacs Lisp Support.
* SCM_NIMP:                              Immediates vs Non-immediates.
* SCM_NINUMP:                            Integer Data.
* scm_noop:                              Asyncs.
* scm_not:                               Booleans.
* scm_ntohl:                             Network Sockets and Communication.
* scm_ntohs:                             Network Sockets and Communication.
* scm_null:                              Emacs Lisp Support.
* scm_null_p:                            List Predicates.
* scm_number_p <1>:                      Complex Numbers.
* scm_number_p:                          Numerical Tower.
* scm_number_to_string:                  Conversion.
* scm_object_address:                    Garbage Collection.
* scm_object_properties:                 Old-fashioned Properties.
* scm_object_property:                   Old-fashioned Properties.
* scm_object_to_string:                  General Conversion.
* scm_odd_p:                             Integer Operations.
* scm_open:                              Ports and File Descriptors.
* scm_open_fdes:                         Ports and File Descriptors.
* scm_open_file:                         File Ports.
* scm_open_input_string:                 String Ports.
* scm_open_output_string:                String Ports.
* scm_opendir:                           File System.
* scm_operator_p:                        Objects.
* scm_output_port_p:                     Ports.
* SCM_PACK:                              Relationship between SCM and scm_t_bits.
* scm_pair_p:                            Pairs.
* scm_parse_path:                        Build Config.
* scm_pause:                             Signals.
* scm_peek_char:                         Reading.
* scm_pipe:                              Ports and File Descriptors.
* scm_port_closed_p:                     Closing.
* scm_port_column:                       Reading.
* scm_port_filename:                     File Ports.
* scm_port_for_each:                     Ports and File Descriptors.
* scm_port_line:                         Reading.
* scm_port_mode:                         File Ports.
* scm_port_p:                            Ports.
* scm_port_revealed:                     Ports and File Descriptors.
* scm_port_with_print_state:             Writing.
* scm_primitive_eval:                    Fly Evaluation.
* scm_primitive_exit:                    Processes.
* scm_primitive_load:                    Loading.
* scm_primitive_load_path:               Loading.
* scm_primitive_make_property:           Property Primitives.
* scm_primitive_move_to_fdes:            Ports and File Descriptors.
* scm_primitive_property_del_x:          Property Primitives.
* scm_primitive_property_ref:            Property Primitives.
* scm_primitive_property_set_x:          Property Primitives.
* scm_print_options <1>:                 Writing.
* scm_print_options:                     Low level options interfaces.
* scm_procedure:                         Procedures with Setters.
* scm_procedure_documentation:           Procedure Properties.
* scm_procedure_environment:             Procedure Properties.
* scm_procedure_name:                    Procedure Properties.
* scm_procedure_p <1>:                   Procedure Properties.
* scm_procedure_p:                       Procedures.
* scm_procedure_properties:              Procedure Properties.
* scm_procedure_property:                Procedure Properties.
* scm_procedure_source:                  Procedure Properties.
* scm_procedure_with_setter_p:           Procedures with Setters.
* SCM_PROCPROPS:                         Closures.
* scm_program_arguments:                 Runtime Environment.
* scm_promise_p:                         Delayed Evaluation.
* scm_putenv:                            Runtime Environment.
* scm_raise:                             Signals.
* scm_random:                            Random.
* scm_random_exp:                        Random.
* scm_random_hollow_sphere_x:            Random.
* scm_random_normal:                     Random.
* scm_random_normal_vector_x:            Random.
* scm_random_solid_sphere_x:             Random.
* scm_random_uniform:                    Random.
* scm_read:                              Scheme Read.
* scm_read_and_eval_x:                   Strange Eval.
* scm_read_char:                         Reading.
* scm_read_delimited_x:                  Line/Delimited.
* scm_read_hash_extend:                  Reader Extensions.
* scm_read_line:                         Line/Delimited.
* scm_read_only_string_p:                Read Only Strings.
* scm_read_options <1>:                  Low level options interfaces.
* scm_read_options:                      Scheme Read.
* scm_read_string_x_partial:             Block Reading and Writing.
* scm_readdir:                           File System.
* scm_readlink:                          File System.
* scm_real_p:                            Reals and Rationals.
* scm_recv:                              Network Sockets and Communication.
* scm_recvfrom:                          Network Sockets and Communication.
* scm_redirect_port:                     Ports and File Descriptors.
* scm_regexp_exec:                       Regexp Functions.
* scm_regexp_p:                          Regexp Functions.
* scm_release_arbiter:                   Arbiters.
* scm_remove_hook_x:                     Hook Reference.
* scm_rename:                            File System.
* scm_reset_hook_x:                      Hook Reference.
* scm_resolve_module:                    Accessing Modules from C.
* scm_restore_signals:                   Signals.
* scm_restricted_vector_sort_x:          Sorting.
* SCM_RETURN_NEWSMOB:                    Creating Instances.
* SCM_RETURN_NEWSMOB2:                   Creating Instances.
* SCM_RETURN_NEWSMOB3:                   Creating Instances.
* scm_reverse:                           Append/Reverse.
* scm_reverse_x:                         Append/Reverse.
* scm_rewinddir:                         File System.
* scm_rmdir:                             File System.
* scm_round:                             Arithmetic.
* scm_run_asyncs:                        Asyncs.
* scm_run_hook:                          Hook Reference.
* scm_search_path:                       Build Config.
* scm_seed_to_random_state:              Random.
* scm_seek:                              Random Access.
* scm_select:                            Ports and File Descriptors.
* scm_send:                              Network Sockets and Communication.
* scm_sendto:                            Network Sockets and Communication.
* scm_set_car_x:                         Pairs.
* scm_set_cdr_x:                         Pairs.
* SCM_SET_CELL_OBJECT:                   Accessing Cell Entries.
* SCM_SET_CELL_TYPE:                     Heap Cell Type Information.
* SCM_SET_CELL_WORD:                     Accessing Cell Entries.
* scm_set_current_error_port:            Default Ports.
* scm_set_current_input_port:            Default Ports.
* scm_set_current_module:                Accessing Modules from C.
* scm_set_current_output_port:           Default Ports.
* scm_set_object_procedure_x:            Objects.
* scm_set_object_properties_x:           Old-fashioned Properties.
* scm_set_object_property_x:             Old-fashioned Properties.
* scm_set_port_column_x:                 Reading.
* scm_set_port_filename_x:               File Ports.
* scm_set_port_line_x:                   Reading.
* scm_set_port_revealed_x:               Ports and File Descriptors.
* scm_set_procedure_properties_x:        Procedure Properties.
* scm_set_procedure_property_x:          Procedure Properties.
* scm_set_smob_equalp:                   Describing a New Type.
* scm_set_smob_free:                     Describing a New Type.
* scm_set_smob_mark:                     Describing a New Type.
* scm_set_smob_print:                    Describing a New Type.
* scm_set_source_properties_x:           Procedure Properties.
* scm_set_source_property_x:             Procedure Properties.
* scm_set_struct_vtable_name_x:          Vtables.
* SCM_SETCAR:                            Pair Data.
* SCM_SETCDR:                            Pair Data.
* scm_setegid:                           Processes.
* scm_seteuid:                           Processes.
* scm_setgid:                            Processes.
* scm_setgrent:                          User Information.
* scm_sethost:                           Network Databases.
* scm_sethostname:                       System Identification.
* scm_setitimer:                         Signals.
* scm_setlocale:                         Locales.
* scm_setnet:                            Network Databases.
* scm_setpgid:                           Processes.
* scm_setpriority:                       Processes.
* SCM_SETPROCPROPS:                      Closures.
* scm_setproto:                          Network Databases.
* scm_setpwent:                          User Information.
* scm_setserv:                           Network Databases.
* scm_setsid:                            Processes.
* scm_setsockopt:                        Network Sockets and Communication.
* scm_setuid:                            Processes.
* scm_setvbuf:                           Ports and File Descriptors.
* scm_shared_array_increments:           Conventional Arrays.
* scm_shared_array_offset:               Conventional Arrays.
* scm_shared_array_root:                 Conventional Arrays.
* scm_shell:                             Guile Initialization Functions.
* scm_shutdown:                          Network Sockets and Communication.
* scm_sigaction:                         Signals.
* scm_simple_format:                     Writing.
* scm_sleep:                             Signals.
* scm_sloppy_assoc:                      Sloppy Alist Functions.
* scm_sloppy_assq:                       Sloppy Alist Functions.
* scm_sloppy_assv:                       Sloppy Alist Functions.
* scm_sloppy_member:                     Sloppy Membership.
* scm_sloppy_memq:                       Sloppy Membership.
* scm_sloppy_memv:                       Sloppy Membership.
* SCM_SNAME:                             Subrs.
* SCM_SNARF_INIT:                        Writing your own snarfing macros.
* scm_socket:                            Network Sockets and Communication.
* scm_socketpair:                        Network Sockets and Communication.
* scm_sort:                              Sorting.
* scm_sort_list:                         Sorting.
* scm_sort_list_x:                       Sorting.
* scm_sort_x:                            Sorting.
* scm_sorted_p:                          Sorting.
* scm_source_properties:                 Procedure Properties.
* scm_source_property:                   Procedure Properties.
* scm_stable_sort:                       Sorting.
* scm_stable_sort_x:                     Sorting.
* scm_stack_id:                          Examining the Stack.
* scm_stack_length:                      Examining the Stack.
* scm_stack_p:                           Examining the Stack.
* scm_stack_ref:                         Examining the Stack.
* scm_stat:                              File System.
* scm_status_exit_val:                   Processes.
* scm_status_stop_sig:                   Processes.
* scm_status_term_sig:                   Processes.
* scm_strerror:                          Error Reporting.
* scm_strftime:                          Time.
* scm_string:                            String Constructors.
* scm_string_append:                     Appending Strings.
* scm_string_capitalize:                 Alphabetic Case Mapping.
* scm_string_capitalize_x:               Alphabetic Case Mapping.
* SCM_STRING_CHARS:                      Vector Data.
* scm_string_ci_to_symbol:               Symbol Primitives.
* scm_string_copy:                       String Selection.
* scm_string_downcase:                   Alphabetic Case Mapping.
* scm_string_downcase_x:                 Alphabetic Case Mapping.
* scm_string_fill_x:                     String Modification.
* scm_string_index:                      String Searching.
* scm_string_length:                     String Selection.
* SCM_STRING_LENGTH:                     Vector Data.
* scm_string_null_p:                     String Predicates.
* scm_string_p:                          String Predicates.
* scm_string_ref:                        String Selection.
* scm_string_rindex:                     String Searching.
* scm_string_set_x:                      String Modification.
* scm_string_split:                      List/String Conversion.
* scm_string_to_list:                    List/String Conversion.
* scm_string_to_number:                  Conversion.
* scm_string_to_obarray_symbol:          Obarray Symbols.
* scm_string_to_symbol:                  Symbol Primitives.
* scm_string_upcase:                     Alphabetic Case Mapping.
* scm_string_upcase_x:                   Alphabetic Case Mapping.
* SCM_STRINGP:                           Vector Data.
* scm_strptime:                          Time.
* scm_struct_p:                          Structure Basics.
* scm_struct_ref:                        Structure Basics.
* scm_struct_set_x:                      Structure Basics.
* scm_struct_vtable:                     Vtables.
* scm_struct_vtable_name:                Vtables.
* scm_struct_vtable_p:                   Vtables.
* scm_struct_vtable_tag:                 Vtables.
* scm_substring:                         String Selection.
* scm_substring_fill_x:                  String Modification.
* scm_substring_move_x:                  String Modification.
* scm_symbol_binding:                    Obarray Symbols.
* scm_symbol_bound_p:                    Obarray Symbols.
* SCM_SYMBOL_CHARS:                      Vector Data.
* scm_symbol_fref:                       Symbol Props.
* scm_symbol_fset_x:                     Symbol Props.
* scm_symbol_hash:                       Symbol Keys.
* scm_symbol_interned_p:                 Obarray Symbols.
* SCM_SYMBOL_LENGTH:                     Vector Data.
* scm_symbol_p:                          Symbol Primitives.
* scm_symbol_pref:                       Symbol Props.
* scm_symbol_pset_x:                     Symbol Props.
* scm_symbol_set_x:                      Obarray Symbols.
* scm_symbol_to_string:                  Symbol Primitives.
* SCM_SYMBOLP:                           Vector Data.
* scm_symlink:                           File System.
* scm_sync:                              File System.
* scm_sys_atan2:                         Primitive Numerics.
* scm_sys_expt:                          Primitive Numerics.
* scm_sys_library_dir:                   Build Config.
* scm_sys_make_void_port:                Void Ports.
* scm_sys_package_data_dir:              Build Config.
* scm_sys_search_load_path:              Loading.
* scm_sys_site_dir:                      Build Config.
* scm_system:                            Processes.
* scm_system_async:                      Asyncs.
* scm_system_async_mark:                 Asyncs.
* scm_tcgetpgrp:                         Terminals and Ptys.
* scm_tcsetpgrp:                         Terminals and Ptys.
* scm_throw:                             Throw.
* scm_thunk_p:                           Procedure Properties.
* scm_times:                             Time.
* scm_tmpnam:                            File System.
* scm_transpose_array:                   Conventional Arrays.
* scm_truncate:                          Arithmetic.
* scm_truncate_file:                     Random Access.
* scm_try_arbiter:                       Arbiters.
* scm_ttyname:                           Terminals and Ptys.
* scm_tzset:                             Time.
* scm_umask:                             Processes.
* scm_uname:                             System Identification.
* SCM_UNBNDP:                            Unique Values.
* SCM_UNDEFINED:                         Unique Values.
* scm_uniform_array_read_x:              Uniform Arrays.
* scm_uniform_array_write:               Uniform Arrays.
* scm_uniform_vector_length:             Uniform Arrays.
* scm_uniform_vector_ref:                Conventional Arrays.
* scm_unintern_symbol:                   Obarray Symbols.
* scm_unmask_signals:                    Asyncs.
* scm_unmemoize:                         Decoding Memoized Source Expressions.
* SCM_UNPACK:                            Relationship between SCM and scm_t_bits.
* scm_unread_char <1>:                   Ports and File Descriptors.
* scm_unread_char:                       Reading.
* scm_unread_string:                     Reading.
* SCM_UNSPECIFIED:                       Unique Values.
* scm_usleep:                            Signals.
* scm_utime:                             File System.
* scm_values:                            Multiple Values.
* scm_variable_bound_p:                  Variables.
* scm_variable_p:                        Variables.
* scm_variable_ref:                      Variables.
* scm_variable_set_x:                    Variables.
* scm_vector:                            Vector Creation.
* SCM_VECTOR_BASE:                       Vector Data.
* scm_vector_fill_x:                     Vector Accessors.
* SCM_VECTOR_LENGTH:                     Vector Data.
* scm_vector_length:                     Vector Accessors.
* scm_vector_move_left_x:                Vector Accessors.
* scm_vector_move_right_x:               Vector Accessors.
* scm_vector_p:                          Vector Creation.
* scm_vector_ref:                        Vector Accessors.
* scm_vector_set_x:                      Vector Accessors.
* scm_vector_to_list:                    Vector Creation.
* SCM_VECTORP:                           Vector Data.
* scm_version:                           Build Config.
* scm_waitpid:                           Processes.
* scm_weak_key_hash_table_p:             Weak key hashes.
* scm_weak_value_hash_table_p:           Weak key hashes.
* scm_weak_vector:                       Weak vectors.
* scm_weak_vector_p:                     Weak vectors.
* scm_with_fluids:                       Fluids.
* scm_with_traps:                        Using Traps.
* scm_write_char:                        Writing.
* scm_write_line:                        Line/Delimited.
* scm_write_string_partial:              Block Reading and Writing.
* search-path:                           Build Config.
* second:                                SRFI-1 Selectors.
* seed->random-state:                    Random.
* seek:                                  Random Access.
* select:                                Ports and File Descriptors.
* send:                                  Network Sockets and Communication.
* sendto:                                Network Sockets and Communication.
* servent:aliases:                       Network Databases.
* servent:name:                          Network Databases.
* servent:port:                          Network Databases.
* servent:proto:                         Network Databases.
* set-batch-mode?!:                      Dynamic Roots.
* set-car!:                              Pairs.
* set-cdr!:                              Pairs.
* set-current-error-port:                Default Ports.
* set-current-input-port:                Default Ports.
* set-current-output-port:               Default Ports.
* set-object-procedure!:                 Objects.
* set-object-properties!:                Old-fashioned Properties.
* set-object-property!:                  Old-fashioned Properties.
* set-port-column!:                      Reading.
* set-port-filename!:                    File Ports.
* set-port-line!:                        Reading.
* set-port-revealed!:                    Ports and File Descriptors.
* set-procedure-properties!:             Procedure Properties.
* set-procedure-property!:               Procedure Properties.
* set-source-properties!:                Procedure Properties.
* set-source-property!:                  Procedure Properties.
* set-struct-vtable-name!:               Vtables.
* set-symbol-property!:                  Symbol Props.
* setegid:                               Processes.
* setenv:                                Runtime Environment.
* seteuid:                               Processes.
* setgid:                                Processes.
* setgr:                                 User Information.
* setgrent:                              User Information.
* sethost:                               Network Databases.
* sethostent:                            Network Databases.
* sethostname:                           System Identification.
* setitimer:                             Signals.
* setlocale:                             Locales.
* setnet:                                Network Databases.
* setnetent:                             Network Databases.
* setpgid:                               Processes.
* setpriority:                           Processes.
* setproto:                              Network Databases.
* setprotoent:                           Network Databases.
* setpw:                                 User Information.
* setpwent:                              User Information.
* setserv:                               Network Databases.
* setservent:                            Network Databases.
* setsid:                                Processes.
* setsockopt:                            Network Sockets and Communication.
* setter:                                Procedures with Setters.
* setuid:                                Processes.
* setvbuf:                               Ports and File Descriptors.
* seventh:                               SRFI-1 Selectors.
* shared-array-increments:               Conventional Arrays.
* shared-array-offset:                   Conventional Arrays.
* shared-array-root:                     Conventional Arrays.
* shutdown:                              Network Sockets and Communication.
* sigaction:                             Signals.
* signal-condition-variable:             Low level thread primitives.
* simple-format:                         Writing.
* sin:                                   Scientific.
* sinh:                                  Scientific.
* sixth:                                 SRFI-1 Selectors.
* sleep:                                 Signals.
* sloppy-assoc:                          Sloppy Alist Functions.
* sloppy-assq:                           Sloppy Alist Functions.
* sloppy-assv:                           Sloppy Alist Functions.
* sloppy-member:                         Sloppy Membership.
* sloppy-memq:                           Sloppy Membership.
* sloppy-memv:                           Sloppy Membership.
* socket:                                Network Sockets and Communication.
* socketpair:                            Network Sockets and Communication.
* software-type:                         System Identification.
* sort:                                  Sorting.
* sort!:                                 Sorting.
* sort-list:                             Sorting.
* sort-list!:                            Sorting.
* sorted?:                               Sorting.
* source-properties:                     Procedure Properties.
* source-property:                       Procedure Properties.
* span:                                  SRFI-1 Searching.
* span!:                                 SRFI-1 Searching.
* split-at:                              SRFI-1 Selectors.
* split-at!:                             SRFI-1 Selectors.
* sqrt:                                  Scientific.
* stable-sort:                           Sorting.
* stable-sort!:                          Sorting.
* stack-id:                              Examining the Stack.
* stack-length:                          Examining the Stack.
* stack-ref:                             Examining the Stack.
* stack?:                                Examining the Stack.
* start-stack:                           Starting a New Stack.
* stat:                                  File System.
* status:exit-val:                       Processes.
* status:stop-sig:                       Processes.
* status:term-sig:                       Processes.
* strerror:                              Error Reporting.
* strftime:                              Time.
* string:                                String Constructors.
* string->char-set:                      SRFI-14 Creating Character Sets.
* string->char-set!:                     SRFI-14 Creating Character Sets.
* string->list <1>:                      List/String Conversion.
* string->list:                          SRFI-13 List/String Conversion.
* string->number:                        Conversion.
* string->obarray-symbol:                Obarray Symbols.
* string->symbol:                        Symbol Primitives.
* string-any:                            SRFI-13 Predicates.
* string-append:                         Appending Strings.
* string-append/shared:                  SRFI-13 Reverse/Append.
* string-capitalize:                     Alphabetic Case Mapping.
* string-capitalize!:                    Alphabetic Case Mapping.
* string-ci->symbol:                     Symbol Primitives.
* string-ci<:                            SRFI-13 Comparison.
* string-ci<=:                           SRFI-13 Comparison.
* string-ci<=?:                          String Comparison.
* string-ci<>:                           SRFI-13 Comparison.
* string-ci<?:                           String Comparison.
* string-ci=:                            SRFI-13 Comparison.
* string-ci=?:                           String Comparison.
* string-ci>:                            SRFI-13 Comparison.
* string-ci>=:                           SRFI-13 Comparison.
* string-ci>=?:                          String Comparison.
* string-ci>?:                           String Comparison.
* string-compare:                        SRFI-13 Comparison.
* string-compare-ci:                     SRFI-13 Comparison.
* string-concatenate:                    SRFI-13 Reverse/Append.
* string-concatenate-reverse:            SRFI-13 Reverse/Append.
* string-concatenate-reverse/shared:     SRFI-13 Reverse/Append.
* string-concatenate/shared:             SRFI-13 Reverse/Append.
* string-contains:                       SRFI-13 Searching.
* string-contains-ci:                    SRFI-13 Searching.
* string-copy <1>:                       String Selection.
* string-copy:                           SRFI-13 Selection.
* string-copy!:                          SRFI-13 Selection.
* string-count:                          SRFI-13 Searching.
* string-delete:                         SRFI-13 Filtering/Deleting.
* string-downcase <1>:                   Alphabetic Case Mapping.
* string-downcase:                       SRFI-13 Case Mapping.
* string-downcase! <1>:                  SRFI-13 Case Mapping.
* string-downcase!:                      Alphabetic Case Mapping.
* string-drop:                           SRFI-13 Selection.
* string-drop-right:                     SRFI-13 Selection.
* string-every:                          SRFI-13 Predicates.
* string-fill! <1>:                      SRFI-13 Modification.
* string-fill!:                          String Modification.
* string-filter:                         SRFI-13 Filtering/Deleting.
* string-fold:                           SRFI-13 Fold/Unfold/Map.
* string-fold-right:                     SRFI-13 Fold/Unfold/Map.
* string-for-each:                       SRFI-13 Fold/Unfold/Map.
* string-hash:                           SRFI-13 Comparison.
* string-hash-ci:                        SRFI-13 Comparison.
* string-index <1>:                      SRFI-13 Searching.
* string-index:                          String Searching.
* string-index-right:                    SRFI-13 Searching.
* string-join:                           SRFI-13 List/String Conversion.
* string-length:                         String Selection.
* string-map:                            SRFI-13 Fold/Unfold/Map.
* string-map!:                           SRFI-13 Fold/Unfold/Map.
* string-match:                          Regexp Functions.
* string-null?:                          String Predicates.
* string-pad:                            SRFI-13 Selection.
* string-pad-right:                      SRFI-13 Selection.
* string-prefix-ci?:                     SRFI-13 Prefixes/Suffixes.
* string-prefix-length:                  SRFI-13 Prefixes/Suffixes.
* string-prefix-length-ci:               SRFI-13 Prefixes/Suffixes.
* string-prefix?:                        SRFI-13 Prefixes/Suffixes.
* string-ref:                            String Selection.
* string-replace:                        SRFI-13 Miscellaneous.
* string-reverse:                        SRFI-13 Reverse/Append.
* string-reverse!:                       SRFI-13 Reverse/Append.
* string-rindex:                         String Searching.
* string-set!:                           String Modification.
* string-skip:                           SRFI-13 Searching.
* string-skip-right:                     SRFI-13 Searching.
* string-split:                          List/String Conversion.
* string-suffix-ci?:                     SRFI-13 Prefixes/Suffixes.
* string-suffix-length:                  SRFI-13 Prefixes/Suffixes.
* string-suffix-length-ci:               SRFI-13 Prefixes/Suffixes.
* string-suffix?:                        SRFI-13 Prefixes/Suffixes.
* string-tabulate:                       SRFI-13 Constructors.
* string-take:                           SRFI-13 Selection.
* string-take-right:                     SRFI-13 Selection.
* string-titlecase:                      SRFI-13 Case Mapping.
* string-titlecase!:                     SRFI-13 Case Mapping.
* string-tokenize:                       SRFI-13 Miscellaneous.
* string-trim:                           SRFI-13 Selection.
* string-trim-both:                      SRFI-13 Selection.
* string-trim-right:                     SRFI-13 Selection.
* string-unfold:                         SRFI-13 Fold/Unfold/Map.
* string-unfold-right:                   SRFI-13 Fold/Unfold/Map.
* string-upcase <1>:                     Alphabetic Case Mapping.
* string-upcase:                         SRFI-13 Case Mapping.
* string-upcase! <1>:                    SRFI-13 Case Mapping.
* string-upcase!:                        Alphabetic Case Mapping.
* string-xcopy!:                         SRFI-13 Replicate/Rotate.
* string<:                               SRFI-13 Comparison.
* string<=:                              SRFI-13 Comparison.
* string<=?:                             String Comparison.
* string<>:                              SRFI-13 Comparison.
* string<?:                              String Comparison.
* string=:                               SRFI-13 Comparison.
* string=?:                              String Comparison.
* string>:                               SRFI-13 Comparison.
* string>=:                              SRFI-13 Comparison.
* string>=?:                             String Comparison.
* string>?:                              String Comparison.
* string?:                               String Predicates.
* strptime:                              Time.
* struct-ref:                            Structure Basics.
* struct-set!:                           Structure Basics.
* struct-vtable:                         Vtables.
* struct-vtable-name:                    Vtables.
* struct-vtable-tag:                     Vtables.
* struct-vtable?:                        Vtables.
* struct?:                               Structure Basics.
* substring:                             String Selection.
* substring-fill!:                       String Modification.
* substring-move!:                       String Modification.
* substring/shared:                      SRFI-13 Selection.
* symbol->keyword:                       Keyword Procedures.
* symbol->string:                        Symbol Primitives.
* symbol-binding:                        Obarray Symbols.
* symbol-bound?:                         Obarray Symbols.
* symbol-fref:                           Symbol Props.
* symbol-fset!:                          Symbol Props.
* symbol-hash:                           Symbol Keys.
* symbol-interned?:                      Obarray Symbols.
* symbol-pref:                           Symbol Props.
* symbol-prefix-proc:                    Using Guile Modules.
* symbol-property:                       Symbol Props.
* symbol-property-remove!:               Symbol Props.
* symbol-pset!:                          Symbol Props.
* symbol-set!:                           Obarray Symbols.
* symbol?:                               Symbol Primitives.
* symlink:                               File System.
* sync:                                  File System.
* system:                                Processes.
* system-async:                          Asyncs.
* system-async-mark:                     Asyncs.
* TAGvector:                             SRFI-4 - Procedures.
* TAGvector->list:                       SRFI-4 - Procedures.
* TAGvector-length:                      SRFI-4 - Procedures.
* TAGvector-ref:                         SRFI-4 - Procedures.
* TAGvector?:                            SRFI-4 - Procedures.
* take:                                  SRFI-1 Selectors.
* take!:                                 SRFI-1 Selectors.
* take-right:                            SRFI-1 Selectors.
* take-while:                            SRFI-1 Searching.
* take-while!:                           SRFI-1 Searching.
* tan:                                   Scientific.
* tanh:                                  Scientific.
* tcgetpgrp:                             Terminals and Ptys.
* tcsetpgrp:                             Terminals and Ptys.
* tenth:                                 SRFI-1 Selectors.
* third:                                 SRFI-1 Selectors.
* throw:                                 Throw.
* thunk?:                                Procedure Properties.
* times:                                 Time.
* tmpnam:                                File System.
* trace:                                 Trace.
* transpose-array:                       Conventional Arrays.
* trap-disable <1>:                      User level options interfaces.
* trap-disable:                          Evaluator Behaviour.
* trap-enable <1>:                       Evaluator Behaviour.
* trap-enable:                           User level options interfaces.
* trap-set! <1>:                         User level options interfaces.
* trap-set!:                             Evaluator Behaviour.
* traps <1>:                             Evaluator Behaviour.
* traps:                                 User level options interfaces.
* truncate <1>:                          Arithmetic.
* truncate:                              Random Access.
* truncate-file:                         Random Access.
* try-arbiter:                           Arbiters.
* ttyname:                               Terminals and Ptys.
* tzset:                                 Time.
* uce-range->char-set!:                  SRFI-14 Creating Character Sets.
* ucs-range->char-set:                   SRFI-14 Creating Character Sets.
* umask:                                 Processes.
* uname:                                 System Identification.
* unfold:                                SRFI-1 Fold and Map.
* unfold-right:                          SRFI-1 Fold and Map.
* unhash-name:                           Garbage Collection.
* uniform-array-read!:                   Uniform Arrays.
* uniform-array-set1!:                   Conventional Arrays.
* uniform-array-write:                   Uniform Arrays.
* uniform-vector-fill!:                  Uniform Arrays.
* uniform-vector-length:                 Uniform Arrays.
* uniform-vector-read!:                  Uniform Arrays.
* uniform-vector-ref:                    Conventional Arrays.
* uniform-vector-write:                  Uniform Arrays.
* unintern-symbol:                       Obarray Symbols.
* unlink:                                File System.
* unlock-mutex:                          Low level thread primitives.
* unmask-signals:                        Asyncs.
* unmemoize:                             Decoding Memoized Source Expressions.
* unread-char <1>:                       Ports and File Descriptors.
* unread-char:                           Reading.
* unread-string <1>:                     Reading.
* unread-string:                         Ports and File Descriptors.
* untrace:                               Trace.
* unzip1:                                SRFI-1 Length Append etc.
* unzip2:                                SRFI-1 Length Append etc.
* unzip3:                                SRFI-1 Length Append etc.
* unzip4:                                SRFI-1 Length Append etc.
* unzip5:                                SRFI-1 Length Append etc.
* use-modules:                           Using Guile Modules.
* use-syntax:                            Using Guile Modules.
* usleep:                                Signals.
* utime:                                 File System.
* values:                                Multiple Values.
* variable-bound?:                       Variables.
* variable-ref:                          Variables.
* variable-set!:                         Variables.
* variable?:                             Variables.
* vector:                                Vector Creation.
* vector->list:                          Vector Creation.
* vector-fill!:                          Vector Accessors.
* vector-length:                         Vector Accessors.
* vector-move-left!:                     Vector Accessors.
* vector-move-right!:                    Vector Accessors.
* vector-ref:                            Vector Accessors.
* vector-set!:                           Vector Accessors.
* vector?:                               Vector Creation.
* version:                               Build Config.
* wait-condition-variable:               Low level thread primitives.
* waitpid:                               Processes.
* weak-key-hash-table?:                  Weak key hashes.
* weak-value-hash-table?:                Weak key hashes.
* weak-vector:                           Weak vectors.
* weak-vector?:                          Weak vectors.
* while:                                 while do.
* with-error-to-file:                    File Ports.
* with-fluids*:                          Fluids.
* with-input-from-file:                  File Ports.
* with-input-from-string:                String Ports.
* with-mutex:                            Higher level thread procedures.
* with-output-to-file:                   File Ports.
* with-output-to-string:                 String Ports.
* with-traps:                            Using Traps.
* write-char:                            Writing.
* write-line:                            Line/Delimited.
* write-string/partial:                  Block Reading and Writing.
* xcons:                                 SRFI-1 Constructors.
* xsubstring:                            SRFI-13 Replicate/Rotate.
* yield:                                 Low level thread primitives.
* zero?:                                 Comparison.
* zip:                                   SRFI-1 Length Append etc.


File: guile.info,  Node: Variable Index,  Next: Type Index,  Prev: Procedure Index,  Up: Top

Variable Index
**************

   This is an alphabetical list of all the important variables and
constants in Guile.

   When looking for a particular variable or constant, please look under
its Scheme name as well as under its C name.  The C name can be
constructed from the Scheme names by a simple transformation described
in the section *Note Transforming Scheme name to C name::.

* Menu:

* %guile-build-info:                     Build Config.
* %load-extensions:                      Loading.
* %load-hook:                            Loading.
* %load-path:                            Build Config.
* *features*:                            Feature Tracking.
* after-gc-hook:                         GC Hooks.
* char-set:ascii:                        SRFI-14 Standard Character Sets.
* char-set:blank:                        SRFI-14 Standard Character Sets.
* char-set:digit:                        SRFI-14 Standard Character Sets.
* char-set:empty:                        SRFI-14 Standard Character Sets.
* char-set:full:                         SRFI-14 Standard Character Sets.
* char-set:graphic:                      SRFI-14 Standard Character Sets.
* char-set:hex-digit:                    SRFI-14 Standard Character Sets.
* char-set:iso-control:                  SRFI-14 Standard Character Sets.
* char-set:letter:                       SRFI-14 Standard Character Sets.
* char-set:letter+digit:                 SRFI-14 Standard Character Sets.
* char-set:lower-case:                   SRFI-14 Standard Character Sets.
* char-set:printing:                     SRFI-14 Standard Character Sets.
* char-set:punctuation:                  SRFI-14 Standard Character Sets.
* char-set:symbol:                       SRFI-14 Standard Character Sets.
* char-set:title-case:                   SRFI-14 Standard Character Sets.
* char-set:upper-case:                   SRFI-14 Standard Character Sets.
* char-set:whitespace:                   SRFI-14 Standard Character Sets.
* F_OK:                                  File System.
* INADDR_ANY:                            Network Sockets and Communication.
* INADDR_BROADCAST:                      Network Sockets and Communication.
* INADDR_LOOPBACK:                       Network Sockets and Communication.
* INADDR_NONE:                           Network Sockets and Communication.
* internal-time-units-per-second:        Time.
* O_APPEND:                              Ports and File Descriptors.
* O_CREAT:                               Ports and File Descriptors.
* O_RDONLY:                              Ports and File Descriptors.
* O_RDWR:                                Ports and File Descriptors.
* O_WRONLY:                              Ports and File Descriptors.
* R_OK:                                  File System.
* REG_EXTENDED:                          Rx Regexps.
* REG_ICASE:                             Rx Regexps.
* REG_NEWLINE:                           Rx Regexps.
* REG_NOTBOL:                            Rx Regexps.
* REG_NOTEOL:                            Rx Regexps.
* scm_after_gc_c_hook:                   GC Hooks.
* scm_after_gc_hook:                     GC Hooks.
* scm_after_sweep_c_hook:                GC Hooks.
* scm_before_gc_c_hook:                  GC Hooks.
* scm_before_mark_c_hook:                GC Hooks.
* scm_before_sweep_c_hook:               GC Hooks.
* SCM_BOOL_F:                            Data types and constants defined by gh.
* SCM_BOOL_T:                            Data types and constants defined by gh.
* SCM_C_HOOK_AND:                        C Hooks.
* SCM_C_HOOK_NORMAL:                     C Hooks.
* SCM_C_HOOK_OR:                         C Hooks.
* SCM_UNDEFINED:                         Data types and constants defined by gh.
* SCM_UNSPECIFIED:                       Data types and constants defined by gh.
* SEEK_CUR:                              Random Access.
* SEEK_END:                              Random Access.
* SEEK_SET:                              Random Access.
* SIGHUP:                                Signals.
* SIGINT:                                Signals.
* W_OK:                                  File System.
* WNOHANG:                               Processes.
* WUNTRACED:                             Processes.
* X_OK:                                  File System.


File: guile.info,  Node: Type Index,  Next: R5RS Index,  Prev: Variable Index,  Up: Top

Type Index
**********

   This is an alphabetical list of all the important data types defined
in the Guile Programmers Manual.

* Menu:

* Alist:                                 Association Lists.
* Arrays:                                Arrays.
* Association Lists:                     Association Lists.
* Booleans:                              Booleans.
* Characters:                            Characters.
* Complex numbers:                       Complex Numbers.
* Exact numbers:                         Exactness.
* Hash Tables:                           Hash Tables.
* Hooks:                                 Hooks.
* Inexact numbers:                       Exactness.
* Integer numbers:                       Integers.
* Keywords:                              Keywords.
* Lists:                                 Lists.
* Numbers:                               Numbers.
* Pairs:                                 Pairs.
* Rational numbers:                      Reals and Rationals.
* Real numbers:                          Reals and Rationals.
* Regular expressions:                   Regular Expressions.
* SCM:                                   Unpacking the SCM type.
* scm_t_bits:                            Unpacking the SCM type.
* scm_t_c_hook:                          C Hooks.
* scm_t_c_hook_function:                 C Hooks.
* scm_t_c_hook_type:                     C Hooks.
* Strings:                               Strings.
* Structures:                            Structures.
* Symbols:                               Symbols.
* Uniform Arrays:                        Uniform Arrays.
* Variables:                             Variables.
* Vectors:                               Vectors.


File: guile.info,  Node: R5RS Index,  Prev: Type Index,  Up: Top

R5RS Index
**********

* Menu:

* *:                                     Arithmetic.
* +:                                     Arithmetic.
* -:                                     Arithmetic.
* /:                                     Arithmetic.
* abs:                                   Arithmetic.
* acos:                                  Scientific.
* angle:                                 Complex.
* append:                                Append/Reverse.
* apply:                                 Fly Evaluation.
* asin:                                  Scientific.
* assoc:                                 Retrieving Alist Entries.
* assq:                                  Retrieving Alist Entries.
* assv:                                  Retrieving Alist Entries.
* atan:                                  Scientific.
* boolean?:                              Booleans.
* call-with-current-continuation:        Continuations.
* call-with-input-file:                  File Ports.
* call-with-output-file:                 File Ports.
* call-with-values:                      Multiple Values.
* car:                                   Pairs.
* cdr:                                   Pairs.
* ceiling:                               Arithmetic.
* char->integer:                         Characters.
* char-alphabetic?:                      Characters.
* char-ci<=?:                            Characters.
* char-ci<?:                             Characters.
* char-ci=?:                             Characters.
* char-ci>=?:                            Characters.
* char-ci>?:                             Characters.
* char-downcase:                         Characters.
* char-lower-case?:                      Characters.
* char-numeric?:                         Characters.
* char-ready?:                           Reading.
* char-upcase:                           Characters.
* char-upper-case?:                      Characters.
* char-whitespace?:                      Characters.
* char<=?:                               Characters.
* char<?:                                Characters.
* char=?:                                Characters.
* char>=?:                               Characters.
* char>?:                                Characters.
* char?:                                 Characters.
* close-input-port:                      Closing.
* close-output-port:                     Closing.
* complex?:                              Complex Numbers.
* cons:                                  Pairs.
* cos:                                   Scientific.
* current-input-port:                    Default Ports.
* current-output-port:                   Default Ports.
* display:                               Writing.
* dynamic-wind:                          Dynamic Wind.
* eof-object?:                           Reading.
* eq?:                                   Equality.
* equal?:                                Equality.
* eqv?:                                  Equality.
* eval:                                  Fly Evaluation.
* even?:                                 Integer Operations.
* exact->inexact:                        Exactness.
* exact?:                                Exactness.
* exp:                                   Scientific.
* expt:                                  Scientific.
* floor:                                 Arithmetic.
* for-each:                              List Mapping.
* force:                                 Delayed Evaluation.
* gcd:                                   Integer Operations.
* imag-part:                             Complex.
* inexact->exact:                        Exactness.
* inexact?:                              Exactness.
* input-port?:                           Ports.
* integer->char:                         Characters.
* integer?:                              Integers.
* interaction-environment:               Fly Evaluation.
* lcm:                                   Integer Operations.
* length:                                List Selection.
* list:                                  List Constructors.
* list->string:                          String Constructors.
* list->vector:                          Vector Creation.
* list-ref:                              List Selection.
* list-tail:                             List Selection.
* list?:                                 List Predicates.
* load:                                  Loading.
* log:                                   Scientific.
* magnitude:                             Complex.
* make-polar:                            Complex.
* make-rectangular:                      Complex.
* make-string:                           String Constructors.
* make-vector:                           Vector Creation.
* map:                                   List Mapping.
* max:                                   Arithmetic.
* member:                                List Searching.
* memq:                                  List Searching.
* memv:                                  List Searching.
* min:                                   Arithmetic.
* modulo:                                Integer Operations.
* negative?:                             Comparison.
* newline:                               Writing.
* not:                                   Booleans.
* null?:                                 List Predicates.
* number->string:                        Conversion.
* number?:                               Numerical Tower.
* odd?:                                  Integer Operations.
* open-input-file:                       File Ports.
* open-output-file:                      File Ports.
* output-port?:                          Ports.
* pair?:                                 Pairs.
* peek-char?:                            Reading.
* positive?:                             Comparison.
* procedure?:                            Procedure Properties.
* quotient:                              Integer Operations.
* rational?:                             Reals and Rationals.
* read:                                  Scheme Read.
* read-char?:                            Reading.
* real-part:                             Complex.
* real?:                                 Reals and Rationals.
* remainder:                             Integer Operations.
* reverse:                               Append/Reverse.
* round:                                 Arithmetic.
* set-car!:                              Pairs.
* set-cdr!:                              Pairs.
* sin:                                   Scientific.
* sqrt:                                  Scientific.
* string:                                String Constructors.
* string->list:                          List/String Conversion.
* string->number:                        Conversion.
* string->symbol:                        Symbol Primitives.
* string-append:                         Appending Strings.
* string-ci<:                            String Comparison.
* string-ci=?:                           String Comparison.
* string-ci>=?:                          String Comparison.
* string-ci>?:                           String Comparison.
* string-copy:                           String Selection.
* string-fill!:                          String Modification.
* string-length:                         String Selection.
* string-ref:                            String Selection.
* string-set!:                           String Modification.
* string<=?:                             String Comparison.
* string<?:                              String Comparison.
* string=?:                              String Comparison.
* string>=?:                             String Comparison.
* string>?:                              String Comparison.
* string?:                               String Predicates.
* substring:                             String Selection.
* symbol->string:                        Symbol Primitives.
* symbol?:                               Symbol Primitives.
* tan:                                   Scientific.
* truncate:                              Arithmetic.
* values:                                Multiple Values.
* vector:                                Vector Creation.
* vector->list:                          Vector Creation.
* vector-fill!:                          Vector Accessors.
* vector-length:                         Vector Accessors.
* vector-ref:                            Vector Accessors.
* vector-set!:                           Vector Accessors.
* vector?:                               Vector Creation.
* with-input-from-file:                  File Ports.
* with-output-to-file:                   File Ports.
* write-char:                            Writing.
* zero?:                                 Comparison.



Tag Table:
Node: Top1142
Node: Guile License5019
Node: Manual Layout7392
Node: Manual Conventions9812
Node: What is Guile?10893
Node: Whirlwind Tour13339
Node: Running Guile Interactively13805
Node: Guile Scripts14685
Node: The Top of a Script File15405
Node: Scripting Examples18219
Node: Linking Programs With Guile21948
Node: Guile Initialization Functions23596
Node: A Sample Guile Main Program27942
Node: Writing Extensions for Guile31962
Node: A Sample Guile Extension33972
Node: Guile Modules36134
Node: Intro to Using Guile Modules36815
Node: Intro to Writing New Modules38294
Ref: Intro to Writing New Modules-Footnote-139892
Node: Intro to Modules and Extensions40066
Node: Obtaining and Installing Guile41709
Node: The Basic Guile Package42101
Node: Packages not shipped with Guile43385
Node: Reporting Bugs45189
Node: Running Intro51951
Node: Guile Scheme52901
Node: Guile Scripting53861
Node: Invoking Guile54461
Node: The Meta Switch58211
Node: Command Line Handling62143
Node: Command Line Args62902
Node: getopt-long64927
Node: getopt-long Example66540
Node: Option Specification69065
Node: Command Line Format72248
Node: getopt-long Reference75042
Node: option-ref Reference77636
Node: Debugging Features78337
Node: Single-Step79452
Node: Trace79556
Node: Backtrace81608
Node: Autoconf Support81865
Node: Autoconf Background82589
Node: Autoconf Macros83583
Node: Using Autoconf Macros86626
Node: Autofrisk89229
Node: Using Autofrisk91943
Node: Miscellaneous Tools93355
Node: Snarfing93907
Node: Init Snarfing with guile-snarf94861
Node: How guile-snarf works96230
Node: Macros guile-snarf recognizes100026
Node: Writing your own snarfing macros102518
Node: Doc Snarfing103318
Node: Executable Modules104521
Node: Basic Ideas107295
Node: About Data108362
Node: Latent Typing109029
Node: Values and Variables110968
Node: Definition112920
Node: About Procedures115503
Node: Procedures as Values116429
Node: Simple Invocation119089
Node: Creating a Procedure120862
Node: Lambda Alternatives123438
Node: About Expressions125299
Node: Evaluating126632
Ref: Evaluating-Footnote-1128767
Node: Eval Literal128903
Node: Eval Variable130152
Node: Eval Procedure130880
Node: Eval Special133938
Node: The REPL135918
Node: Syntax Summary136946
Node: About Closure138822
Node: About Environments139997
Node: Local Variables141806
Node: Chaining143312
Node: Lexical Scope145635
Node: Scoping Example147097
Node: Closure150989
Node: Serial Number153241
Node: Shared Variable154793
Node: Callback Closure156363
Node: OO Closure158642
Node: Further Reading160900
Node: Programming Intro161779
Node: Libguile Intro162481
Node: Programming Overview165047
Node: Extending Dia166513
Node: Dia Objective167472
Node: Dia Steps169508
Node: Dia Smobs170792
Node: Dia Primitives176014
Node: Dia Hook178418
Node: Dia Structure179452
Node: Dia Advanced180955
Node: Scheme vs C185638
Node: Testbed Example187664
Ref: Testbed Example-Footnote-1189278
Node: Programming Options189399
Node: Available Functionality191925
Node: Basic Constraints194559
Node: Style Choices194764
Node: Program Control194949
Node: User Programming195108
Ref: User Programming-Footnote-1198220
Node: Data Representation198500
Node: Data Representation in Scheme200046
Node: A Simple Representation201746
Node: Faster Integers203104
Node: Cheaper Pairs206570
Node: Guile Is Hairier209865
Node: How Guile does it210638
Node: General Rules211332
Node: Conservative GC212495
Node: Immediates vs Non-immediates216618
Node: Immediate Datatypes217833
Node: Integer Data218528
Node: Character Data219614
Node: Boolean Data220158
Node: Unique Values220770
Node: Non-immediate Datatypes222313
Node: Pair Data223901
Node: Vector Data226820
Node: Procedures228470
Node: Closures229113
Node: Subrs230788
Node: Port Data233176
Node: Signalling Type Errors233336
Node: Unpacking the SCM type234841
Node: Relationship between SCM and scm_t_bits236517
Node: Immediate objects238110
Node: Non-immediate objects239306
Node: Heap Cell Type Information240678
Node: Accessing Cell Entries241627
Node: Basic Rules for Accessing Cell Entries245162
Node: Defining New Types (Smobs)246460
Ref: Defining New Types (Smobs)-Footnote-1247629
Node: Describing a New Type247821
Node: Creating Instances253876
Ref: Creating Instances-Footnote-1258651
Node: Type checking258802
Node: Garbage Collecting Smobs260611
Node: A Common Mistake In Allocating Smobs265447
Node: Garbage Collecting Simple Smobs268113
Node: A Complete Example269718
Node: GH274403
Node: GH deprecation275543
Node: gh preliminaries277980
Node: Data types and constants defined by gh278437
Node: Starting and controlling the interpreter280099
Node: Error messages283503
Node: Executing Scheme code283725
Node: Defining new Scheme procedures in C284918
Node: Converting data between C and Scheme287220
Node: C to Scheme287672
Node: Scheme to C289478
Node: Type predicates292223
Node: Equality predicates293583
Node: Memory allocation and garbage collection294788
Node: Calling Scheme procedures from C295018
Node: Mixing gh and scm APIs301820
Node: scm transition summary301999
Node: Reference Intro310075
Node: API Overview310478
Node: Primitives312187
Node: Transforming Scheme name to C name312768
Node: Structuring argument lists for C functions314971
Node: C Only315467
Node: Scheme Only315769
Node: Reference Layout315937
Node: Simple Data Types316569
Node: Booleans318567
Node: Numbers320400
Node: Numerical Tower321856
Node: Integers323441
Node: Reals and Rationals324926
Node: Complex Numbers327627
Node: Exactness328815
Node: Number Syntax329894
Node: Integer Operations331504
Node: Comparison332525
Node: Conversion333453
Node: Complex334409
Node: Arithmetic335252
Node: Scientific337114
Node: Primitive Numerics338526
Node: Bitwise Operations341770
Node: Random345484
Node: Characters348232
Node: Strings352646
Node: String Syntax354237
Ref: String Syntax-Footnote-1354786
Node: String Predicates354881
Node: String Constructors355503
Node: List/String Conversion356239
Node: String Selection357522
Node: String Modification358673
Node: String Comparison359963
Node: String Searching362342
Node: Alphabetic Case Mapping363637
Node: Appending Strings365386
Node: Regular Expressions365904
Node: Regexp Functions367192
Node: Match Structures375197
Node: Backslash Escapes378336
Node: Symbols382423
Node: Symbol Data385289
Node: Symbol Keys387552
Node: Symbol Variables389987
Node: Symbol Primitives391009
Node: Symbol Props395766
Node: Symbol Read Syntax398696
Node: Keywords400310
Node: Why Use Keywords?400995
Node: Coding With Keywords402881
Node: Keyword Read Syntax404864
Node: Keyword Procedures406137
Node: Keyword Primitives406576
Node: Other Types407954
Node: Compound Data Types408587
Node: Pairs409599
Node: Lists412875
Ref: Lists-Footnote-1413737
Node: List Syntax413929
Ref: List Syntax-Footnote-1414901
Node: List Predicates415008
Node: List Constructors415863
Node: List Selection417526
Node: Append/Reverse418753
Node: List Modification421156
Node: List Searching423745
Node: List Mapping425216
Node: Vectors426491
Node: Vector Syntax427497
Node: Vector Creation428190
Node: Vector Accessors430306
Node: Records433186
Node: Structures437561
Node: Structure Concepts438350
Node: Structure Layout439696
Node: Structure Basics443397
Node: Vtables445464
Node: Arrays449781
Node: Conventional Arrays450186
Node: Array Mapping458684
Node: Uniform Arrays460273
Node: Bit Vectors465266
Node: Association Lists and Hash Tables466867
Node: Dictionary Types467379
Node: Association Lists469219
Node: Alist Key Equality470529
Node: Adding or Setting Alist Entries471364
Node: Retrieving Alist Entries475959
Node: Removing Alist Entries478229
Node: Sloppy Alist Functions480982
Node: Alist Example483160
Node: Hash Tables484428
Node: Hash Table Examples485164
Node: Hash Table Reference486909
Node: Procedures and Macros496802
Node: Lambda497515
Node: Optional Arguments500231
Node: let-optional Reference501576
Node: let-keywords Reference502913
Node: lambda* Reference504322
Node: define* Reference507746
Node: Procedure Properties509765
Node: Procedures with Setters513592
Ref: Procedures with Setters-Footnote-1515954
Node: Macros516095
Node: Syntax Rules518105
Node: Pattern Language520070
Node: Define-Syntax520229
Node: Let-Syntax520677
Node: Syntax Case520808
Node: Internal Macros520996
Node: Utility Functions525598
Node: Equality526347
Node: Object Properties528051
Node: Property Primitives530507
Node: Old-fashioned Properties531765
Node: Sorting533016
Node: Copying537347
Node: General Conversion538209
Node: Hooks539273
Node: Hook Example540725
Node: Hook Reference542578
Node: C Hooks546399
Node: Guile Hooks550571
Node: GC Hooks550815
Node: REPL Hooks553029
Node: Binding Constructs553156
Node: Top Level553866
Node: Local Bindings556560
Node: Internal Definitions559693
Node: Binding Reflection561304
Node: Control Mechanisms561812
Node: begin562662
Node: if cond case563739
Node: and or566425
Node: while do567594
Node: Continuations570116
Node: Multiple Values572146
Node: Exceptions574723
Node: Exception Terminology576355
Node: Catch577488
Node: Throw580948
Node: Lazy Catch583402
Node: Exception Implementation586724
Node: Error Reporting588292
Node: Dynamic Wind589899
Node: Handling Errors591689
Node: Input and Output596287
Node: Ports597108
Node: Reading598440
Ref: Reading-Footnote-1602025
Ref: Reading-Footnote-2602481
Node: Writing602928
Node: Closing605679
Node: Random Access607139
Node: Line/Delimited608717
Node: Block Reading and Writing613193
Node: Default Ports616829
Node: Port Types618471
Node: File Ports618842
Node: String Ports625623
Node: Soft Ports628075
Node: Void Ports629775
Node: I/O Extensions630309
Node: C Port Interface630571
Node: Port Implementation634099
Node: Read/Load/Eval638026
Node: Scheme Syntax638792
Node: Expression Syntax639092
Node: Comments639212
Node: Block Comments640123
Node: Case Sensitivity641034
Node: Keyword Syntax641764
Node: Reader Extensions641909
Node: Scheme Read642408
Node: Fly Evaluation644046
Node: Loading646126
Node: Delayed Evaluation649051
Node: Local Evaluation649599
Node: Evaluator Behaviour650071
Node: Memory Management652420
Node: Garbage Collection653521
Node: Weak References654587
Node: Weak key hashes656485
Node: Weak vectors657827
Node: Guardians658824
Node: Objects660846
Node: Modules661784
Node: provide and require663571
Node: Environments664380
Node: The Guile module system666268
Node: General Information about Modules667684
Node: Using Guile Modules670320
Node: Creating Guile Modules674003
Node: Module System Quirks676317
Node: Included Guile Modules677634
Node: Accessing Modules from C679668
Node: Dynamic Libraries683413
Ref: Dynamic Libraries-Footnote-1685418
Node: Low level dynamic linking685694
Node: Extensions691321
Node: Variables691561
Node: Scheduling694396
Node: Arbiters695031
Node: Asyncs696164
Node: Dynamic Roots698713
Node: Threads702986
Node: Low level thread primitives703680
Node: Higher level thread procedures705675
Node: Fluids707248
Node: Options and Config709973
Node: Build Config711214
Node: Feature Tracking715838
Node: Feature Manipulation716662
Node: Common Feature Symbols717516
Node: Runtime Options721743
Node: Low level options interfaces722587
Node: User level options interfaces724263
Node: Reader options726429
Node: Printing options727247
Node: Evaluator options727642
Node: Evaluator trap options728001
Node: Debugger options729865
Node: Examples of option use731926
Node: Translation734406
Node: Emacs Lisp Support734696
Node: Debugging735574
Node: Source Properties735977
Node: Using Traps737828
Node: Capturing the Stack or Innermost Stack Frame738224
Node: Examining the Stack740436
Node: Examining Stack Frames741519
Node: Decoding Memoized Source Expressions743510
Node: Starting a New Stack744091
Node: Deprecated744595
Node: Shared And Read Only Strings745137
Node: Shared Substrings745838
Node: Read Only Strings748835
Node: Sloppy Membership749971
Node: Strange Eval751255
Node: Close All Ports752970
Node: C Module Reg753639
Node: Obarray Symbols754692
Node: Removed Items758954
Node: SLIB759138
Node: SLIB installation759584
Node: JACAL760685
Node: POSIX761298
Node: Conventions762404
Node: Ports and File Descriptors765068
Node: File System781200
Node: User Information791474
Node: Time795268
Node: Runtime Environment800860
Node: Processes803036
Node: Signals813679
Node: Terminals and Ptys819222
Node: Pipes820761
Node: Networking822060
Node: Network Address Conversion822308
Node: Network Databases824781
Node: Network Sockets and Communication834203
Node: Internet Socket Examples847155
Node: Internet Socket Client847452
Node: Internet Socket Server848080
Node: System Identification849409
Node: Locales851282
Node: Encryption851925
Node: SRFI Support853096
Node: About SRFI Usage854493
Node: SRFI-0856180
Node: SRFI-1859086
Node: SRFI-1 Constructors860397
Node: SRFI-1 Predicates861357
Node: SRFI-1 Selectors862969
Node: SRFI-1 Length Append etc864664
Node: SRFI-1 Fold and Map866284
Node: SRFI-1 Filtering and Partitioning871128
Node: SRFI-1 Searching872877
Node: SRFI-1 Deleting875330
Node: SRFI-1 Association Lists876450
Node: SRFI-1 Set Operations877803
Node: SRFI-2881443
Node: SRFI-4882425
Node: SRFI-4 - Read Syntax883764
Node: SRFI-4 - Procedures884872
Node: SRFI-6886743
Node: SRFI-8887247
Node: SRFI-9887499
Node: SRFI-10888861
Node: SRFI-11890055
Node: SRFI-13890910
Node: Loading SRFI-13893075
Node: SRFI-13 Predicates894064
Node: SRFI-13 Constructors895045
Node: SRFI-13 List/String Conversion895676
Node: SRFI-13 Selection897078
Node: SRFI-13 Modification899591
Node: SRFI-13 Comparison900170
Node: SRFI-13 Prefixes/Suffixes902586
Node: SRFI-13 Searching903811
Node: SRFI-13 Case Mapping905739
Node: SRFI-13 Reverse/Append906716
Node: SRFI-13 Fold/Unfold/Map908468
Node: SRFI-13 Replicate/Rotate910808
Node: SRFI-13 Miscellaneous912186
Node: SRFI-13 Filtering/Deleting913090
Node: SRFI-14914090
Node: Loading SRFI-14915169
Node: SRFI-14 Character Set Data Type915609
Node: SRFI-14 Predicates/Comparison916522
Node: SRFI-14 Iterating Over Character Sets917494
Node: SRFI-14 Creating Character Sets919926
Node: SRFI-14 Querying Character Sets922178
Node: SRFI-14 Character-Set Algebra923437
Node: SRFI-14 Standard Character Sets925209
Node: SRFI-16926876
Node: SRFI-17928693
Node: SRFI-19929745
Node: SRFI-19 Constants930430
Node: SRFI-19 Current time and clock resolution930793
Node: SRFI-19 Time object and accessors931248
Node: SRFI-19 Time comparison procedures931842
Node: SRFI-19 Time arithmetic procedures932265
Node: SRFI-19 Date object and accessors932870
Node: SRFI-19 Time/Date/Julian Day/Modified Julian Day converters933682
Node: SRFI-19 Date to string/string to date converters935566
Node: Readline Support935937
Node: Loading Readline Support936589
Node: Readline Options938285
Node: Value History939416
Node: Pretty Printing940375
Node: Formatted Output941974
Node: Rx Regexps949026
Node: Expect953240
Node: The Scheme shell (scsh)959250
Node: Concept Index959815
Node: Procedure Index967488
Node: Variable Index1088198
Node: Type Index1092598
Node: R5RS Index1094391

End Tag Table
