   This reference manual documents Guile, GNU's Ubiquitous Intelligent
Language for Extensions.  This is edition 1.1 corresponding to Guile
1.8.0.

   Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005 Free
Software Foundation.

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

5.20 Support for Internationalization
=====================================

Guile provides an interface to GNU `gettext' for translating message
strings (see Introduction (gettext)).

   Messages are collected in domains, so different libraries and
programs maintain different message catalogues.  The DOMAIN parameter in
the functions below is a string (it becomes part of the message catalog
filename).

   When `gettext' is not available, or if Guile was configured
`--without-nls', dummy functions doing no translation are provided.

 -- Scheme Procedure: gettext msg [domain [category]]
 -- C Function: scm_gettext (msg, domain, category)
     Return the translation of MSG in DOMAIN.  DOMAIN is optional and
     defaults to the domain set through `textdomain' below.  CATEGORY
     is optional and defaults to `LC_MESSAGES' (see Locales).

     Normal usage is for MSG to be a literal string.  `xgettext' can
     extract those from the source to form a message catalogue ready
     for translators (see Invoking the `xgettext' Program (gettext)).

          (display (gettext "You are in a maze of twisty passages."))

     `_' is a commonly used shorthand, an application can make that an
     alias for `gettext'.  Or a library can make a definition that uses
     its specific DOMAIN (so an application can change the default
     without affecting the library).

          (define (_ msg) (gettext msg "mylibrary"))
          (display (_ "File not found."))

     `_' is also a good place to perhaps strip disambiguating extra
     text from the message string, as for instance in How to use `gettext' in GUI programs (gettext).

 -- Scheme Procedure: ngettext msg msgplural n [domain [category]]
 -- C Function: scm_ngettext (msg, msgplural, n, domain, category)
     Return the translation of MSG/MSGPLURAL in DOMAIN, with a plural
     form chosen appropriately for the number N.  DOMAIN is optional
     and defaults to the domain set through `textdomain' below.
     CATEGORY is optional and defaults to `LC_MESSAGES' (see
     Locales).

     MSG is the singular form, and MSGPLURAL the plural.  When no
     translation is available, MSG is used if N = 1, or MSGPLURAL
     otherwise.  When translated, the message catalogue can have a
     different rule, and can have more than two possible forms.

     As per `gettext' above, normal usage is for MSG and MSGPLURAL to
     be literal strings, since `xgettext' can extract them from the
     source to build a message catalogue.  For example,

          (define (done n)
            (format #t (ngettext "~a file processed\n"
                                 "~a files processed\n" n)
                       n))

          (done 1) -| 1 file processed
          (done 3) -| 3 files processed

     It's important to use `ngettext' rather than plain `gettext' for
     plurals, since the rules for singular and plural forms in English
     are not the same in other languages.  Only `ngettext' will allow
     translators to give correct forms.

 -- Scheme Procedure: textdomain [domain]
 -- C Function: scm_textdomain (domain)
     Get or set the default gettext domain.  When called with no
     parameter the current domain is returned.  When called with a
     parameter, DOMAIN is set as the current domain, and that new value
     returned.  For example,

          (textdomain "myprog")
          => "myprog"

 -- Scheme Procedure: bindtextdomain domain [directory]
 -- C Function: scm_bindtextdomain (domain, directory)
     Get or set the directory under which to find message files for
     DOMAIN.  When called without a DIRECTORY the current setting is
     returned.  When called with a DIRECTORY, DIRECTORY is set for
     DOMAIN and that new setting returned.  For example,

          (bindtextdomain "myprog" "/my/tree/share/locale")
          => "/my/tree/share/locale"

     When using Autoconf/Automake, an application should arrange for the
     configured `localedir' to get into the program (by substituting,
     or by generating a config file) and set that for its domain.  This
     ensures the catalogue can be found even when installed in a
     non-standard location.

 -- Scheme Procedure: bind-textdomain-codeset domain [encoding]
 -- C Function: scm_bind_textdomain_codeset (domain, encoding)
     Get or set the text encoding to be used by `gettext' for messages
     from DOMAIN.  ENCODING is a string, the name of a coding system,
     for instance "8859_1".  (On a Unix/POSIX system the `iconv'
     program can list all available encodings.)

     When called without an ENCODING the current setting is returned,
     or `#f' if none yet set.  When called with an ENCODING, it is set
     for DOMAIN and that new setting returned.  For example,

          (bind-textdomain-codeset "myprog")
          => #f
          (bind-textdomain-codeset "myprog" "latin-9")
          => "latin-9"

     The encoding requested can be different from the translated data
     file, messages will be recoded as necessary.  But note that when
     there is no translation, `gettext' returns its MSG unchanged, ie.
     without any recoding.  For that reason source message strings are
     best as plain ASCII.

     Currently Guile has no understanding of multi-byte characters, and
     string functions won't recognise character boundaries in multi-byte
     strings.  An application will at least be able to pass such strings
     through to some output though.  Perhaps this will change in the
     future.

5.21 Debugging Infrastructure
=============================

5.21.1 Interactive Debugging
----------------------------

 -- Scheme Procedure: backtrace [highlights]
 -- C Function: scm_backtrace_with_highlights (highlights)
 -- C Function: scm_backtrace ()
     Display a backtrace of the stack saved by the last error to the
     current output port.  When HIGHLIGHTS is given, it should be a
     list and all members of it are highligthed in the backtrace.

 -- Scheme Procedure: debug
     Invoke the Guile debugger to explore the context of the last error.

5.21.2 Breakpoints
------------------

 -- Generic Function: set-breakpoint! behaviour . location-args
     Set a breakpoint with behaviour BEHAVIOUR at the location
     specified by LOCATION-ARGS.

     The form of the LOCATION-ARGS depends upon what methods for
     `set-breakpoint!' have been provided by the implementations of
     subclasses of the `<breakpoint>' base class.

 -- Generic Function: get-breakpoint . location-args
     Find and return the breakpoint instance at the location specified
     by LOCATION-ARGS.

     The form of the LOCATION-ARGS depends upon what methods for
     `get-breakpoint' have been provided by the implementations of
     subclasses of the `<breakpoint>' base class.

 -- Method: set-breakpoint! behaviour (proc <procedure>)
     Set a breakpoint with behaviour BEHAVIOUR before applications of
     the procedure PROC.

 -- Method: set-breakpoint! behaviour x-as-read (x-pairified <pair>)
     Set a breakpoint with behaviour BEHAVIOUR on the source expression
     X-PAIRIFIED, storing X-AS-READ for use in messages describing the
     breakpoint.

 -- Method: set-breakpoint! behaviour (number <integer>)
     Change the behaviour of existing breakpoint number NUMBER to
     BEHAVIOUR.

 -- Accessor: bp-behaviour breakpoint
     Get or set the behaviour of the breakpoint instance BREAKPOINT.

 -- Accessor: bp-enabled? breakpoint
     Get or set the enabled state of the specified BREAKPOINT.

 -- Procedure: enable-breakpoint! . location-args
 -- Procedure: disable-breakpoint! . location-args
     Enable or disable the breakpoint at the location specified by
     LOCATION-ARGS.

 -- Generic Function: bp-delete! breakpoint
     Delete breakpoint BREAKPOINT.  This means (1) doing whatever is
     needed to prevent the breakpoint from triggering again, and (2)
     removing it from the global list of current breakpoints.

 -- Procedure: delete-breakpoint! . location-args
     Delete the breakpoint at the location specified by LOCATION-ARGS.

 -- Generic Function: bp-describe breakpoint port
     Print a description of BREAKPOINT to the specified PORT.  PORT can
     be `#t' for standard output, or else any output port.

 -- Procedure: describe-breakpoint . location-args
     Print (to standard output) a description of the breakpoint at
     location specified by LOCATION-ARGS.

 -- Procedure: all-breakpoints
     Return a list of all current breakpoints, ordered by breakpoint
     number.

 -- Procedure: describe-all-breakpoints
     Print a description of all current breakpoints to standard output.

5.21.3 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" (see Reader options).  This option is switched
_on_ by default, together with the debug options "debug" and
"backtrace" (see Debugger options), when Guile is run
interactively; all these options are _off_ by default when Guile runs a
script non-interactively.

   The following procedures can be used to access and set the source
properties of read expressions.

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

   In practice there are only two ways that you should use the ability
to set an expression's source breakpoints.

   * To set a breakpoint on an expression, use `(set-source-property!
     EXPR 'breakpoint #t)'.  If you do this, you should also set the
     `traps' and `enter-frame-handler' trap options (see Evaluator trap options)
     and `breakpoints' debug option (see Debugger options)
     appropriately, and the evaluator will then call your
     enter frame handler whenever it is about to evaluate that
     expression.

   * To make a read or constructed expression appear to have come from a
     different source than what the expression's source properties
     already say, you can use `set-source-property!' to set the
     expression's `filename', `line' and `column' properties.  The
     properties that you set will then show up later if that expression
     is involved in a backtrace or error report.

   If you are looking for a way to attach arbitrary information to an
expression other than these properties, you should use
`make-object-property' instead (see Object Properties), because
that will avoid bloating the source property hash table, which is really
only intended for the specific purposes described in this section.

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

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

5.21.6 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
          [highlights]]]
 -- C Function: scm_display_backtrace_with_highlights (stack, port,
          first, depth, highlights)
 -- 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.  When
     HIGHLIGHTS is given, it should be a list and all members of it are
     highligthed in the backtrace.

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

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

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

5.22 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 also documents how to
achieve the same result using the scm interface.

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

5.22.2 Transitioning away from GH
---------------------------------

The following table summarizes how to transition from the GH to the scm
interface.  The replacements that are recommended are not always
completely equivalent to the GH functionality that they should replace.
Therefore, you should read the reference documentation of the
replacements carefully if you are not yet familiar with them.

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.  See Guile Initialization Functions for more
     details.

`gh_repl'
     Use `scm_shell' instead.

`gh_init'
     Use `scm_init_guile' instead.

`gh_catch'
     Use `scm_internal_catch' instead.

`gh_eval_str'
     Use `scm_c_eval_string' instead.

`gh_eval_str_with_catch'
     Use `scm_c_eval_string' together with `scm_internal_catch' instead.

`gh_eval_str_with_standard_handler'
     Use `scm_c_eval_string' together with `scm_internal_catch' and
     `scm_handle_by_message_no_exit' instead.

`gh_eval_str_with_stack_saving_handler'
     Use `scm_c_eval_string' together with `scm_internal_stack_catch'
     and `scm_handle_by_message_no_exit' instead.

`gh_eval_file' or `gh_load'
     Use `scm_c_primitive_load' instead.

`gh_eval_file_with_catch'
     Use `scm_c_primitive_load' together with `scm_internal_catch'
     instead.

`gh_eval_file_with_standard_handler'
     Use `scm_c_primitive_load' together with `scm_internal_catch' and
     `scm_handle_by_message_no_exit' instead.

`gh_new_procedure'
`gh_new_procedure0_0'
`gh_new_procedure0_1'
`gh_new_procedure0_2'
`gh_new_procedure1_0'
`gh_new_procedure1_1'
`gh_new_procedure1_2'
`gh_new_procedure2_0'
`gh_new_procedure2_1'
`gh_new_procedure2_2'
`gh_new_procedure3_0'
`gh_new_procedure4_0'
`gh_new_procedure5_0'
     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.  See A Sample Guile Extension
     for an example.

`gh_defer_ints' and `gh_allow_ints'
     Use `SCM_CRITICAL_SECTION_START' and `SCM_CRITICAL_SECTION_END'
     instead.  Note that these macros are used without parentheses, as
     in `SCM_DEFER_INTS;'.

`gh_bool2scm'
     Use `scm_from_bool' instead.

`gh_int2scm'
     Use `scm_from_int' instead.

`gh_ulong2scm'
     Use `scm_from_ulong' instead.

`gh_long2scm'
     Use `scm_from_long' instead.

`gh_double2scm'
     Use `scm_make_real' instead.

`gh_char2scm'
     Use `SCM_MAKE_CHAR' instead.

`gh_str2scm'
     Use `scm_from_locale_stringn' instead.

`gh_str02scm'
     Use `scm_from_locale_string' instead.

`gh_set_substr'
     Use `scm_string_copy_x'.

`gh_symbol2scm'
     Use `scm_from_locale_symbol' instead.

`gh_ints2scm'
`gh_doubles2scm'
`gh_chars2byvect'
`gh_shorts2svect'
`gh_longs2ivect'
`gh_ulongs2uvect'
`gh_floats2fvect'
`gh_doubles2dvect'
     Use the uniform numeric vector function, see Uniform Numeric Vectors.

`gh_scm2bool'
     Use `scm_is_true' or `scm_to_bool' instead.

`gh_scm2int'
     Use `scm_to_int' instead.

`gh_scm2ulong'
     Use `scm_to_ulong' instead.

`gh_scm2long'
     Use `scm_to_long' instead.

`gh_scm2double'
     Use `scm_to_double' instead.

`gh_scm2char'
     Use `scm_to_char' instead.

`gh_scm2newstr'
     Use `scm_to_locale_string' or similar instead.

`gh_get_substr'
     Use `scm_c_substring' together with `scm_to_locale_string' or
     similar instead.

`gh_symbol2newstr'
     Use `scm_symbol_to_string' together with `scm_to_locale_string' or
     similar instead.

`gh_scm2chars'
     Use `scm_from_locale_string' (or similar) or the uniform numeric
     vector functions (see Uniform Numeric Vectors) instead.

`gh_scm2shorts'
`gh_scm2longs'
`gh_scm2floats'
`gh_scm2doubles'
     Use the uniform numeric vector function, see Uniform Numeric Vectors.

`gh_boolean_p'
     Use `scm_is_bool' instead.

`gh_symbol_p'
     Use `scm_is_symbol' instead.

`gh_char_p'
     Replace `gh_char_p (OBJ)' with
          scm_is_true (scm_char_p (OBJ))

`gh_vector_p'
     Replace `gh_vector_p (OBJ)' with
          scm_is_true (scm_vector_p (OBJ))

`gh_pair_p'
     Replace `gh_pair_p (OBJ)' with
          scm_is_true (scm_pair_p (OBJ))

`gh_number_p'
     Use `scm_is_number' instead.

`gh_string_p'
     Use `scm_is_string' instead.

`gh_procedure_p'
     Replace `gh_procedure_p (OBJ)' by
          scm_is_true (scm_procedure_p (OBJ))

`gh_list_p'
     Replace `gh_list_p (OBJ)' with
          scm_is_true (scm_list_p (OBJ))

`gh_inexact_p'
     Replace `gh_inexact_p (OBJ)' with
          scm_is_true (scm_inexact_p (OBJ))

`gh_exact_p'
     Replace `gh_exact_p (OBJ)' with
          scm_is_true (scm_exact_p (OBJ))

`gh_eq_p'
     Use `scm_is_eq' instead.

`gh_eqv_p'
     Replace `gh_eqv_p (X, Y)' with
          scm_is_true (scm_eqv_p (X, Y))

`gh_equal_p'
     Replace `gh_equal_p (X, Y)' with
          scm_is_true (scm_equal_p (X, Y))

`gh_string_equal_p'
     Replace `gh_string_equal_p (X, Y)' with
          scm_is_true (scm_string_equal_p (X, Y))

`gh_null_p'
     Use `scm_is_null' instead.

`gh_not'
     Use `scm_not' instead.

`gh_make_string'
     Use `scm_make_string' instead.

`gh_string_length'
     Use `scm_string_length' instead.

`gh_string_ref'
     Use `scm_string_ref' instead.

`gh_string_set_x'
     Use `scm_string_set_x' instead.

`gh_substring'
     Use `scm_substring' instead.

`gh_string_append'
     Use `scm_string_append' instead.

`gh_cons'
     Use `scm_cons' instead.

`gh_car' and `gh_cdr'
     Use `scm_car' and `scm_cdr' instead.

`gh_cxxr' and `gh_cxxxr'
     (Where each x is either `a' or `d'.)  Use the corresponding
     `scm_cxxr' or `scm_cxxxr' function 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_list_n' instead.

`gh_length'
     Replace `gh_length (LST)' with
          scm_to_size_t (scm_length (LST))

`gh_append'
     Use `scm_append' instead.

`gh_append2', `gh_append3', `gh_append4'
     Replace `gh_appendN (L1, ..., LN)' by
          scm_append (scm_list_n (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 `scm_c_vector_length' instead.

`gh_uniform_vector_length'
     Use `scm_c_uniform_vector_length' instead.

`gh_uniform_vector_ref'
     Use `scm_c_uniform_vector_ref' instead.

`gh_vector_to_list'
     Use `scm_vector_to_list' instead.

`gh_apply'
     Use `scm_apply_0' instead.

`gh_call0'
`gh_call1'
`gh_call2'
`gh_call3'
     Use `scm_call_0', `scm_call_1', etc instead.

`gh_display'
`gh_write'
`gh_newline'
     Use `scm_display (obj, scm_current_output_port ())' instead, etc.

`gh_lookup'
     Use `scm_variable_ref (scm_c_lookup (name))' instead.

`gh_module_lookup'
     Use `scm_variable_ref (scm_c_module_lookup (module, name))'
     instead.

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

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

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

5.22.6 Error messages
---------------------

[FIXME: need to fill this based on Jim's new mechanism]

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

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

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

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

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

5.22.9.2 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, size_t *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.

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

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

5.22.12 Memory allocation and garbage collection
------------------------------------------------

5.22.13 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 R5RS (r5rs).
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_list_n()'.

 -- 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] */

6 Guile Modules
***************

6.1 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 in the usual way (see Require (slib)).
For example,

     (use-modules (ice-9 slib))
     (require 'primes)
     (probably-prime? 13)
     => #t

   Note that the following Guile core functions are overridden by
`(ice-9 slib)', to implement SLIB specified semantics.

`delete-file'
     Returns `#t' for success or `#f' for failure (see Input/Output (slib)),
     as opposed to the Guile core version
     unspecified for success and throwing an error for failure (see
     File System).

`provided?'
     Accepts a feature specification containing `and' and `or' forms
     combining symbols (see Feature (slib)), as opposed to
     the Guile core taking only plain symbols (see Feature Manipulation).

`open-file'
     Takes a symbol `r', `rb', `w' or `wb' for the open mode (see
     Input/Output (slib)), as opposed to the Guile core
     version taking a string (see File Ports).

`system'
     Returns a plain exit code 0 to 255 (see System Interface (slib)),
     as opposed to the Guile core version
     returning a wait status that must be examined with
     `status:exit-val' etc (see Processes).

6.1.1 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

6.1.2 JACAL
-----------

Jacal is a symbolic math package written in Scheme by Aubrey Jaffer.
It is usually installed as an extra package in SLIB.

   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 Jacal (jacal).
Otherwise you can find it on the web at
`http://www-swiss.ai.mit.edu/~jaffer/JACAL.html'

6.2 POSIX System Calls and Networking
=====================================

6.2.1 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 scsh (see 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, see 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 with `scm-error' (see Error Reporting).  The DATA
parameter is a list containing the Unix `errno' value (an integer).
For example,

     (define (my-handler key func fmt fmtargs data)
       (display key) (newline)
       (display func) (newline)
       (apply format #t fmt fmtargs) (newline)
       (display data) (newline))

     (catch 'system-error
       (lambda () (dup2 -123 -456))
       my-handler)

     -|
     system-error
     dup2
     Bad file descriptor
     (9)

 -- Function: system-error-errno arglist
     Return the `errno' value from a list which is the arguments to an
     exception handler.  If the exception is not a `system-error', then
     the return is `#f'.  For example,

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

6.2.2 Ports and File Descriptors
--------------------------------

Conventions generally follow those of scsh, see The Scheme shell (scsh).

   File ports are implemented using low-level operating system I/O
facilities, with optional buffering to improve efficiency; see
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, three file descriptors
(0, 1, and 2) are automatically imported when a program starts up and
assigned to the initial values of the current/standard input, output,
and error ports, respectively.  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 RCOUNT.  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 `open-file' (see open-file).

 -- 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 (see Processes) 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 File Status Flags (libc), 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' (see close-port), 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', 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 on that port.  If called multiple times, the unread
     characters will be read again in "last-in, first-out" order (i.e.
     a stack).  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'.

      -- Variable: PIPE_BUF
          A write of up to `PIPE_BUF' many bytes to a pipe is atomic,
          meaning when done it goes into the pipe instantaneously and
          as a contiguous block (see Atomicity of Pipe I/O (libc)).

     Note that the output port is likely to block if too much data has
     been written but not yet read from the input port.  Typically the
     capacity is `PIPE_BUF' bytes.

   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 (see open-file).

 -- 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
     open-file.  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 (SCM proc)
 -- C Function: scm_c_port_for_each (void (*proc)(void *, SCM), void
          *data)
     Apply PROC to each port in the Guile port table (FIXME: what is
     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.

     The C function `scm_port_for_each' takes a Scheme procedure
     encoded as a `SCM' value, while `scm_c_port_for_each' takes a
     pointer to a C function and passes along a arbitrary DATA cookie.

 -- Scheme Procedure: setvbuf port mode [size]
 -- C Function: scm_setvbuf (port, mode, size)
     Set the buffering mode for PORT.  MODE can be:

      -- Variable: _IONBF
          non-buffered

      -- Variable: _IOLBF
          line buffered

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

      -- Variable: F_DUPFD
          Duplicate a file descriptor

      -- Variable: F_GETFD
          Get flags associated with the file descriptor.

      -- Variable: F_SETFD
          Set flags associated with the file descriptor to VALUE.

      -- Variable: F_GETFL
          Get flags associated with the open file.

      -- Variable: F_SETFL
          Set flags associated with the open file to VALUE

      -- Variable: F_GETOWN
          Get the process ID of a socket's owner, for `SIGIO' signals.

      -- Variable: F_SETOWN
          Set the process that owns a socket to VALUE, for `SIGIO'
          signals.

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

      -- Variable: LOCK_SH
          Shared lock.  More than one process may hold a shared lock
          for a given file at a given time.

      -- Variable: LOCK_EX
          Exclusive lock.  Only one process may hold an exclusive lock
          for a given file at a given time.

      -- Variable: LOCK_UN
          Unlock the file.

      -- Variable: LOCK_NB
          Don't block when locking.  This is combined with one of the
          other operations using `logior' (see Bitwise Operations).
          If `flock' would block an `EWOULDBLOCK' error is thrown
          (see Conventions).

     The return value is not specified. FILE may be an open file
     descriptor or an open file descriptor port.

     Note that `flock' does not lock files across NFS.

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

6.2.3 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)
     Test accessibility of a file under the real UID and GID of the
     calling process.  The return is `#t' if PATH exists and the
     permissions requested by HOW are all allowed, or `#f' if not.

     HOW is an integer which is one of the following values, or a
     bitwise-OR (`logior') of multiple values.

      -- 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.  This is implied by each of
          the other tests, so there's no need to combine it with them.

     It's important to note that `access?' does not simply indicate
     what will happen on attempting to read or write a file.  In normal
     circumstances it does, but in a set-UID or set-GID program it
     doesn't because `access?' tests the real ID, whereas an open or
     execute attempt uses the effective ID.

     A program which will never run set-UID/GID can ignore the
     difference between real and effective IDs, but for maximum
     generality, especially in library functions, it's best not to use
     `access?' to predict the result of an open or execute, instead
     simply attempt that and catch any exception.

     The main use for `access?' is to let a set-UID/GID program
     determine what the invoking user would have been allowed to do,
     without the greater (or perhaps lesser) privileges afforded by the
     effective ID.  For more on this, see Testing File Access (libc).

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

      -- Scheme Procedure: stat:dev st
          The device number containing the file.

      -- Scheme Procedure: stat:ino st
          The file serial number, which distinguishes this file from all
          other files on the same device.

      -- Scheme Procedure: stat:mode st
          The mode of the file.  This is an integer which incorporates
          file type information and file permission bits.  See also
          `stat:type' and `stat:perms' below.

      -- Scheme Procedure: stat:nlink st
          The number of hard links to the file.

      -- Scheme Procedure: stat:uid st
          The user ID of the file's owner.

      -- Scheme Procedure: stat:gid st
          The group ID of the file.

      -- Scheme Procedure: stat:rdev st
          Device ID; this entry is defined only for character or block
          special files.  On some systems this field is not available
          at all, in which case `stat:rdev' returns `#f'.

      -- Scheme Procedure: stat:size st
          The size of a regular file in bytes.

      -- Scheme Procedure: stat:atime st
          The last access time for the file.

      -- Scheme Procedure: stat:mtime st
          The last modification time for the file.

      -- Scheme Procedure: stat:ctime st
          The last modification time for the attributes of the file.

      -- Scheme Procedure: stat:blksize st
          The optimal block size for reading or writing the file, in
          bytes.  On some systems this field is not available, in which
          case `stat:blksize' returns a sensible suggested block size.

      -- Scheme Procedure: stat:blocks st
          The amount of disk space that the file occupies measured in
          units of 512 byte blocks.  On some systems this field is not
          available, in which case `stat:blocks' returns `#f'.

     In addition, the following procedures return the information from
     `stat:mode' in a more convenient form:

      -- Scheme Procedure: stat:type st
          A symbol representing the type of file.  Possible values are
          `regular', `directory', `symlink', `block-special',
          `char-special', `fifo', `socket', and `unknown'.

      -- Scheme Procedure: stat:perms st
          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'
     (see File Owner (libc)), 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 whose path is specified by STR.

 -- Scheme Procedure: copy-file oldfile newfile
 -- C Function: scm_copy_file (oldfile, newfile)
     Copy the file specified by OLDFILE to NEWFILE.  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 NEWPATH with the value (i.e.,
     pointing to) OLDPATH.  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
     (see Processes).  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 DIRNAME and return a directory
     stream.

 -- Scheme Procedure: directory-stream? object
 -- C Function: scm_directory_stream_p (object)
     Return a boolean indicating whether OBJECT is a directory stream
     as returned by `opendir'.

 -- Scheme Procedure: readdir stream
 -- C Function: scm_readdir (stream)
     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 stream
 -- C Function: scm_rewinddir (stream)
     Reset the directory port STREAM so that the next call to `readdir'
     will return the first directory entry.

 -- Scheme Procedure: closedir stream
 -- C Function: scm_closedir (stream)
     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 an auto-generated name of a temporary file, a file which
     doesn't already exist.  The name includes a path, it's usually in
     `/tmp' but that's system dependent.

     Care must be taken when using `tmpnam'.  In between choosing the
     name and creating the file another program might use that name, or
     an attacker might even make it a symlink pointing at something
     important and causing you to overwrite that.

     The safe way is to create the file using `open' with `O_EXCL' to
     avoid any overwriting.  A loop can try again with another name if
     the file exists (error `EEXIST').  `mkstemp!' below does that.

 -- Scheme Procedure: mkstemp! tmpl
 -- C Function: scm_mkstemp (tmpl)
     Create a new unique file in the file system and return 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 those `X's will be changed in the
     string to return the name of the file.  (`port-filename' on the
     port also gives the name.)

     POSIX doesn't specify the permissions mode of the file, on GNU and
     most systems it's `#o600'.  An application can use `chmod' to
     relax that if desired.  For example `#o666' less `umask', which is
     usual for ordinary file creation,

          (let ((port (mkstemp! (string-copy "/tmp/myfile-XXXXXX"))))
            (chmod port (logand #o666 (lognot (umask))))
            ...)

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

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

 -- Scheme Procedure: passwd:name pw
     The name of the userid.

 -- Scheme Procedure: passwd:passwd pw
     The encrypted passwd.

 -- Scheme Procedure: passwd:uid pw
     The user id number.

 -- Scheme Procedure: passwd:gid pw
     The group id number.

 -- Scheme Procedure: passwd:gecos pw
     The full name.

 -- Scheme Procedure: passwd:dir pw
     The home directory.

 -- Scheme Procedure: passwd:shell pw
     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:

 -- Scheme Procedure: group:name gr
     The group name.

 -- Scheme Procedure: group:passwd gr
     The encrypted group password.

 -- Scheme Procedure: group:gid gr
     The group id number.

 -- Scheme Procedure: group:mem gr
     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.

     This function has been removed from the latest POSIX specification,
     Guile provides it only if the system has it.  Using `(getpwuid
     (geteuid))' may be a better idea.

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

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

 -- Scheme Procedure: tm:sec tm
 -- Scheme Procedure: set-tm:sec tm val
     Seconds (0-59).

 -- Scheme Procedure: tm:min tm
 -- Scheme Procedure: set-tm:min tm val
     Minutes (0-59).

 -- Scheme Procedure: tm:hour tm
 -- Scheme Procedure: set-tm:hour tm val
     Hours (0-23).

 -- Scheme Procedure: tm:mday tm
 -- Scheme Procedure: set-tm:mday tm val
     Day of the month (1-31).

 -- Scheme Procedure: tm:mon tm
 -- Scheme Procedure: set-tm:mon tm val
     Month (0-11).

 -- Scheme Procedure: tm:year tm
 -- Scheme Procedure: set-tm:year tm val
     Year (70-), the year minus 1900.

 -- Scheme Procedure: tm:wday tm
 -- Scheme Procedure: set-tm:wday tm val
     Day of the week (0-6) with Sunday represented as 0.

 -- Scheme Procedure: tm:yday tm
 -- Scheme Procedure: set-tm:yday tm val
     Day of the year (0-364, 365 in leap years).

 -- Scheme Procedure: tm:isdst tm
 -- Scheme Procedure: set-tm:isdst tm val
     Daylight saving indicator (0 for "no", greater than 0 for "yes",
     less than 0 for "unknown").

 -- Scheme Procedure: tm:gmtoff tm
 -- Scheme Procedure: set-tm:gmtoff tm val
     Time zone offset in seconds west of UTC (-46800 to 43200).

 -- Scheme Procedure: tm:zone tm
 -- Scheme Procedure: set-tm:zone tm val
     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)
     For a broken down time object SBD-TIME, return a pair the `car' of
     which is an integer time like `current-time', and the `cdr' of
     which is a new broken down time with normalized fields.

     ZONE is a timezone string, or the default is the `TZ' environment
     variable or the system default (see Specifying the Time Zone with `TZ' (libc)).
     SBD-TIME is taken to be in that
     ZONE.

     The following fields of SBD-TIME are used: `tm:year', `tm:mon',
     `tm:mday', `tm:hour', `tm:min', `tm:sec', `tm:isdst'.  The values
     can be outside their usual ranges.  For example `tm:hour' normally
     goes up to 23, but a value say 33 would mean 9 the following day.

     `tm:isdst' in SBD-TIME says whether the time given is with
     daylight savings or not.  This is ignored if ZONE doesn't have any
     daylight savings adjustment amount.

     The broken down time in the return normalizes the values of
     SBD-TIME by bringing them into their usual ranges, and using the
     actual daylight savings rule for that time in ZONE (which may
     differ from what SBD-TIME had).  The easiest way to think of this
     is that SBD-TIME plus ZONE converts to the integer UTC time, then
     a `localtime' is applied to get the normal presentation of that
     time, in ZONE.

 -- 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 tm
 -- C Function: scm_strftime (format, tm)
     Return a string which is broken-down time structure TM formatted
     according to the given FORMAT string.

     FORMAT contains field specifications introduced by a `%'
     character.  See Formatting Calendar Time (libc),
     or `man 3 strftime', for the available formatting.

          (strftime "%c" (localtime (current-time)))
          => "Mon Mar 11 20:17:43 2002"

     If `setlocale' has been called (see Locales), month and day
     names are from the current locale and in the locale character set.

     Note that `%Z' might print the `tm:zone' in TM or it might print
     just the current zone (`tzset' above).  A GNU system prints
     `tm:zone', a strict C99 system like NetBSD prints the current
     zone.  Perhaps in the future Guile will try to get `tm:zone' used
     always.

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

      -- Scheme Procedure: tms:clock tms
          The current real time, expressed as time units relative to an
          arbitrary base.

      -- Scheme Procedure: tms:utime tms
          The CPU time units used by the calling process.

      -- Scheme Procedure: tms:stime tms
          The CPU time units used by the system on behalf of the calling
          process.

      -- Scheme Procedure: tms:cutime tms
          The CPU time units used by terminated child processes of the
          calling process, whose status has been collected (e.g., using
          `waitpid').

      -- Scheme Procedure: tms:cstime tms
          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.

6.2.6 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: unsetenv name
     Remove variable NAME from the environment.  The name can not
     contain a `=' character.

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

6.2.7 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. See Assigning File Permissions (libc),
     for more on how to
     use umasks.

     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.  `(provided? '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.  `(provided? 'EIDs)' reports whether the system supports
     effective IDs.

 -- Scheme Procedure: setgroups vec
 -- C Function: scm_setgroups (vec)
     Set the current set of supplementary group IDs to the integers in
     the given vector VEC.  The return value is unspecified.

     Generally only the superuser can set the process group IDs (see
     Setting the Group IDs (libc)).

 -- 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--`(provided? '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--`(provided? '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: system* . args
 -- C Function: scm_system_star (args)
     Execute the command indicated by ARGS.  The first element must be
     a string indicating the command to be executed, and the remaining
     items must be strings representing each of the arguments to that
     command.

     This function returns the exit status of the command as provided by
     `waitpid'.  This value can be handled with `status:exit-val' and
     the related functions.

     `system*' is similar to `system', but accepts only one string
     per-argument, and performs no shell interpretation.  The command
     is executed using fork and execlp.  Accordingly this function may
     be safer than `system' in situations where shell interpretation is
     not required.

     Example: (system* "echo" "foo" "bar")

 -- 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,20].
     The default priority is 0; lower priorities (in numerical terms)
     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 should be
     interpreted depending on 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.

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

     A full list of signals on the GNU system may be found in
     Standard Signals (libc).

 -- 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 [thread]]]
 -- C Function: scm_sigaction (signum, handler, flags)
 -- C Function: scm_sigaction_for_thread (signum, handler, flags,
          thread)
     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 HANDLER 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 HANDLER is provided, it is installed as the new handler for
     SIGNUM.  HANDLER 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.  When a scheme procedure has been
     specified, that procedure will run in the given THREAD.  When no
     thread has been given, the thread that made this call to
     `sigaction' is used.

     FLAGS is a `logior' (see Bitwise Operations) of the following
     (where provided by the system), or `0' for none.

      -- Variable: SA_NOCLDSTOP
          By default, `SIGCHLD' is signalled when a child process stops
          (ie. receives `SIGSTOP'), and when a child process terminates.
          With the `SA_NOCLDSTOP' flag, `SIGCHLD' is only signalled for
          termination, not stopping.

          `SA_NOCLDSTOP' has no effect on signals other than `SIGCHLD'.

      -- Variable: SA_RESTART
          If a signal occurs while in a system call, deliver the signal
          then restart the system call (as opposed to returning an
          `EINTR' error from that call).

          Guile always enables this flag where available, no matter what
          FLAGS are specified.  This avoids spurious error returns in
          low level operations.

     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. [FIXME: so what happens when it isn't?]

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

     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.

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

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

6.2.10 Pipes
------------

The following procedures are similar 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 mode
 -- Scheme Procedure: open-pipe* mode prog [args...]
     Execute a command in a subprocess, with a pipe to it or from it, or
     with pipes in both directions.

     `open-pipe' runs the shell COMMAND using `/bin/sh -c'.
     `open-pipe*' executes PROG directly, with the optional ARGS
     arguments (all strings).

     MODE should be one of the following values.  `OPEN_READ' is an
     input pipe, ie. to read from the subprocess.  `OPEN_WRITE' is an
     output pipe, ie. to write to it.

      -- Variable: OPEN_READ
      -- Variable: OPEN_WRITE
      -- Variable: OPEN_BOTH

     For an input pipe, the child's standard output is the pipe and
     standard input is inherited from `current-input-port'.  For an
     output pipe, the child's standard input is the pipe and standard
     output is inherited from `current-output-port'.  In all cases
     cases the child's standard error is inherited from
     `current-error-port' (see Default Ports).

     If those `current-X-ports' are not files of some kind, and hence
     don't have file descriptors for the child, then `/dev/null' is
     used instead.

     Care should be taken with `OPEN_BOTH', a deadlock will occur if
     both parent and child are writing, and waiting until the write
     completes before doing any reading.  Each direction has `PIPE_BUF'
     bytes of buffering (see Ports and File Descriptors), which
     will be enough for small writes, but not for say putting a big
     file through a filter.

 -- Scheme Procedure: open-input-pipe command
     Equivalent to `open-pipe' with mode `OPEN_READ'.

          (let* ((port (open-input-pipe "date --utc"))
                 (str  (read-line port)))
            (close-pipe port)
            str)
          => "Mon Mar 11 20:10:44 UTC 2002"

 -- Scheme Procedure: open-output-pipe command
     Equivalent to `open-pipe' with mode `OPEN_WRITE'.

          (let ((port (open-output-pipe "lpr")))
            (display "Something for the line printer.\n" port)
            (if (not (eqv? 0 (status:exit-val (close-pipe port))))
                (error "Cannot print")))

 -- Scheme Procedure: open-input-output-pipe command
     Equivalent to `open-pipe' with mode `OPEN_BOTH'.

 -- Scheme Procedure: close-pipe port
     Close a pipe created by `open-pipe', wait for the process to
     terminate, and return the wait status code.  The status is as per
     `waitpid' and can be decoded with `status:exit-val' etc (see
     Processes)

   `waitpid WAIT_ANY' should not be used when pipes are open, since it
can reap a pipe's child process, causing an error from a subsequent
`close-pipe'.

   `close-port' (see Closing) can close a pipe, but it doesn't reap
the child process.

   The garbage collector will close a pipe no longer in use, and reap
the child process with `waitpid'.  If the child hasn't yet terminated
the garbage collector doesn't block, but instead checks again in the
next GC.

   Many systems have per-user and system-wide limits on the number of
processes, and a system-wide limit on the number of pipes, so pipes
should be closed explicitly when no longer needed, rather than letting
the garbage collector pick them up at some later time.

6.2.11 Networking
-----------------

6.2.11.1 Network Address Conversion
...................................

This section describes procedures which convert internet addresses
between numeric and string formats.

IPv4 Address Conversion
.......................

An IPv4 Internet address is a 4-byte value, represented in Guile as an
integer in host byte order, so that say "0.0.0.1" is 1, or "1.0.0.0" is
16777216.

   Some underlying C functions use network byte order for addresses,
Guile converts as necessary so that at the Scheme level its host byte
order everywhere.

 -- Variable: INADDR_ANY
     For a server, this can be used with `bind' (see Network Sockets and Communication)
     to allow connections from any interface on
     the machine.

 -- Variable: INADDR_BROADCAST
     The broadcast address on the local network.

 -- Variable: INADDR_LOOPBACK
     The address of the local host using the loopback device, ie.
     `127.0.0.1'.

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

An IPv6 Internet address is a 16-byte value, represented in Guile as an
integer in host byte order, so that say "::1" is 1.

 -- Scheme Procedure: inet-ntop family address
 -- C Function: scm_inet_ntop (family, address)
     Convert a network address from an integer to a printable string.
     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.  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

6.2.11.2 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, one of the `AF' constants, such as
     `AF_INET' or `AF_INET6'.

 -- 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.  For `AF_INET'
     these are integer IPv4 address (see Network Address Conversion).

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

6.2.11.3 Network Socket Address
...............................

A "socket address" object identifies a socket endpoint for
communication.  In the case of `AF_INET' for instance, the socket
address object comprises the host address (or interface on the host)
and a port number which specifies a particular open socket in a running
client or server process.  A socket address object can be created with,

 -- Scheme Procedure: make-socket-address AF_INET ipv4addr port
 -- Scheme Procedure: make-socket-address AF_INET6 ipv6addr port
          [flowinfo [scopeid]]
 -- Scheme Procedure: make-socket-address AF_UNIX path
 -- C Function: scm_make_socket_address family address arglist
     Return a new socket address object.  The first argument is the
     address family, one of the `AF' constants, then the arguments vary
     according to the family.

     For `AF_INET' the arguments are an IPv4 network address number
     (see Network Address Conversion), and a port number.

     For `AF_INET6' the arguments are an IPv6 network address number
     and a port number.  Optional FLOWINFO and SCOPEID arguments may be
     given (both integers, default 0).

     For `AF_UNIX' the argument is a filename (a string).

     The C function `scm_make_socket_address' takes the FAMILY and
     ADDRESS arguments directly, then ARGLIST is a list of further
     arguments, being the port for IPv4, port and optional flowinfo and
     scopeid for IPv6, or the empty list `SCM_EOL' for Unix domain.

The following functions access the fields of a socket address object,

 -- Scheme Procedure: sockaddr:fam sa
     Return the address family from socket address object SA.  This is
     one of the `AF' constants (eg. `AF_INET').

 -- Scheme Procedure: sockaddr:path sa
     For an `AF_UNIX' socket address object SA, return the filename.

 -- Scheme Procedure: sockaddr:addr sa
     For an `AF_INET' or `AF_INET6' socket address object SA, return
     the network address number.

 -- Scheme Procedure: sockaddr:port sa
     For an `AF_INET' or `AF_INET6' socket address object SA, return
     the port number.

 -- Scheme Procedure: sockaddr:flowinfo sa
     For an `AF_INET6' socket address object SA, return the flowinfo
     value.

 -- Scheme Procedure: sockaddr:scopeid sa
     For an `AF_INET6' socket address object SA, return the scope ID
     value.

   The functions below convert to and from the C `struct sockaddr'
(see Address Formats (libc)).  That structure is a
generic type, an application can cast to or from `struct sockaddr_in',
`struct sockaddr_in6' or `struct sockaddr_un' according to the address
family.

   In a `struct sockaddr' taken or returned, the byte ordering in the
fields follows the C conventions (see Byte Order Conversion (libc)).
This means network byte order for `AF_INET' host
address (`sin_addr.s_addr') and port number (`sin_port'), and
`AF_INET6' port number (`sin6_port').  But at the Scheme level these
values are taken or returned in host byte order, so the port is an
ordinary integer, and the host address likewise is an ordinary integer
(as described in Network Address Conversion).

 -- C Function: struct sockaddr * scm_c_make_socket_address (SCM
          family, SCM address, SCM args, size_t *outsize)
     Return a newly-`malloc'ed `struct sockaddr' created from arguments
     like those taken by `scm_make_socket_address' above.

     The size (in bytes) of the `struct sockaddr' return is stored into
     `*OUTSIZE'.  An application must call `free' to release the
     returned structure when no longer required.

 -- C Function: SCM scm_from_sockaddr (const struct sockaddr *address,
          unsigned address_size)
     Return a Scheme socket address object from the C ADDRESS
     structure.  ADDRESS_SIZE is the size in bytes of ADDRESS.

 -- C Function: struct sockaddr * scm_to_sockaddr (SCM address, size_t
          *address_size)
     Return a newly-`malloc'ed `struct sockaddr' from a Scheme level
     socket address object.

     The size (in bytes) of the `struct sockaddr' return is stored into
     `*OUTSIZE'.  An application must call `free' to release the
     returned structure when no longer required.

6.2.11.4 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'; see
Ports and File Descriptors.

   Most systems have limits on how many files and sockets can be open,
so it's strongly recommended that socket ports be closed explicitly when
no longer required (see Ports).

   Some of the underlying C functions take values in network byte order,
but the convention in Guile is that at the Scheme level everything is
ordinary host byte order and conversions are made automatically where
necessary.

 -- 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.  The possible
     values for FAMILY are as follows, where supported by the system,

      -- Variable: PF_UNIX
      -- Variable: PF_INET
      -- Variable: PF_INET6

     The possible values for STYLE are as follows, again where
     supported by the system,

      -- Variable: SOCK_STREAM
      -- Variable: SOCK_DGRAM
      -- Variable: SOCK_RAW
      -- Variable: SOCK_RDM
      -- Variable: SOCK_SEQPACKET

     PROTO can be obtained from a protocol name using `getprotobyname'
     (see Network Databases).  A value of zero means the default
     protocol, which is usually right.

     A socket cannot by used for communication until it has been
     connected somewhere, usually with either `connect' or `accept'
     below.

 -- Scheme Procedure: socketpair family style proto
 -- C Function: scm_socketpair (family, style, proto)
     Return a pair, the `car' and `cdr' of which are two unnamed socket
     ports connected to each other.  The connection is full-duplex, so
     data can be transferred in either direction between the two.

     FAMILY, STYLE and PROTO are as per `socket' above.  But many
     systems only support socket pairs in the `PF_UNIX' family.  Zero
     is likely to be the only meaningful value for PROTO.

 -- Scheme Procedure: getsockopt sock level optname
 -- Scheme Procedure: setsockopt sock level optname value
 -- C Function: scm_getsockopt (sock, level, optname)
 -- C Function: scm_setsockopt (sock, level, optname, value)
     Get or set an option on socket port SOCK.  `getsockopt' returns
     the current value.  `setsockopt' sets a value and the return is
     unspecified.

     LEVEL is an integer specifying a protocol layer, either
     `SOL_SOCKET' for socket level options, or a protocol number from
     the `IPPROTO' constants or `getprotoent' (see Network Databases).

      -- Variable: SOL_SOCKET
      -- Variable: IPPROTO_IP
      -- Variable: IPPROTO_TCP
      -- Variable: IPPROTO_UDP

     OPTNAME is an integer specifying an option within the protocol
     layer.

     For `SOL_SOCKET' level the following OPTNAMEs are defined (when
     provided by the system).  For their meaning see Socket-Level Options (libc),
     or `man 7 socket'.

      -- Variable: SO_DEBUG
      -- Variable: SO_REUSEADDR
      -- Variable: SO_STYLE
      -- Variable: SO_TYPE
      -- Variable: SO_ERROR
      -- Variable: SO_DONTROUTE
      -- Variable: SO_BROADCAST
      -- Variable: SO_SNDBUF
      -- Variable: SO_RCVBUF
      -- Variable: SO_KEEPALIVE
      -- Variable: SO_OOBINLINE
      -- Variable: SO_NO_CHECK
      -- Variable: SO_PRIORITY
          The VALUE taken or returned is an integer.

      -- Variable: SO_LINGER
          The VALUE taken or returned is a pair of integers `(ENABLE .
          TIMEOUT)'.  On old systems without timeout support (ie.
          without `struct linger'), only ENABLE has an effect but the
          value in Guile is always a pair.

     For IP level (`IPPROTO_IP') the following OPTNAMEs are defined
     (when provided by the system).  See `man ip' for what they mean.

      -- Variable: IP_ADD_MEMBERSHIP
      -- Variable: IP_DROP_MEMBERSHIP
          These can be used only with `setsockopt', not `getsockopt'.
          VALUE is a pair `(MULTIADDR . INTERFACEADDR)' of integer IPv4
          addresses (see Network Address Conversion).  MULTIADDR is
          a multicast address to be added to or dropped from the
          interface INTERFACEADDR.  INTERFACEADDR can be `INADDR_ANY'
          to have the system select the interface.  INTERFACEADDR can
          also be an interface index number, on systems supporting that.

 -- 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 sockaddr
 -- Scheme Procedure: connect sock AF_INET ipv4addr port
 -- Scheme Procedure: connect sock AF_INET6 ipv6addr port [flowinfo
          [scopeid]]
 -- Scheme Procedure: connect sock AF_UNIX path
 -- C Function: scm_connect (sock, fam, address, args)
     Initiate a connection on socket port SOCK to a given address.  The
     destination is either a socket address object, or arguments the
     same as `make-socket-address' would take to make such an object
     (see Network Socket Address).  The return value is unspecified.

          (connect sock AF_INET INADDR_LOCALHOST 23)
          (connect sock (make-socket-address AF_INET INADDR_LOCALHOST 23))

 -- Scheme Procedure: bind sock sockaddr
 -- Scheme Procedure: bind sock AF_INET ipv4addr port
 -- Scheme Procedure: bind sock AF_INET6 ipv6addr port [flowinfo
          [scopeid]]
 -- Scheme Procedure: bind sock AF_UNIX path
 -- C Function: scm_bind (sock, fam, address, args)
     Bind socket port SOCK to the given address.  The address is either
     a socket address object, or arguments the same as
     `make-socket-address' would take to make such an object (see
     Network Socket Address).  The return value is unspecified.

     Generally a socket is only explicitly bound to a particular address
     when making a server, ie. to listen on a particular port.  For an
     outgoing connection the system will assign a local address
     automatically, if not already bound.

          (bind sock AF_INET INADDR_ANY 12345)
          (bind sock (make-socket-object AF_INET INADDR_ANY 12345))

 -- 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 from socket port SOCK which has been enabled
     for listening with `listen' above.  If there are no incoming
     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.  The `car' is a new socket port,
     connected and ready to communicate.  The `cdr' is a socket address
     object (see Network Socket Address) which is where the remote
     connection is from (like `getpeername' below).

     All communication takes place using the new socket returned.  The
     given SOCK remains bound and listening, and `accept' may be called
     on it again to get another incoming connection when desired.

 -- Scheme Procedure: getsockname sock
 -- C Function: scm_getsockname (sock)
     Return a socket address object which is the where SOCK is bound
     locally.  SOCK may have obtained its local address from `bind'
     (above), or if a `connect' is done with an otherwise unbound
     socket (which is usual) then the system will have assigned an
     address.

     Note that on many systems the address of a socket in the `AF_UNIX'
     namespace cannot be read.

 -- Scheme Procedure: getpeername sock
 -- C Function: scm_getpeername (sock)
     Return a socket address object which is where SOCK is connected
     to, ie. the remote endpoint.

     Note that on many systems the address of a socket in the `AF_UNIX'
     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 sockaddr [flags]
 -- Scheme Procedure: sendto sock message AF_INET ipv4addr port [flags]
 -- Scheme Procedure: sendto sock message AF_INET6 ipv6addr port
          [flowinfo [scopeid [flags]]]
 -- Scheme Procedure: sendto sock message AF_UNIX path [flags]
 -- C Function: scm_sendto (sock, message, fam, address, args_and_flags)
     Transmit the string MESSAGE as a datagram on socket port SOCK.
     The destination is specified either as a socket address object, or
     as arguments the same as would be taken by `make-socket-address'
     to create such an object (see Network Socket Address).

     The destination address may be followed by an optional FLAGS
     argument which is a `logior' (see Bitwise Operations) 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)))))

6.2.11.5 Network Socket Examples
................................

The following give examples of how to use network sockets.

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

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

6.2.12 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 (all of which are strings).

      -- Scheme Procedure: utsname:sysname un
          The name of the operating system.

      -- Scheme Procedure: utsname:nodename un
          The network name of the computer.

      -- Scheme Procedure: utsname:release un
          The current release level of the operating system
          implementation.

      -- Scheme Procedure: utsname:version un
          The current version level within the release of the operating
          system.

      -- Scheme Procedure: utsname:machine un
          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.

6.2.13 Locales
--------------

 -- Scheme Procedure: setlocale category [locale]
 -- C Function: scm_setlocale (category, locale)
     Get or set the current locale, used for various
     internationalizations.  Locales are strings, such as `sv_SE'.

     If LOCALE is given then the locale for the given CATEGORY is set
     and the new value returned.  If LOCALE is not given then the
     current value is returned.  CATEGORY should be one of the
     following values

      -- Variable: LC_ALL
      -- Variable: LC_COLLATE
      -- Variable: LC_CTYPE
      -- Variable: LC_MESSAGES
      -- Variable: LC_MONETARY
      -- Variable: LC_NUMERIC
      -- Variable: LC_TIME

     A common usage is `(setlocale LC_ALL "")', which initializes all
     categories based on standard environment variables (`LANG' etc).
     For full details on categories and locale names Locales and Internationalization (libc).

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

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

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

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

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

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

An option specification is an association list (see 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 section, 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.

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

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

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

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

6.4.1 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' (see 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 (see 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
(see Invoking Guile).

6.4.2 SRFI-0 - cond-expand
--------------------------

This SRFI lets a portable Scheme program test for the presence of
certain features, and adapt itself by using different blocks of code,
or fail if the necessary features are not available.  There's no module
to load, this is in the Guile core.

   A program designed only for Guile will generally not need this
mechanism, such a program can of course directly use the various
documented parts of Guile.

 -- syntax: cond-expand (feature body...) ...
     Expand to the BODY of the first clause whose FEATURE specification
     is satisfied.  It is an error if no FEATURE is satisfied.

     Features are symbols such as `srfi-1', and a feature specification
     can use `and', `or' and `not' forms to test combinations.  The
     last clause can be an `else', to be used if no other passes.

     For example, define a private version of `alist-cons' if SRFI-1 is
     not available.

          (cond-expand (srfi-1
                        )
                       (else
                        (define (alist-cons key val alist)
                          (cons (cons key val) alist))))

     Or demand a certain set of SRFIs (list operations, string ports,
     `receive' and string operations), failing if they're not available.

          (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
                        ))

The Guile core has the following features,

     guile
     r5rs
     srfi-0
     srfi-4
     srfi-6
     srfi-13
     srfi-14

   Other SRFI feature symbols are defined once their code has been
loaded with `use-modules', since only then are their bindings available.

   The `--use-srfi' command line option (see Invoking Guile) is a
good way to load SRFIs to satisfy `cond-expand' when running a portable
program.

   Testing the `guile' feature allows a program to adapt itself to the
Guile module system, but still run on other Scheme systems.  For
example the following demands SRFI-8 (`receive'), but also knows how to
load it with the Guile mechanism.

     (cond-expand (srfi-8
                   )
                  (guile
                   (use-modules (srfi srfi-8))))

   It should be noted that `cond-expand' is separate from the
`*features*' mechanism (see Feature Tracking), feature symbols in
one are unrelated to those in the other.

6.4.3 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 Lists
and Pairs.

6.4.3.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: list-copy lst
     Return a new list containing the elements of the list LST.

     This function differs from the core `list-copy' (see List Constructors)
     in accepting improper lists too.  And if LST is
     not a pair at all then it's treated as the final tail of an
     improper list and simply returned.

 -- 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 numbers, starting from START and
     adding STEP each time.  The default START is 0, the default STEP
     is 1.  For example,

          (iota 6)        => (0 1 2 3 4 5)
          (iota 4 2.5 -2) => (2.5 0.5 -1.5 -3.5)

     This function takes its name from the corresponding primitive in
     the APL language.

6.4.3.2 Predicates
..................

The procedures in this section test specific properties of lists.

 -- Scheme Procedure: proper-list? obj
     Return `#t' if OBJ is a proper list, or `#f' otherwise.  This is
     the same as the core `list?' (see List Predicates).

     A proper list is a list which ends with the empty list `()' in the
     usual way.  The empty list `()' itself is a proper list too.

          (proper-list? '(1 2 3))  => #t
          (proper-list? '())       => #t

 -- Scheme Procedure: circular-list? obj
     Return `#t' if OBJ is a circular list, or `#f' otherwise.

     A circular list is a list where at some point the `cdr' refers
     back to a previous pair in the list (either the start or some later
     point), so that following the `cdr's takes you around in a circle,
     with no end.

          (define x (list 1 2 3 4))
          (set-cdr! (last-pair x) (cddr x))
          x => (1 2 3 4 3 4 3 4 ...)
          (circular-list? x)  => #t

 -- Scheme Procedure: dotted-list? obj
     Return `#t' if OBJ is a dotted list, or `#f' otherwise.

     A dotted list is a list where the `cdr' of the last pair is not
     the empty list `()'.  Any non-pair OBJ is also considered a dotted
     list, with length zero.

          (dotted-list? '(1 2 . 3))  => #t
          (dotted-list? 99)          => #t

   It will be noted that any Scheme object passes exactly one of the
above three tests `proper-list?', `circular-list?' and `dotted-list?'.
Non-lists are `dotted-list?', finite lists are either `proper-list?' or
`dotted-list?', and infinite lists are `circular-list?'.

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

6.4.3.3 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.  The
     return shares a common tail with 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' always returns a new list, even when I is zero.
     `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.

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

     `concatenate' is the same as `(apply append LIST-OF-LISTS)'.  It
     exists because some Scheme implementations have a limit on the
     number of arguments a function takes, which the `apply' might
     exceed.  In Guile there is no such limit.

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

 -- Scheme Procedure: count pred lst1 ... lstN
     Return a count of the number of times PRED returns true when
     called on elements from the given lists.

     PRED is called with N parameters `(PRED ELEM1 ... ELEMN)', each
     element being from the corresponding LST1 ... LSTN.  The first
     call is with the first element of each list, the second with the
     second element from each, and so on.

     Counting stops when the end of the shortest list is reached.  At
     least one list must be non-circular.

6.4.3.5 Fold, Unfold & Map
..........................

 -- Scheme Procedure: fold proc init lst1 ... lstN
 -- Scheme Procedure: fold-right proc init lst1 ... lstN
     Apply PROC to the elements of LST1 ... LSTN to build a result, and
     return that result.

     Each PROC call is `(PROC ELEM1 ...  ELEMN PREVIOUS)', where ELEM1
     is from LST1, through ELEMN from LSTN.  PREVIOUS is the return
     from the previous call to PROC, or the given INIT for the first
     call.  If any list is empty, just INIT is returned.

     `fold' works through the list elements from first to last.  The
     following shows a list reversal and the calls it makes,

          (fold cons '() '(1 2 3))

          (cons 1 '())
          (cons 2 '(1))
          (cons 3 '(2 1)
          => (3 2 1)

     `fold-right' works through the list elements from last to first,
     ie. from the right.  So for example the following finds the longest
     string, and the last among equal longest,

          (fold-right (lambda (str prev)
                        (if (> (string-length str) (string-length prev))
                            str
                            prev))
                      ""
                      '("x" "abc" "xyz" "jk"))
          => "xyz"

     If LST1 through LSTN have different lengths, `fold' stops when the
     end of the shortest is reached; `fold-right' commences at the last
     element of the shortest.  Ie. elements past the length of the
     shortest are ignored in the other LSTs.  At least one LST must be
     non-circular.

     `fold' should be preferred over `fold-right' if the order of
     processing doesn't matter, or can be arranged either way, since
     `fold' is a little more efficient.

     The way `fold' builds a result from iterating is quite general, it
     can do more than other iterations like say `map' or `filter'.  The
     following for example removes adjacent duplicate elements from a
     list,

          (define (delete-adjacent-duplicates lst)
            (fold-right (lambda (elem ret)
                          (if (equal? elem (first ret))
                              ret
                              (cons elem ret)))
                        (list (last lst))
                        lst))
          (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
          => (1 2 3 4 5)

     Clearly the same sort of thing can be done with a `for-each' and a
     variable in which to build the result, but a self-contained PROC
     can be re-used in multiple contexts, where a `for-each' would have
     to be written out each time.

 -- Scheme Procedure: pair-fold proc init lst1 ... lstN
 -- Scheme Procedure: pair-fold-right proc init lst1 ... lstN
     The same as `fold' and `fold-right', but apply PROC to the pairs
     of the lists instead of the list elements.

 -- Scheme Procedure: reduce proc default lst
 -- Scheme Procedure: reduce-right proc default lst
     `reduce' is a variant of `fold', where the first call to PROC is
     on two elements from LST, rather than one element and a given
     initial value.

     If LST is empty, `reduce' returns DEFAULT (this is the only use
     for DEFAULT).  If LST has just one element then that's the return
     value.  Otherwise PROC is called on the elements of LST.

     Each PROC call is `(PROC ELEM PREVIOUS)', where ELEM is from LST
     (the second and subsequent elements of LST), and PREVIOUS is the
     return from the previous call to PROC.  The first element of LST
     is the PREVIOUS for the first call to PROC.

     For example, the following adds a list of numbers, the calls made
     to `+' are shown.  (Of course `+' accepts multiple arguments and
     can add a list directly, with `apply'.)

          (reduce + 0 '(5 6 7)) => 18

          (+ 6 5)  => 11
          (+ 7 11) => 18

     `reduce' can be used instead of `fold' where the INIT value is an
     "identity", meaning a value which under PROC doesn't change the
     result, in this case 0 is an identity since `(+ 5 0)' is just 5.
     `reduce' avoids that unnecessary call.

     `reduce-right' is a similar variation on `fold-right', working
     from the end (ie. the right) of LST.  The last element of LST is
     the PREVIOUS for the first call to PROC, and the ELEM values go
     from the second last.

     `reduce' should be preferred over `reduce-right' if the order of
     processing doesn't matter, or can be arranged either way, since
     `reduce' is a little more efficient.

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

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

   The `filter' and `filter!' functions are implemented in the Guile
core, see List Modification.

 -- Scheme Procedure: partition pred lst
 -- Scheme Procedure: partition! pred lst
     Split LST into those elements which do and don't satisfy the
     predicate PRED.

     The return is two values (see Multiple Values), the first
     being a list of all elements from LST which satisfy PRED, the
     second a list of those which do not.

     The elements in the result lists are in the same order as in LST
     but the order in which the calls `(PRED elem)' are made on the
     list elements is unspecified.

     `partition' does not change LST, but one of the returned lists may
     share a tail with it.  `partition!' may modify LST to construct
     its return.

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

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

     Note that the name `break' conflicts with the `break' binding
     established by `while' (see while do).  Applications wanting
     to use `break' from within a `while' loop will need to make a new
     define under a different name.

 -- Scheme Procedure: any pred lst1 lst2 ... lstN
     Test whether any set of elements from LST1 ... lstN satisfies
     PRED.  If so the return value is the return from the successful
     PRED call, or if not the return is `#f'.

     Each PRED call is `(PRED ELEM1 ...  ELEMN)' taking an element from
     each LST.  The calls are made successively for the first, second,
     etc elements of the lists, stopping when PRED returns non-`#f', or
     when the end of the shortest list is reached.

     The PRED call on the last set of elements (ie. when the end of the
     shortest list has been reached), if that point is reached, is a
     tail call.

 -- Scheme Procedure: every pred lst1 lst2 ... lstN
     Test whether every set of elements from LST1 ... lstN satisfies
     PRED.  If so the return value is the return from the final PRED
     call, or if not the return is `#f'.

     Each PRED call is `(PRED ELEM1 ...  ELEMN)' taking an element from
     each LST.  The calls are made successively for the first, second,
     etc elements of the lists, stopping if PRED returns `#f', or when
     the end of any of the lists is reached.

     The PRED call on the last set of elements (ie. when the end of the
     shortest list has been reached) is a tail call.

     If one of LST1 ... LSTN is empty then no calls to PRED are made,
     and the return is `#t'.

 -- Scheme Procedure: list-index pred lst1 ... lstN
     Return the index of the first set of elements, one from each of
     LST1...LSTN, which satisfies PRED.

     PRED is called as `(PRED elem1 ... elemN)'.  Searching stops when
     the end of the shortest LST is reached.  The return index starts
     from 0 for the first set of elements.  If no set of elements pass
     then the return is `#f'.

          (list-index odd? '(2 4 6 9))      => 3
          (list-index = '(1 2 3) '(3 1 2))  => #f

 -- Scheme Procedure: member x lst [=]
     Return the first sublist of LST whose CAR is equal to X.  If X
     does not appear in LST, return `#f'.

     Equality is determined by `equal?', or by the equality predicate =
     if given.  = is called `(= X elem)', ie. with the given X first,
     so for example to find the first element greater than 5,

          (member 5 '(3 5 1 7 2 9) <) => (7 2 9)

     This version of `member' extends the core `member' (see List Searching)
     by accepting an equality predicate.

6.4.3.8 Deleting
................

 -- Scheme Procedure: delete x lst [=]
 -- Scheme Procedure: delete! x lst [=]
     Return a list containing the elements of LST but with those equal
     to X deleted.  The returned elements will be in the same order as
     they were in LST.

     Equality is determined by the = predicate, or `equal?' if not
     given.  An equality call is made just once for each element, but
     the order in which the calls are made on the elements is
     unspecified.

     The equality calls are always `(= x elem)', ie. the given X is
     first.  This means for instance elements greater than 5 can be
     deleted with `(delete 5 lst <)'.

     `delete' does not modify LST, but the return might share a common
     tail with LST.  `delete!' may modify the structure of LST to
     construct its return.

     These functions extend the core `delete' and `delete!' (see List Modification)
     in accepting an equality predicate.  See also
     `lset-difference' (see SRFI-1 Set Operations) for deleting
     multiple elements from a list.

 -- Scheme Procedure: delete-duplicates lst [=]
 -- Scheme Procedure: delete-duplicates! lst [=]
     Return a list containing the elements of LST but without
     duplicates.

     When elements are equal, only the first in LST is retained.  Equal
     elements can be anywhere in LST, they don't have to be adjacent.
     The returned list will have the retained elements in the same
     order as they were in LST.

     Equality is determined by the = predicate, or `equal?' if not
     given.  Calls `(= x y)' are made with element X being before Y in
     LST.  A call is made at most once for each combination, but the
     sequence of the calls across the elements is unspecified.

     `delete-duplicates' does not modify LST, but the return might
     share a common tail with LST.  `delete-duplicates!' may modify the
     structure of LST to construct its return.

     In the worst case, this is an O(N^2) algorithm because it must
     check each element against all those preceding it.  For long lists
     it is more efficient to sort and then compare only adjacent
     elements.

6.4.3.9 Association Lists
.........................

Association lists are described in detail in section 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.

     This function extends the core `assoc' by accepting an equality
     predicate.  (see Association Lists)

 -- Scheme Procedure: alist-cons key datum alist
     Cons a new association KEY and DATUM onto ALIST and return the
     result.  This is equivalent to

          (cons (cons KEY DATUM) ALIST)

     `acons' (see Adding or Setting Alist Entries) in the Guile
     core does the same thing.

 -- 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 elements of ALIST but with those
     elements whose keys are equal to KEY deleted.  The returned
     elements will be in the same order as they were in ALIST.

     Equality is determined by the = predicate, or `equal?' if not
     given.  The order in which elements are tested is unspecified, but
     each equality call is made `(= key alistkey)', ie. the given KEY
     parameter is first and the key from ALIST second.  This means for
     instance all associations with a key greater than 5 can be removed
     with `(alist-delete 5 alist <)'.

     `alist-delete' does not modify ALIST, but the return might share a
     common tail with ALIST.  `alist-delete!' may modify the list
     structure of ALIST to construct its return.

6.4.3.10 Set Operations on Lists
................................

Lists can be used to represent sets of objects.  The procedures in this
section operate on such lists as sets.

   Note that lists are not an efficient way to implement large sets.
The procedures here typically take time MxN when operating on M and N
element lists.  Other data structures like trees, bitsets (see Bit Vectors)
or hash tables (see Hash Tables) are faster.

   All these procedures take an equality predicate as the first
argument.  This predicate is used for testing the objects in the list
sets for sameness.  This predicate must be consistent with `eq?' (see
Equality) in the sense that if two list elements are `eq?' then they
must also be equal under the predicate.  This simply means a given
object must be equal to itself.

 -- Scheme Procedure: lset<= = list1 list2 ...
     Return `#t' if each list is a subset of the one following it.  Ie.
     LIST1 a subset of LIST2, LIST2 a subset of LIST3, etc, for as many
     lists as given.  If only one list or no lists are given then the
     return is `#t'.

     A list X is a subset of Y if each element of X is equal to some
     element in Y.  Elements are compared using the given = procedure,
     called as `(= xelem yelem)'.

          (lset<= eq?)                      => #t
          (lset<= eqv? '(1 2 3) '(1))       => #f
          (lset<= eqv? '(1 3 2) '(4 3 1 2)) => #t

 -- Scheme Procedure: lset= = list1 list2 ...
     Return `#t' if all argument lists are set-equal.  LIST1 is
     compared to LIST2, LIST2 to LIST3, etc, for as many lists as
     given.  If only one list or no lists are given then the return is
     `#t'.

     Two lists X and Y are set-equal if each element of X is equal to
     some element of Y and conversely each element of Y is equal to
     some element of X.  The order of the elements in the lists doesn't
     matter.  Element equality is determined with the given =
     procedure, called as `(= xelem yelem)', but exactly which calls
     are made is unspecified.

          (lset= eq?)                      => #t
          (lset= eqv? '(1 2 3) '(3 2 1))   => #t
          (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) => #t

 -- Scheme Procedure: lset-adjoin = list elem1 ...
     Add to LIST any of the given ELEMs not already in the list.  ELEMs
     are `cons'ed onto the start of LIST (so the return shares a common
     tail with LIST), but the order they're added is unspecified.

     The given = procedure is used for comparing elements, called as
     `(= listelem elem)', ie. the second argument is one of the given
     ELEM parameters.

          (lset-adjoin eqv? '(1 2 3) 4 1 5) => (5 4 1 2 3)

 -- Scheme Procedure: lset-union = list1 list2 ...
 -- Scheme Procedure: lset-union! = list1 list2 ...
     Return the union of the argument list sets.  The result is built by
     taking the union of LIST1 and LIST2, then the union of that with
     LIST3, etc, for as many lists as given.  For one list argument
     that list itself is the result, for no list arguments the result
     is the empty list.

     The union of two lists X and Y is formed as follows.  If X is
     empty then the result is Y.  Otherwise start with X as the result
     and consider each Y element (from first to last).  A Y element not
     equal to something already in the result is `cons'ed onto the
     result.

     The given = procedure is used for comparing elements, called as
     `(= relem yelem)'.  The first argument is from the result
     accumulated so far, and the second is from the list being union-ed
     in.  But exactly which calls are made is otherwise unspecified.

     Notice that duplicate elements in LIST1 (or the first non-empty
     list) are preserved, but that repeated elements in subsequent lists
     are only added once.

          (lset-union eqv?)                          => ()
          (lset-union eqv? '(1 2 3))                 => (1 2 3)
          (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) => (5 4 1 2 1 3)

     `lset-union' doesn't change the given lists but the result may
     share a tail with the first non-empty list.  `lset-union!' can
     modify all of the given lists to form the result.

 -- Scheme Procedure: lset-intersection = list1 list2 ...
 -- Scheme Procedure: lset-intersection! = list1 list2 ...
     Return the intersection of LIST1 with the other argument lists,
     meaning those elements of LIST1 which are also in all of LIST2
     etc.  For one list argument, just that list is returned.

     The test for an element of LIST1 to be in the return is simply
     that it's equal to some element in each of LIST2 etc.  Notice this
     means an element appearing twice in LIST1 but only once in each of
     LIST2 etc will go into the return twice.  The return has its
     elements in the same order as they were in LIST1.

     The given = procedure is used for comparing elements, called as
     `(= elem1 elemN)'.  The first argument is from LIST1 and the
     second is from one of the subsequent lists.  But exactly which
     calls are made and in what order is unspecified.

          (lset-intersection eqv? '(x y))                        => (x y)
          (lset-intersection eqv? '(1 2 3) '(4 3 2))             => (2 3)
          (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) => (2 2)

     The return from `lset-intersection' may share a tail with LIST1.
     `lset-intersection!' may modify LIST1 to form its result.

 -- Scheme Procedure: lset-difference = list1 list2 ...
 -- Scheme Procedure: lset-difference! = list1 list2 ...
     Return LIST1 with any elements in LIST2, LIST3 etc removed (ie.
     subtracted).  For one list argument, just that list is returned.

     The given = procedure is used for comparing elements, called as
     `(= elem1 elemN)'.  The first argument is from LIST1 and the
     second from one of the subsequent lists.  But exactly which calls
     are made and in what order is unspecified.

          (lset-difference eqv? '(x y))             => (x y)
          (lset-difference eqv? '(1 2 3) '(3 1))    => (2)
          (lset-difference eqv? '(1 2 3) '(3) '(2)) => (1)

     The return from `lset-difference' may share a tail with LIST1.
     `lset-difference!' may modify LIST1 to form its result.

 -- Scheme Procedure: lset-diff+intersection = list1 list2 ...
 -- Scheme Procedure: lset-diff+intersection! = list1 list2 ...
     Return two values (see Multiple Values), the difference and
     intersection of the argument lists as per `lset-difference' and
     `lset-intersection' above.

     For two list arguments this partitions LIST1 into those elements
     of LIST1 which are in LIST2 and not in LIST2.  (But for more than
     two arguments there can be elements of LIST1 which are neither
     part of the difference nor the intersection.)

     One of the return values from `lset-diff+intersection' may share a
     tail with LIST1.  `lset-diff+intersection!' may modify LIST1 to
     form its results.

 -- Scheme Procedure: lset-xor = list1 list2 ...
 -- Scheme Procedure: lset-xor! = list1 list2 ...
     Return an XOR of the argument lists.  For two lists this means
     those elements which are in exactly one of the lists.  For more
     than two lists it means those elements which appear in an odd
     number of the lists.

     To be precise, the XOR of two lists X and Y is formed by taking
     those elements of X not equal to any element of Y, plus those
     elements of Y not equal to any element of X.  Equality is
     determined with the given = procedure, called as `(= e1 e2)'.  One
     argument is from X and the other from Y, but which way around is
     unspecified.  Exactly which calls are made is also unspecified, as
     is the order of the elements in the result.

          (lset-xor eqv? '(x y))             => (x y)
          (lset-xor eqv? '(1 2 3) '(4 3 2))  => (4 1)

     The return from `lset-xor' may share a tail with one of the list
     arguments.  `lset-xor!' may modify LIST1 to form its result.

6.4.4 SRFI-2 - and-let*
-----------------------

The following syntax can be obtained with

     (use-modules (srfi srfi-2))

 -- library syntax: and-let* (clause ...) body ...
     A combination of `and' and `let*'.

     Each CLAUSE is evaluated in turn, and if `#f' is obtained then
     evaluation stops and `#f' is returned.  If all are non-`#f' then
     BODY is evaluated and the last form gives the return value, or if
     BODY is empty then the result is `#t'.  Each CLAUSE should be one
     of the following,

    `(symbol expr)'
          Evaluate EXPR, check for `#f', and bind it to SYMBOL.  Like
          `let*', that binding is available to subsequent clauses.

    `(expr)'
          Evaluate EXPR and check for `#f'.

    `symbol'
          Get the value bound to SYMBOL and check for `#f'.

     Notice that `(expr)' has an "extra" pair of parentheses, for
     instance `((eq? x y))'.  One way to remember this is to imagine
     the `symbol' in `(symbol expr)' is omitted.

     `and-let*' is good for calculations where a `#f' value means
     termination, but where a non-`#f' value is going to be needed in
     subsequent expressions.

     The following illustrates this, it returns text between brackets
     `[...]' in a string, or `#f' if there are no such brackets (ie.
     either `string-index' gives `#f').

          (define (extract-brackets str)
            (and-let* ((start (string-index str #\[))
                       (end   (string-index str #\] start)))
              (substring str (1+ start) end)))

     The following shows plain variables and expressions tested too.
     `diagnostic-levels' is taken to be an alist associating a
     diagnostic type with a level.  `str' is printed only if the type
     is known and its level is high enough.

          (define (show-diagnostic type str)
            (and-let* (want-diagnostics
                       (level (assq-ref diagnostic-levels type))
                       ((>= level current-diagnostic-level)))
              (display str)))

     The advantage of `and-let*' is that an extended sequence of
     expressions and tests doesn't require lots of nesting as would
     arise from separate `and' and `let*', or from `cond' with `=>'.

6.4.5 SRFI-4 - Homogeneous numeric vector datatypes
---------------------------------------------------

The SRFI-4 procedures and data types are always available, see
Uniform Numeric Vectors.

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

6.4.7 SRFI-8 - receive
----------------------

`receive' is a syntax for making the handling of multiple-value
procedures easier.  It is documented in Multiple Values.

6.4.8 SRFI-9 - define-record-type
---------------------------------

This SRFI is a syntax for defining new record types and creating
predicate, constructor, and field getter and setter functions.  In
Guile this is simply an alternate interface to the core record
functionality (see Records).  It can be used with,

     (use-modules (srfi srfi-9))

 -- library syntax: define-record-type type
          (constructor fieldname ...)
          predicate
          (fieldname accessor [modifier]) ...

     Create a new record type, and make various `define's for using it.
     This syntax can only occur at the top-level, not nested within
     some other form.

     TYPE is bound to the record type, which is as per the return from
     the core `make-record-type'.  TYPE also provides the name for the
     record, as per `record-type-name'.

     CONSTRUCTOR is bound to a function to be called as `(CONSTRUCTOR
     fieldval ...)' to create a new record of this type.  The arguments
     are initial values for the fields, one argument for each field, in
     the order they appear in the `define-record-type' form.

     The FIELDNAMEs provide the names for the record fields, as per the
     core `record-type-fields' etc, and are referred to in the
     subsequent accessor/modifier forms.

     PREDICTATE is bound to a function to be called as `(PREDICATE
     obj)'.  It returns `#t' or `#f' according to whether OBJ is a
     record of this type.

     Each ACCESSOR is bound to a function to be called `(ACCESSOR
     record)' to retrieve the respective field from a RECORD.
     Similarly each MODIFIER is bound to a function to be called
     `(MODIFIER record val)' to set the respective field in a RECORD.

An example will illustrate typical usage,

     (define-record-type employee-type
       (make-employee name age salary)
       employee?
       (name    get-employee-name)
       (age     get-employee-age    set-employee-age)
       (salary  get-employee-salary set-employee-salary))

   This creates a new employee data type, with name, age and salary
fields.  Accessor functions are created for each field, but no modifier
function for the name (the intention in this example being that it's
established only when an employee object is created).  These can all
then be used as for example,

     employee-type => #<record-type employee-type>

     (define fred (make-employee "Fred" 45 20000.00))

     (employee? fred)        => #t
     (get-employee-age fred) => 45
     (set-employee-salary fred 25000.00)  ;; pay rise

   The functions created by `define-record-type' are ordinary top-level
`define's.  They can be redefined or `set!' as desired, exported from a
module, etc.

6.4.9 SRFI-10 - Hash-Comma Reader Extension
-------------------------------------------

This SRFI implements a reader extension `#,()' called hash-comma.  It
allows the reader to give new kinds of objects, for use both in data
and as constants or literals in source code.  This feature is available
with

     (use-modules (srfi srfi-10))

The new read syntax is of the form

     #,(TAG ARG...)

where TAG is a symbol and the ARGs are objects taken as parameters.
TAGs are registered with the following procedure.

 -- Scheme Procedure: define-reader-ctor tag proc
     Register PROC as the constructor for a hash-comma read syntax
     starting with symbol TAG, ie. #,(TAG arg...).  PROC is called with
     the given arguments `(PROC arg...)' and the object it returns is
     the result of the read.

For example, a syntax giving a list of N copies of an object.

     (define-reader-ctor 'repeat
       (lambda (obj reps)
         (make-list reps obj)))

     (display '#,(repeat 99 3))
     -| (99 99 99)

   Notice the quote ' when the #,( ) is used.  The `repeat' handler
returns a list and the program must quote to use it literally, the same
as any other list.  Ie.

     (display '#,(repeat 99 3))
     =>
     (display '(99 99 99))

   When a handler returns an object which is self-evaluating, like a
number or a string, then there's no need for quoting, just as there's
no need when giving those directly as literals.  For example an
addition,

     (define-reader-ctor 'sum
       (lambda (x y)
         (+ x y)))
     (display #,(sum 123 456)) -| 579

   A typical use for #,() is to get a read syntax for objects which
don't otherwise have one.  For example, the following allows a hash
table to be given literally, with tags and values, ready for fast
lookup.

     (define-reader-ctor 'hash
       (lambda elems
         (let ((table (make-hash-table)))
           (for-each (lambda (elem)
                       (apply hash-set! table elem))
                     elems)
           table)))

     (define (animal->family animal)
       (hash-ref '#,(hash ("tiger" "cat")
                          ("lion"  "cat")
                          ("wolf"  "dog"))
                 animal))

     (animal->family "lion") => "cat"

   Or for example the following is a syntax for a compiled regular
expression (see Regular Expressions).

     (use-modules (ice-9 regex))

     (define-reader-ctor 'regexp make-regexp)

     (define (extract-angs str)
       (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
         (and match
              (match:substring match 1))))

     (extract-angs "foo <BAR> quux") => "BAR"

   #,() is somewhat similar to `define-macro' (see Macros) in that
handler code is run to produce a result, but #,() operates at the read
stage, so it can appear in data for `read' (see Scheme Read), not
just in code to be executed.

   Because #,() is handled at read-time it has no direct access to
variables etc.  A symbol in the arguments is just a symbol, not a
variable reference.  The arguments are essentially constants, though
the handler procedure can use them in any complicated way it might want.

   Once `(srfi srfi-10)' has loaded, #,() is available globally,
there's no need to use `(srfi srfi-10)' in later modules.  Similarly
the tags registered are global and can be used anywhere once registered.

   There's no attempt to record what previous #,() forms have been
seen, if two identical forms occur then two calls are made to the
handler procedure.  The handler might like to maintain a cache or
similar to avoid making copies of large objects, depending on expected
usage.

   In code the best uses of #,() are generally when there's a lot of
objects of a particular kind as literals or constants.  If there's just
a few then some local variables and initializers are fine, but that
becomes tedious and error prone when there's a lot, and the anonymous
and compact syntax of #,() is much better.

6.4.10 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*' (see 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.

6.4.11 SRFI-13 - String Library
-------------------------------

The SRFI-13 procedures are always available, see Strings.

6.4.12 SRFI-14 - Character-set Library
--------------------------------------

The SRFI-14 data type and procedures are always available, see
Character Sets.

6.4.13 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' (see 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.

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

6.4.15 SRFI-19 - Time/Date Library
----------------------------------

This is an implementation of the SRFI-19 time/date library.  The
functions and variables described here are provided by

     (use-modules (srfi srfi-19))

   *Caution*: The current code in this module incorrectly extends the
Gregorian calendar leap year rule back prior to the introduction of
those reforms in 1582 (or the appropriate year in various countries).
The Julian calendar was used prior to 1582, and there were 10 days
skipped for the reform, but the code doesn't implement that.

   This will be fixed some time.  Until then calculations for 1583
onwards are correct, but prior to that any day/month/year and day of
the week calculations are wrong.

6.4.15.1 SRFI-19 Introduction
.............................

This module implements time and date representations and calculations,
in various time systems, including universal time (UTC) and atomic time
(TAI).

   For those not familiar with these time systems, TAI is based on a
fixed length second derived from oscillations of certain atoms.  UTC
differs from TAI by an integral number of seconds, which is increased
or decreased at announced times to keep UTC aligned to a mean solar day
(the orbit and rotation of the earth are not quite constant).

   So far, only increases in the TAI <-> UTC difference have been
needed.  Such an increase is a "leap second", an extra second of TAI
introduced at the end of a UTC day.  When working entirely within UTC
this is never seen, every day simply has 86400 seconds.  But when
converting from TAI to a UTC date, an extra 23:59:60 is present, where
normally a day would end at 23:59:59.  Effectively the UTC second from
23:59:59 to 00:00:00 has taken two TAI seconds.

   In the current implementation, the system clock is assumed to be UTC,
and a table of leap seconds in the code converts to TAI.  See comments
in `srfi-19.scm' for how to update this table.

   Also, for those not familiar with the terminology, a "Julian Day" is
a real number which is a count of days and fraction of a day, in UTC,
starting from -4713-01-01T12:00:00Z, ie. midday Monday 1 Jan 4713 B.C.
A "Modified Julian Day" is the same, but starting from
1858-11-17T00:00:00Z, ie. midnight 17 November 1858 UTC.  That time is
julian day 2400000.5.

6.4.15.2 SRFI-19 Time
.....................

A "time" object has type, seconds and nanoseconds fields representing a
point in time starting from some epoch.  This is an arbitrary point in
time, not just a time of day.  Although times are represented in
nanoseconds, the actual resolution may be lower.

   The following variables hold the possible time types.  For instance
`(current-time time-process)' would give the current CPU process time.

 -- Variable: time-utc
     Universal Coordinated Time (UTC).

 -- Variable: time-tai
     International Atomic Time (TAI).

 -- Variable: time-monotonic
     Monotonic time, meaning a monotonically increasing time starting
     from an unspecified epoch.

     Note that in the current implementation `time-monotonic' is the
     same as `time-tai', and unfortunately is therefore affected by
     adjustments to the system clock.  Perhaps this will change in the
     future.

 -- Variable: time-duration
     A duration, meaning simply a difference between two times.

 -- Variable: time-process
     CPU time spent in the current process, starting from when the
     process began.

 -- Variable: time-thread
     CPU time spent in the current thread.  Not currently implemented.

 -- Function: time? obj
     Return `#t' if OBJ is a time object, or `#f' if not.

 -- Function: make-time type nanoseconds seconds
     Create a time object with the given TYPE, SECONDS and NANOSECONDS.

 -- Function: time-type time
 -- Function: time-nanosecond time
 -- Function: time-second time
 -- Function: set-time-type! time type
 -- Function: set-time-nanosecond! time nsec
 -- Function: set-time-second! time sec
     Get or set the type, seconds or nanoseconds fields of a time
     object.

     `set-time-type!' merely changes the field, it doesn't convert the
     time value.  For conversions, see SRFI-19 Time/Date conversions.

 -- Function: copy-time time
     Return a new time object, which is a copy of the given TIME.

 -- Function: current-time [type]
     Return the current time of the given TYPE.  The default TYPE is
     `time-utc'.

     Note that the name `current-time' conflicts with the Guile core
     `current-time' function (see Time).  Applications wanting to
     use both will need to use a different name for one of them.

 -- Function: time-resolution [type]
     Return the resolution, in nanoseconds, of the given time TYPE.
     The default TYPE is `time-utc'.

 -- Function: time<=? t1 t2
 -- Function: time<? t1 t2
 -- Function: time=? t1 t2
 -- Function: time>=? t1 t2
 -- Function: time>? t1 t2
     Return `#t' or `#f' according to the respective relation between
     time objects T1 and T2.  T1 and T2 must be the same time type.

 -- Function: time-difference t1 t2
 -- Function: time-difference! t1 t2
     Return a time object of type `time-duration' representing the
     period between T1 and T2.  T1 and T2 must be the same time type.

     `time-difference' returns a new time object, `time-difference!'
     may modify T1 to form its return.

 -- Function: add-duration time duration
 -- Function: add-duration! time duration
 -- Function: subtract-duration time duration
 -- Function: subtract-duration! time duration
     Return a time object which is TIME with the given DURATION added
     or subtracted.  DURATION must be a time object of type
     `time-duration'.

     `add-duration' and `subtract-duration' return a new time object.
     `add-duration!' and `subtract-duration!' may modify the given TIME
     to form their return.

6.4.15.3 SRFI-19 Date
.....................

A "date" object represents a date in the Gregorian calendar and a time
of day on that date in some timezone.

   The fields are year, month, day, hour, minute, second, nanoseconds
and timezone.  A date object is immutable, its fields can be read but
they cannot be modified once the object is created.

 -- Function: date? obj
     Return `#t' if OBJ is a date object, or `#f' if not.

 -- Function: make-date nsecs seconds minutes hours date month year
          zone-offset
     Create a new date object.

 -- Function: date-nanosecond date
     Nanoseconds, 0 to 999999999.

 -- Function: date-second date
     Seconds, 0 to 59, or 60 for a leap second.  60 is never seen when
     working entirely within UTC, it's only when converting to or from
     TAI.

 -- Function: date-minute date
     Minutes, 0 to 59.

 -- Function: date-hour date
     Hour, 0 to 23.

 -- Function: date-day date
     Day of the month, 1 to 31 (or less, according to the month).

 -- Function: date-month date
     Month, 1 to 12.

 -- Function: date-year date
     Year, eg. 2003.  Dates B.C. are negative, eg. -46 is 46 B.C.
     There is no year 0, year -1 is followed by year 1.

 -- Function: date-zone-offset date
     Time zone, an integer number of seconds east of Greenwich.

 -- Function: date-year-day date
     Day of the year, starting from 1 for 1st January.

 -- Function: date-week-day date
     Day of the week, starting from 0 for Sunday.

 -- Function: date-week-number date dstartw
     Week of the year, ignoring a first partial week.  DSTARTW is the
     day of the week which is taken to start a week, 0 for Sunday, 1 for
     Monday, etc.

 -- Function: current-date [tz-offset]
     Return a date object representing the current date/time, in UTC
     offset by TZ-OFFSET.  TZ-OFFSET is seconds east of Greenwich and
     defaults to the local timezone.

 -- Function: current-julian-day
     Return the current Julian Day.

 -- Function: current-modified-julian-day
     Return the current Modified Julian Day.

6.4.15.4 SRFI-19 Time/Date conversions
......................................

 -- Function: date->julian-day date
 -- Function: date->modified-julian-day date
 -- Function: date->time-monotonic date
 -- Function: date->time-tai date
 -- Function: date->time-utc date

 -- Function: julian-day->date jdn [tz-offset]
 -- Function: julian-day->time-monotonic jdn
 -- Function: julian-day->time-tai jdn
 -- Function: julian-day->time-utc jdn

 -- Function: modified-julian-day->date jdn [tz-offset]
 -- Function: modified-julian-day->time-monotonic jdn
 -- Function: modified-julian-day->time-tai jdn
 -- Function: modified-julian-day->time-utc jdn

 -- Function: time-monotonic->date time [tz-offset]
 -- Function: time-monotonic->time-tai time
 -- Function: time-monotonic->time-tai! time
 -- Function: time-monotonic->time-utc time
 -- Function: time-monotonic->time-utc! time

 -- Function: time-tai->date time [tz-offset]
 -- Function: time-tai->julian-day time
 -- Function: time-tai->modified-julian-day time
 -- Function: time-tai->time-monotonic time
 -- Function: time-tai->time-monotonic! time
 -- Function: time-tai->time-utc time
 -- Function: time-tai->time-utc! time

 -- Function: time-utc->date time [tz-offset]
 -- Function: time-utc->julian-day time
 -- Function: time-utc->modified-julian-day time
 -- Function: time-utc->time-monotonic time
 -- Function: time-utc->time-monotonic! time
 -- Function: time-utc->time-tai time
 -- Function: time-utc->time-tai! time

     Convert between dates, times and days of the respective types.  For
     instance `time-tai->time-utc' accepts a TIME object of type
     `time-tai' and returns an object of type `time-utc'.

     The `!' variants may modify their TIME argument to form their
     return.  The plain functions create a new object.

     For conversions to dates, TZ-OFFSET is seconds east of Greenwich.
     The default is the local timezone, at the given time, as provided
     by the system, using `localtime' (see Time).

     On 32-bit systems, `localtime' is limited to a 32-bit `time_t', so
     a default TZ-OFFSET is only available for times between Dec 1901
     and Jan 2038.  For prior dates an application might like to use
     the value in 1902, though some locations have zone changes prior
     to that.  For future dates an application might like to assume
     today's rules extend indefinitely.  But for correct daylight
     savings transitions it will be necessary to take an offset for the
     same day and time but a year in range and which has the same
     starting weekday and same leap/non-leap (to support rules like
     last Sunday in October).

6.4.15.5 SRFI-19 Date to string
...............................

 -- Function: date->string date [format]
     Convert a date to a string under the control of a format.  FORMAT
     should be a string containing `~' escapes, which will be expanded
     as per the following conversion table.  The default FORMAT is
     `~c', a locale-dependent date and time.

     Many of these conversion characters are the same as POSIX
     `strftime' (see Time), but there are some extras and some
     variations.

     ~~     literal ~
     ~a     locale abbreviated weekday, eg. `Sun'
     ~A     locale full weekday, eg. `Sunday'
     ~b     locale abbreviated month, eg. `Jan'
     ~B     locale full month, eg. `January'
     ~c     locale date and time, eg.
            `Fri Jul 14 20:28:42-0400 2000'
     ~d     day of month, zero padded, `01' to `31'
     ~e     day of month, blank padded, ` 1' to `31'
     ~f     seconds and fractional seconds, with locale decimal
            point, eg. `5.2'
     ~h     same as ~b
     ~H     hour, 24-hour clock, zero padded, `00' to `23'
     ~I     hour, 12-hour clock, zero padded, `01' to `12'
     ~j     day of year, zero padded, `001' to `366'
     ~k     hour, 24-hour clock, blank padded, ` 0' to `23'
     ~l     hour, 12-hour clock, blank padded, ` 1' to `12'
     ~m     month, zero padded, `01' to `12'
     ~M     minute, zero padded, `00' to `59'
     ~n     newline
     ~N     nanosecond, zero padded, `000000000' to `999999999'
     ~p     locale AM or PM
     ~r     time, 12 hour clock, `~I:~M:~S ~p'
     ~s     number of full seconds since "the epoch" in UTC
     ~S     second, zero padded `00' to `60'
            (usual limit is 59, 60 is a leap second)
     ~t     horizontal tab character
     ~T     time, 24 hour clock, `~H:~M:~S'
     ~U     week of year, Sunday first day of week, `00' to `52'
     ~V     week of year, Monday first day of week, `01' to `53'
     ~w     day of week, 0 for Sunday, `0' to `6'
     ~W     week of year, Monday first day of week, `00' to `52'
     ~y     year, two digits, `00' to `99'
     ~Y     year, full, eg. `2003'
     ~z     time zone, RFC-822 style
     ~Z     time zone symbol (not currently implemented)
     ~1     ISO-8601 date, `~Y-~m-~d'
     ~2     ISO-8601 time+zone, `~k:~M:~S~z'
     ~3     ISO-8601 time, `~k:~M:~S'
     ~4     ISO-8601 date/time+zone, `~Y-~m-~dT~k:~M:~S~z'
     ~5     ISO-8601 date/time, `~Y-~m-~dT~k:~M:~S'

Conversions `~D', `~x' and `~X' are not currently described here, since
the specification and reference implementation differ.

   Currently Guile doesn't implement any localizations for the above,
all outputs are in English, and the `~c' conversion is POSIX `ctime'
style `~a ~b ~d ~H:~M:~S~z ~Y'.  This may change in the future.

6.4.15.6 SRFI-19 String to date
...............................

 -- Function: string->date input template
     Convert an INPUT string to a date under the control of a TEMPLATE
     string.  Return a newly created date object.

     Literal characters in TEMPLATE must match characters in INPUT and
     `~' escapes must match the input forms described in the table
     below.  "Skip to" means characters up to one of the given type are
     ignored, or "no skip" for no skipping.  "Read" is what's then
     read, and "Set" is the field affected in the date object.

     For example `~Y' skips input characters until a digit is reached,
     at which point it expects a year and stores that to the year field
     of the date.

            Skip to            Read                        Set
     ~~     no skip            literal ~                   nothing
     ~a     char-alphabetic?   locale abbreviated weekday  nothing
                               name
     ~A     char-alphabetic?   locale full weekday name    nothing
     ~b     char-alphabetic?   locale abbreviated month    date-month
                               name
     ~B     char-alphabetic?   locale full month name      date-month
     ~d     char-numeric?      day of month                date-day
     ~e     no skip            day of month, blank padded  date-day
     ~h     same as `~b'
     ~H     char-numeric?      hour                        date-hour
     ~k     no skip            hour, blank padded          date-hour
     ~m     char-numeric?      month                       date-month
     ~M     char-numeric?      minute                      date-minute
     ~S     char-numeric?      second                      date-second
     ~y     no skip            2-digit year                date-year within
                                                           50 years
     ~Y     char-numeric?      year                        date-year
     ~z     no skip            time zone                   date-zone-offset

     Notice that the weekday matching forms don't affect the date object
     returned, instead the weekday will be derived from the day, month
     and year.

     Currently Guile doesn't implement any localizations for the above,
     month and weekday names are always expected in English.  This may
     change in the future.

6.4.16 SRFI-26 - specializing parameters
----------------------------------------

This SRFI provides a syntax for conveniently specializing selected
parameters of a function.  It can be used with,

     (use-modules (srfi srfi-26))

 -- library syntax: cut slot ...
 -- library syntax: cute slot ...
     Return a new procedure which will make a call (SLOT ...) but with
     selected parameters specialized to given expressions.

     An example will illustrate the idea.  The following is a
     specialization of `write', sending output to `my-output-port',

          (cut write <> my-output-port)
          =>
          (lambda (obj) (write obj my-output-port))

     The special symbol `<>' indicates a slot to be filled by an
     argument to the new procedure.  `my-output-port' on the other hand
     is an expression to be evaluated and passed, ie. it specializes
     the behaviour of `write'.

    <>
          A slot to be filled by an argument from the created procedure.
          Arguments are assigned to `<>' slots in the order they appear
          in the `cut' form, there's no way to re-arrange arguments.

          The first argument to `cut' is usually a procedure (or
          expression giving a procedure), but `<>' is allowed there
          too.  For example,

               (cut <> 1 2 3)
               =>
               (lambda (proc) (proc 1 2 3))

    <...>
          A slot to be filled by all remaining arguments from the new
          procedure.  This can only occur at the end of a `cut' form.

          For example, a procedure taking a variable number of
          arguments like `max' but in addition enforcing a lower bound,

               (define my-lower-bound 123)

               (cut max my-lower-bound <...>)
               =>
               (lambda arglist (apply max my-lower-bound arglist))

     For `cut' the specializing expressions are evaluated each time the
     new procedure is called.  For `cute' they're evaluated just once,
     when the new procedure is created.  The name `cute' stands for
     "`cut' with evaluated arguments".  In all cases the evaluations
     take place in an unspecified order.

     The following illustrates the difference between `cut' and `cute',

          (cut format <> "the time is ~s" (current-time))
          =>
          (lambda (port) (format port "the time is ~s" (current-time)))

          (cute format <> "the time is ~s" (current-time))
          =>
          (let ((val (current-time)))
            (lambda (port) (format port "the time is ~s" val))

     (There's no provision for a mixture of `cut' and `cute' where some
     expressions would be evaluated every time but others evaluated
     only once.)

     `cut' is really just a shorthand for the sort of `lambda' forms
     shown in the above examples.  But notice `cut' avoids the need to
     name unspecialized parameters, and is more compact.  Use in
     functional programming style or just with `map', `for-each' or
     similar is typical.

          (map (cut * 2 <>) '(1 2 3 4))

          (for-each (cut write <> my-port) my-list)

6.4.17 SRFI-31 - A special form `rec' for recursive evaluation
--------------------------------------------------------------

SRFI-31 defines a special form that can be used to create
self-referential expressions more conveniently.  The syntax is as
follows:

     <rec expression> --> (rec <variable> <expression>)
     <rec expression> --> (rec (<variable>+) <body>)

   The first syntax can be used to create self-referential expressions,
for example:

       guile> (define tmp (rec ones (cons 1 (delay ones))))

   The second syntax can be used to create anonymous recursive
functions:

       guile> (define tmp (rec (display-n item n)
                            (if (positive? n)
                                (begin (display n) (display-n (- n 1))))))
       guile> (tmp 42 3)
       424242
       guile>

6.4.18 SRFI-39 - Parameters
---------------------------

This SRFI provides parameter objects, which implement dynamically bound
locations for values.  The functions below are available from

     (use-modules (srfi srfi-39))

   A parameter object is a procedure.  Called with no arguments it
returns its value, called with one argument it sets the value.

     (define my-param (make-parameter 123))
     (my-param) => 123
     (my-param 456)
     (my-param) => 456

   The `parameterize' special form establishes new locations for
parameters, those new locations having effect within the dynamic scope
of the `parameterize' body.  Leaving restores the previous locations,
or re-entering through a saved continuation will again use the new
locations.

     (parameterize ((my-param 789))
       (my-param) => 789
       )
     (my-param) => 456

   Parameters are like dynamically bound variables in other Lisp
dialets.  They allow an application to establish parameter settings (as
the name suggests) just for the execution of a particular bit of code,
restoring when done.  Examples of such parameters might be
case-sensitivity for a search, or a prompt for user input.

   Global variables are not as good as parameter objects for this sort
of thing.  Changes to them are visible to all threads, but in Guile
parameter object locations are per-thread, thereby truely limiting the
effect of `parameterize' to just its dynamic execution.

   Passing arguments to functions is thread-safe, but that soon becomes
tedious when there's more than a few or when they need to pass down
through several layers of calls before reaching the point they should
affect.  And introducing a new setting to existing code is often easier
with a parameter object than adding arguments.

 -- Function: make-parameter init [converter]
     Return a new parameter object, with initial value INIT.

     A parameter object is a procedure.  When called `(param)' it
     returns its value, or a call `(param val)' sets its value.  For
     example,

          (define my-param (make-parameter 123))
          (my-param) => 123

          (my-param 456)
          (my-param) => 456

     If a CONVERTER is given, then a call `(CONVERTER val)' is made for
     each value set, its return is the value stored.  Such a call is
     made for the INIT initial value too.

     A CONVERTER allows values to be validated, or put into a canonical
     form.  For example,

          (define my-param (make-parameter 123
                             (lambda (val)
                               (if (not (number? val))
                                   (error "must be a number"))
                               (inexact->exact val))))
          (my-param 0.75)
          (my-param) => 3/4

 -- library syntax: parameterize ((param value) ...) body ...
     Establish a new dynamic scope with the given PARAMs bound to new
     locations and set to the given VALUEs.  BODY is evaluated in that
     environment, the result is the return from the last form in BODY.

     Each PARAM is an expression which is evaluated to get the
     parameter object.  Often this will just be the name of a variable
     holding the object, but it can be anything that evaluates to a
     parameter.

     The PARAM expressions and VALUE expressions are all evaluated
     before establishing the new dynamic bindings, and they're
     evaluated in an unspecified order.

     For example,

          (define prompt (make-parameter "Type something: "))
          (define (get-input)
            (display (prompt))
            ...)

          (parameterize ((prompt "Type a number: "))
            (get-input)
            ...)

 -- Parameter object: current-input-port [new-port]
 -- Parameter object: current-output-port [new-port]
 -- Parameter object: current-error-port [new-port]
     This SRFI extends the core `current-input-port' and
     `current-output-port', making them parameter objects.  The
     Guile-specific `current-error-port' is extended too, for
     consistency.  (see Default Ports.)

     This is an upwardly compatible extension, a plain call like
     `(current-input-port)' still returns the current input port, and
     `set-current-input-port' can still be used.  But the port can now
     also be set with `(current-input-port my-port)' and bound
     dynamically with `parameterize'.

 -- Function: with-parameters* param-list value-list thunk
     Establish a new dynamic scope, as per `parameterize' above, taking
     parameters from PARAM-LIST and corresponding values from
     VALUES-LIST.  A call `(THUNK)' is made in the new scope and the
     result from that THUNK is the return from `with-parameters*'.

     This function is a Guile-specific addition to the SRFI, it's
     similar to the core `with-fluids*' (see Fluids and Dynamic States).

   Parameter objects are implemented using fluids (see Fluids and Dynamic States),
so each dynamic state has it's own parameter
locations.  That includes the separate locations when outside any
`parameterize' form.  When a parameter is created it gets a separate
initial location in each dynamic state, all initialized to the given
INIT value.

   As alluded to above, because each thread usually has a separate
dynamic state, each thread has it's own locations behind parameter
objects, and changes in one thread are not visible to any other.  When
a new dynamic state or thread is created, the values of parameters in
the originating context are copied, into new locations.

   SRFI-39 doesn't specify the interaction between parameter objects and
threads, so the threading behaviour described here should be regarded
as Guile-specific.

6.4.19 SRFI-55 - Requiring Features
-----------------------------------

SRFI-55 provides `require-extension' which is a portable mechanism to
load selected SRFI modules.  This is implemented in the Guile core,
there's no module needed to get SRFI-55 itself.

 -- library syntax: require-extension clause...
     Require each of the given CLAUSE features, throwing an error if
     any are unavailable.

     A CLAUSE is of the form `(IDENTIFIER arg...)'.  The only
     IDENTIFIER currently supported is `srfi' and the arguments are
     SRFI numbers.  For example to get SRFI-1 and SRFI-6,

          (require-extension (srfi 1 6))

     `require-extension' can only be used at the top-level.

     A Guile-specific program can simply `use-modules' to load SRFIs
     not already in the core, `require-extension' is for programs
     designed to be portable to other Scheme implementations.

6.4.20 SRFI-60 - Integers as Bits
---------------------------------

This SRFI provides various functions for treating integers as bits and
for bitwise manipulations.  These functions can be obtained with,

     (use-modules (srfi srfi-60))

   Integers are treated as infinite precision twos-complement, the same
as in the core logical functions (see Bitwise Operations).  And
likewise bit indexes start from 0 for the least significant bit.  The
following functions in this SRFI are already in the Guile core,

     `logand', `logior', `logxor', `lognot', `logtest', `logcount',
     `integer-length', `logbit?', `ash'

 -- Function: bitwise-and n1 ...
 -- Function: bitwise-ior n1 ...
 -- Function: bitwise-xor n1 ...
 -- Function: bitwise-not n
 -- Function: any-bits-set? j k
 -- Function: bit-set? index n
 -- Function: arithmetic-shift n count
 -- Function: bit-field n start end
 -- Function: bit-count n
     Aliases for `logand', `logior', `logxor', `lognot', `logtest',
     `logbit?', `ash', `bit-extract' and `logcount' respectively.

     Note that the name `bit-count' conflicts with `bit-count' in the
     core (see Bit Vectors).

 -- Function: bitwise-if mask n1 n0
 -- Function: bitwise-merge mask n1 n0
     Return an integer with bits selected from N1 and N0 according to
     MASK.  Those bits where MASK has 1s are taken from N1, and those
     where MASK has 0s are taken from N0.

          (bitwise-if 3 #b0101 #b1010) => 9

 -- Function: log2-binary-factors n
 -- Function: first-set-bit n
     Return a count of how many factors of 2 are present in N.  This is
     also the bit index of the lowest 1 bit in N.  If N is 0, the
     return is -1.

          (log2-binary-factors 6) => 1
          (log2-binary-factors -8) => 3

 -- Function: copy-bit index n newbit
     Return N with the bit at INDEX set according to NEWBIT.  NEWBIT
     should be `#t' to set the bit to 1, or `#f' to set it to 0.  Bits
     other than at INDEX are unchanged in the return.

          (copy-bit 1 #b0101 #t) => 7

 -- Function: copy-bit-field n newbits start end
     Return N with the bits from START (inclusive) to END (exclusive)
     changed to the value NEWBITS.

     The least significant bit in NEWBITS goes to START, the next to
     START+1, etc.  Anything in NEWBITS past the END given is ignored.

          (copy-bit-field #b10000 #b11 1 3) => #b10110

 -- Function: rotate-bit-field n count start end
     Return N with the bit field from START (inclusive) to END
     (exclusive) rotated upwards by COUNT bits.

     COUNT can be positive or negative, and it can be more than the
     field width (it'll be reduced modulo the width).

          (rotate-bit-field #b0110 2 1 4) => #b1010

 -- Function: reverse-bit-field n start end
     Return N with the bits from START (inclusive) to END (exclusive)
     reversed.

          (reverse-bit-field #b101001 2 4) => #b100101

 -- Function: integer->list n [len]
     Return bits from N in the form of a list of `#t' for 1 and `#f'
     for 0.  The least significant LEN bits are returned, and the first
     list element is the most significant of those bits.  If LEN is not
     given, the default is `(integer-length N)' (see Bitwise Operations).

          (integer->list 6)   => (#t #t #f)
          (integer->list 1 4) => (#f #f #f #t)

 -- Function: list->integer lst
 -- Function: booleans->integer bool...
     Return an integer formed bitwise from the given LST list of
     booleans, or for `booleans->integer' from the BOOL arguments.

     Each boolean is `#t' for a 1 and `#f' for a 0.  The first element
     becomes the most significant bit in the return.

          (list->integer '(#t #f #t #f)) => 10

6.4.21 SRFI-61 - A more general `cond' clause
---------------------------------------------

This SRFI extends RnRS `cond' to support test expressions that return
multiple values, as well as arbitrary definitions of test success.
SRFI 61 is implemented in the Guile core; there's no module needed to
get SRFI-61 itself.  Extended `cond' is documented in Simple Conditional Evaluation.

6.5 Readline Support
====================

Guile comes with an interface module to the readline library (see
readline).  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.

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

   You can specify a different history file by setting the environment
variable `GUILE_HISTORY'.  And you can make Guile specific
customizations to your `.inputrc' by testing for application `Guile'
(see Conditional Init Constructs (readline)).
For instance to define a key inserting a matched pair of
parentheses,

     $if Guile
       "\C-o": "()\C-b"
     $endif

6.5.2 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 (see 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.

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

6.7 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] [keyword-options]
     Print the textual representation of the Scheme object OBJ to PORT.
     PORT defaults to the current output port, if not given.

     The further KEYWORD-OPTIONS are keywords and parameters as follows,

    #:display? FLAG
          If FLAG is true then print using `display'.  The default is
          `#f' which means use `write' style.  (see Writing)

    #:per-line-prefix STRING
          Print the given STRING as a prefix on each line.  The default
          is no prefix.

    #:width COLUMNS
          Print within the given COLUMNS.  The default is 79.