This is gauche-refe.info, produced by makeinfo version 4.8 from
gauche-refe.texi.

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Gauche Reference: (gauche-refe.info).	An R5RS Scheme implementation.
END-INFO-DIR-ENTRY


File: gauche-refe.info,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)

   This is a reference manual of Gauche, an R5RS Scheme implementation.
This manual is for version 0.8.5.

* Menu:

* Introduction::
* Concepts::
* Programming in Gauche::
* Core syntax::
* Macros::
* Core library::
* Object system::
* Library modules - Overview::
* Library modules - Gauche extensions::
* Library modules - SRFIs::
* Library modules - Utilities::
* References::
* C to Scheme mapping::
* Function and Syntax Index::
* Module Index::
* Class Index::
* Variable Index::


File: gauche-refe.info,  Node: Introduction,  Next: Concepts,  Prev: Top,  Up: Top

1 Introduction
**************

This is a programmers' guide and reference manual of the Gauche Scheme
system.  Here I tried to describe Gauche's implementation precisely,
sometimes referring to background design choices.

   The target readers are those who already know Scheme and want to
write useful programs in Gauche.  For those who are new to Scheme,
it'll be easier to start from some kind of tutorial.  I'm planning to
write one.

   This manual only deals with Scheme side of things.  Gauche has
another face, a C interface.   Details of it will be discussed in a
separate document to be written.  Those who wants to use Gauche as an
embedded language, or wants to write an extension, need that volume.

   For the Scheme side, I tried to make this manual self-contained for
reader's convenience, i.e. as far as you want to look up Gauche's
features you don't need to refer to other documents.  For example,
description of functions defined in the standard documents are included
in this manual, instead of saying "see the standard document".
However, this document is not a verbatim copy of the standard
documents; sometimes I omit detailed discussions in the standard
documents for brevity.  I put pointers to the original documents, so
please consult them if you need to refer to the standards.

   If you're reading this document off-line, you may find the most
recent version on the web:
     `http://www.shiro.dreamhost.com/scheme/gauche/'.

* Menu:

* Overview of Gauche::
* Notations::


File: gauche-refe.info,  Node: Overview of Gauche,  Next: Notations,  Prev: Introduction,  Up: Introduction

1.1 Overview of Gauche
======================

Gauche is a script interpreter based on Scheme.  Gauche conforms the
language standard "Revised^5 Report on the Algorithmic Language Scheme"
(*Note [R5RS]: r5rs.), and supports various common libraries defined in
SRFIs (`http://srfi.schemers.org').

   The goal of Gauche is to provide a handy tool for programmers and
system administrators to handle daily works conveniently and
efficiently in the production environment.

   There are lots of Scheme implementations available, and each of them
has its design emphasis and weeknesses.  Gauche is designed with
emphasis on the following criteria.

Quick startup
     One of the situation Gauche is aiming at is in the production
     environment, where you write ten-lines throw-away script that may
     invoked very frequently.  This includes CGI scripts as well.
     Gauche includes a set of most common features in its executable,
     while splits less common stuffs into libraries which are to be
     loaded on demand, to make itself start quickly.

Multibyte strings
     We can no longer live happily in ASCII-only or
     1-byte-per-character world.  The practical language
     implementations are required to handle multibyte (wide) characters.
     Gauche supports multibyte strings natively, providing robust and
     consistent support than ad hoc library-level implementation.
     *Note Multibyte Strings::, for details.

Modular development
     Gauche has a simple module system to separate namespaces, which
     allows the developers to work in parallel without worrying name
     collision.

Integrated object system
     A powerful CLOS-like object system with MetaObject protocol
     (mostly compatible with STklos and Guile) is provided.

System interface
     Although Scheme abstracts lots of details of the machine,
     sometimes you have to bypass these high-level layers and go down
     to the basement to make things work.  Gauche has built-in support
     of most of POSIX.1 system calls.  Other modules, such as
     networking module, usually provide both high-level abstract
     interface and low-level interface close to system calls.

Enhanced I/O
     No real application can be written without dealing with I/O.
     Scheme neatly abstracts I/O as a port, but defines least
     operations on it.  Gauche uses a port object as a unified
     abstraction, providing utility functions to operate on the
     underlying I/O system.  *Note Input and output::, for the basic
     I/O support.

   On the other hand, Gauche is _not_ designed for applications such
like high-performance number cruncher or very large scale database
handling.  It is an interpreter, after all.

   You can still use Gauche as a "glue" language for such applications,
however.  For example, you can write a performance-critical part in
another language that compiles to native code, and use Gauche to set up.


File: gauche-refe.info,  Node: Notations,  Prev: Overview of Gauche,  Up: Introduction

1.2 Notations
=============

In this manual, each entry is represented like this:

 -- Category: foo arg1 arg2
     [spec] Description of foo ...

   CATEGORY denotes the category of the entry foo.  The following
category will appear in this manual:

Function                      A Scheme function.
Special Form                  A special form (in the R5RS term,
                              "syntax").
Macro                         A macro.
Module                        A module
Class                         A class.
Generic Function              A generic function
Method                        A method
Reader Syntax                 A lexical syntax that is interpreted by
                              the reader.

   For functions, special forms and macros, the entry may followed by
one or more arguments.  In the argument list, the following notations
may appear:

ARG ...
     Indicates zero or more arguments.

&OPTIONAL X Y Z
&OPTIONAL (X X-DEFAULT) (Y Y-DEFAULT) Z
     Indicates it may take up to three optional arguments.  The second
     form specifies default values.  Note that Gauche doesn't really
     support Common-Lisp style `&optional' argument specifier in the
     lambda list.  I use this notation since it is useful to indicate
     valid pattern of arguments.

&KEYWORD X Y Z
&KEYWORD (X X-DEFAULT) (Y Y-DEFAULT) Z
     Indicates it may take keyword arguments X, Y and Z.  Note that
     Gauche doesn't really support Common-Lisp style `&keyword'
     argument specifier in the lambda list.  I use this notation since
     it is useful to indicate valid pattern of arguments.

&REST ARGS
     Indicates it may take rest arguements.  Note that Gauche doesn't
     really support Common-Lisp style `&rest' argument specifier in the
     lambda list.  I use this notation since it is useful to indicate
     valid pattern of arguments.

   The description of the entry follows the entry line.  If the
specification of the entry comes from some standard or implementation,
its origin is noted in the bracket at the beginning of the description.
The following origins are noted:

[R5RS]
[R5RS+]
     The entry works as specified in "Revised^5 Report of Algorithmic
     Language Scheme.".  If it is marked as "[R5RS+]", the entry has
     additional functionality.

[SRFI-N]
[SRFI-N+]
     The entry works as specified in SRFI-N.  If it is marked as
     "[SRFI-N+]", the entry has additional functionality.

[POSIX]
     The API of the entry reflects the API specified in POSIX.


File: gauche-refe.info,  Node: Concepts,  Next: Programming in Gauche,  Prev: Introduction,  Up: Top

2 Concepts
**********

In this chapter I describe a few Gauche's design concepts that help you
to understand how Gauche works.

* Menu:

* Standard conformance::
* Multibyte Strings::
* Multibyte scripts::
* Case-sensitivity::
* Integerated Object System::
* Module system::
* Compilation::


File: gauche-refe.info,  Node: Standard conformance,  Next: Multibyte Strings,  Prev: Concepts,  Up: Concepts

2.1 Standard conformance
========================

Gauche conforms "Revised^5 Report of Algorithmic Language Scheme,"
including optional syntax and procedures, except the following features.

   * By default, Gauche reads symbols in case-sensitive way.  A
     command-line option is provided to make the reader
     case-insensitive.  (*Note Case-sensitivity::, for details).

   * Continuations created in a certain situation (specifcally, inside
     a Scheme code that is called from external C routine) have limited
     extent (*Note Continuation::, for details).

   * Numeric tower of integer, real, and complex numbers are supported,
     but rational numbers are not.  The reader can read rational numbers
     but converts them to inexact real numbers.  The reader can
     recognize '`#'' as insignificant digits.

   * Procedure `rationalize', `transcript-on' and `transcript-off' are
     not supported.

   Gauche also supports the following SRFIs (Scheme Request for
Implementation).

SRFI-0, Feature-based conditional expansion construct.
     As an autoloaded macro.   *Note Feature conditional::.

SRFI-1, List library.
     Supported by the module `srfi-1'.  *Note List library::.  (Some of
     SRFI-1 procedures are built-in).

SRFI-2, AND-LET*: an AND with local bindings, a guarded LET* special form.
     Supported by the module `srfi-2'.  *Note And-let*::.

SRFI-4, Homogeneous numeric vector datatypes.
     The module `gauche.uvector' provides a superset of `srfi-4'
     procedures, including arithmetic operations and generic interface
     on the SRFI-4 vectors.  *Note Uniform vectors::.

SRFI-5, A compatible let form with signatures and rest arguments
     Supported by the module `srfi-5'.  *Note A compatible let form
     with signatures and rest arguments::.

SRFI-6, Basic String Ports.
     SRFI-6 procedures are built-in.  *Note String ports::.

SRFI-7, Feature-based program configuration language
     Supported as an autoloaded macro.  *Note Feature-based program
     configuration language::.

SRFI-8, receive: Binding to multiple values.
     Syntax `receive' is built-in.  *Note Binding constructs::.

SRFI-9, Defining record types.
     Supported by the module `srfi-9'.  *Note Record types::.

SRFI-10, Sharp-comma external form.
     Built-in.  *Note Read-time constructor::.

SRFI-11, Syntax for receiving multiple values.
     Supported by the module `srfi-11'.  *Note Let-values::.

SRFI-13, String library
     Supported by the module `srfi-13'.  *Note String library::.  (Some
     of SRFI-13 procedures are built-in).

SRFI-14, Character-set library
     Character-set object and a few SRFI-14 procedures are built-in.
     *Note Character set::.  Complete set of SRFI-14 is supported by
     the module `srfi-14'.  *Note Character-set library::.

SRFI-16, Syntax for procedures of variable arity (case-lambda)
     Built-in.  *Note Making Procedures::.

SRFI-17, Generalized set!
     Built-in.  *Note Assignments::.

SRFI-18, Multithreading support
     Some SRFI-18 features are built-in, and the rest is in
     `gauche.threads' module.  *Note Threads::.

SRFI-19, Time Data Types and Procedures.
     Time data type is Gauche built-in (*Note Time::).  Complete set of
     SRFI-19 is supported by the module `srfi-19'.  *Note Time data
     types and procedures::.

SRFI-22, Running Scheme scripts on Unix
     Supported.  *Note Writing Scheme scripts::.

SRFI-23, Error reporting mechanism.
     Built-in.   *Note Signalling exceptions::.

SRFI-25, Multi-dimensional array primitives.
     Supported by the module `gauche.array', which defines superset of
     SRFI-25.  *Note Arrays::.

SRFI-26, Notation for specializing parameters without currying.
     As an autoloaded macro.  *Note Making Procedures::.

SRFI-27, Sources of Random Bits.
     Supported by the module `srfi-27'.  *Note Sources of random bits::.

SRFI-28, Basic format strings.
     Gauche's built-in `format' procedure is a superset of SRFI-28
     `format'.  *Note Output::.

SRFI-29, Localization
     Supported by the module `srfi-29'.  *Note Localization::.

SRFI-30, Nested multi-line comments.
     Supported by the native reader.  *Note Lexical structure::.

SRFI-31, A special form rec for recursive evaluation
     Defined as an autoloaded macro.  *Note Binding constructs::.

SRFI-34, Exception Handling for Programs
     Built-in.  *Note Exceptions::.  (However, Gauche implements
     srfi-18's semantics of `raise' literally, which differs slightly
     from srfi-34's.  This may be changed in future.)

SRFI-35, Conditions
     Built-in.  *Note Conditions::.

SRFI-36, I/O Conditions
     Partly supported.  *Note Conditions::.

SRFI-37, args-fold: a program argument processor
     Supported by the module `srfi-37'.  *Note A program argument
     processor::.

SRFI-38, External Representation for Data With Shared Structure
     Built-in.  See *Note Reading data:: and *Note Output::.

SRFI-39, Parameter objects
     Supported by the module `gauche.parameter'.  *Note Parameters::.

SRFI-42, Eager comprehensions
     Supported by the module `srfi-42'.  *Note Eager comprehensions::.

SRFI-55, require-extension
     Supported as an autoloaded macro.  *Note Requiring extensions::.



File: gauche-refe.info,  Node: Multibyte Strings,  Next: Multibyte scripts,  Prev: Standard conformance,  Up: Concepts

2.2 Multibyte Strings
=====================

Traditionally, a string is considered as a simple array of bytes.
Programmers tend to imagine a string as a simple array of characters
(though a character may occupy more than one byte).  It's not the case
in Gauche.

   Gauche supports _multibyte string_ natively, which means characters
are represented by variable number of bytes in a string.   Gauche
retains semantic compatibility of Scheme string, so such details can be
hidden, but it'll helpful if you know a few points.

   A string object keeps a type tag and a pointer to the storage of the
string body.  The storage of the body is managed in a sort of
"copy-on-write" way--if you take substring, e.g. using directly by
`substring' or using regular expression matcher, or even if you copy a
string by `copy-string', the underlying storage is shared (the "anchor"
of the string is different, so the copied string is not `eq?' to the
original string).  The actual string is copied only if you
destructively modify it.

   Consequently the algorithm like pre-allocating a string by
`make-string' and filling it with `string-set!' becomes _extremely_
inefficient in Gauche.  Don't do it.  (It doesn't work with mulitbyte
strings anyway).  Sequential access of string is much more efficient
using _string ports_ (*Note String ports::).

   String search primitives such as `string-scan' (*Note String
utilities::) and regular expression matcher (*Note Regular expression::)
can return a matched string directly, without using index access at all.

   You can choose _internal_ encoding scheme at the time of compiling
Gauche.   At runtime, a procedure `gauche-character-encoding' can be
used to query the internal encoding.  Currently, the following internal
encodings are supported.

`euc-jp'
     EUC-JP encoding of ASCII, JIS X 0201 kana, JIS X 0212 and JIS X
     0213:2000 Japanese character set.

`sjis'
     Shift-JIS encoding of JIS X 0201 kana and JIS X 0213:2000 Japanese
     character set.  For source-code compatibility, the character code
     between 0 and 0x7f is mapped to ASCII.

`utf-8'
     UTF-8 encoding of Unicode.

`none'
     8-bit fixed-length character encoding, with the code between 0 and
     0x7f matches ASCII.  It's up to the application to interpret the
     string with certain character encodings.

   Conversions from other encoding scheme is provided as a special
port. *Note Character code conversion::, for details.

   The way to specify the encoding of source programs will be explained
in the next section.


File: gauche-refe.info,  Node: Multibyte scripts,  Next: Case-sensitivity,  Prev: Multibyte Strings,  Up: Concepts

2.3 Multibyte scripts
=====================

You can use characters other than `us-ascii' not only in literal
strings and characters, but in in commens, symbol names, literal
regular expressions, and so on.

   So far, Gauche treats any characters other than `us-ascii' as symbol
constituent characters.  Unicode defines more than dozen "space"
characters, though, and they will be treated as whitespace characters
in future.  So it's better to avoid those characters (except in the
strings, regexps and characters) for the time being.

   By default, Gauche assumes the Scheme program is written in its
internal encoding scheme.   It is fine as far as you're writing scripts
to use your own environment, but becomes a problem if somebody else
tries to use your script and finds out you're using different character
encodings than his/hers.

   So, if Gauche finds a comment something like the following within
the first two lines of the program source, it assumes the rest of the
source code is written in `<encoding-name>', and does the appropriate
character encoding conversion to read the source code:
     ;; coding: <encoding-name>

   More precisely, a comment in either first or second line that matches
a regular expression `#/coding[:=]\s*([\w.-]+)/' is recognized, and the
first submatch is taken as an encoding name.  If there are multiple
matches, only the first one is effective.  The first two lines must not
contain characters other than us-ascii in order for this mechanism to
work.

   The following example tells Gauche that the script is written in
EUC-JP encoding.   Note that the string "`-*-'" around the coding would
be recognized by Emacs to select the buffer's encoding appropriately.

     #!/usr/bin/gosh
     ;; -*- coding: euc-jp -*-

     ... script written in euc-jp ...

   Internally, the handling of this _magic comment_ is done by a
special type of port.  See *Note Coding-aware ports:: for the details.
See also *Note Loading Scheme file:: for how to disable this feature.


File: gauche-refe.info,  Node: Case-sensitivity,  Next: Integerated Object System,  Prev: Multibyte scripts,  Up: Concepts

2.4 Case-sensitivity
====================

Historically, most Lisp-family languages are case-insensitive for
symbols.  Scheme is no exception and R5RS defines symbols are read in
case-insensitive way.  (Note that symbols are case-sensitive internally
even in R5RS Scheme; case-insensitivity is about readers.)

   However, nowadays programming is hardly completed in one language.
When you have to interact with other languages that distinguishe
uppercase and lowercase characters, it is desirable that Scheme
distinguishes them as well.

   So Gauche has two modes in reading and writing symbols.  _By
default, Gauche reads and writes symbols in case-sensitive manner_.
This behavior doesn't conform R5RS.

     ; In case-sensitive mode (default)
     (eq? 'a 'A) => #f  ; #t in R5RS
     (symbol->string 'ABC) => "ABC"
     (symbol->string 'abc) => "abc"
     (display (string->symbol "ABC")) => writes ABC
     (display (string->symbol "abc")) => writes abc

   You can make Gauche case-insensitive by giving `-fcase-fold'
command-line option to the `gosh' interpreter (*Note Invoking Gosh::).
In this mode, the reader folds uppercase characters in symbols to
lowercase ones.  If a symbol name contains uppercase characters, it is
written out using |-escape (*Note Symbols::).

     ; In case-insensitive mode (with -fcase-fold option)
     (eq? 'a 'A) => #t
     (symbol->string 'ABC) => "abc"
     (symbol->string 'abc) => "abc"
     (display (string->symbol "ABC")) => writes |ABC|
     (display (string->symbol "abc")) => writes abc

   Right now, there's no way to switch these two modes back and forth
inside the intepreter; an API will be provided in the later versions.


File: gauche-refe.info,  Node: Integerated Object System,  Next: Module system,  Prev: Case-sensitivity,  Up: Concepts

2.5 Integrated Object System
============================

Gauche has a STklos-style object system, similar to CLOS.  If you have
used some kind of object oriented (OO) languages, you'll find it easy
to understand the basic usage:
     ;; Defines a class point, that has x and y coordinate
     (define-class point ()
       ((x :init-value 0)
        (y :init-value 0))
       )

     (define-method move ((p point) dx dy)
       (inc! (slot-ref p 'x) dx)
       (inc! (slot-ref p 'y) dy))

     (define-method write-object ((p point) port)
       (format port "[point ~a ~a]"
               (slot-ref p 'x)
               (slot-ref p 'y)))

   However, if you are familiar with mainstream OO langauges but new to
CLOS-style object system, Gauche's object system may look strange when
you look deeper into it.  Here I describe several characteristics of
Gauche object system quickly.  *Note Object system::, for details.

_Everything is an object (if you care)_
     You have seen this tagline for the other languages.  And yes, in
     Gauche, everything is an object in the sense that you can query
     its class, and get various meta information of the object at run
     time.  You can also define a new method on any class including
     built-in classes.

     Note that, however, in CLOS-like paradigm it doesn't really matter
     whether everything is an object or not, because of the following
     characteristics:

_Method is dispatched by all of its arguments._
     Unlike other object-oriented languages such as C++, Objective-C,
     Python, Ruby, etc., in which a method always belong to a single
     class, a Gauche method doesn't belong to a specific class.

     For example, suppose you define a numeric vector class
     `<num-vector>' and a numeric matrix class `<num-matrix>'.  You can
     define a method `product' with all possible combinations of those
     type of arguments:

            (product <num-vector> <num-matrix>)
            (product <num-matrix> <num-vector>)
            (product <num-vector> <num-vector>)
            (product <num-matrix> <num-matrix>)
            (product <number>     <num-vector>)
            (product <number>     <num-matrix>)
            (product <number>     <number>)

     Each method belongs to neither `<num-vector>' class nor
     `<num-matrix>' class.

     Since a method is not owned by a class, you can always define your
     own method on the existing class (except a few cases that the
     system prohibits altering pre-defined methods).  The above example
     already shows it; you can make `product' method work on the
     built-in class `<number>'.   That is why I said it doesn't make
     much sense to discuss whether everything is object or not in
     CLOS-style object system.

_Class is also an instance._
     By default, a class is also an instance of class `<class>', and a
     generic function is an instance of class `<generic>'.  You can
     subclass `<class>' to customize how a class is initialized or how
     its slots are accessed.  You can subclass `<generic>' to customize
     how the applicable methods are selected, which order those methods
     are called, etc.   The mechanism is called _metaobject protocol_.
     Metaobject protocol allows you to extend the language by the
     language itself.

     To find examples, see the files `lib/gauche/singleton.scm' and
     `lib/gauche/validator.scm' included in the distribution.  You can
     also read `lib/gauche/object.scm', which actually defines how a
     class is defined in Gauche.  For more details about metaobject
     protocol, see *Note [MOP]: mop.

_Class doesn't create namespace_
     In the mainstream OO language, a class often creates its own
     namespace.  This isn't the case in CLOS-style object system.  In
     Gauche, a namespace is managed by the module system which is
     orthogonal to the object system.



File: gauche-refe.info,  Node: Module system,  Next: Compilation,  Prev: Integerated Object System,  Up: Concepts

2.6 Module system
=================

Gauche has a simple module system that allows modularlized development
of large software.

   A higher level interface is simple enough from the user's point of
view.   It works like this: When you want to use the features provided
by module `foo', you just need to say `(use foo)' in your code.  This
form is a macro and interpreted at compile time.  Usually it loads the
files that defines `foo''s features, and imports the external APIs into
the calling module.

   The `use' mechanism is built on top of two independent lower
mechanisms, namespace separation and file loading mechanism.  Those two
lower mechanisms can be used separately, although it is much more
convenient when used together.

   The `use' mechanism is not transitive; that is, if a module B uses a
module A, and a module C uses the module B, C doesn't see the bindings
in A.  It is because B and A is not in the IS-A relationship.  Suppose
the module A implements a low-level functionality and the module B
implements a high-level abstraction; if C is using B, what C wants to
see is just a high-level abstraction, and doesn't concern how B
implements such functionality.  If C wants to access low-level stuff, C
has to USE A explicitly.

   There is another type of relationship, though.  You might want to
take an exiting module A, and add some interface to it and provide the
resulting module B as an extension of A.  In such a case, B is-a A, and
it'd be natural that the module that uses B can also see A's bindings.
In Gauche, it is called _module inheritance_ and realized by `extend'
form.

   The following sections in this manual describes modules in details.
   * *Note Writing Gauche modules:: explains the convention of writing
     modules.

   * *Note Modules:: describes special forms and macros to define and
     to use modules, along the built-in functions to introspect module
     internals.


File: gauche-refe.info,  Node: Compilation,  Prev: Module system,  Up: Concepts

2.7 Compilation
===============

Gauche is a Scheme interpreter, in the sense that it reads a Scheme
form at a time and evaluates it.   Actually, Gauche compiles every
toplevel form into an intermediate form before executing.

   Built-in sytanxes and macros are recognized and expanded at the
compilation time.  Some built-in procedures are expanded in-line as far
as the compiler can see the global binding is not altered at the time
the form is compiled.

   This raises a few problems you should care.

_load is done at run time._
     `load' is a procedure in Gauche, therefore evaluated at run time.
     If the loaded program defines a macro, which is available for the
     compiler after the toplevel form containing `load' is evaluated.
     So, suppose `foo.scm' defines a macro `foo', and you use the macro
     like this:
          ;; in "foo.scm"
          (define-syntax foo
            (syntax-rules () (_ arg) (quote arg)))

          ;; in your program
          (begin (load "foo") (foo (1 2 3)))
            => error, bad procedure: `1'

          (load "foo")
          (foo (1 2 3)) => '(1 2 3)
     The `(begin (load ...))' form fails,  because the compiler doesn't
     know `foo' is a special form at the compilation time and compiles
     `(1 2 3)' as if it is a normal procedure call.  The latter example
     works, however, since the execution of the toplevel form `(load
     "foo")' is done before `(foo (1 2 3))' is compiled.

     To avoid this kind of subtleties, use `require' or `use' to load a
     program fragments.  Those are recognized by the compiler.

_require is done at compile time_
     On the other hand, since `require' and `use' is recognized by the
     compiler, the specified file is loaded even if the form is in the
     conditional expression.   If you really need to load a file on
     certain condition, use `load' or do dispatch in macro (i.e. at
     compile time).


File: gauche-refe.info,  Node: Programming in Gauche,  Next: Core syntax,  Prev: Concepts,  Up: Top

3 Programming in Gauche
***********************

* Menu:

* Invoking Gosh::
* Interactive development::
* Writing Scheme scripts::
* Debugging::
* Profiling and tuning::
* Writing Gauche modules::
* Using extension packages::


File: gauche-refe.info,  Node: Invoking Gosh,  Next: Interactive development,  Prev: Programming in Gauche,  Up: Programming in Gauche

3.1 Invoking Gosh
=================

Gauche can be used either as an independent Scheme interpreter or as an
embedded Scheme library.   The interpreter which comes with Gauche
distribution is a program named `gosh'.

 -- Program: gosh [options] [scheme-file arg ...]
     Gauche's interpreter.   Without SCHEME-FILE, `gosh' works
     interactively, i.e. it reads a Scheme expression from the standard
     input, evaluates it, and prints the result, and repeat that until
     it reads EOF or is terminated.

     If `gosh' is invoked without SCHEME-FILE, but the input is not a
     terminal, it enters read-eval-print loop but not writes out a
     prompt while waiting input form.  This is useful when you pipe
     Scheme program into `gosh'.  You can force this behavior or
     suppress this behavior by `-b' and `-i' options.

     If SCHEME-FILE is specified, `gosh' runs it as a Scheme program
     and exit.  *Note Writing Scheme scripts::, for details.

Command-line options
--------------------

The following command line options are recognized by `gosh'.  The first
command line argument which doesn't begin with `-' is recognized as the
script file.  If you want to specify a file that begins with a minus
sign, use a dummy option ``--''.

 -- Command Option: -I path
     Prepends PATH to the load path list.  You can specify this option
     more than once to add multiple paths.

 -- Command Option: -A path
     Appends PATH to the tail of the load path list.  You can specify
     this option more than once to add multiple paths.

 -- Command Option: -q
     Makes `gosh' not to load the default initialization file.

 -- Command Option: -V
     Prints the `gosh' version and exits.

 -- Command Option: -u module
     Use MODULE.  Before starting execution of SCHEME-FILE or entering
     the read-eval-print loop, the specified module is USEd, i.e.  it
     is loaded and imported (*Note Defining and selecting modules::,
     for details of `use').  You can specify this option more than once
     to use multiple modules.

 -- Command Option: -l file
     Load FILE before starting execution of SCHEME-FILE or entering the
     read-eval-print loop.   The file is loaded in the same way as
     `load' (*Note Loading Scheme file::).  You can specify this option
     more than once to load multiple files.

 -- Command Option: -e scheme-expression
     Evaluate SCHEME-EXPRESSION before starting execution of
     SCHEME-FILE or entering the read-eval-print loop.   Evaluation is
     done in the INTERACTION-ENVIRONMENT (*Note Eval and repl::).  You
     can specify this option more than once to evaluate multiple
     experssions.

 -- Command Option: -E scheme-expression
     Same as -e, except the SCHEME-EXPERSSION is read as if it is
     surrounded by parenthesis.  For example:
          % gosh -umath.const -E"print (sin (* pi/180 15))" -Eexit
          0.25881904510252074

 -- Command Option: -b
     Batch. Does not print prompts in read-eval-print loop even if the
     input is a terminal.

 -- Command Option: -i
     Interactive. Print prompts in read-eval-print loop even if the
     input is not a terminal.

 -- Command Option: -f compiler-option
     This option controls compiler and runtime behavior.  For now we
     have following options available:
    no-inline
          Prohibits the compiler from inilining primitive Scheme
          procedures.

    no-source-info
          Don't keep source information for debugging.  Consumes less
          memory.

    load-verbose
          Reports whenever a file is loaded.

    case-fold
          Ignore case for symbols as specified in R5RS.  (It is
          distinguished by default).  *Note Case-sensitivity::.

    test
          Adds "`../src'" and "`../lib'" to the load path before loading
          initialization file.  This is useful when you want to test the
          compiled `gosh' interpreter inside source tree, without
          installing it.

 -- Command Option: -p profiler-option
     Turn on the profiler.  Currnetly, only "`time'" is supported as
     PROFILER-OPTION.  See *Note Using profiler:: for the details of
     the profiler.

 -- Command Option: `--'
     When `gosh' sees this option, it stops processing the options and
     takes next command line argument as a script file.  It is useful
     in case if you have a script file that begins with a minus sign,
     although it is not generally recommended.

   The options -I, -A, -l, -u, -e and -E are processes in the order of
appearance.  For example, adding a load path by -I affects the -l and
-u option after it but not before it.

Environment variables
---------------------

The following enviornment variables are recognized:

 -- Environment variable: GAUCHE_LOAD_PATH
     You can specify additional load paths by this environment
     variable, delimiting the paths by '`:''.  The paths are appended
     before the system default load paths.

 -- Environment variable: GAUCHE_DYNLOAD_PATH
     You can specify additional load paths for dynamically loaded
     objects by this environment variable, delimiting the paths by
     '`:''.  The paths are appended before the system default load
     paths.


File: gauche-refe.info,  Node: Interactive development,  Next: Writing Scheme scripts,  Prev: Invoking Gosh,  Up: Programming in Gauche

3.2 Interactive development
===========================

When `gosh' is invoked without any script files, it goes into
interactive read-eval-print loop.

   To exit the interpreter, type EOF (usually Control-D in Unix
termials) or evaluate `(exit)'.

   In interactive session, `gosh' loads `gauche.interactive' module
(*Note Interactive session::) for the convenience.  The module also
loads a file `.gaucherc' under the user's home directory if it exists.
You may put settings there that would help interactive debugging.  (As
of Gauche release 0.7.3, `.gauchrc' is no longer loaded when `gosh' is
run in script mode.)

   I recommend you to run `gosh' inside Emacs, for it has rich features
useful to interact with internal Scheme process.  Put the following
line to your `.emacs' file:
     (setq scheme-program-name "gosh")
   And you can run `gosh' by <M-x run-scheme>.

   If you want to use multibyte characters in the interaction, make
sure your terminal's settings is in sync with `gosh''s internal
character encodings.

   Currently `gosh' has no fancy features such as line-editing or
command history.   They'll be added in future.


File: gauche-refe.info,  Node: Writing Scheme scripts,  Next: Debugging,  Prev: Interactive development,  Up: Programming in Gauche

3.3 Writing Scheme scripts
==========================

When a Scheme program file is given to `gosh', it bounds a global
varialbe `*argv*' to the list of the remaining command-line arguments,
then loads the Scheme program.  If the first line of SCHEME-FILE begins
with two character sequence "`#!'", the entire line is ignored by
`gosh'.  This is useful to write a Scheme program that works as an
executable script in unix-like systems.

   Typical Gauche script has the first line like these
     #!/usr/local/bin/gosh
       or,
     #!/usr/bin/env gosh
       or,
     #!/bin/sh
     :; exec gosh -- $0 "$@"
   The second and third form uses a "shell trampoline" technique so
that the script works as far as `gosh' is in the PATH.  The third form
is useful when you want to pass extra arguments to `gosh', for
typically `#!'-magic of executable scripts has limitations for the
number of arguments to pass the interpreter.

   After the file is successfully loaded, `gosh' calls a procedure
named ``main'' if it is defined in the user module.  `Main' receives a
single argument, a list of command line arguments.  Its first element
is the script name itself.

   When `main' returns, and its value is an integer, `gosh' uses it for
exit code of the program.  Otherwise, `gosh' exits with exit code 70
(`EX_SOFTWARE').  This behavior is compatible with the SRFI-22.

   If the `main' procedure is not defined, `gosh' exits after loading
the script file.

   Although you can still write the program main body as toplevel
expressions, like shell scripts or Perl scripts, it is much convenient
to use this ``main'' convention, for you can load the script file
interactively to debug.

 -- Variable: *argv*
     The program arguments passed to the Scheme script is bound to this
     variable.  If `gosh' is invoked in an interactive mode, this
     variable always contains `()'.

     STk uses this variable to pass the command line argument as well,
     but other Scheme implementations use different ways.  It is better
     to define `main' procedure and uses its argument to receive
     command line arguments, for it is expected to be more portable.

 -- Variable: *program-name*
     This variable is bound to the script file name passed to `gosh'.
     If `gosh' is invoked in the interactive mode, this variable
     contains the pathname of `gosh' itself.

     STk uses the same variable to access the program/script name.
     Other Scheme implementations use different ways.

   Now I show several simple examples below.  First, this script works
like `cat(1)', without any command-line option processing and error
handling.

     #!/usr/bin/env gosh

     (define (main args)   ;entry point
       (if (null? (cdr args))
           (copy-port (current-input-port) (current-output-port))
           (for-each (lambda (file)
                       (call-with-input-file file
                         (lambda (in)
                           (copy-port in (current-output-port)))))
                     (cdr args)))
       0)

   The following script is a simple grep command.

     #!/usr/bin/env gosh

     (define (usage)
       (format (current-error-port)
               "Usage: ~a regexp file ...\n" *program-name*)
       (exit 2))

     (define (grep rx port)
       (with-input-from-port port
         (lambda ()
           (port-for-each
            (lambda (line)
              (when (rxmatch rx line)
                (format #t "~a:~a: ~a\n"
                        (port-name port)
                        (- (port-current-line port) 1)
                        line)))
            read-line))))

     (define (main args)
       (if (null? (cdr args))
           (usage)
           (let ((rx (string->regexp (cadr args))))
             (if (null? (cddr args))
                 (grep rx (current-input-port))
                 (for-each (lambda (f)
                             (call-with-input-file f
                               (lambda (p) (grep rx p))))
                           (cddr args)))))
       0)

   See also *Note Parsing command-line options::, for a convenient way
to parse command-line options.


File: gauche-refe.info,  Node: Debugging,  Next: Profiling and tuning,  Prev: Writing Scheme scripts,  Up: Programming in Gauche

3.4 Debugging
=============

Gauche doesn't have much support for debugging yet.  The idea of good
debugging interfaces are welcome.

   For now, the author uses the classic 'debug print stub' technique
when necessary.  A special reader syntax `#?=EXPR' is defined, which is
read as `(debug-print EXPR)'.  The macro `debug-print' evaluates and
returns the result(s), printing messages before and after evaluation of
EXPR.

     gosh> #?=(+ 2 3)
     #?="(stdin)":1:(+ 2 3)
     #?-    5
     5
     gosh> #?=(begin (print "foo") (values 'a 'b 'c))
     #?="(stdin)":2:(begin (print "foo") (values 'a 'b 'c))
     foo
     #?-    a
     #?+    b
     #?+    c
     a
     b
     c
     gosh> (define (fact n)
             (if (zero? n)
                 1
                 (* n #?=(fact (- n 1)))))
     fact
     gosh> (fact 5)
     #?="(stdin)":6:(fact (- n 1))
     #?="(stdin)":6:(fact (- n 1))
     #?="(stdin)":6:(fact (- n 1))
     #?="(stdin)":6:(fact (- n 1))
     #?="(stdin)":6:(fact (- n 1))
     #?-    1
     #?-    1
     #?-    2
     #?-    6
     #?-    24
     120

   You can also use trace/untrace macros in Gauche, written by
Shigenobu Kimura: `http://homepage.mac.com/skimu/ggc/'.


File: gauche-refe.info,  Node: Profiling and tuning,  Next: Writing Gauche modules,  Prev: Debugging,  Up: Programming in Gauche

3.5 Profiling and tuning
========================

If you find your script isn't running fast enough, there are several
possibilities to improve its performance.

   It is always a good idea to begin with finding which part of the
code is consuming the execution time.   Gauche has a couple of basic
tools to help it.  A built-in sampling profiler, explained in the
following subsection, can show how much time is spent in each
procedure, and how many times it is called.  The `gauche.time' module
(*Note Measure timings::) provides APIs to measure execution time of
specific part of the code.

   Optimization is specialization--you look for the most common
patterns of execution, and put a special path to support those patterns
efficiently.  Gauche itself is no exception, so there are some patterns
Gauche can handle very efficiently, while some patterns it cannot.  The
next subsection, *Note Performance tips::, will give you some tips of
how to adapt your code to fit the patterns Gauche can execute well.

* Menu:

* Using profiler::
* Performance tips::


File: gauche-refe.info,  Node: Using profiler,  Next: Performance tips,  Prev: Profiling and tuning,  Up: Profiling and tuning

3.5.1 Using profiler
--------------------

As of 0.8.4, Gauche has a built-in profiler.  It is still experimental
quality and only be tested on Linux.  It isn't available for all
platforms.   It works only in single-thread applications for now.

   To use the profiler non-interactively, give `-ptime' command-line
option to gosh.

     % gosh -ptime your-script.scm

   After the execution of `your-script.scm' is completed, Gauche prints
out the table of functions with its call count and its consumed time,
sorted by the total consumed time.

     Profiler statistics (total 1457 samples, 14.57 seconds)
                                                         num    time/    total
     Name                                                calls  call(ms) samples
     ---------------------------------------------------+------+-------+-----------
     combinations*                                       237351  0.0142   337( 23%)
     (lset-difference #f)                               1281837  0.0020   256( 17%)
     (make-anchor make-anchor)                          3950793  0.0005   198( 13%)
     member                                             4627246  0.0004   190( 13%)
     filter                                              273238  0.0030    81(  5%)
     every                                              1315131  0.0004    59(  4%)
     (lset-difference #f #f)                            1281837  0.0004    54(  3%)
     (make-entry make-entry)                             730916  0.0005    40(  2%)
     (clear? #f)                                         730884  0.0005    33(  2%)
     (initialize #f)                                     599292  0.0005    32(  2%)
     fold                                                237307  0.0013    30(  2%)
     acons                                               806406  0.0004    29(  1%)
     clear?                                               33294  0.0084    28(  1%)
     (combinations* #f)                                  805504  0.0002    15(  1%)
     (make-exit make-exit)                               730884  0.0002    15(  1%)
     lset-difference                                     237318  0.0006    15(  1%)
     reverse!                                            475900  0.0001     6(  0%)
     (fold <top> <top> <list>)                           237323  0.0003     6(  0%)
     procedure?                                          238723  0.0002     4(  0%)
     pair?                                               237307  0.0001     3(  0%)
      :
      :

   Note that the time profiler uses statistic sampling.  Every 10ms the
profiler interrupts the process and records the function that is
executed then.   Compared to the individual execution time per function
call, which is the order of nanoseconds, this sampilng rate is very
sparse.  However, if we run the program long enough, we can expect the
distribution of samples per each function approximately reflects the
distribution of time spent in each function.

   Keep in mind that the number is only approximation; the number of
sample counts for a function may easily vary if the program deals with
different data.   It should also be noted that, for now, GC time is
included in the function in which GC is triggered.  This sometimes
causes a less important function to "float up" to near-top of the list.
To know the general pattern, it is a good custom to run the program
with several different data.

   On the other hand, the call count is accurate since Gauche actually
counts each call.

   Because all functions are basically anonymous in Scheme, the 'name'
field of the profiler result is only a hint.  The functions bound at
toplevel is generally printed with the global variable name it is bound
at the first time.  Internal functions are printed as a list of names,
reflecting the nesting of functions.  Methods are also printed as a
list of the name and specializers.

   The profiler has its own overhead; generally the total process time
will increase 20-30%.  If you want to turn on the profiler selectively,
or you're running a non-stop server program and want to obtain the
statistics without exitting the server, you can call the profiler API
from your program; see *Note Profiler API::, for the details.


File: gauche-refe.info,  Node: Performance tips,  Prev: Using profiler,  Up: Profiling and tuning

3.5.2 Performance tips
----------------------

Don't guess, just benchmark.  It is the first rule of performance
tuning.  Especially for the higher-level languages like Scheme, what
impacts on performance greatly depends on the implementation.  Certain
operations that are very cheap on an impelementation may be costly on
others.  Gauche has such implementation-specific characteristics, and
to know some of them would help to see what to look out in the
benchmark results.

   "80% of execution time is spent in 20% of the code" is another old
saying.  Don't obscure your code by "potential" optimization that has
little impact on the actual execution.  We describe some tips below,
but it doesn't mean you need to watch them all the time.  It is better
to keep most of the code clean and easy to understand, and only do
tricks on the innermost loop.

   *Ports*: To satisfy the specification of SRFI-18 (Threading), every
call to I/O primitives of Gauche locks the port.  This overhead may be
visible if the application does a lot of I/O with smaller units (e.g.
every bytes).   The primitives that deals with larger unit, such as
`read' and `read-block', are less problematic, since they just lock the
port once per call and do all the low-level I/O without the lock
overhead.

   If you find out the locking is indeed a bottleneck, there are couple
of things you can consider: (1) Try using the larger-unit primitives,
instead of calling the smaller-unit ones.  (2) Use `with-port-locking'
(see *Note Port and threads::) to lock the port in larger context.

   *Strings*: Because of the multibyte strings, two operations are
particularly heavy in Gauche: string mutation and indexed string access.
It is a design choice; we encourage the programming style that avoids
those operations.  When you sequentially access the string, string
ports (see *Note String ports::) provides a cleaner and more efficient
way.  When you search and retrieve a substring, there are various
higher-level primitives are provided (see *Note String utilities::,
*Note Regular expression::, and *Note String library::, for example).
If you're using strings to represent an octet stream, use uniform
vectors (see *Note Uniform vectors::) instead.

   *Deep recursion*: Gauche's VM uses a stack for efficient local frame
allocation.  If recursion goes very deep (depending on the code, but
usually several hundreds to a thousand), the stack overflows and Gauche
moves the content of the stack into the heap.  This incurs some
overhead.  If you observe a performance degradation beyond a certain
amount of data, check out this possibility.

   *Generic functions*: Because of its dynamic nature, generic function
calls are slower than procedure calls.  Not only because of the runtime
dispatch overhead, but also because Gauche's compile-time optimizer
can't do much optimization for generic function calls.  You don't need
to avoid generic functions because of performance reasons in general,
but if you do find single function call consuming a large part of
execution time and it is calling a generic function in its inner
loop--then it may be worth to modify it.

   *Redefining builtin functions*: Gauche inlines some builtin
functions if they are not redefined.  Although sometimes it is useful
to redefine basic functions, you may want to limit the effect.  For
example, put redefined functions in a separate module and use the
module in the code that absolutely needs those functions replaced.

   *Closure creation*: When you create a closure, its closing
environment is copied to the heap.  This overhead is small, but it
still may be visible when a closure is created within an innermost loop
that is called millions of times.   If you suspect this is a problem,
try disassemble the function.   Gauche's compiler uses some basic
technique of closure analysis to avoid creating closures for typical
cases, in which case you see the local function's bodies are inlined.
If you see a `CLOSURE' instruction, though, it means a closure is
created.

   This list isn't complete, and may change when Gauche's implementation
is improved, so don't take this as a fixed features.  We'll adjust it
occasionally.


File: gauche-refe.info,  Node: Writing Gauche modules,  Next: Using extension packages,  Prev: Profiling and tuning,  Up: Programming in Gauche

3.6 Writing Gauche modules
==========================

Gauche's libraries are organized by modules.   Although Gauche can load
any valid Scheme programs, there is a convention that Gauche library
follows.    When you write a chunk of Scheme code for Gauche, it is
convenient to make it a module, so that it can be shared and/or reused.

   Usually a module is contained in a file, but you can make a
multi-file module.  First I explain the structure of a single-file
module.  The following template is the convention used in Gauche's
libraries.

     ;; Define the module interface
     (define-module foo
       (use xxx)
       (use yyy)
       (export foo1 foo2 foo3)
       )
     ;; Enter the module
     (select-module foo)

     ... module body ...

     ;; Make `require' happy
     (provide "foo")

   This file must be saved as "foo.scm" in some directory in the
`*load-path*'.

   The `define-module' form creates a module `foo'.  It also loads and
imports some other modules by ``use'' macros, and declares which
symbols the `foo' module exports, by ``export'' syntax.  (See section
*Note Defining and selecting modules::, for detailed specification of
those syntaxes).

   Those `use' forms or `export' forms are not required to appeare in
the `define-module' form, but it is a good convention to keep them in
there at the head of the file so that it is visually recognizable which
modules `foo' depends and which symbols it exports.

   The second form, ``select-module'', specifies the rest of the file
is evaluated in the module `foo' you just defined.   Again, this is
just a convention; you can write entire module body inside
`define-module'.  However, I think it is error-prone, for the closing
parenthesis can be easily forgotten or the automatic indentation
mechanism of editor will be confused.

   After `select-module' you can write whatever Scheme expression.  It
is evaluated in the selected module, `foo'.   Only the bindings of the
exported symbols will be directly accessible from outside.

   The last `provide' form is just a cliche.  It is needed since the
`use' mechanism uses traditional require-provide mechanism (if you
don't know about it, it's ok-just put it as a magic spell).

   So, that's it.   Other programs can use your module by just saying
``(use foo)''.   If you want to make your module available on your site,
you can put it to the site library location, which can be obtained by
     (gauche-site-library-directory)
   in gosh, or
     gauche-config --sitelibdir
   from shell.

   If you feel like to conserve global module name space, you can
organize modules hierarchically.   Some Gauche libraries already does
so.  *Note Library modules - Overview::, for examples.  For example,
`text.tr' module is implemented in "text/tr.scm" file.  Note that the
pathname separator `/' in the file becomes a period in the module name.


File: gauche-refe.info,  Node: Using extension packages,  Prev: Writing Gauche modules,  Up: Programming in Gauche

3.7 Using extension packages
============================

Building and installing packages
--------------------------------

Gauche comes with some amount of libraries, but they aren't enough at
all to use Gauche in the production environment.  There are number of
additional libraries available.   We call them _extention packages_, or
simply packages.  Each package usually provides one or more modules
that adds extra functionality.   Most of the packages provide binding
to other C libraries, such as graphics libraries or database clients.
If the package has some C code, it is likely that you need to compile
it on your machine with the installed Gauche system.

   Usually a package is in the form of compressed tarball, and the
standard "ungzip + untar + configure + make + make install" sequence
does the job.  Read the package's document, for you may be able to
tailor the library for your own needs by giving command-line options to
the `configure' script.

   From Gauche 0.8, an utility script called `gauche-package' is
installed for the convenience.  It automates the build and install
process of packages.

   Suppose you have downloaded a package `Package-1.0.tar.gz'.  If the
package follows the convention, all you have to do is to type this:

     $ gauche-package install Package-1.0.tar.gz

   It ungzips and untars the package, `cd' into the `Package-1.0'
subdirectory, run configure, make, and make install.  By default,
`gauche-package' untars the tarball in the current working directory.
You can change it by a customization file; see below.

   If you need a special priviledge to install the files, you can use
`--install-as' option which runs `make install' part via the `sudo'
program.

     $ gauche-package install --install-as=root Package-1.0.tar.gz

   If it doesn't work for you, you can just build the package by
`gauche-package build Package-1.0.tar.gz', then manually cd to the
`Package-1.0' directory and run `make install'.

   You can give configuration optoins via `-C' or `--configure-options'
command-line argument, like this:

     $ gauche-package install -C "--prefix=/usr/local" Package-1.0.tar.gz

   If the package has adopted the new package description file, it can
remember the configuration options you have specified, and it will
automatically reuse them when you install the package again.  (If
you're a package developer, check out `examples/spigot/README' file in
the Gauche source tree to see how to cooperate with Gauche's package
management system.)

   If you don't have a tarball in your local directory, but you know
the URL where you can download it, you can directly give the URL to
`gauche-package'.  It understands `http' and `ftp', and uses either
`wget' or `ncftpget' to download the tarball, then runs configure and
make.

     $ gauche-package install http://www.example.com/download/Package-1.0.tar.gz

Customizing `gauche-package'
----------------------------

The `gauche-package' program reads `~/.gauche-package' if it exists.
It must contain an associative list of parameters.  It may look like
this:

     (
      (build-dir . "/home/shiro/tmp")
      (gzip      . "/usr/local/bin/gzip")
      (bzip2     . "/usr/local/bin/bzip2")
      (tar       . "/usr/local/bin/gtar")
     )

   The following is a list of recognized parameters.  If the program
isn't given in the configuration file, `gauche-package' searches `PATH'
to find one.

`build-dir'
     A directory where the tarball is extracted.  If URL is given, the
     downloaded file is also placed in this directory.

`bzip2'
     Path to the program `bzip2'.

`cat'
     Path to the program `cat'.

`make'
     Path to the program `make'.

`ncftpget'
     Path to the program `ncftpget'.

`rm'
     Path to the program `rm'.

`sudo'
     Path to the program `sudo'.

`tar'
     Path to the program `tar'.

`wget'
     Path to the program `wget'.


File: gauche-refe.info,  Node: Core syntax,  Next: Macros,  Prev: Programming in Gauche,  Up: Top

4 Core syntax
*************

* Menu:

* Lexical structure::
* Literals::
* Making Procedures::
* Assignments::
* Conditionals::
* Binding constructs::
* Sequencing::
* Iteration::
* Quasiquotation::
* Definitions::
* Modules::


File: gauche-refe.info,  Node: Lexical structure,  Next: Literals,  Prev: Core syntax,  Up: Core syntax

4.1 Lexical structure
=====================

Gauche extends R5RS Scheme parser in some ways:

_Nested block comments (SRFI-30)_
     A text surrounded by '`#|'' and '`|#'' becomes a comment.  It can
     be nested.

_Numeric literals_
     Either integral part or fraction part of inexact real numbers can
     be omitted if it is zero, i.e. `30.', `.25', `-.4' are read as
     real numbers.  The number reader recognizes '`#'' as insignificant
     digits.  Rational number syntax is recognized (e.g. `1/3'), but
     read as an inexact real number.  Complex numbers can be written
     both in the rectangular format (e.g. `1+0.3i') and in the polar
     format (e.g. 3.0@1.57).

_Symbol names_
     Symbol names are case sensitive by default (*Note
     Case-sensitivity::).  Symbol name can begin with digits, '`+'' or
     '`-'', as long as the entire token doesn't consist valid number
     syntax.  Other weird characters can be included in a symbol name
     by surrounding it with '|', e.g. '`|this is a symbol|''.  *Note
     Symbols::, for details.

_Character literal by character code_
     Character literals can be written using its code, by `#\xNN'
     (Gauche internal code) or `#\uNN' (Unicode).  *Note Characters::,
     for details.

_Extended sharp syntax_
     Many more special tokens begins with '`#'' are defined.  See the
     table below.

   The table below lists sharp-syntaxes.

`#!'               [SRFI-22] Specifies interpreter at the
                   beginning of file.        Scheme loader
                   ignores the line.
`#"', `##', `#$',  Unused.
`#%', `#&', `#''   
`#('               [R5RS] Introduces a vector.
`#)'               Unused.
`#*'               If followed by a double quote, denotes an
                   incomplete string.  *Note Strings::.
`#+'               Unused.
`#,'               [SRFI-10] Introduces reader constructor
                   syntax.
`#-', `#.'         Unused.
`#/'               Introduces a literal regular expression.
                   *Note Regular expression::.
`#0' ... `#9'      [SRFI-38] Shared substructure definition and
                   reference.
`#:', `#;'         Unused
`#<'               Introduces an unreadable object.
`#=', `#>'         Unused.
`#?'               Introduces debug macros.  *Note Debugging::.
`#@'               Unused.
`#a'               Unused.
`#b'               [R5RS] Binary number prefix.
`#c'               Unused.
`#d'               [R5RS] Decimal number prefix.
`#e'               [R5RS] Exact number prefix.
`#f'               [R5RS] Boolean false, or       introducing
                   SRFI-4 uniform vector.  *Note Uniform
                   vectors::.
`#g', `#h'         Unused.
`#i'               [R5RS] Inxact number prefix.
`#j', `#k', `#l',  Unused.
`#m', `#n'         
`#o'               [R5RS] Octal number prefix.
`#p', `#q', `#r'   Unused.
`#s'               [SRFI-4] introducing SRFI-4 uniform vector.
                   *Note Uniform vectors::.
`#t'               [R5RS] Boolean true.
`#u'               [SRFI-4] introducing SRFI-4 uniform vector.
                   *Note Uniform vectors::.
`#v', `#w'         Unused.
`#x'               [R5RS] Hexadecimal number prefix.
`#y', `#z'         Unused.
`#['               Introduces a literal character set.  *Note
                   Character set::.
`#\'               [R5RS] Introduces a literal character.
                   *Note Characters::.
`#]', `#^', `#_'   Unused.
`#`'               Introduces an interpolated string.  *Note
                   String interpolation::.
`#{'               Unused.
`#|'               [SRFI-30] Introduces a block comment.
                   Comment ends by matching '`|#''.
`#}', `#~'         Unused.


File: gauche-refe.info,  Node: Literals,  Next: Making Procedures,  Prev: Lexical structure,  Up: Core syntax

4.2 Literals
============

 -- Special Form: quote datum
     [R5RS] Evaluates to DATUM.
          (quote x) => x
          (quote (1 2 3)) => (1 2 3)

 -- Reader Syntax: `'DATUM'
     [R5RS] Equivalent to `(quote datum)'.
          'x => x
          '(1 2 3) => (1 2 3)

_Note:_  R5RS says it is an error to alter the value of a literal
expression.  Gauche doesn't check constant-ness of pairs and vectors,
so you can alter them using the destructive procedures such as
`set-car!' and `vector-set!'.  Doing so will cause unexpected results.
Gauche does check constant-ness of strings, and signals an error if you
try to alter a constant string.


File: gauche-refe.info,  Node: Making Procedures,  Next: Assignments,  Prev: Literals,  Up: Core syntax

4.3 Making Procedures
=====================

 -- Special Form: lambda formals body ...
     [R5RS] Evaluates to a procedure.  The environment in effect when
     this expression is evaluated is stored in the procedure.   When
     the procedure is called, BODY is evaluated sequentially in the
     stored environment extended by the bindings of the formal
     arguments, and returns the value(s) of the last expression in the
     body.

     FORMALS should have one of the following forms:
        * `(VARIABLE ...)' : The procedure takes a fixed number of
          arguments.  The actual arguments are bound to the
          corresponding variables.

        * `VARIABLE' : The procedure takes any number of argumnets.
          The actual arguments are collected to form a new list and
          bound to the variable.

        * `(VARIABLE_0 ... VARIABLE_N-1. VARIABLE_N)' : The procedure
          takes at least N arguments.  The actual arguments up to N is
          bound to the corresponding varibles.  If more than N
          arguments are given, the rest arguments are collected to form
          a new list and bound to VARIABLE_N.

          (lambda (a b) (+ a b))
            => procedure that adds two arguments

          ((lambda (a b) (+ a b)) 1 2)
            => 3

_Note:_ Some Scheme implementations extend the syntax of FORMALS to
have notation of optional arguments or keyword arguments, similar to
CommonLisp's.  Gauche doesn't have such extensions now.

 -- Macro: cut expr-or-slot expr-or-slot2 ...
 -- Macro: cute expr-or-slot expr-or-slot2 ...
     [SRFI-26] Convenience macros to notate a procedure compactly.
     This form can be used to realize partial application, a.k.a
     sectioning or projection.

     Each EXPR-OR-SLOT must be either an expression or a symbol `<>',
     indicating a 'slot'.  The last EXPR-OR-SLOT can be a symbol
     `<...>', indicating a 'rest-slot'.  `Cut' expands into a `lambda'
     form that takes as many arguments as the number of slots in the
     given form, and whose body is an expression
            (EXPR-OR-SLOT EXPR-OR-SLOT2 ...)
     where each occurrence of `<>' is replaced to the corresponding
     argument.  In case there is a rest-slot symbol, the resulting
     procedure is also of variable arity, and all the extra arguments
     are passed to the call of EXPR-OR-SLOT.  See the fourth example
     below.

          (cut cons (+ a 1) <>)  == (lambda (x2) (cons (+ a 1) x2))
          (cut list 1 <> 3 <> 5) == (lambda (x2 x4) (list 1 x2 3 x4 5))
          (cut list)             == (lambda () (list))
          (cut list 1 <> 3 <...>)
             == (lambda (x2 . xs) (apply list 1 x2 3 xs))
          (cut <> a b)           == (lambda (f) (f a b))

          ;; Usage
          (map (cut * 2 <>) '(1 2 3 4))
          (for-each (cut write <> port) exprs)

     `Cute' is a variation of `cut' that evaluates `expr-or-slot's
     before creating the procedure.

          (cute cons (+ a 1) <>)
             == (let ((xa (+ a 1))) (lambda (x2) (cons xa x2)))

     Gauche also has a built-in procedure `pa$' for partial application
     (*Note Combinators::).

 -- Macro: case-lambda clause ...
     [SRFI-16] Each CLAUSE should have the form (FORMALS EXPR ...),
     where FORMALS is a formal arguments list as for `lambda'.

     This expression evaluates to a procedure that accepts a variable
     number of arguments and is lexically scoped in the same manner as
     procedures resulting from `lambda' expressions.  When the
     procedure is called with some arguments, then the first CLAUSE for
     which the arguments agree with FORMALS is selected, where
     agreement is specified as for the FORMALS of a `lambda' expression.
     The variables of `formals' are bound to the given arguments, and
     the EXPR ... are evaluated within the environment.

     It is an error for the arguments not to agree with the FORMALS of
     any CLAUSE.


File: gauche-refe.info,  Node: Assignments,  Next: Conditionals,  Prev: Making Procedures,  Up: Core syntax

4.4 Assignments
===============

 -- Special Form: set! symbol expression
 -- Special Form: set! (proc arg ...) expression
     [R5RS][SRFI-17] First, EXPRESSION is evaluated.  In the first
     form, the binding of SYMBOL is modified so that next reference of
     SYMBOL will return the result of EXPRESSION.  If SYMBOL is not
     locally bound, the global variable named SYMBOL must already
     exist, or an error is signalled.

     The second form is a "generalized set!" specified in SRFI-17.  It
     is a syntactic sugar of the following form.
          ((setter PROC) ARG ... EXPRESSION)
     Note the order of the arguments of the setter method differs from
     CommonLisp's `setf'.

     Some examples:

          (define x 3)
          (set! x (list 1 2))  => undefined
          x                    => (1 2)

          (set! (car x) 5)     => undefined
          x                    => (5 2)

 -- Macro: set!-values (var ...) expr
     Sets values of multiple variables at once.  EXPR must yield as
     many values as VAR ....  Each value is set to the corresponding
     VAR.
          (define a 0)
          (define b 1)
          (set!-values (a b) (values 3 4)) => undefined
          a => 3
          b => 4
          (set!-values (a b) (values b a)) => undefined
          a => 4
          b => 3

 -- Function: setter proc
     [SRFI-17] Returns a setter procedure associated to the procedure
     PROC.  If no setter is associated to PROC, its behavior is
     undefined.

     A setter procedure G of a procedure F is such that when used as
     `(g a b ... v)', the next evaluation of `(f a b ...)' returns V.

     To associate a setter procedure to another procedure, you can use
     the setter of `setter', like this:
          (set! (setter F) G)

     A procedure's setter can be "locked" to it.  System default
     setters, like `set-car!' for `car', is locked and can't be set by
     the above way.   In order to lock a setter to a user defined
     procedure, use `getter-with-setter' below.

     If PROC is not a procedure, a setter generic function of
     `object-apply' is returned; it allows the applicable object
     extension to work seamlessly with the generalized `set!'.  *Note
     Applicable objects::, for the details.

 -- Function: has-setter? proc
     Returns `#t' if a setter is associated to PROC.

 -- Function: getter-with-setter get set
     [SRFI-17] Takes two procedure GET and SET.  Returns a new
     procedure which does the same thing as GET, and its setter is
     locked to SET.

     The intention of this procedure is, according to the SRFI-17
     document, to allow implementations to inline setters efficiently.
     Gauche hasn't implement such optimization yet.

   A few macros that adopts the same semantics of generalized `set!'
are also provided.  They are built on top of `set!'.

 -- Macro: push! place item
     Conses ITEM and the value of PLACE, then sets the result to PLACE.
     PLACE is either a variable or a form (PROC ARG ...), as the second
     argument of `set!'.   The result of this form is undefined.

          (define x (list 2))
          (push! x 3) => undefined
          x => (3 2)

          (push! (cdr x) 4) => undefined
          x => (3 4 2)

     When PLACE is a list, it roughly expands like the following.

          (push! (foo x y) item)
           ==
           (let ((tfoo foo)
                 (tx x)
                 (ty y))
             ((setter tfoo) tx ty (cons item (tfoo tx ty))))

     Note: Common Lisp's `push' macro takes its argument reverse order.
      I adopted this order since it is consistent with other
     destructive operations.  Perl's `push' function takes the same
     argument order, but it appends ITEM at the end of the array
     (Perl's `unshift' is closer to `push!').  You can use a queue
     (*Note Queue::) if you need a behavior of Perl's `push'.

 -- Macro: pop! place
     Retrieves the value of PLACE, sets its cdr back to PLACE and
     returns its car.

          (define x (list 1 2 3))
          (pop! x) => 1
          x => (2 3)

          (define x (vector (list 1 2 3)))
          x => #((1 2 3))
          (pop! (vector-ref x 0)) => 1
          x => #((2 3))

     Note: This works the same as Common Lisp's `pop'.  Perl's `pop'
     pops value from the end of the sequence; its `shift' does the same
     thing as `pop!'.

 -- Macro: inc! place &optional delta
 -- Macro: dec! place &optional delta
     Evaluates the value of PLACE.  It should be a number.  Adds
     (`inc!') or subtracts (`dec!') DELTA to/from it, and then stores
     the result to PLACE.  The default value of DELTA is 1.

     This is Common Lisp's `incf' and `decf'.

 -- Macro: update! place proc
     Generalized form of `push!' etc.  PROC must be a procedure which
     takes one argument and returns one value.   The original value of
     PLACE is passed to the PROC, then its result is set to PLACE.
          (define a (cons 2 3))
          (update! (car a) (lambda (v) (* v 3))) => undefined
          a => (6 . 3)

          (update! (cdr a) (cut - <> 3))
          a => (6 . 0)


File: gauche-refe.info,  Node: Conditionals,  Next: Binding constructs,  Prev: Assignments,  Up: Core syntax

4.5 Conditionals
================

 -- Special Form: if test consequent alternative
 -- Special Form: if test consequent
     [R5RS] TEST is evaluated.  If it yields a true value, CONSEQUENT
     is evaluated.  Otherwise, ALTERNATIVE is evaluated.  If
     ALTERNATIVE is not provided, it results undefined value.

          (if (number? 3) 'yes 'no) => yes
          (if (number? #f) 'yes 'no) => no

          (let ((x '(1 . 2)))
            (if (pair? x)
                (values (car x) (cdr x))
                (values #f #f)))
            => 1 and 2

 -- Special Form: cond clause1 clause2 ...
     [R5RS] Each `clause' must be the form
          (TEST EXPR ...)
          (TEST => EXPR)
          (else EXPR EXPR2 ...)
     The last form can appear only as the last clause.

     `cond' evaluates TEST of each clauses in order, until it yields a
     true value.   Once it yields true, if the clause is the first
     form,  the corresponding EXPRs are evaluated and the result(s) of
     last EXPR is(are) returned; if the clause is the second form, the
     EXPR is evaluated and it must yield a procedure that takes one
     argument.  Then the result of TEST is passed to it, and the
     result(s) it returns will be returned.  If no test yields true,
     and the last clause is not the third form (else clause), an
     undefined value is returned.

     If the last clause is else clause and all tests are failed, EXPRs
     in the else clause are evaluated, and its last EXPR's result(s)
     is(are) returned.

          (cond ((> 3 2) 'greater)
                ((< 3 2) 'less)) => greater
          (cond ((> 3 3) 'greater)
                ((< 3 3) 'less)
                (else 'equal)) => equal
          (cond ((assv 'b '((a 1) (b 2))) => cadr)
                (else #f)) => 2

 -- Special Form: case key clause1 clause2 ...
     [R5RS] KEY may be any expression.  Each CLAUSE should have the form
          ((DATUM ...) EXPR EXPR2 ...)
     where each DATUM is an external representation of some object.
     All the DATUMs must be distinct. The last CLAUSE may be an "else
     clause," which has the form
          (else EXPR EXPR2 ...)

     First, KEY is evaluated and its result is compared against each
     DATUM.  If the result of evaluating DATUM is equivalent (using
     `eqv?', *Note Equivalence::), to a DATUM, then the expressions in
     the corresponding clause are evaluated sequentially, and the
     result(s) of the last expression in the CLAUSE is(are) returned
     from the case expression.  If the result of evaluating KEY is
     different from every DATUM, then if there is an else clause its
     expressions are evaluated and the result(s) of the last is(are)
     the result(s) of the case expression; otherwise the result of the
     case expression is unspecified.
          (case (* 2 3)
            ((2 3 5 7) 'prime)
            ((1 4 6 8 9) 'composite)) => composite
          (case (car '(c d))
            ((a) 'a)
            ((b) 'b)) => undefined
          (case (car '(c d))
            ((a e i o u) 'vowel)
            ((w y) 'semivowel)
            (else 'consonant)) => consonant

 -- Special Form: and test ...
     [R5RS] The TEST expressions are evaluated from left to right, and
     the value of the first expression that evaluates to a false value
     is returned.  Any remaining expressions are not evaluated.  If all
     the expressions evaluate to true values, the value of the last
     expression is returned.  If there are no expressions then `#t' is
     returned.

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

 -- Special Form: or test ...
     [R5RS] The TEST expressions are evaluated from left to right, and
     the value of the first expression that evaluates to a true value
     is returned. Any remaining expressions are not evaluated.  If all
     expressions evaluate to false values, the value of the last
     expression is returned. If there are no expressions then `#f' is
     returned.

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

 -- Special Form: when test body ...
 -- Special Form: unless test body ...
     Evaluates TEST.  If it yields true value (or false in case of
     `unless'), BODY ... are evaluated sequentially, and the result(s)
     of the last evaluation is(are) returned.  Otherwise, undefined
     value is returned.


File: gauche-refe.info,  Node: Binding constructs,  Next: Sequencing,  Prev: Conditionals,  Up: Core syntax

4.6 Binding constructs
======================

 -- Special Form: let ((var expr) ...) body ...
 -- Special Form: let* ((var expr) ...) body ...
 -- Special Form: letrec ((var expr) ...) body ...
     [R5RS] Creates a local scope where VAR ... are bound to the value
     of EXPR ..., then evaluates BODY ....  VARs must be symbols, and
     there shouldn't be a duplication.  The value(s) of the last
     expression of BODY ... becomes the value(s) of this form.

     The three forms differ in terms of the scope EXPRs are evaluated.
     `Let' evaluates EXPRs before (outside of) `let' form.  `Let*'
     evaluates EXPRs in the scope where VARs before it are bound.
     `Letrec' evaluates EXPRs in the environment where VARs are already
     bound (to an undefined value, initially).  `letrec' is necessary
     to define mutually recursive local procedures.
          (define x 'top-x)

          (let  ((x 3) (y x)) (cons x y)) => (3 . top-x)
          (let* ((x 3) (y x)) (cons x y)) => (3 . 3)

          (let ((cons (lambda (a b) (+ a b)))
                (list (lambda (a b) (cons a (cons b 0)))))
            (list 1 2))  => (1 2 . 0)

          (letrec ((cons (lambda (a b) (+ a b)))
                   (list (lambda (a b) (cons a (cons b 0)))))
            (list 1 2))  => 3

 -- Macro: let1 var expr body ...
     A convenient macro when you have only one variable.  Expanded as
     follows.

          (let ((VAR EXPR)) BODY ...)

 -- Macro: fluid-let ((var val) ...) body ...
     A macro that emulates dynamic scoped variables.  VARs must be
     variables bound in the scope including `fluid-let' form.  VALs are
     expressions.  `Fluid-let' first evaluates VALs, then evaluates
     BODY ..., with binding VARs to the corresponding values during the
     dynamic scope of BODY ....

     Note that, in multithreaded environment, the change of the value
     of VARs are visible from all the threads.   This form is provided
     mainly for the porting convenience.   Use parameter objects instead
     (*Note Parameters::) for thread-local dynamic state.
          (define x 0)

          (define (print-x) (print x))

          (fluid-let ((x 1))
            (print-x))  => ;; prints 1

 -- Special Form: receive formals expression body ...
     [SRFI-8] This is the way to receive multiple values.  FORMALS can
     be a (maybe-improper) list of symbols.  EXPRESSION is evaluated,
     and the returned value(s) are bound to FORMALS like the binding of
     lambda formals, then BODY ... are evaluated.

          (define (divrem n m)
            (values (quotient n m) (remainder n m)))

          (receive (q r) (divrem 13 4) (list q r))
            => (3 1)

          (receive all (divrem 13 4) all)
            => (3 1)

          (receive (q . rest) (divrem 13 4) (list q rest)
            => (3 (1))

     See also `call-with-values' in *Note Multiple values:: which is
     the procedural equivalent of `receive'.  You can use
     `define-values' (*Note Definitions::) to bind multiple values to
     the toplevel variables simultaneously.  Also `let-values' and
     `let*-values' in SRFI-11 (*Note Let-values::) provides `let'-like
     syntax with multiple values.

 -- Macro: rec var expr
 -- Macro: rec (name . vars) expr ...
     [SRFI-31] A macro to evaluate an expression with recursive
     reference.

     In the first form, evaluates expr while VAR in EXPR is bound to
     the result of EXPR.  The second form is equivalent to the
     followings.
          (rec NAME (lambda VARS EXPR ...))

     Some examples:

          ;; constant infinite stream
          (rec s (cons 1 (delay s)))

          ;; factorial function
          (rec (f n)
            (if (zero? n)
                1
                (* n (f (- n 1)))))


File: gauche-refe.info,  Node: Sequencing,  Next: Iteration,  Prev: Binding constructs,  Up: Core syntax

4.7 Sequencing
==============

 -- Special Form: begin form ...
     [R5RS] Evaluates FORMs sequentially, and returns the last
     result(s).

     `Begin' doesn't introduce new "block" like `let', that is, you
     can't place "internal define" at the beginning of FORMs generally.
      Semantically `begin' behaves as if FORMs are spliced into the
     surrounding context.  For example, topleve expression like the
     following is the same as two toplevel definitions:

          (begin (define x 1) (define y 2))

     Here's a trickier example:

          (let ()
            (begin
              (define x 2)
              (begin
                (define y 3)
              ))
            (+ x y))

            ==

          (let ()
            (define x 2)
            (define y 3)
            (+ x y))

 -- Macro: begin0 exp0 exp1 ...
     Evaluates EXP0, EXP1, ..., then returns the result(s) of EXP0.
     The name is taken from MzScheme.  This is called `prog1' in
     CommonLisp.

     Unlike `begin', this _does_ creates a "block", for the `begin0'
     form is expanded as follows.

          (receive tmp EXP0
            EXP1 ...
            (apply values tmp))


File: gauche-refe.info,  Node: Iteration,  Next: Quasiquotation,  Prev: Sequencing,  Up: Core syntax

4.8 Iteration
=============

 -- Special Form: do ((variable init [step]) ...) (test expr ...) body
          ...
     [R5RS]

 -- Special Form: let name bindings body ...
     [R5RS]

 -- Macro: dotimes (variable limit [result]) body ...
 -- Macro: dolist (variable lexpr [result]) body ...
     Imported from Common Lisp.  These are equivalent to the following
     forms, respectively.
          (dotimes (variable limit result) body ...)
          ==>
          (do ((tlimit limit)
               (variable 0 (+ variable 1)))
              ((>= variable tlimit) result)
            body ...)

          (dolist (variable lexpr result) body ...)
          ==>
          (begin
            (for-each (lambda (variable) body ...) lexpr)
            (let ((variable '())) result))


File: gauche-refe.info,  Node: Quasiquotation,  Next: Definitions,  Prev: Iteration,  Up: Core syntax

4.9 Quasiquotation
==================

 -- Special Form: quasiquote template
     [R5RS]


File: gauche-refe.info,  Node: Definitions,  Next: Modules,  Prev: Quasiquotation,  Up: Core syntax

4.10 Definitions
================

 -- Special Form: define variable expression
 -- Special Form: define (variable . formals) body ...
     [R5RS] This form has different meanings in the toplevel (without no
     local bindings) or inside a local scope.

     On toplevel, it defines a global binding to a symbol VARIABLE.  In
     the first form, it globally binds a symbol VARIABLE to the value
     of EXPRESSION, in the current module.
          (define x (+ 1 2))
          x => 3
          (define y (lambda (a) (* a 2)))
          (y 8) => 16

     The second form is a syntactic sugar of defining a procedure.  It
     is equivalent to the following form.
          (define (NAME . ARGS) BODY ...)
            == (define NAME (lambda ARGS BODY ...))

     If the form appears inside a local scope (internal define), this
     introduce a local binding of the variable.

     Note that `begin' (*Note Sequencing::) doesn't introduce a new
     scope.  `Define's in the `begin' act as if `begin' and surrounding
     parenthesis are not there.  Thus these two forms are equivalent.
          (let ((x 0))
            (begin
              (define (foo y) (+ x y)))
            (foo 3))
           ==
          (let ((x 0))
            (define (foo y) (+ x y))
            (foo 3))

 -- Macro: define-values (var ...) expr
     EXPR is evaluated, and it should return as many values as VARs.
     Then each value of the results are bound to each variable in VAR
     ....  *Note Let-values::.
          (define-values (lo hi) (min&max 3 -1 15 2))

          lo => -1
          hi => 15

 -- Special Form: define-constant variable expression
 -- Special Form: define-constant (variable . formals) body ...
     Like `define', but that the compiler assumes the value of VARIABLE
     won't change and generates optimized code.

     An error is signalled when you use `set!' to change the value of
     VARIABLE.   It is allowed to redefine VARIABLE, but a warning is
     printed.

 -- Special Form: define-in-module module variable expression
 -- Special Form: define-in-module module (variable . formals) body ...
     This form creates a global binding of VARIABLE in MODULE, which
     must be either a symbol of the module name or a module object.  If
     MODULE is a symbol, the named module must exist.

     EXPRESSION is evaluated in the current module.

     The second form is merely a syntactic sugar of:
          (define-in-module module variable (lambda formals body ...))

   Note: to find out if a symbol has definition (global binding) in the
current module, you can use `symbol-bound?' (*Note Module
introspection::).


File: gauche-refe.info,  Node: Modules,  Prev: Definitions,  Up: Core syntax

4.11 Modules
============

This section describes the semantics of Gauche modules and its API.
See also *Note Writing Gauche modules::, for the conventions Gauche is
using for its modules.

* Menu:

* Module semantics::
* Modules and libraries::
* Defining and selecting modules::
* Using modules::
* Module inheritance::
* Module introspection::
* Predefined modules::


File: gauche-refe.info,  Node: Module semantics,  Next: Modules and libraries,  Prev: Modules,  Up: Modules

4.11.1 Module semantics
-----------------------

Module is an object that maps symbols onto _bindings_, and affects the
resolution of global variable reference.

   Unlike CommonLisp's packages, which map names to symbols, in Gauche
symbols are always `eq?' if two have the same name.  However, Gauche's
symbol doesn't have a 'value' slot in it.  From a given symbol, a
module finds its binding that keeps a value.  Different modules can
associate different bindings to the same symbol, that yield different
values.

     ;; Makes two modules A and B, and defines a global variable 'x' in them
     (define-module A (define x 3))
     (define-module B (define x 4))

     ;;  #<symbol 'x'> ---[module A]--> #<binding that has 3>
     (with-module A x) => 3

     ;;  #<symbol 'x'> ---[module B]--> #<binding that has 4>
     (with-module B x) => 4

   A module can _export_ a part or all of its bindings for other module
to use.  A module can _import_ other modules, and their exported
bindings become visible to the module.  A module can import any number
of modules.

     (define-module A
       (export pi)
       (define pi 3.1416))

     (define-module B
       (export e)
       (define e 2.71828))

     (define-module C
       (import A B))

     (select-module C)
     (* pi e) => 8.539748448

   A module can also be _inherited_, that is, you can extend the
existing module by inheriting it and adding new bindings and exports.
From the new module, all ancestor's bindings (including non-exported
bindings) are visible.  (A new module inherits the `gauche' module by
default, which is why the built-in procedures and syntax of `gauche'
are available in the new module).  From outside, the new module looks
like having all exported bindings of the original module plus the newly
defined and exported bindings.

     ;; Module A defines and exports deg->rad.
     ;; A binding of pi is not exported.
     (define-module A
       (export deg->rad)
       (define pi 3.1416)   ;; not exported
       (define (deg->rad deg) (* deg (/ pi 180))))

     ;; Module Aprime defines and exports rad->deg.
     ;; The binding of pi is visible from inside Aprime.
     (define-module Aprime
       (extend A)
       (export rad->deg)
       (define (rad->deg rad) (* rad (/ 180 pi))))

     ;; Module C imports Aprime.
     (define-module C
       (import Aprime)
       ;; Here, both deg->rad and rad->deg are visible,
       ;; but pi is not visible.
       )

   At any moment of the compilation, there is one "current module"
available, and the global variable reference is looked for from the
module.  If there is a visible binding of the variable, the variable
reference is compiled to the access of the binding.  If the compiler
can't find a visible binding, it marks the variable reference with the
current module, and delays the resolution of binding at the time the
variable is actually used.  That is, when the variable is referenced at
run time, the binding is again looked for from the marked module (_not_
the current module at the run time) and if found, the variable
reference code is replaced for the the code to access the binding.  If
the variable reference is not found even at run time, an 'undefined
variable' error is signalled.

   Once the appropriate binding is found for the global variable, the
access to the binding is hard-wired in the compiled code and the global
variable resolution will never take place again.

   The definition special form such as `define' and `define-syntax'
inserts the binding to the current module.   Thus it may shadow the
binding of imported or inherited modules.

   The resolution of binding of a global variable happens like this.
First, the current module is searched.  Then, each imported module is
taken in the reverse order of import, and searched, including each
module's ancestors.  Note that import is not transitive; imported
module list is not chased recursively.  Finally, ancestors of the
current module are searched in order.

   This order is important when more than one modules defines the same
name and your module imports both.  Assuming your module don't define
that name, if you first import a module `A' then a module `B', you'll
see `B''s binding.

   If you import `A', then `B', then `A' again, the last import takes
precedence; that is, you'll see `A''s binding.


File: gauche-refe.info,  Node: Modules and libraries,  Next: Defining and selecting modules,  Prev: Module semantics,  Up: Modules

4.11.2 Modules and libraries
----------------------------

Modules are run-time data structure; you can procedurally create
modules with arbitrary names at run-time.

   However, most libraries use modules to create their own namespace,
so that they can control which bindings to be visible from library
users.

   Usually a library is provided in the form of one or more Scheme
source file(s), so it is convenient to have a convention to map module
names to file names, and vice versa; then, you can load a library file
and import its module by one action with `use' macro, for example.

   For the time being, Gauche uses a simple rules for this mapping:
Module names are organized hierarchically, using period ``.'' for
separator, e.g. `gauche.mop.validator'.  If such a module is requested
and doesn't exist in the current running environment, Gauche maps the
module name to a pathname by replacing periods to directory separator,
i.e.  `gauche/mop/validator', and look for `gauche/mop/validator.scm'
in the load paths.

   Note that this is just a default behavior.  Theoretically, one
Scheme source file may contain multiple modules, or one module
implementation may span to multiple files.  In future, there may be
some hook to customize this mapping for special cases.  So, when you
are writing routines that deal with modules and library files, do not
apply the above default rule blindly.   Gauche provides two procedures,
`module-name->path' and `path->module-name', to do mapping for you (see
*Note Module introspection::, for details).


File: gauche-refe.info,  Node: Defining and selecting modules,  Next: Using modules,  Prev: Modules and libraries,  Up: Modules

4.11.3 Defining and selecting modules
-------------------------------------

 -- Special Form: define-module name body ...
     NAME must be a symbol.  If a module named NAME does not exist,
     create one.  Then evaluates BODY sequentially in the module.

 -- Special Form: select-module name
     Makes a module named NAME as the current module.  It is an error
     if no module named NAME exists.

     If `select-module' is used in the Scheme file, its effect is
     limited inside the file, i.e. even if you load/require a file that
     uses `select-module' internallly, the current module of requirer is
     not affected.

 -- Special Form: with-module name body ...
     Evaluates BODY sequentially in the module named NAME.  Returns the
     last result(s).  If no moudle named NAME, an error is signalled.

 -- Special Form: current-module
     Evaluates to the current module in the compile context.  Note that
     this is a special form, not a function.  Module in Gauche is
     statically determined at compile time.
          (define-module foo
            (export get-current-module)
            (define (get-current-module) (module-name (current-module))))

          (define-module bar
            (import foo)
            (get-current-module)) => foo ; not bar


File: gauche-refe.info,  Node: Using modules,  Next: Module inheritance,  Prev: Defining and selecting modules,  Up: Modules

4.11.4 Using modules
--------------------

 -- Special Form: export symbol ...
     Makes bindings of SYMBOLs in the current module available to
     modules that imports the current module.

 -- Special Form: export-all
     Makes all bindings in the current module available to modules that
     imports it.

 -- Special Form: import module-name ...
     Makes all exported bindings in the module named MODULE-NAME
     available in the current module.   The named modules should exist
     when the compiler sees this special form.

     Note that imports are not transitive.  The modules that
     MODULE-NAMEs are importing are not automatically imported to the
     current module.  This keeps modules' modularity; a library module
     can import whatever modules it needs without worring about
     polluting the namespace of the user of the module.

 -- Macro: use name
     A convenience macro that combines module imports and on-demand
     file loading.  Basically, `(use foo)' is equivalent to the
     following two forms:
          (require "foo")
          (import foo)
     That is, it loads the library file named "`foo'" (if not yet
     loaded) which defines a module named `foo' in it, and then import
     the module `foo' into the current module.

     Although the files and modules are orthogonal concept, it is
     practically convenient to separate files by modules.  Gauche
     doesn't force you to do so, and you can always use `require' and
     `import' separately.  However, all modules provided with Gauche
     are arranged so that they can be used by `use' macro.

     If a module is too big to fit in one file, you can split them into
     several subfiles and one main file.  The main file defines the
     module, and either loads, requires, or autoloads subfiles.

     Actually, the file pathname of the given module name is obtained
     by the procedure `module-name->path' below.  The default rule is
     to replace periods ``.'' in the NAME for ``/'';  for example,
     `(use foo.bar.baz)' is expanded to:
          (require "foo/bar/baz")
          (import foo.bar.baz)
     This is not very Scheme-ish way, but nevertheless convenient.  In
     future, there may be some mechanism to customize this mapping.


File: gauche-refe.info,  Node: Module inheritance,  Next: Module introspection,  Prev: Using modules,  Up: Modules

4.11.5 Module inheritance
-------------------------

The export-import mechanism doesn't work well in some cases, such as:

   * You want to create a module that is mostly the same as the
     existing one, but adding or altering some definitions.

   * You wrote a bunch of related modules that are often used together,
     and not want your users to repeat a bunch of 'use' forms every time
     they use your module.

   You can use module inheritance in these cases.

 -- Macro: extend module-name ...
     Makes the current module inherit from named modules.  The current
     inheritance information is altered by the inheritance information
     calculated from given modules.

     A new module inherits from `gauche' module when created.  If you
     put `(extend scheme)' in that module, for example, the module
     resets to inherit directly from `scheme' module that has only
     bindings defined in R5RS, hence, after the export form, you can't
     use 'import' or any other `gauche'-specific bindings in the module.

     If a named module is not defined yet, `extend' tries to load it,
     using the same convention `use' macro does.

     A module can inherit multiple modules, exactly the same way as a
     class can inherit from multiple classes.  The resolution of order
     of inheritance needs to be explained a bit.

     Each module has a _module precedence list_, which lists modules in
     the order of how they are searched.  When the module inherits
     multiple modules, module precedence lists of inherited modules are
     merged into a single list, keeping the constraints that: (1) if a
     module A appears before module B in some module precedence list, A
     has to appear before B in the resulting module precedence list;
     and (2) if a module A appears before module B in `extend' form, A
     has to appear before B in the resulting module precedence list.
     If no precedence list can be constructed with these constraints,
     an error is signalled.

   For example, suppose you wrote a library in modules `mylib.base',
`mylib.util' and `mylib.system'.  You can bundle those modules into one
module by creating a module `mylib', as follows:

     (define-module mylib
       (extend mylib.system mylib.util mylib.base))

   The user of your module just says `(use mylib)' and all exported
symbols from three submodules become available.


File: gauche-refe.info,  Node: Module introspection,  Next: Predefined modules,  Prev: Module inheritance,  Up: Modules

4.11.6 Module introspection
---------------------------

This subsection lists procedures that operates on modules at run-time.
With these procedures you can introspect the modules, create new modules
procedurally, or check the existence of certain modules/libraries, for
example.  However, don't forget that modules are primarily compile-time
structures.  Tweaking modules at run-time is only for those who know
what they are doing.

 -- Builtin Class: <module>
     A module class.

 -- Function: module? obj
     Returns true if OBJ is a module.

 -- Function: find-module name
     Returns a module object whose name is a symbol NAME.  If the named
     module doesn't exist, `#f' is returned.

 -- Function: make-module name &keyword if-exists
     Creates and returns a module that has symbol NAME.  If the named
     module already exists, the behavior is specified by IF-EXISTS
     keyword argument.  If it is `:error' (default), an error is
     signalled.  If it is `#f', `#f' is returned.

     Note that creating modules on-the-fly isn't usually necessary for
     ordinal scripts, since to execute already written program requires
     modules to be specified by name, i.e. syntax `define-module',
     `import', `extend', `with-module' all takes module names, not
     modules.  It is because module are inherently compile-time
     structure.  However, there are some cases that dynamically created
     modules are useful, especially the program itself is dynamically
     created.  You can pass a module to `eval' to compile and evaluate
     such dynamically created programs in it (*Note Eval and repl::).

     You can also pass `#f' to NAME to create _anonymous_ module.
     Anonymous modules can't be looked up by `find-module', nor can be
     imported or inherited (since `import' and `extend' take module
     names, not modules).  It is useful when you want to have a
     temporary, segregated namespace dynamically--for example, you can
     create an anonymous module to evaluate code fragments sent from
     other program, and discards the module when the connection is
     terminated.  Anonymous modules are not registered in the system
     dictionary and are garbage collected when nobody keeps reference
     to it.

 -- Function: all-modules
     Returns a list of all named modules.  Anonymous modules are not
     included.

 -- Function: module-name module
 -- Function: module-imports module
 -- Function: module-exports module
 -- Function: module-table module
     Accessors of a module object.  Returns the name of the module (a
     symbol), list of imported modules, list of exported symbols, and a
     hash table that maps symbols to bindings, of the MODULE are
     returned, respectively.

     If the MODULE exports all symbols, `module-exports' returns `#t'.

     It is an error to pass a non-module object.

 -- Function: module-parents module
 -- Function: module-precedence-list module
     Returns the information of module inheritance.  `Module-parents'
     returns the modules MODULE directly inherits from.
     `Module-precedence-list' returns the module precedence list of
     MODULE (*Note Module inheritance::).

 -- Function: symbol-bound? symbol &optional module
     Returns true if SYMBOL's global binding is visible from MODULE.
     If MODULE is omitted, the current module is used.

 -- Function: module-name->path symbol
     Converts a module name SYMBOL to a fragment of pathname string.

 -- Function: path->module-name string
     Reverse function of `module-name->path'.

   If you want to find out specific libraries and/or modules are
installed in the system and available from the program, see *Note
Operations on libraries::.


File: gauche-refe.info,  Node: Predefined modules,  Prev: Module introspection,  Up: Modules

4.11.7 Predefined modules
-------------------------

Several modules are predefined in Gauche.

 -- Builtin Module: null
     This module corresponds to the null environment referred in R5RS.
     This module contains only syntactic bindings of R5RS syntax.

 -- Builtin Module: scheme
     This module contains all the binding of `null' module, and the
     binding of procedures defined in R5RS.

   Note that if you change the current module to `null' or `scheme' by
`select-module', there will be no way to switch back to other modules,
since module-related syntaxes and procedures are not visible from
`null' and `scheme' modules.

 -- Builtin Module: gauche
     This module contains all the bindings of `scheme' module, plus
     Gauche specific built-in procedures.

 -- Builtin Module: user
     This module is the default module the user code is compiled.  all
     the bindings of `gauche' module is imported.


File: gauche-refe.info,  Node: Macros,  Next: Core library,  Prev: Core syntax,  Up: Top

5 Macros
********

Gauche supports both R5RS hygienic macros and traditional macros.

   Macro of Lisp-family language is very different feature from ones of
other languages, such as C preprocessor macros.  It allows you to
extend the original language syntax.  You can use macros to change
Gauche syntax so that you can run a Scheme program written to other
Scheme implementations, and you can even design your own mini-language
to solve your problem easily.

* Menu:

* Hygienic Macros::
* Traditional Macros::
* Macro expansion::
* Macro utilities::


File: gauche-refe.info,  Node: Hygienic Macros,  Next: Traditional Macros,  Prev: Macros,  Up: Macros

5.1 Hygienic Macros
===================

R5RS hygienic macro is based on a special pattern language, and
guaranteed that no "variable capture" occurs.  "Variable catpture"
means that if you insert new variable bindings in the expanded form,
the new bindings shadows the bindings in the form passed to the macro.

 -- Special Form: define-syntax name transformer-spec
     [R5RS]

 -- Special Form: let-syntax ((name transformer-spec) ...) body
 -- Special Form: letrec-syntax ((name transformer-spec) ...) body
     [R5RS]

 -- Special Form: syntax-rules literals clause1 clause2 ...
     [R5RS]


File: gauche-refe.info,  Node: Traditional Macros,  Next: Macro expansion,  Prev: Hygienic Macros,  Up: Macros

5.2 Traditional Macros
======================

 -- Special Form: define-macro name procedure
 -- Special Form: define-macro (name formals) body ...
     Defines NAME to be a global macro whose transformer is PROCEDURE.
     The second form is a shorthand notation of the following form:
          (define-macro name (lambda formals body ...))

     When a form `(name ARG ...)' is seen by the compiler, it calls
     PROCEDURE with ARG ....  When PROCEDURE returns, the compiler
     inserts the returned form in place of the original form, and
     compile it again.


File: gauche-refe.info,  Node: Macro expansion,  Next: Macro utilities,  Prev: Traditional Macros,  Up: Macros

5.3 Macro expansion
===================

 -- Function: macroexpand form
 -- Function: macroexpand-1 form
     If FORM is a list and its first element is a variable globally
     bound to a macro, `macroexpand-1' invokes its macro transformer and
     returns the expanded form.  Otherwise, returns FORM as is.

     `macroexpand' repeats `macroexpand-1' until the FORM can't be
     expanded.

     These procedures can be used to expand globally defined macros.

 -- Special Form: %macroexpand form
 -- Special Form: %macroexpand-1 form


File: gauche-refe.info,  Node: Macro utilities,  Prev: Macro expansion,  Up: Macros

5.4 Macro utilities
===================

 -- Macro: syntax-error msg arg ...
 -- Macro: syntax-errorf fmt arg ...
     Signal an error.  They are same as `error' and `errorf' (*Note
     Signalling exceptions::), except that the error is signalled at
     macro-expansion time (i.e. compile time) rather than run time.

     They are useful to tell the user the wrong usage of macro in the
     comprehensive way, instead of the cryptic error from the macro
     expander.   Because of the purpose, ARG ... are first passed to
     `unwrap-syntax' described below, to strip off the internal
     syntactic binding informations.

          (define-syntax my-macro
            (syntax-rules ()
              ((_ a b)   (foo2 a b))
              ((_ a b c) (foo3 a b c))
              ((_ . ?)
               (syntax-error "malformed my-macro" (my-macro . ?)))))

          (my-macro 1 2 3 4)
            => error: "malformed my-macro: (mymacro 1 2 3 4)"


 -- Function: unwrap-syntax form
     Removes internal syntactic information from FORM.  In order to
     implement a hygienic macro, macro expander replaces symbols in the
     macro form for identifiers, which captures the syntactic
     environment where they are defined.  Although it is necessary
     information for the compiler, it is rather confusing for users if
     it appears in the messages.  This function replaces occurrences of
     identifiers in FORM to the original symbols.


File: gauche-refe.info,  Node: Core library,  Next: Object system,  Prev: Macros,  Up: Top

6 Core library
**************

* Menu:

* Equivalence::
* Numbers::
* Booleans::
* Pairs and Lists::
* Symbols::
* Keywords::
* Identifiers::
* Characters::
* Character set::
* Strings::
* Regular expression::
* Vectors::
* Hashtables::
* Weak pointers::
* Control features::
* Exceptions::
* Eval and repl::
* Input and output::
* Loading Programs::
* Comparison and sorting::
* System interface::
* Development helper API::


File: gauche-refe.info,  Node: Equivalence,  Next: Numbers,  Prev: Core library,  Up: Core library

6.1 Equivalence
===============

Scheme has three different general equivalence test predicates.  Other
than these, some types have their own comarison predicates.

 -- Function: eq? obj1 obj2
     [R5RS] This is the fastest and finest predicate.  Returns `#t' if
     OBJ1 and OBJ2 are allocated objects of the same types, and denote
     the same location.  Returns `#t' if both objects are `#f', `#t',
     or `()'.  You can think EQ? as a pointer comparison.  Note that
     the result is unspecified in Scheme standard when both objects are
     characters or numbers.

          (eq? #t #t)               => #t
          (eq? #t #f)               => #f
          (eq? 'a 'a)               => #t
          (eq? 'a 'b)               => #f
          (eq? (list 'a) (list 'a)) => #f
          (let ((x (list 'a)))
            (eq? x x))              => #t

 -- Function: eqv? obj1 obj2
     [R5RS] When OBJ1 and OBJ2 are both exact or both inexact numbers,
     EQV? returns `#t' iff `(= OBJ1 OBJ2)' is true.  When OBJ1 and OBJ2
     are both characters, EQV? returns `#t' iff `(char=? OBJ1 OBJ2)' is
     true.  Otherwise, `eqv?' is the same as `eq?' on Gauche.

          (eqv? #\a #\a)             => #t
          (eqv? #\a #\b)             => #f
          (eqv? 1.0 1.0)             => #t
          (eqv? 1 1)                 => #t
          (eqv? 1 1.0)               => #f
          (eqv? (list 'a) (list 'a)) => #f
          (let ((x (list 'a)))
            (eqv? x x))              => #t

 -- Function: equal? obj1 obj2
     [R5RS+] If OBJ1 and OBJ2 are both aggregate types, `equal?'
     compares its elements recursively.  Otherwise, `equal?' behaves
     the same as `eqv?'.

     If OBJ1 and OBJ2 are other than booleans, numbers, characters,
     pairs, strings and vectors, and the class of both objects are the
     same, `equal?' calls the generic function `object-equal?'.  By
     defining the method, users can extend the behavior of `equal?' for
     user-defined classes.

          (equal? (list 1 2) (list 1 2)) => #t
          (equal? "abc" "abc")           => #t
          (equal? 100 100)               => #t
          (equal? 100 100.0)             => #f


 -- Generic Function: object-equal? obj1 obj2
     This generic function is called when `equal?' is called on the
     objects it doesn't know about.  You can define this method on your
     class so that `equal?' can check equivalence.   This method is
     supposed to return `#t' if OBJ1 is equal to OBJ2, `#f' otherwise.
     If you want to check equivalence of elements recursively, do not
     call `object-equal?' directly; call `equal?' on each element.

          (define-class <foo> ()
            ((x :init-keyword :x)
             (y :init-keyword :y)))

          (define-method object-equal? ((a <foo>) (b <foo>))
            (and (equal? (slot-ref a 'x) (slot-ref b 'x))
                 (equal? (slot-ref a 'y) (slot-ref b 'y))))

          (equal? (make <foo> :x 1 :y (list 'a 'b))
                  (make <foo> :x 1 :y (list 'a 'b)))
            => #t

          (equal? (make <foo> :x 1 :y (make <foo> :x 3 :y 4))
                  (make <foo> :x 1 :y (make <foo> :x 3 :y 4)))
            => #t

   Sometimes you want to test if two aggregate structures are
topologically equal, i.e., if one has a shared substructure, the other
has a shared substructure in the same way.  `Equal?' can't handle it;
module `util.isomorph' provides a procedure `isomorphic?' which does
the job (*Note Determine isomorphism::).


File: gauche-refe.info,  Node: Numbers,  Next: Booleans,  Prev: Equivalence,  Up: Core library

6.2 Numbers
===========

Gauche supports the following types of numbers
multi-precision exact integer
     There's no limit of the size of number except the memory of the
     machine.

inexact floating-point real number
     Using `double'-type of underlying C compiler, usually IEEE 64-bit
     floating point number.

inexact floating-point complex number
     Real part and imaginary part are represented by inexact
     floating-point real numbers.

* Menu:

* Number classes::
* Numerical predicates::
* Numerical comparison::
* Arithmetics::
* Numerical conversions::
* Bitwise operations::


File: gauche-refe.info,  Node: Number classes,  Next: Numerical predicates,  Prev: Numbers,  Up: Numbers

6.2.1 Number classes
--------------------

 -- Builtin Class: <number>
 -- Builtin Class: <complex>
 -- Builtin Class: <real>
 -- Builtin Class: <integer>
     These classes consist a class hierarchy of number objects.
     `<complex>' inherits `<number>', `<real>' inherits `<complex>' and
     `<integer>' inherits `<real>'.

     Note that these classes does not exactly corresponds to the number
     hierarchy defined in R5RS.  Especially, only exact integers are
     the instances of the `<integer>' class.  That is,
          (integer? 1)        => #t
          (is-a? 1 <integer>) => #t
          (is-a? 1 <real>)    => #t

          (integer? 1.0)        => #t
          (is-a? 1.0 <integer>) => #f
          (is-a? 1.0 <real>)    => #t

          (class-of (expt 2 100)) => #<class <integer>>
          (class-of (sqrt -3)) => #<class <complex>>


File: gauche-refe.info,  Node: Numerical predicates,  Next: Numerical comparison,  Prev: Number classes,  Up: Numbers

6.2.2 Numerical predicates
--------------------------

 -- Function: number? obj
 -- Function: complex? obj
 -- Function: real? obj
 -- Function: rational? obj
 -- Function: integer? obj
     [R5RS] Returns `#t' if OBJ is a number, a complex number, a real
     number, a rational number or an integer, respectively.   In
     Gauche, a set of numbers is the same as a set of complex numbers,
     and a set of rational numbers is the same as a set of real numbers
     (since we have only limited-precision floating numbers).

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

 -- Function: exact? obj
 -- Function: inexact? obj
     [R5RS] Returns `#t' if OBJ is an exact number and an inexact
     number, respectively.

          (exact? 1)       => #t
          (exact? 1.0)     => #f
          (inexact? 1)     => #f
          (inexact? 1.0)   => #t

          (exact? (modulo 5 3)) => #t
          (inexact? (modulo 5 3.0)) => #f

 -- Function: zero? z
     [R5RS] Returns `#t' if a number Z equals to zero.

          (zero? 1)        => #f
          (zero? 0)        => #t
          (zero? 0.0)      => #t
          (zero? 0.0+0.0i) => #t

 -- Function: positive? x
 -- Function: negative? x
     [R5RS] Returns `#t' if a real number X is positive and negative,
     respectively.  It is an error to pass a non-real number.

 -- Function: odd? n
 -- Function: even? n
     [R5RS] Returns `#t' if an integer N is odd and even, respectively.
     It is an error to pass a non-integral number.

          (odd? 3)     => #t
          (even? 3)    => #f
          (odd? 3.0)   => #t

 -- Function: fixnum? n
 -- Function: bignum? n
     Returns `#t' iff N is an exact integer whose internal
     representation is FIXNUM and BIGNUM, respectively.  Portable
     Scheme programs don't need to care about the internal
     representation of integer.   These are for certain low-level
     routines that does particular optimization.


File: gauche-refe.info,  Node: Numerical comparison,  Next: Arithmetics,  Prev: Numerical predicates,  Up: Numbers

6.2.3 Numerical comparison
--------------------------

 -- Function: `=' z1 z2 z3 ...
     [R5RS] If all the numbers Z are equal, returns `#t'.

          (= 2 2)          => #t
          (= 2 3)          => #f
          (= 2 2.0)        => #t
          (= 2 2.0 2.0+0i) => #t

 -- Function: `<' x1 x2 x3 ...
 -- Function: `<=' x1 x2 x3 ...
 -- Function: `>' x1 x2 x3 ...
 -- Function: `>=' x1 x2 x3 ...
     [R5RS] Returns `#t' If all the real numbers X are monotonically
     increasing, monotonically nondecreasing, monotonically decreasing,
     or monotonically nonincreasing, respectively.

 -- Function: max x1 x2 ...
 -- Function: min x1 x2 ...
     [R5RS] Returns a maximum or minimum number in the given real
     numbers, respectively.

 -- Function: min&max x1 x2 ...
     Returns a maximum and minimum number in the given real numbers.


File: gauche-refe.info,  Node: Arithmetics,  Next: Numerical conversions,  Prev: Numerical comparison,  Up: Numbers

6.2.4 Arithmetics
-----------------

 -- Function: `+' z ...
 -- Function: `*' z ...
     [R5RS] Returns the sum or the product of given numbers,
     respectively.  If no argument is given, `(+)' yields 0 and `(*)'
     yields 1.

 -- Function: `-' z1 z2 ...
 -- Function: `/' z1 z2 ...
     [R5RS] If only one number Z1 is given, returns its negation and
     reciprocal, respectively.

     If more than one number are given, returns:
          Z1 - Z2 - Z3 ...
          Z1 / Z2 / Z3 ...
     respectively.

          (- 3)       => -3
          (- -3.0)    => 3.0
          (- 5+2i)    => -5.0-2.0i
          (/ 3)       => 0.333333333333333
          (/ 5+2i)    => 0.172413793103448-0.0689655172413793i

          (- 5 2 1)     => 2
          (- 5 2.0 1)   => 2.0
          (- 5+3i -i)   => 5.0+2.0i
          (/ 6+2i 2)    => 3.0+1.0i

 -- Function: abs z
     [R5RS+] For real number Z, returns an absolute value of it.  For
     complex number Z, returns the magnitude of the number.  The
     complex part is Gauche extension.
          (abs -1)   => 1
          (abs -1.0) => 1.0
          (abs 1+i)  => 1.4142135623731

 -- Function: quotient n1 n2
 -- Function: remainder n1 n2
 -- Function: modulo n1 n2
     [R5RS] Returns the quotient, remainder and modulo of dividing an
     integer N1 by an integer N2.   The result is an exact number only
     if both N1 and N2 are exact numbers.

     Remainder and modulo differ when either one of the arguments is
     negative.  Remainder R and quotient Q have the following
     relationship.
            N1 = Q * N2 + R
     where `abs(Q) = floor(abs(N1)/abs(N2))'.  Consequently, R's sign
     is always the same as N1's.

     On the other hand, modulo works as expected for positive N2,
     regardless of the sign of N1 (e.g. `(modulo -1 N2) == N2 - 1').
     If N2 is negative, it is mapped to the positive case by the
     following relationship.
            modulo(N1, N2) = -modulo(-N1, -N2)
     Consequently, MODULO's sign is always the same as N2's.
          (remainder 10 3)    => 1
          (modulo 10 3)       => 1

          (remainder -10 3)   => -1
          (modulo -10 3)      => 2

          (remainder 10 -3)   => 1
          (modulo 10 -3)      => -2

          (remainder -10 -3)  => -1
          (modulo -10 -3)     => -1

 -- Function: quotient&remainder n1 n2
     Calculates the quotient and the remainder of dividing integer N1
     by integer N2 simultaneously, and returns them as two values.

 -- Function: gcd n ...
 -- Function: lcm n ...
     [R5RS] Returns the greatest common divisor or the least common
     multiplier of the given integers, respectively

 -- Function: numerator q
 -- Function: denominator q
     [R5RS] Returns the numerator and denominator of a rational number
     Q.  Since Gauche doesn't support full rational numbers, they
     actually work only on integers; that is, given integer Q,
     `numerator' always returns Q and `denominator' always return 1.

 -- Function: floor x
 -- Function: ceiling x
 -- Function: truncate x
 -- Function: round x
     [R5RS] The argument X must be a real number.  `Floor' and
     `ceiling' return a maximum integer that isn't greater than X and a
     minimum integer that isn't less than X, respectively.  TRUNCATE
     returns an integer that truncates X towards zero.  ROUND returns
     an integer that is closest to X.  If fractional part of X is
     exactly 0.5, ROUND returns the closest even integer.

 -- Function: clamp x &optional min max
     Returns
           MIN if X `<' MIN
           X   if MIN `<=' X `<=' MAX
           MAX if MAX `<' X
     If MIN or MAX is omitted or `#f', it is regarded as -INFINITY or
     +INFINITY, respectively.  Returns an exact integer only if all the
     given numbers are exact integers.
          (clamp 3.1 0.0 1.0) => 1.0
          (clamp 0.5 0.0 1.0) => 0.5
          (clamp -0.3 0.0 1.0) => 0.0
          (clamp -5 0)        => 0
          (clamp 3724 #f 256) => 256

 -- Function: exp z
 -- Function: log z
 -- Function: sin z
 -- Function: cos z
 -- Function: tan z
 -- Function: asin z
 -- Function: acos z
 -- Function: atan z
     [R5RS] Transcedental functions.  Work for complex numbers as well.

 -- Function: atan x y
     [R5RS] For real numbers X and Y, returns `atan(Y/X)'.

 -- Function: sinh z
 -- Function: cosh z
 -- Function: tanh z
 -- Function: asinh z
 -- Function: acosh z
 -- Function: atanh z
     Hyperbolic trigonometric functions.  Work for complex numbers as
     well.

 -- Function: sqrt z
     [R5RS] Returns a square root of a complex number Z.  The branch
     cut scheme is the same as Common Lisp.  For real numbers, it
     returns a positive root.

 -- Function: expt z1 z2
     [R5RS] Returns Z1^Z2 (Z1 powered by Z2), where Z1 and Z2 are
     complex numbers.


File: gauche-refe.info,  Node: Numerical conversions,  Next: Bitwise operations,  Prev: Arithmetics,  Up: Numbers

6.2.5 Numerical conversions
---------------------------

 -- Function: make-rectangular x1 x2
 -- Function: make-polar x1 x2
     [R5RS] Creates a complex number from two real numbers, X1 and X2.
     `make-rectangular' returns X1 + iX2.  `make-polar' returns
     X1e^(iX2).

 -- Function: real-part z
 -- Function: imag-part z
 -- Function: magnitude z
 -- Function: angle z
     [R5RS] Decompose a complex number Z and returns a real number.
     `real-part' and `imag-part' return Z's real and imaginary part,
     respectively.  `magnitude' and `angle' return Z's magnitude and
     angle, respectively.

 -- Function: decode-float x
     Given floating-point number (inexact real number), returns a
     vector of three exact integers, `#(M, E, SIGN)', where
            X = (* SIGN M (expt 2.0 E))
            SIGN is either 1, 0 or -1.
     The API is taken from ChezScheme.
          (decode-float 3.1415926)
           => #(7074237631354954 -51 1)
          (* 7074237631354954 (expt 2.0 -51))
           => 3.1415926

 -- Function: fmod x y
 -- Function: modf x
 -- Function: frexp x
 -- Function: ldexp x n
     [POSIX] These procedures can be used to compose and decompose
     floating point numbers.  `Fmod' computes the remainder of dividing
     X by Y, that is, it returns X-N*Y where N is the quotient of X/Y
     rounded towards zero to an integer.   `Modf' returns two values; a
     fractional part of X and an integral part of X.   `Frexp' returns
     two values, FRACTION and EXPONENT of X, where X = FRACTION *
     2^EXPONENT, and 0 <= FRACTION <= 0.5.  LDEXP is a reverse
     operation of `frexp'; it returns a real number X * 2^N.
          (fmod 32.1 10.0)  => 2.1
          (fmod 1.5 1.4)    => 0.1
          (modf 12.5)       => 0.5 and 12.0
          (frexp 3.14)      => 0.785 and 2
          (ldexp 0.785 2)   => 3.14

 -- Function: exact->inexact z
 -- Function: inexact->exact z
     [R5RS] Converts an exact number to an inexact number, or vice
     versa.

     Since Gauche doesn't support general rational numbers, the result
     of `inexact->exact' is always a whole number.  If the passed
     number is not an integer, the fraction part is rounded.  Note that
     it is an implementation dependent behavior.  If you want to get a
     closest exact integer of the given inexact real number, it's
     better to use `round' explicitly before `inexact->exact'.

     If you pass an inexact number to `exact->inexact' or an exact
     number to `inexact->exact', Gauche returns the argument as is,
     instead of reporting an error.  This is also an implementation
     dependent behavior and you shouldn't count on that.

 -- Function: number->string z &optional radix use-upper?
 -- Function: string->number string &optional radix
     [R5RS+] These procedurs convert a number and its string
     representation in radix RADIX system.  RADIX must be between 2 and
     36 inclusive.  If RADIX is omitted, 10 is assumed.

     `Number->string' takes a number Z and returns a string.  If Z is
     not an exact integer, RADIX must be 10.  For the numbers with
     radix more than 10, lower case alphabet character is used for
     digits, unless the optional argument USE-UPPER? is true, in that
     case upper case characters are used.  The argument USE-UPPER? is
     Gauche's extension.

     `String->number' takes a string STRING and parses it as a number
     in radix RADIX system.  If the number looks like non-exact number,
     only radix 10 is allowed.  If the given string can't be a number,
     `#f' is returned.

 -- Generic Function: x->number obj
 -- Generic Function: x->integer obj
     Generic coercion functions.  Returns `natural' interpretation of
     OBJ as a number or an exact integer, respectively.  The default
     methods are defined for numbers and strings; a string is
     interpreted by STRING->NUMBER, and if the string can't be
     interpreted as a number, 0 is returned.  Other OBJ is simply
     converted to 0.  If OBJ is naturally interpreted as a number that
     is not an exact integer, `x->integer' uses `round' and
     `inexact->exact' to obtain an integer.

     Other class may provide a method to customize the behavior.


File: gauche-refe.info,  Node: Bitwise operations,  Prev: Numerical conversions,  Up: Numbers

6.2.6 Bitwise operations
------------------------

These procedures treat integers as half-open bit vectors.  If an
integer is positive, it is regarded as if infinite number of zeros are
padded to the left.  If an integer is negative, it is regarded in 2's
complement form, and infinite number of 1's are padded to the left.

   The API is consisntent to SLIB's "logical" module.

 -- Function: ash n count
     Shifts integer N left with COUNT bits.  If COUNT is negative,
     `ash' shifts N right with -COUNT bits.

          ; Note: 6  == [...00110], and
          ;       -6 == [...11010]
          (ash 6 2)   => 24  ;[...0011000]
          (ash 6 -2)  => 1   ;[...0000001]
          (ash -6 2)  => -24 ;[...1101000]
          (ash -6 -2) => -2  ;[...1111110]

 -- Function: logand n1 n2 ...
 -- Function: logior n1 n2 ...
 -- Function: logxor n1 n2 ...
     Returns bitwise and, bitwise inclusive or and bitwise exclusive or
     of two or more integers N1, N2 ....

 -- Function: lognot n
     Returns bitwise not of an integer N.

 -- Function: logtest n1 n2 ...
     == `(not (zero? (logand N1 N2 ...)))'

 -- Function: logbit? index n
     Returns `#t' if INDEX-th bit of integer N is 1, #F otherwise.

 -- Function: bit-field n start end
     Extracts START-th bit (inclusive) to END-th bit (exclusive) from
     an exact integer N, where START < END.

 -- Function: copy-bit index n bit
     If BIT is true, sets INDEX-th bit of an exact integer N.  If BIT
     is false, resets INDEX-th bit of an exact integer N.

 -- Function: copy-bit-field n start end from

 -- Function: logcount n

 -- Function: integer-length n


File: gauche-refe.info,  Node: Booleans,  Next: Pairs and Lists,  Prev: Numbers,  Up: Core library

6.3 Booleans
============

 -- Builtin Class: <boolean>
     A boolean class.  Only `#t' and `#f' belong to this class.

 -- Function: not obj
     [R5RS] Returns `#t' if and only if OBJ is `#f', and returns `#f'
     otherwise.

 -- Function: boolean? obj
     [R5RS] Returns `#t' if OBJ is a boolean value.


File: gauche-refe.info,  Node: Pairs and Lists,  Next: Symbols,  Prev: Booleans,  Up: Core library

6.4 Pairs and Lists
===================

Pairs and lists are one of the most fundamental data structure in
Scheme.  Gauche core provides all standard list procedures, plus some
useful procedures that are commonly supported in lots of
implementations.  If they are not enough, you can find more procedures
in the modules described in *Note List library::, *Note Additional list
library::, and *Note Combination library::.  See also *Note Collection
framework:: and *Note Sequence framework:: for generic
collection/sequence operations.

* Menu:

* Pair and null class::
* List predicates::
* List constructors::
* List accessors and modifiers::
* Other list procedures::


File: gauche-refe.info,  Node: Pair and null class,  Next: List predicates,  Prev: Pairs and Lists,  Up: Pairs and Lists

6.4.1 Pair and null class
-------------------------

 -- Builtin Class: <list>
     An abstract class respresents lists.   A parent class of `<null>'
     and `<pair>'.   Inherits `<sequence>'.

     Note that a cirular list is also an instance of the `<list>' class,
     while R5RS procedure `list?' returns false on the circular lists
     and dotted lists.
          (use srfi-1)
          (list? (circular-list 1 2)) => #f
          (is-a? (circular-list 1 2) <list>) => #t

 -- Builtin Class: <null>
     A class of empty list.  `()' is the only instance.

 -- Builtin Class: <pair>
     A class of pairs.


File: gauche-refe.info,  Node: List predicates,  Next: List constructors,  Prev: Pair and null class,  Up: Pairs and Lists

6.4.2 List predicates
---------------------

 -- Function: pair? obj
     [R5RS] Returns `#t' if OBJ is a pair, `#f' otherwise.

 -- Function: null? obj
     [R5RS] Returns `#t' if OBJ is an empty list, `#f' otherwise.

 -- Function: list? obj
     [R5RS] Returns `#t' if OBJ is a proper list, `#f' otherwise.  This
     function returns `#f' if OBJ is a dotted or circular list.

     See also `proper-list?', `circular-list?' and `dotted-list?' in
     *Note SRFI-1 List predicates::.


File: gauche-refe.info,  Node: List constructors,  Next: List accessors and modifiers,  Prev: List predicates,  Up: Pairs and Lists

6.4.3 List constructors
-----------------------

 -- Function: cons obj1 obj2
     [R5RS] Constructs a pair of OBJ1 and OBJ2 and returns it.
          (cons 'a 'b) => (a . b)

 -- Function: acons obj1 obj2 obj3
     Returns `(cons (cons OBJ1 OBJ2) OBJ3)'.  Useful to put an entry at
     the head of an associative list.
          (acons 'a 'b '((c . d))) => ((a . b) (c . d))

 -- Function: make-list len &optional fill
     [SRFI-1] Makes a proper list of length LEN.  If optional argument
     FILL is provided, each element is initialized by it.  Otherwise
     each element is undefined.
          (make-list 5 #t) => (#t #t #t #t #t)

 -- Function: list obj ...
     [R5RS] Makes a list, whose elements are OBJ ....
          (list 1 2 3) => (1 2 3)
          (list) => ()

 -- Function: list* obj1 obj2 ...
     Like `list', but the last argument becomes cdr of the last pair.
     SRFI-1 defines the same function with the name `cons*'.
          (list* 1 2 3) => (1 2 . 3)
          (list* 1) => 1

 -- Function: list-copy list
     [SRFI-1] Shallow copies LIST.  If LIST is circular, this function
     diverges.


File: gauche-refe.info,  Node: List accessors and modifiers,  Next: Other list procedures,  Prev: List constructors,  Up: Pairs and Lists

6.4.4 List accessors and modifiers
----------------------------------

 -- Function: car pair
 -- Function: cdr pair
     [R5RS] Returns car and cdr of PAIR, respectively.

 -- Function: set-car! pair obj
 -- Function: set-cdr! pair obj
     [R5RS] Modifies car and cdr of PAIR, by OBJ, respectively.

     Note: `(setter car)' == `set-car!', and `(setter cdr)' ==
     `set-cdr!'.

 -- Function: caar pair
 -- Function: cadr pair
     ...

 -- Function: cdddar pair
 -- Function: cddddr pair
     [R5RS] `caar' == `(car (car x))', `cadr' == `(car (cdr x))', and
     so on.

     The corresponding setters are also defined.
          (let ((x (list 1 2 3 4 5)))
            (set! (caddr x) -1)
            x)
            => (1 2 -1 4 5)

 -- Function: length list
     [R5RS] Returns the length of a proper list LIST.  If LIST is a
     dotted list, an error is signalled.  If LIST is a circular list,
     this function diverges.

     If you want to handle circular lists as well, See `length+' in
     *Note SRFI-1 List miscellaneous routines::.

 -- Function: list-tail list k
     [R5RS] Returns K-th cdr of LIST.  LIST can be a proper, dotted or
     circular list.

 -- Function: list-ref list k &optional fallback
     [R5RS+] Returns K-th element of LIST.  LIST can be a proper,
     dotted or circular list.

     By default, `list-ref' signals an error if K is negative, or
     greater than or equal to the length of LIST.  However, if an
     optional argument FALLBACK is given, it is returned for such case.
     This is an extension of Gauche.

 -- Function: last-pair list
     [SRFI-1] Returns the last pair of LIST.  LIST can be a proper or
     dotted list.


File: gauche-refe.info,  Node: Other list procedures,  Prev: List accessors and modifiers,  Up: Pairs and Lists

6.4.5 Other list procedures
---------------------------

 -- Function: append list ...
     [R5RS] Returns a list consisting of the elements of the first LIST
     followed by the elements of the other lists.  The resulting list
     is always newly allocated, except that it shares structure with
     the last list argument.  The last argument may actually be any
     object; an improper list results if the last argument is not a
     proper list.

 -- Function: append! list ...
     [SRFI-1] Returns a list consisting of the elements of the first
     LIST followed by the elements of the other lists.  The cells in
     the lists except the last one may be reused to construct the
     result.   The last argument may be any object.

 -- Function: reverse list
     [R5RS] Returns a newly allocated list consisting of the elements
     of LIST in reverse order.

 -- Function: reverse! list
     [SRFI-1] Returns a list consisting of the elements of LIST in
     reverse order.  The cells of LIST may be reused to construct the
     returned list.

 -- Function: memq obj list
 -- Function: memv obj list
 -- Function: member obj list
     [R5RS] Searches OBJ in the LIST.  If `n'-th element of LIST equals
     to OBJ (in the sense of `eq?' for `memq', `eqv?' for `memv', and
     `equal?' for `member'), `(list-tail LIST N)' is returned.
     Otherwise, `#f' is returned.

     If you use SRFI-1 (*Note List library::), `member' is extended to
     take optional argument for a equality procedure.
          (memq 'a '(a b c))          => (a b c)
          (memq 'b '(a b c))          =>  (b c)
          (memq 'a '(b c d))          => #f
          (memq (list 'a) '(b (a) c)) => #f
          (memv 101 '(100 101 102))   => (101 102)

 -- Function: assq obj list
 -- Function: assv obj list
 -- Function: assoc obj list
     [R5RS] Each element in LIST must be a pair.  These procedures
     search a pair whose car matches OBJ (in the sense of `eq?' for
     `assq', `eqv?' for `assv', and `equal?' for `assoc') from left to
     right, and return the leftmost matched pair if any.  If no pair
     matches, these return `#f'.

     If you use SRFI-1 (*Note List library::), `assoc' is extended to
     take optional argument for a equality procedure.


File: gauche-refe.info,  Node: Symbols,  Next: Keywords,  Prev: Pairs and Lists,  Up: Core library

6.5 Symbols
===========

 -- Builtin Class: <symbol>
     A class for symbols.

     In Gauche, all symbols are _interned_, i.e. two symbols with the
     same print name are always `eq?'.

 -- Reader Syntax: `|name|'
     Denotes a symbol that has weird name, i.e. the name including the
     characters which is not allowed in the R5RS symbol syntax.  If the
     interpreter is running in case-insensitive mode, this syntax can
     be used to include uppercase characters in a symbol (*Note
     Case-sensitivity::).

     The syntax is taken from CommonLisp.  Some other Scheme
     implementation use it as well.

 -- Function: symbol? obj
     [R5RS] Returns true if and only if OBJ is a symbol.
          (symbol? 'abc)     => #t
          (symbol? 0)        => #f
          (symbol? 'i)       => #t
          (symbol? '-i)      => #f
          (symbol? '|-i|)    => #t

 -- Function: symbol->string symbol
     [R5RS] Returns the name of SYMBOL in a string.  Returned string is
     immutable.

          (symbol->string 'foo) => foo

 -- Function: string->symbol string
     [R5RS] Returns a symbol whose name is a string STRING.  STRING may
     contain weird characters.

          (string->symbol "a") => a
          (string->symbol "A") => A
          (string->symbol "weird symbol name") => |weird symbol name|

 -- Function: gensym &optional prefix


File: gauche-refe.info,  Node: Keywords,  Next: Identifiers,  Prev: Symbols,  Up: Core library

6.6 Keywords
============

 -- Builtin Class: <keyword>
     A keyword is a sort of a special symbol that is automatically
     quoted.  It is extensively used in pass-by-name arguments (keyword
     arguments), and keyword-value list.  Unlike CommonLisp, keywords
     and symbols are distinct types.

     See also `let-keywords*' macro (*Note Optional argument parsing::)
     for keyword argument processing.

 -- Reader syntax: `:NAME'
     Read to a keyword whose name is NAME.  (Note that the preceding
     ':' is not a part of the keyword's name.)

 -- Function: keyword? obj
     Returns `#t' if OBJ is a keyword.

 -- Function: make-keyword name
     Returns a keyword whose name is NAME.

 -- Function: keyword->string keyword
     Returns the name of the keyword KEYWORD.

 -- Function: get-keyword key kv-list &optional fallback
     A useful procedure to extract a value from key-value list.  A
     key-value list KV-LIST must contains even number of elements; the
     first, third, fifth ... elements are regarded as keys, and the
     second, fourth, sixth ... elements are the values of the preceding
     keys.

     This procedure looks for KEY from the keys, and if it finds one,
     it returns the corresponding value.  If there are more than one
     matching keys, the leftmost one is taken.  If there is no matching
     key, it returns FALLBACK if provided, or signals an error
     otherwise.

     It is an error if KV-LIST is not a proper, even-number element
     list.

     Actually, `keywords' in the keyword-value list and the KEY argument
     need not be a keyword--it can be any Scheme object.  Key comparison
     is done by `eq?'.

     This procedure is taken from STk.

          (get-keyword :y '(:x 1 :y 2 :z 3))
            => 2
          (get-keyword 'z '(x 1 y 2 z 3))
            => 3

          (get-keyword :t '(:x 1 :y 2 :z 3))
            => #<error>
          (get-keyword :t '(:x 1 :y 2 :z 3) #f)
            => #f

 -- Macro: get-keyword* key kv-list &optional fallback
     Like `get-keyword', but FALLBACK is evaluated only if KV-LIST does
     not have KEY.

 -- Function: delete-keyword key kv-list
 -- Function: delete-keyword! key kv-list
     Removes all the keys and values from KV-LIST for keys that are
     `eq?' to KEY.

     `delete-keyword' doesn't change KV-LIST, but the returned list may
     share the common tail of it.

     `delete-keyword!' doesn't allocate, and _may_ destructively
     changes KV-LIST.  You still have to use the returned value, for
     the original list may not be changed if its first key matches KEY.

     If there's no key that matches KEY, KV-LIST is returned.

          (delete-keyword :y '(:x 1 :y 2 :z 3 :y 4))
           => (:x 1 :z 3)



File: gauche-refe.info,  Node: Identifiers,  Next: Characters,  Prev: Keywords,  Up: Core library

6.7 Identifiers
===============

 -- Builtin Class: <identifier>

 -- Function: identifier? obj

 -- Function: identifier->symbol identiifer


File: gauche-refe.info,  Node: Characters,  Next: Character set,  Prev: Identifiers,  Up: Core library

6.8 Characters
==============

 -- Builtin Class: <char>

 -- Reader Syntax: `#\charname'
     [R5RS] Denotes a literal character.

     When the reader reads `#\', it fetches a sbusequent character.  If
     it is one of `()[]{}" \|;#', this is a character literal of itself.
     Otherwise, the reader reads subsequent characters until it sees a
     non word-constituent character.  If only one character is read, it
     is the character.  Otherwise, the reader matches the read
     characters with predefined character names.  If it doesn't match
     any, an error is signalled.

     The following character names are recognized.  These haracter
     names are case insensitive.
    `space'
          Whitespace (ASCII #x20)

    `newline, nl, lf'
          Newline (ASCII #x0a)

    `return, cr'
          Carriage return (ASCII #x0d)

    `tab, ht'
          Horizontal tab (ASCII #x09)

    `page'
          Form feed (ASCII #x0c)

    `escape, esc'
          Escape (ASCII #x1b)

    `delete, del'
          Delete (ASCII #x7f)

    `null'
          NUL character (ASCII #x00)

    `xN'
          A character whose internal encoding is the integer N, when N
          is a hexadecimal integer.  Note that this notation is not
          portable among different internal encoding schemes except
          ASCII character range.

    `uN'
          A character whose UCS character code is the integer N, where
          N is 4-digit or 8-digit hexadecimal number.  If Gauche is
          compiled with the internal encoding other than UTF-8, the
          reader uses `gauche.charconv' module to convert Unicode to
          the internal character code.  Note that the specified
          character may not be defined in the internal encoding; in
          which case, either a substitution character is used, or an
          error is signalled.

          #\newline => #\newline ; newline character
          #\x0a     => #\newline ; ditto
          #\x41     => #\A       ; ASCII letter 'A'
          #\u0041   => #\A       ; ASCII letter 'A', specified by UCS
          #\u3042   => ; Hiragana letter A, specified by UCS
          #\u0002a6b2 => ; JISX0213 Kanji 2-94-86, specified by UCS4

     You can denote multibyte characters with this syntax if the
     program text is written in the same encoding as the internal
     character encoding.

 -- Function: char? obj
     [R5RS] Returns `#t' if OBJ is a character, `#f' otherwise.

 -- Function: char`='? char1 char2
 -- Function: char`<'? char1 char2
 -- Function: char`<='? char1 char2
 -- Function: char`>'? char1 char2
 -- Function: char`>='? char1 char2
     [R5RS] Compares characters.  Character comparison is done in
     internal character encoding.

 -- Function: char-ci`='? char1 char2
 -- Function: char-ci`<'? char1 char2
 -- Function: char-ci`<='? char1 char2
 -- Function: char-ci`>'? char1 char2
 -- Function: char-ci`>='? char1 char2
     [R5RS] Compares characters in case-insensitive way.  In the
     current version, character cases are not well defined outside the
     ASCII character range.

 -- Function: char-alphabetic? char
 -- Function: char-numeric? char
 -- Function: char-whitespace? char
 -- Function: char-upper-case? char
 -- Function: char-lower-case? char
     [R5RS] Returns true if a character CHAR is an alphabetic character
     (`[A-Za-z]'), a numeric character (`[0-9]'), a whitespace
     character, an upper case character or a lower case character,
     respectively.  Currently, these procedures works only for ASCII
     characters.  They return `#f' for all other characters.

 -- Function: char->integer char
 -- Function: integer->char n
     [R5RS] `char->integer' returns an exact integer that represents
     internal encoding of the character CHAR.  `integer->char' returns
     a character whose internal encoding is an exact integer N.  The
     following expression is always true for valid charcter CHAR:
          (eq? char (integer->char (char->integer char)))

     The result is undefined if you pass N to `integer->char' that
     doesn't have a corresponding character.

 -- Function: char->ucs char
 -- Function: ucs->char n
     Converts a character CHAR to integer UCS codepoint, and integer
     UCS codepoint N to a character, respectively.

     If Gauche is compiled with UTF-8 encoding, these procedures are the
     same as `char->integer' and `integer->char'.

     When Gauche's internal encoding differs from UTF-8, these
     procedures implicitly loads `gauche.charconv' module to convert
     internal character code to UCS or vice versa (*Note Character code
     conversion::).  If CHAR doesn't have corresponding UCS codepoint,
     `char->ucs' returns `#f'.  If UCS codepoint N can't be represented
     in the internal character encoding, `ucs->char' returns `#f',
     unless the conversion routine provides a substitution character.

 -- Function: char-upcase char
 -- Function: char-downcase char
     [R5RS] Returns the upper case and lower case of CHAR, respectively.
     If CHAR doesn't have such distinction of upper or lower case,
     `char' itself is returned.

     In the current version, character cases are not well defined
     outside the ASCII character range.

 -- Function: digit->integer char &optional (radix 10)
     If given character CHAR is a valid digit character in radix RADIX
     number, the corresponding integer is returned.  Otherwise `#f' is
     returned.
          (digit->integer #\4) => 4
          (digit->integer #\e 16) => 14
          (digit->integer #\9 8) => #f
     Note: CommonLisp has a similar function in rather confusing name,
     `digit-char-p'.

 -- Function: integer->digit integer &optional (radix 10)
     Reverse operation of `digit->integer'.  Returns a character that
     represents the number INTEGER in the radix RADIX system.  If
     INTEGER is out of the valid range, `#f' is returned.
          (integer->digit 13 16) => #\d
          (integer->digit 10) => #f
     Note: CommonLisp's `digit-char'.

 -- Function: gauche-character-encoding
     Returns a symbol designates the native character encoding, selected
     at the compile time.  The possible return values are those:
    `euc-jp'
          EUC-JP

    `utf-8'
          UTF-8

    `sjis'
          Shift JIS

    `none'
          No multibyte character support (8-bit fixed-length character).

 -- Function: supported-character-encodings
     Returns a list of string names of character encoding schemes that
     are supported in the native multibyte encoding scheme.


File: gauche-refe.info,  Node: Character set,  Next: Strings,  Prev: Characters,  Up: Core library

6.9 Character Set
=================

 -- Builtin Class: <char-set>
     Character set class.  Character set object represents a set of
     characters.  Gauche provides built-in support of character set
     creation and a predicate that tests whether a character is in the
     set or not.

     Further operations, such as set algebra, is defined in SRFI-14
     module (*Note Character-set library::).

 -- Reader Syntax: `#[char-set-spec]'
     You can write a literal character set in this syntax.
     char-set-spec is a sequence of characters to be included in the
     set.  You can include the following special sequences:
    `X-Y'
          Characters between X and Y, inclusive.  X must be smaller
          than Y in the internal encoding.

    `^'
          If char-set-spec begins with caret, the actual character set
          is a complement of what the rest of char-set-spec indicates.

    `\xNN'
          A character whose internal code is a hexadecimal number NN.

    `\uNNNN'
          A character whose UCS-2 code is a 4-digit hexadecimal number
          NNNN.

    `\UNNNNNNNN'
          A character whose UCS-4 code is a 8-digit hexadecimal number
          NNNNNNNN.

    `\s'
          Whitespace characters.

    `\S'
          Complement of whitespace characters.

    `\d'
          Decimal digit characters.

    `\D'
          Complement of decimal digit characters.

    `\w'
          Word constituent characters.  Currently, it is alphanumeric
          characters and underscore.

    `\W'
          Complement of word constituent characters.

    `\\'
          A backslash character.

    `\-'
          A minus character.

    `\^'
          A caret character.

    `[:alnum:] ...'
          Character set a la POSIX.  The following character set name is
          recognized: `alnum', `alpha', `blank', `cntrl', `digit',
          `graph', `lower', `print', `punct', `space', `upper' and
          `xdigit'.

          #[aeiou]     ; a character set consists of vowels
          #[a-zA-Z]    ; alphabet
          #[[:alpha:]] ; alphabet (using POSIX notation)
          #[\x0d\x0a]  ; newline and carriage return
          #[\\\-]      ; backslash and minus
          #[]          ; empty charset

 -- Function: char-set? obj
     [SRFI-14] Returns true if and only if OBJ is a character set
     object.

 -- Function: char-set-contains? char-set char
     [SRFI-14] Returns true if and only if a character set object
     CHAR-SET contains a character CHAR.
          (char-set-contains? #[a-z] #\y) => #t
          (char-set-contains? #[a-z] #\3) => #f

          (char-set-contains? #[^ABC] #\A) => #f
          (char-set-contains? #[^ABC] #\D) => #t

 -- Function: char-set char ...
     [SRFI-14] Creates a character set that contains CHAR ....
          (char-set #\a #\b #\c)   => #[a-c]

 -- Function: char-set-copy char-set
     [SRFI-14] Copies a character set CHAR-SET.


File: gauche-refe.info,  Node: Strings,  Next: Regular expression,  Prev: Character set,  Up: Core library

6.10 Strings
============

 -- Builtin Class: <string>
     A string class.   In Gauche, a string can be viewed in two ways: a
     sequence of characters, or a sequence of bytes.

   R5RS string operations are very minimal.  Gauche supports some extra
built-in operations, and also a rich string library defined in SRFI-13.
 *Note String library::, for details about SRFI-13.

* Menu:

* String syntax::
* String Predicates::
* String Constructors::
* String interpolation::
* String Accessors & Modifiers::
* String Comparison::
* String utilities::
* String Pointers::
* Incomplete strings::


File: gauche-refe.info,  Node: String syntax,  Next: String Predicates,  Prev: Strings,  Up: Strings

6.10.1 String syntax
--------------------

 -- Reader syntax: `"'...`"'
     [R5RS+] Denotes a literal string.  Inside the double quotes, the
     following backslash escape sequences are recognized.

    `\"'
          [R5RS] Double-quote character

    `\\'
          [R5RS] Backslash character

    `\n'
          Newline character (ASCII 0x0a).

    `\r'
          Return character (ASCII 0x0d).

    `\f'
          Form-feed character (ASCII 0x0c).

    `\t'
          Tab character (ASCII 0x09)

    `\0'
          ASCII NUL character (ASCII 0x00).

    `\xNN'
          A byte represented by two-digit hexadecimal number NN.  The
          byte is interpreted as the internal multibyte encoding.

    `\uNNNN'
          A character whose UCS2 code is represented by four-digit
          hexadecimal number NNNN.

    `\UNNNNNNNN'
          A character whose UCS4 code is represented by eight-digit
          hexadecimal number NNNNNNNN.

     If Gauche is compiled with internal encoding other than UTF-8, the
     reader uses `gauche.charconv' module to interpret `\uNNNN' and
     `\UNNNNNNNN' escape sequence.

 -- Reader syntax: `#*"'...`"'
     Denotes incomplete string.  The same escape sequences as the
     complete string syntax are recognized.

     Note: literal incomplete strings used to be `#"..."'.  As of
     Gauche 0.6.3, the syntax switched to `#*"..."'.  String
     interpolation will eventually take `#"..."' syntax.

     Rationale of the syntax: '`#*'' is used for bit vector in Common
     Lisp.  Since an incomplete strings is really a byte vector, it has
     similarity.  (Bit vector can be added later, if necessary, and two
     can coexist).


File: gauche-refe.info,  Node: String Predicates,  Next: String Constructors,  Prev: String syntax,  Up: Strings

6.10.2 String Predicates
------------------------

 -- Function: string? obj
     [R5RS] Returns `#t' if OBJ is a string, `#f' otherwise.

 -- Function: string-immutable? obj
     Returns `#t' if OBJ is an immutable string, `#f' otherwise

 -- Function: string-incomplete? obj
     Returns `#t' if OBJ is an incomplete string, `#f' otherwise


File: gauche-refe.info,  Node: String Constructors,  Next: String interpolation,  Prev: String Predicates,  Up: Strings

6.10.3 String Constructors
--------------------------

 -- Function: make-string k &optional char
     [R5RS] Returns a string of length K.  If optional CHAR is given,
     the new string is filled with it.  Otherwise, the string is filled
     with a whitespace.  The result string is always complete.

          (make-string 5 #\x) => "xxxxx"

     Note that the algorithm to allocate a string by `make-string' and
     then fills it one character at a time is _extremely_ inefficient
     in Gauche, and should be avoided.   That kind of algorithms
     unnecessarily assumes underlying string allocation and
     representation mechanism, which Gauche doesn't follow.  You can
     use an output string port for a string construction (*Note String
     ports::).  Even creating a list of characters and using
     `list->string' is faster than using `make-string' and
     `string-set!'.

 -- Function: make-byte-string k &optional byte
     Creates and returns an incomplete string o size K.  If BYTE is
     given, which must be an exact integer, and its lower 8 bits are
     used to initialize every byte in the created string.

 -- Function: string char ...
     [R5RS] Returns a string consisted by CHAR ....

 -- Generic Function: x->string obj
     A generic coercion function.  Returns a string representation of
     OBJ.  The default methods are defined as follows: strings are
     returned as is, numbers are converted by `number->string', symbols
     are converted by `symbol->string', and other objects are converted
     by `display'.

     Other class may provide a method to customize the behavior.


File: gauche-refe.info,  Node: String interpolation,  Next: String Accessors & Modifiers,  Prev: String Constructors,  Up: Strings

6.10.4 String interpolation
---------------------------

The term "string interpolation" is used in various scripting languages
such as Perl and Python to refer to the feature to embed expressions in
a string literal, which are evaluated and then their results are
inserted into the string literal at run time.

   Scheme doesn't define such a feature, but Gauche implements it as a
reader macro.

 -- Reader syntax: `#`'STRING-LITERAL
     Evaluates to a string.  If STRING-LITERAL contains the character
     sequence `,EXPR', where EXPR is a valid external representation of
     a Scheme expression, EXPR is evaluated and its result is inserted
     in the original place (by using `x->string', see *Note String
     Constructors::).

     The comma and the following expression must be adjacent (without
     containing any whitespace characters), or it is not recognized as
     a special sequence.

     Two adjacent commas are converted to a single comma.  You can embed
     a comma before a non-whitespace character in STRING-LITERAL by
     this.

     Other characters in the STRING-LITERAL are copied as is.

     If you use a variable as EXPR and need to delimit it from the
     subsequent string, you can use the symbol escape syntax using `|'
     character, as shown in the last two examples below.

          #`"This is Gauche, version ,(gauche-version)."
           => "This is Gauche, version 0.8.5."

          #`"Date: ,(sys-strftime \"%Y/%m/%d\" (sys-localtime (sys-time)))"
           => "Date: 2002/02/18"

          (let ((a "AAA")
                (b "BBB"))
           #`"xxx ,a ,b zzz")
           => "xxx AAA BBB zzz"

          #`"123,,456,,789"
           => "123,456,789"

          (let ((n 5)) #`"R,|n|RS")
           => "R5RS"

          (let ((x "bar")) #`"foo,|x|.")
           => "foobar"

     In fact, the reader expands this syntax into a macro call, which
     is then expanded into a call of `string-append' as follows:
          #`"This is Gauche, version ,(gauche-version)."
           ==
          (string-append "This is Gauche, version "
                         (x->string (gauche-version))
                         ".")

   _Rationale of the syntax:_ Some other scripting languages use
``$expr'' or '`#{...}''.  I chose this syntax with respect to the
quasiquote (*Note Quasiquotation::).  Althogh it may be awkward to
delimit variable names by `|', the comma syntax should be easier to
read than the other exotic syntax for seasoned Scheme programmers.

   Note that Scheme allows wider range of characters for valid
identifier names than usual scripting languages.  Consequently, you
will almost always need to use `|' delimiters when you interpolate the
value of a variable.  For example, while you can write
`"$year/$month/$day $hour:$minutes:$seconds"' in Perl, you should write
`#`",|year|/,|month|/,day ,|hour|:,|minutes|:,seconds"'.  It may be
better always to delimit direct variable references in this syntax to
avoid confusion.


File: gauche-refe.info,  Node: String Accessors & Modifiers,  Next: String Comparison,  Prev: String interpolation,  Up: Strings

6.10.5 String Accessors & Modifiers
-----------------------------------

 -- Function: string-length string
     [R5RS] Returns a length of (possibly incomplete) string STRING.

 -- Function: string-size string
     Returns a size of (possibly incomplete) STRING.  A size of string
     is a number of bytes STRING occupies on memory.  The same string
     may have different sizes if the native encoding scheme differs.

     For incomplete string, its length and its size always match.

 -- Function: string-ref cstring k &optional fallback
     [R5RS+] Returns K-th character of a complete string CSTRING.  It
     is an error to pass an incomplete string.

     By default, an error is signalled if `k' is out of range
     (negative, or greater than or equal to the length of CSTRING).
     However, if an optional argument FALLBACK is given, it is returned
     in such case.  This is Gauche's extension.

 -- Function: string-byte-ref string k
     Returns K-TH byte of a (possibly incomplete) string STRING.
     Returned value is an integer in the range between 0 and 255.  K
     must be greater than or equal to zero, and less than `(string-size
     STRING)'.

 -- Function: string-set! string k char
     [R5RS] Substitute STRING's K-th character by CHAR.  K must be
     greater than or equal to zero, and less than `(string-length
     STRING)'.  Return value is undefined.

     If STRING is an incomplete string, integer value of the lower 8
     bits of CHAR is used to set STRING's K-th byte.

     See the notes in `make-string' about performance consideration.

 -- Function: string-byte-set! string k byte
     Substitute STRING's K-th byte by integer BYTE.  BYTE must be in
     the range between 0 to 255, inclusive.  K must be greater than or
     equal to zero, and less than `(string-size STRING)'.  If STRING is
     a complete string, it is turned to incomplete string by this
     operation.  Return value is undefined.


File: gauche-refe.info,  Node: String Comparison,  Next: String utilities,  Prev: String Accessors & Modifiers,  Up: Strings

6.10.6 String Comparison
------------------------

 -- Function: string=? string1 string2
 -- Function: string-ci`='? string1 string2
     [R5RS]

 -- Function: string`<'? string1 string2
 -- Function: string`<='? string1 string2
 -- Function: string`>'? string1 string2
 -- Function: string`>='? string1 string2
 -- Function: string-ci`<'? string1 string2
 -- Function: string-ci`<='? string1 string2
 -- Function: string-ci`>'? string1 string2
 -- Function: string-ci`>='? string1 string2
     [R5RS]


File: gauche-refe.info,  Node: String utilities,  Next: String Pointers,  Prev: String Comparison,  Up: Strings

6.10.7 String utilities
-----------------------

 -- Function: substring string start end
     [R5RS]

 -- Function: string-append string ...
     [R5RS]

 -- Function: string->list string &optional start end
 -- Function: list->string list
     [R5RS+][SRFI-13]

 -- Function: string-copy string &optional start end
     [R5RS+][SRFI-13]

 -- Function: string-fill! string char &optional start end
     [R5RS+][SRFI-13] Fills STRING by CHAR.  Optional START and END
     limits the effective area.
          (string-fill! "orange" #\X)
            => "XXXXXX"
          (string-fill! "orange" #\X 2 4)
            => "orXXge"

 -- Function: string-join strs &optional delim grammer
     [SRFI-13] Concatenate strings in the list STRS, with a string
     DELIM as `glue'.

     The argument GRAMMER may be one of the following symbol to specify
     how the strings are concatenated.
    `infix'
          Use DELIM between each string.  This mode is default.  Note
          that this mode introduce ambiguity when STRS is an empty
          string or a list with a null string.
               (string-join '("apple" "mango" "banana") ", ")
                 => "apple, mango, banana"
               (string-join '() ":")
                 => ""
               (string-join '("") ":")
                 => ""

    `strict-infix'
          Works like `infix', but empty list is not allowed to STRS,
          thus avoiding ambiguity.

    `prefix'
          Use DELIM before each string.
               (string-join '("usr" "local" "bin") "/" 'prefix)
                 => "/usr/local/bin"
               (string-join '() "/" 'prefix)
                 => ""
               (string-join '("") "/" 'prefix)
                 => "/"

    `suffix'
          Use DELIM after each string.
               (string-join '("a" "b" "c") "&" 'suffix)
                 => "a&b&c&"
               (string-join '() "&" 'suffix)
                 => ""
               (string-join '("") "&" 'suffix)
                 => "&"


 -- Function: string-scan string item &optional return
     Scan ITEM (either a string or a character) in STRING.  The RETURN
     argument specifies what value should be returned when ITEM is
     found in STRING.  It must be one of the following symbols.

    `index'
          Returns the index in STRING if ITEM is found, or `#f'.  This
          is the default behavior.
               (string-scan "abracadabra" "ada") => 5
               (string-scan "abracadabra" #\c) => 4
               (string-scan "abracadabra" "aba") => #f

    `before'
          Returns a substring of STRING before ITEM, or `#f' if ITEM is
          not found.
               (string-scan "abracadabra" "ada" 'before) => "abrac"
               (string-scan "abracadabra" #\c 'before) => "abra"

    `after'
          Returns a substring of STRING after ITEM, or `#f' if ITEM is
          not found.
               (string-scan "abracadabra" "ada" 'after) => "bra"
               (string-scan "abracadabra" #\c 'after) => "adabra"

    `before*'
          Returns a substring of STRING before ITEM, and the substring
          after it.  If ITEM is not found, returns `(values #f #f)'.
               (string-scan "abracadabra" "ada" 'before*)
                 => "abrac" and "adabra"
               (string-scan "abracadabra" #\c 'before*)
                 => "abra" and "cadabra"

    `after*'
          Returns a substring of STRING up to the end of ITEM, and the
          rest.  If ITEM is not found, returns `(values #f #f)'.
               (string-scan "abracadabra" "ada" 'after*)
                 => "abracada" and "bra"
               (string-scan "abracadabra" #\c 'after*)
                 => "abrac" and "adabra"

    `both'
          Returns a substring of STRING before ITEM and after ITEM.  If
          ITEM is not found, returns `(values #f #f)'.
               (string-scan "abracadabra" "ada" 'both)
                 => "abrac" and "bra"
               (string-scan "abracadabra" #\c 'both)
                 => "abra" and "adabra"

 -- Function: string-split string splitter
     Splits STRING by SPLITTER and returns a list of strings.  SPLITTER
     can be a character, a character set, a string, a regexp, or a
     procedure.

     If SPLITTER is a character, the character is used as a delimiter.

     If SPLITTER is a character set, any consecutive characters that
     are member of the character set are used as a delimiter.

     If a procedure is given to SPLITTER, it is called for each
     character in STRING, and the consecutive characters that caused
     SPLITTER to return a true value are used as a delimiter.

          (string-split "/aa/bb//cc" #\/)    => ("" "aa" "bb" "" "cc")
          (string-split "/aa/bb//cc" "/")    => ("" "aa" "bb" "" "cc")
          (string-split "/aa/bb//cc" "//")   => ("/aa/bb" "cc")
          (string-split "/aa/bb//cc" #[/])   => ("" "aa" "bb" "cc")
          (string-split "/aa/bb//cc" #/\/+/) => ("" "aa" "bb" "cc")
          (string-split "/aa/bb//cc" #[\w])  => ("/" "/" "//" "")
          (string-split "/aa/bb//cc" char-alphabetic?) => ("/" "/" "//" "")

          ;; some boundary cases
          (string-split "abc" #\/) => ("abc")
          (string-split ""    #\/) => ("")

     See also `string-tokenize' in (*Note SRFI-13 other string
     operations::).


File: gauche-refe.info,  Node: String Pointers,  Next: Incomplete strings,  Prev: String utilities,  Up: Strings

6.10.8 String Pointers
----------------------

 -- Builtin Class: <string-pointer>
     String pointer is an object to access string efficiently in
     sequential order (either forward or backward).

     Higher level string iterators and accessors are constructed on top
     of this primitive.  *Note String library::, for details.  It is
     highly recommended to use SRFI-13 functions instead of these
     string pointer objects, for portability.

 -- Function: make-string-pointer str &optional (index 0)
     Creates a string pointer that points to the INDEX-th character of
     string STR.

 -- Function: string-pointer-copy sp
     Copies a string pointer.  The resulting string pointer shares the
     same string as SP, but has distinct pointer.

 -- Function: string-pointer? obj
     Returns `#t' if OBJ is a string pointer.

 -- Function: string-pointer-next! sp
 -- Function: string-pointer-prev! sp

 -- Function: string-pointer-set! sp index

 -- Function: string-pointer-substring sp &keyword (after #f)

 -- Function: string-pointer-index sp
 -- Function: string-pointer-byte-index sp


File: gauche-refe.info,  Node: Incomplete strings,  Prev: String Pointers,  Up: Strings

6.10.9 Incomplete strings
-------------------------

 -- Function: string-complete->incomplete str

 -- Function: string-incomplete->complete str


File: gauche-refe.info,  Node: Regular expression,  Next: Vectors,  Prev: Strings,  Up: Core library

6.11 Regular expression
=======================

Gauche has a built-in regular expression engine which is mostly
upper-compatible of POSIX extended regular expression.  Gauche's regexp
also includes some extensions from Perl 5 regexp.

 -- Builtin Class: <regexp>
     Regular expression object.  You can construct a regexp object from
     a string by `string->regexp' at run time.  Gauche also has a
     special syntax to denote regexp literals, which construct regexp
     object at loading time.

     Gauche's regexp engine is fully aware of multibyte characters.

 -- Builtin Class: <regmatch>
     Regexp match object.  A regexp matcher `rxmatch' returns this
     object if match.  This object contains all the information about
     the match, including submatches.

     The advantage of using match object, rather than substrings or
     list of indices is efficiency.  The regmatch object keeps internal
     state of match, and computes indices and/or substrings only when
     requested.  This is particularly effective for mutibyte strings,
     for index access is slow on them.

 -- Reader Syntax: `#/regexp-spec/'
 -- Reader Syntax: `#/regexp-spec/i'
     Denotes literal regular expression object.  When read, it becomes
     an instance of `<regexp>'.

     If a letter '`i'' is given at the end, the created regexp becomes
     _case-folding regexp_, i.e. it matches in the case-insensitive
     way.  (The current version only cares ASCII characters for
     case-folding-- beyond ASCII characters, the match is done in the
     same way as normal match.)

     The advantage of using this syntax over `string->regexp' is that
     the regexp is compiled only once.  You can use literal regexp
     inside loop without worring about regexp compilation overhead.  If
     you want to construct regexp on-the-fly, however, use
     `string->regexp'.

   Gauche's built-in regexp syntax follows POSIX extended regular
expression, with a bit of extensions taken from Perl.

   Note that the syntax described here is just a surface syntax.
Gauche's regexp compiler works on the abstract syntax tree, and
alternative syntax such as SRE will be supported in the future versions.

`re*'
     Matches zero or more repetition of re.

`re+'
     Matches one or more repetition of re.

`re?'
     Matches zero or one occurrence of re.

`re{n}'
`re{n,}'
`re{n,m}'
     Bounded repetition.  `re{n}' matches exactly n occurrences of re.
     `re{n,}' matches n or more occurrences of re.  `re{n,m}' matches
     at least N and at most M occurrences of re, where N <= M.

`re*?'
`re+?'
`re??'
`re{n,}?'
`re{n,m}?'
     Same as the above repetition construct, but these syntaxes use
     "non-greedy" or "lazy" match strategy.  That is, they try to match
     the minimum number of occurrences of re first, then retry longer
     ones only if it fails.  Compare the following examples:
          (rxmatch-substring (#/<.*>/ "<tag1><tag2><tag3>") 0)
            => "<tag1><tag2><tag3>"

          (rxmatch-substring (#/<.*?>/ "<tag1><tag2><tag3>") 0)
            => "<tag1>"

`(re...)'
     Clustering with capturing.  The regular expression enclosed by
     parenthesis works as a single re.  Besides, the string that
     matches re ... is saved as a _submatch_.

`(?:re...)'
     Clustering without capturing.   `re ...' works as a single re, but
     the matched string isn't saved.

`(?i:re...)'
`(?-i:re...)'
     Lexical case sensitivity control.  `(?i:re...)' makes re...
     matches case-insensitively, while `(?-i:re...)' makes re...
     matches case-sensitively.

     Perl's regexp allows several more flags to appear between '?' and
     ':'.  Gauche only supports above two, for now.

`pattern1|pattern2|...'
     Alternation.  Matches either one of patterns, where each pattern
     is re ....

`.'
     Matches any character (including newline).

`[char-set-spec]'
     Matches any of the character set specified by char-set-spec.
     *Note Character set::, for the details of char-set-spec.

`\s, \d, \w'
     Matches a whitespace character (`#[[:space:]]'), a digit character
     (`#[[:digit:]]'), or a word-constituent character
     (`#[[:alpha:][:digit:]_]'), respectively.

     Can be used both inside and outside of character set.

`\S, \D, \W'
     Matches the complement character set of `\s', `\d' and `\w',
     respectively.

`^, $'
     Beginning and end of string assertion, when appears at the
     beginning or end of the pattern.

`\b, \B'
     Word boundary and non word boundary assertion, repectively.  That
     is, `\b' matches an empty string between word-constituent
     character and non-word-constituent character, and `\B' matches an
     empty string elsewhere.

`(?=pattern)'
`(?!pattern)'
     Positive/negative lookahead assertion.  Match succeeds if pattern
     matches (or does not match) the input string from the current
     position, but this doesn't move the current position itself, so
     that the following regular expression is applied again from the
     current position.

     For example, the following expression matches strings that might
     be a phone number, except the numbers in Japan (i.e. ones that
     begin with "81").
          \+(?!81)\d{9,}


 -- Function: string->regexp string &keyword case-fold
     Takes STRING as a regexp specification, and constructs an instance
     of `<regexp>' object.

     If a true value is given to the keyword argument CASE-FOLD, the
     created regexp object becomes case-folding regexp.  (See the above
     explanation about case-folding regexp).

 -- Function: regexp? OBJ
     Returns true iff OBJ is a regexp object.

 -- Function: regexp->string REGEXP
     Returns a source string describing the regexp REGEXP.  The
     returned string is immutable.

 -- Function: rxmatch regexp string
     REGEXP is a regular expression object.  A string STRING is matched
     by REGEXP.  If it matches, the function returns a `<regmatch>'
     object.  Otherwise it returns `#f'.

     This is called `match', `regexp-search' or `string-match' in some
     other Scheme implementations.

 -- Generic application: REGEXP STRING
     A regular expression object can be applied directly to the string.
     This works the same as `(rxmatch REGEXP STRING)', but allows
     shorter notation.   *Note Applicable objects::, for generic
     mechanism used to implement this.

 -- Function: rxmatch-start match &optional (i 0)
 -- Function: rxmatch-end match &optional (i 0)
 -- Function: rxmatch-substring match &optional (i 0)
     MATCH is a match object returned by `rxmatch'.  If I equals to
     zero, the functions return start, end or the substring of entire
     match, respectively.  With positive integer I, it returns those of
     I-th submatches.  It is an error to pass other values to I.

     It is allowed to pass `#f' to MATCH for convenience.  The
     functions return `#f' in such case.

     These functions correspond to scsh's `match:start', `match:end'
     and `match:substring'.

 -- Function: rxmatch-num-matches match
     Returns the number of matches in MATCH.  The number includes the
     "whole match", so it is always a positive integer for a
     `<regmatch>' object.  The number also includes the submatches that
     don't have value (see the examples below).

     For the convenience, `rxmatch-num-matches' returns 0 if MATCH is
     `#f'.

          (rxmatch-num-matches (rxmatch #/abc/ "abc"))
            => 1

          (rxmatch-num-matches (rxmatch #/(a(.))|(b(.))/ "ba"))
            => 5

          (rxmatch-num-matches #f)
            => 0


 -- Function: rxmatch-after match &optional (i 0)
 -- Function: rxmatch-before match &optional (i 0)
     Returns substring of the input string after or before MATCH.  If
     optional argument is given, the I-th submatch is used (0-th
     submatch is the entire match).
          (define match (rxmatch #/(\d+)\.(\d+)/ "pi=3.14..."))

          (rxmatch-after match) => "..."
          (rxmatch-after match 1) => ".14..."

          (rxmatch-before match) => "pi="
          (rxmatch-before match 2) => "pi=3."

 -- Generic application: REGMATCH &optional INDEX
 -- Generic application: REGMATCH `'before' &optional INDEX
 -- Generic application: REGMATCH `'after' &optional INDEX
     A regmatch object can be applied directly to the integer index, or
     a symbol `before' or `after'.  They works the same as
     `(rxmatch-substring REGMATCH INDEX)', `(rxmatch-before REGMATCH)',
     and `(rxmatch-after REGMATCH)', respectively.  This allows shorter
     notation.  *Note Applicable objects::, for generic mechanism used
     to implement this.

          (define match (#/(\d+)\.(\d+)/ "pi=3.14..."))

          (match)           => "3.14"
          (match 1)         => "3"
          (match 2)         => "14"

          (match 'after)    => "..."
          (match 'after 1)  => ".14..."

          (match 'before)   => "pi="
          (match 'before 2) => "pi=3."

   Seel also *Note Regular expression utilities::, which defines useful
macros and functions to deal with regular expression matching.


File: gauche-refe.info,  Node: Vectors,  Next: Hashtables,  Prev: Regular expression,  Up: Core library

6.12 Vectors
============

 -- Builtin Class: <vector>
     A vector is a simple 1-dimensional array of Scheme objects.  You
     can access its element by index in constant time.  Once created, a
     vector can't be resized.

     Class `<vector>' inherits `<sequence>' and you can use various
     generic functions such as `map' and `fold' on it.   *Note
     Collection framework::, and *Note Sequence framework::.

     If you keep only a homogeneous numeric type, you may be able to
     use SRFI-4 homogenous vectors (*Note Homogeneous vectors::).

 -- Function: vector? obj
     [R5RS] Returns `#t' if OBJ is a vector, `#f' otherwise.

 -- Function: make-vector k &optional fill
     [R5RS] Creates and returns a vector with length K.  If optional
     argument FILL is given, each element of the vector is initialized
     by it.  Otherwise, the initial value of each element is undefined.

 -- Function: vector obj ...
     [R5RS] Creates a vector whose elements are OBJ ....

 -- Function: vector-length vector
     [R5RS] Returns the length of a vector VECTOR.

     With `gauche.collection' module, you can also use a method
     `size-of'.

 -- Function: vector-ref vector k &optional fallback
     [R5RS+] Returns K-th element of vector VECTOR.

     By default, `vector-ref' signals an error if K is negative, or
     greater than or equal to the length of VECTOR.  However, if an
     optional argument FALLBACK is given, it is returned for such case.
     This is an extension of Gauche.

     With `gauche.sequence' module, you can also use a method `ref'.

 -- Function: vector-set! vector k obj
     [R5RS] Sets K-th element of the vector VECTOR to OBJ.  It is an
     error if K is negative or greater than or equal to the length of
     VECTOR.

     With `gauche.sequence' module, you can also use a setter method of
     `ref'.

 -- Function: vector->list vector &optional start end
 -- Function: list->vector list
     [R5RS+] Converts a vector to a list, or vice versa.

     The optional START and END argument of `vector->list' limits the
     range of the VECTOR to be retrieved.

          (vector->list '#(1 2 3 4 5))     => (1 2 3 4 5)
          (list->vector '(1 2 3 4 5))      => #(1 2 3 4 5)
          (vector->list '#(1 2 3 4 5) 2 4) => (3 4)

     With GAUCHE.COLLECTION module, you can use `(coerce-to <list>
     VECTOR)' and `(coerce-to <vector> LIST)' as well.

 -- Function: vector-fill! vector fill &optional start end
     [R5RS+] Sets all elements in a vector VECTOR to FILL.

     Optional START and END limits the range of effect between START-th
     index (inclusive) to END-th index (exclusive).  START defaults to
     zero, and END defaults to the length of VECTOR.  These optional
     arguments are Gauche's extension.

 -- Function: vector-copy vector &optional start end fill
     [SRFI-43] Copies a vector VECTOR.  Optional START and END
     arguments can be used to limit the range of VECTOR to be copied.
     If the range specified by START and END falls outside of the
     original VECTOR, the FILL value is used to fill the result vector.

          (vector-copy '#(1 2 3 4 5))     => #(1 2 3 4 5)
          (vector-copy '#(1 2 3 4 5) 2 4) => #(3 4)
          (vector-copy '#(1 2 3 4 5) 3 7 #f) => #(4 5 #f #f)


File: gauche-refe.info,  Node: Hashtables,  Next: Weak pointers,  Prev: Vectors,  Up: Core library

6.13 Hashtables
===============

 -- Builtin Class: <hash-table>
     Hash table class.

 -- Function: make-hash-table &optional type
     Creates a hash table.   A symbol TYPE specifies the type of the
     table.  The following types are currently supported.  (If TYPE is
     omitted, `eq?' is assumed.)
    `eq?'
          Keys are compared by `eq?'.

    `eqv?'
          Keys are compared by `eqv?'.

    `equal?'
          Keys are compared by `equal?'.

    `string=?'
          Keys are compared by `string=?'.  Key must be a string.

     Hash functions used for `eq?', `eqv?' and `string=?'-type hash
     tables are built in the system; they can be called from Scheme as
     `eq-hash', `eqv-hash', and `string-hash' (SRFI-13).  Those
     functions can't be extended for user-defined objects.   On the
     other hand, `equal?'-type hash tables uses `hash' function below,
     with which you define hash functions for user-defined objects.


 -- Function: hash obj
     Returns a hash value of OBJ.  This is the hash function used in
     `equal?'-type hash table.  The hash value is an exact non-negative
     integer, and it has two properties:
        * For any object A and B, if `(equal? A and B)', then `(= (hash
          A) (hash B))', while `hash' is defined for types of A and B.

        * The value of `hash' is independent from the runtime state of
          the machine (such as address of the data); so you can safely
          save the hash value to file and read it again with different
          process without losing vailidity of the hash value.
     If OBJ is either a number, a boolean, a character, a symbol, a
     keyword, a string, a list or a vector, internal hash function is
     used to calculate the hash value.  If OBJ is other than that,
     `hash' calls a generic function `object-hash' to calculate the
     hash value.

 -- Generic Function: object-hash obj
     By defining a method for this generic function, objects of
     user-defined types can have a hash value and can be used in
     `equal?' hash table.

     The method has to return an exact non-negative integer, and has to
     follow the same constraints as of `hash'.

     If the method needs to get hash value of OBJ's elements, it has to
     call `hash' on them, not `object-hash'.  For the hashing of
     primitive objects are done in `hash'.
          (define-class <myclass> () (x y))

          ;; user-defined equality function
          (define-method object-equal? ((a <myclass>) (b <myclass>))
            (and (equal? (ref a 'x) (ref b 'x))
                 (eq?    (ref a 'y) (ref b 'y))))

          ;; user-defined hash function
          (define-method object-hash ((a <myclass>))
            (hash (list (ref a 'x) (ref a 'y))))

 -- Function: eq-hash obj
 -- Function: eqv-hash obj
     These are hash functions used for `eq?'-type and `eqv?'-type hash
     tables.  Returns a non-negative integer up to 2^_n_-1, where _n_
     is system-dependent value no less than 32.  The returned hash
     value is system- and process-dependent, and can't be carried over
     the boundary of the running process.

     Note: don't hash numbers by `eq-hash'.  Two numbers are not
     guaranteed to be `eq?' even if they are numerically equal, so they
     are not supposed to be used as a key in `eq?'-type hash table.

 -- Function: hash-table? obj
     Returns `#t' if OBJ is a hash table.

 -- Function: hash-table-type ht
     Returns one of symbols `eq?', `eqv?', `equal?' or `string=?',
     indicating the type of the hash table HT.

 -- Function: hash-table-num-entries ht
     Returns the number of entries in the hash table HT.

 -- Function: hash-table type key&value ...
     Constructs and returns a hash table of type TYPE from given list
     of arguments.  TYPE is the same as of `make-hash-table'.  Each
     KEY&VALUE must be a pair, and its car is used as a key and its cdr
     is used as a value.

          (hash-table 'eq? '(a . 1) '(b . 2))
            ==
            (let ((h (make-hash-table 'eq?)))
               (hash-table-put! h 'a 1)
               (hash-table-put! h 'b 2)
               h)

 -- Function: hash-table-get ht key &optional default
     Search KEY from a hash table HT, and returns its value if found.
     If the key is not found in the table and DEFAULT is given, it is
     returned.  Otherwise an error is signalled.

 -- Function: hash-table-put! ht key value
     Puts a key KEY with a value VALUE to the hash table HT.

 -- Method: ref (ht <hash-table>) key &optional default
 -- Method: (setter ref) (ht <hash-table>) key value
     Method versions of `hash-table-get' and `hash-table-put!'.

 -- Function: hash-table-exists? ht key
     Returns `#t' if a hash table HT has a key KEY.

 -- Function: hash-table-delete! ht key
     Deletes an entry that has a key KEY from the hash table HT.
     Returns `#t' if the entry has exist, or `#f' if the entry hasn't
     exist.   The same function is called `hash-table-remove!' in STk
     (except that it returns an undefined value); I use `delete' for
     consistency to SRFI-1, SRFI-13 and other parts of the libraries.

 -- Function: hash-table-push! ht key value
     Conses VALUE to the existing value for the key KEY in the hash
     table HT and makes it the new value for KEY.  If there's no entry
     for KEY, an entry is created with the value `(list VALUE)'.

     Works the same as the following code, except that this function
     only looks up the KEY once, thus it's more efficient.
          (hash-table-put! ht key
              (cons value (hash-table-get ht key '())))

 -- Function: hash-table-pop! ht key &optional default
     Looks for the value for the key KEY in the hash table HT.  If
     found and it is a pair, replaces the value for its cdr and returns
     car of the original value.  If no entry for KEY is in the table,
     or the value is not a pair, the table is not modified and the
     procedure returns DEFAULT if given, or signals an error otherwise.

     During the operation the key is looked for only once, thus runs
     efficiently.

 -- Function: hash-table-update! ht key proc &optional default
     A more general version of `hash-table-push!' etc.  It works
     basically as the following code piece, except that the lookup of
     KEY is only done once.
          (let ((tmp (proc (hash-table-get HT KEY))))
            (hash-table-put! HT KEY tmp)
            tmp)
     When HT doesn't have the entry for KEY, the action depends on
     whether DEFAULT is given.  If DEFAULT is given, its value is
     stored to HT as the entry of KEY (Note that PROC won't be called
     in this case).   If DEFAULT is not given, an error is signalled.

     For example, when you use a hash table to count the occurrences of
     items, the following line is suffice to increment the counter of
     the item, regardless of whether ITEM has already appeared or not.

          (hash-table-update! ht item (cut + 1 <>) 0))


 -- Function: hash-table-for-each ht proc
 -- Function: hash-table-map ht proc
     A procedure PROC is called with two arguments, a key and its
     associated value, over all the entries in the hash table HT.

 -- Function: hash-table-fold ht kons knil
     For all entries in the hash table HT, a procedure KONS is called
     with three arguments; a key, its associated value, and the
     previous return value of PROC.  The first call of PROC receives
     KNIL as the third argument.  The return value of the last call of
     PROC is returned from `hash-table-fold'.

 -- Function: hash-table-keys ht
 -- Function: hash-table-values ht
     Returns all the keys or values of hash table HT in a list,
     respectively.

   See also *Note Additional list library::, where `hash-table->alist'
and `alist->hash-table' are defined.


File: gauche-refe.info,  Node: Weak pointers,  Next: Control features,  Prev: Hashtables,  Up: Core library

6.14 Weak pointers
==================

A weak pointer is a reference to an object that doesn't prevent the
object from being garbage-collected.  Gauche provides weak pointers as
a _weak vector_ object.  A weak vector is like a vector of objects,
except each object can be garbage collected if it is not referenced
from objects other than weak vectors.   If the object is collected, the
entry of the weak vector is replaced for `#f.'
     gosh> (define v (make-weak-vector 1))
     v
     gosh> (weak-vector-ref v 0)
     #f
     gosh> (weak-vector-set! v 0 (cons 1 1))
     #<undef>
     gosh> (weak-vector-ref v 0)
     (1 . 1)
     gosh> (gc)
     #<undef>
     gosh> (gc)
     #<undef>
     gosh> (weak-vector-ref v 0)
     #f

 -- Builtin Class: <weak-vector>
     The weak vector class.  Inherits `<sequence>' and `<collection>',
     so you can use `gauche.collection' (*Note Collection framework::)
     and `gauche.sequence' (*Note Sequence framework::).
          (coerce-to <weak-vector> '(1 2 3 4))
            => a weak vector with four elements

 -- Function: make-weak-vector size
     Creates and returns a weak vector of size SIZE.

 -- Function: weak-vector-length wvec
     Returns the length of a weak vector WVEC.

 -- Function: weak-vector-ref wvec k &optioal fallback
     Returns K-th element of a weak vector WVEC.

     By default, `weak-vector-ref' signals an error if K is negative,
     or greater than or equal to the size of WVEC.  However, if an
     optional argument FALLBACK is given, it is returned for such case.

     With `gauche.sequence' module, you can also use a method `ref'.

 -- Function: weak-vector-set! wvec k obj
     Sets K-th element of the weak vector WVEC to OBJ.  It is an error
     if K is negative or greater than or equal to the size of WEC.


File: gauche-refe.info,  Node: Control features,  Next: Exceptions,  Prev: Weak pointers,  Up: Core library

6.15 Control features
=====================

* Menu:

* Procedures::
* Applicable objects::
* Continuation::
* Multiple values::
* Delayed Evaludation::


File: gauche-refe.info,  Node: Procedures,  Next: Applicable objects,  Prev: Control features,  Up: Control features

6.15.1 Procedures
-----------------

 -- Builtin Class: <procedure>

 -- Function: procedure? obj
     [R5RS] Returns `#t' if OBJ is a procedure, `#f' otherwise.

 -- Function: apply proc arg1 ... args
     [R5RS] Calls a procedure PROC with a list of arguments, `(ARG1 ...
     . ARGS)'.  The last argument ARGS must be a proper list.  Returns
     (a) value(s) PROC returns.
          (apply list 'a 'b '(c d e)) => (a b c d e)

          (apply + 1 2 '(3 4 5))      => 15

* Menu:

* Mapping::
* Combinators::
* Optional argument parsing::
* Procedure arity::


File: gauche-refe.info,  Node: Mapping,  Next: Combinators,  Prev: Procedures,  Up: Procedures

6.15.1.1 Mapping
................

 -- Function: map proc list1 list2 ...
     [R5RS+] Applies PROC for each element(s) of given list(s), and
     returns a list of the results.  R5RS doesn't specify the
     application order of `map', but Gauche guarantees PROC is always
     applied in order of the list(s).  Gauche's `map' also terminates
     as soon as one of the list is exhausted.

          (map car '((a b) (c d) (e f))) => (a c e)

          (map cons '(a b c) '(d e f))
            => ((a . d) (b . e) (c . f))

     Note that the `gauche.collection' module (*Note Collection
     framework::) extends `map' to work on any type of collection.

 -- Function: for-each proc list1 list2 ...
     [R5RS] Applies PROC for each element(s) of given list(s) in order.
     The results of PROC are discarded.  The return value of `for-each'
     is undefined.  When more than one list is given, `for-each'
     terminates as soon as one of the list is exhausted.

     Note that the `gauche.collection' module (*Note Collection
     framework::) extends `for-each' to work on any type of collection.


File: gauche-refe.info,  Node: Combinators,  Next: Optional argument parsing,  Prev: Mapping,  Up: Procedures

6.15.1.2 Combinators
....................

Gauche has some primitive procedures that allows combinatory
programming.

 -- Function: pa$ proc arg ...
     Partial application.  Returns a procedure, and when it is called
     with arguments M ..., it is equivalent to call `(proc arg ... m
     ...)'.

          (define add3 (pa$ + 3))
          (add3 4) => 7

          (map (pa$ * 2) '(1 2 3)) => (2 4 6)

     Macros `cut' and `cute' defined in SRFI-26 provide a similar
     abstraction, with a bit more flexible but less compact notation.
     *Note Making Procedures::.

 -- Function: apply$ proc
 -- Function: map$ proc
 -- Function: for-each$ proc
     Partial application version of `apply', `map' and `for-each'.

          (define map2* (map$ (pa$ * 2)))
          (map2* '(1 2 3)) => (2 4 6)


   There are more 'partial-applied' version of procedures defined in
SRFI-1 (*Note List library::), such as `fold$', `filter$', `member$',
etc.

 -- Function: compose f ...
     Combine procedures.  All arguments must be procedures.  When two
     procedures are given, `(compose f g)' is equivalent to the
     following code:
          (lambda args (call-with-values (lambda () (apply g args)) f))

     When more than two arguments are passed, they are composed as
     follows:
          (compose f g h ...) == (compose (compose f g) h ...)

     Some examples:

          (define not-zero? (compose not zero?))
          (not-zero? 3) => #t
          (not-zero? 0) => #f

          (define dot-product (compose (apply$ +) (map$ *)))
          (dot-product '(1 2 3) '(4 5 6)) => 32

     A couple of edge cases: if only one argument is given, the argument
     itself is returned.  If no argumens are given, the procedure
     `values' is returned.

 -- Function: any-pred pred ...
     Returns a procedure which applies given argument(s) to each
     predicate PRED.  If any PRED returns a non-`#f' value, the value
     is returned.  If all the PREDs return `#f', `#f' is returned.

          (define string-or-symbol? (any-pred string? symbol?))
          (string-or-symbol? "abc") => #t
          (string-or-symbol? 'abc)  => #t
          (string-or-symbol? 3)     => #f

          (define <> (any-pred < >))
          (<> 3 4) => #t
          (<> 3 3) => #f

          ((any-pred (cut memq <> '(a b c))
                     (cut memq <> '(1 2 3)))
           'b)  => '(b c)

 -- Function: every-pred pred ...
     Returns a procedure which applies given argument(s) to each
     predicate PRED.  If every PRED returns a non-`#f' value, the value
     returned by the last PRED is returned.  If any PRED returns `#f',
     `every-pred' returns `#f' without calling further PREDs.

          ((every-pred odd? positive?) 3)  => #t
          ((every-pred odd? positive?) 4)  => #f
          ((every-pred odd? positive?) -3) => #f

          (define safe-length (every-pred list? length))
          (safe-length '(a b c))  => 3
          (safe-length "aaa")     => #f


File: gauche-refe.info,  Node: Optional argument parsing,  Next: Procedure arity,  Prev: Combinators,  Up: Procedures

6.15.1.3 Optional argument parsing
..................................

To have optional arguments or keyword arguments in Scheme, you have to
take variable arguments as a list and decompose them by yourself.   The
following macros help it.

 -- Macro: let-optionals* restargs (var-spec ...) body ...
 -- Macro: let-optionals* restargs (var-spec ... . restvar) body ...
     Given a list of values RESTARGS, binds variables accodring to
     VAR-SPEC, then evaluates BODY.

     VAR-SPEC can be either a symbol, or a list of two elements and its
     car is a symbol.  The symbol is the bound variable name.  The
     values in RESTARGS are bound to the symbol in order.  If there are
     not as many values in RESTARGS as VAR-SPEC, the rest of SYMBOLs
     are bound to the default values, determined as follows: If
     VAR-SPEC is just a symbol, the default value is undefined.  If
     VAR-SPEC is a list, the default value is the result of evaluation
     of the second element of the list.  In the latter case the second
     element is only evaluated when there are not enough arguments.
     The binding proceeds in the order of VAR-SPEC, so the second
     element may refer to the bindings of previous VAR-SPEC.

     In the second form, RESTVAR must be a symbol and bound to the list
     of values whatever left from RESTARGS after binding to VAR-SPEC.

     It is not an error if RESTARG has more values than VAR-SPECs.  The
     extra values are simply ignored in the first form.

          (define (proc x . args)
            (let-optionals* args ((a 'a)
                                  (b 'b)
                                  (c 'c))
              (list x a b c)))

          (proc 0)         => (0 a b c)
          (proc 0 1)       => (0 1 b c)
          (proc 0 1 2)     => (0 1 2 c)
          (proc 0 1 2 3)   => (0 1 2 3)

          (define (proc2 . args)
            (let-optionals* args ((a 'a) . b)
              (list a b)))

          (proc2)          => (a ())
          (proc2 0)        => (0 ())
          (proc2 0 1)      => (0 (1))
          (proc2 0 1 2)    => (0 (1 2))

          (define (proc3 . args)
            (let-optionals* args ((a 0)
                                  (b (+ a 1))
                                  (c (+ b 1)))
              (list a b c)))

          (proc3)          => (0 1 2)
          (proc3 8)        => (8 9 10)
          (proc3 8 2)      => (8 2 3)
          (proc3 8 2 -1)   => (8 2 -1)

 -- Macro: get-optional restargs default
     This is a short version of LET-OPTIONALS* where you have only one
     optional argument.  Given the optional argument list RESTARGS,
     this macro returns the value of optional argument if one is given,
     or the result of DEFAULT otherwise.  DEFAULT is not evaluated
     unless RESTARGS is an empty list.

          (define (proc x . maybe-opt)
            (let ((option (get-optional maybe-opt #f)))
              (list x option)))

          (proc 0)         => (0 #f)
          (proc 0 1)       => (0 1)

 -- Macro: let-keywords* restarg (var-spec ...) body ...
     This macro is for keyword arguments.  VAR-SPEC can be one of the
     following forms:

    `(SYMBOL EXPR)'
          If the RESTRAG contains keyword which has the same name as
          SYMBOL, binds SYMBOL to the corresponding value.  If such a
          keyword doesn't appear in RESTARG, binds SYMBOL to the result
          of EXPR.

    `(SYMBOL KEYWORD EXPR)'
          If the RESTARG contains keyword KEYWORD, binds SYMBOL to the
          corresponding value.  If such a keyword doesn't appear in
          RESTARG, binds SYMBOL to the result of EXPR.

     The default value EXPR is only evaluated when the keyword is not
     given to the RESTARG.  The binding is done in the order of
     VAR-SPEC, so the EXPR can refer to the variables bound by
     preceding VAR-SPEC.

     If a keyword that doesn't listed in VAR-SPEC appears in RESTARG,
     it is simply ignored.

          (define (proc x . options)
            (let-keywords* options ((a 'a)
                                    (b :beta 'b)
                                    (c 'c))
              (list x a b c)))

          (proc 0)         => (0 a b c)
          (proc 0 :a 1)    => (0 1 b c)
          (proc 0 :beta 1) => (0 a 1 c)
          (proc 0 :beta 1 :c 3) => (0 a 1 3)


File: gauche-refe.info,  Node: Procedure arity,  Prev: Optional argument parsing,  Up: Procedures

6.15.1.4 Procedure arity
........................

Interface to query procedure's arity.  The API is taken from MzScheme
(PLT Scheme).

 -- Function: arity PROC
     Given procedure PROC, returns an integer, an _arity-at-least_
     object, or a list of integer(s) and _arity-at-least_ objects.

     An integer result indicates PROC takes exactly that number of
     arguments.  An _arity-at-least_ indicates PROC takes at least
     `(arity-at-least-value _arity-at-least_)' arguments.   The list
     indicates there are multiple procedures with different arities.

     Since one can add methods to an existing procedure or generic
     function at any moment in Gauche, the value returned by `arity'
     only indicates the current state of the procedure.  It will change
     if new method is added to the procedure/generic-function.

          (arity cons) => 2
          (arity list) => #<arity-at-least 0>
          (arity make) => (#<arity-at-least 1>)

 -- Function: arity-at-least? OBJ
     Returns true if OBJ is an arity-at-least object.

 -- Function: arity-at-least-value ARITY-AT-LEAST
     Returns the number of required arguments the arity-at-least object
     indicates.

 -- Function: procedure-arity-includes? PROC K
     If a procedure PROC can take K arguments, returns `#t'.  Otherwise
     returns `#f'.


File: gauche-refe.info,  Node: Applicable objects,  Next: Continuation,  Prev: Procedures,  Up: Control features

6.15.2 Applicable objects
-------------------------

Gauche has a special hook to make an arbitrary object _applicable_.

 -- Generic Function: object-apply OBJECT ARG ...
     If an object that is neither a procedure nor a generic function is
     applied to some arguments, the object and the arguments are passed
     to a generic function `object-apply'.

     This can be explained better by examples.

   For example, suppose you try to evaluate the following expression:

     ("abcde" 2)

   The operator evaluates to a string, which is neither a procedure nor
a generic fuction.  So Gauche interpretes the expression as if it were
like this:

     (object-apply "abcde" 2)

   Gauche doesn't define a method of `object-apply' that takes
`<string>' and `<integer>' by default, so this signals an error.
However, if you define such a method:

     (define-method object-apply ((s <string>) (i <integer>))
       (string-ref s i))

   Then the first expression works as if a string is _applied_ on the
integer:

     ("abcde" 2) => #\c

   This mechanism works on almost all occasions where a procedure is
allowed.

     (apply "abcde" '(1))   => (#\b)
     (map "abcde" '(3 2 1)) => (#\d #\c #\b)

   Among Gauche built-in objects, `<regexp>' object and `<regmatch>'
object have `object-apply' defined.  *Note Regular expression::.

 -- Generic Function: (setter object-apply) OBJECT ARG ... VALUE
     If a form of applying an applicable object appears in the first
     position of `set!' form, this method is called, that is:
          (set! (OBJECT ARG ...) VALUE)
           => ((setter object-apply) OBJECT ARG ... VALUE)


File: gauche-refe.info,  Node: Continuation,  Next: Multiple values,  Prev: Applicable objects,  Up: Control features

6.15.3 Continuation
-------------------

 -- Function: call-with-current-continuation proc
 -- Function: call/cc proc
     [R5RS] Encapsulates the current continuation to a procedure
     ("continuation procedure"), and calls PROC with it.  When PROC
     returns, its value becomes `call/cc''s value.  When the
     continuation procedure is invoked with zero or more arguments
     somewhere, the further calculation is abandoned and `call/cc'
     returns with the arguments given to the continuation procedure.

     First class continuation is one of the most distinct feature of
     Scheme, but this margin is too small to contain explanation.
     Please consult to the appropriate documents.

     Gauche supports full continuation, with a few limitations in rare
     cases.   Normally a continuation has an unlimited extent.  However,
     if a continuation is created during "callback" from C code-- that
     is, you call some C-implemented function that calls Scheme code
     again--the continuation's extent is limited until the Scheme
     evaluation returns to the C code.   If you try to invoke the
     continuation from out of its extent, Gauche detects it and signals
     an error.  This is a fundamental limitation and not likely to be
     addressed.

     Note that it is still allowed to invoke a continuation from such
     callbacks.  Also, the typical higher-order functions such as
     `map', `for-each' or `apply' are not using callbacks, and not
     affected by this limitation

     Fortunately, there are not much cases that you need to create an
     unlimited extent continuation in such callbacks.  So far, the
     following code is executed in such callbacks.  Besides them,
     typical callback functions from external C libraries, like GUI
     toolkit, obeys the same limitation.
        * A `write-object' method that is invoked from `write',
          `display' or `format' (*Note Output::).

        * A filler and a flusher callbacks of buffered ports (*Note
          Virtual ports::).


 -- Macro: let/cc var body ...
     This macro expands to : `(call/cc (lambda (VAR) BODY ...))'.  The
     API is taken from PLT Scheme.

 -- Function: dynamic-wind before thunk after
     [R5RS] BEFORE, THUNK and AFTER are all procedures with no
     arguments.  In normal situation, `dynamic-wind' calls BEFORE, then
     THUNK, then AFTER, then returns whatever value(s) THUNK returned.

     If a control flow goes out from THUNK by invoking a continuation
     captured outside of the dynamic scope of `dynamic-wind' (for
     example, an error is signalled in THUNK), AFTER is called.

     If a control flow goes into THUNK by invoking a continuation
     captured inside THUNK from outside of the dynamic scope of
     `dynamic-wind', BEFORE is called.
          (letrec ((paths '())
                   (c #f)
                   (add (lambda (s) (push! paths s))))
            (dynamic-wind
             (lambda () (add 'connect))
             (lambda ()
               (add (call/cc (lambda (c0) (set! c c0) 'talk1))))
             (lambda () (add 'disconnect)))
            (if (< (length paths) 4)
                (c 'talk2)
                (reverse paths)))
           => (connect talk1 disconnect connect talk2 disconnect)


File: gauche-refe.info,  Node: Multiple values,  Next: Delayed Evaludation,  Prev: Continuation,  Up: Control features

6.15.4 Multiple values
----------------------

 -- Function: values obj ...
     [R5RS] Returns OBJ ... as multiple values.  Caller can capture
     multiple values by a built-in syntax `receive' (*Note Binding
     constructs::), or the R5Rs procedure `call-with-values' described
     below.  See also *Note Let-values::.
          (values 1 2) => 1 and 2

 -- Function: call-with-values producer consumer
     [R5RS] Call a procedure PRODUCER with no argument.  Then applies a
     procedure CONSUMER on the value(s) PRODUCER returned.  Returns the
     value(s) CONSUMER returns.
          (call-with-values (lambda () (values 1 2)) cons)
            => (1 . 2)

 -- Macro: values-ref mv-expr k
     Returns K-th value of what MV-EXPR returns.  Conceptually, it is
     the same as the following code.
          (call-with-values (lambda () mv-expr) (lambda r (list-ref r k)))
     This macro uses shortcuts for the typical cases like K is zero.

     Similar to Common Lisp's `nth-value', but the argument order is
     flipped to match other Scheme's `*-ref' procedures.


File: gauche-refe.info,  Node: Delayed Evaludation,  Prev: Multiple values,  Up: Control features

6.15.5 Delayed Evaludation
--------------------------

A syntax `delay' and a procedure `force' are used together to implemnt
_lazy evaluation_ semantics.

 -- Special Form: delay expression
     [R5RS] Returns a _promise_ object that encapsulates the evaluation
     of EXPRESSION.   The evaluation of EXPRESSION is delayed until its
     value is explicitly requested by `force'.

 -- Function: force promise
     [R5RS] If PROMISE is not a promise, it is just returned.

     Otherwise, if PROMISE's value hasn't been computed, `force' makes
     PROMISE's encapsulated expression be evaluated, and returns the
     result.

     Once PROMISE's value is computed, it is memoized in it so that
     subsequent `force' on it won't cause the computation.

 -- Function: promise? obj
     Returns `#t' iff OBJ is a promise object created by `delay'.

   The following example uses a simple lazy stream to calculate
fibonacci numbers.

     (define (lcar lis)   ;; lazy car
       (car (force lis)))

     (define (lcdr lis)   ;; lazy cdr
       (cdr (force lis)))

     (define (ltake lis n)  ;; lazy take
       (if (<= n 0) '() (cons (lcar lis) (ltake (lcdr lis) (- n 1)))))

     (define (lmap proc l1 l2)  ;; lazy map
       (if (null? l1)
         '()
         (cons (proc (lcar l1) (lcar l2))
               (delay (lmap proc (lcdr l1) (lcdr l2))))))

     ;; lazy list of fibonacci numbers
     (define fibs (list* 1 1 (delay (lmap + fibs (cdr fibs)))))

     ;; take a look
     (ltake fibs 20)
       => (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
           987 1597 2584 4181 6765)


File: gauche-refe.info,  Node: Exceptions,  Next: Eval and repl,  Prev: Control features,  Up: Core library

6.16 Exceptions
===============

Gauche's exception system consists of three components; (1) the way to
signal an exceptional case has occurred, (2) the way to specify how to
handle such a case, and (3) the standard objects (_conditions_) to
communicate the code that signals an exceptional case and the code that
handles it.

   Those three components are typically used together, so first we
explain the typical usage patterns using examples.  Then we describe
each feature in detail.

   Note for terminology: some languages use the word _exception_ to
refer to an object used to communicate the code that encountered an
exceptional situation with a handler that deals with it.  Gauche uses a
term _condition_ to refer to such objects, following SRFI-35.
_Exception_ is the situation, and _condition_ is a runtime object that
describes it.

* Menu:

* Exception handling overview::
* Signalling exceptions::
* Handling exceptions::
* Conditions::


File: gauche-refe.info,  Node: Exception handling overview,  Next: Signalling exceptions,  Prev: Exceptions,  Up: Exceptions

6.16.1 Exception handling overview
----------------------------------

Catching specific errors
........................

One of the most typical exception handling is to catch a specific error
raised by some built-in or library procedures.  A macro `guard' can be
used for such a purpose.  The code looks like this:

     (guard (exc
             ((condition-has-type? exc <read-error>) (format #t "read error!")
                                                     'read-error)
             (else 'other-error))
       (read-from-string "(abc")))

   The cadr of `guard' clause is a form of `(VARIABLE CLAUSE ...)'.  In
this example, the variable is `exc', and it has two clauses.  Each
CLAUSE has the form like the one in `cond'.

   The cddr of `guard' is the body, a list of expressions.  This
example has only one expression, `(read-from-string "(abc")'.

   `guard' starts executing its body.  `read-from-string' reaises an
error of type `<read-error>' when it encounters syntactic errors.  The
form `guard' intercepts the error, and binds the condition object to
the variable EXC, then checks the clauses following EXC in a similar
manner to `cond'--in this case, the thrown condition is of type
`<read-error>', so the test of the first clause is satisfied, and the
rest of clause is executed, i.e. `"read error!"' is printed and a
symbol `read-error' is returned.

   If you're familiar with other languages, you may recognize the
pattern.  The cddr of `guard' form is like TRY clause of C++/Jave or
the cadr of `handler-case' of Common Lisp; and the cdadr of `guard'
form is like `catch' clauses or the cddr of `handler-case'.

   In the test expressions it is common to check the type of thrown
condition.  The function `condition-has-type?' is defined in SRFI-35
but it's rather lengthy.  Gauche's condition classes can also work like
a predicate, so you can write the above expression like this.

     (guard (exc
             ((<read-error> exc) 'read-error)
             (else 'other-error))
       (read-from-string "(abc")))

   _Note:_ Generally you can't use `is-a?' to test if the thrown
condition is of a specific type, since a condition may be _compound_.
See *Note Conditions:: about compound conditions.

   If no tests of CLAUSEs satisfy and no `else' clause is given, the
exception `falls off' the `guard' construct, i.e.  it will be handled
by the outer level of `guard' form or top-level.  For example, the
following `guard' form only handles `<read-error>' and `<system-error>';
if the body throws other type of conditions, it must be handled by
outer level.

     (guard (exc
             ((<read-error> exc) (handle-read-error))
             ((<system-error> exc) (handle-system-error))
             )
       body ...)

   See *Note Handling exceptions:: for more details on `guard' and
other lower-level exception handling constructs.

Signalling exceptions from your code
....................................

The generic way to signal an exception is to use `raise' procedure.

     (raise CONDITION)

   You can pass any object to CONDITION; its interpretation solely
depends on the exception handler.  If you know the code raises an
integer as a condition, you can catch it by `guard' as this:

     (guard (exc
             ((integer? exc) 'raised))
       (raise 3))

   However, as a convention, it is preferable to use an instance of
`<condition>' or one of its subclasses.  A macro `condition' can be
used to create a condition object.  The following examples show how to
create a condition with some slot values and then raise it.

     ;; create and raise an error condition
     (raise (condition
             (<error> (message "An error occurred."))))

     ;; create and raise a system error condition
     (raise (condition
             (<system-error> (message "A system error occurred.")
                             (errno 4))))

   See *Note Conditions:: for the details of `condition' macro and what
kind of condition classes are provided.

   The most common type of condition is an error condition, so a
convenience procedure `error' and `errorf' are provided.  They create
an error condition with a message and raise it.

     ;; `error' concatenates the arguments into a message.
     (unless (integer? obj)
       (error "Integer expected, but got:" obj))

     ;; `errorf' uses format to create a message.
     (unless (equal? x y)
       (errorf "~s and ~s don't match" x y))

   _Note:_ unlike the exception throwing constructs in some languages,
such as `throw' of C++/Java, which abandons its continuation, Scheme's
`raise' may return to its caller.   If you don't want `raise' to
return, a rule of thumb is always to pass one of error conditions to
it; then Gauche guarantees `raise' wont return.   See the description
of `raise' in *Note Signalling exceptions:: for more details.

Defining your own condition
...........................

You can also define your own condition classes to pass
application-specific information from the point of raising exception to
the handlers.

   To fit to Gauche's framework (SRFI-35), it is desirable that the new
condition class inherits a built-in `<condition>' class or one of its
descendants, and also is an instance of a metaclass `<condition-meta>'.

   One way of ensuring the above convention as well as increasing
portability is to use `define-condition-type' macro, defined in
`SRFI-35'.

     (define-condition-type <myapp-error> <error>
       myapp-error?
       (debug-info myapp-error-debug-info)
       (reason myapp-error-reason))

   This defines a condition type (which is a class in Gauche)
`<myapp-error>', with a predicate `myapp-error?' and slots with
accessors.   Then you can use the new condition type like the following
code:

     (guard (exc
              ((myapp-error? exc)
               (let ((debug-info (myapp-error-debug-info exc))
                     (reason (myapp-error-reason exc)))
                 ... handle myapp-error ...)))
       ...
       ...
       (if (something-went-wrong)
         (raise (condition
                  (<myapp-error> (debug-info "during processing xxx")
                                 (reason "something went wrong")))))
       ...
       ...
       )

   See the description of `define-condition-type' macro for how the
condition type is implemented in Gauche's object system.


File: gauche-refe.info,  Node: Signalling exceptions,  Next: Handling exceptions,  Prev: Exception handling overview,  Up: Exceptions

6.16.2 Signalling exceptions
----------------------------

Signalling errors
.................

The most common case of exceptions is an error.  Two convenience
functions to signal a standard error condition are provided.   To
signal a condition other than the standard error, you can use `raise'
as explained below.

 -- Function: error string arg ...
     [SRFI-23] Signals an error.   Internally the action is realized by
     those two steps.
       1. An error condition is created, with the message prefixed by
          STRING and followed by ARGs.

       2. The error condition is thrown, which may be handled by the
          current active exception handler, if any.

     If no error handler is active, the default error handler is used,
     which prints the error message to the current error port and some
     debug information.   Then, if Gauche is running interactively, the
     control moves to the toplevel; if Gauche is running as a script,
     it exits with the exit status `EX_SOFTWARE' (70).

 -- Function: errorf fmt-string arg ...
     Similar to an error, but the error message is formatted by
     `format', i.e. it is equivalent to:
          (define (errorf fmt . args)
            (error (apply format #f fmt args)))

Signalling generic conditions
.............................

 -- Function: raise condition
     [SRFI-18] This is the base mechanism of signalling exceptions.

     The procedure invokes the current exception handler.  The argument
     CONDITION represents the nature of the exception, and passed to
     the exception handler.  Gauche's built-in and library functions
     always use an instance of `<condition>' or one of its subclasses
     as CONDITION, but you can pass any Scheme object to `raise'.  The
     interpretation of CONDITION is up to the exception handler.

     _Note:_ Unlike some of the mainstream languages in which
     "throwing" an exception never returns, you can set up an exception
     handler in the way that `raise' may return.  The details are
     explained in *Note Handling exceptions::.

     If you don't want `raise' to return, the best way is to pass a
     condition which is an instance of `<serious-condition>' or one of
     its subclasses.  Gauche's internal mechanism guarantees raising
     such an exception won't return.  See *Note Conditions:: for the
     hierarchy of built-in conditions.


File: gauche-refe.info,  Node: Handling exceptions,  Next: Conditions,  Prev: Signalling exceptions,  Up: Exceptions

6.16.3 Handling exceptions
--------------------------

High-level exception handling mechanism
.......................................

 -- Macro: guard (var clause ...) body ...
     [SRFI-34] This is _the_ high-level form to handle errors in Gauche.
     It is built on top of `with-error-handler' function below.

     VAR is a symbol, and CLAUSEs are the same form as `cond''s
     clauses, i.e. each clause can be either one of the following forms:
       1. `(TEST EXPR ...)'

       2. `(TEST => PROC)'

     The last CLAUSE may be `(else EXPR ...)'.

     This form evaluates BODY ... and returns the value(s) of the last
     BODY expression in normal case.  If an exception is raised during
     the evaluation of body expressions, the raised exception is bound
     to a variable VAR, then evaluates TEST expression of each clause.
     If one of TEST expressions returns true value, then the
     corresponding EXPRs are evaluated if the clause is the first form
     above, or an PROC is evaluated and the result of TEST is passed to
     the procedure PROC if the clause is the second form.

     When the TEST(s) and EXPR(s) in the clauses are evaluated, the
     exception handler that is in effect of the caller of `guard' are
     installed; that is, if an exception is raised again within CLAUSEs,
     it is handled by the _outer_ exception handler or `guard' form.

     If no TEST returns true value and the last `clause' is `else'
     clause, then the associated EXPRs are evaluated.  If no TEST
     returns true value and there's no `else' clause, the raised
     exception is re-raised, to be handled by the outer exception
     handler.

     When the exception is handled by one of `clause's, `guard' returns
     the value(s) of the last EXPR in the handling clause.

 -- Function: with-error-handler handler thunk
     Makes HANDLER the active error handler and executes THUNK.  If
     THUNK returns normally, the result(s) will be returned.  If an
     error is signalled during execution of THUNK, HANDLER is called
     with one argument, an exception object representing the error,
     with the continuation of `with-error-handler'.  That is,
     `with-error-handler' returns whatever value(s) HANDLER returns.

     If HANDLER signals an error, it will be handled by the handler
     installed when `with-error-handler' called.

     The dynamic environment where HANDLER is executed is the same as
     the error occurs.  If `dynamic-wind' is used in THUNK, its AFTER
     method is called after HANDLER has returned, and before
     `with-error-handler' returns.

     The behavior of `with-error-handler' can be described in the form
     of Scheme code shown below, using the low-level mechanism.  Note
     that the actual function is built in VM, using lighter mechanisms
     (similar to "one-shot continuation", *Note [1CC]: onecont.).

          ;; conceptual implementation of with-error-handler
          (define (with-error-handler handler thunk)
            (call/cc
              (lambda (cont)
                (let* ((prev-handler (current-exception-handler))
                  (with-exception-handler
                    (lambda (exn)
                      (if (error? exn)
                          (with-exception-handler
                            (lambda (err) (prev-handler err))
                            (lambda () (call-with-values (handler exn) cont)))
                          (prev-handler exn)))
                    thunk))))))

Low-level exception handling mechanism
......................................

This layer provides SRFI-18 compatible simple exception mechanism.  You
can override the behavior of higher-level constructs such as
`with-error-handler' by using `with-exception-handler'.

   Note that it is a double-edged sword.  You'll get a freedom to
construct your own exception handling semantics, but the Gauche system
won't save if something goes wrong.   Use these primitives when you
want to customize the system's higher-level semantics or you are
porting from other SRFI-18 code.

 -- Function: current-exception-handler
     [SRFI-18] Returns the current exception handler.

 -- Function: with-exception-handler handler thunk
     [SRFI-18] A procedure HANDLER must take one argument.  This
     procedure sets HANDLER to the current exception handler and calls
     THUNK.

   Generally, if you want to handle non-continuable exception such as
errors using this low-level mechanism, you have to transfer the control
from the handler explicitly (See the explanation of
`with-error-handler' above).  `raise' detects if the handler returns on
the non-continuable exceptions and reports an error using the default
error handler mechanism, but it is just a safety net.

   Note also that HANDLER is called in the same dynamic environment of
`raise'.  So if you raise an exception inside HANDLER, it is captured
by HANDLER again.   It is the programmer's responsibility to propagate
the exception handling to the "outer" exception handlers.

   The behavior of those procedures can be explained in the following
conceptual Scheme code.

     ;; Conceptual implementation of low-level exception mechanism.
     ;; Suppose %xh is a list of exception handlers

     (define (current-exception-handler) (car %xh))

     (define (raise exn)
       (receive r ((car %xh) exn)
         (when (uncontinuable-exception? exn)
           (set! %xh (cdr %xh))
           (raise (make-error "returned from uncontinuable exception")))
         (apply values r)))

     (define (with-exception-handler handler thunk)
       (let ((prev %xh))
         (dynamic-wind
           (lambda () (set! %xh (cons handler %xh)))
           thunk
           (lambda () (set! %xh prev)))))


File: gauche-refe.info,  Node: Conditions,  Prev: Handling exceptions,  Up: Exceptions

6.16.4 Conditions
-----------------

Built-in Condition classes
..........................

Gauche currently has the following hierarchy of built-in condition
classes.  It approximately reflects SRFI-35 and SRFI-36 condition
hierarchy, although they have Gauche-style class names.  If there's a
corresponding SRFI condition type, the class has the SRFI name as well.

       <condition>
         +- <compound-condition>
         +- <serious-condition>
         |    +- <serious-compound-condition> ; also inherits <compound-condition>
         +- <message-condition>
              +- <error>                      ; also inherits <serious-condition>
                   +- <system-error>
                   +- <read-error>
                   +- <io-error>
                        +- <port-error>
                             +- <io-read-error>
                             +- <io-write-error>
                             +- <io-closed-error>
                             +- <io-unit-error>

   Note that some conditions may occur simultaneously; for example,
error during reading from a file because of device failure may consist
both `<system-error>' _and_ `<io-read-error>'.  In such cases, a
_compound condition_ is raised.  So you can't just use, for instance,
`(is-a? obj <io-read-error>)' to check if `<io-read-error>' is thrown.
See the "Condition API" section below.

 -- Metaclass: <condition-meta>
     Every condition class is an instance of this class.  This class
     defines `object-apply' so that you can use a condition class as a
     predicate, e.g.:

          (<error> obj) == (condition-has-type? obj <error>)

 -- Class: <condition>
 -- Condition Type: &condition
     [SRFI-35] The root class of the condition hierarchy.

 -- Class: <compound-condition>
     Represents a compound condition.  A compound condition can be
     created from one or more conditions by `make-compound-condition'.
     Don't use this class directly.

     A compound condition returns `#t' for `condition-has-type?' if any
     of the original conditions has the given type.

 -- Class: <serious-condition>
 -- Condition Type: &serious
     [SRFI-35] Conditions of this class are for the situations that are
     too serious to ignore or continue.  Particularly, you can safely
     assume that if you `raise' this type of condition, it never
     returns.

 -- Class: <serious-compound-condition>
     This is an internal class to represent a compound condition with
     any of its component condition is serious.   Inherits both
     `<compound-condition>' and `<serious-condition>'.
     `make-compound-condition' uses this class if the passed conditions
     includes a serious one.  Don't use this class directly.

 -- Class: <message-condition>
 -- Condition Type: &message
     [SRFI-35] This class represents a condition with a message.  It
     has one slot.

      -- Instance Variable of <message-condition>: message
          A message.


 -- Class: <error>
 -- Condition Type: &error
     [SRFI-35] Indicates an error.  Inherits `<serious-condition>' and
     `<message-condition>', thus has `message' slot.

     Note: SRFI-35 `&error' condition only inherits `&serious' and not
     `&message', so you have to use compound condition to attach a
     message to the error condition.  Gauche uses multiple inheritance
     here, largely because of backward compatibility.  To write a
     portable code, an error condition should be used with a message
     condition, like this:

          (condition
            (&message (message "Error message"))
            (&error))

 -- Class: <system-error>
     A subclass of `<error>'.  When a system call returns an error,
     this type of exception is thrown.  The `message' slot usually
     contains the description of the error (like the one from
     `strerror(3)').  Besides that, this class has one more instance
     slot:

      -- Instance Variable of <system-error>: errno
          Contains an integer value of system's error number.

     This class doesn't have corresponding SRFI condition type, but
     important to obtain OS's raw error code.  In some cases, this type
     of condition is compounded with other condition types, like
     `<io-read-error>'.

 -- Class: <read-error>
 -- Condition Type: &read-error
     [SRFI-36] A subclass of `<error>'.  When the reader detects a
     lexical or syntactic error during reading an S-expression, this
     type of exception is thrown.

      -- Instance Variable of <read-error>: port
          A port from which the reader is reading.  (NB: SRFI-36's
          `&read-error' doesn't have this slot.  Portable program
          shouldn't rely on this slot).

      -- Instance Variable of <read-error>: line
          A line count (1-base) of the input where the reader raised
          this error.  It may be -1 if the reader is reading from a
          port that doesn't keep track of line count.

      -- Instance Variable of <read-error>: column
      -- Instance Variable of <read-error>: position
      -- Instance Variable of <read-error>: span
          These slots are defined in SRFI-36's `&read-error'.  For the
          time being, these slots always hold `#f'.


 -- Class: <io-error>
 -- Condition Type: &io-error
     [SRFI-36] A base class of I/O errors.  Inherits `<error>'.

 -- Class: <port-error>
 -- Condition Type: &io-port-error
     [SRFI-36] An I/O error related to a port.   Inherits `<io-error>'.

      -- Instance Variable of <port-error>: port
          Holds the port where the error occurred.

 -- Class: <io-read-error>
 -- Condition Type: &io-read-error
     [SRFI-36] An I/O error during reading from a port.  Inherits
     `<port-error>'.

 -- Class: <io-write-error>
 -- Condition Type: &io-write-error
     [SRFI-36] An I/O error during writing to a port.  Inherits
     `<port-error>'.

 -- Class: <io-closd-error>
 -- Condition Type: &io-closed-error
     [SRFI-36] An I/O error when read/write is attempted on a closed
     port.  Inherits `<port-error>'.

 -- Class: <io-unit-error>
     An I/O error when the read/write is requested with a unit that is
     not supported by the port (e.g. a binary I/O is requested on a
     character-only port).   Inherits `<port-error>'.

Condition API
.............

 -- Macro: define-condition-type name supertype predicate field-spec ...
     [SRFI-35+] Defines a new condition type.  In Gauche, a condition
     type is a class, whose metaclass is `<condition-meta>'.

     NAME becomes the name of the new type, and also the variable of
     that name is bound to the created condition type.  SUPERTYPE is
     the name of the supertype (direct superclass) of this condition
     type.  A condition type must inherit from `<condition>' or its
     descendants.  (Multiple inheritance can't be specified by this
     form, and generally should be avoided in condition type hierarchy.
     Instead, you can use compound conditions, which don't introduce
     multiple inheritance.)

     A variable PREDICATE is bound to a predicate procedure for this
     condition type.

     Each `field-spec' is a form of `(field-name accessor-name)', and
     the condition will have fields named by FIELD-NAME, and a variable
     ACCESSOR-NAME will be bound to a procedure that accesses the
     field.   In Gauche, each field becomes a slot of the created class.

     Gauche extends srfi-35 to allow PREDICATE and/or `accessor-name'
     to be `#f', or `accessor-name' to be omitted, if you don't need to
     them to be defined.

 -- Function: condition-type? obj
     [SRFI-35] Returns `#t' iff OBJ is a condition type.  In Gauche, it
     means `(is-a? obj <condition-meta>)'.

 -- Function: make-condition-type name parent field-names
     [SRFI-35] A procedural version to create a new condition type.

 -- Function: make-condition type field-name value ...
     [SRFI-35] Creates a new condition of conditon-type TYPE, and
     initializes its fields as specified by `field-name' and `value'
     pairs Returns `#t' iff OBJ is a condition.  In Gauche, it means
     `(is-a? obj <condition>)'.

 -- Function: condition-has-type? obj type
     [SRFI-35] Returns `#t' iff OBJ belongs to a condition type TYPE.
     Because of compound conditions, this is not equivalent to `is-a?'.

 -- Function: condition-ref condition field-name
     [SRFI-35] Retrieves the value of field FIELD-NAME of CONDITION.
     If CONDITION is a compound condition, you can access to the field
     of its original conditions; if more than one original condition
     have FIELD-NAME, the first one passed to `make-compound-condition'
     has precedence.

     You can use SLOT-REF and/or REF to access to the field of
     conditions; compound conditions define a `slot-missing' method so
     that SLOT-REF behaves as if the compound conditions have all the
     slots of the original conditions.  Using `condition-ref' increases
     portability, though.

 -- Function: make-compound-condition condition0 condition1 ...
     [SRFI-35] Returns a compound condition that has all CONDITION0
     CONDITION1 ....  The returned condition's fields are the union of
     all the fields of given conditions; if any conditions have the
     same name of fields, the first one takes precedence.   The
     returned condition also has condition-type of all the types of
     given conditions.  (This is not a multiple inheritance.  See
     `<compound-condition>' above.)

 -- Function: extract-condition condition condition-type
     [SRFI-35] CONDITION must be a condition and have type
     CONDITION-TYPE.  This procedure returns a condition of
     CONDITION-TYPE, with field values extracted from CONDITION.

 -- Macro: condition type-field-binding ...
     [SRFI-35] A convenience macro to create a (possibly compound)
     condition.  TYPE-FIELD-BINDING is a form of `(CONDITION-TYPE
     (FIELD-NAME VALUE-EXPR) ...)'.

          (condition
            (type0 (field00 value00) ...)
            (type1 (field10 value10) ...)
            ...)
           ==
          (make-compound-condition
            (make-condition type0 'field00 value00 ...)
            (make-condition type1 'field10 value10 ...)
            ...)


File: gauche-refe.info,  Node: Eval and repl,  Next: Input and output,  Prev: Exceptions,  Up: Core library

6.17 Eval and repl
==================

 -- Function: eval expr env
     [R5RS] Evaluate EXPR.   ENV must be a value returned by the
     following procedures below.  Right now it is just a `<module>'
     object, but it is possible that the Gauche adopts a first-class
     environment object in future.

 -- Function: null-environment version
 -- Function: scheme-report-environment version
 -- Function: interaction-environment
     [R5RS] Returns an environment specifier which can be used as the
     second argument of `eval'.   Right now an environment specifier is
     just a module.  `(null-environment 5)' returns a `null' module,
     which contains just the syntactic bindings specified in R5RS,
     `(scheme-report-environment 5)' returns a `scheme' module, which
     contains syntactic and procedure bindings in R5RS, and
     `(interaction-environment)' returns a `user' module that contains
     all the Gauche built-ins plus whatever the user defined.  It is
     possible that the Gauche adopts a first-class environment object
     in future, so do not rely on the fact that the environment
     specifier is just a module.

     An error is signaled if a value other than 5 is passed as VERSION
     argument.


 -- Function: read-eval-print-loop &optional reader evaluator printer
          prompter
     This exports `Gosh''s default read-eval-print loop to applications.
     Each argument can be `#f', which indicates it to use Gauche's
     default procedure(s), or a procedure that satisfies the following
     conditions.

    _reader_
          A procedure that takes no arguments.  It is supposed to read
          an expression and returns it.

    _evaluator_
          A procedure that takes two arguments, an expression and an
          environment specifier.  It is supposed to evaluate the
          expression and returns zero or more value(s).

    _printer_
          A procedure that takes zero or more arguments.   It is
          supposed to print out these values.   The result of this
          procedure is discarded.

    _prompter_
          A procedure that takes no arguments.  It is supposed to print
          out the prompt.   The result of this procedure is discarded.

     Given those procedures, `read-eval-print-loop' runs as follows:

       1. Prints the prompt by calling PROMPTER.

       2. Reads an expression by calling READER.  If it returns EOF,
          exits the loop and returns from `read-eval-print-loop'.

       3. Evaluates an expression by calling EVALUATOR

       4. Prints the result by calling PRINTER, then repeats from 1.

     When an error is signaled from one of those procedures, it is
     captured and reported by the default escape handler, then the loop
     restarts from 1.

     It is OK to capture a continuation within those procedures and
     re-invoke them afterwards.


File: gauche-refe.info,  Node: Input and output,  Next: Loading Programs,  Prev: Eval and repl,  Up: Core library

6.18 Input and Output
=====================

* Menu:

* Ports::
* Port and threads::
* Common port operations::
* File ports::
* String ports::
* Coding-aware ports::
* Input::
* Output::


File: gauche-refe.info,  Node: Ports,  Next: Port and threads,  Prev: Input and output,  Up: Input and output

6.18.1 Ports
------------

 -- Builtin Class: <port>
     A port class.   A port is Scheme's way of abstraction of I/O
     channel.  Gauche extends a port in number of ways so that it can
     be used in wide range of applications.

     Standard Scheme (R5RS) essentially defines a port as an entity that
     you can fetch a character at a time and look one character ahead
     from an input port, and put a character at a time to an output
     port.  Other R5RS I/O routines can be built on top of them.

     Besides this basics, Gauche's port can handle the following
     opertaions.

    Binary I/O
          You can read/write one octet at a time, instead of a
          character.  (Remember, Gauche handles multibyte characters,
          so a character may be consisted from more than one bytes).
          Most ports allow you to mix binary I/O and character I/O, if
          needed.

          The most basic binary I/O primitives are `read-byte' and
          `write-byte'.  You can also use higher-level functionality,
          such as `pack' and `unpack' in *Note Packing Binary Data::.

    Block I/O
          You can read/write a specified number of byte sequences.
          This can be an efficient way of moving block of data, if the
          port's underlying implementation supports block I/O operation.

    Conversion
          Some ports can be used to convert a data stream from one
          format to another; one of such applications is character code
          conversion ports, provided by `gauche.charconv' module (*Note
          Character code conversion::, for details).

    Extra features
          There are also a ports with special functionality.  A
          coding-aware port (*Note Coding-aware ports::) recognizes a
          special "magic comment" in the file to know which character
          encoding the file is written.  Virtual ports (*Note Virtual
          ports::) allows you to program the behavior of the port in
          Scheme.



File: gauche-refe.info,  Node: Port and threads,  Next: Common port operations,  Prev: Ports,  Up: Input and output

6.18.2 Port and threads
-----------------------

When Gauche is compiled with thread support, the builtin port
operations locks the port, so that port access from multiple threads
will be serialized.  (It is required by SRFI-18, BTW).  Here, "builtin
port opertaions" are the port access functions that takes a port and
does some I/O or query on it, such as `read'/`write',
`read-char'/`write-char', `port->string', etc.  Note that `call-with-*'
and `with-*' procedures do not lock the port during calling the given
procedures, since the procedure may pass the reference of the port to
the other thread, and Gauche wouldn't know if that's the case.

   This means usually you don't need to worry about accessing the ports
under multithreaded environment, but also it costs some overhead for
each port access.  The overhead may be a problem if your program is I/O
intensive and does a lot of fine-grained port access (character-wise or
byte-wise).  If that is the case, you can explicitly lock the port
during the processing by the following procedure:

 -- Function: with-port-locking port thunk
     Executes THUNK, while making the calling thread hold the exclusive
     lock of PORT during the dynamic extent of THUNK.

     Calls of the builtin port functions during the lock is held would
     bypass mutex operations and yield better performance.

     Note that the lock is held during the dynamic extent of THUNK; so,
     if THUNK invokes a continuation captured outside of
     `with-port-locking', the lock is released.  If the continuation
     captured within THUNK is invoked afterwards, the lock is
     re-acquired.

     `With-port-locking' may be nested.  The lock is valid during the
     outermost call of `with-port-locking'.


File: gauche-refe.info,  Node: Common port operations,  Next: File ports,  Prev: Port and threads,  Up: Input and output

6.18.3 Common port operations
-----------------------------

 -- Function: port? obj
 -- Function: input-port? obj
 -- Function: output-port? obj
     [R5RS] Returns true if OBJ is a port, an input port and an output
     port, respectively.  `Port?' is not listed in the R5RS standard
     procedures, but mentioned in the "Disjointness of Types" section.

 -- Function: port-closed? port
     Returns true if OBJ is a port and it is already closed.  A closed
     port can't be reopened.

 -- Function: current-input-port
 -- Function: current-output-port
     [R5RS] Returns the current input port and the current output port,
     respectively.

 -- Function: current-error-port
     Returns the current output port.

 -- Function: standard-input-port
 -- Function: standard-output-port
 -- Function: standard-error-port
     Returns ports that are bound initially to current input, output and
     error port, respectively.

 -- Function: with-input-from-port port thunk
 -- Function: with-output-to-port port thunk
 -- Function: with-error-to-port port thunk
     Calls THUNK.  During evaluation of thunk, the current input port,
     current output port and current error port are set to PORT,
     respectively.

 -- Function: close-input-port port
 -- Function: close-output-port port
     [R5RS] Closes input and output PORT, respectively

 -- Function: port-type port
     Returns the type of PORT in one of the symbols `file', `string' or
     `proc'.

 -- Function: port-name port
     Returns the name of PORT.  If the port is associated to a file, it
     is the name of the file.   Otherwise, it is some description of
     the port.

 -- Function: port-buffering port
 -- Function: (setter port-buffering) port buffering-mode
     If PORT is type of file port (i.e. `(port-type PORT)' returns
     `file'), these procedures gets and sets the port's buffering mode.
     For input ports, the port buffering mode may be either one of
     `:full', `:modest' or `:none'.  For output ports,
     `port-buffering', it may be one of `:full', `:line' or `:none'.
     *Note File ports::, for explanation of those modes.

     If `port-buffering' is applied to ports other than file ports, it
     returns `#f'.  If the setter of port-buffering is applied to ports
     other than file ports, it signals an error.

 -- Function: port-current-line port
     Returns the current line count of PORT.  This information is only
     available on file-based port, and as long as you're doing
     sequential character I/O on it.  Otherwise, this returns -1.

 -- Function: port-file-number port
     Returns an integer file descriptor, if the PORT is associated to
     the system file I/O.  Returns `#f' otherwise.

 -- Function: port-seek port offset &optional whence
     If the given PORT allows random access, this procedure sets the
     read/write pointer of the PORT accodring to the given OFFSET and
     WHENCE, then returns the updated offset (number of bytes from the
     beginning of the data).  If PORT is not random-accessible, `#f' is
     returned.  In the current version, file ports and input string
     ports are fully random-accessible.  You can only query the current
     byte offset of output string ports.

     Note that port position is represented by byte count, not
     character count.

     It is allowed to seek after the data if PORT is an output file
     port.  See POSIX lseek(2) document for details of the behavior.
     For input file port and input string port, you can't seek after
     the data.

     The WHENCE argument must be a small integer that represents from
     where OFFSET should be counted.   The following constant values
     are defined.

    `SEEK_SET'
          OFFSET represents the byte count from the beginning of the
          data.  This is the default behavior when WHENCE is omitted.

    `SEEK_CUR'
          OFFSET represents the byte count relative to the current
          read/write pointer.  If you pass 0 to OFFSET, you can get the
          current port position without changing it.

    `SEEK_END'
          OFFSET represents the byte count relative to the end of the
          data.

 -- Function: port-tell port
     Returns the current read/write pointer of PORT in byte count, if
     PORT is random-accessible.   Returns `#f' otherwise.  This is
     equivalent to the following call:
          (port-seek PORT 0 SEEK_CUR)

   _Note on the names_:  `Port-seek' is called `seek', `file-position'
or `input-port-position'/ `output-port-position' on some
implementations.  `Port-tell' is called `tell', `ftell' or
`set-file-position!'.   Some implementations have `port-position' for
different functionality.  CommonLisp has `file-position', but it is not
suitable for us since PORT need not be a file port.  `Seek' and `tell'
reflects POSIX name, and with Gauche naming convention we could use
`sys-seek' and `sys-tell'; however, PORT deals with higher level of
abstraction than system calls, so I dropped those names, and adopted
new names.

 -- Function: copy-port src dst &keyword (unit 0)
     Copies data from an input port SRC to an output port DST, until
     eof is read from SRC.

     The keyword argument UNIT may be zero, a positive exact integer, a
     symbol `byte' or a symbol `char', to specify the unit of copying.
     If it is an integer, a buffer of the size (in case of zero, a
     system default size) is used to copy, using block I/O.  Generally
     it is the fastest if you copy between normal files.   If UNIT is a
     symbol `byte', the copying is done byte by byte, using C-verson of
     `read-byte' and `write-byte'.  If UNIT is a symbol `char', the
     copying is done character by character, using C-version of
     `read-char' and `write-char'.


File: gauche-refe.info,  Node: File ports,  Next: String ports,  Prev: Common port operations,  Up: Input and output

6.18.4 File ports
-----------------

 -- Function: open-input-file filename &keyword if-does-not-exist
          buffering element-type
 -- Function: open-output-file filename &keyword if-does-not-exist
          if-exists buffering element-type
     [R5RS+] Opens a file FILENAME for input or output, and returns an
     input or output port associated with it, respectively.

     The keyword arguments specify precise behavior on the exceptional
     case.

    `:if-exists'
          This keyword argument can be specified only for
          `open-output-file', and specifies the action when the
          FILENAME already exists.  One of the following value can be
          given.
         `:supersede'
               The existing file is truncated.  This is the default
               behavior.

         `:append'
               The output data will be appended to the existing file.

         `:overwrite'
               The output data will overwrite the existing content.  If
               the output data is shorter than the existing file, the
               rest of existing file remains.

         `:error'
               An error is signalled.

         `#f'
               No action is taken, and the function returns `#f'.

    `:if-does-not-exist'
          This keyword argument specifies the action when FILENAME does
          not exist.
         `:error'
               An error is signalled.  This is the default behavior of
               `open-input-file'.

         `:create'
               A file is created.  This is the default behavior of
               `open-output-file'.  The check of file existence and
               creation is done atomically; you can exclusively create
               the file by specifying `:error' or `#f' to IF-EXISTS,
               along this option.  You can't specify this value for
               `open-input-file'.

         `#f'
               No action is taken, and the function returns `#f'.

    `:buffering'
          This argument specifies the buffering mode.  The following
          values are allowed.  The port's buffering mode can be get/set
          by `port-buffering'.  (*Note Common port operations::).
         `:full'
               Buffer the data as much as possible.  This is the
               default mode.

         `:none'
               No buffering is done.  Every time the data is written
               (to an output port) or read (from an input port), the
               underlying system call is used.  Process's standard
               error port is opened in this mode by default.

         `:line'
               This is valid only for output ports.  The written data
               is buffered, but the buffer is flushed whenever a
               newline character is written.  This is suitable for
               interactive output port.  Process's standard output port
               is opened in this mode by default.  (Note that this
               differs from the line buffering mode of C stdio, which
               flushes the buffer as well when input is requested from
               the same file descriptor.)

         `:modest'
               This is valid only for input ports.  This is almost the
               same as the mode `:full', except that `read-block' may
               return less data than requested if the requested amount
               of data is not immediately available.  (In the `:full'
               mode, `read-block' waits the entire data to be read).
               This is suitable for the port connected to a pipe or
               network.

    `:element-type'
          This argument specifies the type of the file.
         `:character'
               The file is opened in "character" (or "text") mode.

         `:binary'
               The file is opened in "binary" mode.
          _In the current version, this argument is ignored and all
          files are opened in binary mode.  It doesn't make difference
          in the Unix platforms._

     By combination of IF-EXISTS and IF-DOES-NOT-EXIST flags, you can
     implement various actions:
          (open-output-file "foo" :if-exists :error)
           => ;opens "foo" exclusively, or error

          (open-output-file "foo" :if-exists #f)
           => ;opens "foo" exclusively, or returns #f

          (open-output-file "foo" :if-exists :append
                                  :if-does-not-exist :error)
           => ;opens "foo" for append only if it already exists

     To check the existence of a file without opening it, use
     `sys-access' or `file-exists?' (*Note File stats::).

     Note: `gauche.charconv' module extends these procedures to take
     ENCODING keyword argument so that they can read or write in
     different character encoding scheme.  *Note Character code
     conversion::.

     Note for portability: Some Scheme implementations (e.g. STk) allows
     you to specify a command to FILENAME and reads from, or writes to,
     the subprocess standard input/output.  Some other scripting
     languages (e.g. Perl) have similar features.  In Gauche,
     `open-input-file' and `open-output-file' strictly operates on
     files (what the underlying OS thinks as files).  However, you can
     use "process ports" to invoke other command in a subprocess and to
     communiate it.  *Note Process ports::, for details.

 -- Function: call-with-input-file string proc &keyword
          if-does-not-exist buffering element-type
 -- Function: call-with-output-file string proc &keyword
          if-does-not-exist if-exists buffering element-type
     [R5RS] Opens a file specified by STRING for input/output, and call
     PROC with one argument, the file port.  When PROC returns, or an
     error is signalled from PROC that is not captured within PROC, the
     file is closed.

     The keyword arguments `if-exists', `element-type' and
     `if-does-not-exist' have the same meanings of `open-input-file'
     and `open-output-file''s.  Note that if you specify `#f' to
     IF-EXISTS and/or IF-DOES-NOT-EXIST, PROC may receive `#f' instead
     of a port object when the file is not opened.

     Returns the value(s) `proc' returned.

 -- Function: with-input-from-file string thunk &keyword
          if-does-not-exist buffering element-type
 -- Function: with-output-to-file string thunk &keyword
          if-does-not-exist if-exists buffering element-type
     [R5RS] Opens a file specified by STRING for input or output and
     makes the opened port as the current input or output port, then
     calls THUNK.  The file is closed when THUNK returns or an error is
     signalled from THUNK that is not captured within THUNK.

     Returns the value(s) `thunk' returns.

     The keyword arguments have the same meanings of `open-input-file'
     and `open-output-file''s, except that when `#f' is given to
     IF-EXISTS and IF-DOES-NOT-EXIST and the opening port is failed,
     THUNK isn't called at all and `#f' is returned as the result of
     `with-input-from-file' and `with-output-to-file'.

   _Notes on semantics of closing file ports:_ R5RS states, in the
description of `call-with-input-file' et al., that _"If _proc_ does not
return, then the port will not be closed automatically unless it is
possible to prove that the port will never again be used for read or
write operation."_

   Gauche's implementation slightly misses this criteria; the mere fact
that an uncaptured error is thrown in PROC does not prove the port will
never be used.  Nevertheless, it is very diffcult to think the
situation that you can do meaningful operation on the port after such
an error is signalled; you'd have no idea what kind of state the port
is in.  In practical programs, you should capture error explicitly
inside PROC if you still want to do some meaningful operation with the
port.

   Note that if a continuation captured outside `call-with-input-file'
et al. is invoked inside PROC, the port is not closed.  It is possible
that the control returns later into the PROC, if a continuation is
captured in it (e.g. coroutines).  The low-level exceptions (*Note
Handling exceptions::) also doesn't ensure closing the port.

 -- Function: open-input-fd-port fd &keyword buffering name owner?
 -- Function: open-output-fd-port fd &keyword buffering name owner?
     Creates and returns an input or output port on top of the given
     file descriptor.  BUFFERING specifies the buffering mode as
     described in `open-input-file' entry above; the default is
     `:full'.  NAME is used for the created port's name and returned by
     `port-name'.  A boolean flag `owner?' specfies whether FD should
     be closed when the port is closed.


File: gauche-refe.info,  Node: String ports,  Next: Coding-aware ports,  Prev: File ports,  Up: Input and output

6.18.5 String ports
-------------------

String ports are the ports that you can read from or write to memory.

 -- Function: open-input-string string
     [SRFI-6] Creates an input string port that has the content STRING.
     This is a more efficient way to access a string in order rather
     than using `string-ref' with incremental index.

          (define p (open-input-string "foo x"))
          (read p) => foo
          (read-char p) => #\space
          (read-char p) => #\x
          (read-char p) => #<eof>
          (read-char p) => #<eof>

 -- Function: get-remaining-input-string port
     PORT must be an input string port.  Returns the remaining content
     of the input port.  The internal pointer of PORT isn't moved, so
     the subsequent read from PORT isn't affected.  If PORT has already
     reached to EOF, a null string is returned.

          (define p (open-input-string "abc\ndef")
          (read-line p)                  => "abc"
          (get-remaining-input-string p) => "def"
          (read-char p)                  => #\d
          (read-line p)                  => "ef"
          (get-remaining-input-string p) => ""

 -- Function: open-output-string
     [SRFI-6] Creates an output string port.   Anything written to the
     port is accumulated in the buffer, and can be obtained as a string
     by `get-output-string'.  This is a far more efficient way to
     construct a string sequentially than pre-allocate a string and
     fill it with `string-set!'.

 -- Function: get-output-string port
     [SRFI-6] Takes an output string port `port' and returns a string
     that has been accumulated to `port' so far.  If a byte data has
     been written to the port, this function re-scans the buffer to see
     if it can consist a complete string; if not, an incomplete string
     is returned.

     This doesn't affect the PORT's operation, so you can keep
     accumulating content to PORT after calling `get-output-string'.

 -- Function: call-with-input-string string proc
 -- Function: call-with-output-string proc
 -- Function: with-input-from-string string thunk
 -- Function: with-output-to-string thunk
     These utility functions are trivially defined as follows.  The
     interface is parallel to the file port version.
          (define (call-with-output-string proc)
            (let ((out (open-output-string)))
              (proc out)
              (get-output-string out)))

          (define (call-with-input-string str proc)
            (let ((in (open-input-string str)))
              (proc in)))

          (define (with-output-to-string thunk)
            (let ((out (open-output-string)))
              (with-output-to-port out thunk)
              (get-output-string out)))

          (define (with-input-from-string str thunk)
            (with-input-from-port (open-input-string str) thunk))

 -- Function: call-with-string-io str proc
 -- Function: with-string-io str thunk
          (define (call-with-string-io str proc)
            (let ((out (open-output-string))
                  (in  (open-input-string str)))
              (proc in out)
              (get-output-string out)))

          (define (with-string-io str thunk)
            (with-output-to-string
              (lambda ()
                (with-input-from-string str
                  thunk))))

 -- Function: write-to-string obj &optional writer
 -- Function: read-from-string string &optional start end
     These convenience functions cover commin idioms using string ports.
          (write-to-string obj writer)
            ==
            (with-output-to-string (lambda () (writer obj)))

          (read-from-string string)
            ==
            (with-input-from-string string read)
     The default value of WRITER is the procedure `write'.  The default
     values of START and END is 0 and the length of STRING.

     Portability note: Common Lisp has these functions, with different
     optional arguments.  STk has `read-from-string' without optional
     argument.


File: gauche-refe.info,  Node: Coding-aware ports,  Next: Input,  Prev: String ports,  Up: Input and output

6.18.6 Coding-aware ports
-------------------------

A coding-aware port is a special type of procedural input port that is
used by `load' to read a program source.  The port recognizes the magic
comment to specify the character encoding of the program source, such
as `;; -*- coding: utf-8 -*-', and makes an appropriate character
encoding conversion.  See *Note Multibyte scripts:: for the details of
coding magic comment.

 -- Function: open-coding-aware-port iport
     Takes an input port and returns an input coding aware port, which
     basically just pass through the data from IPORT to its reader.
     However, if a magic comment appears within the first two lines of
     data from IPORT, the coding aware port applies the necessary
     character encoding conversion to the rest of the data as they are
     read.

     The passed port, IPORT, is "owned" by the created coding-aware
     port.  That is, when the coding-aware port is closed, IPORT is
     also closed.  The content read from IPORT is buffered in the
     coding-aware port, so other code shouldn't read from IPORT.

     By default, Gauche's `load' uses a coding aware port to read the
     program source, so that the coding magic comment works for the
     Gauche source programs (see *Note Loading Scheme file::).
     However, since the mechanism itself is independent from `load',
     you can use this port for other purposes; it is particulary useful
     to write a function that processes Scheme source programs which
     may have the coding magic comment.


File: gauche-refe.info,  Node: Input,  Next: Output,  Prev: Coding-aware ports,  Up: Input and output

6.18.7 Input
------------

For the input-related procedures, the optional IPORT argument must be
an input port, and when omitted, the current input port is assumed.

* Menu:

* Reading data::
* Read-time constructor::
* Input utility functions::


File: gauche-refe.info,  Node: Reading data,  Next: Read-time constructor,  Prev: Input,  Up: Input

6.18.7.1 Reading data
.....................

 -- Function: read &optional iport
     [R5RS] Reads an S-expression from IPORT and returns it.  Gauche
     recognizes the lexical structure specified in R5RS, and some
     additional lexical structures listed in *Note Lexical structure::.

     If IPORT has already reached to the end of file, an eof object is
     returned.

     The procedure reads up to the last character that consists the
     S-expression, and leaves the rest in the port.  It's not like
     CommonLisp's `read', which consumes whitespaces after S-expression
     by default.

 -- Function: read-with-shared-structure &optional iport
 -- Function: read/ss &optional iport
     [SRFI-38] These procedures are defined in srfi-38 to recognize
     shared substructure notation (`#n=', `#n#').   Gauche's builtin
     `read' recognizes the srfi-38 notation, so these are just synonyms
     to `read'; these are only provided for srfi-38 compatibility.

 -- Function: read-char &optional iport
     [R5RS] Reads one character from IPORT and returns it.  If IPORT
     has already reached to the end, returns an eof object.  If the
     byte stream in IPORT doesn't consist a valid character, the
     behavior is undefined.  (In future, a port will have a option to
     deal with invalid characters).

 -- Function: peek-char &optional iport
     [R5RS] Reads one character in IPORT and returns it, keeping the
     character in the PORT.  If the byte stream in IPORT doesn't
     consist a valid character, the behavior is undefined.  (In future,
     a port will have a option to deal with invalid characters).

 -- Function: read-byte &optional iport
     Reads one byte from an input port IPORT, and returns it as an
     integer in the range between 0 and 255.  If IPORT has already
     reached EOF, an eof object is returned.

 -- Function: peek-byte &optional iport
     Peeks one byte at the head of an input port IPORT, and returns it
     as an integer in the range between 0 and 255.  If IPORT has
     already reached EOF, an eof object is returned.

 -- Function: read-line &optional iport allow-byte-string?
     Reads one line (a sequence of characters terminated by newline or
     EOF) and returns a string.  The terminating newline is not
     included.  This function recognizes popular line terminators (LF
     only, CRLF, and CR only).  If IPORT has already reached EOF, an
     eof object is returned.

     If a byte sequence is read from IPORT which doesn't constitute a
     valid character in the native encoding, `read-line' signals an
     error by default.  However, if a true value is given to the
     argument ALLOW-BYTE-STRING?, `read-line' returns a byte string
     (incomplete string) in such case, without reporting an error.  It
     is particulary useful if you read from a source whose character
     encoding is not yet known; for example, to read XML document, you
     need to check the first line to see if there is a charset parameter
     so that you can then use an appropriate character conversion port.

 -- Function: read-block nbytes &optional iport
     Reads NBYTES bytes from IPORT, and returns an incomplete string
     consisted by those bytes.  The size of returned string may shorter
     than NBYTES when IPORT doesn't have enough bytes to fill.  If
     NBYTES is zero, a null string is always returned.

     If IPORT has already reached EOF, an eof object is returned.

     If IPORT is a file port, the behavior of `read-block' differs by
     the buffering mode of the port (*Note File ports::, for the detail
     explanation of buffering modes).
        * If the buffering mode is `:full', `read-block' waits until
          NBYTES data is read, except it reads EOF.

        * If the buffering mode is `:modest' or `:none', `read-block'
          returns shorter string than NBYTES even if it doesn't reach
          EOF, but the entire data is not available immediately.

     `Read-block' returns newly allocated string every time.  If you
     want to avoid allocation and read the data into a pre-allocated
     fixed-length buffer, you can use `read-block!' in `gauche.uvector'
     module (*Note Uvector block I/O::).  It uses a uniform vector as
     the buffer.

     If you want to write a chunk of bytes to a port, you can use
     either `display' if the data is in string, or `write-block' in
     `gauche.uvector' (*Note Uvector block I/O::) if the data is in
     uniform vector.

 -- Function: eof-object? obj
     [R5RS] Returns true if OBJ is an EOF object.

 -- Function: char-ready? port
     [R5RS] If a character is ready to be read from PORT, returns `#t'.

     For now, this procedure actually checks only if next _byte_ is
     immediately available from PORT.   If the next byte is a part of a
     multibyte character, the attempt to read the whole character may
     block, even if `char-ready?' returns `#t' on the port.  (It is
     unlikely to happen in usual situation, but theoretically it can.
     If you concern, use `read-block' to read the input as a byte
     sequence, then use input string port to read characters.)


File: gauche-refe.info,  Node: Read-time constructor,  Next: Input utility functions,  Prev: Reading data,  Up: Input

6.18.7.2 Read-time constructor
..............................

Read-time constructor, defined in SRFI-10, provides an easy way to
create an external representation of user-defined structures.

 -- Reader Syntax: `#,(TAG ARG ...)'
     [SRFI-10] Gauche maintains a global table that associates a TAG
     (symbol) to _a constructor procedure_.

     When the reader encounters this syntax, it reads ARG ..., finds a
     reader constructor associated with TAG, and calls the constructor
     with ARG ... as arguments, then inserts the value returned by the
     constructor as the result of reading the syntax.

     Note that this syntax is processed inside the reader--the
     evaluator doesn't see any of ARGs, but only sees the object the
     reader returns.

 -- Function: define-reader-ctor TAG PROCEDURE
     [SRFI-10] Associates a reader constructor PROCEDURE with TAG.

     Examples:
          (define-reader-ctor 'pi (lambda () (* (atan 1) 4)))

          #,(pi) => 3.141592653589793

          '(#,(pi)) => (3.141592653589793)

          (define-reader-ctor 'hash
            (lambda (type . pairs)
              (let ((tab (make-hash-table type)))
                (for-each (lambda (pair)
                            (hash-table-put! tab (car pair) (cdr pair)))
                          pairs)
                tab)))

          (define table
           #,(hash eq? (foo . bar) (duh . dah) (bum . bom)))

          table => #<hash-table eq? 0x80f9398>
          (hash-table-get table 'duh) => dah

     Combined with `write-object' method (*Note Output::), it is easy
     to make a user-defined class written in the form it can be read
     back:

          (define-class <point> ()
            ((x :init-value 0 :init-keyword :x)
             (y :init-value 0 :init-keyword :y)))

          (define-method write-object ((p <point>) out)
            (format out "#,(<point> ~s ~s)" (ref p 'x) (ref p 'y)))

          (define-reader-ctor '<point>
            (lambda (x y) (make <point> :x x :y y)))


   _NOTE:_ The extent of the effect of `define-reader-ctor' is not
specified in SRFI-10, and might pose a compatibility problem among
implementations that support SRFI-10.  (In fact, the very existence of
`define-reader-ctor' is up to an implementation choice.)

   In Gauche, at least for the time being, `define-reader-ctor' take
effects as soon as the form is compiled and evaluated.  Since Gauche
compiles and evaluates each toplevel form in order, TAG specified in
`define-reader-ctor' can be used immediately after that.  However, it
doesn't work if the call of `define-reader-ctor' and the use of TAG is
enclosed in a `begin' form, for the entire `begin' form is compiled at
once before being evaluated.

   Other implementations may require to read the entire file before
making its `define-reader-ctor' call effective.  If so, it effectively
prevents one from using `define-reader-ctor' and the defined TAG in the
same file.   It is desirable to separate the call of
`define-reader-ctor' and the use of TAG in the different files if
possible.

   Another issue about the current `define-reader-ctor' is that it
modifies the global table of Gauche system, hence not modular.  The
code written by different people might use the same tags, and yield an
unexpected result.   In future versions, Gauche may have some way to
encapsulate the scope of TAG, although the author doesn't have clear
idea yet.


File: gauche-refe.info,  Node: Input utility functions,  Prev: Read-time constructor,  Up: Input

6.18.7.3 Input utility functions
................................

 -- Function: port->string port
 -- Function: port->list reader port
 -- Function: port->string-list port
 -- Function: port->sexp-list port
     Generally useful input procedures.  The API is taken from scsh and
     STk.

     `port->string' reads PORT until EOF and returns the accumulated
     data as a string.

     `port->list' applies READER on PORT repeatedly, until READER
     returns an EOF, then returns the list of objects READER returned.

     `(port->string-list port)' == `(port->list read-line port)' , and
     `(port->sexp-list port)' == `(port->list read port)' .

 -- Function: port-fold fn knil reader
 -- Function: port-fold-right fn knil reader
 -- Function: port-for-each fn reader
 -- Function: port-map fn reader
     Convenient iterators over the input read by READER.  Basically,
     READER is called repeatedly without arguments and FN is called for
     each item it returns, until READER returns EOF.   Actually READER
     can be any thunk; it doesn't need to be related to input port.

     Suppose READER returns a series of items {X0, X1, ..., Xn}.
     `port-fold' returns the following:
          (fn Xn (fn Xn-1 ... (fn X0 knil)))
     while PORT-FOLD-RIGHT returns the following:
          (fn X0 (fn X1 ... (fn Xn knil)))
     That is, `(port-fold cons '() read)' returns a reverse list of all
     the inputs, while `(port-fold-right cons '() read)' returns the
     same thing as `(port->list read port)'.

     On the other hand, `port-for-each' and `port-map' applies FN to
     each item.  The former discards the results FN returns, while the
     latter returns a list of results.


File: gauche-refe.info,  Node: Output,  Prev: Input,  Up: Input and output

6.18.8 Output
-------------

For the following procedures, the optional PORT argument must be an
output port, and when omitted, the current output port is assumed.

 -- Function: write obj &optional port
 -- Function: display obj &optional port
     [R5RS] Produces a printable representation of an object OBJ to the
     output port.  `Write' uses object's standard external
     representation whenever possible, so that the written output would
     be read back by `read', whereas `display' produces more
     human-readable output.

     When `write' and `display' encounter an object of a user-defined
     class, they call the generic function `write-object'.

     These procedures may not stop when OBJ contains a cyclic structure.
     See `write/ss' below.

 -- Function: write-with-shared-structure obj &optional port
 -- Function: write/ss obj &optional port
 -- Function: write* obj &optional port
     [SRFI-38] Produces the output like `write', except that they
     recognize shared substructures and/or cyclic structures, and use
     `#n=' and `#n#' syntax to indicate them.

          (write/ss
            (let ((x (list 'a)))
              (list x x)))
           => ;; writes (#0=(a) #0#)

          (write/ss
            (let ((x (list 'a)))
              (set-cdr! x x)
              x))
           => ;; writes #0=(a . #0#)

     The `read' procedure can recognize this syntax, so when you read
     it back, you can get a structure which is isomorphic to the
     original one.

     Three procedures are the same.  Gauche has been used the name
     `write*' for long, which is taken from STklos.  However,
     `write-with-shared-structure' and `write/ss' have been introduced
     in srfi-38, so these names will be more portable.

     Note: The user-defined `write-object' methods work transparently
     for these procedures as well.

 -- Function: print expr ...
     Displays EXPRs (using `display') to the current output port, then
     writes a newline.

 -- Method: write-object (obj <object>) port
     You can customize how the object is printed out by this method.

 -- Function: newline &optional port
     [R5RS] Writes a newline character to PORT

 -- Function: flush &optional port
 -- Function: flush-all-ports
     Output the buffered data in PORT, or all ports, respectively.

     The function "flush" is called in variety of ways on the various
     Scheme implementations: `force-output' (Scsh, SCM), `flush-output'
     (Gambit), or `flush-output-port' (Bigloo).  The name `flush' is
     taken from STk and STklos.

 -- Function: write-char char &optional port
     [R5RS] Write a single character CHAR to the output port PORT.

 -- Function: write-byte byte &optional port
     Write a byte BYTE to the port.  BYTE must be an exact integer in
     range between 0 and 255.

 -- Function: format port string arg ...
 -- Function: format string arg ...
     [SRFI-28+] Format ARG ... according to STRING.  This function is a
     subset of CommonLisp's `format' function, with a bit of extension.
     It is also a superset of SRFi-28, Basic format strings (*Note
     [SRFI-28]: srfi-28.).

     PORT specifies the destination; if it is an output port, the
     formatted result is written to it; if it is `#t', the result is
     written to the current output port; if it is `#f', the formatted
     result is returned as a string.  PORT can be omitted, as SRFI-28
     `format'; it has the same effects as giving `#f' to the PORT.

     STRING is a string that contains format directives.  A format
     directive is a character sequence begins with tilda, ``~'', and
     ends with some specific characters.  A format directive takes the
     corresponding ARG and formats it.  The rest of string is copied to
     the output as is.

          (format #f "the answer is ~s" 42)
            => "the answer is 42"

     The format directive can take one or more PARAMETERS, separated by
     comma characters.  A parameter may be an integer or a character;
     if it is a character, it should be preceded by a quote character.
     Parameter can be omitted, in such case the system default value is
     used.  The interpretation of the parameters depends on the format
     directive.

     Furthermore, a format directive can take two additional flags:
     atmark ``@'' and colon ``:''.  One or both of them may modify the
     behavior of the format directive.  Those flags must be placed
     immediately before the directive character.

     If a character ``v'' or ``V'' is in the place of the parameter,
     the value of the parameter is taken from the format's argument.
     The argument must be either an integer, a character, or `#f'
     (indicating that the parameter is effectively omitted).

     Some examples:

    `~10,2s'
          A format directive `~s', with two parameters, 10 and 2.

    `~12,,,'*A'
          A format directive `~a', with 12 for the first parameter and
          a character ``*'' for the fourth parameter.  The second and
          third parameters are omitted.

    `~10@d'
          A format directive `~d', with 10 for the first parameter and
          ``@'' flag.

    `~v,vx'
          A format directive `~x', whose first and second parameter will
          be taken from the arguments.

     The following is a complete list of the supported format
     directives.  Either upper case or lower case character can be used
     for the format directive; usually they have no distinction, except
     noted.

    ~MINCOL,COLINC,MINPAD,PADCHAR,MAXCOLA
          Ascii output.  The corresponding argument is printed by
          `display'.  If an integer MINCOL is given, it specifies the
          minimum number of characters to be output; if the formatted
          result is shorter than MINCOL, a whitespace is padded to the
          right (i.e. the result is left justified).

          The COLINC, MINPAD and PADCHAR parameters control, if given,
          further padding.  A character PADCHAR replaces the padding
          character for the whitespace.  If an integer MINPAD is given
          and greater than 0, at least MINPAD padding character is
          used, regardless of the resulting width.  If an integer COLINC
          is given, the padding character is added (after MINPAD) in
          chunk of COLINC characters, until the entire width exceeds
          MINCOL.

          If atmark-flag is given, the format result is right
          justified, i.e.  padding is added to the left.

          The MAXCOL parameter, if given, limits the maximum number of
          characters to be written.  If the length of formatted string
          exceeds MAXCOL, only MAXCOL characters are written.  If
          colon-flag is given as well and the length of formatted string
          exceeds MAXCOL, MAXCOL - 4 characters are written and a
          string "` ...'" is attached after it.

               (format #f "|~a|" "oops")
                 => "|oops|"
               (format #f "|~10a|" "oops")
                 => "|oops      |"
               (format #f "|~10@a|" "oops")
                 => "|      oops|"
               (format #f "|~10,,,'*@a|" "oops")
                 => "|******oops|"

               (format #f "|~,,,,10a|" '(abc def ghi jkl)
                 => "|(abc def gh|"
               (format #f "|~,,,,10:a|" '(abc def ghi jkl)
                 => "|(abc de ...|"

    ~MINCOL,COLINC,MINPAD,PADCHAR,MAXCOLS
          S-expression output.  The corresponding argument is printed
          by `write'.  The semantics of parameters and flags are the
          same as `~A' directive.

               (format #f "|~s|" "oops")
                 => "|\"oops\"|"
               (format #f "|~10s|" "oops")
                 => "|\"oops\"    |"
               (format #f "|~10@s|" "oops")
                 => "|    \"oops\"|"
               (format #f "|~10,,,'*@s|" "oops")
                 => "|****\"oops\"|"

    ~MINCOL,PADCHAR,COMMACHAR,INTERVALD
          Decimal output.  The argument is formatted as an decimal
          integer.  If the argument is not an integer, all parameters
          are ignored (after processing ``v'' parameters) and it is
          formatted by `~A' directive.

          If an integer parameter MINCOL is given, it specifies minimum
          width of the formatted result; if the result is shorter than
          it, PADCHAR is padded on the left (i.e. the result is right
          justified).  The default of PADCHAR is a whitespace.

               (format #f "|~d|" 12345)
                 => "|12345|"
               (format #f "|~10d|" 12345)
                 => "|     12345|"
               (format #f "|~10,'0d|" 12345)
                 => "|0000012345|"

          If atmark-flag is given, the sign ``+'' is printed for the
          positive argument.

          If colon-flag is given, every INTERVAL-th digit of the result
          is grouped and COMMACHAR is inserted between them.  The
          default of COMMACHAR is ``,'', and the default of INTERVAL is
          3.

               (format #f "|~:d|" 12345)
                 => "|12,345|"
               (format #f "|~,,'_,4:d|" -12345678)
                 => "|-1234_5678|"

    ~MINCOL,PADCHAR,COMMACHAR,INTERVALB
          Binary output.  The argument is formatted as a binary integer.
          The semantics of parameters and flags are the same as the
          `~D' directive.

    ~MINCOL,PADCHAR,COMMACHAR,INTERVALO
          Octal output.  The argument is formatted as an octal integer.
          The semantics of parameters and flags are the same as the
          `~D' directive.

    ~MINCOL,PADCHAR,COMMACHAR,INTERVALX

    ~MINCOL,PADCHAR,COMMACHAR,INTERVALx
          Hexadecimal output.  The argument is formatted as a
          hexadecimal integer.  If ``X'' is used, upper case alphabets
          are used for the digits larger than 10.  If ``x'' is used,
          lower case alphabets are used.  The semantics of parameters
          and flags are the same as the `~D' directive.

               (format #f "~8,'0x" 259847592)
                 => "0f7cf5a8"
               (format #f "~8,'0X" 259847592)
                 => "0F7CF5A8"

    ~COUNT*
          Moves the argument counter COUNT times forward, effectively
          skips next COUNT arguments.  The default value of COUNT is 1,
          hence skip the next argument.  If a colon-flag is given,
          moves the argument counter backwards, e.g. `~:*' makes the
          next directive to process last argument again.  If an
          atmark-flag is given, COUNT specifies absolute position of
          the arguments, starting from 0.



File: gauche-refe.info,  Node: Loading Programs,  Next: Comparison and sorting,  Prev: Input and output,  Up: Core library

6.19 Loading Programs
=====================

* Menu:

* Loading Scheme file::
* Loading dynamic library::
* Require and provide::
* Autoload::
* Operations on libraries::


File: gauche-refe.info,  Node: Loading Scheme file,  Next: Loading dynamic library,  Prev: Loading Programs,  Up: Loading Programs

6.19.1 Loading Scheme file
--------------------------

 -- Function: load file &keyword paths (error-if-not-found #t)
          environment ignore-coding
     [R5RS+] Loads FILE, that is, read Scheme expressions in FILE and
     evaluates them.  An extension "`.scm'" may be omitted from FILE.

     If FILE doesn't begin with "/" or "./" or "../", it is searched
     from the system file search list, stored in a variable
     `*load-path*'.  Or you can explicitly specify the search path by
     passing a list of directory names to the keyword argument PATHS.

     On success, `load' returns `#t'.  If the specified file is not
     found, an error is signalled unless the keyword argument
     ERROR-IF-NOT-FOUND is `#f', in which case `load' returns `#f'.

     By default, `load' uses a coding-aware port (*Note Coding-aware
     ports::) so that the "`coding:'" magic comment at the beginning of
     the source file is effective.  (See *Note Multibyte scripts::, for
     the details of the coding magic comment).  If a true value is
     given to the keyword argument IGNORE-CODING, `load' doesn't create
     the coding-aware port and directly reads from the file port.

     If a module is given to the keyword argument ENVIRONMENT, `load'
     works as if the given module is selected at the beginning of the
     loaded file.

     The current module is preserved; even `select-module' is called in
     FILE, the module in which `load' is called is restored afterwards.

     If you want to load a library file, it's better to use ``use''
     (*Note Defining and selecting modules::), or ``require'' described
     below.  *Note Compilation::, for difference between `load' and
     `require'.

 -- Variable: *load-path*
     Keeps a list of directories that are searched by `load' and
     `require'.

     If you want to add other directories to the search path, do not
     modify this variable directly; use `add-load-path', described
     below, instead.

 -- Special Form: add-load-path path &optional (afterp #f)
     Adds a path PATH to the library load path list.  If a true value
     is given to AFTERP, PATH is added after the existing paths;
     otherwise, PATH is added before the existing paths.

     Use this form instead of changing `*load-path*' directly.  This
     form is a special form and recognized by the compiler; if you
     change `*load-path*', it is in effect at run time, and that may be
     too late for "use" or "require".

     Furthermore, `add-load-path' looks for the architecture dependent
     directories under the specified path and if it exists, sets up the
     internal path list for dynamic loading correctly.   Suppose you
     have your Scheme module in `/home/yours/lib', and that requires a
     dyncamic loadable library.  You can put the library under
     `/home/yours/lib/ARCH/', where ARCH is the value
     `(gauche-architecture)' returns (*Note Environment Inquiry::).
     Then you can have compiled libraries for multiple platforms and
     Gauche can still find the right library.

 -- Function: load-from-port port
     Reads Scheme expressions from an input port PORT and evaluates
     them, until EOF is read.

     Note that unless you pass a coding-aware port to PORT, the
     "`coding:'" magic comment won't be handled.

 -- Function: current-load-port
 -- Function: current-load-history
 -- Function: current-load-next
     These procedures allows you to query the current context of
     loading.  They returns the following values when called inside a
     file being loaded:
    `current-load-port'
          Returns the port object from which the file is being read.

    `current-load-history'
          Returns a list of pairs of a port and a line number (integer),
          representing the nesting of loads.  Suppose you load
          `foo.scm', and from its line 7 it loads `bar.scm', and from
          its line 18 it loads `baz.scm'.   If you call
          `current-load-history' in the file `baz.scm', you'll get
               ((#<port "foo.scm"> . 7) (#<port "bar.scm"> . 18))

    `current-load-next'
          Returns a list of remaining directories to be searched at the
          time this file is found.   Suppose the `*load-path*' is `("."
          "../lib" "/home/gauche/lib" "/share/gauche/lib")' and you
          load `foo.scm', which happens to be in `../lib/'.  Then,
          inside `foo.scm', `current-load-next' returns:
               ("/home/gauche/lib" "/share/gauche/lib")

     When called outside of `load', these procedures returns `#f', `()'
     and `()', respectively.


File: gauche-refe.info,  Node: Loading dynamic library,  Next: Require and provide,  Prev: Loading Scheme file,  Up: Loading Programs

6.19.2 Load dynamic library
---------------------------

 -- Function: dynamic-load file &keyword init-function export-symbols
     Loads and links a dynamic loadable library (shared library) FILE.
     FILE shouldn't contain the suffix (".so" on most systems);
     `dynamic-load' adds it, for it may differ among platforms.

     The keyword argument INIT-FUNCTION specifies the initialization
     function name of the library in a string.  By default, if the file
     basename (without extension) is "foo", the initialization function
     name is "Scm_Init_foo".

     The keyword argument EXPORT-SYMBOLS tells whether the dynamic
     loader that the external symbols in FILE should be appended to the
     symbol table of the running process.  (Note: I'm talking about C
     function and variable names, not Scheme symbols).  By default, the
     symbols in FILE are not visible from other dynamically loaded
     libraries.  If you want to allow other dynamically loaded
     libraries to call C function in your library, you should give `#t'
     to this argument.  It sets `RTLD_GLOBAL' flag for `dlopen()'.

     Usually a dynamic loadable library is provided with wrapping Scheme
     module, so the user doesn't have to call this function directly.

     There's no way to unload the loaded libraries.


File: gauche-refe.info,  Node: Require and provide,  Next: Autoload,  Prev: Loading dynamic library,  Up: Loading Programs

6.19.3 Require and provide
--------------------------

 -- Special Form: require feature
     If FEATURE is not loaded, load it.  FEATURE must be a string, and
     it is taken as a file name (without suffix) to be loaded.  This
     loading takes place at compile time.   The loaded file must provide
     FEATURE; if not, a warning is issued.

     If you load SLIB module, `require' is extended.  *Note SLIB:: for
     details.

 -- Function: provide feature
     Adds FEATURE to the system's provided feature list, so that the
     subsequent `require' won't load the same file again.  Usually this
     procedure should be called at the end of the Scheme file that is
     to be `require'd.   The reason that it should be at the end of
     file is that if an error is raised during loading, you may want to
     fix the error and `require' it again.

 -- Function: provided? feature
     Returns `#t' if FEATURE is already provided.


File: gauche-refe.info,  Node: Autoload,  Next: Operations on libraries,  Prev: Require and provide,  Up: Loading Programs

6.19.4 Autoload
---------------

 -- Macro: autoload file/module item ...
     Sets up ITEM ... to be autoloaded.  That is, when an ITEM is
     referenced for the first time, FILE/MODULE is loaded before the
     ITEM is evaluated.  This delays the loading of FILE/MODULE until
     it is needed.

     You can specify either a string file name or a symbol module name
     to FILE/MODULE.  If it is a string, the named file is loaded.  If
     it is a symbol, the named module is loaded (using the same rule as
     of `use'), then the binding of ITEM in the FILE/MODULE is imported
     to the module used the autoload (*Note Defining and selecting
     modules::, for details of `use').

     ITEM can be either a variable name (symbol), or a form `(:macro
     SYMBOL)'.  If it is a variable, the named file/module is loaded
     when the variable is about to be evaluated.  If it is the latter
     form, the named file/module is loaded when a form `(SYMBOL arg
     ...)' is about to be _compiled_, which enables autoloading macros.

     FILE/MODULE must define SYMBOL in it, or an error is signalled
     when FILE/MODULE is autoloaded.

     The following is an example of autoloading procedures.
          (autoload "foo" foo0 foo1)
          (autoload "bar" bar0 bar1)

          (define (foobar x)
            (if (list? x)
                (map bar0 x)
                (foo0)))

          (foobar '(1 2)) ; "bar" is loaded at this moment

          (foobar #f)     ; "foo" is loaded at this moment

     Note that if you set to autoload macro, the file/module is loaded
     immediately when such form that uses the macro is compiled,
     regardless of the piece of the code is executed or not.


File: gauche-refe.info,  Node: Operations on libraries,  Prev: Autoload,  Up: Loading Programs

6.19.5 Operations on libraries
------------------------------

There are several procedures you can use to check if certain libraries
and/or modules are installed in the system.

   In the following descriptions, PATTERN is either a symbol or a
string.  If it is a symbol, it specifies a module name (e.g.
`foo.bar').  If it is a string, it specifies a partial pathname of the
library (e.g. `"foo/bar"'), which will be searched under library search
paths.  You can also use glob-like metacharacters '`*'' and '`?'' in
PATTERN.

 -- Function: library-fold pattern proc seed &keyword paths strict?
          allow-duplicates?
     A basic iterator for library/module files.  This procedure
     searches Scheme program files which matches PATTERN, under
     directories listed in PATHS (the default is the standard file load
     paths, `*load-path*').  For each matched file, it calls PROC with
     three arguments: the matched module or library name, the full path
     of the program file, and the state value.  SEED is used as the
     initial state value, and the value PROC returns is used as the
     state value for the next call of PROC.  The value returned from
     the last PROC becomes the return value of `library-fold'.

     If PATTERN is a symbol and the keyword argument STRICT?  is `#t'
     (which is the default), this procedure calls `library-has-module?'
     on the files whose name seems to match the given pattern of module
     name, in order to find out the file really implements the module.
     It can be a time consuming process if you try to match large
     number of modules; you can pass `#f' to STRICT? to avoid the extra
     check.  If PATTERN is a string, matching is done only for file
     names so STRICT? is ignored.

     By default, if there are more than one files that have the same
     name that matches PATTERN in PATHS, only the first one appears in
     PATHS is taken.  This gives you the file you'll get if you use
     `require' or `use' for that library.  If you want to iterate all
     of matching files, pass `#t' to the ALLOW-DUPLICATES? keyword
     argument.

     Here are some examples (the result may differ in your environment).
          (library-fold 'srfi-1 acons '())
           => ((srfi-1 . "../lib/srfi-1.scm"))

          (library-fold "srfi-1" acons '())
           => (("srfi-1" . "../lib/srfi-1.scm"))

          ;; Note the returned list is in a reverse order of
          ;; how `acons' is called.
          (library-fold 'srfi-1 acons '() :allow-duplicates? #t)
           => ((srfi-1 . "/usr/share/gauche/0.7.1/lib/srfi-1.scm")
             (srfi-1 . "../lib/srfi-1.scm"))

          ;; In the following cases, the module name doesn't match,
          ;; but the filename does.
          (library-fold 'srfi-19.* acons '())
           => ()

          (library-fold "srfi-19/*" acons '())
           => (("srfi-19/read-tai" . "../lib/srfi-19/read-tai.scm")
             ("srfi-19/format" . "../lib/srfi-19/format.scm"))

          ;; Finds available dbm implementations
          (library-fold 'dbm.* acons '())
           => ((dbm.cdb . "/usr/share/gauche/0.7.1/lib/dbm/cdb.scm")
             (dbm.gdbm . "../lib/dbm/gdbm.scm")
             (dbm.ndbm . "../lib/dbm/ndbm.scm")
             (dbm.odbm . "../lib/dbm/odbm.scm"))

 -- Function: library-map pattern proc &keyword paths allow-duplicates?
          strict?
 -- Function: library-for-each pattern proc &keyword paths
          allow-duplicates? strict?
     `Map' and `for-each' version of iterator over matched
     libraries/modules.  See `library-fold' above for deatiled
     operation of matching and the meanings of keyword arguments.

     PROC receives two arguments, the matched module/library name and
     full path of the file.  `Library-map' returns a list of results of
     PROC.  `Library-for-each' discards the results.

          (library-map 'srfi-4 list :allow-duplicates? #t)
           => ((srfi-4 "../lib/srfi-4.scm")
                      (srfi-4 "/usr/share/gauche/0.7.1/lib/srfi-4.scm"))

          (library-map 'dbm.* (lambda (m p) m))
           => (dbm.odbm dbm.ndbm dbm.gdbm dbm.cdb)

 -- Function: library-exists? mod/path &keyword paths force-search?
          strict?
     Search a library or a module specified by MOD/PATH, and returns a
     true value if it finds one.  PATHS and STRICT?  keyword arguments
     have the same meaning as `library-fold'.

     Unlike the iterator procedures above, this procedure first checks
     loaded libraries and modules in the calling process, and returns
     true if it finds MOD/PATH in it, without looking into the
     filesystem.   Passing `#t' to FORCE-SEARCH? keyword arguments
     skips the checking of loaded libraries and modules.

 -- Function: library-has-module? path module
     Returns `#t' iff a file specified by PATH exists and appears to
     implement a module named by `module'.  PATH must be an actual
     filename.

          (library-has-module? "./test/foo/bar.scm" 'foo.bar)
           => #t ;; if ./test/foo/bar.scm implements module foo.bar.

     This procedure assumes a typical layout of the source code to
     determine if the given file implements the module, i.e., it reads
     the first form of the code and see if it is a `define-module' form
     that is defining the given module.


File: gauche-refe.info,  Node: Comparison and sorting,  Next: System interface,  Prev: Loading Programs,  Up: Core library

6.20 Comparison and sorting
===========================

 -- Function: compare obj1 obj2

 -- Generic Function: object-compare obj1 obj2

 -- Function: sort seq &optional cmpfn
 -- Function: sort! seq &optional cmpfn
     Sorts elements in a sequence SEQ (a list or a vector) in ascending
     order and returns the sorted sequence.  `sort!' destructively
     reuses the original sequence.  The sorting order is specified by
     `cmpfn', which is a procedure takes two elements of SEQ, and
     returns `#t' if the first argument strictly precedes the second.

          (sort '(("Chopin" "Frederic")
                  ("Liszt" "Franz")
                  ("Alkan" "Charles-Valentin"))
                (lambda (x y) (string<? (car x) (car y))))
            => (("Alkan" "Charles-Valentin")
                       ("Chopin" "Frederic")
                       ("Liszt" "Franz"))

     Some builtin objects have natural comparison order, and it is used
     if CMPFN is omitted.

     In the current implementation, quicksort and heapsort algorithm is
     used when CMPFN is omitted, and merge sort algorithm is used when
     CMPFN is given.  This might be changed later.

 -- Function: stable-sort seq cmpfn
 -- Function: stable-sort! seq cmpfn
     Sort a sequence SEQ (a list or a vector), using stable sort
     algorithm (currently they are using merge sort).  The sorting
     order is specified by `cmpfn', which is a procedure takes two
     elements of LIST, and returns `#t' if the first argument strictly
     precedes the second.  Unlike `sort'/`sort!', CMPFN cannot be
     omitted.


File: gauche-refe.info,  Node: System interface,  Next: Development helper API,  Prev: Comparison and sorting,  Up: Core library

6.21 System interface
=====================

Gauche supports most of POSIX.1 functions and other system functions
popular among Unix variants as built-in procedures.

   Lots of Scheme implementations provide some sort of system interface
under various APIs.  Some are just called by different names (e.g,
`delete-file' or `remove-file' or `unlink' to delete a file), some do
more abstraction introducing new Scheme objects.  Instead of just
picking one of such interfaces, I decided to implement Gauche's system
interface API in two layers; the lower level layer, described in this
section, follows the operating system's API as close as possible.  On
top of that, the higher-level APIs are provided, with considering
compatibility to the existing systems.

   The low level system interface has the name `sys-'NAME and usually
correspond to the system call NAME.  I tried to keep the interface
similar whenever reasonable.

   Gauche restarts a system call after it is interrupted by a signal.
See *Note Signal:: for the details.

   If you are familiar with system programming in C, see also *Note C
to Scheme mapping::, which shows correspondence between C standard
library functions and Gauche procedures.

* Menu:

* Program termination::
* Environment Inquiry::
* Filesystems::
* Unix groups and users::
* Locale::
* Signal::
* System Inquiry::
* Time::
* Unix process management::
* I/O multiplexing::
* Miscellaneous system calls::


File: gauche-refe.info,  Node: Program termination,  Next: Environment Inquiry,  Prev: System interface,  Up: System interface

6.21.1 Program termination
--------------------------

 -- Function: exit &optional (code 0)
     [POSIX] Terminates the current process with the exit code CODE.
     CODE must be zero or positive exact integer.  This procedure first
     invokes the AFTER thunks of the current dynamic handlers (*Note
     Continuation::), then flushes opened file buffers, finally calls
     `exit(2)'.

 -- Function: sys-exit &optional (code 0)
     [POSIX] Terminates the current process with the exit code CODE.
     CODE must be zero or positive exact integer.  This procedure calls
     `_exit(2)' directly.  No cleanup is done.  Unflushed file output
     is discarded.

 -- Function: sys-abort
     [POSIX] Calls POSIX abort().  This usually terminates the running
     process and dumps core.  No cleanup is done.


File: gauche-refe.info,  Node: Environment Inquiry,  Next: Filesystems,  Prev: Program termination,  Up: System interface

6.21.2 Environment Inquiry
--------------------------

 -- Function: sys-getenv name
     [POSIX] Returns the value of the environment variable NAME as a
     string, or `#f' if the environment variable is not defined.

 -- Function: sys-putenv name value
     Add environment variable NAME with VALUE to the current process's
     environment.  If the system doesn't support putenv(3), this
     function signals an error.

 -- Function: gauche-version
 -- Function: gauche-architecture
 -- Function: gauche-library-directory
 -- Function: gauche-architecture-directory
 -- Function: gauche-site-library-directory
 -- Function: gauche-site-architecture-directory
     These functions returns a string that tells information about
     Gauche interpreter itself.


File: gauche-refe.info,  Node: Filesystems,  Next: Unix groups and users,  Prev: Environment Inquiry,  Up: System interface

6.21.3 Filesystems
------------------

System calls that deal with filesystems.  See also *Note Filesystem
utilities::, which defines high-level APIs on top of the procedures
described here.

* Menu:

* Directories::
* Directory manipulation::
* Pathnames::
* File stats::
* Other file operations::


File: gauche-refe.info,  Node: Directories,  Next: Directory manipulation,  Prev: Filesystems,  Up: Filesystems

6.21.3.1 Directories
....................

See also *Note Directory utilities:: for high-level API.

 -- Function: sys-readdir path
     PATH must be a string that denotes valid pathname of an existing
     directory.  This function returns a list of strings of the
     directory entries.  The returned list is not sorted.  An error is
     signalled if PATH doesn't exists or is not a directory.

 -- Function: sys-glob pattern
     An interface to `glob(3)' function.  PATTERN is a file pattern
     like sh(1): a character ``?'' matches any single character, ``*''
     matches zero or more characters, ``[abc]'' matches either ``a'',
     ``b'' or ``c''.  If no pathname matches PATTERN, an empty list is
     returned.

     If the undelying platform doesn't have `glob()', this function
     signals an error of "feature not supported".

     Note: it is known that on some systems glob() implementation has a
     security issue.  Gauche will eventually implement glob()
     functionality in itself.

   *Note File stats::, to check if a path is actually a directory.


File: gauche-refe.info,  Node: Directory manipulation,  Next: Pathnames,  Prev: Directories,  Up: Filesystems

6.21.3.2 Directory manipulation
...............................

 -- Function: sys-remove filenmae
     [POSIX] If FILENAME is a file it is removed.  On some systems this
     may also work on an empty directory, but portable scripts
     shouldn't depend on it.

 -- Function: sys-rename old new
     [POSIX] Renames a file OLD to NEW.  The new name can be in
     different directory from the old name, but both paths must be on
     the same device.

 -- Function: sys-tmpnam
     [POSIX] Creates a file name which is supposedly unique, and
     returns it.  This is in POSIX, but its use is discouraged because
     of potential security risk.  Use `sys-mkstemp' below if possible.

 -- Function: sys-mkstemp template
     Creates and opens a file that has unique name, and returns two
     values; opened port and the created filename.  The file is created
     exclusively, avoiding race conditions.   TMPNAME is used as the
     prefix of the file.  Unlinke Unix's mkstemp, you don't need
     padding characters.  The file is opened for writing, and its
     permission is set to 600.

 -- Function: sys-link existing new
     [POSIX] Creates a hard link named NEW to the existing file
     EXISTING.

 -- Function: sys-unlink pathname
     [POSIX] Removes PATHNAME.  It can't be a directory.  Returns `#t'
     if it is successfully removed, or #F if PATHNAME doesn't exist.
     An error is signalled otherwise.

 -- Function: sys-symlink existing new
     Creates a symbolic link named NEW to the pathname EXISTING.  On
     systems that doesn't support symbolic links, this function is
     unbound.

 -- Function: sys-readlink path
     If a file specified by PATH is a symbolic link, its content is
     returned.  If PATH doesn't exist or is not a symbolic link, an
     error is signalled.  On systems that don't support symbolic links,
     this function is unbound.

 -- Function: sys-mkdir pathname mode
     [POSIX] Makes a directory PATHNAME with mode MODE.  (Note that
     MODE is masked by the current umask; see `sys-umask' below).  The
     parent directory of PATHNAME must exist and be writable by the
     process.  To create intermediate directories at once, use
     `make-directory*' in `file.util' (*Note Directory utilities::).

 -- Function: sys-rmdir pathname
     [POSIX] Removes a directory PATHNAME.  The directory must be empty.
     To remove a directory with its contents, use `remove-directory*'
     in `file.util' (*Note Directory utilities::).

 -- Function: sys-umask mode
     [POSIX] Sets umask setting to MODE.  Returns previous umask
     setting.  See `man umask' for more details.


File: gauche-refe.info,  Node: Pathnames,  Next: File stats,  Prev: Directory manipulation,  Up: Filesystems

6.21.3.3 Pathnames
..................

See also *Note Pathname utilities::, for high-level APIs.

 -- Function: sys-normalize-pathname pathname &keyword absolute expand
          canonicalize
     Converts PATHNAME according to the way specified by keyword
     arguments.  More than one keyword argument can be specified.
    `absolute'
          If this keyword arugment is given and true, and PATHNAME is
          not   an absolute pathname, it is converted to an absolute
          pathname by   appending the current working directory in
          front of PATHNAME.

    `expand'
          If this keyword argument is given and true, and PATHNAME
          begins   with ``~'', it is expanded as follows:
             *     If PATHNAME is consisted entirely by "`~'", or begins
                  with "`~/'", then the character "`~'" is replaced
               for the pathname of the current user's home directory.

             *     Otherwise, characters following ``~'' until either
               ``/'' or     the end of PATHNAME are taken as a user
               name, and the user's     home directory is replaced in
               place of it.  If there's no such     user, an error is
               signalled.

    `canonicalize'
          Tries to remove pathname components "`.'" and "`..'".    The
          pathname interpretation is done purely in textural level, i.e.
           it doesn't access filesystem to see the conversion reflects
          the   real files.  It may be a problem if there's a symbolic
          links to   other directory in the path.

 -- Function: sys-basename pathname
 -- Function: sys-dirname pathname
     `sys-basename' returns a basename, that is the last component of
     PATHNAME.  `sys-dirname' returns the components of PATHNAME but
     the last one.   If PATHNAME has a trailing ``/'', it is simply
     ignored.
          (sys-basename "foo/bar/bar.z") => "bar.z"
          (sys-basename "coo.scm") => "coo.scm"
          (sys-basename "x/y/") => "y"
          (sys-dirname "foo/bar/bar.z") => "foo/bar"
          (sys-dirname "coo.scm") => "."
          (sys-dirname "x/y/") => "x"
     These functions doesn't check if PATHNAME really exists.

     Some boundary cases:
          (sys-basename "") => ""
          (sys-dirname "") => "."

          (sys-basename "/") => ""
          (sys-dirname "/") => "/"
     Note: The above behavior is the same as Perl's `basename' and
     `dirname'.   On some implementations, the command `basename' may
     return `"/"' for the argument `"/"', and `"."' for the argument
     `"."'.

 -- Function: sys-realpath pathname
     `sys-realpath' returns an absolute pathname of PATHNAME that does
     not include "`.'", "`..'" or symbolic links.  If the system does
     not support realpath(3), this function signals an error.


File: gauche-refe.info,  Node: File stats,  Next: Other file operations,  Prev: Pathnames,  Up: Filesystems

6.21.3.4 File stats
...................

See also *Note File attribute utilities::, for high-level APIs.

 -- Function: file-exists? path
 -- Function: file-is-regular? path
 -- Function: file-is-directory? path
     Returns true if PATH exists, is a regular file, or is a directory,
     respectively.   The latter two returns false if PATH doesn't exist
     at all.

     These functions are built on top of primitive system interfaces
     described below; I provide these for convenience and compatibility
     (STk has the same functions).

 -- Builtin Class: <sys-stat>
     An object that represents `struct stat', attributes of an entry in
     the filesystem.   It has the following read-only slots.

      -- Instance Variable of <sys-stat>: type
          A symbol represents the type of the file.
          `regular'         a regular file
          `directory'       a directory
          `character'       a character device
          `block'           a block device
          `fifo'            a fifo
          `symlink'         a symbolic link
          `socket'          a socket
          If the file type is none of the above, `#f' is returned.

          Note: Some operating systems don't have the `socket' file type
          and returns `fifo' for socket files.   Portable programs
          should check both possibilities to see if the given file is a
          socket.

      -- Instance Variable of <sys-stat>: perm
          An exact integer for permission bits of `struct stat'.  It is
          the same as lower 9-bits of "mode" slot; provided for the
          convenience.

      -- Instance Variable of <sys-stat>: mode
      -- Instance Variable of <sys-stat>: ino
      -- Instance Variable of <sys-stat>: dev
      -- Instance Variable of <sys-stat>: rdev
      -- Instance Variable of <sys-stat>: nlink
      -- Instance Variable of <sys-stat>: uid
      -- Instance Variable of <sys-stat>: gid
      -- Instance Variable of <sys-stat>: size
          An exact integer for those information of `struct stat'.

      -- Instance Variable of <sys-stat>: atime
      -- Instance Variable of <sys-stat>: mtime
      -- Instance Variable of <sys-stat>: ctime
          A number of seconds since Unix Epoch for those information of
          `struct stat'.

 -- Function: sys-stat path
 -- Function: sys-fstat port-or-fd
     [POSIX] Returns a `<sys-stat>' object of PATH, or the underlying
     file of PORT-OR-FD, which may be a port or a positive exact
     integer file descriptor, respectively.

     If PATH is a symbolic link, a stat of the file the link points to
     is returned from `sys-stat'.

     If PORT-OR-FD is not associated to a file, `sys-fstat' returns
     `#f'.

 -- Function: sys-lstat path
     Like `sys-stat', but it returns a stat of a symbolic link if PATH
     is a symbolic link.

     gosh> (describe (sys-stat "gauche.h"))
     #<<sys-stat> 0x815af70> is an instance of class <sys-stat>
     slots:
       type      : regular
       perm      : 420
       mode      : 33188
       ino       : 845140
       dev       : 774
       rdev      : 0
       nlink     : 1
       uid       : 400
       gid       : 100
       size      : 79549
       atime     : 1020155914
       mtime     : 1020152005
       ctime     : 1020152005

 -- Function: sys-stat->mode stat
 -- Function: sys-stat->ino stat
 -- Function: sys-stat->dev stat
 -- Function: sys-stat->rdev stat
 -- Function: sys-stat->nlink stat
 -- Function: sys-stat->size stat
 -- Function: sys-stat->uid stat
 -- Function: sys-stat->gid stat
 -- Function: sys-stat->atime stat
 -- Function: sys-stat->mtime stat
 -- Function: sys-stat->ctime stat
 -- Function: sys-stat->file-type stat
     *Deprecated*.  Use `slot-ref' to access information of
     `<sys-stat>' object.

 -- Function: sys-access pathname amode
     [POSIX] Returns a boolean value of indicating whether access of
     PATHNAME is allowed in AMODE.   This procedure signals an error if
     used in a suid/sgid program (see the note below).  AMODE can be a
     combinations (logical or) of following predefined flags.
    `R_OK'
          Checks whether PATHNAME is readable by the current user.

    `W_OK'
          Checks whether PATHNAME is writable by the current user.

    `X_OK'
          Checks whether PATHNAME is executable (or searchable in case
          PATHNAME is a directory) by the current user.

    `F_OK'
          Checks whether PATHNAME exists or not, regardless of the
          access permissions of PATHNAME.  (But you need to have access
          permissions of the directories containing PATHNAME).

     _Note:_ Access(2) is known to be a security hole if used in
     suid/sgid program to check the real user's priviledge of accessing
     the file.

 -- Function: sys-chmod path mode
     Change the mode of the file named PATH to MODE.  MODE must be a
     small positive integer whose lower 9 bits specifies POSIX style
     permission.

 -- Function: sys-chown path owner-id group-id
     Change the owner and/or group of the file named PATH to OWNER-ID
     and GROUP-ID respectively.  OWNER-ID and GROUP-ID must be an exact
     integer.  If either of them is -1, the corresponding ownership is
     not changed.

 -- Function: sys-utime path &optional atime mtime
     Change the file's access time and modification time to ATIME and
     MTIME, respectively.   If ATIME and MTIME is omitted, they are set
     to the current time.  See also `touch-file' (*Note File
     operations::).


File: gauche-refe.info,  Node: Other file operations,  Prev: File stats,  Up: Filesystems

6.21.3.5 Other file operations
..............................

 -- Function: sys-chdir dir
     [POSIX] An interface to `chdir(2)'.  See also `current-directory'
     (*Note Directory utilities::).

 -- Function: sys-pipe &keyword (buffering :line)
     [POSIX] Creates a pipe, and returns two ports.  The first returned
     port is an input port and the second is an output port.  The data
     put to the output port can be read from the input port.

     BUFFERING can be `:full', `:line' or `:none', and specifies the
     buffering mode of the ports opened on the pipe.  *Note File
     ports::, for details of the buffering mode.  The default mode is
     sufficient for typical cases.

          (receive (in out) (sys-pipe)
            (display "abc\n" out)
            (flush out)
            (read-line in)) => "abc"

     Note: the returned value is changed from version 0.3.15, in which
     `sys-pipe' returned a list of two ports.

 -- Function: sys-mkfifo path mode
     [POSIX] creates a fifo (named pipe) with a name PATH and mode
     MODE.  MODE must be a positive exact integer to represent the file
     mode.

 -- Function: sys-isatty port-or-fd
     [POSIX] PORT-OR-FD may be a port or an integer file descriptor.
     Returns `#t' if the port is connected to the console, `#f'
     otherwise.

 -- Function: sys-ttyname port-or-fd
     [POSIX] PORT-OR-FD may be a port or an integer file descriptor.
     Returns the name of the terminal connected to the port, or `#f' if
     the port is not connected to a terminal.


File: gauche-refe.info,  Node: Unix groups and users,  Next: Locale,  Prev: Filesystems,  Up: System interface

6.21.4 Unix groups and users
----------------------------

Unix groups
...........

 -- Builtin Class: <sys-group>
     Unix group information.  Has following slots.

      -- Instance Variable of <sys-group>: name
          Group name.

      -- Instance Variable of <sys-group>: gid
          Group id.

      -- Instance Variable of <sys-group>: passwd
          Group password.

      -- Instance Variable of <sys-group>: mem
          List of user names who are in this group.


 -- Function: sys-getgrgid gid
 -- Function: sys-getgrnam name
     [POSIX] Returns `<sys-group>' object from an integer group id GID
     or a group name NAME, respectively.  If the specified group
     doesn't exist, `#f' is returned.

 -- Function: sys-gid->group-name gid
 -- Function: sys-group-name->gid name
     Convenience function to convert between group id and group name.

Unix users
..........

 -- Builtin Class: <sys-passwd>
     Unix user information.  Has following slots.

      -- Instance Variable of <sys-passwd>: name
          User name.

      -- Instance Variable of <sys-passwd>: uid
          User ID.

      -- Instance Variable of <sys-passwd>: gid
          User's primary group id.

      -- Instance Variable of <sys-passwd>: passwd
          User's (encrypted) password.  If the system uses the shadow
          password file, you just get obscure string like "x".

      -- Instance Variable of <sys-passwd>: gecos
          Gecos field.

      -- Instance Variable of <sys-passwd>: dir
          User's home directory.

      -- Instance Variable of <sys-passwd>: shell
          User's login shell.

      -- Instance Variable of <sys-passwd>: class
          User's class (only available on some systems).


 -- Function: sys-getpwuid uid
 -- Function: sys-getpwnam name
     [POSIX] Returns `<sys-passwd>' object from an integer user id UID
     or a user name NAME, respectively.  If the specified user doesn't
     exist, `#f' is returned.

 -- Function: sys-uid->user-name uid
 -- Function: sys-user-name->uid
     Convenience functions to convert between user id and user name.

Password encryption
...................

 -- Function: sys-crypt key salt
     This is the interface to `crypt(3)'.   KEY and SALT must be a
     string, and an encrypted string is returned.  On systems where
     `crypt(3)' is not available, call to this function signals an
     error.


File: gauche-refe.info,  Node: Locale,  Next: Signal,  Prev: Unix groups and users,  Up: System interface

6.21.5 Locale
-------------

 -- Function: sys-setlocale category locale
     [POSIX] Sets the locale of the category CATEGORY to the locale
     LOCALE.  CATEGORY must be an exact integer; the following
     pre-defined variables are available.  LOCALE must be a string
     locale name.  Returns the locale name on success, or `#f' if the
     system couldn't change the locale.

 -- Variable: LC_ALL
 -- Variable: LC_COLLATE
 -- Variable: LC_CTYPE
 -- Variable: LC_MONETARY
 -- Variable: LC_NUMERIC
 -- Variable: LC_TIME
     Predefined variables for possible CATEGORY value of
     `sys-setlocale'.

 -- Function: sys-localeconv
     [POSIX] Returns an assoc list of various information for
     formatting numbers in the current locale.

   An example session.  It may differ on your system settings.
     (sys-localeconv)
      =>
        ((decimal_point . ".") (thousands_sep . "")
         (grouping . "") (int_curr_symbol . "")
         (currency_symbol . "") (mon_decimal_point . "")
         (mon_thousands_sep . "") (mon_grouping . "")
         (positive_sign . "") (negative_sign . "")
         (int_frac_digits . 127) (frac_digits . 127)
         (p_cs_precedes . #t) (p_sep_by_space . #t)
         (n_cs_precedes . #t) (n_sep_by_space . #t)
         (p_sign_posn . 127) (n_sign_posn . 127))

     (sys-setlocale LC_ALL "fr_FR")
      => "fr_FR"

     (sys-localeconv)
      =>
       ((decimal_point . ",") (thousands_sep . "")
        (grouping . "") (int_curr_symbol . "FRF ")
        (currency_symbol . "F") (mon_decimal_point . ",")
        (mon_thousands_sep . " ") (mon_grouping . "\x03\x03")
        (positive_sign . "") (negative_sign . "-")
        (int_frac_digits . 2) (frac_digits . 2)
        (p_cs_precedes . #f) (p_sep_by_space . #t)
        (n_cs_precedes . #f) (n_sep_by_space . #t)
        (p_sign_posn . 1) (n_sign_posn . 1))


File: gauche-refe.info,  Node: Signal,  Next: System Inquiry,  Prev: Locale,  Up: System interface

6.21.6 Signal
-------------

Gauche can send out operating system's signals to the other processes
(including itself) and can handle the incoming signals.

   In multithread environment, all threads share the signal handlers,
and each thread has its own signal mask.  See *Note Signals and
threads::, for details.

   When a system call is interrupted by a signal, and a programmer
defines a handler for the signal that doesn't transfer control to other
context, the system call is restarted after the handler returns.

* Menu:

* Signals and signal sets::
* Sending signals::
* Handling signals::
* Masking and waiting signals::
* Signals and threads::


File: gauche-refe.info,  Node: Signals and signal sets,  Next: Sending signals,  Prev: Signal,  Up: Signal

6.21.6.1 Signals and signal sets
................................

Signals are referred by its signal number (a small integer) defined on
the underlying operating system.  Variables are pre-defined to the
system's signal number.  System's signal numbers may be architecture
dependent, so you should use those variables rather than using literal
integers.

 -- Variable: SIGABRT
 -- Variable: SIGALRM
 -- Variable: SIGCHLD
 -- Variable: SIGCONT
 -- Variable: SIGFPE
 -- Variable: SIGHUP
 -- Variable: SIGILL
 -- Variable: SIGINT
 -- Variable: SIGKILL
 -- Variable: SIGPIPE
 -- Variable: SIGQUIT
 -- Variable: SIGSEGV
 -- Variable: SIGSTOP
 -- Variable: SIGTERM
 -- Variable: SIGTSTP
 -- Variable: SIGTTIN
 -- Variable: SIGTTOU
 -- Variable: SIGUSR1
 -- Variable: SIGUSR2
     These variables are bound to the signal numbers of POSIX signals.

 -- Variable: SIGTRAP
 -- Variable: SIGIOT
 -- Variable: SIGBUS
 -- Variable: SIGSTKFLT
 -- Variable: SIGURG
 -- Variable: SIGXCPU
 -- Variable: SIGXFSZ
 -- Variable: SIGVTALRM
 -- Variable: SIGPROF
 -- Variable: SIGWINCH
 -- Variable: SIGPOLL
 -- Variable: SIGIO
 -- Variable: SIGPWR
     These variables are bound to the signal numbers of system-dependent
     signals.  Not all of them may be defined on some systems.

   Besides each signal numbers, you can refer to a set of signals using
a `<sys-sigset>' object.  It can be used to manipulate the signal mask,
and to install a signal handler to a set of signals at once.

 -- Class: <sys-sigset>
     A set of signals.   An empty sigset can be created by
          (make <sys-sigset>)

 -- Function: sys-sigset-add! sigset signal ...
 -- Function: sys-sigset-delete! sigset signal ...
     SIGSET must be a `<sys-sigset>' object.  Those procedures adds and
     removes the specified signals from SIGSET respectively, and
     returns the result.  SIGSET itself is also modified.

     SIGNAL may be either a signal number, another `<sys-sigset>'
     object, or `#t' for all available signals.

 -- Function: sys-sigset-fill! sigset
 -- Function: sys-sigset-empty! sigset
     Fills SIGSET by all available signals, or empties SIGSET.

 -- Function: sys-signal-name signal
     Returns the human-readable name of the signal.


File: gauche-refe.info,  Node: Sending signals,  Next: Handling signals,  Prev: Signals and signal sets,  Up: Signal

6.21.6.2 Sending signals
........................

To send a signal, you can use `sys-kill' which works like `kill(2)'.

 -- Function: sys-kill pid sig
     [POSIX] Sends a signal SIG to the specified process(es).  SIG must
     be a positive exact integer.  PID is an exact integer and
     specifies the target process(es):
        * If PID is positive, it is the target process id.

        * If PID is zero, the signal is sent to every process in the
          process group of the current process.

        * If PID is less than -1, the signal is sent to every process in
          the process group -PID.

   There's no Scheme equivalence for `raise()', but you can use
`(sys-kill (sys-getpid) SIG)'.


File: gauche-refe.info,  Node: Handling signals,  Next: Masking and waiting signals,  Prev: Sending signals,  Up: Signal

6.21.6.3 Handling signals
.........................

You can register signal handling procedures in Scheme.  (In multithread
environment, signal handlers are shared by all threads; see *Note
Signals and threads:: for details).

   When a signal is delivered to the Scheme process, it is queued in VM,
and processed in a 'safe point' where the state of VM is consistent.
(Note that this makes handling of some signals such as `SIGILL'
useless, for the process can't continue sensible execution after
queuing the signal).

   When you're using the `gosh' interpreter, the default behavior for
each signal is as in the following table.

`SIGABRT, SIGILL, SIGKILL, SIGCONT, SIGSTOP, SIGSEGV, SIGBUS'
     Cannot be handled in Scheme.  `Gosh' follows the system's default
     behavior.

`SIGCHLD, SIGTSTP, SIGTTIN, SIGTTOU, SIGWINCH'
     No signal handles are installed for these signals by `gosh',
     so the process follows the system's default behavior.
     Scheme programs can install its own signal handler if necessary.

`SIGHUP, SIGQUIT, SIGTERM'
     `Gosh' installs a signal handler for these signals        that
     exits from the application with code 0.

`SIGPWR, SIGXCPU, SIGUSR1, SIGUSR2'
     On Linux platforms with thread support, these signals are used
       by the system and not available for Scheme.  On other systems,
          these signals behaves the same as described below.

`other signals'
     `Gosh' installs the default signal handler, which signals
     an "unhandled signal" error.  Scheme programs can override it
      by its own signal handler.

   If you're using Gauche embedded in some other application, it may
redefine the default behavior.

   Use the following procedures to get/set signal handlers from Scheme.

 -- Function: set-signal-handler! signals handler
     SIGNALS may be a single signal number or a `<sys-sigset>' object,
     and HANDLER should be either `#t', `#f' or a procedure that takes
     one argument.  If HANDLER is a procedure, it will be called when
     the process receives one of specified signal(s), with the received
     signal number as an argument.  It is safe to do anything in
     HANDLER, including throwing an error or invoking continuation
     captured elsewhere.  (However, continuations captured inside
     HANDLER will be invalid once you return from HANDLER).

     If HANDLER is `#t', the operating system's default behavior is set
     to the specified signal(s).  If HANDLER is `#f', the specified
     signals(s) will be ignored.

     Note that signal handler setting is shared among threads in
     multithread enviornment.  The handler is called from the thread
     which is received the signal.  See *Note Signals and threads:: for
     details.

 -- Function: get-signal-handler signum
     Returns the handler setting of a signal SIGNUM.

 -- Function: get-signal-handlers
     Returns an associative list of all signal handler settings.  Car
     of each element of returned list is a `<sys-sigset>' object, and
     cdr of it is the handler (a procedure or a boolean value) of the
     signals in the set.

 -- Macro: with-signal-handlers (handler-clause ...) thunk
     A convenience macro to install signal handlers temporarily during
     execution of THUNK.  (Note: though this is convenient, this has
     certain dangerous properties described below.  Use with caution.)

     Each HANDLER-CLAUSE may be one of the following forms.
    `(SIGNALS EXPR ...)'
          SIGNALS must be an expression that will yield either a signal,
          a list of signals, or a `<sys-sigset>' object.  Installs a
          signal handler for SIGNALS that evaluates EXPR ... when one
          of the signals in SIGNALS is delivered.

    `(SIGNALS => HANDLER)'
          This form sets the handler of SIGNALS to HANDLER, where
          HANDLER should be either `#t', `#f' or a procedure that takes
          one argument.

          If HANDLER is a procedure, it will be called when the process
          receives one of specified signal(s), with the received signal
          number as an argument.  If HANDLER is `#t', the operating
          system's default behavior is set to the specified signal(s).
          If HANDLER is `#f', the specified signals(s) will be ignored.

     When the control exits from THUNK, the signal handler setting
     before `with-signal-handlers' are recovered.

     _CAVEAT:_ If you're setting more than one signal handlers, they
     are installed in serial.  If a signal is delivered before all the
     handlers are installed, the signal handler state may be left
     inconsistent.  Also note that the handler setting is a global
     state; you can't set "thread local" handler by
     `with-signal-handlers', although the form may be misleading.


File: gauche-refe.info,  Node: Masking and waiting signals,  Next: Signals and threads,  Prev: Handling signals,  Up: Signal

6.21.6.4 Masking and waiting signals
....................................

A Scheme program can set a signal mask, which is a set of signals to be
blocked from delivery.   If a signal is delivered which is completely
blocked in the process, the signal becomes "pending".  The pending
signal may be delivered once the signal mask is changed not to block
the specified signal.  (However, it depends on the operating system
whether the pending signals are queued or not.)

   In multithread environment, each thread has its own signal mask.

 -- Function: sys-sigmask how mask
     Modifies the current thread's signal mask, and returns the previous
     signal mask.   MASK should be a `<sys-sigset>' object.  HOW
     argument should be one of the following integer constants:
    `SIG_SETMASK'
          Sets MASK as the thread's signal mask.

    `SIG_BLOCK'
          Adds signals in MASK to the thread's signal mask.

    `SIG_UNBLOCK'
          Removes signals in MASK from the thread's signal mask.

 -- Function: sys-sigsuspend mask
     Atomically sets thread's signal mask to MASK and suspends the
     calling thread.  When a signal that is not blocked and has a
     signal handler installed is delivered, the associated handler is
     called, then `sys-sigsuspend' returns.


File: gauche-refe.info,  Node: Signals and threads,  Prev: Masking and waiting signals,  Up: Signal

6.21.6.5 Signals and threads
............................

The semantics of signals looks a bit complicated in the multithread
environment.   Nevertheless, it is pretty comprehensible once you
remember a small number of rules.  Besides, Gauche sets up the default
behavior easy to use, while allowing programmers to do tricky stuff.

   If you don't want to be bothered by the details, just remember one
thing, with one sidenote.  *By default*, signals are handled by the
primordial (main) thread.  However, if the main thread is suspended on
mutex or condition variable, the signal may not be handled at all, so
be careful.

   Now, if you are curious about the details, here are the rules:
   * The signal handler setting is shared by all threads.

   * The signal mask is thread-specific.

   * If a process receives an asynchronous signal (think it as a signal
     delivered from other processes), one thread is chosen, out of
     threads which don't block that signal.

   * The signal handler is run on the chosen thread.  However, if the
     chosen thread is waiting for acquiring a mutex lock or a condition
     variable, the handling of signal will be delayed until the thread
     is restarted.   Signal delivery itself doesn't restart the thread.

   Now, these rules have several implications.

   If there are more than one thread that don't block a particular
signal, you can't know which thread receives the signal.  Such a
situation is much less useful in Gauche than C programs because of the
fact that the signal handling can be delayed indefinitely if the
receiver thread is waiting on mutex or condition variable.  So, it is
recommended to make sure, for each signal, there is only one thread
that can receive it.

   In Gauche, all threads created by `make-thread' (*Note Thread
procedures::) blocks all the signals by default (except the reserved
ones).   This lets all the signals to be directed to the primordial
(main) thread.

   Another strategy is to create a thread dedicated for handling
signals.  To do so, you have to block the signals in the primordial
thread, then create the signal-handling thread, and within that thread
you unblock all the signals.  Such a thread can just loop on
`sys-pause'.

     (thread-start!
       (make-thread
         (lambda ()
           (sys-sigmask SIG_SETMASK (make <sys-sigset>)) ;;empty mask
           (let loop () (sys-pause) (loop)))))

   Complicated application may want to control per-thread signal
handling precisely.   You can do so, just make sure that at any moment
only the designated thread unblocks the desired signal.


File: gauche-refe.info,  Node: System Inquiry,  Next: Time,  Prev: Signal,  Up: System interface

6.21.7 System Inquiry
---------------------

 -- Function: sys-uname
     [POSIX] Returns a list of five elements, `(SYSNAME NODENAME
     RELEASE VERSION MACHINE)'.

 -- Function: sys-gethostname
     Returns the host name.  If the system doesn't have gethostname(),
     the second element of the list returned by `sys-uname' is used.

 -- Function: sys-getdomainname
     Returns the domain name.  If the system doesn't have
     getdomainname(), `"localdomain"' is returned.

 -- Function: sys-getcwd
     [POSIX] Returns the current working directory by a string.  If the
     current working directory couldn't be obtained from the system, an
     error is signalled.   See also `sys-chdir'  (*Note Other file
     operations::), `current-directory' (*Note Directory utilities::).

 -- Function: sys-getgid
 -- Function: sys-getegid
     [POSIX] Returns integer value of real and effective group id of the
     current process, respectively.

 -- Function: sys-setgid gid
     [POSIX] Sets the effective group id of the current process.

 -- Function: sys-getuid
 -- Function: sys-geteuid
     [POSIX] Returns integer value of real and effective user id of the
     current process, respectively.

 -- Function: sys-setuid uid
     [POSIX] Sets the effective user id of the current process.

 -- Function: sys-getgroups
     [POSIX] Returns a list of integer ids of supplementary groups.

 -- Function: sys-getlogin
     [POSIX] Returns a string of the name of the user logged in on the
     controlling terminal of the current process.  If the system can't
     determine the information, `#f' is returned.

 -- Function: sys-getpgrp
     [POSIX] Returns a process group id of the current process.

 -- Function: sys-getpgid pid
     Returns a process group id of the process specified by PID.  If
     PID is zero, the current process is used.

     Note that `getpgid()' call is not in POSIX.  If the system doesn't
     have GETPGID(), SYS-GETPGID still works if PID is zero (it just
     calls `sys-getpgrp'), but signals an error if PID is not zero.

 -- Function: sys-setpgid pid pgid
     [POSIX] Sets the process group id of the process PID to PGID.  If
     PID is zero, the process ID of the current process is used.  If
     PGID is zero, the process ID of the process specified by `pid' is
     used.  (Hence `sys-setpgid(0, 0)' sets the process group id of the
     current process to the current process id).

 -- Function: sys-setsid
     [POSIX] Creates a new session if the calling process is not a
     process group leader.

 -- Function: sys-getpid
 -- Function: sys-getppid
     [POSIX] Returns the current process id and the parent process id,
     respectively.

 -- Function: sys-times
     [POSIX]

 -- Function: sys-ctermid
     [POSIX]  Returns the name of the controlling terminal of the
     process.  This may be just a `"/dev/tty"'.   See also
     `sys-ttyname'.


File: gauche-refe.info,  Node: Time,  Next: Unix process management,  Prev: System Inquiry,  Up: System interface

6.21.8 Time
-----------

Gauche has two representations of time, one is compatible to POSIX API,
and the other is compatible to SRFI-18, SRFI-19 and SRFI-21.  Most
procedures accept both representations; if not, the representation the
procedure accepts is indicated as either 'POSIX time' or 'SRFI time'.

   POSIX time is represented by a real number which is a number of
seconds since Unix Epoch (Jan 1, 1970, 0:00:00GMT).  Procedure
`sys-time', which corresponds to POSIX `time(2)', returns this time
representation.

   SRFI-compatible time is represented by an object of `<time>' class,
which keeps seconds and nanoseconds, as well as the type of the time
(UTC, TAI, duration, process time, etc).  `Current-time' returns this
representation.

POSIX time
..........

 -- Function: sys-time
     [POSIX] Returns the current time in POSIX time (the time since
     Epoch (00:00:00 UTC, January 1, 1970), measured in seconds).  It
     may be a non-integral number, depending on the architecture.

     Note that POSIX's definition of "seconds since the Epoch" doesn't
     take leap seconds into acount.

 -- Function: sys-gettimeofday
     Returns two values.  The first value is a number of seconds, and
     the second value is a fraction in a number of microseconds, since
     1970/1/1 0:00:00 UTC.   If the system doesn't have `gettimeofday'
     call, this function calls `time()'; in that case, microseconds
     portion is always zero.

 -- Builtin Class: <sys-tm>
     Represents `struct tm', a calendar date.  It has the following
     slots.

      -- Instance Variable of <sys-tm>: sec
          Seconds. 0-61.

      -- Instance Variable of <sys-tm>: min
          Minutes. 0-59.

      -- Instance Variable of <sys-tm>: hour
          Hours.  0-23.

      -- Instance Variable of <sys-tm>: mday
          Day of the month, counting from 1.  1-31.

      -- Instance Variable of <sys-tm>: mon
          Month, counting from 0.  0-11.

      -- Instance Variable of <sys-tm>: year
          Years since 1900, e.g. 102 for the year 2002.

      -- Instance Variable of <sys-tm>: wday
          Day of the week.  Sunday = 0 .. Saturday = 6.

      -- Instance Variable of <sys-tm>: yday
          Day of the year.  January 1 = 0 .. December 31 = 364 or 365.

      -- Instance Variable of <sys-tm>: isdst
          A flag that indicates if the daylight saving time is in
          effect.  Positive if DST is in effect, zero if not, or
          negative if unknown.

 -- Function: sys-gmtime time
 -- Function: sys-localtime time
     [POSIX] Converts TIME to `<sys-tm>' object, represented in GMT or
     local timezone, respectively.   TIME can be either POSIX-time or
     SRFI-time.

 -- Function: sys-ctime time
     [POSIX] Converts TIME to it string representation, using POSIX
     ctime().  TIME can be either POSIX-time or SRFI-time.

 -- Function: sys-difftime time1 time0
     [POSIX] Returns the difference of two times in the real number of
     seconds.  TIME0 and TIME1 can be either POSIX-time or SRFI-time.

 -- Function: sys-asctime tm
     [POSIX] Converts `<sys-tm>' object TM to a string representation.

 -- Function: sys-strftime format tm
     [POSIX] Converts `<sys-tm>' object TM to a string representation,
     according to a format string FORMAT.

 -- Function: sys-mktime tm
     [POSIX] Converts `<sys-tm>' object TM, expressed as local time, to
     the POSIX-time (number of seconds since Epoch).

 -- Function: sys-tm->alist tm
     (Deprecated function)

SRFI time
.........

 -- Builtin Class: <time>
     The `<time>' object also represents a point of time.

      -- Instance Variable of <time>: type
          Indicates time type.  `time-utc' is the default, and that
          represents the number of seconds since Unix Epoch.  SRFI-19
          (*Note Time data types and procedures::) adds more types.

      -- Instance Variable of <time>: second
          Second part of the time.

      -- Instance Variable of <time>: nanosecond
          Nanosecond part of the time.

 -- Function: current-time
     [SRFI-18][SRFI-21] Returns the `<time>' object representing the
     current time in `time-utc'.   *Note Time data types and
     procedures::, for it redefines `current-time' to allow optional
     argument to specify time type.

 -- Function: time? obj
     [SRFI-18][SRFI-19][SRFI-21] Returns `#t' if OBJ is a time object.

 -- Function: time->seconds time
 -- Function: seconds->time seconds
     [SRFI-18][SRFI-21] Converts between time object and the number of
     seconds (POSIX-time).  TIME argument of `time->seconds' has to be
     a `<time>' object.


File: gauche-refe.info,  Node: Unix process management,  Next: I/O multiplexing,  Prev: Time,  Up: System interface

6.21.9 Unix process management
------------------------------

The following procedures provide pretty raw, direct interface to the
system calls.  See also *Note High Level Process Interface::, which
provides more convenient process handling on top of these primitives.

Fork and exec
.............

 -- Function: sys-system command
     [POSIX] Runs COMMAND in a subprocess.   COMMAND is usually passed
     to `sh', so the shell metacharacters are interpreted.

     This function returns an integer value `system()' returned.  Since
     POSIX doesn't define what `system()' returns, you can't interpret
     the returned value in a portable way.

 -- Function: sys-fork
     [POSIX] Fork the current process.  Returns 0 if you're in the
     child process, and a child process' pid if you're in the parent
     process.  All the opened file descriptors are shared between the
     parent and the child.  See `fork(2)' of your system for details.

     If the child process runs some Scheme code and exits instead of
     calling `sys-exec', it should call `sys-exit' instead of `exit' to
     terminate itself.  Normal exit call tries to flush the file
     buffers, and on some OS it messes up the parent's file buffers.

     It should be noted that `sys-fork' is not safe when multiple
     threads are running.  Because `fork(2)' copies the process' memory
     image which includes any mutex state, a mutex which is locked by
     another thread at the time of `sys-fork' remains locked in the
     child process, nevertheless the child process doesn't have the
     thread that unlock it!  (This applies to the internal mutexes as
     well, so even you don't use Scheme multex explicitly, this
     situation can always happen.)

     If what you want is to spawn another program in a multi-threaded
     application, use `sys-fork-and-exec' explained below.  If you
     absolutely need to run Scheme code in the child process, a typical
     technique is that you fork a manager process at the beginning of
     application, and whenever you need a new process you ask the
     manager process to fork one for you.

 -- Function: sys-exec command args &optional iomap
     [POSIX+] Execute COMMAND with ARGS, a list of arguments.  The
     current process image is replaced by COMMAND, so this function
     never returns.

     All elements of ARGS must be strings.  The first element of ARGS
     is used as `argv[0]', i.e. the program name.

     The optional IOMAP argument, when provided, specifies how the open
     file descriptors are treated.  It must be the following format:
          ((to-fd . from-port-or-fd) ...)
     To-fd must be an integer, and from-port-or-fd must be an integer
     file descriptor or a port.  Each element of the list makes the
     file descriptor of from-port-or-fd of the current process be
     mapped to the file descriptr to-fd in the executed process.

     If IOMAP is provided, any file descriptors other than specified in
     the iomap list will be closed before `exec()'.  Otherwise, all
     file descriptors in the current process remain open.

          (sys-exec "ls" '("ls" "-l")) => ;; ls is executed.

          (let ((out (open-output-file "ls.out")))
            (sys-exec "ls" '("ls" "-l") `((2 . 1) (1 . ,out)))
             =>
            ;; ls is executed, with its stderr redirected
            ;; to the current process's stdout, and its
            ;; stdout redirected to the file "ls.out".

     When it encounters an error, most of the time it raises an error
     condition.  Once the file descriptors are permuted, however, it
     would be impractical to handle errors in reasonable way (you don't
     even know stderr is still available!), so Gauche simply exits on
     the error.

 -- Function: sys-fork-and-exec command args &optional iomap
     Like `sys-exec', but executes `fork(2)' just before remapping I/O
     and `execvp(2)'.  Returns child's process id.

     It is strongly recommended to use this procedure instead of
     `sys-fork' and `sys-exec' combination when you need to spawn
     another program while other threads are running.  No memory
     allocation nor lock acquisition is done between `fork(2)' and
     `execvp(2)', so it's pretty safe in the multithreaded environment.

Wait
....

 -- Function: sys-wait
     [POSIX] Calls system's `wait(2)'.  The process suspends its
     execution until one of the child terminates.  Returns two exact
     integer values, the first one is the child's process id, and the
     second is a status code.  The status code can be interpreted by
     the following functions.

 -- Function: sys-waitpid pid &keyword nohang untraced
     [POSIX] This is an interface to `waitpid(3)', an extended version
     of wait.

     PID is an exact integer specifying which child(ren) it's waiting.
     If it is a positive integer, it waits fot that specific child.  If
     it is zero, it waits for any member of this process group.  If it
     is -1, it waits for any child process.  If it is less than -1, it
     waits for any child process whose process group id is equal to the
     absolute value of PID.

     The calling process suspends until one of those child process is
     terminated, unless true is specified to the keyword argument
     NOHANG.

     If true is specified to the keyword argument UNTRACED, the status
     of stopped child process can be also returned.

     The return values are two exact integers, the first one is the
     child process id, and the second is a status code.  If NOHANG is
     true and no child process status is available, the first value is
     zero.

 -- Function: sys-wait-exited? status
 -- Function: sys-wait-exit-status status
     [POSIX] The argument is an exit status returned as a second value
     from `sys-wait' or `sys-waitpid'.  `sys-wait-exited?' returns `#t'
     if the child process is terminated normally.
     `sys-wait-exit-status' returns the exit code the child process
     passed to `exit(2)', or the return value of `main()'.

 -- Function: sys-wait-signaled? status
 -- Function: sys-wait-termsig status
     [POSIX] The argument is an exit status returned as a second value
     from `sys-wait' or `sys-waitpid'.  `sys-wait-signaled?' returns
     `#t' if the child process is termintaed by an uncaught signal.
     `sys-wait-termsig' returns the signal number that terminted the
     child.

 -- Function: sys-wait-stopped? status
 -- Function: sys-wait-stopsig status
     [POSIX] The argument is an exit status returned as a second value
     from `sys-waitpid'.  `sys-wait-stopped?' returns `#t' if the child
     process is stopped.   This status can be caught only by
     `sys-waitpid' with true UNTRACED argument.  `sys-wait-stopsig'
     returns the signum number that stopped the child.


File: gauche-refe.info,  Node: I/O multiplexing,  Next: Miscellaneous system calls,  Prev: Unix process management,  Up: System interface

6.21.10 I/O multiplexing
------------------------

The interface functions for `select(2)'.  The higher level interface is
provided on top of these primitives; see *Note Simple dispatcher::.

 -- Builtin Class: <sys-fdset>
     Represents `fd_set', a set of file descriptors.  You can make an
     empty file descriptor set by make method:
          (make <sys-fdset>)

 -- Function: sys-fdset-ref fdset port-or-fd
 -- Function: sys-fdset-set! fdset port-or-fd flag
     Gets and sets specific file descritor bit of FDSET.  PORT-OR-FD
     may be a port or an integer file descriptor.  If PORT-OR-FD is a
     port that doesn't have associated file descriptor, `sys-fdset-ref'
     returns `#f', and `sys-fdset-set!' doesn't modify FDSET.  FLAG
     must be a boolean value.

     You can use generic setter of `sys-fdset-ref' as this:
          (set! (sys-fdset-ref fdset port-or-fd) flag)
            == (sys-fdset-set! fdset port-or-fd flag)

 -- Function: sys-fdset-max-fd fdset
     Returns the maximum file descriptor number in FDSET.

 -- Function: sys-select readfds writefds exceptfds &optional timeout
 -- Function: sys-select! readfds writefds exceptfds &optional timeout
     Waits for a set of file descriptors to change status.  READFDS,
     WRITEFDS, and EXCEPTFDS are `<fdset>' objects to represent a set
     of file descriptors to watch.  File descriptors in READFDS are
     watched to see if characters are ready to be read.   File
     descriptors in WRITEFDS are watched if writing to them is ok.
     File descriptors in EXCEPTFDS are watched for exceptions.  You can
     pass `#f' to one or more of those arguments if you don't care
     about watching the condition.

     TIMEOUT specifies maximum time `sys-select' waits for the
     condition change.  It can be a real number, for number of
     microseconds, or a list of two integers, the first is the number
     of seconds and the second is the number of microseconds.  If you
     pass `#f', `sys-select' waits indefinitely.

     `sys-select' returns four values.  The first value is a number of
     descriptors it detected status change.  It may be zero if timeout
     expired.  The second, third and fourth values are `<fdset>' object
     that contains a set of descriptors that changed status for
     reading, writing, and exception, respectively.  If you passed `#f'
     to one or more of READFDS, WRITEFDS and EXCEPTFDS, the
     corresponding return value is `#f'.

     `sys-select!' variant works the same as `sys-select', except it
     modifies the passed `<fdset>' arguments.  `sys-select' creates new
     `<fdset>' objects and doesn't modify its arguments.


File: gauche-refe.info,  Node: Miscellaneous system calls,  Prev: I/O multiplexing,  Up: System interface

6.21.11 Miscellaneous system calls
----------------------------------

 -- Function: sys-pause
     [POSIX] Suspends the process until it receives a signal whose
     action is to either execute a signal-catching function or to
     terminate the process.  This function only returns when the
     signal-catching function returns.  The returned value is undefined.

     Note that just calling `pause()' doesn't suffice the above
     semantics in Scheme-level.  Internally this procedure calls
     `sigsuspend()' with the current signal mask.

 -- Function: sys-alarm seconds
     [POSIX] Arranges a SIGALRM signal to be delivered after SECONDS.
     The previous settings of the alarm clock is cancelled.  Passing
     zero to SECONDS doesn't schedule new alarm.  Returns the number of
     seconds remaining until previously scheduled alarm was due to be
     delivered (or zero if no alarm is active).

 -- Function: sys-sleep seconds
     [POSIX] Suspends the process until the specified number of seconds
     elapses, or the process receives a signal.  Returns zero if it
     sleeps well, or the number of unslept seconds if it is woke up by
     a signal.

     To be portable across POSIX implementation, keep SECONDS less than
     65536.

 -- Function: sys-nanosleep nanoseconds
     [POSIX] Suspends the process until the specified number of
     nanoseconds elapses, or the process receives a signal.  The
     argument NANOSECONDS can be a `<time>' object (*Note Time::), or a
     real number.  Returns `#f' if NANOSECONDS elapsed, or a `<time>'
     object that indicates the remaining time if `sys-nanosleep' is
     interrupted by a signal.

          ;wait for 0.5 sec
          (sys-nanosleep 500000000)

          ;wait for 1.3 sec
          (sys-nanosleep (make <time> :second 1 :nanosecond 300000000)

 -- Function: sys-random
 -- Function: sys-srandom seed
     A pseudo random number generator.  `sys-random' returns a random
     number between 0 and a positive integer RAND_MAX, inclusive.  This
     is a straightforward interface to `random(3)'.  If the underlying
     system doesn't have `random(3)', `lrand48(3)' is used.

     `sys-srandom' sets the seed of the random number generator.  It
     uses either `srandom(3)' or `srand48(3)', depending on the system.

     The intention of these functions are to provide an off-the-stock
     handy random number generator (RNG) for applications that doens't
     sensitive to the quality and/or speed of RNG.  For serious
     statistics analysis, use Mersenne Twister RNG in `math.mt-random'
     module (*Note Mersenne-Twister random number generator::).

 -- Variable: RAND_MAX
     Bound to a positive integer that `sys-random' may return.


File: gauche-refe.info,  Node: Development helper API,  Prev: System interface,  Up: Core library

6.22 Development helper API
===========================

Gauche has some basic built-in APIs to help developers to analyze the
program.

* Menu:

* Debugging aid::
* Profiler API::


File: gauche-refe.info,  Node: Debugging aid,  Next: Profiler API,  Prev: Development helper API,  Up: Development helper API

6.22.1 Debugging aid
--------------------

 -- Macro: debug-print expr
     This macro prints EXPR in a source form, then evaluates it, then
     prints out the result(s), and returns them.

     The special reader syntax `#?=EXPR' is expanded into `(debug-print
     EXPR)'.  See *Note Debugging::, for the details.

 -- Function: disasm closure
     Disassemble the compiled body of CLOSURE and print it.  It may not
     be very useful unless you're tracking a compiler bug, or trying to
     tune the program to its limit.

     If you're reading the disassembler output, keep in mind that the
     compiled code vector may have some dead code; they are produced by
     the jump optimization, but the compiler doesn't bother to eliminate
     them.


File: gauche-refe.info,  Node: Profiler API,  Prev: Debugging aid,  Up: Development helper API

6.22.2 Profiler API
-------------------

These are the functions to control Gauche's built-in profiler.  See
*Note Using profiler:: for the explanation of the profiler.

   Note that the profiler doesn't work correctly yet in multi-threaded
program.

 -- Function: profiler-start
     Starts the sampling profiler.   If the profiler is already started,
     nothing is done.

 -- Function: profiler-stop
     Stop the sampling profiler, and save the sampled data into the
     internal structure.   If there are already saved sampled data, the
     newly obtained data is added to it.  If the profiler isn't
     running, nothing is done.

 -- Function: profiler-reset
     Stop the profiler if it is running.  Then discard the saved
     sampled data.

 -- Function: profiler-show &keyword sort-by max-rows
     Show the saved sampled data.

     The keyword argument SORT-BY may be one of the symbols `time',
     `count', or `time-per-call', to specify how the result should be
     sorted.  The default is `time'.

     The keyword argument MAX-ROWS specifies the max number of rows to
     be shown.  If it is `#f', all the data is shown.


File: gauche-refe.info,  Node: Object system,  Next: Library modules - Overview,  Prev: Core library,  Up: Top

7 Object system
***************

Gauche's object system design is largely inspired by STklos, whose
design has come from TinyCLOS.  It supports multiple inheritance,
multimethods, and metaobject protocol.

   The type system is integrated to the object system, that is, a
string is an instance of the class `<string>', and so on.

* Menu:

* Introduction to the object system::
* General Inquiry::
* Class::
* Instance::
* Generic function and method::
* Metaobject protocol::


File: gauche-refe.info,  Node: Introduction to the object system,  Next: General Inquiry,  Prev: Object system,  Up: Object system

7.1 Introduction to the object system
=====================================

This section briefly explains the basic structure of Gauche's object
system.   It is strongly influenced by CLOS (Common-Lisp Object System).
If you have experience in CLOS or related systems such as TinyCLOS,
STklos or Guile's object system, you may skip to the next section.

   Three concepts play the central role in CLOS-like object systems: A
_class_, a _generic function_, and a _method_.

   A _class_ specifies a structure of object.  It also defines a
datatype (strictly speaking, it's not the same thing as a datatype, but
let's skip the complicated part for now).

   For example, a point in 2D space can be represented by x and y
coordinates.  A point class can be defined using `define-class' macro.
In the shortest form, it can be defined like this:

     (define-class <2d-point> () (x y))

   (You can find the code of definitions in the examples of this section
in `examples/oointro.scm' of Gauche's source distribution.)

   The symbol `<2d-point>' is the name of the class, and also the
global variable `<2d-point>' is bound to a class object.  Surrounding a
class name by `<' and `>' is just a convention; you can pass any symbol
to `define-class'.

   The second argument of `define-class' is a list of direct
superclasses, which specifies inheritance of the class.  We'll come
back to it later.

   The third argument of `define-class' is a list of _slots_.  A slot
is a storage space, usually in each object, where you can store a
value.  It is something similar to what is called a field or an
instance variable in other object-oriented languages; but slots can be
configured more than just a per-object storage space.

   Now we defined a 2D point class, so we can create an instance of a
point.  You can pass a class to a generic function `make' to create an
instance.  (Don't worry about what generic function is--think it as a
special type of function, just for now).

     (define a-point (make <2d-point>))

     a-point  => #<<2d-point> 0x8117570>

   If you are using `gosh' interactively, you can use a generic
function `describe' to inspect the internal of an instance.  A short
alias, `d', is defined to `describe' for the convenience.  (See *Note
Interactive session:: for the details).

     gosh> (d a-point)
     #<<2d-point> 0x8117570> is an instance of class <2d-point>
     slots:
       x         : #<unbound>
       y         : #<unbound>

   In order to access or modify the value of the slot, you can use
`slot-ref' and `slot-set!', respectively.  These names are taken from
STklos.

     (slot-ref a-point 'x)  ;; access to the slot x of a-point
       => error, since slot 'x doesn't have a value yet

     (slot-set! a-point 'x 10.0)  ;; set 10.0 to the slot x of a-point

     (slot-ref a-point 'x)
       => 10.0

   Gauche also provides a shorter name, `ref', which can also be used
in srfi-17's generalized `set!' syntax:
     (ref a-point 'x) => 10.0

     (set! (ref a-point 'y) 20.0)

     (ref a-point 'y) => 20.0

   Now you can see slot values are set.
     gosh> (d a-point)
     #<<2d-point> 0x8117570> is an instance of class <2d-point>
     slots:
       x         : 10.0
       y         : 20.0

   In practice, it is usually convenient if you can specify the default
value for a slot, or give values for slots when you create an instance.
Such information can be specified by _slot options_.  Let's modify the
definition of `<2d-point>' like this:

     (define-class <2d-point> ()
       ((x :init-value 0.0 :init-keyword :x :accessor x-of)
        (y :init-value 0.0 :init-keyword :y :accessor y-of)))

   Note that each slot specification is now a list, instead of just a
symbol as in the previous example.  The list's car now specifies the
slot name, and its cdr gives various information.   The value after
`:init-value' defines the default value of the slot.  The keyword after
`:init-keyword' defines the keyword argument which can be passed to
`make' to initialize the slot at creation time.  The name after keyword
`:accessor' is bound to a generic function that can be used to
access/modify the slot, instead of using `slot-ref'/`slot-set!'.

   Let's see some interactive session.  You create an instance of the
new `<2d-point>' class, and you can see the slots are initialized by
the default values.
     gosh> (define a-point (make <2d-point>))
     a-point
     gosh> (d a-point)
     #<<2d-point> 0x8148680> is an instance of class <2d-point>
     slots:
       x         : 0.0
       y         : 0.0

   You create another instance, this time giving initialization values
by keyword arguments.
     gosh> (define b-point (make <2d-point> :x 50.0 :y -10.0))
     b-point
     gosh> (d b-point)
     #<<2d-point> 0x8155b80> is an instance of class <2d-point>
     slots:
       x         : 50.0
       y         : -10.0

   Accessors are less verbose than `slot-ref'/`slot-set!', thus
convenient.
     gosh> (x-of a-point)
     0.0
     gosh> (x-of b-point)
     50.0
     gosh> (set! (y-of a-point) 3.33)
     #<undef>
     gosh> (y-of a-point)
     3.33

   The full list of available slot options is described in *Note
Defining class::.  At a first grance, the declarations of such slot
options may look verbose.  The system might have provide a static way
to define init-keywords or accessor names automatically; however,
CLOS-like systems prefer flexibility.  Using a mechanism called
metaobject protocol, you can customize how these slot options are
interpreted, and you can add your own slot options as well.  See *Note
Metaobject protocol::, for details.

   We can also have `<2d-vector>' class in similar fashion.

     (define-class <2d-vector> ()
       ((x :init-value 0.0 :init-keyword :x :accessor x-of)
        (y :init-value 0.0 :init-keyword :y :accessor y-of)))

   Yes, we can use the same accessor name like `x-of', and it is
effectively overloaded.

   If you are familiar with mainstream object-oriented languages, you
may wonder where methods are.  Here they are.  The following form
defines a method `move-by!' of three arguments, PT, DX, DY, where PT is
an instance of `<2d-point>'.

     (define-method move-by! ((pt <2d-point>) dx dy)
       (inc! (x-of pt) dx)
       (inc! (y-of pt) dy))

   The second argument of `define-method' macro specifies a _method
specializer list_.  It indicates the first argument must be an instance
of `<2d-point>', and the second and third can be any type.   The syntax
to call a method is just like the one to call an ordinary function.

     gosh> (move-by! b-point 1.4 2.5)
     #<undef>
     gosh> (d b-point)
     #<<2d-point> 0x8155b80> is an instance of class <2d-point>
     slots:
       x         : 51.4
       y         : -7.5

   You can overload the method by different specializers; here you can
move a point using a vector.
     (define-method move-by! ((pt <2d-point>) (delta <2d-vector>))
       (move-by! pt (x-of delta) (y-of delta)))

   Specialization isn't limited to a user-defined classes.  You can
also specialize a method using Gauche's built-in type.
     (define-method move-by! ((pt <2d-point>) (c <complex>))
       (move-by! pt (real-part c) (imag-part c)))

   And here's the example session:
     gosh> (define d-vector (make <2d-vector> :x -9.0 :y 7.25))
     d-vector
     gosh> (move-by! b-point d-vector)
     #<undef>
     gosh> (d b-point)
     #<<2d-point> 0x8155b80> is an instance of class <2d-point>
     slots:
       x         : 42.4
       y         : -0.25
     gosh> (move-by! b-point 3+2i)
     #<undef>
     gosh> (d b-point)
     #<<2d-point> 0x8155b80> is an instance of class <2d-point>
     slots:
       x         : 45.4
       y         : -2.25

   You see that a method is dispached not only by its primary receiver
(`<2d-point>'), but also other arguments.  In fact, the first argument
is no more special than the rest.  In CLOS-like system a method does
not belong to a particular class.

   So what is actually a method?  Inspecting `move-by!' reveals that it
is an instance of `<generic>', a generic function.  (Note that
`describe' truncates the printed value in `methods' slot for the sake
of readability).
     gosh> move-by!
     #<generic move-by! (3)>
     gosh> (d move-by!)
     #<generic move-by! (3)> is an instance of class <generic>
     slots:
       name      : move-by!
       methods   : (#<method (move-by! <2d-point> <complex>)> #<method (move-
     gosh> (ref move-by! 'methods)
     (#<method (move-by! <2d-point> <complex>)>
      #<method (move-by! <2d-point> <2d-vector>)>
      #<method (move-by! <2d-point> <top> <top>)>)

   I said a generic function is a special type of function.  It is
recognized by Gauche as an applicable object, but when applied, it
selects appropriate method(s) according to its arguments and calls the
selected method(s).

   What the `define-method' macro actually does is (1) to create a
generic function of the given name if it does not exist yet, (2) to
create a method object with the given specializers and the body, and
(3) to add the method object to the generic function.

   The accessors are also generic functions, created implicitly by the
`define-class' macro.
     gosh> (d x-of)
     #<generic x-of (2)> is an instance of class <generic>
     slots:
       name      : x-of
       methods   : (#<method (x-of <2d-vector>)> #<method (x-of <2d-point>)>)

   In the mainstream dynamic object-oriented languages, a class has
many roles; it defines a structure and a type, creates a namespace for
its slots and methods, and is responsible for method dispatch.  In
Gauche, namespace is managed by modules, and method dispatch is handled
by generic functions.

   The default printed representation of object is not very
user-friendly.  Gauche's `write' and `display' function call a generic
function `write-object' when they encounter an instance they don't know
how to print.  You can define its method specialized to your class to
customize how the instance is printed.
     (define-method write-object ((pt <2d-point>) port)
       (format port "[[~a, ~a]]" (x-of pt) (y-of pt)))

     (define-method write-object ((vec <2d-vector>) port)
       (format port "<<~a, ~a>>" (x-of vec) (y-of vec)))

   And what you'll get is:
     gosh> a-point
     [[0.0, 3.33]]
     gosh> d-vector
     <<-9.0, 7.25>>

   If you customize the printed representation to conform srfi-10
format, and define a corresponding read-time constructor, you can make
your instances to be written-out and read-back just like built-in
objects.  See *Note Read-time constructor:: for the details.

   Several built-in functions have similar way to extend their
functionality for user-defined objects.  For example, if you specialize
a generic function `object-equal?', you can compare the instances by
`equal?':
     (define-method object-equal? ((a <2d-point>) (b <2d-point>))
       (and (equal? (x-of a) (x-of b))
            (equal? (y-of a) (y-of b))))

     (equal? (make <2d-point> :x 1 :y 2) (make <2d-point> :x 1 :y 2))
       => #t

     (equal? (make <2d-point> :x 1 :y 2) (make <2d-point> :x 2 :y 1))
       => #f

     (equal? (make <2d-point> :x 1 :y 2) 'a)
       => #f

     (equal? (list (make <2d-point> :x 1 :y 2)
                   (make <2d-point> :x 3 :y 4))
             (list (make <2d-point> :x 1 :y 2)
                   (make <2d-point> :x 3 :y 4)))
       => #t

   Let's proceed to more interesting examples.  Think of a class
`<shape>', which is an entity that can be drawn.  As a base class, it
keeps common attributes such as a color and line thickness in its slots.
     (define-class <shape> ()
       ((color     :init-value '(0 0 0) :init-keyword :color)
        (thickness :init-value 2 init-keyword :thickness)))

   When an instance is created, `make' calls a generic function
`initialize', which takes care of initializing slots such as processing
init-keywords and init-values.  You can customize the initialization
behavior by specializing the `initialize' method.   The `initialize'
method is called with two arguments, one is a newly created instance,
and another is a list of arguments passed to `make'.

   We define a `initialize' method for `<shape>' class, so that the
created shape will be automatically recorded in a global list.   Note
that we don't want to replace system's `initialize' behavior completely,
since we still need the init-keywords to be handled.

     (define *shapes* '())  ;; global shape list

     (define-method initialize ((self <shape>) initargs)
       (next-method)  ;; let the system to handle slot initialization
       (push! *shapes* self)) ;; record myself to the global list
   The trick is a special method, `next-method'.  It can only be used
inside a method body, and calls _less specific method_ of the same
generic function--typically, it means you call the same method of
superclass.  Most object-oriented languages have the concept of calling
superclass's method.  Because of multiple-argument dispatching and
multiple inheritance, `next-method' is a little bit more complicated,
but the basic idea is the same.

   So, what's the superclass of `<shape>'?  In fact, all Scheme-defined
class inherits a class called `<object>'.  And it is `<object>''s
initialize method which takes care of slot initialization.  After
calling `next-method' within your `initialize' method, you can assume
all the slots are properly initialized.  So it is generally the first
thing in your `initialize' method to call `next-method'.

   Let's inspect the above code.  When you call `(make <shape> args
...)', the system allocates memory for an instance of `<shape>', and
calls `initialize' generic funciton with the instance and `args ...'.
It is dispatched to the `initialize' method you just defined.  In it,
you call `next-method', which in turn calls `<object>' class's
`initialize' method.  It initializes the instance with init-values and
init-keywords.  After it returns, you register the new `<shape>'
instance to the global shape list `*shapes*'.

   The `<shape>' class represents just an abstract concept of shape.
Now we define some concrete drawable shapes, by _subclassing_ the
`<shape>' class.
     (define-class <point-shape> (<shape>)
       ((point  :init-form (make <2d-point>) :init-keyword :point)))

     (define-class <polyline-shape> (<shape>)
       ((points :init-value '() :init-keyword :points)
        (closed :init-value #f  :init-keyword :closed)))

   Note the second argument passed to `define-class'.  It indicates
that `<point-shape>' and `<polyline-shape>' inherit slots of `<shape>'
class, and also instances of those subclasses can be accepted wherever
an instance of `<shape>' class is accepted.

   The `<point-shape>' adds one slot, `point', which contains an
instance of `<2d-point>' defined in the beginning of this section.  The
`<polyline-shape>' class stores a list of points, and a flag, which
specifies whether the end point of the polyline is connected to its
starting point or not.

   Inheritance is a powerful mechanism that should be used with care,
or it easily result a code which is untractable ("Object-oriented
programming offers a sustainable way to write spaghetti code.", as Paul
Graham says in his article "The Hundred-Year Language").  The rule of
thumb is to make a subclass when you need a subtype.  The inheritance
of slots is just something that comes with, but it shouldn't be the
main reason to do subclassing.  You can always "include" the
substructure, as is done in `<point-shape>' class.

   There appeared a new slot option in `<point-shape>' class.  The
`:init-form' slot option specifies the default value of the slot when
init-keyword is not given to `make' method.  However, unlike
`:init-value', with which the value is evaluated at the time the class
is defined, the value with `:init-form' is evaluated when the system
actually needs the value.  So, in the `<point-shape>' instance, the
default `<2d-point>' instance is only created if the `<point-shape>'
instance is created without having `:point' init-keyword argument.

   A shape may be drawn in different formats for different devices.
For now, we just consider a PostScript output.  To make the `draw'
method polymorphic, we define a postscript output device class,
`<ps-device>'.

     (define-class <ps-device> () ())

   Then we can write a `draw' method, specialized for both `<shape>'
and `<ps-device>'.
     (define-method draw ((self <shape>) (device <ps-device>))
       (format #t "gsave\n")
       (draw-path self device)
       (apply format #t "~a ~a ~a setrgbcolor\n" (ref self 'color))
       (format #t "~a setlinewidth\n" (ref self 'thickness))
       (format #t "stroke\n")
       (format #t "grestore\n"))

   In this code, the DEVICE argument isn't used within the method body.
It is just used for method dispatching.  If we eventually have
different output devices, we can add a `draw' method that is
specialized for such devices.

   The above `draw' method does the common work, but actual drawing
must be done in specialized way for each subclasses.
     (define-method draw-path ((self <point-shape>) (device <ps-device>))
       (apply format #t "newpath ~a ~a 1 0 360 arc closepath\n"
              (point->list (ref self 'point))))

     (define-method draw-path ((self <polyline-shape>) (device <ps-device>))
       (let ((pts (ref self 'points)))
         (when (>= (length pts) 2)
           (format #t "newpath\n")
           (apply format #t "~a ~a moveto\n" (point->list (car pts)))
           (for-each (lambda (pt)
                       (apply format #t "~a ~a lineto\n" (point->list pt)))
                     (cdr pts))
           (when (ref self 'closed)
             (apply format #t "~a ~a lineto\n" (point->list (car pts))))
           (format #t "closepath\n"))))

     ;; utility method
     (define-method point->list ((pt <2d-point>))
       (list (x-of pt) (y-of pt)))

   Finally, we do a little hack.  Let `draw' method work on the list of
shapes, so that we can draw multiple shapes within a page in batch.
     (define-method draw ((shapes <list>) (device <ps-device>))
       (format #t "%%\n")
       (for-each (cut draw <> device) shapes)
       (format #t "showpage\n"))

   Then we can write some simple figures ....
     (use srfi-1)      ;; for iota
     (use math.const)  ;; for constant pi

     (define (shape-sample)

       ;; creates 5 corner points of pentagon
       (define (make-corners scale)
         (map (lambda (i)
                (let ((pt (make <2d-point>)))
                  (move-by! pt (make-polar scale (* i 2/5 pi)))
                  (move-by! pt 200 200)
                  pt))
              (iota 5)))

       (set! *shapes* '())  ;; clear the shape list
       (let* ((corners (make-corners 100)))
         ;; a pentagon in green
         (make <polyline-shape>
           :color '(0 1 0) :closed #t
           :points corners)
         ;; a star-shape in red
         (make <polyline-shape>
           :color '(1 0 0) :closed #t
           :points (list (list-ref corners 0)
                         (list-ref corners 2)
                         (list-ref corners 4)
                         (list-ref corners 1)
                         (list-ref corners 3)))
         ;; put dots in each corner of the star
         (for-each (cut make <point-shape> :point <>)
                   (make-corners 90))
         ;; draw the shapes
         (draw *shapes* (make <ps-device>)))
       )

   The function `shape-sample' writes out a PostScript code of simple
drawing to the current output port.  You can write it out to file by
the following expression, and then view the result by PostScript viewer
such as GhostScript.
     (with-output-to-file "oointro.ps" shape-sampe)


File: gauche-refe.info,  Node: General Inquiry,  Next: Class,  Prev: Introduction to the object system,  Up: Object system

7.2 General Inquiry
===================

 -- Function: class-of obj
     Returns a class metaobject of OBJ.

          (class-of 3)         => #<class <integer>>
          (class-of "foo")     => #<class <string>>
          (class-of <integer>) => #<class <class>>

 -- Function: is-a? obj class
     Returns true if OBJ is an instance of CLASS or an instance of
     descendants of CLASS.

          (is-a? 3 <integer>)   => #t
          (is-a? 3 <real>)      => #t
          (is-a? 5+3i <real>)   => #f
          (is-a? :foo <symbol>) => #f

If OBJ's class has been redefined, these procedures first updates OBJ
to change its class to the new class.  So `class-of' always returns the
new class.  This behavior is different from stklos 0.55, which
`class-of' returns an old class if OBJ hasn't been updated.  If you
need to get the old class, you should use `current-class-of' below.
See *Note Class redefinition:: for the details of the semantics of
redefined class.

 -- Function: current-class-of obj
     Returns a class metaobject of OBJ.  If OBJ's class has been
     redefined, but OBJ is not updated for the change, then this
     procedure returns the original class of OBJ without updating OBJ.

     You need this procedure in rare occasions, such as within
     `change-class' method, in which you don't want to trigger updating
     OBJ (which would cause infinite loop).


File: gauche-refe.info,  Node: Class,  Next: Instance,  Prev: General Inquiry,  Up: Object system

7.3 Class
=========

In this section, a class in Gauche is explained in detail.

* Menu:

* Defining class::
* Inheritance::
* Class object::
* Slot definition object::
* Class redefinition::
* Class definition examples::


File: gauche-refe.info,  Node: Defining class,  Next: Inheritance,  Prev: Class,  Up: Class

7.3.1 Defining class
--------------------

To define a class, use a macro `define-class'.

 -- Macro: define-class name supers (slot-spec ...) option ...
     Creates a class object according to the arguments, and globally
     bind it to a variable NAME.   This macro should be used at
     toplevel.

     SUPERS is a list of direct superclasses from which this class
     inherits.   You can use multiple inheritance.  All Scheme-defined
     classes implicitly inherits `<object>'.  It is implicitly added to
     the right of SUPERS list, so you don't need to specify it.  See
     *Note Inheritance::, for the details abount inheritance.

     SLOT-SPEC is a specification of a "slot", sometimes known as a
     "field" or an "instance variable" (but you can specify "class
     variable" in SLOT-SPEC as well).  The simplest form of SLOT-SPEC
     is just a symbol, which names the slot.  Or you can give a list,
     whose first element is a symbol and whose rest is an interleaved
     list of keywords and values.  The list form not only defines a
     name of the slot but specifies behavior of the slot.  It is
     explained below.

     Finally, OPTION ... is an interleaved list of keywords and values,
     specifies how class object should be created.  This macro
     recognizes one keyword, `:metaclass', whose corresponding value is
     used for metaclass (class that instantiates another class).
     Other options are passed to the `make' method to create the class
     object.  *Note Class instantiation::, for the usage of metaclass.

   If a slot specification is a list, it should be in the following
form:

     (SLOT-NAME :option1 value1 :option2 value2 ...)

   Each keyword (`option1' etc.) gives a _slot option_.  By default,
the following slot options are recognized.  You can add more slot
options by defining metaclass.

`:allocation'
     Specifies an allocation type of this slot, which specifies how the
     value for this slot is stored.  The following keyword values are
     recognized by the standard class.  A programmer can define his own
     metaclass to extend the class to recognize other allocation types.
    `:instance'
          A slot is allocated for each instance, so that every instance
          can have distinct value.  This realizes so-called "instance
          variable" behavior.  If `:allocation' slot option is omitted,
          this is the default.

    `:class'
          A slot is allocated in this class object, so that every
          instance will share the same value for this slot.  This
          realizes so-called "class variable" behavior.  The slot value
          is also shared by all subclasses (unless a subclass
          definition shadows the slot).

    `:each-subclass'
          Similar to `class' allocation, but a slot is allocated for
          each class; that is, it is shared by every instance of the
          class, but not shared by the instances of its subclasses.

    `:virtual'
          No storage is allocated for this type of slot.  Accessing the
          slot calls procedures given in `:slot-ref' and `:slot-set!'
          options described below.  In other words, you can make a
          procedural slot.  If a slot's allocation is specified as
          virtual, at least `:slot-ref' option has to be specified as
          well, or `define-class' raises an error.

    `:builtin'
          This type of allocation only appears in built-in classes, and
          you can't specify it in Scheme-defined class.

`:init-keyword'
     A keyword value given to this slot option can be used to pass an
     initial value to `make' method when an instance is created.

`:init-value'
     Gives an initial value of the slot, if the slot is not initialized
     by the keyword argument at the creation time.   The value is
     evaluated when `define-class' is evaluated.

`:init-form'
     Like `init-value', but the value given is wrapped in a thunk, and
     evaluated each time when the value is required.  If both
     `init-value' and `init-form' are given, `init-form' is ignored.
     Actually, `:init-form EXPR' is converted to `:init-thunk (lambda
     () EXPR)' by `define-class' macro.

`:initform'
     A synonym of `init-form'.  This is kept for compatibility to STk,
     and shouldn't be used in the new code.

`:init-thunk'
     Gives a thunk, which will be evaluated to obtain an initial value
     of the slot, if the slot is not initialized by the keyword argument
     at the creation time.  To give a value to `:init-form' is
     equivalent to give `(lambda () value)' to `:init-thunk'.

`:getter'
     Takes a symbol, and a getter method is created and bound to the
     generic function of that name.  The getter method takes an instance
     of the class and returns the value of the slot.

`:setter'
     Takes a symbol, and a setter method is created and bound to the
     generic function of that name.  The setter method takes an instance
     of the class and a value, and sets the value to the slot of the
     instance.

`:accessor'
     Takes a symbol, and create two methods; a getter method and a
     setter method.  A getter method is bound to the generic function
     of the given name, and a setter method is added as the _setter_ of
     that generic function (see *Note Assignments:: for generic
     setters).

`:slot-ref'
     Specifies a value that evaluates to a procedure which takes one
     argument, an instance.  This slot option must be specified if the
     allocation of the slot is `virtual'.  Whenever a program tries to
     get the value of the slot, either using `slot-ref' or the getter
     method, the specified procedure is called, and its result is
     returned as the value of the slot.  The procedure can return an
     undef value (the return value of `undefined') to indicate the slot
     doesn't have a value.  If the slot allocation is not `virtual'
     this slot option is ignored.

`:slot-set!'
     Specifies a value that evaluates to a procedure which takes two
     arguments, an instance and a value.  Whenever a program tries to
     set the value of the slot, either using `slot-set!' or the setter
     method, the specified procedure is called with the value to be set.
     If the slot allocation is not `virtual' this slot option is
     ignored.  If this option isn't given to a virtual slot, the slot
     becomes read-only.

`:slot-bound?'
     Specifies a value that evaluates to a procedure which takes one
     argument, an instance.  This slot option is only meaningful when
     the slot allocation is `virtual'.  Whenever a program tries to
     determine whether the slot has a value, this procedure is called.
     It should return a true value if the slot has a value, or `#f'
     otherwise.  If this slot option is omitted for a virtual slot, the
     system calls the procedure given to `slot-ref' instead, and see
     whether its return value is `#<undef>' or not.


File: gauche-refe.info,  Node: Inheritance,  Next: Class object,  Prev: Defining class,  Up: Class

7.3.2 Inheritance
-----------------

Inheritance has two roles.  First, you can _extend_ the existing class
by adding more slots.  Second, you can _specialize_ the methods related
to the existing class so that those methods will do a little more
specific task than the original methods.

   Let's define some terms.  When a class `<T>' inherits a class `<S>',
we call `<T>' a _subclass_ of `<S>', and `<S>' a _superclass_ of `<T>'.
This relation is transitive: `<T>''s subclasses are also `<S>''s
subclasses, and `<S>''s superclasses are also `<T>''s superclasses.
Specifically, if `<T>' directly inherits `<S>', that is, `<S>' appeared
in the superclass list when `<T>' is defined, then `<S>' is a _direct
superclass_ of `<T>', and `<T>' is a _direct subclass_ of `<S>'.

   When a class is defined, it and its superclasses are ordered from
subclasses to superclasses, and a list of classes is created in such
order.   It is called _class precedence list_, or CPL.  Every class has
its own CPL.  A CPL of a class always begins with the class itself, and
ends with `<top>'.

   You can query a class's CPL by a procedure `class-precedence-list':

     gosh> (class-precedence-list <boolean>)
     (#<class <boolean>> #<class <top>>)
     gosh> (class-precedence-list <string>)
     (#<class <string>> #<class <sequence>> #<class <collection>> #<class <top>>)

   As you see, all classes inherits a class named `<top>'.  Some
built-in classes have several abstract classes in its CPL between
itself and `<top>'; the above example shows `<string>' class inherits
`<sequence>' and `<collection>'.  That means a string can behave both
as a sequence and a collection.

     gosh> (is-a? "abc" <string>)
     #t
     gosh> (is-a? "abc" <sequence>)
     #t
     gosh> (is-a? "abc" <collection>)
     #t

   How about inheritance of Scheme-defined classes?  If there's only
single inheritance, its CPL is straightforward: you can just follow the
class's super, its super's super, its super's super's super, ..., until
you reach `<top>'.  See the example:

     gosh> (define-class <a> () ())
     <a>
     gosh> (define-class <b> (<a>) ())
     <b>
     gosh> (class-precedence-list <b>)
     (#<class <b>> #<class <a>> #<class <object>> #<class <top>>)

   Scheme-defined class always inherits `<object>'.  It is
automatically inserted by the system.

   When multiple inheritance is involved, a story becomes a bit
complicated.  We have to merge multiple CPLs of the superclasses into
one CPL.  It is called _linearization_, and there are several known
linealization strategies.  By default, Gauche uses an algorithm called
_C3 linearization_, which is consistent with the local precedence order,
monotonicity, and the extended precedence graph.  We don't go into the
details here; as a general rule, the order of superclasses in a class's
CPL is always consistent to the order of direct superclasses of the
class, the order of CPL of each superclasses, and the order of direct
superclasses of each superclass, and so on.   See *Note [Dylan]: dylan.
for the precise description.

   If a class inherits superclasses in a way that its CPL can't be
constructed with satisfying consistencies, an error is reported.

   Here's a simple example of multiple inheritance.

     (define-class <grid-layout> () ())

     (define-class <horizontal-grid> (<grid-layout>) ())

     (define-class <vertical-grid> (<grid-layout>) ())

     (define-class <hv-grid> (<horizontal-grid> <vertical-grid>) ())

     (map class-name (class-precedence-list <hv-grid>))
      => (<hv-grid> <horizontal-grid> <vertical-grid>
          <grid-layout> <object> <top>)

   Note that the order of direct superclasses of `<hv-grid>'
(`<horizontal-grid>' and `<vertical-grid>') is kept.

   The following is a little twisted example:

     (define-class <pane> () ())

     (define-class <scrolling-mixin> () ())

     (define-class <scrollable-pane> (<pane> <scrolling-mixin>) ())

     (define-class <editing-mixin> () ())

     (define-class <editable-pane> (<pane> <editing-mixin>) ())

     (define-class <editable-scrollable-pane>
        (<scrollable-pane> <editable-pane>) ())

     (map class-name (class-precedence-list <editable-scrollable-pane>))
      => (<editable-scrollable-pane> <scrollable-pane>
          <editable-pane> <pane> <scrolling-mixin> <editing-mixin>
          <object> <top>)

   Once the class precedence order is determined, the slots of defined
class is calculated as follows: the slot definitions are collected in
the direction from superclasss to subclass in CPL.  If a subclass has a
slot definition of the same name of the one in superclass, then the
slot defintion of the subclass is taken and superclass's is discarded.
 Suppose a class `<S>' defines slots `a', `b', and `c', a class `<T>'
defines slots `c', `d', and `e', and a class `<U>' defines slots `b'
and `e'.  When `<U>''s CPL is `(<U> <T> <S> <object> <top>)', then
`<U>''s slots is calculated as the chart below; that is, `<U>' gets
five slots, of which `b' and `e''s definitions come from `<U>''s
definitions, `c' and `d''s come from `<T>', and `a''s comes from `<S>'.

        CPL      | slot definitions
                 |  () indicates shadowed slot
      -----------+-------------------
        <top>    |
        <object> |
        <S>      | a  (b) (c)
        <T>      |         c   d  (e)
        <U>      |     b           e
      -----------+--------------------
      <U>'s slots| a   b   c   d   e

   You can get a list of slot definitions of a class object using
`class-slots' function.

   Note that the behavor described above is mere a default behavior.
You can customize how the CPL is computed, or how slot definitions are
inherited, by defining metaclass.  For example, you can write a
metaclass that allows you to merge slot options of the same slot names,
instead of the one shadowing the other.  Or you can write a metaclass
that forbids a subclass shadows the superclass's slot.


File: gauche-refe.info,  Node: Class object,  Next: Slot definition object,  Prev: Inheritance,  Up: Class

7.3.3 Class object
------------------

What is a class?  In Gauche, a class is just an object that implements
a specific feature: to instantiate an object.  Because of that, you can
introspect the class by just looking into the slot values.  There are
some procedures provided for the convenience of such introspection.
Note that if those procedures return a list, it belongs to the class
and you shouldn't modify it.

 -- Function: class-name class
     Returns the name of CLASS.

          (class-name <string>) => <string>

 -- Function: class-precedence-list class
     Returns the class precedence list of CLASS.

          (class-precedence-list <string>)
            => (#<class <string>>
                #<class <sequence>>
                #<class <collection>>
                #<class <top>>)

 -- Function: class-direct-supers class
     Returns a list of direct superclasses of CLASS.  A direct
     superclass is a class from which CLASS inherits directly.

          (class-direct-supers <string>)
            => (#<class <sequence>>)

 -- Function: class-direct-subclasses class
     Returns a list of direct subclasses of CLASS.  A direct subclass
     is a class that directly inherits CLASS.  If `<T>' is a direct
     subclass of `<S>', then `<S>' is a direct superclass of `<T>'.

 -- Function: class-slots class
     Returns a list of _slot definitions_ of CLASS.  A slot definition
     is a list whose car is the name of the slot and whose cdr is a
     keyword-value list that specifies slot options.  You can further
     inspect a slot definition to know what characteristics the slot
     has.  See *Note Slot definition object:: for the details.

     The standard way to get a list of slot names of a given class is
     `(map slot-definition-name (class-slots class))'.

 -- Function: class-slot-definition class slot-name
     Returns a slot definition of a slot specified by SLOT-NAME in a
     class CLASS.  If CLASS doesn't have a named slot, `#f' is returned.

 -- Function: class-direct-slots class
     Returns a list of slot definitions that are directly defined in
     this class (i.e. not inherited from superclasses).  This
     information is used to calculate slot inheritance during class
     initialization.

 -- Function: class-direct-methods class
     Returns a list of methods that has CLASS in its specializer.

 -- Function: class-slot-accessor class slot-name
     Returns a slot accessor object of the slot specified by SLOT-NAME
     in CLASS.  A slot accessor object is an internal object that
     encapsulates the information how to access, modify, and initialize
     the given slot.

     You don't usually need to deal with slot accessor objects unless
     you are defining some special slots using metaobject protocol.


File: gauche-refe.info,  Node: Slot definition object,  Next: Class redefinition,  Prev: Class object,  Up: Class

7.3.4 Slot definition object
----------------------------

A slot definition object, returned by `class-slots',
`class-direct-slots' and `class-slot-definition', keeps information
about a slot.  Currently Gauche uses a list to represent the slot
definition, as STklos and TinyCLOS do.  However, it is not guaranteed
that Gauche keeps such a structure in future; you should use the
following dedicated accessor method to obtain information of a slot
definition object.

 -- Function: slot-definition-name slot-def
     Returns the name of a slot given by a slot definition object
     SLOT-DEF.

 -- Function: slot-definition-options slot-def
     Returns a keyword-value list of slot options of SLOT-DEF.

 -- Function: slot-definition-allocation slot-def
     Returns the value of `:allocation' option of SLOT-DEF.

 -- Function: slot-definition-getter slot-def
 -- Function: slot-defininion-setter slot-def
 -- Function: slot-definition-accessor slot-def
     Returns the value of `:getter', `:setter' and `:accessor' slot
     options of SLOT-DEF, respectively.

 -- Function: slot-definition-option slot-def option &optional default
     Returns the value of slot option OPTION of SLOT-DEF.  If there's
     no such an option, DEFAULT is returned if given, or an error is
     signalled otherwise.


File: gauche-refe.info,  Node: Class redefinition,  Next: Class definition examples,  Prev: Slot definition object,  Up: Class

7.3.5 Class redefinition
------------------------

If the specified class name is bound to a class when `define-class' is
used, it is regarded as _redefinition_ of the original class.

   Redefinition of a class means the following operations:
   * A new class object is created based on the new definition, and
     bound to the variable given to `define-class'.

   * Methods defined on the original class (i.e. methods that have the
     original class in their specializers) are changed so that they are
     defined on the new class.

   * The direct-subclasses link of the direct superclasses of the
     original class is modified so that they will point to the new
     class.

   * All the subclasses of the original class are redefined recursively
     so that they reflect the changes of the class.  Each class
     remembers its initialization arguments, and each redefined
     subclass gets the same initalization arguments as the original
     subclass.

   * The original class is marked _redefined_.

   Note that the original class and the new class are different objects.
The original class object remembers which variable in which module it
is originally bound, and replaces the binding to a new class.  If you
keep the direct reference to the original class somewhere else, it
still refers to the original class; you might want to take extra care.
You can customize class redefinition behavior by defining the
`class-redefinition' method; see *Note Metaobject protocol:: for the
details.

   If there are instances of the original class, such instances are
automatically _updated_ when it is about to be accessed or modified via
`class-of', `is-a?', `slot-ref', `slot-set!', `ref', getter method, or
setter method.

   Updating an instance means that the class of the instance is changed
(from the old class to the new class).  By default, the values of the
slots that are common in the original class and the new class are
carried over, and the slots added by the new class are initialized
according to the slot specification of the new class, and the values of
the slots that are removed from the original class are discarded.  You
can customize this behavior by writing the `change-class' method.  See
*Note Changing classes::, for the details.

Notes on thread safety
......................

Class redefinition process is non-local operation with full of
side-effects.  It is difficult to guarantee that two threads safely run
class redefinition protocol simultaneously.   So Gauche uses a
process-wide lock to limit only one thread to enter the class
redefinition protocol at a time.

   If a thread tries to redefine a class while another thread is in the
redefinition protocol, the thread is blocked, even if it is redefining
a class different from the one that are being redefined; because
redefinition affects all the subclasses, and all the methods and
generic functions that are related to the class and subclasses, it is
not trivial to determine two classes are completely independent or not.

   If a thread tries to access an instance whose class is being
redefined by another thread, also the thread is blocked until the
redefinition is finished.

   Note that the instance update protocol isn't serialized.  If two
threads try to access an instance whose class has been redefined, both
trigger the instance update protocol, which would cause an undesired
race condition.  It is the application's responsibility to ensure such
a case won't happen.  It is natural since the instance access isn't
serialized by the system anyway.  However, an extra care is required to
have mutex within an instance; just accessing the mutex in it may
trigger the instance update protocol.

Notes on compatibility
......................

Class redefinition protocol subtlely differs among CLOS-like Scheme
systems.   Gauche's is very similar to STklos's, except that STklos
0.56 doesn't replace bindings of redefined subclasses, and also it
doesn't remember initialization arguments so the redefined subclass may
lose some of the information that the original subclass has.  Guile's
object system swaps identities of the original class and the redefined
class at the end of class redefinition protocol, so the reference to
the original class object will turn to the redefined class.  As far as
the author knows, class redefinition is not thread-safe in both STklos
0.56 and Guile 1.6.4.


File: gauche-refe.info,  Node: Class definition examples,  Prev: Class redefinition,  Up: Class

7.3.6 Class definition examples
-------------------------------

Let's see some examples.  Suppose you are defining a graphical toolkit.
A `<window>' is a rectangle region on the screen, so it has width and
height.  It can be organized hierarchically, i.e. a window can be
placed within another window; so it has a pointer to the parent window.
And we specify the window's position, x, y, by the coordinate relative
to its parent window.  Finally, we create a "root" window that covers
entire screen.  It also serves the default parent window.  So far, what
we get is something like this:

     ;; The first version
     (define-class <window> ()
       (;; Pointer to the parent window.
        (parent      :init-keyword :parent :init-form *root-window*)
        ;; Sizes of the window
        (width       :init-keyword :width  :init-value 1)
        (height      :init-keyword :height :init-value 1)
        ;; Position of the window relative to the parent.
        (x           :init-keyword :x :init-value 0)
        (y           :init-keyword :y :init-value 0)
        ))

     (define *screen-width* 1280)
     (define *screen-height* 1024)

     (define *root-window*
       (make <window> :parent #f :width *screen-width* :height *screen-height*))

   Note the usage of `:init-value' and `:init-form'.  When the
`<window>' class is defined, we haven't bound `*root-window*' yet, so
we can't use `:init-value' here.

     gosh> *root-window*
     #<<window> 0x80db1d0>
     gosh> (define window-a (make <window> :width 100 :height 100))
     window-a
     gosh> (d window-a)
     #<<window> 0x80db1b0> is an instance of class <window>
     slots:
       parent    : #<<window> 0x80db1d0>
       width     : 100
       height    : 100
       x         : 0
       y         : 0
     gosh> (define window-b
             (make <window> :parent window-a :width 50 :height 20 :x 10 :y 5))
     window-b
     gosh> (d window-b)
     #<<window> 0x80db140> is an instance of class <window>
     slots:
       parent    : #<<window> 0x80db1b0>
       width     : 50
       height    : 20
       x         : 10
       y         : 5

   If you're like me, you don't want to expose a global variable such
as `*root-window*' for users of your toolkit.  One way to encapsulate
it (to certain extent) is to keep the pointer to the root window in a
class variable.  Add the following slot option to the definition of
`<window>', and the slot `root-window' of the `<window>' class refers
to the same storage space.

     (define-class <window> ()
       (...
        ...
        (root-window :allocation :class)
        ...))

   You can use `slot-ref' and `slot-set!' on an instance of `<window>',
or use `class-slot-ref' and `class-slot-set!' on the `<window>' class
itself, to get/set the value of the `root-window' slot.

   The users of the toolkit may want to get the absolute position of
the window (the coordinates in the root window) instead of the relative
position.  You may provide virtual slots that returns the absolute
positions, like the following:

     (define-class <window> ()
       (...
        ...
        (root-x :allocation :virtual
                :slot-ref  (lambda (o)
                             (if (ref o 'parent)
                                 (+ (ref (ref o 'parent) 'root-x)
                                    (ref o 'x))
                                 (ref o 'x)))
                :slot-set! (lambda (o v)
                             (set! (ref o 'x)
                                   (if (ref o 'parent)
                                       (- v (ref (ref o 'parent) 'root-x))
                                       v)))
                 )
         ...))

   Whether providing such interface via methods or virtual slots is
somewhat a matter of taste.   Using virtual slots has an advantage of
being able to hide the change of implementation, i.e. you can change to
keep `root-x' in a real slot and make `x' a virtual slot later without
breaking the code using `<window>'.  (In the mainstream object-oriented
languages, such kind of "hiding implementation" is usually achieved by
hiding instance variables and exposing methods.  In Gauche and other
CLOS-like systems, slots are always visible to the users, so the
situation is a bit different.


File: gauche-refe.info,  Node: Instance,  Next: Generic function and method,  Prev: Class,  Up: Object system

7.4 Instance
============

In this section, we explain how to create and use an instance.

* Menu:

* Creating instance::
* Accessing instance::
* Changing classes::


File: gauche-refe.info,  Node: Creating instance,  Next: Accessing instance,  Prev: Instance,  Up: Instance

7.4.1 Creating instance
-----------------------

Using class object, you can create an instance of the class by a
generic function `make'.  A specialized method for standard `<class>'
is defined:

 -- Generic Function: make
 -- Method: make (class <class>) arg ...
     Creates an instance of CLASS and returns it.  ARG ... is typically
     a keyword-value list to initialize the instance.

   Conceptually, the default `make' method is defined as follows:

     (define-method make ((class <class>) . initargs)
       (let ((obj (allocate-instance class initargs)))
         (initialize obj initargs)
         obj))

   That is, first it allocates memory for CLASS's instance, then
initialize it with the INITIALIZE method.

 -- Generic Function: allocate-instance
 -- Method: allocate-instance (class <class>) initargs
     Returns a newly-allocated uninitialized instance of CLASS.

 -- Generic Function: initialize
 -- Method: initialize (obj <object>) initargs
     The default initialize method for `<object>' works as follows:

        * For each initializable slot of the class
             * If (the slot has the :init-keyword slot option AND the
               keyword appears in INITARGS): Then the corresponding
               value is used to initialize the slot

             * Else if the slot has :init-value slot option: Then the
               value given to the slot option is used to initialize the
               slot

             * Else if the slot has :init-thunk slot option: Then the
               thunk is called, and the returned value is used to
               initialize the slot.

             * Else: The slot is left unbound.

     Among the default slot allocation classes, only instance-allocated
     slots are initializable and are handled by the above sequence.
     Class-allocated slots (e.g. its slot allocation is either `:class'
     or `:each-subclass') are initialized when the class object is
     created, if `:init-value' or `:init-form' slot option is given.
     Virtual slots aren't initialized at all.

     An user-defined allocation class can be configured either
     initializable or not initializable; see *Note Metaobject
     protocol:: for the details.

     If you specialize INITIALIZE method, make sure to call
     `next-method' so that the slots are properly initialized by the
     default sequence, before accessing any slot of the newly created
     instance.

   Typically you specialize `initialize' method for your class to
customize how the instance is initialized.

   It is not common to specialize `allocate-instance' method.  However,
knowing that how `make' works, you can specialize `make' itself to
avoid allocation of instance in some circumstances (e.g. using
pre-allocated instances).


File: gauche-refe.info,  Node: Accessing instance,  Next: Changing classes,  Prev: Creating instance,  Up: Instance

7.4.2 Accessing instance
------------------------

Standard accessors
..................

 -- Function: slot-ref obj slot
     Returns a value of the slot SLOT of object OBJECT.

     If the specified slot is not bound to any value, a generic function
     `slot-unbound' is called with three arguments, OBJ's class, OBJ,
     and SLOT.  The default behavior of `slot-unbound' is to signal an
     error.

     If the object doesn't have the specified slot, a generic function
     `slot-missing' is called with three arguments, OBJ's class, OBJ,
     and SLOT.  The default behavior of `slot-missing' is to signal an
     error.

 -- Function: slot-set! obj slot value
     Alters the value of the slot SLOT of object OBJECT to the value
     VALUE.

     If the object doesn't have the specified slot, a generic function
     `slot-missing' is called with four arguments, OBJ's class, OBJ,
     SLOT, VALUE.

 -- Function: slot-bound? obj slot
     Returns true if object OBJ's slot SLOT is bound, otherwise returns
     false.

     If the object doesn't have the specified slot, a generic function
     `slot-missing' is called with three arguments, OBJ's class, OBJ,
     SLOT.

 -- Function: slot-exists? obj slot
     Returns true if OBJ has the slot named SLOT.

 -- Function: slot-push! obj slot value
     This function implements the common idiom.  It can be defined like
     the following code (but it may be optimized in the future
     versions).
          (define (slot-push! obj slot value)
            (slot-set! obj slot (cons value (slot-ref obj slot))))

 -- Method: ref (obj <object>) (slot <symbol>)
 -- Method: (setter ref) (obj <object>) (slot <symbol>) value
     These methods just calls `slot-ref' and `slot-set!', respectively.
     They are slightly less efficient than directly calling `slot-ref'
     and `slot-set!', but more compact in the program code.

Fallback methods
................

 -- Generic Function: slot-unbound
 -- Method: slot-unbound (class <class>) obj slot
     This generic function is called when an unbound slot value is
     retrieved.  The return value of this generic function will be
     returned to the caller that tried to get the value.

     The default method just signals an error.

 -- Generic Function: slot-missing
 -- Method: slot-missing (class <class>) obj slot &optional value
     This generic function is called when a non-existent slot value is
     retrieved or set.  The return value of this generic function will
     be returned to the caller that tried to get the value.

     The default method just signals an error.

Special accessors
.................

 -- Function: class-slot-ref class slot-name
 -- Function: class-slot-set! class slot-name obj
 -- Function: class-slot-bound? class slot-name obj
     When slot's `:allocation' option is either `:class' or
     `:each-subclass', these procedures allow you to get/set the value
     of the slot without having an instance.

 -- Method: slot-ref-using-class (class <class>) (obj <object>)
          slot-name
 -- Method: slot-set-using-class! (class <class>) (obj <object>)
          slot-name value
 -- Method: slot-bound-using-class? (class <class>) (obj <object>)
          slot-name
     Generic function version of `slot-ref', `slot-set!' and
     `slot-bound?'.   CLASS must be the class of OBJECT.

     Besides being generic, these functions are different from their
     procedural versions that they don't trigger class redefinition
     when `obj''s class has been redefined (i.e. in which case, CLASS
     should be the original class of OBJ).

     Note: Unlike CLOS, `slot-ref' etc. don't call the generic function
     version in it, so you can't customize the behavior of `slot-ref'
     by specializing `slot-ref-using-class'.  So the primary puropose
     of those generic functions are to be used within `change-class'
     method; especially, `slot-ref' etc.  can't be used during OBJ's
     being redefined, since they trigger class redefinition again (see
     *Note Changing classes:: for details).


File: gauche-refe.info,  Node: Changing classes,  Prev: Accessing instance,  Up: Instance

7.4.3 Changing classes
----------------------

Class change protocol
.....................

An unique feature of CLOS-family object system is that you can change
classes of an existing instance.  The two classes doesn't need to be
related; you can change a sewing machine into an umbrella, if you like.

 -- Generic Function: change-class
 -- Method: change-class (obj <object>) (new-class <class>)
     Changes an object OBJ's class to NEW-CLASS.  The default method
     just calls `change-object-class' procedure.

 -- Function: change-object-class obj orig-class new-class
     Changes an object OBJ's class from ORIG-CLASS to NEW-CLASS.  This
     isn't a generic function--changing object's class needs some
     secret magic, and this procedure encapsulates it.

     The precise steps of changing class are as follow:

       1. A new instance of NEW-CLASS is allocated by
          `allocate-instance'.

       2. For each slot of NEW-CLASS:
            1. If the slot also exists in OLD-CLASS, and is bound in
               OBJ, the value is retrieved from OBJ and set to the new
               instance.  (The slot is _carried over_).

            2. Otherwise, the slot of the new instance is initialized
               by standard slot initialization protocol, as described
               in *Note Creating instance::.

       3. Finally, the content of the new instance is _transplanted_ to
          the OBJ--that is, OBJ becomes the instance of NEW-CLASS
          without changing its identity.

     Note that `initialize' method isn't called on OBJ.  If you desire,
     you can call it by your own `change-class' method.

     `Change-object-class' returns OBJ.

   Usually a user is not supposed to call `change-object-class'
directly.  Instead, she can define a specialized `change-class'.  For
example, if she wants to carry over the slot `x' of old class to the
slot `y' of new class, she may write something like this:

     (define-method change-class ((obj <old-class>) <new-class>)
       (let ((old-val (slot-ref obj 'x)))
         (next-method)               ;; calls default change-class
         (slot-set! obj 'y old-val)  ;; here, obj's class is already <new-class>.
         obj))

Customizing instance update
...........................

Updating an instance for a redefined class is also handled as class
change.  When an object is accessed via normal slot accessor/modifier,
its class is checked whether it has been redefined.  And if it has
indeed been redefined, `change-class' is called with the redefined
class as NEW-CLASS; that is, updating an instance is regarded as
changing object's class from the original one to the redefined one.

   By specializing `change-class', you can customize the way an
instance is updated for a redefined class.  However, you need a special
care to write `change-class' for class redefinition.

   First, the redefinition changes global binding of the class object.
So you need to keep the reference to the old class before redefining
the class, and use the old class to specialize `change-class' method:

     ;; save old <myclass>
     (define <old-myclass> <myclass>)

     ;; redefine <myclass>
     (define-class <myclass> ()
       ...)

     ;; define customized change-class method
     (define-method change-class ((obj <old-myclass>) <myclass>)
       ...
       (next-method)
       ...)

   Next, note that the above `change-class' method may be triggered
implicitly when you access to OBJ via `slot-ref', `slot-set!',
`class-of', etc.  If you use such procedures like `slot-ref' on OBJ
again within `change-class', it would trigger the instance update
protocol recursively, which would cause an infinite loop.  You can only
use the methods that doesn't trigger instance update, that is,
`slot-ref-using-class', `slot-set-using-class!',
`slot-bound-using-class?' and `current-class-of'.

   If you want to carry over a slot whose value is calculated
procedurally, such as a virtual slot, then `slot-ref' etc.  might be
called implicitly on OBJ during calculating the slot value.  Actually
`change-object-class' has a special protection to detect such a
recursion.  If that happens, `change-object-class' gives up to retrieve
the slot value and just initializes the slot of the new instance as if
the old slot were unbound.

   Customizing instance update is highly tricky business, although very
powerful.   You can find some nontrivial cases in the test program of
Gauche source tarball; take a look at `test/object.scm'.


File: gauche-refe.info,  Node: Generic function and method,  Next: Metaobject protocol,  Prev: Instance,  Up: Object system

7.5 Generic function and method
===============================

Defining methods
----------------

 -- Macro: define-generic name &keyword class
     Creates a generic function and bind it to NAME.

     You don't usually need to use this, since the `define-method'
     macro implicitly creates a generic function if it doesn't exist
     yet.

     You can pass a subclass of `<generic>' to the CLASS keyword
     argument so that the created generic function will be the instance
     of the passed class, instead of the default `<generic>' class.  It
     is useful when you defined a subclass of `<generic>' to customize
     generic function application behavior.

 -- Macro: define-method name specs body
     Defines a method whose name is NAME.  If there's already a generic
     function object globally bound to NAME, the created method is
     added to the generic function.  If NAME is unbound, or bound to an
     object except a generic function, then a new generic function is
     created, bound to NAME, then a new method is added to it.

     SPECS specifies the arguments and their types for this method.
     It's like the argument list of lambda form, except you can specify
     the type of each argument.

          specs : ( arg ... )
                | ( arg ... . symbol )
                | symbol

          arg   : ( symbol class )
                | symbol

     Class specifies the class that the argument has to belong to.  If
     `arg' is just a symbol, it is equivalent to `(arg <top>)'.  You
     can't specify the type for the "rest" argument, for it is always
     bound to a list.

     The list of classes of the argument list is called _method
     specializer list_, based on which the generic function will select
     appropriate methods(s).  Here are some examples of SPECS and the
     corresponding specializer list:

          specs:        ((self <myclass>) (index <integer>) value)
          specializers: (<myclas> <integer> <top>)

          specs:        ((self <myclass>) obj . options)
          specializers: (<myclas> <top> . <top>)

          specs:        (obj (attr <string>))
          specializers: (<top> <string>)

          specs:        args
          specializers: <top>

     If you define a method on NAME whose specializer list matches with
     one in the generic function's methods, then the existing method is
     replaced by the newly defined one.

Applying generic function
-------------------------

When a generic function is applied, first it selects methods whose
specializer list matches the given arguments.  For example, suppose a
generic function `foo' has three methods, whose specializer lists are
`(<string> <top>)', `(<string> <string>)', and `(<top> <top>)',
respectively.  When `foo' is applied like `(foo "abc" 3)', the first
and the third method will be selected.

   Then the selected methods are sorted from the most _specific_ method
to the least specific method.  It is calculated as follows:

   * Suppose we have a method `a' that has specializers `(A1 A2 ...)',
     and a method `b' that has `(B1 B2 ...)'.

   * Find the minimum N where the classes `An' and `Bn' differ.   Then
     the class of N-th argument is taken, and its class precedence list
     is checked.  If `An' comes before `Bn' in the CPL, then method `a'
     is more specific than `b'.  Otherwise, `b' is more specific than
     `a'.

   * If all the specializers of `a' and `b' are the same, except that
     one has an improper tail ("rest" argument) and another doesn't,
     then the method that doesn't have an improper tail is more
     specific than the one that has.

   Once methods are sorted, the body of the first method is called with
the actual argument.

   Within the method body, a special local variable `next-method' is
bound implicitly.

 -- Next method: next-method
 -- Next method: next-method args ...
     This variable is bound within a method body to a special object
     that encapsulates the next method in the sorted method list.

     Calling without arguments invokes the next method with the same
     arguments as this method is called with.  Passing ARGS ...
     explicitly invokes the next method with the passed arguments.

     If `next-method' is called in the least specific method, i.e.
     there's no "next method", an error is signalled.


File: gauche-refe.info,  Node: Metaobject protocol,  Prev: Generic function and method,  Up: Object system

7.6 Metaobject protocol
=======================

In CLOS-like object systems, the object system is built on top of
itself--that is, things such as the structure of the class, how a class
is created, how an instance is created and initialized, and how a
method is dispatched and called, are all defined in terms of the object
system.  For example, a class is just an instance of the class
`<class>' that defines a generic structure and behavior of standard
classes.  If you subclass `<class>', then you can create your own set
of classes that behaves differently than the default behavior; in
effect, you are creating your own object system.

   _Metaobject protocols_ are the definitions of APIs concerning about
how the object systems are built--building-block classes, and the names
and orders of generic functions to be called during operations of the
object system.  Subclassing these classes and specializing these
methods are the means of customizing object system behaviors.

* Menu:

* Class instantiation::
* Customizing slot access::
* Method instantiation::
* Customizing method application::


File: gauche-refe.info,  Node: Class instantiation,  Next: Customizing slot access,  Prev: Metaobject protocol,  Up: Metaobject protocol

7.6.1 Class instantiation
-------------------------

Every class is an instance of a group of special classes.  A class that
can be a class of another class is called _metaclass_.  In Gauche, only
the `<class>' class or its subclasses can be a metaclass.

Expansion of `define-class'
...........................

The `define-class' macro is basically a wrapper of the code that
creates an instance of `<class>' (or specified metaclass) and bind it
to the given name.  Suppose you have the following `define-class' form.
     (define-class NAME (SUPERS)
       SLOT-SPECS
       OPTIONS ...)

   It is expanded into a form like this (you can see the exact form by
looking at the definition of `define-class' macro in ``gauche-config
--syslibdir`/gauche/object.scm').
     (define NAME
       (let ((tmp1 (make METACLASS
                      :name 'NAME :supers (list SUPERS)
                      :slots (map PROCESS-SLOT-DEFINITIONS
                                  SLOT-SPECS)
                      :defined-modules (list (current-module))
                      OPTIONS ...)))
         ... CHECK CLASS REDEFINITION ...
         ... REGISTERING ACCESSOR METHODS ...
         tmp1))

   The created class's class, i.e. METACLASS, is determined by the
following rules.

  1. If `:metaclass' option is given to the `define-class' macro, its
     value is used.  The value must be the `<class>' class or its
     descendants.

  2. Otherwise, the metaclasses of the classes in the class precedence
     list is examined.
        * If all the metaclasses are `<class>', then the created
          class's metaclass is also `<class>'.

        * If all the metaclasses are either `<class>' or another
          metaclass `A', then the created class' metaclass is `A'.

        * If the set of metaclasses contains more than one metaclass
          (`A', `B', `C' ...) other than `<class>', then the created
          class' metaclass is a metaclass that inherits all of those
          metaclasses `A', `B', `C' ....

   The class's name, superclasses, and slot definitions are passed as
the initialization arguments to the `make' generic function, with other
arguments passed to `define-class'.  The initialization argument
`defined-modules' is passed to remember which module the class is
defined, for the redefinition of this class.

   The slot specifications SLOT-SPECS are processed by internal method
PROCESS-SLOT-DEFINITIONS (which can't be directly called) to be turned
into slot definitions.  Specifically, an `:init-form' slot option is
turned into an `:init-thunk' option, and `:getter', `:setter' and
`:accessor' slot options are quoted.

   After the class (an instance of METACLASS) is created, the global
binding of NAME is checked.  If it is bound to a class, then the class
redefinition protocol is invoked (see *Note Class redefinition::).

   Then, the methods given to `:getter', `:setter' and `:accessor' slot
options in SLOT-SPEC are collected and registered to the corresponding
generic functions.

Class structure
...............

 -- Class: <class>
     The base class of all metaclasses, `<class>', has the following
     slots.  Note that these slots are for internal management, and
     users shouldn't change their values after the class is
     initialized.  It is recommended to obtain information about a
     class by procedures described in *Note Class object::, instead of
     directly accessing those slots.

      -- Instance Variable of <class>: name
          The name of the class; the symbol given to `define-class'
          macro.  `class-name' returns this value.

      -- Instance Variable of <class>: cpl
          Class precedence list.  `class-precedence-list' returns this
          value.

      -- Instance Variable of <class>: direct-supers
          The list of direct superclasses.  `class-direct-supers'
          returns this value.

      -- Instance Variable of <class>: accessors
          An assoc list of slot accessors--it encapsulates how each slot
          should be accessed.

      -- Instance Variable of <class>: slots
          A list of slot definitions.  `class-slots' returns this value.
          See *Note Slot definition object::, for the details of slot
          definitions.

      -- Instance Variable of <class>: direct-slots
          A list of slot definitions that is directly specified in this
          class definition (i.e. not inherited).  `class-direct-slots'
          returns this value.

      -- Instance Variable of <class>: num-instance-slots
          The number of instance allocated slots.

      -- Instance Variable of <class>: direct-subclasses
          A list of classes that directly inherits this class.
          `class-direct-subclasses' returns this value.

      -- Instance Variable of <class>: direct-methods
          A list of methods that has this class in its specializer list.
          `class-direct-methods' returns this value.

      -- Instance Variable of <class>: initargs
          The initialization argument list when this class is created.
          The information is used to initialize redefined class (see
          *Note Class redefinition::).

      -- Instance Variable of <class>: defined-modules
          A list of modules where this class has a global binding.

      -- Instance Variable of <class>: redefined
          If this class has been redefined, this slot contains a
          reference to the new class.  Otherwise, this slot has `#f'.

      -- Instance Variable of <class>: category
          The value of this slot indicates how this class is created.
          Scheme defined class has a symbol `scheme'.  Other values are
          for internal use.

The make method for `<class>'
.............................

 -- Method: make (class <class>) &rest initargs


File: gauche-refe.info,  Node: Customizing slot access,  Next: Method instantiation,  Prev: Class instantiation,  Up: Metaobject protocol

7.6.2 Customizing slot access
-----------------------------

 -- Generic Function: compute-slots

 -- Generic Function: compute-get-n-set

 -- Function: slot-ref-using-accessor obj slot-accessor
 -- Function: slot-set-using-accessor obj slot-accessor value


File: gauche-refe.info,  Node: Method instantiation,  Next: Customizing method application,  Prev: Customizing slot access,  Up: Metaobject protocol

7.6.3 Method instantiation
--------------------------

 -- Method: make (class <method>) &rest initargs


File: gauche-refe.info,  Node: Customizing method application,  Prev: Method instantiation,  Up: Metaobject protocol

7.6.4 Customizing method application
------------------------------------

 -- Generic Function: apply-generic gf args

 -- Generic Function: sort-applicable-methods gf methods args

 -- Generic Function: method-more-specific? method1 method2 classes

 -- Generic Function: apply-methods gf methods args

 -- Generic Function: apply-method gf method build-next args


File: gauche-refe.info,  Node: Library modules - Overview,  Next: Library modules - Gauche extensions,  Prev: Object system,  Up: Top

8 Library modules - Overview
****************************

In the following chapters, the library modules bundled with the Gauche
distribution are explained.  Those modules should generally be loaded
and imported (usually using `use' - *Note Using modules::, for
details), unless otherwise noted.

   Some modules are described as "autoloaded".  That means you don't
need to `load' or `use' the module explicitly; at the first time the
bindings are used in the program, the module is automatically loaded
and imported.  See *Note Autoload::, for the details of autoloading.

   *Note Library modules - Gauche extensions:: describes `gauche.*'
modules, which are more or less considered the core features of Gauche
but separated since less frequently used.  (Some modules are rather
ad-hoc, but here for historically reasons).  The modules in this
category include system APIs (e.g. `gauche.fcntl', `gauche.termios'),
networking (`gauche.net'), thread APIs (`gauche.threads'), and some
high-level routines that are built on top of Gauche low-level core APIs
(e.g. `gauche.process', `gauche.regexp').

   *Note Library modules - SRFIs:: describes the modules that provides
SRFI functionalities.  Note that some of SRFI features are built in
Gauche core and not listed here.  *Note Standard conformance::, for
entire list of supported SRFIs.

   *Note Library modules - Utilities:: describes the modules provides
miscellaneous utility functions--including dbm-style database
interface, filesystem utilities, network protocol utilities, and more.

   There are a few procedures that helps your program to check the
existence of certain modules or libraries at run-time.  See *Note
Operations on libraries::, for the details.

   The following table summarizes naming categories of the modules,
including external ones and planned ones.

`data.*'
     Generic data structures (planned).

`dbm.*'
     DBM interface

`gauche.*'
     Stuffs more or less considered as Gauche core features.

`gl.*'
     OpenGL binding and related libraries (external package).

`gtk.*'
     GTk+ binding and related libraries (external package).

`file.*'
     Manipulating files and directories.

`lang.*'
     Language-related libraries, artificial and/or natural (planned).

`math.*'
     Mathematics.

`compat.*'
     Compatibility libraries

`rfc.*'
     Implementations of net protocols defined in RFC's.

`srfi-*'
     SRFI implementations.

`text.*'
     Libraries dealing with text data.

`util.*'
     Generic implementations of various algorithms.

`www.*'
     Implementations of various protocols and formats mainly used in
     WWW.


File: gauche-refe.info,  Node: Library modules - Gauche extensions,  Next: Library modules - SRFIs,  Prev: Library modules - Overview,  Up: Top

9 Library modules - Gauche extensions
*************************************

* Menu:

* Arrays::
* Character code conversion::
* Collection framework::
* Configuration parameters::
* Low-level file operations::
* Hooks::
* Interactive session::
* Listener::
* User-level logging::
* Singleton::
* Slot with validator::
* Networking::
* Parameters::
* Parsing command-line options::
* High Level Process Interface::
* Regular expression utilities::
* Reloading modules::
* Simple dispatcher::
* Sequence framework::
* Syslog::
* Termios::
* Unit testing::
* Threads::
* Measure timings::
* Uniform vectors::
* Comparing version numbers::
* Virtual ports::


File: gauche-refe.info,  Node: Arrays,  Next: Character code conversion,  Prev: Library modules - Gauche extensions,  Up: Library modules - Gauche extensions

9.1 `gauche.array' - Arrays
===========================

 -- Module: gauche.array
     This module provides multi-dimensional array data type and
     operations.  The primitive API follows SRFI-25.  Besides a generic
     srfi-25 array that can store any Scheme objects, this module also
     provides array classes that stores numeric objects efficiently,
     backed up by homogeneous numeric vectors (*Note Uniform vectors::).
     An external representation of arrays, using SRFI-10 mechanism, is
     also provided.

     Each element of an N-dimensional array can be accessed by N
     integer indices, `[ I_0 I_1 ... I_N-1 ]'.  An array has associated
     SHAPE that knows lower-bound S_K and upper-bound E_K of index of
     each dimension, where S_K <= E_K, and the index I_K must satisfy
     S_K <= I_K < E_K.  (Note: it is allowed to have S_K == E_K, but
     such array can't store any data.  It is also allowed to have
     zero-dimensional array, that can store a single data.).  The shape
     itself is a [ D x 2 ] array, where D is the dimension of the array
     which the shape represents.

     You can pass index(es) to array access primitives in a few ways;
     each index can be passed as individual argument, or can be
     'packed' in a vector or one-dimensional array.  In the latter
     case, such a vector or an array is called an "index object".
     Using a vector is efficient in Gauche when you iterate over the
     elements by changing the vector elements, for it won't involve
     memory allocation.

     Arrays can be compared by the `equal?' procedure.  `Equal?'
     returns `#t' if two arrays have the same shape and their
     corresponding elements are the same in the sense of `equal?'.

     Internally, an array consists of a backing storage and a mapping
     procedure.  A backing storage is an object of aggregate type that
     can be accessed by an integer index.  A mapping procedure takes
     multi-dimensional indices (or index object) and returns a scalar
     index into the backing storage.

 -- Class: <array-base>
     An abstract base class of array types, that implements generic
     operations on the array.   To create an array instance, you should
     use one of the following concrete array classes.

 -- Class: <array>
 -- Class: <u8array>
 -- Class: <s8array>
 -- Class: <u16array>
 -- Class: <s16array>
 -- Class: <u32array>
 -- Class: <s32array>
 -- Class: <u64array>
 -- Class: <s64array>
 -- Class: <f32array>
 -- Class: <f64array>
     Concrete array classes.  The `<array>' class implements srfi-25
     compatible array, i.e. an array that can store any Scheme objects.
     The `<u8array>' class through `<f64array>' classes uses a
     `<u8vector' through `<f64vector>' as a backing stroage, and can
     only store a limited range of integers or inexact real numbers,
     but they are space efficient.

 -- Reader syntax: `#,(<array> SHAPE OBJ ...)'
     An array is written out in this format.  (Substitute `<array>' for
     `<u8array>' if the array is `<u8array>', etc.)  SHAPE is a list of
     even number of integers, and each 2N-th integer and 2N+1-th
     integer specifies the inclusive lower-bound and exclusive
     upper-bound of N-th dimension, respectively.  The following OBJ
     ... are the values in the array listed in row-major order.

     When read back, this syntax is read as an array with the same shape
     and content, so it is `equal?' to the original array.

          ; an array such that:
          ;   8 3 4
          ;   1 5 9
          ;   6 7 2
          #,(<array> (0 3 0 3) 8 3 4 1 5 9 6 7 2)

          ; a 4x4 identity matrix
          #,(<array> (0 4 0 4) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1)

 -- Function: array? obj
     [SRFI-25] Returns `#t' if OBJ is an array, #F otherwise.  It is
     equivalent to `(is-a? obj <array-base>)'.

 -- Function: make-array shape &optional init
     [SRFI-25] Creates an array of shape SHAPE.  SHAPE must be a [ D x
     2 ] array, and for each K (0 <= K < D), the [ K 0 ] element must
     be less than or equal to the [ K 1] element.  If INIT is given,
     all the elements are initialized by it.  Otherwise, the initial
     value of the elements are undefined.

          (make-array (shape 0 2 0 2 0 2) 5)
           => #,(<array> (0 2 0 2 0 2) 5 5 5 5 5 5 5 5)

 -- Function: make-u8array shape &optional init
 -- Function: make-s8array shape &optional init
     ...

 -- Function: make-f32array shape &optional init
 -- Function: make-f64array shape &optional init
     Like `make-array', but creates and returns an uniform numeric
     array.

 -- Function: shape bound ...
     [SRFI-25] Takes even number of exact integer arguments, and returns
     a two-dimensional array that is suitable for representing the shape
     of an array.

          (shape 0 2 1 3 3 5)
           => #,(<array> (0 3 0 2) 0 2 1 3 3 5)

          (shape)
           => #,(<array> (0 0 0 2))

 -- Function: array shape init ...
     [SRFI-25] Creates an array of shape SHAPE, initializing its
     elements by INIT ....

          (array (shape 0 2 1 3) 'a 'b 'c 'd)
           => #,(<array> (0 2 1 3) a b c d)

 -- Function: array-rank array
     [SRFI-25] Returns the number of dimensions of an array ARRAY.

          (array-rank (make-array (shape 0 2 0 2 0 2))) => 3
          (array-rank (make-array (shape))) => 0

 -- Function: array-shape array
     Returns a shape array of ARRAY.

 -- Function: array-start array dim
 -- Function: array-end array dim
 -- Function: array-length array dim
     [SRFI-25+] `Array-start' returns the inclusive lower bound of
     index of DIM-th dimension of an array ARRAY.  `Array-end' returns
     the exclusive upper bound.  And `array-length' returns the
     difference between two.  `Array-start' and `array-end' are defined
     in SRFI-25.

          (define a (make-array (shape 1 5 0 2)))

          (array-start a 0)  => 1
          (array-end a 0)    => 5
          (array-length a 0) => 4
          (array-start a 1)  => 0
          (array-end a 1)    => 2
          (array-length a 1) => 2

 -- Function: array-size array
     Returns the total number of elements in the array ARRAY.

          (array-size (make-array (shape 5 9 1 3))) => 8
          (array-size (make-array (shape))) => 1
          (array-size (make-array (shape 0 0 0 2))) => 0

 -- Function: array-ref array k ...
 -- Function: array-ref array index
     [SRFI-25] Gets the element of array `array'.  In the first form,
     the element is specified by indices K ....  In the second form,
     the element is specified by an index object INDEX, which must be a
     vector or an one-dimensional array.

 -- Function: array-set! array k ... value
 -- Function: array-set! array index value
     [SRFI-25] Sets the element of array ARRAY to VALUE.  In the first
     form, the element is specified by indices K ....  In the second
     form, the element is specified by an index object INDEX, which
     must be a vector or an one-dimensional array.

 -- Function: share-array array shape proc
     [SRFI-25] Creates and returns a new array of shape SHAPE, that
     shares the backing storage with the given array ARRAY.  The
     procedure PROC maps the indices of the new array to the indices to
     the original array, i.e. PROC must be a N-ary procedure that
     returns M values, where N is the dimension of the new array and M
     is the one of the original array.  Furthermore, PROC must be an
     affine function; each mapping has to be a linear combination of
     input arguments plus optional constant.  (`Share-array' optimizes
     the mapping function based on the affinity assumption, so PROC
     won't be called every time the new array is accessed).

 -- Function: array-for-each-index array proc &optional index

 -- Function: shape-for-each shape proc &optional index

 -- Function: tabulate-array shape proc &optional index

 -- Function: array-retabulate! array shape proc &optional index
 -- Function: array-retabulate! array proc &optional index

 -- Function: array-map! array shape proc array0 array1 ...
 -- Function: array-map! array proc array0 array1 ...

 -- Function: array-map shape proc array0 array1 ...
 -- Function: array-map proc array0 array1 ...

 -- Function: array->vector array
 -- Function: array->list array

 -- Function: array-concatenate a b &optional dimension

 -- Function: array-transpose array &optional dim1 dim2

 -- Function: array-rotate-90 array &optional dim1 dim2

 -- Function: array-flip array &optional dimension
 -- Function: array-flip! array &optional dimension

 -- Function: identity-array dimension &optional class

 -- Function: array-inverse array

 -- Function: determinant array
 -- Function: determinant! array

 -- Function: array-mul a b

 -- Function: array-expt array pow

 -- Function: array-div-left a b
 -- Function: array-div-right a b

 -- Function: array-add-elements array array-or-scalar ...
 -- Function: array-add-elements! array array-or-scalar ...

 -- Function: array-sub-elements array array-or-scalar ...
 -- Function: array-sub-elements! array array-or-scalar ...
 -- Function: array-mul-elements array array-or-scalar ...
 -- Function: array-mul-elements! array array-or-scalar ...
 -- Function: array-div-elements array array-or-scalar ...
 -- Function: array-div-elements! array array-or-scalar ...


File: gauche-refe.info,  Node: Character code conversion,  Next: Collection framework,  Prev: Arrays,  Up: Library modules - Gauche extensions

9.2 `gauche.charconv' - Character Code Conversion
=================================================

 -- Module: gauche.charconv
     This module defines a set of functions that converts character
     encoding schemes (CES) of the given data stream.  This module also
     overloads Gauche's file stream creating functions (such as
     `open-input-file' and `call-with-output-file') so that they accept
     `:encoding' keyword argument.

     As of release 0.5.6, Gauche natively supports conversions between
     typical Japanese character encodings: ISO2022JP, ISO2022JP-3,
     EUC-JP (EUC-JISX0213), Shift_JISX0213, UTF-8 (Unicode 3.2).
     Conversions between other encodings are handled by `iconv(3)'.
     *Note Supported character encoding schemes::, for details.

* Menu:

* Supported character encoding schemes::
* Autodetecting the encoding scheme::
* Conversion ports::
* Extended port procedures::


File: gauche-refe.info,  Node: Supported character encoding schemes,  Next: Autodetecting the encoding scheme,  Prev: Character code conversion,  Up: Character code conversion

9.2.1 Supported character encoding schemes
------------------------------------------

A CES is represented by its name as a string or a symbol.  Case is
ignored.  There may be several aliases defined for a single encoding.

   A CES name "none" is special.  When Gauche's native encoding is
`none', Gauche just treats a string as a byte sequence, and it's up to
the application to interpret the sequence in an appropriate encoding.
So, conversion to and from CES "none" does nothing.

   You can check whether the specific conversion is supported on your
system or not, by the following function.

 -- Function: ces-conversion-supported? from-ces to-ces
     Returns `#t' if conversion from the character encoding scheme
     (CES) FROM-CES to TO-CES is supported in this system.

     Note that this procedure may return true even if system only
     supports partial conversion between FROM-CES and TO-CES.  In such
     case, actual conversion might lose information by coercing
     characters in FROM-CES which are not supported in TO-CES.  (For
     example, conversion from Unicode to EUC-JP is "supported",
     although Unicode has characters that are not in EUC-JP).

     Also note that this procedure always returns `#t' if FROM-CES
     and/or TO-CES is "none", for conversion to/from CES "none" always
     succeeds (in fact, it does nothing).

          ;; see if you can convert the internal encoding to EUC-JP
          (ces-conversion-supported? (gauche-character-encoding) "euc-jp")

   Also there are two useful procedures to deal with CES names.

 -- Function: ces-equivalent? ces-a ces-b &optional unknown-value
     Returns true if two CESes CES-A and CES-B are equivalent to the
     knowledge of the system.  Returns false if they are not.  If the
     system doesn't know about equivalency, UNKNOWN-VALUE is returned,
     whose default is `#f'.

     CES "none" works like a wild card; it is "equivalent" to any CES.
     (Thus, `ces-equivalent?' is not transitive.  The intended use of
     `ces-equivalent?' is to compare two given CES names and see if
     conversion is required or not).

          (ces-equivalent? 'eucjp "EUC-JP")            => #t
          (ces-equivalent? 'shift_jis "EUC-JP")        => #f
          (ces-equivalent? "NoSuchEncoding" 'utf-8 '?) => ?

 -- Function: ces-upper-compatible? ces-a ces-b &optional unknown-value
     Returns true if a string encoded in CES CES-B can also be regarded
     as a string encoded in CES-A without conversion, to the knowledge
     of the system.  Returns false if not.  Returns UNKNOWN-VALUE if
     the system can't determine which is the case.

     Like `ces-equivalent?', CES "none" works like a wildcard.  It is
     upper-compatible to any CES, and any CES is upper-compatible to
     "none".

          (ces-upper-compatible? "eucjp" "ASCII")             => #t
          (ces-upper-compatible? "eucjp" "utf-8")             => #f
          (ces-upper-compatible? "utf-8" "NoSuchEncoding" '?) => ?

   Conversion between common japanese CESes (EUC_JP, Shift JIS, UTF-8
and ISO2022-JP) of the character set JIS X 0201 and JIS X 0213 is
handled by Gauche's built-in algorithm (see below for details).  When
other CES name is given, Gauche uses `iconv(3)' if it is linked.

   When Gauche's conversion routine encounters a character that can't
be mapped, it replaces the character for "geta mark" (U+3013) if it's a
multibyte character in the input encoding, or for '?' if it's a
singlebyte character in the input encoding.  If that happens in iconv,
handling of such character depends on iconv implementation (glibc
implementation returns an error).

   If the conversion routine encounters an input sequence that is
illegal in the input CES, an error is signalled.

   *Details of Gauche's native conversion algorithm:* Between EUC_JP,
Shift JIS and ISO2022JP, Gauche uses arithmetic conversion whenever
possible.  This even maps the undefined codepoint properly.  Between
Unicode (UTF-8) and EUC_JP, Gauche uses lookup tables.  Between Unicode
and Shift JIS or ISO2022JP, Gauche converts the input CES to EUC_JP,
then convert it to the output CES.  If the same CES is specified for
input and output, Gauche's conversion routine just copies input
characters to output characters, without checking the validity of the
encodings.

`EUC_JP, EUCJP, EUCJ, EUC_JISX0213'
     Covers ASCII, JIS X 0201 kana, JIS X 0212 and JIS X 0213 character
     sets.  JIS X 0212 character set is supported merely because it uses
     the code region JIS X 0213 doesn't use, and JIS X 0212 characters
     are not converted properly to Shift JIS and UTF-8.  Use JIS X 0213.

`SHIFT_JIS, SHIFTJIS, SJIS'
     Covers Shift_JISX0213, except that 0x5c and 0x7e is mapped to ASCII
     character set (REVERSE SOLIDUS and TILDE), instead of JIS X 0201
     Roman (YEN SIGN and OVERLINE).

`UTF-8, UTF8'
     Unicode 3.2.  Note that some JIS X 0213 characters are mapped to
     Extension B (U+20000 and up).  Some JIS X 0213 characters are
     mapped to two unicode characters (one base character plus a
     combining character).

`ISO2022JP, CSISO2022JP, ISO2022JP-1, ISO2022JP-2, ISO2022JP-3'
     These encodings differ a bit (except ISO2022JP and CSISO2022JP,
     which are synonyms), but Gauche handles them same.  If one of
     these CES is specified as input, Gauche recognizes escape
     sequences of any of CES.  ISO2022JP-2 defines several non-Japanese
     escape sequences, and they are recognized by Gauche, but mapped to
     substitution character ('?' or geta mark).

     For output, Gauche assumes ISO2022JP first, and uses ISO2022JP-1
     escape sequence to put JIS X 0212 character, or uses ISO2022JP-3
     escape sequence to put JIS X 0213 plane 2 character.  Thus, if the
     string contains only JIS X 0208 characters, the output is
     compatible to ISO2022JP.  Precisely speaking, JIS X 0213 specifies
     some characters in JIS X 0208 codepoint that shouldn't be mixed
     with JIS X 0208 characters; Gauche output those characters as JIS
     X 0208 for compatibility.  (This is the same policy as
     Emacs-Mule's iso2022jp-3-compatible mode).


File: gauche-refe.info,  Node: Autodetecting the encoding scheme,  Next: Conversion ports,  Prev: Supported character encoding schemes,  Up: Character code conversion

9.2.2 Autodetecting the encoding scheme
---------------------------------------

There are cases that you don't know the CES of the input, but you know
it is one of several possible encodings.  The charconv module has a
mechanism to guess the input encoding.  There can be multiple
algorithms, and each algorithm has the name.  Right now, there's only
one algorithm implemented:
`"*JP"'
     To guess the character encoding from japanese text, among either
     ISO2022-JP(-1,2,3), EUCJP, SHIFT_JIS or UTF-8.

   This name can be used in place of CES name for some conversion
functions.

 -- Function: ces-guess-from-string string scheme
     Guesses the CES of STRING by the character guessing scheme SCHEME
     (e.g. "*JP").  Returns CES name that can be used by other charconv
     functions.   It may return `#f' if the guessing scheme finds no
     possible encoding in STRING.  Note that if there may be more than
     one possible encoding in STRING, the guessing scheme returns one
     of them, usually in favor of the native CES.


File: gauche-refe.info,  Node: Conversion ports,  Next: Extended port procedures,  Prev: Autodetecting the encoding scheme,  Up: Character code conversion

9.2.3 Conversion ports
----------------------

 -- Function: open-input-conversion-port source from-code &keyword
          to-code buffer-size owner?
     Takes an input port SOURCE, which feeds characters encoded in
     FROM-CODE, and returns another input port, from which you can read
     characters encoded in TO-CODE.

     If TO-CODE is omitted, the native CES is assumed.

     BUFFER-SIZE is used to allocate internal buffer size for
     conversion.  The default size is about 1 kilobytes and it's
     suitable for typical cases.

     If you don't know the SOURCE's CES, you can specify CES guessing
     scheme, such as `"*JP"', in place of FROM-CODE.  The conversion
     port tries to guess the encoding, by prefetching the data from
     SOURCE up to the buffer size.  It signals an error if the code
     guessing routine finds no appropriate CES.  If the guessing
     routine finds ambiguous input, however, it silently assume one of
     possible CES's, in favor of the native CES.  Hence it is possible
     that the guessing is wrong if the buffer size is too small.  The
     default size is usually enough for most text documents, but it may
     fail if the large text contains mostly ASCII characters and
     multibyte characters appear only at the very end of the document.
     To be sure for the worst case, you have to specify the buffer size
     large enough to hold entire text.

     By default, `open-input-conversion-port' leaves SOURCE open.  If
     you specify true value to OWNER?, the function closes SOURCE after
     it reads EOF from the port.

     For example, the following code copies a file `unknown.txt' to a
     file `eucjp.txt', converting unknown japanese CES to EUC-JP.
          (call-with-output-file "eucjp.txt"
            (lambda (out)
              (copy-port (open-input-conversion-port
                           (open-input-file "unknown.txt")
                           "*jp"             ;guess code
                           :to-code "eucjp"
                           :owner? #t)       ;close unknown.txt afterwards
                         out)))

 -- Function: open-output-conversion-port sink to-code &keyword
          from-code buffer-size owner?
     Creates and returns an output port that converts given characters
     from FROM-CODE to TO-CODE and feed to an output port SINK.  If
     FROM-CODE is omitted, the native CES is assumed.  You can't
     specify a character guessing scheme (such as "*JP") to neither
     FROM-CODE nor TO-CODE.

     BUFFER-SIZE specifies the size of internal conversion buffer.  The
     characters put to the returned port may stay in the buffer, until
     the port is explicity flushed (by `flush') or the port is closed.

     By default, the returned port doesn't closes SINK when itself is
     closed.  If a keyword argument OWNER? is provided and true,
     however, it closes SINK when it is closed.

 -- Function: ces-convert string from-code &optional to-code
     Convert STRING's character encoding from FROM-CODE to TO-CODE, and
     returns the converted string.  The returned string may be a
     byte-string if TO-CODE is different from the native CES.

     FROM-CODE can be a name of character guessing scheme (e.g. "*JP").
     when TO-CODE is omitted, the native CES is assumed.

 -- Function: call-with-input-conversion iport proc &keyword encoding
          conversion-buffer-size
 -- Function: call-with-output-conversion oport proc &keyword encoding
          conversion-buffer-size
     These procedures can be used to perform character I/O with
     different encoding temporary from the original port's encoding.

     `call-with-input-conversion' takes an input port IPORT which uses
     the character encoding ENCODING, and calls PROC with one argument,
     a conversion input port.  From the port, PROC can read characters
     in Gauche's internal encoding.  Note that once PROC is called, it
     has to read all the characters until EOF; see the note below.

     `call-with-output-conversion' takes an output port OPORT which
     expects the character encoding ENCODING, and calls PROC with one
     argument, a temporary conversion output port.  To the port, PROC
     can write characters in Gauche's internal encoding.  When PROC
     returns, or it exits with an error, the temporary conversion
     output port is flushed and closed.  The caller of
     `call-with-output-conversion' can continue to use OPORT with
     original encoding afterwards.

     Both procedure returns the value(s) that PROC returns.  The
     default value of ENCODING is Gauche's internal encoding.  Those
     procedures don't create a conversion port when it is not
     necessary.   If CONVERSION-BUFFER-SIZE is given, it is used as the
     BUFFER-SIZE argument when the conversion port is open.

     You shouldn't use IPORT/OPORT directly while PROC is
     active--character encoding is a stateful process, and mixing I/O
     from/to the conversion port and the underlying port will screw up
     the state.

     _Note:_ for the `call-with-input-conversion', you can't use IPORT
     again unless PROC reads EOF from it.  It's because a conversion
     port needs to buffer the input, and there's no way to undo the
     buffered input to IPORT when PROC returns.

 -- Function: with-input-conversion iport thunk &keyword encoding
          conversion-buffer-size
 -- Function: with-output-conversion oport thunk &keyword encoding
          conversion-buffer-size
     Similar to `call-with-*-conversion', but these procedures call
     THUNK without arguments, while the conversion port is set as the
     current input or output port, respectively.  The meaning of
     keyword arguments are the same as `call-with-*-conversion'.

 -- Function: wrap-with-input-conversion port from-code &keyword
          to-code owner? buffer-size
 -- Function: wrap-with-output-conversion port to-code &keyword
          from-code owner? buffer-size
     Convenient procedures to avoid adding unnecessary conversion port.
     Each procedure works like `open-input-conversion-port' and
     `open-output-conversion-port', respectively, except if system
     knows no conversoin is needed, no conversion port is created and
     PORT is returned as is.

     When a conversion port is created, PORT is always owned by the
     port.  When you want to close the port, always close the port
     returned by `wrap-with-*-conversion', instead the original PORT.
     If you close the original PORT first, the pending conversion won't
     be flushed.  (Some conversion requires trailing sequence that is
     generated only when the conversion port is closing, so simply
     calling `flush' isn't enough.)

     The BUFFER-SIZE argument is passed to the `open-*-conversion-port'.


File: gauche-refe.info,  Node: Extended port procedures,  Prev: Conversion ports,  Up: Character code conversion

9.2.4 Extended port procedures
------------------------------

 -- Function: open-input-file filename &keyword encoding
          conversion-buffer-size ...
 -- Function: call-with-input-file filename proc &keyword encoding
          conversion-buffer-size ...
 -- Function: with-input-from-file filename thunk &keyword encoding
          conversion-buffer-size ...
 -- Function: open-output-file filename &keyword encoding
          conversion-buffer-size ...
 -- Function: call-with-output-file filename proc &keyword encoding
          conversion-buffer-size ...
 -- Function: with-output-to-file filename thunk &keyword encoding
          conversion-buffer-size ...
     These Gauche built-in procedures are extended to accept two extra
     keyword arguments, ENCODING and CONVERSION-BUFFER-SIZE.  (*Note
     File ports::, for their default behavior).

     You can give a CES of the file FILENAME to ENCODING, and the port
     automatically converts the file CES to the Gauche's native CES.
     You can use a CES guessing algorithm name for input file port.

     The keyword argument CONVERSION-BUFFER-SIZE has the same meaning
     as BUFFER-SIZE of `open-input-conversion-port'.


File: gauche-refe.info,  Node: Collection framework,  Next: Configuration parameters,  Prev: Character code conversion,  Up: Library modules - Gauche extensions

9.3 `gauche.collection' - Collection framework
==============================================

 -- Module: gauche.collection
     This module provides a set of generic functions (GFs) that iterate
     over various collections.   The Scheme standard [R5RS] has some
     iterative primitives such as `map' and `for-each', and SRFI-1
     (*Note List library:: adds a rich set of such functions, but they
     work only on lists.

     Using the method dispatch of the object system, this module
     efficiently extends those functions for other collection classes
     such as vectors and hash tables.  It also provides a simple way
     for user-defined class to adapt those opertaions.  So far, the
     following operations are defined.

    Mapping
          `fold', `fold2', `fold3', `map', `map-to', `map-accumf,
          '`for-each'

    Selection and searching
          `find', `filter', `filter-to', `remove', `remove-to',
          `partition', `partition-to' `group-collection'

    Conversion
          `coerce-to'

    Miscellaneous
          `size-of', `lazy-size-of'

    Fundamental iterator creator
          `call-with-iterator', `call-with-builder', `with-iterator',
          `with-builder', `call-with-iterators'.

     Those operations work on _collections_ and its subclass,
     _sequences_.  A collection is a certain form of a set of objects
     that you can traverse all the object in it in a certain way.  A
     sequence is a collection that all its elements are ordered, so that
     you can retrieve its element by index.

     The following Gauche built-in objects are treated as collections
     and/or sequences.
    `<list>'
          A sequence.

    `<vector>'
          A sequence.

    `<string>'
          A sequence (of characters)

    `<hash-table>'
          A collection.  Each element is a pair of a key and a value.

    `<s8vector>, <u8vector>, ... <f64vector>'
          A sequence (methods defined in `srfi-4' module, *Note
          Homogeneous vectors::).

     *Note Sequence framework::, for it adds more sequence specific
     methods.

     The methods that needs to return a set of objects, i.e.  `map',
     `filter', `remove' and `partition'.  returns a list (or lists).
     The corresponding "-to" variant (`map-to', `filter-to',
     `remove-to' and `partition-to'.  takes a collection class argument
     and returns the collection of the class.

* Menu:

* Mapping over collection::
* Selection and searching in collection::
* Miscellaneous operations on collection::
* Fundamental iterator creators::
* Implementing collections::


File: gauche-refe.info,  Node: Mapping over collection,  Next: Selection and searching in collection,  Prev: Collection framework,  Up: Collection framework

9.3.1 Mapping over collection
-----------------------------

These generic functions extends the standard mapping procedures.  See
also *Note Mapping over sequences::, if you care the index as well as
elements.

 -- Generic function: fold proc knil coll coll2 ...
     This is a natural extension of FOLD in SRFI-1 (*Note SRFI-1
     Fold::).

     For each element EI in the collection COLL, PROC is called as
     (PROC EI RI-1), where RI-1 is the result of (I-1)-th invocation of
     PROC for I > 0, and R0 is KNIL.  Returns the last invocation of
     PROC.
          (fold + 0 '#(1 2 3 4)) => 10
          (fold cons '() "abc")  => (#\c #\b #\a)

     If the COLL is a sequence, it is guaranteed that the elements are
     traversed in order.  Otherwise, the order of iteration is
     undefined.

     You can fold more than one collection, although it doesn't make
     much sense unless all of the collections are sequences.  Suppose
     E(K, I) for I-th element of K-th collection.  PROC is called as
          (PROC E(0,I) E(1,I) ... E(K-1,I) RI-1)

     Different types of collections can be mixed together.

          (fold acons '() "abc" '#(1 2 3))
            => ((#\c 3) (#\b 2) (#\a 1))

          ;; calculates dot product of two vectors
          (fold (lambda (a b r) (+ (* a b) r)) 0
                '#(3 5 7) '#(2 4 6))
            => 68

     When more than one collection is given, `fold' terminates as soon
     as at least one of the collections exhausted.

 -- Generic function: fold2 proc knil1 knil2 coll coll2 ...
 -- Generic function: fold3 proc knil1 knil2 knil3 coll coll2 ...
     Like `fold', but they can carry two and three state values instead
     of one, respectively.  The state values are initialized by KNILN.
     The procedure PROC is called with each element of COLLN, and the
     state values.  It must return two (`fold2') or three (`fold3')
     values, which will be used as the state values of next iteration.
     The values returned in the last iteration will be the return
     values of `fold2' and `fold3'.

          (fold2 (lambda (elt a b) (values (min elt a) (max elt b)))
                 256 0 '#u8(33 12 142 1 74 98 12 5 99))
           => 1 and 142  ;; find minimum and maximum values

     See also `map-accum' below.

 -- Generic function: map proc coll coll2 ...
     This extends the built-in `map' (*Note Procedures::).  Apply PROC
     for each element in the collection COLL, and returns a list of the
     results.

     If the COLL is a sequence, it is guaranteed that the elements are
     traversed in order.  Otherwise, the order of iteration is
     undefined.

     If more than one collection is passed, PROC is called with
     elements for each collection.  In such case, `map' terminates as
     soon as at least one of the collection is exhausted.  Note that
     passing more than one collection doesn't make much sense unless
     all the collections are sequences.

          (map (lambda (x) (* x 2)) '#(1 2 3))
            => #(2 4 6)

          (map char-upcase "abc")
            => (#\A #\B #\C)

          (map + '#(1 2 3) '#(4 5 6))
            => (5 7 9)

     `map' _always_ returns a list.  If you want to get the result in a
     different type of collection, use `map-to' described below.  If
     you wonder why `(map char-upcase "abc")' doesn't return `"ABC"',
     read the discussion in the bottom of this subsection.

 -- Generic function: map-to class proc coll coll2 ...
     This works the same as `map', except the result is returned in a
     collection of class CLASS.   `Class' must be a collection class
     and have a builder interface (*Note Fundamental iterator
     creators::).

          (map-to <vector> + '#(1 2 3) '#(4 5 6))
            => #(5 7 9)

          (map-to <string> char-upcase "def")
            => "DEF"

          (map-to <vector> char=? "bed" "pet")
            => #(#f #t #f)

 -- Generic function: map-accum proc seed coll1 coll2 ...
     Collects results of PROC over collections, while passing a state
     value.  PROC is called like this:
          (PROC ELT1 ELT2 ... SEED)
     Where ELT1 ELT2 ... are the elements of COLL1 COLL2 ....  It must
     return two values; the first value is collected into a list (like
     `map'), while the second value is passed as SEED to the next call
     of PROC.

     When one of the collections is exhausted, `map-accum' returns two
     values, the list of the first return values from PROC, and the
     second return value of the last call of PROC.

     If the given collections are sequences, it is guaranteed that PROC
     is applied in order of the sequence.

     This is similar to Haskell's `mapAccumL', but note that the order
     of `proc''s argument and return values are reversed.

 -- Generic function: for-each proc coll coll2 ...
     Extension of built-in `for-each' (*Note Procedures::).  Applies
     PROC for each elements in the collection(s).  The result of PROC
     is discarded.  The return value of `for-each' is undefined.

     If the COLL is a sequence, it is guaranteed that the elements are
     traversed in order.  Otherwise, the order of iteration is
     undefined.

     If more than one collection is passed, PROC is called with
     elements for each collection.  In such case, `for-each' terminates
     as soon as one of the collection is exhausted.  Note that passing
     more than one collection doesn't make much sense unless all the
     collections are sequences.

 -- Generic Function: fold$ proc
 -- Generic Function: fold$ proc knil
 -- Generic Function: map$ proc
 -- Generic Function: for-each$ proc
     Partial-application version of `fold', `map' and `for-each'.

   _Discussion:_  It is debatable what type of collection `map' should
return when it operates on the collections other than lists.  It may
seem more "natural" if `(map * '#(1 2) '#(3 4))' returns a vector, and
`(map char-upcase "abc")' returns a string.

   Although such interface seems work for simple cases, it'll become
problematic for more general cases.  What type of collection should be
returned if a string and a vector are passed?  Furthermore, some
collection may only have iterator interface but no builder interface,
so that the result can't be coerced to the argument type (suppose
you're mapping over database records, for example).  And Scheme
programmers are used to think `map' returns a list, and the result of
`map' are applied to the procedures that takes list everywhere.

   So I decided to add another method, `map-to', to specify the return
type explicitly The idea of passing the return type is taken from
CommonLisp's `map' function, but taking a class metaobject, `map-to' is
much flexible to extend using method dispatch.  This protocol ("-to"
variant takes a class metaobject for the result collection) is used
thoughout the collection framework.


File: gauche-refe.info,  Node: Selection and searching in collection,  Next: Miscellaneous operations on collection,  Prev: Mapping over collection,  Up: Collection framework

9.3.2 Selection and searching in collection
-------------------------------------------

 -- Generic function: find pred coll
     Applies PRED for each element of a collection COLL until PRED
     returns a true value.  Returns the element on which PRED returned
     a true value, or `#f' if no element satisfies PRED.

     If COLL is a sequence, it is guaranteed that PRED is applied in
     order.  Otherwise the order of application is undefined.  Returns
     a list of elements of collection COLL that satisfies the predicate
     PRED.   If the collection is a sequence, the order is preserved in
     the result.

          (filter char-upper-case? "Hello, World")
            => (#\H #\W)
          (filter even? '#(1 2 3 4)) => (2 4)

 -- Generic function: filter-to class pred coll
     Same as `filter', but the result is returned as a collection of
     class CLASS.

          (filter-to <vector> even? '#(1 2 3 4)) => #(2 4)
          (filter-to <string> char-upper-case? "Hello, World")
            => "HW"

 -- Generic function: remove pred coll
     Returns a list of elements of collection COLL that does not
     satisfy the predicate PRED.   If the collection is a sequence, the
     order is preserved in the result.

          (remove char-upper-case? "Hello, World")
            => (#\e #\l #\l #\o #\, #\space #\o #\r #\l #\d)
          (remove even? '#(1 2 3 4)) => (1 3)

 -- Generic function: remove-to class pred coll
     Same as `remove', but the result is returned as a collection of
     class CLASS.

          (remove-to <vector> even? '#(1 2 3 4)) => #(1 3)
          (remove-to <string> char-upper-case? "Hello, World")
            => "ello, orld"

 -- Generic function: partition pred coll
     Does `filter' and `remove' the same time.  Returns two lists, the
     first consists of elements of the collection COLL that satisfies
     the predicate PRED, and the second consists of elements that
     doesn't.

          (partition char-upper-case? "PuPu")
            => (#\P #\P) and (#\u #\u)
          (partition even? '#(1 2 3 4))
            => (2 4) and (1 3)

 -- Generic function: partition-to class pred coll
     Same as `partition', except the results are returned in the
     collections of class CLASS.

          (partition-to <string> char-upper-case? "PuPu")
            => "PP" and "uu"
          (partition-to <vector> even? '#(1 2 3 4))
            => #(2 4) and #(1 3)

 -- Generic function: group-collection coll &keyword key test
     Generalized `partition'.  Groups elements in COLL into those who
     has the same key value, and returns the groups as of lists.  Key
     values are calculated by applying the procedure KEY to each
     element of COLL.  The default value of KEY is `identity'.   For
     each element of COLL, KEY is applied exactly once.  The equal-ness
     of keys are compared by TEST procedure, whose default is `eqv?'.

     If COLL is a sequence, then the order of elements in each group of
     the result is the same order in COLL.

          (group-collection '(1 2 3 2 3 1 2 1 2 3 2 3))
            => ((1 1 1) (2 2 2 2 2) (3 3 3 3))

          (group-collection '(1 2 3 2 3 1 2 1 2 3 2 3) :key odd?)
            => ((1 3 3 1 1 3 3) (2 2 2 2 2))

          (group-collection '(("a" 2) ("b" 5) ("c" 1) ("b" 3) ("a" 6))
            :key car :test string=?)
            => ((("a" 2) ("a" 6)) (("b" 5) ("b" 3)) (("c" 1)))

     See also `group-sequence' in `gauche.sequence' (*Note Selection
     and searching in sequence::), which only groups adjacent elements.


File: gauche-refe.info,  Node: Miscellaneous operations on collection,  Next: Fundamental iterator creators,  Prev: Selection and searching in collection,  Up: Collection framework

9.3.3 Miscellaneous operations on collection
--------------------------------------------

 -- Generic function: size-of coll
     Returns the number of elements in the collection.  Default method
     iterates over the collection to calculate the size, which is not
     very efficient and may diverge if the collection is infinite.
     Some collection classes overload the method for faster calculation.

 -- Generic function: lazy-size-of coll
     Returns either the size of the collection, or a promise to
     calculate it.  The intent of this method is to avoid size
     calculation if it is expensive.  In some cases, the caller wants
     to have size just for optimization, and it is not desirable to
     spend time to calculate the size.  Such caller uses this method
     and just discards the information if it is a promise.

 -- Generic function: coerce-to class coll
     Convert a collection COLL to another collection which is an
     instance of CLASS.  If COLL is a sequence and CLASS is a sequence
     class, the order is preserved.

          (coerce-to <vector> '(1 2 3 4))
            => #(1 2 3 4)

          (coerce-to <string> '#(#\a #\b #\c))
            => "abc"


File: gauche-refe.info,  Node: Fundamental iterator creators,  Next: Implementing collections,  Prev: Miscellaneous operations on collection,  Up: Collection framework

9.3.4 Fundamental iterator creators
-----------------------------------

These are fundamental methods on which all the rest of iterative method
are built.  The method interface is not intended to be called from
general code, but suitable for building other iterator construct.   The
reason why I chose this interface as fundamental methods are explained
at the bottom of this subsection.

 -- Generic function: call-with-iterator collection proc &keyword start
     A fundamental iterator creator.   This creates two procedures from
     COLLECTION, both take no argument, and then call PROC with those
     two procedures.   The first procedure is terminate predicate,
     which returns `#t' if the iteration is exhausted, or `#f' if there
     are still elements to be visited.  The second procedure is an
     incrementer, which returns one element from the collection and
     sets the internal pointer to the next element.  The behavior is
     undefined if you call the incrementer after the terminate
     predicate returns `#t'.

     If the collection is actually a sequence, the incrementer is
     guaranteed to return elements in order, from 0-th element to the
     last element.  If a keyword argument START is given, however, the
     iteration begins from START-th element and ends at the last
     element.  If the collection is not a sequence, the iteration order
     is arbtrary, and START argument has no effect.

     An implementation of CALL-WITH-ITERATOR method may limit the
     extent of the iterator inside the dynamic scope of the method.
     For example, it allocates some resource (e.g. connect to a
     database) before calling PROC, and deallocates it (e.g. disconnect
     from a database) after PROC returns.

     This method returns the value(s) PROC returns.

          (call-with-iterator '(1 2 3 4 5)
            (lambda (end? next)
              (do ((odd-nums 0))
                  ((end?) odd-nums)
                (when (odd? (next)) (inc! odd-nums)))))
           => 3

     See also `with-iterator' macro below, for it is easier to use.

 -- Macro: with-iterator (collection end? next args ...) body ...
     A convenience macro to call `call-with-iterator'.
          (with-iterator (coll end? next args ...) body ...)
           ==
          (call-with-iterator coll
            (lambda (end? next) body ...)
             args ...)

 -- Function: call-with-iterators collections proc
     A helper function to write n-ary iterator method.  This function
     applies `call-with-iterator' for each COLLECTIONs, and makes two
     lists, the first consists of terminate predicates and the second
     of incrementers.  Then PROC is called with those two lists.
     Returns whatever PROC returns.

 -- Generic function: call-with-builder collection-class proc &keyword
          size
     A fundamental builder creator.  Builder is a way to construct a
     collection incrementally.  Not all collection classes provide this
     method.

     COLLECTION-CLASS is a class of the collection to be built.  This
     method creates two procedures, adder and getter, then calls PROC
     with those procedures.  Adder procedure takes one argument and
     adds it to the collection being built.  Getter takes no argument
     and returns a built collection object.  The effect is undefined if
     adder is called after getter is called.

     A keyword argument SIZE may be specified if the size of the result
     collection is known.  Certain collections may be built much more
     efficiently if the size is known; other collections may just
     ignore it.   The behavior is undefined if more than SIZE elements
     are added, or the collection is retrieved before SIZE elements are
     accumulated.

     If the collection class is actually a sequence class, adder is
     guaranteed to add elements in order.  Otherwise, the order of
     elements are insignificant.

     Some collection class may take more keyword arguments to
     initialize the collection.

     This method returns the value(s) PROC returned.

          (call-with-builder <list>
            (lambda (add! get)
              (add! 'a) (add! 'b) (add! 'c) (get)))
           => (a b c)

          (call-with-builder <vector>
            (lambda (add! get)
              (add! 'a) (add! 'b) (add! 'c) (get)))
           => #(a b c)

     See also `with-builder' macro below, for it is much easier to use.

 -- Macro: with-builder (collection add! get args ...) body ...
     A convenience macro to call `call-with-builder'.
          (with-builder (coll add! get args ...) body ...)
           ==
          (call-with-builder coll
            (lambda (add! get) body ...)
            args ...)

   _Discussion_: Other iterator methods are built on top of
call-with-iterator and call-with-builder.  By implementing those
methods, you can easily adapt your own collection class to all of those
iterative operations.   Optionally you can overload some of higher-level
methods for efficiency.

   It is debatable that which set of operations should be primitives.
I chose call-with-iterator style for efficiency of the applications I
see most.   The following is a discussion of other possible primitive
iterators.

`fold'
     It is possible to make `fold' a primitive method, and build other
     iterator method on top of it.  Collection-specific iterating
     states can be kept in the stack of `fold', thus it runs
     efficiently.  The method to optimize a procedure that uses `fold'
     as a basic iterator construct.  However, it is rather cumbersome
     to derive generator-style interface from it.   It is also tricky
     to iterate irregulary over more than one collections.

CPS
     Passes iteratee the continuation procedure that continues the
     iteration.   The iteratee just returns when it want to terminate
     the iteration.  It has resource management problem described in
     Oleg Kiselyov's article (*Note OLEG2: oleg2.).

Iterator object
     Like C++ iterator or Common Lisp generator.  Easy to write loop.
     The problem is that every call of checking termination or getting
     next element must be dispatched.

Series
     Common Lisp's series can be very efficient if the compiler can
     statically analyze the usage of series.  Unfortunately it is not
     the case in Gauche.  Even if it could, the extension mechanism
     doesn't blend well with Gauche's object system.

Macros
     Iterator can be implemented as macros, and that will be very
     efficient; e.g. Scheme48's iterator macro.  It uses macros to
     extend, however, and that doesn't blend well with Gauche's object
     system.

   The current implementation is close to the iterator object approach,
but using closures instead of iterator objects so that avoiding
dispatching in the inner loop.  Also it allows the iterator
implementator to take care of the resource problem.


File: gauche-refe.info,  Node: Implementing collections,  Prev: Fundamental iterator creators,  Up: Collection framework

9.3.5 Implementing collections
------------------------------

The minimum requirements of the collection class implementation is as
follow:
   * The class inherits `<collection>' abstract class.

   * A method `call-with-iterator' is implemented.

   This makes iterator methods such as `map', `for-each', `find' and
`filter' to work.

   In order to make the constructive methods (e.g. `map-to' to create
your collection), you have to implement `call-with-builder' method as
well.  Note that `call-with-builder' method must work a sort of class
method, dispatched by class, rather than normal method dispatched by
instance.   In Gauche, you can implement it by using a metaclass.
Then the minimal code will look like this:

     (define-class <your-collection-meta> (<class>) ())

     (define-class <your-collection> (<collection>)
      (...) ;; slots
      :metaclass <your-collection-meta>)

     (define-method call-with-iterator
         ((coll <your-collection>) proc . options)
       ...
       )

     (define-method call-with-builder
          ((coll <your-collection-meta>) proc . options)
       ...
       )

   Optionally, you can overload other generic functions to optimize
performance.


File: gauche-refe.info,  Node: Configuration parameters,  Next: Low-level file operations,  Prev: Collection framework,  Up: Library modules - Gauche extensions

9.4 `gauche.config' - Configuration parameters
==============================================

 -- Module: gauche.config
     This module provides a simple wrapper to obtain configuration
     parameters via `gauche-config' program.

     The `gauche-config' program is a simple shell script that records
     various parameters given at the configuration time of Gauche.

 -- Function: gauche-config option
     Calls `gauche-config' with the option OPTION, and returns the
     string of the parameter value.  It is an error to give the option
     gauche-config doesn't understand.

     See the manpage of `gauche-config', or run `gauche-config' without
     any argument from the shell, to find out the valid options.
          (gauche-config "--cc")
            => "gcc"
          (gauche-config "-L")
            => "-L/usr/lib/gauche/0.6.5/i686-pc-linux-gnu"
          (gauche-config "-l")
            => "-ldl -lcrypt -lm -lpthread"


File: gauche-refe.info,  Node: Low-level file operations,  Next: Hooks,  Prev: Configuration parameters,  Up: Library modules - Gauche extensions

9.5 `gauche.fcntl' - Low-level file operations
==============================================

 -- Module: gauche.fcntl
     Provides an interface to `fcntl(2)', including advisory file
     locking.

 -- Function: sys-fcntl port-or-fd operation &optional arg
     Performs certain operation on the file specfied by PORT-OR-FD,
     which should be a port object or an integer that specifies a
     system file descriptor.  If it is a port, it must be associated to
     the opened file (i.e. `port-type' returns `file', see *Note Common
     port operations::).

     The operation is specified by an integer OPERATION.  Several
     variables are defined for valid OPERATION.

    `F_GETFD'
          Returns flags associated to the file descriptor of PORT-OR-FD.
          The optional argument ARG is not used.   The return value is
          an integer whose definition is system specific, except one
          flag, `FD_CLOEXEC', which indicates the file descriptor
          should be closed on `exec'.  See the manual entry of
          `fcntl(2)' of your system for the details.

    `F_SETFD'
          Sets the file descriptor flags given as ARG to PORT-OR-FD.
          For example, the portable way of setting `FL_CLOEXEC' flag is
          as follows:
               (sys-fcntl port F_SETFD
                         (logior FD_CLOEXEC
                                 (sys-fcntl port F_GETFD)))

    `F_GETFL'
          Returns flags associated to the open files specified by
          PORT-OR-FD.  The flags includes the following information:

             * File access mode.  When masked by `O_ACCMODE', it's
               either one of `O_RDONLY', `O_WRONLY' or `O_RDWR'.

             * File creation options.  `O_CREAT', `O_EXCL' and/or
               `O_TRUNC'.

             * Whether appending is allowed or not, by `O_APPEND'

             * Whether I/O is blocking or non-blocking, by `O_NONBLOCK'.

             * Whether it grabs terminal control, by `O_NOCTTY'.

          The system may define system-specific flags.

    `F_SETFL'
          Sets flags to the open files specified by PORT-OR-FD.  Among
          the flags listed above, only `O_NONBLOCK' and `O_APPEND' can
          be changed.

          Note that `F_GETFD'/`F_SETFD' concern flags associated to the
          file descriptor itself, while `F_GETFL'/`F_SETFL' concern
          flags associated to the opened file itself.  This makes
          difference when more than one file descriptor points to the
          same opened file.

    `F_DUPFD'
          Creates new file descriptor that points to the same file
          referred by PORT-OR-FD.  An integer must be provided as ARG,
          and that specifies the minimum value of file descriptor to be
          assigned.

    `F_GETLK'
          The third argument must be provided and be an instance of
          `<sys-flock>' object described below.  It searches the lock
          information specified by ARG, and modifies ARG accordingly.

    `F_SETLK'
    `F_SETLKW'
          The third argument must be provided and be an instance of
          `<sys-flock>' object described below.  Sets the advisory file
          lock according to ARG.   If the lock is successfully
          obtained, `#t' is returned.  If the other process has the
          lock conflicting the request, `F_SETLK' returns `#f', while
          `F_SETLKW' waits until the lock is available.

    `F_GETOWN'
          Returns the process id or process group that will receive
          SIGIO and SIGURG signals for events on the file descriptor.
          Process group is indicated by a negative value.  This flag is
          only available on the systems that has this feature (BSD and
          Linux have this).

    `F_SETOWN'
          Sets the process id or process group that will receive SIGIO
          and SIGURG signals for events on the file descriptor.
          Process group is indicated by a negative value.  This flag is
          only available on the systems that has this feature (BSD and
          Linux have this).  Check out fcntl(2) manpage of your system
          for the details.


     Other value for OPERATION causes an error.

 -- Builtin Class: <sys-flock>
     A structure represents POSIX advisory record locking.  Advisory
     record locking means the system may not prevents the process from
     operating on files that it doesn't have an appropriate lock.  All
     the processes are expected to use `fcntl' to check locks before it
     operates on the files that may be shared.

     The following slots are defined.

      -- Instance Variable of <sys-flock>: type
          An integer represents lock type.  Following variables are
          predefined for the valid values:

         `F_RDLCK'
               Read locking

         `F_WRLCK'
               Write locking

         `F_UNLCK'
               To remove a lock by `F_SETLK', or to indicate the record
               is not locked by `F_GETLK'.

      -- Instance Variable of <sys-flock>: whence
          Indicates from where `start' is measured.

      -- Instance Variable of <sys-flock>: start
          The offset of beginning of the locked region.

      -- Instance Variable of <sys-flock>: len
          The number of bytes to lock.  Zero means "until EOF".

      -- Instance Variable of <sys-flock>: pid
          An integer process id that holding the lock; used only by
          `F_GETLK'.


File: gauche-refe.info,  Node: Hooks,  Next: Interactive session,  Prev: Low-level file operations,  Up: Library modules - Gauche extensions

9.6 `gauche.hook' - Hooks
=========================

 -- Module: gauche.hook
     Provides a hook object, which manages a list of closures to be
     called at certain time.

     This API of hooks are upper-compatible of Guile's, with the
     following extensions.
        * Based on Gauche's object system.  Most APIs are methods so
          you can extend the hook features.

        * Hook object itself is applicable.  You don't need to use
          `run-hook'.

        * The method to remove a procedure from a hook is called
          `delete-hook!', for consistency with SRFI-1 and others.
          `remove-hook!' is defined as an alias of `delete-hook!' for
          compability with Guile.

 -- Class: <hook>
     A hook class, which keeps a list of procedures to be called at
     once.

     The `object-apply' method is defined on `<hook>' class, so you can
     "apply" a hook object as if it were a procedure--which causes all
     the registered procedure to be invoked.

 -- Function: make-hook &optional (arity 0)
     Creates a new hook object with given arity, which should be a
     non-negative integer.

 -- Function: hook? obj
     Returns true if OBJ is a hook object.

 -- Function: hook-empty? hook
     Returns true if HOOK's procedure list is empty.

 -- Method: add-hook! (hook <hook>) proc &optional (append? #f)
     Adds a procedure PROC to HOOK.  If APPEND?  is given and true,
     PROC is added at the end of the list.  Otherwise, PROC is added at
     the front of the list.  The PROC has to be called with the arity
     given at the `make-hook'.

 -- Method: delete-hook! (hook <hook>) proc
 -- Method: remove-hook! (hook <hook>) proc
     Removes PROC from the procedure list of HOOK.  `Remove-hook!' is
     an alias of `delete-hook!' just for compability with Guile.

 -- Method: reset-hook! (hook <hook>)
     Empties HOOK's procedure list.

 -- Method: hook->list (hook <hook>)
     Returns a copy of HOOK's procedure list.

 -- Method: run-hook (hook <hook>) arg ...
     Calls HOOK's procedures in order, with arguments ARG ....  The
     number of arguments must match the arity given at `make-hook'.


File: gauche-refe.info,  Node: Interactive session,  Next: Listener,  Prev: Hooks,  Up: Library modules - Gauche extensions

9.7 `gauche.interactive' - Utilities for interactive session
============================================================

 -- Module: gauche.interactive
     Provides useful utilities for the interactive session.

     This module is automatically loaded when you run `gosh'
     interactively.

     This module also sets autoloads for functions defined in
     `gauche.reload' module (see *Note Reloading modules::), so that
     those functions can be used by default in interactive development.

 -- Macro: apropos pattern &optional module
     Show a list of defined variables whose name matches PATTERN.  If
     you give a module or a module name MODULE, only the variables
     defined in that module are listed.  Without MODULE, the variables
     "visible" from the current module are listed.

     PATTERN may be a symbol or a regexp object.  If it is a symbol,
     the variables whose name contains the substring that matches the
     symbol's name are listed.  If it is a regexp object, the variables
     whose name matches the regexp are listed.

     Some examples:
          ;; List variables that contains "string" in their name
          (apropos 'string)

          ;; Search in srfi-14 module
          (apropos 'char 'srfi-14)

 -- Generic Function: describe obj
 -- Generic Function: d obj
     Prints the detail information about a Scheme object OBJ.  The
     default method shows OBJ's class, and if it has any slots, the
     list of slot names and their values.  You can specialize this
     method for customized display.

 -- Function: info symbol
     Displays a page of Gauche's info file that contains definition of
     the function or syntax specified by SYMBOL.  If an environment
     variable `INFOPATH' is defined, this function searches for the
     info file from the directories in it.  Otherwise, this function
     guesses info file location from the `gosh''s library directory.
     If the info file can't be found, an error is signalled.   If the
     info file is found, but SYMBOL is not in its index, an error is
     signalled as well.  So this function doesn't work if you haven't
     installed info file.

     If the current output port is a tty, the info page is displayed by
     a paging software.  If an environment variable `PAGER' is defined,
     it is used as a paging software.  Otherwise, this function looks
     for `less' and `more' in this order from the directories in
     `PATH'.  If none of them is found, or the output port is not a
     tty, this function just displays the page.

     The first invocation of this function in a session takes some time
     to parse the info file.


File: gauche-refe.info,  Node: Listener,  Next: User-level logging,  Prev: Interactive session,  Up: Library modules - Gauche extensions

9.8 `gauche.listener' - Listener
================================

 -- Module: gauche.listener
     This module provides a convenient way to enable multiple
     read-eval-print loop (repl) concurrently.

     An obvious way to run multiple repls is to use threads; creating
     as many threads as sessions and calling `read-eval-print-loop'
     (*Note Eval and repl::) from each thread.  Nevertheless, sometimes
     single threaded implementation is preferred.  For instance, you're
     using a library which is not MT-safe, or your application already
     uses select/poll-based dispatching mechanism.

     To implement repl in the single-threaded selection-base
     application, usually you register a handler that is called when
     data is available in the listening port.  The handler reads the
     data and add them into a buffer.  Then it examines if the data in
     the buffer consists a complete expression, and if so, it reads the
     expression from the buffer, evaluates it, then prints the result
     to the reporting port.  The `<listener>' class in this module
     provides this handler mechanism, so all you need to do is to
     register the handler to your dispatching mechanism.

     Note: it may also be desirable to buffer the output sometimes, but
     the current version doesn't implement it.

 -- Class: <listener>
     An object that maintains the state of a repl session.  It has many
     external slots to customize its behavior.  Those slot values can
     be set at construction time by using the keyword of the same name
     as the slot, or can be set by `slot-set!' afterwards.  However,
     most of them should be set before calling `listener-read-hander'.

      -- Instance Variable of <listener>: input-port
          Specifies the input port from which the listener get the
          input.  The default value is the current input port when the
          object is constructed.

      -- Instance Variable of <listener>: output-port
          Specifies the output port to which the listener output will
          go.  The default value is the current output port when the
          object is constructed.

      -- Instance Variable of <listener>: error-port
          Specifies the output port to which the listener's error
          messages will go.  The default value is the current error
          port when the object is constructed.

      -- Instance Variable of <listener>: reader
          A procedure with no arguments.  It should read a Scheme
          expression from the current input port when called.  The
          default value is system's `read' procedure.

      -- Instance Variable of <listener>: evaluator
          A procedure that takes two arguments, a Scheme expression and
          an environment specifier.  It should evaluate the expression
          in the given environment and returns zero or more value(s).
          The default value is system's `eval' procedure.

      -- Instance Variable of <listener>: printer
          A procedure that takes zero or more argument(s) and prints
          them out to the current output port.  The default value is a
          procedure that prints each value by `write', followed by a
          newline.

      -- Instance Variable of <listener>: prompter
          A procedure with no arguments.  It should prints a prompt to
          the current output port.  The output is flushed by the
          listener object so this procedure doesn't need to care about
          it.  The default procedure prints `"listener> "'.

      -- Instance Variable of <listener>: environment
          An environment specifier where the expressions will be
          evaluated.  The default value is the value returned by
          `(interaction-environment)'.

      -- Instance Variable of <listener>: finalizer
          A thunk that will be called when EOF is read from
          `input-port'.  It can be `#f' if no such procedure is needed.
          The default value is `#f'.

      -- Instance Variable of <listener>: error-handler
          A procedure that takes one argument, an error exception.  It
          is called when an error occurs during read-eval-print stage,
          with the same dynamic environment as the error is signalled.
          The default value is a procedure that simply prints the error
          exception by `report-error'.

 -- Method: listener-read-handler (listener <listener>)
     Returns a thunk that is to be called when a data is available from
     `input-port' of the listener.

     The returned thunk (read handler) does the following steps.  Note
     that the first prompt is _not_ printed by this procedure.  See
     `listener-show-prompt' below.
       1. Reads available data from `input-port' and appends it to the
          listener's internal buffer.

       2. Scans the buffer to see if it has a complete S-expression.
          If not, returns.

       3. Reads the S-expression from the buffer.  The read data is
          removed from the buffer.

       4. Evaluates the S-expression, then prints the result to
          `output-port'.

       5. Prints the prompt by prompter procedure to `output-port',
          then flush `output-port'.

       6. Repeats from 2.

 -- Method: listener-show-prompt (listener <listener>)
     Shows a prompt to the listener's output port, by using listener's
     prompter procedure.  Usually you want to use this procedure to
     print the first prompt, for instance, when the client is connected
     to the listener socket.

 -- Function: complete-sexp? str
     Returns `#t' if STR contains a complete S-expression.  This
     utility procedure is exported as well, since it might be useful
     for other purposes.

     Note that this procedure only checks syntax of the expressions,
     and doesn't rule out erroneous expressions (such as containing
     invalid character name, unregistered SRFI-10 tag, etc.).  This
     procedure may raise an error if the input contains '`#<''
     character sequence.

   The following code snippet opens a server socket, and opens a Scheme
interactive session when a client is connected.  (Note: this code is
just for demonstration.  Do not run this program on the machine
accessible from outside network!)

     (use gauche.net)
     (use gauche.selector)
     (use gauche.listener)

     (define (scheme-server port)
       (let ((selector (make <selector>))
             (server   (make-server-socket 'inet port :reuse-addr? #t))
             (cid      0))

         (define (accept-handler sock flag)
           (let* ((client (socket-accept server))
                  (id     cid)
                  (input  (socket-input-port client :buffering :none))
                  (output (socket-output-port client))
                  (finalize (lambda ()
                              (selector-delete! selector input #f #f)
                              (socket-close client)
                              (format #t "client #~a disconnected\n" id)))
                  (listener (make <listener>
                              :input-port input
                              :output-port output
                              :error-port output
                              :prompter (lambda () (format #t "client[~a]> " id))
                              :finalizer finalize))
                  (handler (listener-read-handler listener))
                  )
             (format #t "client #~a from ~a\n" cid (socket-address client))
             (inc! cid)
             (listener-show-prompt listener)
             (selector-add! selector input (lambda _ (handler)) '(r))))

         (selector-add! selector
                        (socket-fd server)
                        accept-handler
                        '(r))
         (format #t "scheme server started on port ~s\n" port)
         (do () (#f) (selector-select selector))))


File: gauche-refe.info,  Node: User-level logging,  Next: Singleton,  Prev: Listener,  Up: Library modules - Gauche extensions

9.9 `gauche.logger' - User-level logging
========================================

 -- Module: gauche.logger
     Provides a simple interface to log the program's activity.  The
     information can be written to the specified file, or to the system
     logger using `syslog(3)'.  When a file is used, syslog-like prefix
     string is added to each message, which is configurable.  It can
     also takes care of locking of the file (see the description of
     `lock-policy' below).

 -- Class: <log-drain>
     Represents the destination of log messages.  There's one implicit
     global `<log-drain>' instance, which is used by default.  However,
     you can create as many instances by `make' method as you want, in
     case if you want to log to more than one destination.

      -- Instance Variable of <log-drain>: path
          Path of the log file.  It can be also `#t', which means the
          current error port, or `#f', which makes `log-format' to
          return the formatted message but not write to any log files,
          or a symbol `syslog', which means the messages are sent to
          the system logger.

          By default, this slot is `#f'.

      -- Instance Variable of <log-drain>: prefix
          Specifies the prefix string that is attached to the beginning
          of every message.  If the message spans to several lines, the
          prefix is attached to each line.   The value of this slot can
          also be a procedure that takes `<log-drain>' object and
          returns a string to be used as the prefix.  The procedure is
          called every time prefix is needed.

          When the `path' slot is a symbol `syslog', the value of this
          slot is ignored.  System logger will attach an appropriate
          prefix.

          When the value of the prefix slot is a string, the following
          character sequences have special meanings and replaced by
          `log-format' for appropriate information when written out.

         `~T'
               Current time, in the format of "Mmm DD hh:mm:ss" where
               "Mmm" is an abbreviated month, "DD" is the day of month,
               "hh", "mm" and "ss" are hours (in 24 hour basis),
               minutes and seconds, respectively.  This format is
               compatible with system logs.

         `~Y'
               Current 4-digit year.

         `~P'
               The program name.  The default value is the basename of
               `*program-name*' (*Note Writing Scheme scripts::), but
               you can change it by the `program-name' slot described
               below.

         `~$'
               The process id of this program.

         `~U'
               The name of the effective user of the process.

         `~H'
               The hostname the process is running.

          The default value of this slot is "`~T ~P[~$]: '".  For
          example, if a string "this is a log message.\nline 2\nline 3"
          is given as the message, it produces something like the
          following log entry.

               Sep  1 17:30:23 myprogram[441]: this is a log message
               Sep  1 17:30:23 myprogram[441]: line 2
               Sep  1 17:30:23 myprogram[441]: line 3


      -- Instance Variable of <log-drain>: program-name
          Specifies the program name written by `~P' directive of the
          prefix slot.

      -- Instance Variable of <log-drain>: lock-policy
          Specifies the way the log file should be locked.  If the
          value of this slot is a symbol `fcntl', the log file is
          locked using fcntl() (*Note Low-level file operations::).  If
          the value is a symbol `file', the log file is locked by
          creating auxiliary lock file, whose name is generated by
          appending ".lock" after the log file path.  The logging
          process needs a write permission to the log file directory.
          Note that if the process is killed forcibly during writing the
          log file, a stale lock file may remain.  `Log-format'
          silently removes the lock file if it is unusually old
          (currently 10 minutes).  If the value is `#f', no locking is
          performed.

          The default value is `fcntl', except MacOSX which doesn't
          support fcntl()-style locking and thus `file' is default.

          The locking isn't performed if the destination is not a file.

      -- Instance Variable of <log-drain>: syslog-option
      -- Instance Variable of <log-drain>: syslog-facility
      -- Instance Variable of <log-drain>: syslog-priority
          The value of these slots are used when the destination of the
          drain is the system logger.   *Note Syslog::, for the
          detailed information about these values.  The default values
          of these slots are `LOG_PID', `LOG_USER' and `LOG_INFO',
          respectively.

 -- Function: log-open path &keyword prefix program-name
     Sets the destination of the default log message to the path PATH.
     It can be a string or a boolean, as described above.  You can also
     set prefix and program name by corresponding keyword arguments.

     Despite its name, this function doesn't open the specified file
     immediately.  The file is opened and closed every time `log-format'
     is called.

 -- Method: log-format (format <string>) arg ...
 -- Method: log-format (drain <log-drain>) (format <string>) arg ...
     Formats a log message by FORMAT and ARG ..., by using `format'
     (*Note Output::).    In the first form, the output goes to the
     default destination.  In the second form, the output goes to the
     specfied drain.

     The file is opened and closed every time.  You can safely move the
     log file while your program that touches the log file is running.
     Also `log-format' acquires a write lock of the log file by
     `sys-fcntl' (*Note Low-level file operations::).

     If the first form of `log-format' is called before `log-open' is
     called, `log-format' does nothing.  It is useful to embed debug
     stubs in your code; once your code is past the debugging stage,
     you just comment out `log-open' and the code runs without logging.


File: gauche-refe.info,  Node: Singleton,  Next: Slot with validator,  Prev: User-level logging,  Up: Library modules - Gauche extensions

9.10 `gauche.mop.singleton' - Singleton
=======================================

 -- Module: gauche.mop.singleton
     Provides a metaclass to define a singleton class.

 -- Class: <singleton-meta>
     Creates a singleton class.  A singleton class is a class that is
     guaranteed to create only one instance.  The first invocation of
     `make' creates the single instance, and further attempt of
     creation returns the same instance.
          (define-class single () () :metaclass <singleton-meta>)

          (define a (make single))
          (define b (make single))

          (eq? a b) => #t

     The slots of the instance are initialized at the first invocation
     of `make'.  Initargs of `make' are effective only in the fist
     invocation, and ignored in the subsequent invocation.

 -- Method: instance-of (class <singleton-meta>) &rest initargs
     This method just calls `make' with the passed arguments.  It is
     more obvious in the program that you're dealing with singleton.

 -- Class: <singleton-mixin>
     An instance of `<singleton-meta>'.  Instead of specifying
     `<singleton-meta>' as the `:metaclass' argument of `define-class',
     you can inherit this class to give your class the property of
     singleton.


File: gauche-refe.info,  Node: Slot with validator,  Next: Networking,  Prev: Singleton,  Up: Library modules - Gauche extensions

9.11 `gauche.mop.validator' - Slot with validator
=================================================

 -- Module: gauche.mop.validator
     Provides a metaclass that adds `:validator' slot option.

 -- Class: <validator-meta>
     This metaclass adds a feature that the class can validate a value
     before being set to the slot.   For example, if you want to
     guarantee that a certain slot always holds a string value, you can
     make a procedure be called before the slot is modified, either by
     `slot-ref' or by a setter method.  In the procedure you can either
     rejects a value except string, or coerce the value to a string.

     The validator procedure can be set per each slot by using
     `:validator' slot option.  The procedure takes two values, the
     instance and the value to be set.  Whatever the procedure returns
     is set to the actual slot value.  See the following example:

          (define-class <v> ()
            ((a :accessor a-of
                :validator (lambda (obj value) (x->string value)))
             (b :accessor b-of
                :validator (lambda (obj value)
                             (if (integer? value)
                                 value
                                 (error "integer required for slot b")))))
            :metaclass <validator-meta>)

          (define v (make <v>))
          (slot-set! v 'a 'foo)
          (slot-ref v 'a) => "foo"

          (set! (a-of v) 1234)
          (a-of v) => "1234"

          (slot-set! v 'b 55)
          (slot-ref v 'b) => 55

          (slot-set! v 'b 3.4) => error
          (set! (b-of v) 3.4)  => error

     You can specify default slot value (`:init-value' etc.) with
     `:validator'.  In that case, the initialization method of the
     instance calls the validator with the specified default value, if
     :init-keyword is not given.

          (define-class <v> ()
            ((a :initform 'foo :init-keyword :a
                :validator (lambda (obj value) (x->string value)))))

          (slot-ref (make <v>) 'a)        => "foo"
          (slot-ref (make <v> :a 555) 'a) => "555"

     It looks similar to the virtual slot, but note that a slot with
     validator has an actual storage in the instance, while a virtual
     slot doesn't.

     It is also a good example of customizing how the slots are accessed
     using the metaobject protocol.  This feature is implemented by
     only couple of dozen lines of code.


File: gauche-refe.info,  Node: Networking,  Next: Parameters,  Prev: Slot with validator,  Up: Library modules - Gauche extensions

9.12 `gauche.net' - Networking
==============================

 -- Module: gauche.net
     Provides a set of functions necessary for network communications
     based on BSD socket interface.

     The API is provided in two different levels.  Lower level routines
     reflect traditional BSD socket interface, such as `bind(2)'.
     Higher level routines provides more convenient way to create
     typical connection-oriented server/client sockets.

     This module also provides APIs to obtain various information about
     hostnames, service ports, and protocols.

* Menu:

* Socket address::
* High-level network functions::
* Low-level socket interface::
* Netdb interface::


File: gauche-refe.info,  Node: Socket address,  Next: High-level network functions,  Prev: Networking,  Up: Networking

9.12.1 Socket address
---------------------

 -- Builtin Class: <sockaddr>
     An abstract base class of socket addresses.  Each socket address
     family is implemented as a subclass of this class.

     Although socket addresses are built-in classes, you can use `make'
     method to create an instance of a specific socket address family.

 -- Generic Function: sockaddr-family addr
     Returns a symbol that indicates the family of the socket address
     ADDR.

 -- Generic Function: sockaddr-name addr
     Returns a string which represents the content of the socket address
     ADDR.

 -- Builtin Class: <sockaddr-in>
     AF_INET family socket address.  To create an instance of this
     class, use `make' method as follows:
          (make <sockaddr-in> :host HOST :port PORT)
     HOST can be a string, or one of the keywords `:any', `:broadcast',
     `:none' or `:loopback'.  If it is a string, it is either a host
     name or a dotted IP notation.  Gauche uses `gethostbyname(3)' to
     obtain the actual IP address from HOST parameter.  If it is a
     keyword `:any', or `:broadcast', the address uses `INADDR_ANY', or
     `INADDR_BROADCAST' respectively.  The keyword `:loopback' is a
     synonym to the IPv4 loopback address "127.0.0.1".

     PORT must be a positive integer indicating the port number.  See
     also `make-sockaddrs' below, to create multiple socket addresses
     on the machine which may have more than one protocol stack.

 -- Method: sockaddr-family (addr <sockaddr-in>)
     Returns a symbol `inet'.

 -- Method: sockaddr-name (addr <sockaddr-in>)
     Returns a string in the form "A.B.C.D:PORT",  where "A.B.C.D" is
     dotted decimal notion of the IP address and PORT is the port
     number.

 -- Method: sockaddr-addr (addr <sockaddr-in>)
     Returns the IP address as an integer.

 -- Method: sockaddr-port (addr <sockaddr-in>)
     Returns the port number as an integer.

 -- Builtin Class: <sockaddr-un>
     AF_UNIX family socket address.  To create an instance of this
     class, use `make' method as follows:
          (make <sockaddr-un> :path PATH)
     PATH must be a string specifying pathname of the socket.

 -- Method: sockaddr-family (addr <sockaddr-un>)
     Returns a symbol `unix'.

 -- Method: sockaddr-name (addr <sockaddr-un>)
     Returns a pathname of the socket address.

 -- Builtin Class: <sockaddr-in6>
     AF_INET6 family socket address.  This is only avalable if gauche
     is configured with -enable-ipv6 configure option.  The constructor
     and the slots are the same as `<sockaddr-in>'.  See also
     `make-sockaddrs' below, to create multiple socket addresses on the
     machine which may have more than one protocol stack.

 -- Function: make-sockaddrs host port &optional proto
     This is a higher-level utility procedure to create all possible
     inet domain socket addresses that point to `HOST:PORT' of protocol
     PROTO.  Particularly, if the specified host has both IPv4 and IPv6
     addresses, and the running system supports both, then both IPv4
     and IPv6 socket addresses are returned.   If HOST has multiple IP
     addresses, socket addresses are created for each of these IP
     address.   You can make your network application much more portable
     among different network stack configurations.

     Passing `#f' to HOST creates the local (server) address.  You can
     also pass a service name (e.g. `"http"') instead of an integer, to
     the PORT argument.  The value of PROTO can be either a symbol
     `tcp' or `udp', and the default is `tcp'.

     It always returns a list of socket addresses.  If the lookup of
     HOST is failed, null list is returned.


File: gauche-refe.info,  Node: High-level network functions,  Next: Low-level socket interface,  Prev: Socket address,  Up: Networking

9.12.2 High-level network functions
-----------------------------------

 -- Builtin Class: <socket>
     Abstracts a socket, a communication endpoint.

     For a connection-oriented socket, you can access the communication
     channel by two ports associated to the socket, one for input and
     another for output.  `socket-input-port' and `socket-output-port'
     returns those ports, respectively.

   The following two functions are convenient ways to create a
connection-oriented socket.  Those functions are to provide an easy
methods for typical cases, but have less control.  If you need more
than these functions provide, use low-level interface.

 -- Function: make-client-socket &optional address-spec ...
     Creates and returns a client socket, connected to the address
     specified by ADDRESS-SPEC ....

    `(make-client-socket 'unix PATH)'
          The client socket is connected to the unix domain server
          socket of addreess PATH.

    `(make-client-socket 'inet HOST PORT)'
          The client socket is connected to the inet domain server
          socket with hostname HOST and port PORT.   TCP protocol is
          assumed.   HOST can be either a hostname, or a dotted decimal
          notation of IPv4 address.  If gauche is compiled with
          -enable-ipv6, IPv6 address notation can also be used.  PORT
          must be an exact integer specifying a port number, or a
          string service name (e.g. `"http"').

          If gauche is compiled with -enable-ipv6, and the hostname is
          given, and the hostname has both IPv6 and IPv4 addresses, then
          IPv6 connection is tried first, and IPv4 is used when IPv6
          fails.

    `(make-client-socket HOST PORT)'
          This works the same as above.  This form is for compatibility
          with STk.

    `(make-client-socket SOCKADDR)'
          If an instance of `<sockaddr>' is passed, a socket suitable
          for SOCKADDR is opened and then connected to the given
          address.

     This function raises an error if it cannot create a socket, or
     cannot connect to the specified address.

          (make-client-socket 'inet "www.w3.com" 80)
            => ;a socket connected to www.w3.com, port 80
          (make-client-socket "127.0.0.1" 23)
            => ;a socket connected to localhost, port 23
          (make-client-socket 'unix "/tmp/.sock"
            => ;a socket connected to a unix domain socket "/tmp/.sock"

 -- Function: make-server-socket &optional address-spec ...
     Creates and returns a server socket, listening the address
     specified by ADDRESS-SPEC.

    `(make-server-socket 'unix PATH)'
          The socket is bound to a unix domain socket with a name PATH.

    `(make-server-socket 'inet PORT [:reuse-addr? FLAG] [:sock-init PROC])'
          The socket is bound to an inet domain TCP socket, listening
          port PORT, which must be a non-negative exact integer or a
          string service name (e.g. `"http"').  If PORT is zero, the
          system assigns one of available port numbers.  If a keyword
          argument REUSE-ADDR? is given and true, `SO_REUSEADDR' option
          is set to the socket before bound to the port.  This allows
          the process to bind the server socket immediately after other
          process releases the port.

          If keyword argument `sock-init' is given, it should be a
          procedure that takes two arguments, a created socket and the
          socket address.  The procedure is called just after the
          socket is created.  It is useful to set some special socket
          options.

    `(make-server-socket PORT [:reuse-addr? FLAG] [:sock-init PROC])'
          This is a synonym to the above form (except PORT must be an
          integer).  This form is backward-compatible with STk's
          `make-server-socket'.

    `(make-server-socket SOCKADDR [:reuse-addr? FLAG][:sock-init PROC])'
          This form explicitly specifies the socket address to listen
          by an instance of `<sockaddr>'.

          (make-server-socket 'inet 8080)
            => #<socket (listen "0.0.0.0:8080")>
          (make-server-socket 8080)
            => #<socket (listen "0.0.0.0:8080")>
          (make-server-socket 'inet 0)
            => #<socket (listen "0.0.0.0:35628")>
          (make-server-socket 'unix "/tmp/.sock")
            => #<socket (listen "/tmp/.sock")>

 -- Function: make-server-sockets host port &keyword reuse-addr?
          sock-init
     Creates one or more sockets that listen at PORT on all available
     network interfaces of HOST.  You can specify a service name (such
     as "`http'") to PORT, as well as an integer port number.  Returns
     a list of opened, bound and listened sockets.

     This procedure is particularly useful when the host has multiple
     protocol stacks, such as IPv4 and IPv6; in which case, you can
     start a server that listenes both protocol using
     `make-server-sockets'.

     The meaning of keyword arguments are the same as of
     `make-server-socket'.

   Several accessors are available on the returned socket object.

 -- Function: socket-address socket
     Returns a socket address associated with SOCKET.  If no address
     has been associated to the socket, `#f' is returned.

 -- Function: socket-input-port socket &keyword (buffering `:modest')
 -- Function: socket-output-port socket &keyword (buffering `:line')
     Returns an input and output port associated with SOCKET,
     respectively.

     The keyword argument BUFFERING specifies the buffering mode of the
     port.  *Note File ports::, for explanation of the buffering mode.

 -- Function: socket-close socket
     Closes SOCKET.  All the ports associated to SOCKET are closed as
     well.   If the socket is connected, Note: as of release 0.7.2,
     this procedure does not shutdown the connection.  It is because
     SOCKET may be referenced by forked process(es) and you might want
     to close it without interfering the existing connection.   You can
     call `socket-shutdown' to shutdown the connection explicitly.


 -- Function: call-with-client-socket socket proc
     SOCKET must be a connected client socket.  PROC is called with two
     arguments, an input port that reads from the socket and an output
     port that writes to the socket.  The socket is closed after PROC
     returns or PROC raises an error.

   This is an example of usage of high-level socket functions, a very
simple http client.

     #!/usr/bin/env gosh
     (use gauche.regexp)
     (use gauche.net)

     (define (usage)
       (display "Usage: swget url\n" (current-error-port))
       (exit 1))

     ;; Returns three values: host, port, and path.
     (define (parse-url url)
       (rxmatch-let (rxmatch #/^http:\/\/([-A-Za-z\d.]+)(:(\d+))?(\/.*)?/ url)
           (#f host #f port path)
         (values host port path)))

     (define (get url)
       (receive (host port path) (parse-url url)
         (call-with-client-socket
             (make-client-socket 'inet host (string->number (or port "80")))
           (lambda (in out)
             (format out "GET ~a HTTP/1.0\r\n" path)
             (format out "host: ~a\r\n\r\n" host)
             (flush out)
             (copy-port in (current-output-port))))))

     (define (main args)
       (if (= (length args) 2)
           (get (cadr args))
           (usage))
       0)


File: gauche-refe.info,  Node: Low-level socket interface,  Next: Netdb interface,  Prev: High-level network functions,  Up: Networking

9.12.3 Low-level socket interface
---------------------------------

These functions provide APIs similar to the system calls.  Those who
are familiar to programming with socket APIs will find these functions
useful since you can have more detailed control over the sockets.

 -- Function: make-socket domain type &optional protocol
     Returns a socket with specified parameters.

 -- Variable: PF_UNIX
 -- Variable: PF_INET
     These variables are bound to `PF_UNIX' and `PF_INET'.

 -- Variable: AF_UNIX
 -- Variable: AF_INET
     These variables are bound to `AF_UNIX' and `AF_INET'.

 -- Variable: SOCK_STREAM
 -- Variable: SOCK_DGRAM
 -- Variable: SOCK_RAW
     These variables are bound to `SOCK_STREAM', `SOCK_DGRAM' and
     `SOCK_RAW'.

 -- Function: socket-fd socket
     Returns an integer system file descriptor of the underlying socket.

 -- Function: socket-status socket
     Returns a internal status of SOCKET, by one of the following
     symbols.
     none                The socket is just created.
     bound               The socket is bound to an address by
                         `socket-bind'
     listening           The socket is listening a connection by
                         `socket-listen'
     connected           The socket is connected by `socket-connect' or
                         `socket-accept'.
     shutdown            The socket is shutdown by `socket-shutdown'
     closed              The socket is closed by `socket-close'.

 -- Function: socket-bind socket address
     Binds SOCKET to the local network address ADDRESS.  It is usually
     used to associate specific address to the server port.  If binding
     failed, an error is signalled (most likely the address is already
     in use).

     For the inet domain address, you can pass ADDRESS with port=0; the
     system assigns the port number and sets the actual address to the
     `address' slot of SOCKET.

 -- Function: socket-listen socket backlog
     Listens SOCKET.  The socket must be already bound to some address.
     BACKLOG specifies maximum number of connection requests to be
     queued.

 -- Function: socket-accept socket
     Accepts a connection request coming to SOCKET.  Returns a new
     socket that is connected to the remote entity.  The original
     SOCKET keeps waiting for further connections.  If there's no
     connection requests, this call waits for one to come.

     You can use `sys-select' to check if there's a pending connection
     request.

 -- Function: socket-connect socket address
     Connects SOCKET to the remote address ADDRESS.  This is the way
     for a client socket to connect to the remote entity.

 -- Function: socket-shutdown socket how
     Shuts down connection of SOCKET.  If HOW is 0, the receive channel
     of SOCKET is disallowed.  If HOW is 1, the send channel of SOCKET
     is disallowed.  If HOW is 2, both receive and send channels are
     disallowed.  It is an error to call this function on a
     non-connected socket.

     If you shut down the send channel of the socket, the remote peer
     sees EOF from its receive channel.  This is useful if the remote
     peer expects EOF before sending something back to you.

 -- Function: socket-getsockname socket
     Returns a `<sockaddr>' instance that is the local address of
     SOCKET.

 -- Function: socket-getpeername socket
     Returns a `<sockaddr>' instance that is the peer address of SOCKET.

 -- Function: socket-send socket msg &optional flags
 -- Function: socket-sendto socket msg to-address &optional flags.
     Interfaces to `send(2)' and `sendto(2)', respectively.  Transmits
     the content of MSG (string) through SOCKET.  When `socket-send' is
     used, SOCKET must already be connected.  On the other hand,
     `socket-setdto' can be used for non-connected socket, and the
     destination address is specified by a `<sockaddr>' instance
     TO-ADDRESS.

     The optional FLAGS can be a bitwise OR of the integer constants
     `MSG_*'.  See the system's manpage of `send(2)' and `sendto(2)'
     for the details.

 -- Function: socket-recv socket bytes &optional flags
 -- Function: socket-recvfrom socket bytes &optional flags
     Interfaces to `recv(2)' and `recvfrom(2)', respectively.  Receives
     a message up to the BYTES bytes from a socket SOCKET.
     `socket-recv' should be used with a connected socket, whereas
     `socket-recvfrom' can be used with non-connected socket.

     `socket-recv' returns a received message as a (possibly incomplete)
     string.   `socket-recvfrom' returns two values, a received message
     and the sender's socket address.

     The optional FLAGS can be a bitwise OR of the integer constants
     `MSG_*'.  See the system's manpage of `recv(2)' and `recvfrom(2)'
     for the details.

 -- Variable: MSG_CTRUNC
 -- Variable: MSG_DONTROUTE
 -- Variable: MSG_EOR
 -- Variable: MSG_OOB
 -- Variable: MSG_PEEK
 -- Variable: MSG_TRUNC
 -- Variable: MSG_WAITALL
     Pre-defined integer constants to be used as FLAGS values for
     `socket-send', `socket-sendto', `socket-recv' and
     `socket-recvfrom'.   Some of these constants may not be defined if
     the underlying operating system doesn't provide them.

   Further control over sockets and protocol layers is possible by
getsockopt/setsockopt interface, as described below.

 -- Function: socket-setsockopt socket level option value
 -- Function: socket-getsockopt socket level option rsize
     These are the interface to setsockopt() and getsockopt() calls.
     The interface is a bit clumsy, in order to allow full access to
     those low-level calls.

     SOCKET must be a non-closed socket object.  LEVEL and OPTION is an
     exact integer to specify the level of protocol stack and the
     option you want to deal with.  There are several variables
     pre-bound to system constants listed below.

     To set the socket option, you can pass either an exact integer or
     a string to VALUE.  If it is an integer, the value is passed to
     setsockopt(2) as C `int' value.  If it is a string, the byte
     sequence is passed as is.  The required type of value depends on
     the option, and Gauche can't know if the value you passed is
     expected by setsockopt(2); it is your responsibility to pass the
     correct values.

     To get the socket option, you need to tell the maximum length of
     expected result by RSIZE parameter, for Gauche doesn't know the
     amount of data each option returns.  `socket-getsockopt' returns
     the option value as a byte string.  If you know the option value
     is an integer, you can pass 0 to RSIZE; in that case
     `socket-getsockopt' returns the value as an exact integer.

     Note about the name: I tempted to name these function
     socket-{set|get}opt or socket-{set|get}-option, but I rather took
     the naming consistency.  Hence duplicated "sock"s.


   The following predefined variables are provided.  Note that some of
them are not available on all platforms.  See manpages `socket(7)',
`tcp(7)' or `ip(7)' of your system to find out exact specification of
those values.

   For "level" argument:

 -- Variable: SOL_SOCKET
 -- Variable: SOL_TCP
 -- Variable: SOL_IP
     These variables are bound to `SOL_SOCKET', `SOL_TCP' and `SOL_IP',
     respectively.

   For "option" argument:

 -- Variable: SO_KEEPALIVE
     Expects integer value.  If it is not zero, enables sending  of
     keep-alive messages on connection-oriented sockets.

 -- Variable: SO_OOBINLINE
     Expects integer value.  If it is not zero, out-of-band data is
     directly placed into the receive data stream.  Otherwise
     out-of-band  data  is  only passed when the MSG_OOB flag is set
     during receiving.

 -- Variable: SO_REUSEADDR
     Expects integer value.  If it is not zero, `socket-bind' allows to
     reuse local addresses, unless an active listening socket bound to
     the address.

 -- Variable: SO_TYPE
     Gets the socket type as an integer (like `sock_stream').  Can be
     only used with `socket-getsockopt'.

 -- Variable: SO_BROADCAST
     Expects integer value.  If it is not zero, datagram sockets are
     allowed to send/receive broadcast packets.

 -- Variable: SO_PRIORITY
     Expects integer value, specifying the protocol-defined priority
     for all packets to be sent on this socket.

 -- Variable: SO_ERROR
     Gets and clears the pending socket error as an integer.  Can be
     only used with `socket-getsockopt'.


File: gauche-refe.info,  Node: Netdb interface,  Prev: Low-level socket interface,  Up: Networking

9.12.4 Netdb interface
----------------------

 -- Builtin Class: <sys-hostent>
     A class of objects for network hosts.  Corresponding to `struct
     hostent' in C.  The following slots are available read-only.

      -- Instance Variable of <sys-hostent>: name
          The formal name of the host (string).

      -- Instance Variable of <sys-hostent>: aliases
          A list of alias names of the host (list of strings).

      -- Instance Variable of <sys-hostent>: addresses
          A list of addresses (list of strings).  Only ipv4 address is
          supported currently.  Each address is represented by dotted
          decimal notation.

 -- Function: sys-gethostbyname name
     Looks up a host named NAME.  If found, returns a `<sys-hostent>'
     object.  Otherwise, returns `#f'.
          (let ((host (sys-gethostbyname "www.w3c.org")))
            (list (slot-ref host 'name)
                  (slot-ref host 'aliases)
                  (slot-ref host 'addresses)))
            => ("www.w3.org" ("www.w3c.org") ("18.29.1.34" "18.29.1.35"))

 -- Function: sys-gethostbyaddr addr proto
     Looks up a host that has an address ADDR of protocol PROTO.  ADDR
     is a natural string representation of the address; for ipv4, it is
     a dotted decimal notation.  PROTO is a protocol number; only
     `AF_INET' is supported currently.  If the host is found, returns a
     `<sys-hostent>' object.  Otherwise, returns `#f'.
          (let ((host (sys-gethostbyaddr "127.0.0.1" AF_INET)))
            (list (slot-ref host 'name)
                  (slot-ref host 'aliases)
                  (slot-ref host 'addresses))
            => ("localhost" ("localhost.localdomain") ("127.0.0.1"))

 -- Builtin Class: <sys-servent>
     An entry of the network service database.  Corresponding to
     `struct servent' in C.  The following slots are available
     read-only.

      -- Instance Variable of <sys-servent>: name
          The formal name of the service (string).

      -- Instance Variable of <sys-servent>: aliases
          A list of alias names of the service (list of strings).

      -- Instance Variable of <sys-servent>: port
          A port number registered for this service (exact integer).

      -- Instance Variable of <sys-servent>: proto
          A protocol name for this service (string).

 -- Function: sys-getservbyname name proto
     Looks up the network service database with a service name NAME and
     a protocol PROTO.  Both NAME and PROTO must be a string.  If a
     service is found, an instance of `<sys-servent>' is returned.
     Otherwise, `#f' is returned.
          (let ((serv (sys-getservbyname "http" "tcp")))
            (list (slot-ref serv 'name)
                  (slot-ref serv 'aliases)
                  (slot-ref serv 'port)
                  (slot-ref serv 'proto)))
            => ("http" () 80 "tcp")

 -- Function: sys-getservbyport port proto
     Looks up the network service database with a service port PORT and
     a protocol PROTO.  PORT must be an exact integer, and PROTO must
     be a string.  If a service is found, an instance of
     `<sys-servent>' is returned.  Otherwise, `#f' is returned.
          (let ((serv (sys-getservbyport 6000 "tcp")))
            (list (slot-ref serv 'name)
                  (slot-ref serv 'aliases)
                  (slot-ref serv 'port)
                  (slot-ref serv 'proto)))
            => ("x-server" () 6000 "tcp")

 -- Builtin Class: <sys-protoent>
     An entry of the protocol database.   Corresponds to `struct
     protoent' in C.   The following slots are available read-only.

      -- Instance Variable of <sys-servent>: name
          The formal name of the protocol (string).

      -- Instance Variable of <sys-servent>: aliases
          A list of alias names of the protocol (list of strings).

      -- Instance Variable of <sys-servent>: proto
          A protocol number (exact integer).

 -- Function: sys-getprotobyname name
     Looks up the network protocol database with a name NAME, which
     must be a string.  If a protocol is found, an instance of
     `<sys-protoent>' is returned.  Otherwise, `#f' is returned.
          (let ((proto (sys-getprotobyname "icmp")))
            (list (slot-ref proto 'name)
                  (slot-ref proto 'aliases)
                  (slot-ref proto 'proto)))
            => ("icmp" ("ICMP") 1)

 -- Function: sys-getprotobynumber number
     Looks up the network protocol database with a protocol number
     NUMBER, which must be an exact integer.  If a protocol is found,
     an instance of `<sys-protoent>' is returned.  Otherwise, `#f' is
     returned.
          (let ((proto (sys-getprotobynumber 17)))
            (list (slot-ref proto 'name)
                  (slot-ref proto 'aliases)
                  (slot-ref proto 'proto)))
            => ("udp" ("UDP") 17)

 -- Builtin Class: <sys-addrinfo>
     The new interface to keep address information.  Corresponds to
     `struct addrinfo' in C.  This is only available if gauche is
     configured with -enable-ipv6 option.  The following slots are
     provided.

      -- Instance Variable of <sys-addrinfo>: flags

      -- Instance Variable of <sys-addrinfo>: family

      -- Instance Variable of <sys-addrinfo>: socktype

      -- Instance Variable of <sys-addrinfo>: protocol

      -- Instance Variable of <sys-addrinfo>: addrlen

      -- Instance Variable of <sys-addrinfo>: addr

 -- Function: sys-getaddrinfo nodename servname hints
     Returns `<sys-addrinfo>' instance from the given NODENAME,
     SERVNAME and HINTS.  This is only available if gauche is compiled
     with -enable-ipv6 option.


File: gauche-refe.info,  Node: Parameters,  Next: Parsing command-line options,  Prev: Networking,  Up: Library modules - Gauche extensions

9.13 `gauche.parameter' - Parameters
====================================

 -- Module: gauche.parameter
     A _parameter_ is somethink like a stateful procedure that takes
     zero or one argument.  If no argument is given, the parameter
     returns the current value it is keeping.  If single argument is
     given, it will be the current value of the parameter.  A parameter
     has several advantages over global variables to store states.

     Value of parameters are kept for each thread, so you can use a
     parameter as a thread-local storage.  When a new thread is
     created, it inherits a copy of parameters from its creator thread.

     You can give a "filter procedure" that checks the new value before
     setting it as the parameter value, so that you can guarantee the
     value of the parameter is always sane.

     With the macro `parameterize', you can change the parameter's
     value within certain dynamic scope.   It can effectively replace
     dynamically scoped variables.

     You can also register callback procedures to be called whenever
     the value of the parameter is changed.   It can effectively
     replace so-called "traced variables"

     The basic parameter object feature is defined in SRFI-39.  It also
     can be found in other Scheme implementations, including
     ChezScheme, Chicken and MzScheme.  Gauche's one is upper
     compatible to SRFI-39.

 -- Class: <parameter>
     A parameter class.  A `object-apply' method is defined so that a
     parameter can be used as if it were a procedure.

 -- Function: make-parameter value &optional filter
     [SRFI-39] Creates a parameter whose initial value is VALUE.  If an
     optional argument FILTER is given, it must be a procedure that
     takes one argument and returns one value; whenever the parameter's
     value is about to change, the procedure is called with the given
     value, and the value the procedure returns will be the parameter's
     value.  The filter procedure can raise an error or reject to
     change the parameter's value.

 -- Macro: parameterize ((param value) ...) body ...
     [SRFI-39] Evaluages BODY ..., with change parameter PARAM's value
     to the given VALUE within the dynamic scope of BODY ....  Returns
     the value(s) of the result of the last BODY.

   Some examples:
     (define a (make-parameter 1))
     (a) => 1
     (a 2) => 1
     (a) => 2
     (parameterize ((a 3))
       (a)) => 3
     (a) => 2

 -- Method: parameter-observer-add! (p <parameter>) proc &optional when
          where
     Adds PROC to "observer" procedures of a parameter P.  Observer
     procedures are called either (1) just before a new value is set to
     the parameter, or (2) just after the new value is set to the
     parameter.   In case of (1), a filter procedure is already applied
     before a callback is called.  In either case, observer procedures
     are called with two arguments, the old value and the new value.
     The return value(s) of observer procedures are discarded.

     The optional WHEN argument must be either a symbol `before' or
     `after', to specify whether PROC should be called before or after
     the value is changed.   If omitted, `after' is assumed.

     The optional WHERE argument must be either a symbol `append' or
     `prepend', to specify whether PROC should be prepended or appended
     to the existing observer procedure list.  If omitted, `append' is
     assumed.

     _Note_: Although the parameter value itself is thread-local, the
     observer list is shared by all threads.

 -- Method: parameter-observer-delete! (p <parameter>) proc &optional
          when
     Deletes PROC from observer procedure list of a parameter P.  If
     PROC is not in the list, nothing happens.  You can give either a
     symbol `before' or `after' to WHEN argument to specify from which
     list PROC should be deleted.  If WHEN argument is omitted, PROC is
     deleted from both lists.

 -- Method: parameter-pre-observers (p <parameter>)
 -- Method: parameter-post-observers (p <parameter>)
     Returns a hook object (*Note Hooks::) that keeps "before" or
     "after" observers, respectively.

     _Note_: Although the parameter value itself is thread-local, these
     hook objects are shared by all threads.


File: gauche-refe.info,  Node: Parsing command-line options,  Next: High Level Process Interface,  Prev: Parameters,  Up: Library modules - Gauche extensions

9.14 `gauche.parseopt' - Parsing command-line options
=====================================================

 -- Module: gauche.parseopt
     This module defines a convenient way to parse command-line options.
     The interface is hinted by Perl, and conveniently handles
     long-format options with mutiple option arguments.

     Actually, you have a few choices to parse command-line options in
     Gauche.  SRFI-37 (*Note A program argument processor::) provides
     functional interface to parse POSIX/GNU compatible argument syntax.
     SLIB has `getopt'-compatible utility.  Required features may
     differ from application to application, so choose whichever fits
     your requirement.

 -- Macro: parse-options args (option-clause ...)
     ARGS is an expression that contains a list of command-line
     arguments.  This macro scans the command-line options (an argument
     that begins with ``-'') and processes it as specified in
     OPTION-CLAUSEs, then returns the remaining arguments.

     Unlike typical `getopt' or `getopt_long' implementation in C,
     `parse-options' does not permute the given command-line arguments.
     It stops parsing when it encounters a non-option argument
     (argument without starting with a minus sign).

     If the parser encounters an argument with only two minus signs
     ``--'', it stops argument parsing and returns a list of arguments
     after ``--''.

     Each OPTION-CLAUSE is consisted by a pair of OPTION-SPEC and its
     action.

     OPTION-SPEC is a string that specifies the name of the option and
     how the option takes the arguments.  An alphanumeric characters,
     underscore, plus and minus sign is allowed for option's names,
     except that minus sign can't be the first character, i.e. the
     valid option name matches a regexp `#/[\w+][-\w+]*/'.

     If the option takes argument(s), it can be specified by attaching
     equal character and a character (or characters) that represents
     the type of the argument(s) after the name.  The option can take
     more than one arguments.  The following characters are recognized
     as a type specifier of the option's argument.

    `s'
          String.

    `n'
          Number.

    `f'
          Real number (flonum).

    `i'
          Exact integer.

    `e'
          S-expression.

    `y'
          Symbol (argument is converted by `string->symbol').

     Let's see some examples of OPTION-SPEC:

    `"NAME"'
          Specifies option NAME, that doesn't take any argument.

    `"NAME=s"'
          Option NAME takes one argument, and it is passed as a string.

    `"NAME=i"'
          Option NAME takes one argument, and it is passed as an exact
          integer.

    `"NAME=ss"'
          Option NAME takes two arguments, both string.

    `"NAME=iii"'
          Option NAME takes three integer arguments.

    `"NAME=sf"'
          Option NAME takes two arguments, the first is a string and the
          second is a number.

     If the option has alternative names, they can be concatenated by
     "|".  For example, an option spec `"h|help"' will match both "h"
     and "help".

     In the command line, the option may appear with preceding single
     or double minus signs.  The option's argument may be comibined by
     the option itself with an equal sign.  For example, all the
     following command line arguments match an option spec `"prefix=s"'.
          -prefix /home/shiro
          -prefix=/home/shiro
          --prefix /home/shiro
          --prefix=/home/shiro

     If a given command-line option matches one of OPTION-SPEC, then
     the associated action is evaluated.  An action can be one of the
     following forms.

    `BIND-SPEC BODY ...'
          BIND-SPEC is a proper or dotted list of variables like
          lambda-list.  The option's arguments are bound to BIND-SPEC,
          then then BODY ... is evaluated.

    `=> PROC'
          If a command-line option matches OPTION-SPEC, calls a
          procedure PROC with a list of the option's arguments.

     Examples:
          (parse-options '("-file" "foo")
            (("file=s" (file)
               (format #t "file is ~s\n" file))))
           => ;"`file is "foo"'" is printed

          (parse-options '("-scale" "1.5" "2.2")
            (("scale=ff" (xscale yscale)
               (format #t "scale is ~sx~s\n" xscale yscale))))
           => ;"`scale is 1.5x2.2'" is printed

          (parse-options '("-scale" "1.5" "2.2")
            (("scale=ff" scales
               (format #t "scale is ~s\n" scales))))
           => ;"`scale is (1.5 2.2)'" is printed

          (define (scales x y)
            (format #t "scale is ~sx~s\n" x y))

          (parse-options '("-scale" "1.5" "2.2")
            (("scale=ff" => scales)))
           => ;"`scale is 1.5x2.2'" is printed

     If a symbol `else' is at the position of OPTION-SPEC, the clause
     is selected when no other option clause matches a given
     command-line option.  Three "arguments" are associated to the
     clause; the unmatched option, the rest of arguments, and a
     procedure that represents the option parser.

          (parse-options args
            (("file=s" => process-file)
             (else (option . _)  (error "unrecognized option:" option))))

     Unlike other clause, the else clause returns to the caller of
     `parse-options', without looping further.  In order to continue
     looping, you have to call the third argument of the else clause
     with the remaining arguments.  This can be used to implement your
     own sub-parser.  The following example just skips unrecognized
     option, with printing a warning, and continues parsing:

          (parse-options args
            (("file=s" => process-file)
             (else (option args continue)
               (format #t "warning: ignoring unrecognized option: ~a" option)
               (continue args))))


 -- Macro: let-args args (bind-spec ... [. rest]) body ...
     This macro wraps `parse-options' to make it look more like
     ordinary Scheme construct.  For example, a simple script can be
     written as follows:

          (define (main args)
            (let-args (cdr args)
                ((quiet   "q|quiet" #t)
                 (verbose "v|verbose" #f)
                 (outfile "o|outfile=s")
                 (help    "h|help" => (cut show-help (car args)))
                )
              ....))

          (define (show-help progname)
            ...)

     BIND-SPEC must be one of the following forms.

          1. (VAR OPTION-SPEC)
          2. (VAR OPTION-SPEC DEFAULT)
          3. (VAR OPTION-SPEC => CALLBACK)
          4. (VAR OPTION-SPEC DEFAULT => CALLBACK)

          5. (else FORMALS FORM ...)

     A list of command-line arguments passed to ARGS are parsed
     according to OPTION-SPECs.  If the corresponding option is given,
     a variable VAR is bound to a value as follows:
          (a) If the BIND-SPEC is 1. or 2., then
            (a1) If OPTION-SPEC doesn't require an argument, then `#t':
            (a2) If OPTION-SPEC requires one argument, then the value of
                 the argument:
            (a3) If OPTION-SPEC requires more than one argument,
                 the list of the values of the arguments.
          (b) If the BIND-SPEC is 3. or 4., then CALLBACK is called with
            the value(s) of arguments, and its return value.

     As a special case, VAR can be `#f', in which case the value is
     ignored.  It is only useful for side effects in CALLBACK.

     If the corresponding option is not given in ARGS, VAR is bound to
     DEFAULT if it is given, or `#f' otherwise.

     The last BIND-SPEC may be the form 5. in which case it is treated
     in the same way as `else' clause of `parse-options'.

     The BIND-SPEC list can be an improper list, whose last `cdr' is a
     symbol.  In which case, a list of the rest of the command-line
     arguments is bound to the variable named by the symbol.

     Note that the DEFAULT, CALLBACK, and forms in `else' clause is
     evaluated outside of the scope of binding of VARs (as the name
     `let-args' implies).

     After all the bindings is done, BODY ... are evaluated.  BODY may
     began with internal define forms.

 -- Macro: make-option-parser (option-clause ...)
     This is a lower-level interface.  OPTION-CLAUSEs are the same as
     `parse-options'.  This macro returns a procedure that can be used
     later to parse the command line options.

     The returned procedure takes one required argument and one
     optional argument.  The required argument is a list of strings,
     for given command-line arguments.  The optional argument may be a
     procedure that takes more than three arguments, and if given, the
     procedure is used as if it is the body of `else' option clause.


File: gauche-refe.info,  Node: High Level Process Interface,  Next: Regular expression utilities,  Prev: Parsing command-line options,  Up: Library modules - Gauche extensions

9.15 `gauche.process' - High Level Process Interface
====================================================

 -- Module: gauche.process
     This module provides a higher-level API of Unix process control,
     implemented on top of low-level system calls such as `sys-fork'
     and `sys-exec'.  The interface is mostly compatible with STk's
     process library.  This module also provides "process ports", a
     convenient way to send/receive information to/from subprocesses.

* Menu:

* Process object::
* Process ports::


File: gauche-refe.info,  Node: Process object,  Next: Process ports,  Prev: High Level Process Interface,  Up: High Level Process Interface

9.15.1 Process object
---------------------

 -- Class: <process>
     An object to keep the status of a child process.  You can create
     the process object by `run-process' procedure described below.
     The process ports explained in the next section also use process
     objects.

     Note that the `<process>' class keeps track of the child processes
     spawned by high-level APIs such as `run-process' or
     `open-input-process'.  The exit status of such children must be
     collected by `process-wait' or `process-wait-any' calls, which
     also do some bookkeeping.   Using the low-level process calls such
     as `sys-wait' or `sys-waitpid' directly will cause inconsistent
     state.


 -- Function: run-process command arg ...
     Run COMMAND with ARG in a subprocess, and returns a `<process>'
     object.   COMMAND is searched from the command search path.

     Command line arguments ARGs can include the following keyword
     arguments which specify special handling of the child process, as
     listed below.

     Other than such keyword arguments, COMMAND and ARGs are converted
     to strings by `x->string'.
    `:input FILE'
    `:output FILE'
    `:error FILE'
          These arguments controls the subprocess' standard i/o.  FILE
          may be either a string or a keyword `:pipe'.  If it is a
          string, the process' standard input, output, or error goes to
          the named file.   If it is `:pipe', the process'
          corresponding standard i/o is connected to a pipe, and the
          other side of the pipe is available for the calling process.

    `:wait FLAG'
          If FLAG is true, `run-process' waits until the subprocess
          terminates.  Othewise the subprocess runs asynchronously and
          `run-process' returns immediately, which is the default
          behavior.  Note that if the subprocess is running
          asynchronously, it is the caller's responsibility to call
          `process-wait' at certain timing to collect its exit status.

    `:fork FLAG'
          If FLAG is true, `run-process' forks to run the subprocess,
          which is the default behavior.  If FLAG is false,
          `run-process' directly calls `sys-exec', so it never returns.

 -- Function: process? obj
     == `(is-a? OBJ <process>)'

 -- Method: process-pid (process <process>)
     Returns the process ID of the subprocess PROCESS.

 -- Method: process-command (process <process>)
     Returns the command invoked in the subprocess PROCESS.

 -- Method: process-input (process <process>)
 -- Method: process-output (process <process>)
 -- Method: process-error (process <process>)
     If the process' standard input, output or error is connected to a
     pipe, returns another end of the pipe, i.e. `process-input'
     returns an output port that can feed data to PROCESS' stdin,
     `process-output' returns an input port that can read data from
     PROCESS' stdout, and `process-error' returns an input port that
     can read data from `process'' stderr.  If the corresponding i/o is
     not connected to the pipe, the function returns `#f'.

          (let* ((process (run-process "date" :output :pipe))
                 (line (read-line (process-output process))))
            (process-wait process)
            line)
           => "Fri Jun 22 22:22:22 HST 2001"

 -- Function: process-alive? process
     Returns true if PROCESS is alive.  Note that Gauche can't know the
     subprocess' status until it is explicitly checked by
     `process-wait'.

 -- Function: process-list
     Returns a list of active processes.  The process remains active
     until its exit status is explicitly collected by `process-wait'.
     Once the process's exit status is collected and its state changed
     to inactive, it is removed from the list `process-list' returns.

 -- Function: process-wait process &optional nohang
     Obtains the exit status of the subprocess PROCESS, and stores it
     to PROCESS's status slot.  The status can be obtained by
     `process-exit-status'.

     This suspends execution until PROCESS exits by default.  However,
     if a true value is given to an optional argument NOHANG, it
     returns immediately if PROCESS hasn't exit.

     Returns `#t' if this call actually obtains the exit status, or
     `#f' otherwise.

 -- Function: process-wait-any &optional nohang
     Obtains the exit status of any of the subprocesses created by
     `run-process'.  Returns a process object whose exit status is
     collected.

     If a true value is given to the optional argument NOHANG, this
     procedure returns `#f 'immediately even if no child process has
     exit.  If NOHANG is omitted or `#f', this procedure waits for any
     of children exits.

     If there's no child processes, this procedure immediately returns
     `#f'.

 -- Function: process-exit-status process
     Returns exit status of PROCESS retrieved by `process-wait'.  If
     this is called before `process-wait' is called on PROCESS, the
     result is undefined.

 -- Function: process-send-signal process signal
     Sends a signal SIGNAL to the subprocess PROCESS.  SIGNAL must be
     an exact integer for signal number.  *Note Signal::, for
     predefined variables of signals.

 -- Function: process-kill process
 -- Function: process-stop process
 -- Function: process-continue process
     Sends SIGKILL, SIGSTOP and SIGCONT to PROCESS, respectively.


File: gauche-refe.info,  Node: Process ports,  Prev: Process object,  Up: High Level Process Interface

9.15.2 Process ports
--------------------

 -- Function: open-input-process-port command &keyword output error
          encoding conversion-buffer-size
     Runs COMMAND asynchronously in a subprocess.  Returns two values,
     an input port which is connected to the stdout of the running
     subprocess, and a process object.

     COMMAND can be a string or a list.  If it is a string, it is
     passed to `/bin/sh'.  You can use shell metacharacters in this
     form, such as environment variable interpolation, globbing, and
     redirections.

     If COMMAND is a list, each element is converted to a string by
     `x->string' and then passed directly to `sys-exec' (the `car' of
     the list is used as both the command path and the first element of
     argv, i.e. `argv[0]').  Use this form if you want to avoid the
     shell from interfering.

     The subprocess's stdout is redirected to `/dev/null' by default,
     and its stderr shares the calling process's stderr.  You can
     change these by giving file pathnames to OUTPUT and ERROR keyword
     arguments, respectively.

     You can also give the ENCODING keyword argument to specify
     character encoding of the process output.  If it differs from the
     Gauche's internal encoding format, `open-input-process-port'
     inserts a character encoding conversion port.  If ENCODING is
     given, the CONVERSION-BUFFER-SIZE keyword argument can control the
     conversion buffer size.  See *Note Character code conversion::, for
     the details of character encoding conversions.
          (receive (port process) (open-input-process-port "ls -l Makefile")
            (begin0 (read-line port)
                    (process-wait process)))
           => "-rw-r--r--   1 shiro    users        1013 Jun 22 21:09 Makefile"

          (receive (port process) (open-input-process-port '(ls -l "Makefile"))
            (begin0 (read-line port)
                    (process-wait process)))
           => "-rw-r--r--   1 shiro    users        1013 Jun 22 21:09 Makefile"

          (open-input-process-port "command 2>&1")
           => ;the port reads both stdout and stderr

          (open-input-process-port "command 2>&1 1>/dev/null")
           => ;the port reads stderr
     The exit status of subprocess is not automatically collected.  It
     is the caller's responsibility to issue `process-wait', or the
     subprocess remains in a zombie state.  If it bothers you, you can
     use one of the following functions.

 -- Function: call-with-input-process command proc &keyword output
          error encoding conversion-buffer-size
     Runs COMMAND in a subprocess and pipes its stdout to an input
     port, then call PROC with the port as an argument.  When PROC
     returns, it collects its exit status, then returns the result PROC
     returned.  The cleanup is done even if PROC raises an error.

     The semantics of COMMAND and keyword arguments are the same as
     `open-input-process-port' above.
          (call-with-input-process "ls -l *"
            (lambda (p) (read-line p)))

 -- Function: with-input-from-process command thunk &keyword output
          error encoding conversion-buffer-size
     Runs COMMAND in a subprocess, and calls THUNK with its current
     input port connected to the command's stdout.  The command is
     terminated and its exit status is collected, after THUNK returns
     or raises an error.

     The semantics of COMMAND and keyword arguments are the same as
     `open-input-process-port' above.
          (with-input-from-process "ls -l *" read-line)

 -- Function: open-output-process-port command &keyword input error
          encoding conversion-buffer-size
     Runs `command' in a subprocess asynchronously.  Returns two values,
     an output port which is connected to the stdin of the subprocess.
     and the process object.

     The subprocess's stdin is redirected from `/dev/null', and its
     stderr shares the calling process's stderr by default.  You can
     change these by giving file pathnames to INPUT and ERROR keyword
     arguments, respectively.

     The semantics of COMMAND is the same as `open-input-process-port'.
     The semantics of ENCODING and CONVERSION-BUFFER-SIZE are also the
     same.

     The exit status of the subprocess is not automatically collected.
     The caller should call `process-wait' on the subprocess at
     appropriate time.

 -- Function: call-with-output-process command proc &keyword input
          error encoding conversion-buffer-size
     Runs `command' in a subprocess, and calls PROC with an output port
     which is connected to the stdin of the command.  The exit status
     of the command is collected after either PROC returns or raises an
     error.

     The semantics of keyword arguments are the same as
     `open-input-process-port'.
          (call-with-output-process "/usr/sbin/sendmail"
            (lambda (out) (display mail-body out)))

 -- Function: with-output-to-process command thunk &keyword input error
          encoding conversion-buffer-size
     Same as `call-with-output-process', except that the output port
     which is connected to the stdin of the command is set to the
     current output port while executing THUNK.

 -- Function: call-with-process-io command proc &keyword error encoding
          conversion-buffer-size
     Runs COMMAND in a subprocess, and calls PROC with two arguments;
     the first argument is an input port which is connected to the
     command's stdout, and the second is an output port connected to
     the command's stdin.  The error output from the command is shared
     by the calling process's, unless an alternative pathname is given
     to the ERROR keyword argument.

     The exit status of the command is collected when PROC returns or
     raises an error.

 -- Function: process-output->string command
 -- Function: process-output->string-list command
     Runs COMMAND and collects its output (to stdout) and returns them.
     `process-output->string' concatenates all the output from COMMAND
     to one string, replacing any sequence of whitespace characters to
     single space.   The action is similar to "command substitution" in
     shell scripts.  `process-output->string-list' collects the output
     from COMMAND line-by-line and returns the list of them.  Newline
     characters are stripped.

     Internally, COMMAND is run by `call-with-input-process'.
          (process-output->string "uname -smp")
            => "Linux i686 unknown"

          (process-output->string "ls")
            => "a.out foo.c foo.c~ foo.o"

          (process-output->string-list "ls")
            => ("a.out" "foo.c" "foo.c~" "foo.o")



File: gauche-refe.info,  Node: Regular expression utilities,  Next: Reloading modules,  Prev: High Level Process Interface,  Up: Library modules - Gauche extensions

9.16 `gauche.regexp' - Regular expression utilities
===================================================

 -- Module: gauche.regexp
     This module defines some macros and utilities useful in regexp
     match.  See *Note Regular expression:: for builtin regexp features.
     As of release 0.4.11, this module is set to be autoloaded in
     `gosh', so you don't usually need to say `(use gauche.regexp)'.

     The interface of some of the macros is borrowed from scsh
     (`if-match', `let-match' and `match-cond'), but I changed the name
     of macros since scsh's `match-cond' can be confusing (e.g. Bigloo
     has `match-lambda' and `match-case' in pattern match library, that
     sounds too similar).

   In the following macros, MATCH-EXPR is an expression which produces
a match object or `#f'. Typically it is a call of `rxmatch', but it can
be any expression.

 -- Macro: rxmatch-let match-expr (var ...) form ...
     Evaluates MATCH-EXPR, and if matched, binds VAR ...  to the
     matched strings, then evaluates FORMs.  The first VAR receives the
     entire match, and subsequent variables receive submatches.  If the
     number of submatches are smaller than the number of variables to
     receive them, the rest of variables will get `#f'.

     It is possible to put `#f' in variable position, which says you
     don't care that match.

          (rxmatch-let (rxmatch #/(\d+):(\d+):(\d+)/
                                "Jan  1 23:59:58, 2001")
             (time hh mm ss)
            (list time hh mm ss))
           => ("23:59:58" "23" "59" "58")

          (rxmatch-let (rxmatch #/(\d+):(\d+):(\d+)/
                                "Jan  1 23:59:58, 2001")
             (#f hh mm)
            (list hh mm))
           => ("23" "59")

     This macro corresponds to scsh's `let-match'.

 -- Macro: rxmatch-if match-expr (var ...) then-form else-form
     Evaluates MATCH-EXPR, and if matched, binds VAR ...  to the
     matched strings and evaluate THEN-FORM.  Otherwise evaluates
     ELSE-FORM.  The rule of binding VARs is the same as `rxmatch-let'.

          (rxmatch-if (rxmatch #/(\d+:\d+)/ "Jan 1 11:22:33")
              (time)
            (format #f "time is ~a" time)
            "unknown time")
           => "time is 11:22"

          (rxmatch-if (rxmatch #/(\d+:\d+)/ "Jan 1 11-22-33")
              (time)
            (format #f "time is ~a" time)
            "unknown time")
           => "unknown time"

     This macro corresponds to scsh's `if-match'.

 -- Macro: rxmatch-cond clause ...
     Evaluate condition in CLAUSEs one by one.  If a condition of a
     clause satisfies, rest portion of the clause is evaluated and
     becomes the result of `rxmatch-cond'.  CLAUSE may be one of the
     following pattern.

    `(MATCH-EXPR (VAR ...) FORM ...)'
          Evaluate MATCH-EXPR, which may return a regexp match object
          or `#f'.  If it returns a match object, the matches are bound
          to VARs, like RXMATCH-LET, and FORMs are evaluated.

    `(test EXPR FORM ...)'
          Evaluates EXPR.  If it yields true, evaluates FORMs.

    `(test EXPR => PROC)'
          Evaluates EXPR and if it is true, calls PROC with the result
          of EXPR as the only argument.

    `(else FORM ...)'
          If this clause exists, it must be the last clause.  If other
          clauses fail, FORMs are evaluated.

     If no `else' clause exists, and all the other clause fail, an
     undefined value is returned.

          ;; parses several possible date format
          (define (parse-date str)
            (rxmatch-cond
              ((rxmatch #/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/ str)
                  (#f mm dd yyyy)
                (map string->number (list yyyy mm dd)))
              ((rxmatch #/^(\d\d\d\d)\/(\d\d?)\/(\d\d?)$/ str)
                  (#f yyyy mm dd)
                (map string->number (list yyyy mm dd)))
              ((rxmatch #/^\d+\/\d+\/\d+$/ str)
                  (#f)
               (error "ambiguous: ~s" str))
              (else (error "bogus: ~s" str))))

          (parse-date "2001/2/3") => (2001 2 3)
          (parse-date "12/25/1999") => (1999 12 25)

     This macro corresponds to scsh's `match-cond'.

 -- Macro: rxmatch-case string-expr clause ...
     STRING-EXPR is evaluated, and CLAUSEs are interpreted one by one.
     A CLAUSE may be one of the following pattern.

    `(RE (VAR ...) FORM ...)'
          RE must be a literal regexp object (*Note Regular
          expression::).  If the result of STRING-EXPR matches RE, the
          match result is bound to VARs and FORMs are evaluated, and
          `rxmatch-case' returns the result of the last FORM.

          If RE doesn't match the result of STRING-EXPR, STRING-EXPR
          yields non-string value, the interpretation proceeds to the
          next clause.

    `(test PROC FORM ...)'
          A procedure PROC is applied on the result of STRING-EXPR.  If
          it yields true value, FORMs are evaluated, and `rxmatch-case'
          returns the result of the last FORM.

          If PROC yieds `#f', the interpretation proceeds to the next
          clause.

    `(test PROC => PROC2)'
          A procedure PROC is applied on the result of STRING-EXPR.  If
          it yields true value, PROC2 is applied on the result, and its
          result is returned as the result of `rxmatch-case'.

          If PROC yieds `#f', the interpretation proceeds to the next
          clause.

    `(else FORM ...)'
          This form must appear at the end of CLAUSEs, if any.  If
          other clauses fail, FORMs are evaluated, and the result of
          the last FORM becomes the result of `rxmatch-case'.

     If no `else' clause exists, and all other clause fail, an
     undefined value is returned.

     The `parse-date' example above becomes simpler if you use
     `rxmatch-case'
          (define (parse-date2 str)
            (rxmatch-case str
              (test (lambda (s) (not (string? s))) #f)
              (#/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/ (#f mm dd yyyy)
               (map string->number (list yyyy mm dd)))
              (#/^(\d\d\d\d)\/(\d\d?)\/(\d\d?)$/ (#f yyyy mm dd)
               (map string->number (list yyyy mm dd)))
              (#/^\d+\/\d+\/\d+$/                (#f)
               (error "ambiguous: ~s" str))
              (else (error "bogus: ~s" str))))

 -- Function: regexp-replace regexp string substitution
 -- Function: regexp-replace-all regexp string substitution
     Replaces the part of STRING that matched to REGEXP for
     SUBSTITUTION.  `regexp-replace' just replaces the first match of
     REGEXP, while `regexp-replace-all' repeats the replacing
     throughout entire STRING.

     SUBSTITUTION may be a string or a procedure.  If it is a string,
     it can contain a digit sequence preceded by a backslash (e.g.
     `\2') that refers the submatch.  `\0' refers to the entire match.
     Note that you need two backslashes to include backslash character
     in the literal string; if you want to include a backslash
     character itself in the SUBSTITUTION, you need four backslashes.

          (regexp-replace #/def|DEF/ "abcdefghi" "...")
            => "abc...ghi"
          (regexp-replace #/def|DEF/ "abcdefghi" "|\\0|")
            => "abc|def|ghi"
          (regexp-replace #/def|DEF/ "abcdefghi" "|\\\\0|")
            => "abc|\\0|ghi"
          (regexp-replace #/c(.*)g/ "abcdefghi" "|\\1|")
            => "ab|def|hi"

     If SUBSTITUTION is a procedure, for every match in STRING it is
     called with one argument, regexp-match object.  The returned value
     from the procedure is inserted to the output string using
     `display'.

          (regexp-replace #/c(.*)g/ "abcdefghi"
                          (lambda (m)
                            (list->string
                             (reverse
                              (string->list (rxmatch-substring m 1))))))
           => "abfedhi"

     Note: `regexp-replace-all' applies itself recursively to the
     remaining of the string after match.  So the beginning of string
     assertion in REGEXP doesn't only mean the beginning of input
     string.

 -- Function: regexp-quote string
     Returns a string with the characters that are special to regexp
     escaped.
          (regexp-quote "[2002/10/12] touched foo.h and *.c")
           => "\\[2002/10/12\\] touched foo\\.h and \\*\\.c"


File: gauche-refe.info,  Node: Reloading modules,  Next: Simple dispatcher,  Prev: Regular expression utilities,  Up: Library modules - Gauche extensions

9.17 `gauche.reload' - Reloading modules
========================================

 -- Module: gauche.reload
     In the development cycle, you often have to reload modules
     frequently.  This module supports it.

     Note that some part of semantics of the program depends on the
     order of loading modules, so reloading arbitrary modules may
     change the program behavior unexpectedly.  This module is for
     developers who knows what they are doing.

     *Redefinition rules*: Reloading a module resets all the binding in
     the module by default.  Sometimes it is not desirable, however.
     For example, you might have  a large list of objects that takes
     time to rebuild.  You can specify rules for the reloading
     procedure to determine which binding to keep.

     The rule is described in the following syntax.
            <module-rules> : (<module-rule> ...)
            <module-rule>  : (<module-pattern> <rule> ...)
            <module-pattern> : a symbol module name, or a symbol containing glob pattern
            <rule>         : procedure | symbol | regexp
                           | (and <rule> ...)
                           | (or  <rule> ...)
                           | (not <rule>)

     `<module-rules>' is the global rule to determine per-module rules.
     `<module-pattern>' is either a symbol module name or a symbol
     that contains glob pattern (e.g. `mylib.*').  If `<rule>' is a
     procedure, it is used as a predicate and the bindings whose value
     satisfies the predicate are kept from redefinition.   If `<rule>'
     is a symbol, the binding of the variable whose name is the symbol
     is kept.  If `<rule>' is a regexp, the bindings of the variable
     whose name matches the regexp are kept.

     Note that the mechanism to prevent redefinition is kind of ad-hoc
     hack and semantically unclean.  It's just for your convenience.
     Take a look at the code if you want to know the exact behavior.

 -- Function: reload module-name &optional rule ...
     Reloads the specified module.   You can optionally specify
     redefinition rules by RULE ..., where each RULE is the term
     `<rule>' defined above.

 -- Function: reload-modified-modules &optional module-rules
     Reloads module(s) that have been modified since they are loaded
     last time.  If optional MODULE-RULES is given, it is used to
     determine the redefinition rules for reloaded modules.  If
     MODULE-RULES is omitted, the current rules are used.  The default
     of current rules is empty.   You can set the current rules by
     `module-reload-rules'.

 -- Function: module-reload-rules &optional module-rules
     This is a parameter (*Note Parameters::) that keeps the default
     module rules for `reload-modified-modules'.  If called without
     arguments, returns the current module rules.  If called with
     MODULE-RULES, sets the argument to the current module rules.

 -- Function: reload-verbose &optional flag
     This is a parameter to control verbosity of the reloading
     procedures.  If called without arguments, returns the current
     verbosity flag.  If called with FLAG, it is set to the current
     verbosity flag.


File: gauche-refe.info,  Node: Simple dispatcher,  Next: Sequence framework,  Prev: Reloading modules,  Up: Library modules - Gauche extensions

9.18 `gauche.selector' - Simple dispatcher
==========================================

 -- Module: gauche.selector
     This module provides a simple interface to dispatch I/O events to
     registered handlers, based on `sys-select' (*Note I/O
     multiplexing::).

 -- Class: <selector>
     A dispatcher instance that keeps watching I/O ports with associated
     handlers.  A new instance can be created by `make' method.

 -- Method: selector-add! (self <selector>) port-or-fd proc flags
     Add a handler PROC to the selector.  PROC is called when
     PORT-OR-FD, which should be a port object or an integer that
     specifies a system file descriptor,  meets a certain condition
     specified by FLAGS.  FLAGS must be a list of one or more of the
     following symbols.
    `r'
          Calls PROC when data is available at PORT-OR-FD to read.

    `w'
          Calls PROC when PORT-OR-FD is ready to be written.

    `x'
          Calls PROC when an exceptional condition occurs on PORT-OR-FD.

     PROC is called with two arguments.  The first one is PORT-OR-FD
     itself, and the second one is a symbol `r', `w' or `x', indicating
     the condition.

     If a handler is already associated with PORT-OR-FD under the same
     condition, the previous handler is replaced by PROC.

 -- Method: selector-delete! (self <selector>) port-or-fd proc flags
     Deletes the handler entries that matches PORT-OR-FD, PROC and
     FLAGS.   One or more of the arguments may be `#f', meaning "don't
     care".  For example,
          (selector-delete! selector the-port #f #f)
     deletes all the handlers associated to THE-PORT, and
          (selector-delete! selector #f #f '(w))
     delets all the handlers waiting for writable condition.

 -- Method: selector-select (self <selector>) &optional (timeout #f)
     Dispatcher body.  Waits for the conditions registered in SELF, and
     when it occurs, calls the associated handler.  If the TIMEOUT
     argument is omitted or false, this method waits indefinitely.
     Alternatively you can give a timeout value, that can be a real
     number in microseconds, or a list of two integers that represents
     seconds and microseconds.

     Returns the number of handlers called.  Zero means the selector
     has been timed out.

     It is safe to modify SELF inside handler.  The change will be
     effective from the next call of `selector-select'

   This is a simple example of "echo" server:

     (use gauche.net)
     (use gauche.selector)

     (define (echo-server port)
       (let ((selector (make <selector>))
             (server   (make-server-socket 'inet port :reuse-addr? #t)))

         (define (accept-handler sock flag)
           (let* ((client (socket-accept server))
                  (output (socket-output-port client)))
             (selector-add! selector
                            (socket-input-port client :buffered? #f)
                            (lambda (input flag)
                              (echo client input output))
                            '(r))))

         (define (echo client input output)
           (let ((str (read-block 4096 input)))
             (if (eof-object? str)
                 (begin (selector-delete! selector input #f #f)
                        (socket-close client))
                 (begin (display str output)
                        (flush output)))))

         (selector-add! selector
                        (socket-fd server)
                        accept-handler
                        '(r))
         (do () (#f) (selector-select selector))))


File: gauche-refe.info,  Node: Sequence framework,  Next: Syslog,  Prev: Simple dispatcher,  Up: Library modules - Gauche extensions

9.19 `gauche.sequence' - Sequence framework
===========================================

 -- Module: gauche.sequence
     Provides a generic opertaions on _sequences_.  A sequence is a
     collection in which elements can be accessed by integer index,
     starting with zero.

     This module inherits `gauche.collection' (*Note Collection
     framework::), All the collection generic operations can be applied
     to a sequence as well.

     Among Gauche builtin class, lists, vectors and strings are
     sequences and the specialized methods are defined for them.
     Other extension types, such as SRFI-4 uniform vector, have the
     methods as well.

* Menu:

* Fundamental sequence accessors::
* Slicing sequence::
* Mapping over sequences::
* Selection and searching in sequence::
* Implementing sequence::


File: gauche-refe.info,  Node: Fundamental sequence accessors,  Next: Slicing sequence,  Prev: Sequence framework,  Up: Sequence framework

9.19.1 Fundamental sequence accessors
-------------------------------------

 -- Method: ref (seq <sequence>) index &optional fallback
     Returns INDEX-th element of the sequence SEQ.  This method enables
     uniform access for any sequence types.

     When INDEX is less than zero, or greater than or equal to the size
     of the sequence, FALLBACK is returned if provided, or an error is
     signalled if not.

          (ref '(a b c) 1)  => b
          (ref '#(a b c) 1) => b
          (ref "abc" 1)     => #\b

 -- Method: (setter ref) (seq <sequence>) index value
     Sets VALUE to the INDEX-th element of the sequence SEQ.  This is
     the uniform sequence modifier.

          (let ((x (list 'a 'b 'c)))
            (set! (ref x 1) 'z)
            x) => (a z c)

          (let ((x (vector 'a 'b 'c)))
            (set! (ref x 1) 'z)
            x) => #(a z c)

          (let ((x (string #\a #\b #\c)))
            (set! (ref x 1) #\z)
            x) => "azc"

 -- Method: referencer (seq <sequence>)

 -- Method: modifier (seq <sequence>)


File: gauche-refe.info,  Node: Slicing sequence,  Next: Mapping over sequences,  Prev: Fundamental sequence accessors,  Up: Sequence framework

9.19.2 Slicing sequence
-----------------------

 -- Method: subseq (seq <sequence>) &optional start end
     Retrieve a subsequence of the sequence SEQ, from START-th element
     (inclusive) to END-th element (exclusive).  If END is omitted, up
     to the end of sequence is taken.  The type of the returned
     sequence is the same as SEQ.

          (subseq '(a b c d e) 1 4)   => (b c d)
          (subseq '#(a b c d e) 1 4)  => #(b c d)
          (subseq "abcde" 1 4)        => "bcd"

          (subseq '(a b c d e) 3)     => (d e)

 -- Method: (setter subseq) (seq <sequence>) start end value-seq
 -- Method: (setter subseq) (seq <sequence>) start value-seq
     Sets the elements of VALUE-SEQ from the START-th element
     (inclusive) to the END-th element (exclusive) of the sequence SEQ.
     VALUE-SEQ can be any sequence, but its size must be larger than
     (END - START).

     In the second form, END is figured out by the length of VALUE-SEQ.

          (define s (vector 'a 'b 'c 'd 'e))
          (set! (subseq s 1 4) '(4 5 6))
          s => #(a 4 5 6 e)
          (set! (subseq s 0)   "ab")
          s => #(#\a #\b 5 6 e)


File: gauche-refe.info,  Node: Mapping over sequences,  Next: Selection and searching in sequence,  Prev: Slicing sequence,  Up: Sequence framework

9.19.3 Mapping over sequences
-----------------------------

You can use extended `fold', `map', `for-each' and other generic
functions on sequences, since a sequence is also a collection.
However, sometimes you want to have index as well as the element itself
during iteration.   There are several generic functions for it.

 -- Method: fold-with-index kons knil (seq <sequence>) ...
     Like generic `fold', except KONS is given the index within SEQ, as
     the first argument, as well as each element from SEQs and the
     accrued value.

          (fold-with-index acons '() '(a b c))
            => ((2 . c) (1 . b) (0 . a))

 -- Method: map-with-index proc (seq <sequence>) ...
 -- Method: map-to-with-index class proc (seq <sequence>) ...
 -- Method: for-each-with-index proc (seq <sequence>) ...
     Like `map', `map-to' and `for-each', except PROC receives the
     index as the first argument.

          (map-with-index list '(a b c d) '(e f g h))
            => ((0 a e) (1 b f) (2 c g) (3 d h))

          (map-to-with-index <vector> cons '(a b c d))
            => #((0 . a) (1 . b) (2 . c) (3 . d))

 -- Method: find-with-index pred (seq <sequence>)
     Finds the first element in SEQ that satisfies PRED like `find',
     but returns two values, the index of the element and the element
     itself.   If no element satisfies PRED, two `#f''s are returned.

          (find-with-index char-upper-case? "abraCadabra")
            => 4 and #\C

          (find-with-index char-numeric? "abraCadabra")
            => #f and #f

 -- Method: find-index pred (seq <sequence>)
     Like `find', but returns the index of the first element that
     satisfies PRED in SEQ, instead of the element itself.  If no
     element in SEQ satisfies PRED, `#f' is returned.

          (find-index char-upper-case? "abraCadabra")
            => 4

          (find-index char-numeric? "abraCadabra")
            => #f

     See also `list-index' in SRFI-1 (*Note SRFI-1 Searching::).


File: gauche-refe.info,  Node: Selection and searching in sequence,  Next: Implementing sequence,  Prev: Mapping over sequences,  Up: Sequence framework

9.19.4 Selection and searching in sequence
------------------------------------------

Note that selection and searching methods for collections can also be
applied to sequences.  See *Note Selection and searching in
collection::.

 -- Generic function: group-sequence seq &keyword key test
     Groups consecutive elements in a sequence SEQ which have the
     common key value.  A key value of an element is obtained by
     applying the procedure KEY to the element; the default procedure
     is `identity'.  For each element in SEQ, KEY is applied exactly
     once.  The equal-ness of keys are compared by TEST procedure,
     whose default is `eqv?'.

          (group-sequence '(1 1 1 2 3 4 4 2 2 3 1 1 3))
            => ((1 1 1) (2) (3) (4 4) (2 2) (3) (1 1) (3))

          (group-sequence '(1 1 1 2 3 4 4 2 2 3 1 1 3)
                          :key (cut modulo <> 2)))
            => ((1 1 1) (2) (3) (4 4 2 2) (3 1 1 3))

          (group-sequence '#("a" "a" "b" "b" "c" "d" "d")
                          :test string=?)
            => (("a" "a") ("b" "b") ("c") ("d" "d"))

          (group-sequence "aabbcdd"
                          :test char=?)
            => ((#\a #\a) (#\b #\b) (#\c) (#\d #\d))

     This method is similar to Haskell's `group'.  If you want to group
     elements that are not adjacent, use `group-collection' (*Note
     Selection and searching in collection::).



File: gauche-refe.info,  Node: Implementing sequence,  Prev: Selection and searching in sequence,  Up: Sequence framework

9.19.5 Implementing sequence
----------------------------


File: gauche-refe.info,  Node: Syslog,  Next: Termios,  Prev: Sequence framework,  Up: Library modules - Gauche extensions

9.20 `gauche.syslog' - Syslog
=============================

 -- Module: gauche.syslog
     This module provides syslog(3) system logger interface.

     For the common applications, you might find `gauche.logger' module
     easier to use (*Note User-level logging::).  This module is for
     those who need direct access to the syslog API.

     The procedures are only defined if the undelying system supports
     them.

 -- Function: sys-openlog ident option facility
     [POSIX] Opens a connection to the system logger.  A string argument
     IDENT is used for the prefix of the log, and usually is the
     program name.  OPTION is an integer flag to control the behavior
     of logging, and FACILITY is an integer that specify the type of
     the program.

     The flag for OPTION can be composed by `logior'-ing one or more of
     the following integer constants: `LOG_CONS', `LOG_NDELAY',
     `LOG_NOWAIT', `LOG_ODELAY', `LOG_PERROR' and `LOG_PID'.  (Some of
     the constants may not be defined if the underlying system doesn't
     support them).

     The FACILITY argument can be one of the following integer
     constants: `LOG_AUTH', `LOG_AUTHPRIV', `LOG_CRON', `LOG_DAEMON',
     `LOG_FTP', `LOG_KERN', `LOG_LOCAL0' through `LOG_LOCAL7',
     `LOG_LPR', `LOG_MAIL', `LOG_NEWS', `LOG_SYSLOG', `LOG_USER' and
     `LOG_UUCP'.  (Some of the constants may not be defined if the
     underlying system doesn't support them).

     See your system's manpage of openlog(3) for detail description
     about these constants.  Log the string MESSAGE.  Unlike syslog(3),
     this procedure doesn't do formatting--you can use `format' (*Note
     Output::) to create a formatted message, or use higher-level
     routine `log-format' (*Note User-level logging::).

     An integer argument PRIORITY can be composed by `logior'-ing one
     of the FACILITY constants described above and the LEVEL constants:
     `LOG_EMERG', `LOG_ALERT', `LOG_CRIT', `LOG_ERR', `LOG_WARNING',
     `LOG_NOTICE', `LOG_INFO', `LOG_DEBUG'.


 -- Function: sys-closelog
     [POSIX] Closes the connection to the logging system.

 -- Function: sys-setlogmask mask
     [POSIX] Sets the process's log priority mask that determines which
     calls to `sys-syslog' may be logged.  An priority MASK can be
     composed by `logior'-ing bitmasks corresponding to the LEVEL
     argument of `sys-syslog'.  You can use `sys-logmask' below to
     obtain a bitmask from the level.

 -- Function: sys-logmask level
     [POSIX] Returns an integer bitmask for `sys-setlogmask' from the
     log level LEVEL.


File: gauche-refe.info,  Node: Termios,  Next: Unit testing,  Prev: Syslog,  Up: Library modules - Gauche extensions

9.21 `gauche.termios' - Termios
===============================

 -- Module: gauche.termios
     This module defines POSIX termios interface, which controls
     terminal attributes.  This module also provides pseudo tty
     interface, if the system provides it.

 -- Builtin Class: <sys-termios>
     POSIX termios(7) structure.

      -- Instance Variable of <sys-termios>: iflag

      -- Instance Variable of <sys-termios>: oflag

      -- Instance Variable of <sys-termios>: cflag

      -- Instance Variable of <sys-termios>: lflag

      -- Instance Variable of <sys-termios>: cc

     The slots `iflag', `oflag', `cflag' and `lflag' contains
     non-negative integers representing bitmasks.

     The slot `cc' contains a _copy_ of `c_cc' array of `struct
     termios', as an u8vector (see *Note Uniform vectors:: for the
     details about u8vector).  Since `cc' slot is a copy of the
     internal structure, you have to `set!' an u8vector to the slot
     explicitly to make changes to the `c_cc' array.


   Throughout this section, argument PORT-OR-FD refers to either a port
object or a small integer representing system's file descriptor.  If
PORT is not associated to the system terminal, an error is signalled.
(You can check if PORT has an associated terminal by `sys-isatty?'.
*Note Other file operations::).

 -- Function: sys-tcgetattr port-or-fd
     Returns terminal parameters in a `<sys-termios>' object,
     associated to PORT-OR-FD.

 -- Function: sys-tcsetattr port-or-fd when termios
     Sets terminal parameters associated to PORT-OR-FD by TERMIOS,
     which must be an instance of `<sys-termios>'.

     An integer argument WHEN specifies when the changes take effect.
     Three variables are pre-defined for the argument:
    `TCSANOW'
          The change is reflected immediately.

    `TCSADRAIN'
          The change is reflected after all pending output is flushed.

    `TCSAFLUSH'
          The change is reflected after all pending output is flushed,
          and all pending input is discarded.

 -- Function: sys-tcsendbreak port-or-fd duration
     Transmits a zero stream for the specified duration to the terminal
     associated to PORT-OR-FD.  The unit of duration depends on the
     system; see man tcsendbreak(3) of your system for details.

 -- Function: sys-tcdrain port-or-fd
     Waits until all output written to PORT-OR-FD is transmitted.

 -- Function: sys-tcflush port-or-fd queue
     Discards data in the buffer of PORT-OR-FD, specified by QUEUE,
     which may be one of the following values.
    `TCIFLUSH'
          Discards data received but not read.

    `TCOFLUSH'
          Discards data written but not transmitted.

    `TCIOFLUSH'
          Do both `TCIFLUSH' and `TCOFLUSH' action.

 -- Function: sys-tcflow port-or-fd action
     Controls data flow of PORT-OR-FD by ACTION, which may be one of
     the following values:
    `TCOOFF'
          Suspends output transmission.

    `TCOON'
          Restarts output transmission.

    `TCIOFF'
          Transmits a STOP character to make the terminal device stop
          transmitting data to the system.

    `TCION'
          Transmits a START character to make the terminal device
          resume transmitting data to the system.

 -- Function: sys-tcgetpgrp port-or-fd
     Returns process group ID of the terminal associated to PORT-OR-FD.

 -- Function: sys-tcsetpgrp port-or-fd pgrp
     Sets process group ID of the terminal associated to PORT-OR-FD to
     PGRP.

 -- Function: sys-cfgetispeed termios
 -- Function: sys-cfsetispeed termios speed
 -- Function: sys-cfgetospeed termios
 -- Function: sys-cfsetospeed termios speed
     Gets/sets input/output speed (baud rate) parameter stored in
     TERMIOS object.   Speed is represented by the following predefined
     numbers: `B0', `B50', `B75', `B110', `B134', `B150', `B200',
     `B300', `B600', `B1200', `B1800', `B2400', `B4800', `B9600',
     `B19200', `B38400'.

     Some system may support higher baud rate, such as `B57600',
     `B115200' or `B230400'.  You can use `symbol-bound?' to check
     these options are defined.  `B0' is used to terminate the
     connection.

 -- Function: sys-openpty &optional term
     Opens a pair of pseudo ttys, one for master and the other for
     slave, then returns two integers which are their file descriptors.
     An optional argument TERM must be, if passed, a `<sys-termios>'
     object; it sets the slave pty's parameters.

     You can use `open-input-fd-port' and/or `open-output-fd-port' to
     create a port around the returned file descriptor (*Note File
     ports::).  To obtain pseudo tty's name, use `sys-ttyname' (*Note
     Other file operations::).

     This function is available only if the system supports
     `openpty(3)'.

 -- Function: sys-forkpty &optional term
     Opens a pair of pseudo ttys, one for master and the other for
     slave, sets the slave pty suitable for login terminal, then
     fork(2).

     Returns two integers; the first value is a child pid for the
     parent process, and 0 for the child process.  The second value is
     a file descriptor of the master pty.

     An optional argument TERM must be, if passed, a `<sys-termios>'
     object; it sets the slave pty's parameters.

     This function is available only if the system supports
     `forkpty(3)'.

   The following example shows how to get a password from the user
without echoing:

     (use gauche.termios)

     (define (get-password prompt)
       (let* ((port (current-input-port))
              (attr (sys-tcgetattr port))
              (lflag (slot-ref attr 'lflag)))
         ;; Show prompt
         (display prompt)
         (flush)
         ;; Turn off echo during reading.
         (dynamic-wind
          (lambda ()
            (slot-set! attr 'lflag (logand lflag (lognot ECHO)))
            (sys-tcsetattr port TCSAFLUSH attr))
          (lambda ()
            (read-line port))
          (lambda ()
            (slot-set! attr 'lflag lflag)
            (sys-tcsetattr port TCSANOW attr)))))


File: gauche-refe.info,  Node: Unit testing,  Next: Threads,  Prev: Termios,  Up: Library modules - Gauche extensions

9.22 `gauche.test' - Unit Testing
=================================

 -- Module: gauche.test
     Defines a set of functions to write test scripts.  A test script
     will look like this:
          (use gauche.test)
          (test-start "my feature")
          (load "my-feature")  ; load your program
          (import my-feature)  ; if your program defines a module.

          (test-module 'my-feature) ; tests consistency in your module.

          (test-section "feature group 1")
          (test "feature 1-1" EXPECT (lambda () TEST-BODY))
          (test "feature 1-2" EXPECT (lambda () TEST-BODY))
           ...

          (test-section "feature group 2")
          (define test-data ...)
          (test "feature 2-1" EXPECT (lambda () TEST-BODY))
          (test "feature 2-2" *test-error* (lambda () TEST-THAT-SIGNALS-ERROR))
           ...

          (test-end)

     With this convention, you can run test both interactively or in
     batch.   To run a test interactively, just load the file and it
     reports a result of each test, as well as the summary of failed
     test at the end.  To run a test in batch, it is convenient to
     redirect the stdout to some file If stdout is redirected to other
     than tty, all the verbose logs will go there, and only a small
     amount of messages go to stderr.

     It is recommended to have a "test" target always in Makefile of
     your module/program, so that the user of your program can run a
     test easily.  The rule may look like this:

          test :
                  gosh my-feature-test.scm > test.log


 -- Function: test name expected thunk &optional compare
     Calls THUNK, and compares its result with EXPECTED.  The
     comparison predicate is `equal?' by default, but you can specify
     your own predicate by the argument COMPARE.  NAME is a name of the
     test, for logging purpose.

     If THUNK signals an uncaptured error, it is catched and yields a
     special error object.  A global variable `*test-error*' is bound
     to the error object, so that you can test an expected error.

     The procedure COMPARE is called as follows:
          (COMPARE EXPECTED RESULT-OF-THUNK)
     It should return `#t' if the given result agrees the expected
     value, or `#f' otherwise.  One typical usage of the custom
     comparison method is to compare inexact numbers tolerating small
     error.

          (test "test 1" (/ 3.141592653589 4)
                (lambda () (atan 1))
                (lambda (expected result)
                  (< (abs (- expected result)) 1.0e-10)))

 -- Variable: *test-error*
     Bound to a special error object, which can be used as an expected
     value if the test thunk is supposed to signal an error.

          (test "test if car signals an error" *test-error*
                (lambda () (car 5)))

 -- Variable: *test-report-error*
     If this variable is true, the `test' routine prints stack trace to
     the current error port when it captures an error.  It is useful
     when you got an unexpected test-error object and want to check out
     where the error is occurring.

     This variable is initialized by the environment variable
     `GAUCHE_TEST_REPORT_ERROR' when the `gauche.test' module is
     loaded.  For example, you can use the environment variable to
     check out an unexpected error from your test script as follows
     (the value of the environment variable doesn't matter).

          env GAUCHE_TEST_REPORT_ERROR=1 gosh mytest.scm

 -- Macro: test* name expected expr &optional compare
     A convenience macro that wraps EXPR by lambda.

          (test* name expected expr)
            == (test name expected (lambda () expr))

 -- Function: test-module module
     MODULE must be a symbol module name or a module.  This procedure
     performs some heuristic consistency check of the given module: (1)
     whether symbols set as autoload in MODULE can actually be loaded,
     and (2) whether the symbols declared in export list is actually
     defined in the module.   Although not perfect, this test can catch
     some careless typo in symbol names.

 -- Function: test-start module-name
     Initializes internal state and prints a log header.  This should
     be called before any tests.  MODULE-NAME is used only for logging
     purpose.

 -- Function: test-section section-name
     Marks beginning of the group of tests.  This is just for logging.

 -- Function: test-end
     Prints out list of failed tests.


File: gauche-refe.info,  Node: Threads,  Next: Measure timings,  Prev: Unit testing,  Up: Library modules - Gauche extensions

9.23 `gauche.threads' - Threads
===============================

If enabled at compilation time, Gauche can use threads built on top of
POSIX threads (pthreads).

 -- Module: gauche.threads
     Provides thread API.   You can 'use' this module regardless
     whether the thread support is compiled in or not; if threads are
     not supported, many thread-related procedures simply signals a
     "not supported" error.

   To check if threads are available in the running Gauche program, use
the following procedure.

 -- Function: gauche-thread-type
     Returns a symbol that indicates the supported thread type.  In the
     current version, the return value may be `pthread' when threads on
     top of POSIX threads are available, or `none' when threads are not
     available.

   Scheme-level thread API conforms SRFI-18, "Multithreading support"
(*Note [SRFI-18]: srfi-18.), wrapped around Gauche's object interface.

* Menu:

* Thread programming tips::
* Thread procedures::
* Synchronization primitives::
* Thread exceptions::


File: gauche-refe.info,  Node: Thread programming tips,  Next: Thread procedures,  Prev: Threads,  Up: Threads

9.23.1 Thread programming tips
------------------------------

Although the surface API of threads looks simple and portable, you need
to know how the threads are implemented in order to utilize the
feature's potential.   Some languages support threads as language's
built-in construct and encourage programmers to express the calculation
in terms of threads.  However, it should be noted that in many cases
there are alternative ways than threads to implement the desired
algorithm, and you need to compare advantages and disadvantages of
using threads depending on how the threads are realized in the
underlying system.

   In Gauche, the primary purpose of threads is to write programs that
_require_ preemptive scheduling, therefore are difficult to express in
other ways.  Preemptive threads may be required, for example, when you
have to call a module that does blocking I/O which you can't intercept,
or may spend nondeterministic amount of calculation time that you want
to interrupt.

   For each Gauche's thread, an individual VM is allocated and it is
run by the dedicated POSIX thread.  Thus there is not much overhead in
context switch than the native thread, but the creation of threads
costs much higher than, say, lightweight threads built on top of
call/cc.  So Gauche's preemptive threads are _not_ designed for
applications that want to create thousands of threads for fine-grained
calculation.

   The recommended usage is the technique so called "thread pool", that
you create a set of threads and keep them around for long time and
dispatch jobs to them as needed.

   Preemptive threads have other difficulties (e.g. see *Note
[FairThreads]: fairthreads.), and sometimes the alternatives may be a
better fit than the native preemptive threads.

   * If what you need is just a concurrent calculation, you might be
     able to use cooperative thread technique built on top of
     `call/cc'.   Creating call/cc-based threads is much faster than
     creating native threads.

   * If what you need is to deal with blocking I/O, and you have all
     your code at hand, it is sometimes easier to use good old
     `select'-based dispatching (*Note Simple dispatcher::, for
     example).

   * If what you need is to control the resouce consumption in the
     subsystem, and the subsystem works fairly independently from the
     main system, you may be able to use Unix processes instead of
     threads.  It may sound to go backward, but Unix process does
     provide higher "shield" between the subsystem and the main system
     (e.g. the main system can keep running even if subsystem
     segfaults).


   Of course, these technique are not mutually exclusive with native
threads.  You can use dispatcher with "thread pool" technique, for
example.   Just keep it in your mind that the native threads are not
only but one of the ways to realize those features.


File: gauche-refe.info,  Node: Thread procedures,  Next: Synchronization primitives,  Prev: Thread programming tips,  Up: Threads

9.23.2 Thread procedures
------------------------

 -- Builtin Class: <thread>
     A thread.  Each thread has an associated thunk which is evaluated
     by a POSIX thread.  When thunk returns normally, the result is
     stored in the internal 'result' slot, and can be retrieved by
     `thread-join!'.  When thunk terminates abnormally, either by
     raising an exception or terminated by `thread-terminate!', the
     exception condition is stored in their internal 'result exception'
     slot, and will be passed to the thread calling `thread-join!' on
     the terminated thread.

     Each thread has its own dynamic environment and dynamic handler
     stack.  When a thread is created, its dynamic environment is
     initialized by the creator's dynamic environment.  The thread's
     dynamic handler stack is initially empty.

     Access to the resouces shared by multiple threads must be protected
     explicitly by synchronization primitives.  *Note Synchronization
     primitives::.

     Access to ports are serialized by Gauche. If multiple threads
     attempt to write to a port, their output may be interleaved but no
     output will be lost, and the state of the port is kept consistent.
     If multiple threads attempt to read from a port, a single read
     primitive (e.g. `read', `read-char' or `read-line') works
     atomically.

     Signal handlers are shared by all threads, but each thread has its
     own signal mask.  *Note Signals and threads::, for details.

     A thread object has the following external slots.

      -- Instance Variable of <thread>: name
          A name can be associated to a thread.  This is just for the
          convenience of the application.  The primordial thread has
          the name "`root'".

      -- Instance Variable of <thread>: specific
          A thread-local slot for use of the application.

 -- Function: current-thread
     [SRFI-18], [SRFI-21] Returns the current thread.

 -- Function: thread? obj
     [SRFI-18], [SRFI-21] Returns `#t' if OBJ is a thread, `#f'
     otherwise.

 -- Function: make-thread thunk &optional name
     [SRFI-18], [SRFI-21] Creates and returns a new thread.  To run the
     thread, you need to call `thread-start!'.

     You can provide the name of the thread by the optional argument
     NAME.

     Internally, this procedure just allocates and initializes a Scheme
     thread object; the POSIX thread is not created until
     `thread-start!'  is called.

 -- Function: thread-name thread
     [SRFI-18], [SRFI-21] Returns the value of NAME slot of THREAD.

 -- Function: thread-specific thread
 -- Function: thread-specific-set! thread value
     [SRFI-18], [SRFI-21] Gets/sets the value of the THREAD's specific
     slot.

 -- Function: thread-start! thread
     [SRFI-18], [SRFI-21] Starts the THREAD.  It is an error if THREAD
     is already started.  Returns THREAD.

 -- Function: thread-yield!
     [SRFI-18], [SRFI-21] Suspends the execution of the calling thread
     and yields CPU to other waiting runnable threads, if any.

 -- Function: thread-sleep! timeout
     [SRFI-18], [SRFI-21] Suspends the calling thread for the period
     specified by TIMEOUT, which must be either a `<time>' object
     (*Note Time::) that specifies absolute point of time, or a real
     number that specifies relative point of time from the time this
     procedure is called in number of seconds.

     After the specified time passes, `thread-sleep!' returns with
     unspecified value.

     If TIMEOUT points a past time, `thread-sleep!' returns immediately.

 -- Function: thread-terminate! thread
     [SRFI-18], [SRFI-21] Terminates the specified thread THREAD.  The
     THREAD is terminated and an instance of
     `<terminated-thread-exception>' is stored in the result exception
     field of THREAD.

     If THREAD is the same as the calling thread, this procedure won't
     return.  Otherwise, this procedure returns unspecified value.

     This procedure should be used with care, since THREAD won't have a
     chance to call cleanup procedures (such as 'after' thunks of
     `dynamic-wind') If THREAD is in the critical section, it leaves
     some state inconsistent.  However, once a thread is terminated,
     any mutex that the thread has kept becomes 'abandoned' state, and
     an attempt to lock such a mutex by other thread raises an
     'abandoned mutex exception', so that you will know the situation.
     *Note Synchronization primitives::.

 -- Function: thread-join! thread &optional timeout timeout-val
     [SRFI-18], [SRFI-21] Waits termination of THREAD, or until the
     timeout is reached if TIMEOUT is given.

     TIMEOUT must be either a `<time>' object (*Note Time::) that
     specifies absolute point of time, or a real number that specifies
     relative point of time from the time this procedure is called in
     number of seconds, or `#f' that indicates no timeout (default).

     If THREAD terminates normally, `thread-join!' returns a value
     which is stored in the result field of THREAD.  If THREAD
     terminates abnormally, `thread-join!' raises an exception which is
     stored in the result exception field of THREAD.

     If the timeout is reached, THREAD-JOIN! returns TIMEOUT-VAL if
     given, or raises `<join-timeout-exception>'.


File: gauche-refe.info,  Node: Synchronization primitives,  Next: Thread exceptions,  Prev: Thread procedures,  Up: Threads

9.23.3 Synchronization primitives
---------------------------------

 -- Builtin Class: <mutex>
     A primitive synchronization device.  It can take one of four
     states: locked/owned, locked/not-owned, unlocked/abandoned and
     unlocked/not-abandoned.  A mutex can be locked (by `mutex-lock!')
     only if it is in unlocked state.  An 'owned' mutex keeps a thread
     that owns it.  Typically an owner thread is the one that locked
     the mutex, but you can make a thread other than the locking thread
     own a mutex.  A mutex becomes unlocked either by `mutex-unlock!'
     or the owner thread terminates.  In the former case, a mutex
     becomes unlocked/not-abandoned state.  In the latter case, a mutex
     becomes unlocked/abandoned state.

     A mutex has the following external slots.

      -- Instance Variable of <mutex>: name
          The name of the mutex.

      -- Instance Variable of <mutex>: state
          The state of the mutex.  This is a read-only slot.  See the
          descrption of `mutex-state' below.

      -- Instance Variable of <mutex>: specific
          A slot an application can keep arbitrary data.  For example,
          an application can implement a 'recursive' mutex using the
          specific field.

 -- Function: mutex? obj
     [SRFI-18], [SRFI-21] Returns `#t' if OBJ is a mutex, `#f'
     otherwise.

 -- Function: make-mutex &optional name
     [SRFI-18], [SRFI-21] Creates and returns a new mutex object.  When
     created, the mutex is in unlocked/not-abandoned state.
     Optionally, you can give a name to the mutex.

 -- Function: mutex-name mutex
     [SRFI-18], [SRFI-21] Returns the name of the mutex.

 -- Function: mutex-specific mutex
 -- Function: mutex-specific-set! mutex value
     [SRFI-18], [SRFI-21] Gets/sets the specific value of the mutex.

 -- Function: mutex-state mutex
     [SRFI-18], [SRFI-21] Returns the state of MUTEX, which may be one
     of the followings:

    a thread
          The mutex is locked/owned, and the owner is the returned
          thread.

    symbol `not-owned'
          The mutex is locked/not-owned.

    symbol `abandoned'
          The mutex is unlocked/abandoned.

    symbol `not-abandoned'
          The mutex is unlocked/not-abandoned.

 -- Function: mutex-lock! mutex &optional timeout thread
     [SRFI-18], [SRFI-21] Locks MUTEX.  If MUTEX is in
     unlocked/not-abandoned state, this procedure changes its state to
     locked state exclusively.  By default, MUTEX becomes locked/owned
     state, owned by the calling thread.  You can give other owner
     thread as THREAD argument.  If THREAD argument is given and `#f',
     the mutex becomes locked/not-owned state.

     If MUTEX is in unlocked/abandoned state, that is, some other
     thread has been terminated without unlocking it, this procedure
     signals 'abandoned mutex exception' (*Note Thread exceptions::)
     after changing the state of MUTEX.

     If MUTEX is in locked state and TIMEOUT is omitted or `#f', this
     procedure blocks until MUTEX becomes unlocked.   If TIMEOUT is
     specified, `mutex-lock!' returns when the specified time reaches in
     case it couldn't obtain a lock.  You can give TIMEOUT an absolute
     point of time (by `<time>' object, *Note Time::), or a relative
     time (by a real number).

     `Mutex-lock!' returns `#t' if MUTEX is successfully locked, or
     `#f' if timeout reached.

     Note that MUTEX itself doesn't implements a 'recursive lock'
     feature; that is, if a thread that has locked MUTEX tries to lock
     MUTEX again, the thread blocks.  It is not difficult, however, to
     implement a recursive lock semantics on top of this mutex.  The
     following example is taken from SRFI-18 document:

          (define (mutex-lock-recursively! mutex)
            (if (eq? (mutex-state mutex) (current-thread))
                (let ((n (mutex-specific mutex)))
                  (mutex-specific-set! mutex (+ n 1)))
                (begin
                  (mutex-lock! mutex)
                  (mutex-specific-set! mutex 0))))

          (define (mutex-unlock-recursively! mutex)
            (let ((n (mutex-specific mutex)))
              (if (= n 0)
                  (mutex-unlock! mutex)
                  (mutex-specific-set! mutex (- n 1)))))

 -- Function: mutex-unlock! mutex &optional condition-variable timeout
     [SRFI-18], [SRFI-21] Unlocks MUTEX.  The state of MUTEX becomes
     unlocked/not-abandoned.  It is allowed to unlock a mutex that is
     not owned by the calling thread.

     If optional CONDITION-VARIABLE is given, `mutex-unlock!' serves
     the "condition variable wait" operation (e.g. `pthread_cond_wait'
     in POSIX threads).   The current thread atomically wait on
     CONDITION-VARIABLE and unlocks MUTEX.  The thread will be
     unblocked when other thread signals on CONDITION-VARIABLE (see
     `condition-variable-signal!' and `condition-variable-broadcast!'
     below), or TIMEOUT reaches if it is supplied.  The TIMEOUT
     argument can be either a `<time>' object to represent an absolute
     time point (*Note Time::), a real number to represent a relative
     time in seconds, or `#f' which means never.  The calling thread
     may be unblocked prematurely, so it should reacquire the lock of
     MUTEX and checks the condition, as in the follwing example (it is
     taken from SRFI-18 document):

          (let loop ()
            (mutex-lock! m)
            (if (condition-is-true?)
                (begin
                  (do-something-when-condition-is-true)
                  (mutex-unlock! m))
                (begin
                  (mutex-unlock! m cv)
                  (loop))))

 -- Function: with-locking-mutex mutex thunk
     Calls THUNK with locking a mutex MUTEX.  This is defined as
     follows.
          (define (with-locking-mutex mutex thunk)
            (dynamic-wind
             (lambda () (mutex-lock! mutex))
             thunk
             (lambda () (mutex-unlock! mutex))))

 -- Builtin Class: <condition-variable>
     A condition variable keeps a set of threads that are waiting for a
     certain condition to be true.  When a thread modifies the state of
     the concerned condition, it can call `condition-variable-signal!'
     or `condition-variable-broadcast!', which unblock one or more
     waiting threads so that they can check if the condition is
     satisfied.

     A condition variable object has the following slots.

      -- Instance Variable of <mutex>: name
          The name of the condition variable.

      -- Instance Variable of <mutex>: specific
          A slot an application can keep arbitrary data.

     Note that SRFI-18 doesn't have a routine equivalent to pthreads'
     `pthread_cont_wait'.  If you want to wait on condition variable,
     you can pass a condition variable to `mutex-unlock!' as an
     optional argument (see above), then acquire mutex again by
     `mutex-lock!'.  This design is for flexibility; see SRFI-18
     document for the details.

     This is the common usage of pthreads' condition variable:
          while (some_condition != TRUE) {
            pthread_cond_wait(condition_variable, mutex);
          }
     And it can be translated to SRFI-18 as follows:
          (let loop ()
            (unless some-condition
              (mutex-unlock! mutex condition-variable)
              (mutex-lock! mutex)
              (loop)))

 -- Function: condition-variable? obj
     [SRFI-18], [SRFI-21] Returns `#t' if OBJ is a condition variable,
     `#f' otherwise.

 -- Function: make-condition-variable &optional name
     [SRFI-18], [SRFI-21] Returns a new condition variable.  You can
     give its name by optional NAME argument.

 -- Function: condition-variable-name cv
     [SRFI-18], [SRFI-21] Returns the name of the condition variable.

 -- Function: condition-variable-specific cv
 -- Function: condition-variable-specific-set! cv value
     [SRFI-18], [SRFI-21] Gets/sets the specific value of the condition
     variable.

 -- Function: condition-variable-signal! cv
     [SRFI-18], [SRFI-21] If there are threads waiting on CV, causes
     the scheduler to select one of them and to make it runnable.

 -- Function: condition-variable-broadcast! cv
     [SRFI-18], [SRFI-21] Unblocks all the threads waiting on CV.


File: gauche-refe.info,  Node: Thread exceptions,  Prev: Synchronization primitives,  Up: Threads

9.23.4 Thread exceptions
------------------------

Some types of exceptions may be thrown from thread-related procedures.
These exceptions can be handled by Gauche's exception mechanism (*Note
Exceptions::).

 -- Builtin Class: <thread-exception>
     A base class of thread-related exceptions.  Inherits `<exception>'
     class.  It has one slot.

      -- Instance Variable of <thread-exception>: thread
          A thread that threw this exception.

 -- Builtin Class: <join-timeout-exception>
     An exception thrown by `thread-join!' when a timeout reaches
     before the waited thread returns.  Inherits `<thread-exception>'.

 -- Builtin Class: <abandoned-mutex-exception>
     An exception thrown by `mutex-lock!' when a MUTEX to be locked is
     in unlocked/abandoned state.  Inherits `<thread-exception>'.  It
     has one additional slot.

      -- Instance Variable of <abandoned-mutex-exception>: mutex
          A mutex that caused this exception.

 -- Builtin Class: <terminated-thread-exception>
     An exception thrown by `thread-join!' when the waited thread is
     terminated abnormally (by `thread-terminate!').  Inherits
     `<thread-exception>'.  It has one additional slot.

      -- Instance Variable of <terminated-thread-exception>: terminator
          A thread that terminated the thread that causes this
          exception.

 -- Builtin Class: <uncaught-exception>
     An exception thrown by `thread-join!' when the waited thread is
     terminated by an uncaught exception.  Inherits
     `<thread-exception>'.  It has one additional slot.

      -- Instance Variable of <uncaught-exception>: reason
          An exception that caused the termination of the thread.

 -- Function: join-timeout-exception? obj
 -- Function: abandoned-mutex-exception? obj
 -- Function: terminated-thread-exception? obj
 -- Function: uncaught-exception? obj
     [SRFI-18], [SRFI-21] These procedures checks if OBJ is a certain
     type of exception.  Provided for the compatibility to SRFI-18.

 -- Function: uncaught-exception-reason exc
     [SRFI-18], [SRFI-21] Returns the value of `reason' slot of
     `<uncaught-exception>' object.  Provided for the compatibility to
     SRFI-18.


File: gauche-refe.info,  Node: Measure timings,  Next: Uniform vectors,  Prev: Threads,  Up: Library modules - Gauche extensions

9.24 `gauche.time' - Measure timings
====================================

 -- Module: gauche.time
     Provides two simple ways to measure execution time of Scheme code.
     A macro `time', which is convenient for interactive use, and
     `<time-counter>' objects which are useful to be embedded in the
     program.

 -- Macro: time expr expr2 ...
     Evaluates EXPR EXPR2 ... sequentially, as `begin', and returns the
     result(s) of the last expression.  Before returning the value(s),
     the macro reports the elapsed (real) time and CPU times in the
     user space and the kernel space to the current error port, much
     like the bourne shell's time command.

     The current version uses `sys-gettimeofday' (*Note Time::) to
     calculate the elapsed time, and `sys-times' (*Note System
     Inquiry::) to calculate user and system CPU times.  So the
     resolution of these numbers depends on these underlying system
     calls.  Usually the CPU time has 10ms resolution, while the
     elapsed time might have higher resolution.  On the systems that
     doesn't have gettimeofday(2) support, however, the elapsed time
     resolution can be as bad as a second.

          gosh> (time (length (sort (call-with-input-file "/usr/share/dict/words" port->string-list))))
          ;(time (length (sort (call-with-input-file "/usr/share/dict/words" port- ...
          ; real   0.357
          ; user   0.350
          ; sys    0.000
          45427

 -- Class: <time-counter>
     An abstract class of time counters.  Time counter is a kind of
     timer whose value is incremented as the time passes.  The counting
     can be started and stopped any number of times.  The value of the
     counter can be read when the timer is stopping.  You can have
     multiple time counters.  It is useful, for example, to measure the
     time in two parts inside a loop independently.

     The concrete subclass determines which time it is counting.  You
     have to instantiate one of those subclasses described below to use
     the time counter.

 -- Class: <real-time-counter>
 -- Class: <user-time-counter>
 -- Class: <system-time-counter>
 -- Class: <process-time-counter>
     Classes for time counters that count real (elapsed) time,
     user-space CPU time, kernel-space CPU time, and total CPU time
     (user + system), respectively.

 -- Method: time-counter-start! (counter <time-counter>)
 -- Method: time-counter-stop! (counter <time-counter>)
     Starts and stops the COUNTER.  The time during the counter is
     running is accumulated to the counter value when the counter is
     stopped.

     Start/stop pairs can be nested, but only the outermost pair takes
     the effect.  That is, if you call `time-counter-start!' on the
     counter that is already started, it doesn't have any effect except
     that to stop such a counter you have to call `time-counter-stop!'
     one more time.  It is useful when you want to measure the time
     spent in the larger block that may already contain timer
     start/stop pairs.

     Calling `time-counter-stop!' on the already stopped counter has no
     effect.

 -- Method: time-counter-reset! (counter <time-counter>)
     Resets the value of COUNTER.  If COUNTER is already running, it is
     forced to stop before being reset.

 -- Method: time-counter-value (counter <time-counter>)
     Returns the current value of the counter as the number of seconds,
     in a real number.  The resolution depends on the source of the
     counter.

 -- Macro: with-time-counter counter expr ...
     A convenience macro to run the COUNTER while EXPR ...  are
     evaluated.  Returns the result(s) of the last expression.  It is
     defined as follows.
          (define-syntax with-time-counter
            (syntax-rules ()
              ((_ counter . exprs)
               (dynamic-wind
                (lambda () (time-counter-start! counter))
                (lambda () . exprs)
                (lambda () (time-counter-stop! counter))))
              ))

   The following example measures approximate times spend in process-A
and process-B inside a loop.

     (let ((ta (make <real-time-counter>))
           (tb (make <real-time-counter>)))
       (dotimes (i 100000)
         (with-time-counter ta
           (process-A))
         (with-time-counter tb
           (process-B)))
       (format #t "Time spent in process-A: ~s\n" (time-counter-value ta))
       (format #t "Time spent in process-B: ~s\n" (time-counter-value tb))
       )


File: gauche-refe.info,  Node: Uniform vectors,  Next: Comparing version numbers,  Prev: Measure timings,  Up: Library modules - Gauche extensions

9.25 `gauche.uvector' - Uniform vectors
=======================================

 -- Module: gauche.uvector
     Provides vectors whose elements are of the same numeric type, as
     defined in SRFI-4 (*Note SRFI-4: srfi-4.).

     Gauche's implementation is a superset of SRFI-4 in a few ways:
        * Some routines takes optional parameters: `TAGvector->list'
          takes optional start and end indices, and `TAGvector-ref'
          takes optional fallback value.

        * Additional functions: copy procedures (`TAGvector-copy' and
          `TAGvector-copy!'), conversion procedures
          (`TAGvector->vector' and `vector->TAGvector'), and some
          arithmetic functions (`TAGvector-add', etc.)

        * Implements the collection framework (*Note Collection
          framework::) and the sequence framework (*Note Sequence
          framework::).  So the methods like `map', `for-each', `ref'
          or `subseq' can be used on the SRFI-4 vector types.

     There are some advantages of using SRFI-4 vectors over normal
     (heterogeneous) vectors.  It may be more compact than the normal
     vectors.  Some operations (especially Gauche's extension of vector
     arithmetic operations) can bypass type check and conversion of
     individual elements, thus be more efficient.  And it is much easier
     and efficient to communicate with external libraries that require
     homogeneous array of numbers; for example, OpenGL binding of Gauche
     uses SRFI-4 vectors extensively.
The following ten types of vectors are defined.
_s8vector_
     Elements are exact integers in the range between -2^7 and 2^7-1

_u8vector_
     Elements are exact integers in the range between 0 and 2^8-1

_s16vector_
     Elements are exact integers in the range between -2^15 and 2^15-1

_u16vector_
     Elements are exact integers in the range between 0 and 2^16-1

_s32vector_
     Elements are exact integers in the range between -2^31 and 2^31-1

_u32vector_
     Elements are exact integers in the range between 0 and 2^32-1

_s64vector_
     Elements are exact integers in the range between -2^63 and 2^63-1

_u64vector_
     Elements are exact integers in the range between 0 and 2^64-1

_f32vector_
     Elements are inexact real numbers representable in the `float' of
     C compiler that compiles Gauche.  Usually it is a single precision
     IEEE floating point number.

_f64vector_
     Elements are inexact real numbers representable in the `double' of
     C compiler that compiles Gauche.  Usually it is a double precision
     IEEE floating point number.

   When you try to store a number out of the range of the vector type,
an error is signalled by default.  However, some procedures take an
optional argument CLAMP that specifies alternative behavior in such a
case.  CLAMP argument may take one of the following values.
`#f'
     Default behavior (signals an error).

`high'
     Clamps high bound; i.e. if the value to be stored is beyond the
     higher bound of the range, the maximum value is stored instead.

`low'
     Clamps low bound; i.e. if the value to be stored is below the
     lower bound of the range, the minimum value is stored instead.

`both'
     Clamps both sides; does both `high' and `low'.

     (list->u8vector '(-1))         => error
     (list->u8vector '(-1) 'low)    => #u8(0)
     (list->u8vector '(-1) 'high)   => error
     (list->u8vector '(3000) 'high) => #u8(255)
     (list->u8vector '(-100 20 300) 'both) => #u8(0 20 255)

   In the following description, `TAG' can be replaced for any of `s8',
`u8', `s16', `u16', `s32', `u32', `s64', `u64', `f32', `f64'.

* Menu:

* Uvector basic operations::
* Uvector conversion operations::
* Uvector numeric operations::
* Uvector block I/O::


File: gauche-refe.info,  Node: Uvector basic operations,  Next: Uvector conversion operations,  Prev: Uniform vectors,  Up: Uniform vectors

9.25.1 Uvector basic operations
-------------------------------

 -- Builtin Class: <TAGvector>
     A class for TAGvector.  It inherits `<sequence>'.

 -- Reader Syntax: `#TAG(N ...)'
     Denotes a literal homogeneous vector.
          #s8(3 -2 4)
          #u32(4154 88357 2 323)
          #f32(3.14 0.554525 -3.342)

 -- Function: TAGvector? OBJ
     [SRFI-4] Returns `#t' if OBJ is a TAGvector, `#f' otherwise.

 -- Function: TAGvector X ...
     [SRFI-4] Constructs TAGvector whose elements are numbers X ....
     The numbers must be exact integer for exact integer vectors, and
     in the valid range of the vector.
          (s8vector 1 2 3) => #s8(1 2 3)

 -- Function: make-TAGvector LEN &OPTIONAL FILL
     [SRFI-4] Constructs a TAGvector of length LEN.  The elements are
     initialized by a number FILL.   For exact integer vectors, FILL
     must be an exact integer and in the valid range.  If FILL is
     omitted, the content of the vector is undefined.
          (make-u8vector 4 0) => #u8(0 0 0 0)

 -- Function: TAGvector-length VEC
     [SRFI-4] Returns the length of the TAGvector VEC.

     Note that the generic function `size-of' can be used to obtain the
     length of VEC as well, if you import `gauche.collection' (*Note
     Collection framework::).
          (s16vector-length '#s16(111 222 333)) => 3

          (use gauche.collection)
          (size-of '#s16(111 222 333)) => 3

 -- Function: TAGvector-ref VEC K &optional FALLBACK
     [SRFI-4+] Returns the K-th element of TAGvector VEC.

     If the index K is out of the valid range, an error is signalled
     unless an optional argument FALLBACK is given; in that case,
     FALLBACK is returned.

     Note that the generic function `ref' can be used as well, if you
     import `gauche.collection'.

          (u16vector-ref '#u16(111 222 333) 1) => 222

          (use gauche.collection)
          (ref '#u16(111 222 333) 1) => 222

 -- Function: TAGvector-set! VEC K N &optional CLAMP
     [SRFI-4+] Sets a number N to the K-th element of TAGvector VEC.
     Optional CLAMP argument specifies the behavior when N is out of
     valid range.   Default is to signal an error.

     Note that the setter of the generic function `ref' can be used as
     well, if you import `gauche.collection'.
          (let ((v (s32vector -439 852 8933)))
            (s32vector-set! v 1 4)
            v)
           => #s32vector(-439 4 8933)

          (use gauche.collection)
          (let ((v (s32vector -439 852 8933)))
            (set! (ref v 1) 4)
            v)
           => #s32vector(-439 4 8933)

 -- Function: TAGvector-copy VEC &optional START END
     Copies the srfi-4 vector VEC.  If START and/or END are given, they
     limit the range of VEC to be copied.

          (u8vector-copy '#u8(1 2 3 4))     => #u8(1 2 3 4)
          (u8vector-copy '#u8(1 2 3 4) 2)   => #u8(3 4)
          (u8vector-copy '#u8(1 2 3 4) 1 3) => #u8(2 3)

 -- Function: TAGvector-copy! TARGET TSTART SOURCE &optional SSTART SEND
     Both TARGET and SOURCE must be TAGvectors, and TARGET must be
     mutable.  This procedure copies the elements of START, beginning
     from index SSTART (inclusive) and up to SEND, into TARGET,
     beginning from index TSTART.  SSTART and TSTART may be omitted,
     and in that case 0 and the length of SOURCE are assumed,
     respectively.

          (let ((target (u8vector 0 1 2 3 4 5 6)))
            (u8vector-copy! target 2 '#u8(10 11 12 13 14) 1 4)
            target)
           => #u8(0 1 11 12 13 6)

     If the number of elements in the source vector between SSTART and
     SEND is larger than the target vector beginning from TSTART, the
     excess elements are silently discarded.

     _Note:_ This procedure used to take just two uniform vectors,
     TARGET and SOURCE, and just copies contents of SOURCE to TARGET.
     Both vectors had to be the same type and same length.  The API is
     revised to the current form to make it parallel with
     `string-copy!' (SRFI-13) and `vector-copy!' (SRFI-43).  The old
     interface is still supported for the backward compatibility, but
     it is deprecated and will be gone in the future releases.

   Using collection and sequence framework, you can perform various
operations on the homogeneous vectors.

     (use gauche.collection)
     (use gauche.sequence)

     (fold + 0 '#s32(1 2 3 4)) => 10

     (map-to <f32vector> * '#f32(3.2 1.1 4.3) '#f32(-4.3 2.2 9.4))
       => #f32(-13.760001 2.420000 40.420002)

     (subseq #u32(1 4 3 4 5) 2 4) => #u32(3 4)


File: gauche-refe.info,  Node: Uvector conversion operations,  Next: Uvector numeric operations,  Prev: Uvector basic operations,  Up: Uniform vectors

9.25.2 Uvector conversion operations
------------------------------------

 -- Function: TAGvector->list VEC &optional START END
     [SRFI-4+] Converts TAGvector VEC to a list.  If START and/or END
     are given, they limit the range of VEC to be extracted.

     Note that the generic function `coerce-to' can be used as well, if
     you import `gauche.collection'.
          (u32vector->list '#u32(9 2 5)) => (9 2 5)

          (use gauche.collection)
          (coerce-to <list> '#u32(9 2 5)) => (9 2 5)

 -- Function: TAGvector->vector VEC &optional START END
     Converts TAGvector VEC to a vector.  If START and/or END are
     given, they limit the range of VEC to be copied.

     Note that the generic function `coerce-to' can be used as well, if
     you import `gauche.collection'.
          (f32vector->vector '#f32(9.3 2.2 5.5))   => #(9.3 2.2 5.5)
          (f32vector->vector '#f32(9.3 2.2 5.5) 2) => #(5.5)

          (use gauche.collection)
          (coerce-to <vector> '#f32(9.3 2.2 5.5)) => #(9.3 2.2 5.5)

 -- Function: list->TAGvector LIST &optional CLAMP
     [SRFI-4+] Converts a list LIST to a TAGvector.  Optional argument
     CLAMP specifies the behavior when the element of LIST is out of
     the valid range.

     Note that the generic function `coerce-to' can be used as well, if
     you import `gauche.collection'.
          (list->s64vector '(9 2 5)) => #s64(9 2 5)

          (use gauche.collection)
          (coerce-to <s64vector> '(9 2 5)) => #s64(9 2 5)

 -- Function: vector->TAGvector VEC &optional START END CLAMP
     Converts a vector VEC to a TAGvector.  If START and/or END are
     given, they limit the range of VEC to be copied.  Optional
     argument CLAMP specifies the behavior when the element of VEC is
     out of the valid range.

     Note that the generic function `coerce-to' can be used as well, if
     you import `gauche.collection'.
          (vector->f64vector '#(3.1 5.4 3.2)) => #f64(3.1 5.4 3.2)

          (use gauche.collection)
          (coerce-to <f64vector> '#(3.1 5.4 3.2)) => #f64(3.1 5.4 3.2)

 -- Function: string->s8vector string &optional start end
 -- Function: string->u8vector string &optional start end
     Returns an s8vector or u8vector whose byte sequence is the same as
     the internal representation of the given string.  Optional range
     arguments START and END specifies the _character position_ inside
     STRING to be converted.

     These procedures are useful when you want to access byte sequence
     of the string randomly.

          (string->u8vector "abc") => #u8(97 98 99)

 -- Function: string->s8vector! target tstart string &optional start end
 -- Function: string->u8vector! target tstart string &optional start end
     TARGET must be an s8vector or a u8vector, respectively.  TARGET
     must be mutable.  Like copies the raw byte representation of STRING
     into TARGET beginning from index TSTART.

     Returns TARGET.

          (let ((target (make-u8vector 10 0)))
            (string->u8vector! target 3 "abcde"))
           => #u8(0 0 0 97 98 99 100 101 0 0)


 -- Function: s8vector->string vec &optional start end
 -- Function: u8vector->string vec &optional start end
     Converts a byte sequence in s8vector or u8vector to a string that
     has the same byte sequence.  Optional range arguments START and
     END specifies the byte position in VEC to be converted.

     Note that these procedure may result an incomplete string if VEC
     contains a byte sequence invalid as the internal encoding of the
     string.

 -- Function: string->s32vector string &optional start end
 -- Function: string->u32vector string &optional start end
     Returns an s32vector or u32vector whose elements are the internal
     codes of the characters in the string.  Optional range arguments
     START and END specifies the _character position_ inside STRING to
     be converted.

     These procedures are useful when you want to access the characters
     in the string randomly.

 -- Function: s32vector->string vec &optional start end
 -- Function: u32vector->string vec &optional start end
     Without START and END, these procedures work like this:
          (lambda (vec) (map-to <string> integer->char vec)))
     Optional range arguments START and END limits the range of
     conversion between them.

 -- Function: uvector-alias uvector-class vec &optional start end
     This procedure creates an uvector of class UVECTOR-CLASS that
     shares the storage of the given uniform vector VEC.  If optional
     START and END arugments are given, only the specified range of VEC
     is used for the new vector.  Since the storage is shared,
     modification of the original vector can be seen from the new
     vector, or vice versa.

     The class UVECTOR-CLASS must be either one of the uniform vector
     class, but is not necessary match the class of the source vector
     VEC.   In such case, the new vector looks at the same region of
     VEC's memory, but interpretes it differently.  For example, the
     following code determines whether Gauche is running on big-endian
     or little-endian machine:

          (let ((u8v (uvector-alias <u8vector> #u32(1))))
            (if (zero? (u8vector-ref u8v 0))
                'big-endian
                'little-endian))

     If the UVECTOR-CLASS is other than s8vector or u8vector, the
     region the new vector points has to meet the alignment
     requirement.  You can assume the beginning of the source vector is
     aligned suitable for any uniform vectors.  So, for example, if
     you're creating u32vector from u8vector, the START and END must be
     multiple of 4 (or, if they're omitted, the length of the original
     u8vector must be multiple of 4).  An error is signalled when the
     given parameters doesn't satisfy alignment constraint.


File: gauche-refe.info,  Node: Uvector numeric operations,  Next: Uvector block I/O,  Prev: Uvector conversion operations,  Up: Uniform vectors

9.25.3 Uvector numeric operations
---------------------------------

 -- Function: TAGvector-add VEC VAL &optional CLAMP
 -- Function: TAGvector-add! VEC VAL &optional CLAMP
 -- Function: TAGvector-sub VEC VAL &optional CLAMP
 -- Function: TAGvector-sub! VEC VAL &optional CLAMP
 -- Function: TAGvector-mul VEC VAL &optional CLAMP
 -- Function: TAGvector-mul! VEC VAL &optional CLAMP
     Element-wise arithmetic.  VEC must be a TAGvector, and VAL must be
     either a TAGvector, a vector, or a list of the same length as VEC,
     or a number (an exact integer for integer vectors, and a real
     number for f32- and f64-vectors).

     If VAL is a TAGvector, its elements are added to, subtracted from,
     or multiplied by the corresponding elements of VEC, respectively,
     and the results are gathered to a TAGvector and returned.  The
     destructive version (those have bang `!' in the name) reuses VEC
     to store the result.  If the result of calculation goes out of the
     range of TAGvector's element, the behavior is specified by CLAMP
     optional argument.  (For f32vector and f64vector, CLAMP argument
     is ignored and the result may contain infinity).

     If VAL is a number, it is added to, subtracted from, or multiplied
     by each element of VEC, respectively.

          (s8vector-add '#s8(1 2 3 4) '#s8(5 6 7 8)) => #s8(6 8 10 12)
          (u8vector-sub '#u8(1 2 3 4) '#u8(2 2 2 2)) => error
          (u8vector-sub '#u8(1 2 3 4) '#u8(2 2 2 2) 'both) => #u8(0 0 1 2)

          (f32vector-mul '#f32(3.0 2.0 1.0) 1.5) => #f32(4.5 3.0 1.5)

 -- Function: TAGvector-div VEC VAL
 -- Function: TAGvector-div! VEC VAL
     Element-wise division of flonum vectors.   These are only defined
     for f32vector and f64vector.  VAL must be a TAGvector, a vector or
     a list of the same length as VEC, or a real number.

          (f32vector-div '#f32(1.0 2.0 3.0) 2.0) => #f32(0.5 1.0 1.5)

 -- Function: TAGvector-and VEC VAL
 -- Function: TAGvector-and! VEC VAL
 -- Function: TAGvector-ior VEC VAL
 -- Function: TAGvector-ior! VEC VAL
 -- Function: TAGvector-xor VEC VAL
 -- Function: TAGvector-xor! VEC VAL
     Element-wise logical (bitwise) operation.  These procedures are
     only defined for integral vectors.  VAL must be a TAGvector, a
     vector or a list of the same length as VEC, or an exact integer.
     Bitwise and, inclusive or or exclusive or is calculated between
     each element in VEC and the corresponding element of VAL (when VAL
     is a non-scalar value), or VAL itself (when VAL is an integer).
     The result is returned in a TAGvector.  The destructive version
     reuses VEC to store the result.

 -- Function: TAGvector-dot VEC0 VEC1
     Calculates the dot product of two TAGvectors.  The length of VEC0
     and VEC1 must be the same.

 -- Function: TAGvector-range-check VEC MIN MAX
     VEC must be a TAGvector, and each of MIN and MAX must be either a
     TAGvector, a vector or a list of the same length as VEC, or a
     number, or `#f'.

     For each element in VEC, this procedure checks if the value is
     between MINVAL and MAXVAL inclusive, where MINVAL and MAXVAL are
     the corresponding values of MIN and MAX (when MIN and/or MAX is/are
     non-scalar value) or MIN and MAX themselves (when MIN and/or MAX
     is/are a number).  When MIN is `#f', negative infinity is assumed.
     When MAX is `#f', positive infinity is assumed.

     If all the elements in VEC are within the range, `#f' is returned.
     Otherwise, the index of the leftmost element of VEC that is out
     of range is returned.

          (u8vector-range-check '#u8(3 1 0 2) 0 3)  => #f
          (u8vector-range-check '#u8(3 1 0 2) 1 3)  => 2

          (u8vector-range-check '#u8(4 32 64 98) 0 '#u8(10 40 70 90))
            => 3

          ;; Range check in a program
          (cond
           ((u8vector-range-check u8v 1 31)
            => (lambda (i)
                (errorf "~sth vector element is out of range: ~s"
                        i (u8vector-ref u8v i))))
           (else (do-something u8v)))

 -- Function: TAGvector-clamp VEC MIN MAX
 -- Function: TAGvector-clamp! VEC MIN MAX
     VEC must be a TAGvector, and each of MIN and MAX must be either a
     TAGvector, a vector or a list of the same length as VEC, or a
     number, or `#f'.

     Like TAGvector-range-check, these procedures check if each element
     of VEC are within the range between MINVAL and MAXVAL inclusive,
     which are defived from MIN and MAX.  If the value is less than
     MINVAL, it is replaced by MINVAL.  If the value is grater than
     MAXVAL, it is replaced by MAXVAL.

     TAGvector-clamp creates a copy of VEC and do clamp operation on
     it, while TAGvector-clamp! modifies VEC.  Both return the clamped
     vector.

          (s8vector-clamp '#s8(8 14 -3 -22 0) -10 10) => #s8(8 10 -3 -10 0)


File: gauche-refe.info,  Node: Uvector block I/O,  Prev: Uvector numeric operations,  Up: Uniform vectors

9.25.4 Uvector block I/O
------------------------

A uniform vector can be seen as an abstraction of a chunk of memory.
So you might want to use it for binary I/O.  Yes, you can do it.

 -- Function: read-block! vec &optional iport start end
     Reads a chunk of data from the given input port IPORT, and stores
     it to the uniform vector VEC.  You can give any uniform vector.
     If optional START and END arguments are given, they specify the
     index range in VEC that is to be filled, and the rest of the
     vector remains untouched.  Otherwise, entire vector is used.  If
     IPORT is omitted, the current input port is used.

     If the input reached EOF before the required region of VEC is
     filled, the rest of the vector is untouched.

     If IPORT is already reached EOF when `read-block!' is called, an
     EOF object is returned.  Otherwise, the procedure returns the
     number of _elements_ read (not bytes).

     If the IPORT is a buffered port with `modest' or `none' buffering
     mode (*Note File ports::), `read-block!' may return before all the
     elements in VEC is filled, even if IPORT hasn't reached EOF.  The
     ports connected to a pipe or a network socket behave so by
     default.  If you know there will be enough data arriving and want
     to make sure VEC is filled, change the buffering mode of IPORT to
     `full'.

     The data is read as a byte stream, so if you give uniform vectors
     other than s8vector or u8vector, your result may affected by the
     endianness of the platform.    Suppose the input stream has a byte
     sequence `#x01, #x02, #x03, #x04'.  If you read it into u32vector,
     the first element you'll get may be `#x01020304' if you're using
     big-endian architecture, or `#x04030201' if you're using
     little-endian architecture.

 -- Function: write-block vec &optional oport start end
     Writes out the content of the uniform vector VEC 'as is' to the
     output port OPORT.   If OPORT is omitted, the current output port
     is used.  If optional START and END arguments are given, they
     specify the index range in VEC to be written out.  This procedure
     returns an unspecified value.

     If you write out a uniform vector except s8vector and u8vector, the
     care should be taken about the endianness, as in `read-block!'.
     The number `#x01020304' in your u32vector may be written out as
     the byte sequence `#x01, #x02, #x03, #x04' or `#x04, #x03, #x02,
     #x01', depending on your architecture.


File: gauche-refe.info,  Node: Comparing version numbers,  Next: Virtual ports,  Prev: Uniform vectors,  Up: Library modules - Gauche extensions

9.26 `gauche.version' - Comparing version numbers
=================================================

 -- Module: gauche.version
     This module provides a convenient procedure to compare _version
     numbers_ or _revision numbers_, such as "`0.5.1'", "`3.2-3'" or
     "`8.2pl1'".  Usually each release of software component has a
     version number, and you can define order between them.  For
     example, version "1.2.3" is newer than "1.2" and older than "2.1".
      You can compare those version numbers like this:

          (version<? "2.2.3" "2.2.11")     => #t
          (version<? "2.3.1" "2.3")        => #f
          (version<? "2.3.1-1" "2.3.1-10") => #t
          (version<? "13a" "5b")           => #f

     There are no standard way to name versions, so I chose one
     convention.   This won't work for all possible variations, but I
     think it covers typical cases.

     Strictly speaking, you can only define partial order between
     version numbers, for there can be branches.   This module uses
     simple measure and just assumes the version numbers can be fully
     ordered.

     The version number here is defined by the following syntax.
           <version> : <principal-release>
                     | <version> <post-subrelease>
                     | <version> <pre-subrelease>
           <principal-release> : <relnum>
           <post-subrelease>   : [.-] <relnum>
           <pre-subrelease>    : _ <relnum>
           <relnum>            : [0-9A-Za-z]+

     Typically `<relnum>' is composed by numeric part and extension
     part.  For example, "23a" is composed by an integer 23 and
     extension "a".  If `<relnum>' doesn't begins with digits, we
     assume its numeric part is -1.

     Then, the order of `<relnum>' is defined as follows:
       1. If relnum A and relnum B have different numeric part, we
          ignore the extension and order them numerically, e.g.  "`3b'"
          < "`4a'".

       2. If relnum A and relnum B have the same numeric part, we
          compare extension by alphabetically, e.g.  "`4c'" < "`4d'"
          and "`5'" < "`5a'".

     Given the order of `<relnum>', the order of version numbers are
     defined as follows:
       1. Decompose each version number into a list of
          `<principal-release>' and subsequence subrelease components.
          We call each element of the list "release components".

       2. If the first release component of both lists are the same,
          remove it from both.  Repeat this until the head of the lists
          differ.

       3. Now we have the following cases.
            1. Both lists are empty: versions are the same.

            2. One list (A) is empty and the other list (B) has
               post-subrelease at head: A is prior to B

            3. One list (A) is empty and the other list (B) has
               pre-subrelease at head: B is prior to A

            4. List A's head is post-subrelease and list B's head is
               pre-subrelease: B is prior to A

            5. Both lists have post-subrelease or pre-subrelease at
               head: compare their relnums.
          Here are some examples:
          "1" < "1.0" < "1.1" < "1.1.1" < "1.1.2" < "1.2" < "1.11"
          "1.2.3" < "1.2.3-1" < "1.2.4"
          "1.2.3" < "1.2.3a" < "1.2.3b"
          "1.2_rc0" < "1.2_rc1" < "1.2" < "1.2-pl1" < "1.2-pl2"
          "1.1-patch112" < "1.2_alpha"

     The reason of having `<pre-subrelease>' is to allow "release
     candidate" or "pre-release" version.

 -- Function: version=? ver1 ver2
 -- Function: version<? ver1 ver2
 -- Function: version<=? ver1 ver2
 -- Function: version>? ver1 ver2
 -- Function: version>=? ver1 ver2
     Returns a boolean value depending on the order of two version
     number string VER1 and VER2.  If the arguments contain invalid
     strings as the defined version number, an error is signalled.

 -- Function: version-compare ver1 ver2
     Compares two version number strings VER1 and VER2, and returns
     either -1, 0, or 1, depending whether VER1 is prior to VER2, VER1
     is the same as VER2, or VER1 is after VER2, respectively.

 -- Function: relnum-compare rel1 rel2
     This is lower-level procedure of `version-compare'.  Compares two
     release numbers (relnums) REL1 and REL2, and returns either -1, 0,
     or 1 depending whether  REL1 is prior to REL2, REL1 is the same as
     REL2, or REL1 is after REL2, respectively.


File: gauche-refe.info,  Node: Virtual ports,  Prev: Comparing version numbers,  Up: Library modules - Gauche extensions

9.27 `gauche.vport' - Virtual ports
===================================

 -- Module: gauche.vport
     _Virtual ports_, or procedural ports, are the ports whose behavior
     can be programmed in Scheme.

     This module provides two kinds of virtual ports: Fully virtual
     ports, in which every I/O operation invokes user-provided
     procedures, and virtual buffered ports, in which I/O operations
     are done on an internal buffer and user-provided procedures are
     called only when the buffer needs to be filled or flushed.

     This module also provides virtual buffered ports backed up by a
     uniform vector, as an example of the feature.

Fully virtual ports
...................

This type of virtual ports are realized by classes
`<virtual-input-port>' and `<virtual-output-port>'.  You can customize
the port behavior by setting appropriate slots with procedures.

 -- Class: <virtual-input-port>
     An instance of this class can be used as an input port.  The
     behavior of the port depends on the settings of the instance slot
     values.

     To work as a meaningful input port, at least either one of `getb'
     or `getc' slot must be set.  Otherwise, the port returns EOF for
     all input requests.

      -- Instance Variable of <virtual-input-port>: getb
          If set, the value must be a proceture that takes no arguments.
          Every time binary input is required, the procedure is called.

          The procedure must return an exact integer between 0 and 255
          inclusive, or `#f' or an EOF object.  If it returns an
          integer, it becomes the value read from the port.  If it
          returns other values, the port returns EOF.

          If the port is requested a character input and it doesn't have
          the `getc' procedure, the port calls this procedure, possibly
          multiple times, to construct a whole character.

      -- Instance Variable of <virtual-input-port>: getc
          If set, the value must be a proceture that takes no arguments.
          Every time character input is required, the procedure is
          called.

          The procedure must return a character, `#f' or an EOF object.
          If it returns a character, it becomes the value read from
          the port.  If it returns other values, the port returns EOF.

          If the port is requested a binary input and it doesn't have
          the `getb' procedure, the port calls this procedure, then
          converts a character into a byte sequence, and use it as the
          binary value(s) read from the port.

      -- Instance Variable of <virtual-input-port>: gets
          If set, the value must be a procedure that takes one argument,
          a positive exact integer.  It is called when the block binary
          input, such as `read-block', is requested.  It must return a
          (maybe incomplete) string up to the specified size, or `#f'
          or EOF object.  If it returns a null string, `#f' or EOF
          object, the port thinks it reached EOF.  If it returns other
          string, it is used as the result of block read.  It shouldn't
          return a string larger than the given size (Note: you must
          count size (bytes), not the number of characters).  The
          reason of this procedure is efficiency; if this procedure is
          not provided, the port calls `getb' procedure repeatedly to
          prepare the block of data.  In some cases, providing block
          input can be much more efficient (e.g. suppose you're reading
          from a block of memory chunk).

          You can leave this slot unset if you don't need to take such
          advantage.

      -- Instance Variable of <virtual-input-port>: ready
          If set, the value must be a procedure that takes one boolean
          argument.  It is called when `char-ready?' or `byte-ready?' is
          called on the port.   The value returned from your procedure
          will be the result of these procedures.

          The boolean argument is `#t' if `char-ready?' is called, or
          `#f' if `byte-ready?' is called.

          If unset, `char-ready?' and `byte-ready?' always return `#t'
          on the port

      -- Instance Variable of <virtual-input-port>: close
          If set, the value must be a procedure that takes no arguments.
          It is called when the port is closed.  Return value is
          discarded.  You can leave this unset if you don't need to
          take an action when the port is closed.

          This procedure may be called from a finalizer, so you have to
          be careful to write it.   See the note on finalization below.

      -- Instance Variable of <virtual-input-port>: seek
          If set, the value must be a procedure that takes two
          arguments, offset and whence.  The meaning of them is the
          same as the arguments to `port-seek' (*Note Common port
          operations::).  The procedure must adjust the port's internal
          read pointer so that the next read begins from the new
          pointer.  It should return the updated pointer (the byte
          offset from the beginning of the port).

          If unset, call of `port-seek' and `port-tell' on this port
          will return `#f'.

          Note that this procedure may be called for the purpose of
          merely querying the current position, with 0 as `offset' and
          `SEEK_CUR' as `whence'.  If your port knows the read pointer
          but cannot move it, you can still provide this procedure,
          which returns the current pointer position for such queries
          and returns `#f' for other arguments.


 -- Class: <virtual-output-port>
     An instance of this class can be used as an output port.  The
     behavior of the port depends on the settings of the instance slot
     values.

     To work as an output port, at least either one of `putb' or `putc'
     slot has to be set.

      -- Instance Variable of <virtual-output-port>: putb
          If set, the value must be a procedure that takes one argument,
          a byte value (exact integer between 0 and 255, inclusive).
          Every time binary output is required, the procedure is called.
          The return value of the procedure is ignored.

          If this slot is not set and binary output is requested, the
          port may signal an `<io-unit-error>' error.

      -- Instance Variable of <virtual-output-port>: putc
          If set, the value must be a procedure that takes one argument,
          a character.  Every time character output is required, the
          procedure is called.  The return value of the procedure is
          ignored.

          If this slot is not set but `putb' slot is set, the virtual
          port decomposes the character into a sequence of bytes then
          calls `putb' procedures.

      -- Instance Variable of <virtual-output-port>: puts
          If set, the value must be a procedure that takes a (possibly
          incomplete) string.  The return value of the procedure is
          ignored.

          This is for efficiency.  If this slot is not set, the virtual
          port calls `putb' or `putc' repeatedly to output a chunk of
          data.  But if your code can perform chunked output
          efficiently, you can provide this procedure.

      -- Instance Variable of <virtual-output-port>: flush
          If set, the value must be a procedure that takes no arguments.
          It is called when flushing a port is required (e.g. `flush'
          is called on the port, or the port is being closed).

          This procedure is useful that your port does some sort of
          buffering, or needs to keep some state.  If your port doesn't
          do stateful operation, you can leave this unset.

          This procedure may be called from a finalizer, and needs a
          special care.  See notes on finalizers below.


      -- Instance Variable of <virtual-output-port>: close
          The same as `<virtual-input-port>''s `close' slot.

      -- Instance Variable of <virtual-output-port>: seek
          The same as `<virtual-input-port>''s `seek' slot.


Virtual buffered ports
......................

This type of virtual ports are realized by classes
`<buffered-input-port>' and `<buffered-output-port>'.  You can
customize the port behavior by setting appropriate slots with
procedures.

   Those ports have internal buffer and only calls Scheme procedures
when the buffer needs to be filled or flushed.  Generally it is far
more efficient than calling Scheme procedures for every I/O operation.
Actually, the internal buffering mechanism is the same as Gauche's
file I/O ports.

   These ports uses `u8vector' as a buffer.  See *Note Uniform vectors::
for the details.

 -- Class: <buffered-input-port>
     An instance of this class behaves as an input port.  It has the
     following instance slots.  For a meaningful input port, you have
     to set at least `fill' slot.

      -- Instance Variable of <buffered-input-port>: fill
          If set, it must be a procedure that takes one argument, a
          `u8vector'.  It must fill the data from the beginning of the
          vector.  It doesn't need to fill the entire vector if there's
          not so many data.  However, if there are remaining data, it
          must fill at least one byte; if the data isn't readily
          available, it has to wait until some data becomes available.

          The procedure must return a number of bytes it actually
          filled.  It may return 0 or an EOF object to indicate the
          port has reached EOF.

      -- Instance Variable of <buffered-input-port>: ready
          If set, it must be a procedure that takes no arguments.  The
          procedure must return a true value if there are some data
          readily available to read, or `#f' otherwise.  Unlike fully
          virtual ports, you don't need to distinguish binary and
          character I/O.

          If this slot is not set, the port is regarded as it always
          has data ready.

      -- Instance Variable of <buffered-input-port>: close
          If set, it must be a procedure that takes no arguments.  The
          procedure is called when the virtual buffered port is closed.
          You don't need to set this slot unless you need some cleaning
          up when the port is closed.

          This procedure may be called from a finalizer, and needs
          special care.  See the note on finalization below.

      -- Instance Variable of <buffered-input-port>: filenum
          If set, it must be a procedure that returns underlying file
          descriptor number (exact nonnegative integer).  The procedure
          is called when `port-file-number' is called on the port.

          If there's no such underlying file descriptor, you can return
          `#f', or you can leave this slot unset.

      -- Instance Variable of <buffered-input-port>: seek
          If set, it must be a procedure that takes two arguments,
          OFFSET and WHENCE.  It works the same way as
          `<virtual-input-port>''s seek procedure; see above.

          This procedure may be called from a finalizer, and needs
          special care.  See the note on finalization below.


 -- Class: <buffered-output-port>
     An instance of this class behaves as an output port.  It has the
     following instance slots.  You have to set at least `flush' slot.

      -- Instance Variable of <buffered-output-port>: flush
          If set, it must be a procedure that takes two arguments, an
          `u8vector' buffer and a flag.  The procedure must output data
          in the buffer to somewhere, and returns the number of bytes
          actually output.

          If the flag is false, the procedure may output less than
          entire buffer (but at least one byte).  If the flag is true,
          the procedure must output entire buffer.

      -- Instance Variable of <buffered-output-port>: close
          Same as `<buffered-input-port>''s `close' slot.

      -- Instance Variable of <buffered-output-port>: filenum
          Same as `<buffered-input-port>''s `filenum' slot.

      -- Instance Variable of <buffered-output-port>: seek
          Same as `<buffered-input-port>''s `seek' slot.


Uniform vector ports
....................

The following two procedures returns a bufferd input/output port backed
up by a uniform vector.    The source or destination vector can be any
type of uniform vector, but they are aliased to `u8vector' (see
`uvector-alias' in *Note Uvector conversion operations::).

   If used together with `pack'/`unpack' (see *Note Packing Binary
Data::), it is useful to parse or construct binary data structure.  It
is also an example of using virtual ports; read `gauche/vport.scm' (or
`ext/vport/vport.scm' in the source tree) if you're curious about the
implementation.

 -- Function: open-input-uvector uvector
     Returns an input port that reads the content of the given uniform
     vector UVECTOR from its beginning.  If reading operation reaches
     the end of UVECTOR, EOF is returned.  Seek operation is also
     implemented.

 -- Function: open-output-uvector uvector
     Returns an output port that fills the given uvector by the data
     output to the port.  If UVECTOR is completely filled, more data
     are silently discarded.  Seek operation is also implemented.

Note on finalization
....................

If an unclosed virtual port is garbage collected, its close procedure
is called (in case of virtual buffered ports, its flush procedure may
also be called before close procedure).  It is done by a finalizer of
the port.  Since it is a part of garbage-collection process (although
the Scheme procedure itself is called outside of the garbage collector
main part), it requires special care.

   * It is possible that the object the virtual port has a reference
     may already be finalized.  For example, if a virtual port X holds
     the only reference to a _sink_ port Y, to which the output goes.
     X's `flush' procedure sends its output to Y.  However, if `flush'
     procedure can be called from a finalizer, it may be possible that
     Y's finalizer has already been called and Y is closed.   So X's
     `flush' procedure has to check if Y has not been closed.

   * You cannot know when and in which thread the finalizer runs.  So
     if the procedure like `close' or `flush' of virtual ports need to
     lock or access the global resource, it needs to take extra care of
     avoiding dead lock or conflict of access.

     Even in single thread programs, the finalizer can run anywhere in
     Scheme programs, so effectively it should be considered as running
     in a different thread.


File: gauche-refe.info,  Node: Library modules - SRFIs,  Next: Library modules - Utilities,  Prev: Library modules - Gauche extensions,  Up: Top

10 Library modules - SRFIs
**************************

This chapter lists modules that provides SRFI functionalities.  Note
that some of SRFI features are built in Gauche core and not listed
here.  *Note Standard conformance::, for entire list of supported SRFIs.

* Menu:

* Feature conditional::
* List library::
* And-let*::
* Homogeneous vectors::
* A compatible let form with signatures and rest arguments::
* Feature-based program configuration language::
* Record types::
* Let-values::
* String library::
* Character-set library::
* Time data types and procedures::
* Sources of random bits::
* Localization::
* A program argument processor::
* Eager comprehensions::
* Requiring extensions::


File: gauche-refe.info,  Node: Feature conditional,  Next: List library,  Prev: Library modules - SRFIs,  Up: Library modules - SRFIs

10.1 `srfi-0' - Feature conditional
===================================

 -- Module: srfi-0
     Provides SRFI-0 `cond-expand' macro form.  Now this module is
     autoloaded when `cond-expand' is used, so you don't need to say
     `(use srfi-0)' explicitly.  Portable programs can't use 'use' form
     anyway.

 -- Macro: cond-expand (feature-requirement command-or-definition ...)
          ...
     [SRFI-0] This macro expands to COMMAND-OR-DEFINITION ... if Gauche
     supports FEATURE-REQUIREMENT.  In a way, it can be used to absorb
     the different feature sets supported by different Scheme
     implementations.

     FEATURE-REQUIREMNT must be in the following syntax:
          FEATURE-REQUIREMENT
            : FEATURE-IDENTIFIER
            | (and FEATURE-REQUIREMENT ...)
            | (or  FEATURE-REQUIREMENT ...)
            | (not FEATURE-REQUIREMENT)

     FEATURE-IDENTIFIER is a symbol that indicates a feature.  If such
     a feature is supported in Gauche, it satisfies the
     FEATURE-REQUIREMENT.  You can do boolean combination of
     FEATURE-REQUIREMENTs to compose more complex conditions.

     The macro tests each FEATURE-REQUIREMENT in order, and if one is
     satisfied, the macro itself expands to the corresponding
     COMMAND-OR-DEFINITION ....

     The last clause may begin with a symbol `else' instead of
     FEATURE-REQUIREMENT.  If no condition is fulfilled before it, then
     the macro expands to the COMMAND-OR-DEFINITIONs of the else
     clause.  If there's no else clause and no condition is fulfilled,
     an error is signalled.

     Currently, Gauche recognizes srfi names (e.g. `srfi-1') that it
     supports (*Note Standard conformance::, for the list of supported
     SRFIs), and a symbol `gauche' as FEATURE-IDENTIFIER.

     Suppose you are writing a program that requires srfi-13 (string
     library).  In Gauche, the standard way to use srfi-13 is like this:

          (use srfi-13)

          ;; ... your program ...

     However, the 'use' macro is Gauche specific and won't work on
     other Scheme implementations.  You can write instead:

          (cond-expand
            (srfi-13
              ;; ... your program ...
            ))

     If the implementation supports `srfi-13', the form expands to your
     program.  Note that Gauche issues `(use srfi-13)' for you in this
     case.

     The above form signals an error if the implementation doesn't
     support srfi-13.  However, you might want to run your program on
     such implentations as well, by providing alternative library
     definitions.

          (cond-expand
           (srfi-13
             ;; ... your program ...
           )
           (else
             (load "my-srfi-13-implementation")
             ;; ... your program ...
           ))


File: gauche-refe.info,  Node: List library,  Next: And-let*,  Prev: Feature conditional,  Up: Library modules - SRFIs

10.2 `srfi-1' - List library
============================

 -- Module: srfi-1
     SRFI-1 is a rich collection of list manipulation library (*Note
     [SRFI-1]: srfi-1.).  It is available by saying `(use srfi-1)'.
     The implementation is based on Olin Shivers's reference
     implementation.  I splitted it into number of subfiles that will
     be autoloaded on demand.

* Menu:

* SRFI-1 List constructors::
* SRFI-1 List predicates::
* SRFI-1 List selectors::
* SRFI-1 List miscellaneous routines::
* SRFI-1 Fold::
* SRFI-1 Filtering & Partitioning::
* SRFI-1 Searching::
* SRFI-1 Deletion::
* SRFI-1 Association lists::
* SRFI-1 Set operations::


File: gauche-refe.info,  Node: SRFI-1 List constructors,  Next: SRFI-1 List predicates,  Prev: List library,  Up: List library

10.2.1 List constructors
------------------------

 -- Function: xcons cd ca
     [SRFI-1] Equivalent to `(cons ca cd)'.  Useful to pass to
     higher-order procedures.

 -- Function: cons* elt1 elt2 ...
     [SRFI-1] Like `list', but the last argument provides the tail of
     the constructed list.  This is just a synonym of Gauche built-in
     procedure `list*'.
          (cons* 1 2 3 4) => (1 2 3 . 4)
          (cons* 1) => 1

 -- Function: list-tabulate n init-proc
     [SRFI-1] Constructs an N-element list, in which each element is
     generated by `(INIT-PROC i)'.
          (list-tabulate 4 values) => (0 1 2 3)

 -- Function: circular-list elt1 elt2 ...
     [SRFI-1] Constructs a circular list of the elements.
          (circular-list 'z 'q) => (z q z q z q ...)

 -- Function: iota count &optional (start 0) (step 1)
     [SRFI-1] Returns a list of numbers, starting from START,
     increasing by STEP.
          (iota 5) => (0 1 2 3 4)
          (iota 5 0 -0.1) => (0 -0.1 -0.2 -0.3 -0.4)


File: gauche-refe.info,  Node: SRFI-1 List predicates,  Next: SRFI-1 List selectors,  Prev: SRFI-1 List constructors,  Up: List library

10.2.2 List predicates
----------------------

 -- Function: proper-list? x
     [SRFI-1] Returns `#t' if x is a proper list.

 -- Function: circular-list? x
     [SRFI-1] Returns `#t' if x is a circular list.

 -- Function: dotted-list? x
     [SRFI-1] Returns `#t' if x is a finite, non-nil-terminated list.
     This includes non-pair, non-() values (e.g. symbols, numbers),
     which are considered to be dotted lists of length 0.

 -- Function: null-list? list
     [SRFI-1] Returns `#t' if LIST is the empty list `()', and #F
     otherwise.

 -- Function: not-pair? x
     [SRFI-1] `(lambda (x) (not (pair? x)))'.

     SRFI-1 says: Provided as a procedure as it can be useful as the
     termination condition for list-processing procedures that wish to
     handle all finite lists, both proper and dotted.

 -- Function: list= elt= list ...
     [SRFI-1] Determines list equality by comparing every n-th element
     of given lists by the procedure ELT=.

     It is an error to apply `list=' to anything except proper lists.

     The equality procedure must be consistent with `eq?', i.e.
          (eq? x y) => (elt= x y).


File: gauche-refe.info,  Node: SRFI-1 List selectors,  Next: SRFI-1 List miscellaneous routines,  Prev: SRFI-1 List predicates,  Up: List library

10.2.3 List selectors
---------------------

 -- Function: first pair
 -- Function: second pair
 -- Function: third pair
 -- Function: fourth pair
 -- Function: fifth pair
 -- Function: sixth pair
 -- Function: seventh pair
 -- Function: eighth pair
 -- Function: ninth pair
 -- Function: tenth pair
     [SRFI-1] Returns n-th element of the (maybe improper) list.

 -- Function: car+cdr pair
     [SRFI-1] Returns two values, `(car pair)' and `(cdr pair)'.

 -- Function: take x i
 -- Function: drop x i
     [SRFI-1] `take' returns the first i elements of list x.  `drop'
     returns all but the first i elements of list x.
          (take '(a b c d e)  2) => (a b)
          (drop '(a b c d e)  2) => (c d e)
     X may be any value:
          (take '(1 2 3 . d) 2) => (1 2)
          (drop '(1 2 3 . d) 2) => (3 . d)
          (drop '(1 2 3 . d) 3) => d
     `drop' is exactly equivalent to performing I cdr operations on X.
     The returned value shares a common tail with X.  On the other
     hand, take always allocates a new list for result if the argument
     is a list of non-zero length.

     An error is signalled if I is past the end of list X.  *Note
     Additional list library::, for more tolerant version of `take' and
     `drop'.

     For generic subsequence extranction from any sequence, see `subseq'
     in *Note Slicing sequence::.

 -- Function: take-right flist i
 -- Function: drop-right flist i
     [SRFI-1] `take-right' returns the last I elements of FLIST.
     `drop-right' returns all but the last I elements of FLIST.
          (take-right '(a b c d e) 2) => (d e)
          (drop-right '(a b c d e) 2) => (a b c)
     FLIST may be any finite list.
          (take-right '(1 2 3 . d) 2) => (2 3 . d)
          (drop-right '(1 2 3 . d) 2) => (1)
          (take-right '(1 2 3 . d) 0) => d
          (drop-right '(1 2 3 . d) 0) => (1 2 3)
     `take-right''s return value always shares a common tail with FLIST.
     `drop-right' always allocates a new list if the argument is a list
     of non-zero length.

     An error is signalled if I is larger than the length of FLIST.
     *Note Additional list library::, for more tolerant version of
     `take-right' and `drop-right'.

 -- Function: take! x i
 -- Function: drop-right! x i
     [SRFI-1]  Linear update variants of TAKE and DROP-RIGHT.  Those
     procedures may destructively modifies X.

     If X is circular, `take!' may return a list shorter than expected.

 -- Function: split-at x i
 -- Function: split-at! x i
     [SRFI-1] `split-at' splits the list X at index I, returning a list
     of the first I elements, and the remaining tail.
          (split-at '(a b c d e) 2) => (a b) (c d e)
     `split-at!' is the linear-update variant. It may destructively
     modifes X to produce the result.

 -- Function: last pair
     [SRFI-1] Returns the last element of the non-empty, finite list
     PAIR.  It is equivalent to `(car (last-pair pair))'.  Note that
     `last-pair' is Gauche built-in procedure.


File: gauche-refe.info,  Node: SRFI-1 List miscellaneous routines,  Next: SRFI-1 Fold,  Prev: SRFI-1 List selectors,  Up: List library

10.2.4 List miscellaneous routines
----------------------------------

 -- Function: length+ x
     EN [SRFI-1] If X is a proper list, returns its length.  Otherwise,
     returns `#f'.

 -- Function: concatenate list-of-lists
 -- Function: concatenate! list-of-lists!
     [SRFI-1] Equivalent to `(apply append LIST-OF-LISTS)' and `(apply
     append! LIST-OF-LISTS)', respectively.

 -- Function: append-reverse rev-head tail
 -- Function: append-reverse! rev-head tail
     [SRFI-1] `append-reverse' returns `(append (reverse rev-head)
     tail)'.  `append-reverse!' is the linear-update variant.

 -- Function: zip clist1 clist2 ...
     [SRFI-1] Equivalent to `(map list clist1 clist2 ...)'.  If `zip'
     is passed N lists, it returns a list as long as the shortest of
     these lists, each element of which is an N-element list comprised
     of the corresponding elements from the parameter lists.
          (zip '(one two three)
               '(1 2 3)
               '(odd even odd even odd even odd even))
               => ((one 1 odd) (two 2 even) (three 3 odd))

          (zip '(1 2 3)) => ((1) (2) (3))
     At least one of the argument lists must be finite:
          (zip '(3 1 4 1) (circular-list #f #t))
               => ((3 #f) (1 #t) (4 #f) (1 #t))

 -- Function: unzip1 list
 -- Function: unzip2 list
 -- Function: unzip3 list
 -- Function: unzip4 list
 -- Function: unzip5 list
     [SRFI-1] `unzip1' takes a list of lists, where every list must
     contain at least one element, and returns a list containing the
     initial element of each such list.  `unzip2' takes a list of
     lists, where every list must contain at least two elements, and
     returns two values: a list of the first elements, and a list of
     the second elements. `unzip3' does the same for the first three
     elements of the lists, and so on.
          (unzip2 '((1 one) (2 two) (3 three))) =>
             (1 2 3) and
             (one two three)

 -- Function: count pred clist1 clist2 ...
     [SRFI-1] A procedure PRED is applied to the N-th element of given
     lists, from N is zero to the length of the the shortest finite
     list in the given lists, and the count of times PRED returned true
     is returned.
          (count even? '(3 1 4 1 5 9 2 5 6)) => 3
          (count < '(1 2 4 8) '(2 4 6 8 10 12 14 16)) => 3
     At least one of the argument lists must be finite:
          (count < '(3 1 4 1) (circular-list 1 10)) => 2

 -- Function: count$ pred
     Partial application version of `count'
          ((count$ pred) arg ...) === (count pred arg ...)


File: gauche-refe.info,  Node: SRFI-1 Fold,  Next: SRFI-1 Filtering & Partitioning,  Prev: SRFI-1 List miscellaneous routines,  Up: List library

10.2.5 List fold, unfold & map
------------------------------

 -- Function: fold kons knil clist1 clist2 ...
     [SRFI-1] The fundamental list iterator.  When it is given a single
     list CLIST1 = (E1 E2 ... EN), then this procedure returns
          (KONS EN ... (KONS E2 (KONS E1 KNIL)) ... )

     If N list arguments are provided, then the KONS function must take
     N+1 parameters: one element from each list, and the "seed" or fold
     state, which is initially KNIL.  The fold operation terminates
     when the shortest list runs out of values.  At least one of the
     list arguments must be finite.

     Examples:
          (fold + 0 '(3 1 4 1 5 9)) => 23 ;sum up the elements
          (fold cons '() '(a b c d e)) => (e d c b a) ;reverse
          (fold cons* '() '(a b c) '(1 2 3 4 5))
              => (c 3 b 2 a 1) ;n-ary case

 -- Function: fold-right kons knil clist1 clist2 ...
     [SRFI-1] The fundamental list recursion operator.  When it is
     given a single list CLIST1 = (E1 E2 ... EN), then this procedure
     returns
          (KONS E1 (KONS E2 ... (KONS EN KNIL)))

     If N list arguments are provided, then the KONS function must take
     N+1 parameters: one element from each list, and the "seed" or fold
     state, which is initially KNIL.  The fold operation terminates
     when the shortest list runs out of values.  At least one of the
     list arguments must be finite.

     Examples:
          (fold-right cons '() '(a b c d e))
             => (a b c d e) ;copy list
          (fold-right cons* '() '(a b c) '(1 2 3 4 5))
             => (a 1 b 2 c 3) ;n-ary case

 -- Function: pair-fold kons knil clist1 clist2 ...
 -- Function: pair-fold-right kons knil clist1 clist2 ...
     [SRFI-1] Like `fold' and `fold-right', but the procedure KONS gets
     each `cdr' of the given CLISTs, instead of `car'.

 -- Function: reduce f ridentity list
 -- Function: reduce-right f ridentity list
     [SRFI-1] Variant of `fold' and `fold-right'.   F must be a binary
     operator, and RIDENTITY is the value such that for any value X
     that is valid as F's input,
           (f x ridentity) == x

     These functions effectively do the same thing as `fold' or
     `fold-right', respectively, but omit the first application of F to
     RIDENTITY, using the above nature.  So RIDENTITY is used only when
     LIST is empty.

 -- Function: unfold p f g seed &optional tail-gen
     [SRFI-1] Fundamental recursive list constructor.  Defined by the
     following recursion.

          (unfold p f g seed tail-gen) ==
             (if (p seed)
                 (tail-gen seed)
                 (cons (f seed)
                       (unfold p f g (g seed))))
     That is, P determines where to stop, G is used to generate
     successive seed value from the current seed value, and F is used
     to map each seed value to a list element.

 -- Function: unfold-right p f g seed &optional tail
     [SRFI-1] Fundamental iterative list constructor.  Defined by the
     following recursin.

          (unfold-right p f g seed tail) ==
            (let lp ((seed seed) (lis tail))
              (if (p seed)
                  lis
                  (lp (g seed) (cons (f seed) lis))))

 -- Function: append-map f clist1 clist2 ...
 -- Function: append-map! f clist1 clist2 ...
     [SRFI-1] Equivalent to

            (apply append (map F CLIST1 CLIST2 ...))
            (apply append! (map F CLIST1 CLIST2 ...))
     At least one of the list arguments must be finite.

 -- Function: map! f clist1 clist2 ...
     [SRFI-1] The procedure F is applied to each element of CLIST1 and
     corresponding elements of CLIST2s, and the result is collected to
     a list.  Cells in CLIST1 is reused to construct the result list.

 -- Function: map-in-order f clist1 clist2 ...
     [SRFI-1] A variant of `map', but it guarantees to apply F on each
     elements of arguments in a left-to-right order.  Since Gauche's
     `map' implementation follows the same order, this function is just
     a synonym of `map'.

 -- Function: pair-for-each f clist1 clist2 ...
     [SRFI-1] Like `for-each', but the procedure F is applied on each
     `cdr' of CLISTs.

 -- Function: filter-map f clist1 clist2 ...
     [SRFI-1] Like `map', but only true values are saved.  At least one
     of the list arguments must be finite.
          (filter-map (lambda (x) (and (number? x) (* x x)))
                      '(a 1 b 3 c 7))
            => (1 9 49)

 -- Function: fold$ kons &optional knil
 -- Function: fold-right$ kons &optional knil
 -- Function: reduce$ f &optional ridentity
 -- Function: reduce-right$ f &optional ridentity
     Partial application versions of `fold', `fold-right', `reduce',
     and `reduce-right'.


File: gauche-refe.info,  Node: SRFI-1 Filtering & Partitioning,  Next: SRFI-1 Searching,  Prev: SRFI-1 Fold,  Up: List library

10.2.6 List filtering & partitioning
------------------------------------

 -- Function: filter pred list
 -- Function: filter! pred list
     [SRFI-1] A procedure PRED is applied on each element of LIST, and
     a list of elements that PRED returned true on it is returned.
          (filter odd? '(3 1 4 5 9 2 6)) => (3 1 5 9)
     `filter!' is the linear-update variant.  It may destructively
     modifies LIST to produce the result.

 -- Function: remove pred list
 -- Function: remove! pred list
     [SRFI-1] A procedure PRED is applied on each element of LIST, and
     a list of elements that PRED returned false on it is returned.
          (remove odd? '(3 1 4 5 9 2 6)) => (4 2 6)
     `remove!' is the linear-update variant.  It may destructively
     modifies LIST to produce the result.

 -- Function: partition pred list
 -- Function: partition! pred list
     [SRFI-1] `filter' and `remove' simultaneously, i.e.  returns two
     lists, the first is the result of filtering elements of LIST by
     PRED, and the second is the result of removing elements of LIST by
     PRED.
          (partition odd? '(3 1 4 5 9 2 6))
            => (3 1 5 9) (4 2 6)
     `partition!' is the linear-update variant.  It may destructively
     modifies LIST to produce the result.

 -- Function: filter$ pred
 -- Function: remove$ pred
 -- Function: partition$ pred
     Partial application versions of `filter', `remove' and `partition'.


File: gauche-refe.info,  Node: SRFI-1 Searching,  Next: SRFI-1 Deletion,  Prev: SRFI-1 Filtering & Partitioning,  Up: List library

10.2.7 List searching
---------------------

 -- Function: find pred clist
     [SRFI-1] Applies PRED for each element of CLIST, from left to
     right, and returns the first element that PRED returns true on.

 -- Function: find-tail pred clist
     [SRFI-1] Applies PRED for each element of CLIST, from left to
     right, and when PRED returns a true value, returns the pair whose
     car is the element.

 -- Function: take-while pred clist
 -- Function: take-while! pred list
     [SRFI-1] Returns the longest initial prefix of CLIST whose
     elements all satisfy PRED.

 -- Function: drop-while pred clist
     [SRFI-1] Drops the longest initial prefix of CLIST whose elements
     all satisfy PRED, and returns the rest.

 -- Function: span pred clist
 -- Function: span! pred list
 -- Function: break pred clist
 -- Function: break! pred list
     [SRFI-1] `span' is equivalent to `(values (take-while pred clist)
     (drop-while pred clist))'.  `break' inverts the sense of PRED.

 -- Function: any pred clist1 clist2 ...
     [SRFI-1] Applies PRED across each element of CLISTs, and returns
     as soon as PRED returns a non-false value.  The return value of
     `any' is the non-false value PRED returned.  If CLISTs are
     exhausted before PRED returns a non-false value, `#f' is returned.

 -- Function: every pred clist1 clist2 ...
     [SRFI-1] Applies PRED across each element of CLISTs, and returns
     `#f' as soon as PRED returns `#f'.  If all application of PRED
     return a non-false value, `every' returns the last result of the
     applications.

 -- Function: list-index pred clist1 clist2 ...
     [SRFI-1] Returns the index of the leftmost element that satisfies
     PRED.

 -- Function: member$ item
 -- Function: find$ pred
 -- Function: find-tail$ pred
 -- Function: any$ pred
 -- Function: every$ pred
     Partial application version of `member', `find', `find-tail',
     `any' and `every'.


File: gauche-refe.info,  Node: SRFI-1 Deletion,  Next: SRFI-1 Association lists,  Prev: SRFI-1 Searching,  Up: List library

10.2.8 List deletion
--------------------

 -- Function: delete x list &optional elt=
 -- Function: delete! x list &optional elt=
     [SRFI-1] Equivalent to
            (remove (lambda (y) (elt= x y)) list)
            (remove! (lambda (y) (elt= x y)) list)
     The comparison procedure, ELT=, defaults to `equal?'.

 -- Function: delete$ x
     Partial application version of `delete'.

 -- Function: delete-duplicates list &optional elt=
 -- Function: delete-duplicates! list &optional elt=
     [SRFI-1] Removes duplicate elements from LIST.  If there are
     multiple equal elements in LIST, the result list only contains the
     first or leftmost of these elements in the result. The order of
     these surviving elements is the same as in the original list.  The
     comparison procedure, ELT=, defaults to `equal?'.


File: gauche-refe.info,  Node: SRFI-1 Association lists,  Next: SRFI-1 Set operations,  Prev: SRFI-1 Deletion,  Up: List library

10.2.9 Association lists
------------------------

 -- Function: alist-cons key datum alist
     [SRFI-1] Returns `(cons (cons KEY DATUM) ALIST)'.  This is an
     alias of the Gauche builtin procedure `acons'.

 -- Function: alist-copy alist
     [SRFI-1] Returns a fresh copy of ALIST.  The spine of ALIST and
     each cell that points a key and a value is copied.
          (define a (list (cons 'a 'b) (cons 'c 'd)))
          a => ((a . b) (c . d))

          (definea b (alist-copy a))
          b => ((a . b) (c . d))

          (set-cdr! (car a) 'z)
          a => ((a . z) (c . d))
          b => ((a . b) (c . d))

 -- Function: alist-delete key alist &optional =
 -- Function: alist-delete! key alist &optional =
     [SRFI-1] Deletes all cells in ALIST whose key is the same as KEY.
     Comparison is done by a procedure =.  The default is `eqv?'.

     The linear-update version `alist-delete!' may or may not modify
     ALIST.

 -- Function: assoc$ item
     Partial application version of `assoc'.


File: gauche-refe.info,  Node: SRFI-1 Set operations,  Prev: SRFI-1 Association lists,  Up: List library

10.2.10 Lists as sets
---------------------

These procedures use a list as a set, that is, the elements in a list
matter, but their order doesn't.

   All procedures in this category takes a comparison procedure ELT=,
as the first argument, which is used to determine two elements in the
given sets are the same.

   See also *Note Combination library::, which concerns combinations of
elements in the set.

 -- Function: lset<= elt= list1 ...
     [SRFI-1] Returns `#t' iff all elements in LIST1 are also included
     in LIST2, and so on.  If no lists are given, or a single list is
     given, `#t' is returned.

 -- Function: lset= elt= list1 list2 ...
     [SRFI-1] Returns `#t' if all elements in LIST1 are in LIST2, and
     all elements in LIST2 are in LIST1, and so on.

          (lset= eq? '(b e a) '(a e b) '(e e b a)) => #t

 -- Function: lset-adjoin elt= list elt ...
     [SRFI-1] Adds ELT ... to the set LIST, if each one is not already
     a member of LIST.  (The order doesn't matter).

          (lset-adjoin eq? '(a b c) 'a 'e) => '(e a b c)

 -- Function: lset-union elt= list1 ...
     [SRFI-1] Returns the union of the sets LIST1 ....

 -- Function: lset-intersection elt= list1 list2 ...
     [SRFI-1] Returns a set of elements that are in every LISTs.

 -- Function: lset-difference elt= list1 list2 ...
     [SRFI-1] Returns a set of elements that are in LIST1 but not in
     LIST2.  In n-ary case, binary differece operation is simply folded.

 -- Function: lset-xor elt= list1 ...
     [SRFI-1] Returns the exclusive-or of given sets; that is, the
     returned set consists of the elements that are in either LIST1 or
     LIST2, but not in both.   In n-ary case, binary xor operation is
     simply folded.

 -- Function: lset-diff+intersection elt= list1 list2 ...
     [SRFI-1] Returns two sets, a difference and an intersection of
     given sets.

 -- Function: lset-union! elt= list ...
 -- Function: lset-intersection! elt= list1 list2 ...
 -- Function: lset-difference! elt= list1 list2 ...
 -- Function: lset-xor! elt= list1 ...
 -- Function: lset-diff+intersection! elt= list1 list2 ...
     [SRFI-1] Linear update variant of the corresponding procedures.
     The cells in the first list argument may be reused to construct
     the result.


File: gauche-refe.info,  Node: And-let*,  Next: Homogeneous vectors,  Prev: List library,  Up: Library modules - SRFIs

10.3 `srfi-2' - And-let*
========================

 -- Module: srfi-2
     Provides SRFI-2 `and-let*' macro.

 -- Macro: and-let* (binding ...) body ...
     [SRFI-2] In short, it works like `let*', but returns #f immediately
     whenever the expression in BINDINGs evaluates to #f.

     Each BINDING should be one of the following form:
    (VARIABLE EXPRESSION)
          The EXPRESSION is evaluated; if it yields true value, the
          value is bound to VARIABLE, then proceed to the next binding.
          If no more bindings, evaluates BODY ....   If EXPRESSION
          yieds `#f', stops evaluation and returns `#f' from `and-let*'.

    (EXPRESSION)
          In this form, VARIABLE is omitted.  EXPRESSION is evaluated
          and the result is used just to determine whether we continue
          or stop further evaluation.

     Let's see some examples.  The following code searches KEY from an
     assoc-list ALIST and returns its value if found.
          (and-let* ((entry (assoc key alist))) (cdr entry))

     If ARG is a string representation of an exact integer, returns its
     value; otherwise, returns 0:
          (or (and-let* ((num (string->number arg))
                         ((exact? num))
                         ((integer? num)))
                num)
              0)

     The following is a hypothetical code that searches a certain
     server port number from a few possibilities (environment variable,
     configuration file, ...)
          (or (and-let* ((val (sys-getenv "SERVER_PORT")))
                (string->number val))
              (and-let* ((portfile (expand-path "~/.server_port"))
                         ((file-exists? portfile))
                         (val (call-with-input-string portfile port->string)))
                (string->number val))
              8080) ; default



File: gauche-refe.info,  Node: Homogeneous vectors,  Next: A compatible let form with signatures and rest arguments,  Prev: And-let*,  Up: Library modules - SRFIs

10.4 `srfi-4' - Homogeneous vectors
===================================

 -- Module: srfi-4
     SRFI-4 is now implemented in `gauche.uvector' module *Note Uniform
     vectors::.  This module simply inherits `gauche.uvector' for
     backward-compatibility.


File: gauche-refe.info,  Node: A compatible let form with signatures and rest arguments,  Next: Feature-based program configuration language,  Prev: Homogeneous vectors,  Up: Library modules - SRFIs

10.5 `srfi-5' - A compatible let form with signatures and rest arguments
========================================================================

 -- Module: srfi-5
     This module provides srfi-5's extended `let' syntax.

 -- Macro: let ((var val) ... [. (rest val ...)]) body ...
 -- Macro: let name ((var val) ... [. (rest val ...)]) body ...
 -- Macro: let (name (var val) ... [. (rest val ...)]) body ...
     [SRFI-5] The `let' syntax is extended in two ways.

        * The extended `let' syntax accepts the NAME identifier (for
          named let syntax) within the list of bindings (as in the third
          syntax above).

        * The extended `let' syntax accepts the rest parameter binding
          which works like the rest paremter in the `lambda' syntax.

     See SRFI-5 document for rationale of this extension.


File: gauche-refe.info,  Node: Feature-based program configuration language,  Next: Record types,  Prev: A compatible let form with signatures and rest arguments,  Up: Library modules - SRFIs

10.6 `srfi-7' - Feature-based program configuration language
============================================================

 -- Module: srfi-7
     This module provides a program configuration metalanguage
     (`program' form) defined in srfi-7.  Gauche autoloads srfi-7
     module, so you don't need to say `(use srfi-7)' explicitly.  Note
     that the `program' form isn't necessary to be a Scheme expression.
     Srfi-7 allows an implementation to preprocess the `program' form
     to produce a Scheme program, then executes it with different means.
     Gauche implements `program' form as a macro, so it can evaluates
     the form directly.  Nonetheless, it doesn't make sense to mix
     `program' form and other forms in one file, or expecting a return
     value of `program' form.  A typical usage of `program' form is to
     prepare a single file which just contains `program' form.  (It can
     load other files using `files' clause (see below) within the
     `program' form.)   To execute such a program file in Gauche, you
     can just load it.

 -- Configuration Language: program program-clause program-clause2 ...
     [SRFI-7] This is a configuration language to structure a Scheme
     program, based on availability of the features.

     A Scheme program is constructed from the `program' form.  Gauche
     evaluates the constructed Scheme program on-the-fly.

     Each PROGRAM-CLAUSE needs to be one of the "Program Clauses" below.

 -- Program Clause: requires feature-id feature-id2 ...
     [SRFI-7] The FEATURE-ID's are the same as `srfi-0''s (*Note
     Feature conditional::).  It tells that the following code requires
     these FEATURE-ID's.

     If a feature-id which is not supported in Gauche is given, an
     error is signaled.

 -- Program Clause: files filename ...
     [SRFI-7] Inserts the content of the FILENAMEs into a program.  In
     Gauche, this clause just causes FILENAMEs to be loaded into the
     current module.

 -- Program Clause: code scheme-expression ...
     [SRFI-7] The SCHEME-EXPRESSIONs are inserted into a program.

 -- Program Clause: feature-cond clause clause2 ...
     [SRFI-7] CLAUSE is a following form:
          (REQUIREMENT PROGRAM-CLAUSE PROGRAM-CLAUSE2 ...)

     Where REQUIREMENT should be one of the following:
        * FEATURE-ID

        * `(and REQUIREMENT ...)'

        * `(or REQUIREMENT ...)'

        * `(not REQUIREMENT)'

     The REQUIREMENT of the last CLAUSE may be `else'.

     Gauche checks each REQUIREMENT one by one, and if it finds a
     fulfilled REQUIREMENT, inserts the PROGRAM-CLAUSEs in that CLAUSE
     into the program.


File: gauche-refe.info,  Node: Record types,  Next: Let-values,  Prev: Feature-based program configuration language,  Up: Library modules - SRFIs

10.7 `srfi-9' - Record types
============================

 -- Module: srfi-9
     Contains a macro to use record types.  A record type is
     implemented on top of Gauche's object system.

     The SRFI-9 record type is not as powerful as the object system, but
     it will be useful if you want your program to be portable.

     See also *Note SLIB-compatible record type::, which provides an
     SCM-compatible procedural interface of record types.

 -- Macro: define-record-type name (constructor init-tag ...) predicate
          (field accessor [modifier]) ...
     Creates a record type and binds it to NAME.  In Gauche, a record
     type is just a subclass of `<record>'.

     CONSTRUCTOR is bound to a procedure that creates an instance of
     the record type, which takes as many arguments as INIT-TAG ....
     Each INIT-TAG corresponds to one of the field name, and the fields
     of the created record instance is initialized accordingly.  Not all
     of fields need to appear in INIT-TAG; uninitialized fields remain
     unbound.

     PREDICATE is bound to a procedure that takes one argument, and
     returns #t if the argument is an instance of the defined record
     type, #f otherwise.

     Followings are field specifications.  The record has fields FIELD
     ..., and each field can be accessed by a method ACCESSOR.  If
     MODIFIER is given to the field, it is bound to a method that sets
     the value to the field.

     Example:
          (define-record-type pare
            (kons x y) pare?
            (x kar set-kar!)
            (y kdr))
           => #<class pare>

          (pare? (kons 2 3)) => #t
          (pare? (cons 2 3)) => #f

          (kar (kons 2 3)) => 2
          (kdr (kons 2 3)) => 3

          (let ((x (kons 2 3)))
            (set-kar! x -1)
            (kar x)) => -1

     Conceptually, the above example is expanded into the following
     sequence of forms.
          (define-class pare (<record>) (x y))
          (define (kons x y)
            (let ((obj (make pare)))
              (slot-set! obj 'x x)
              (slot-set! obj 'y y)
              obj))
          (define (pare? obj) (is-a? obj pare))
          (define-method kar ((obj pare))
            (slot-ref obj 'x))
          (define-method set-kar! ((obj pare) value)
            (slot-set! obj 'x value))
          (define-method kdr ((obj pare))
            (slot-ref obj 'y))



File: gauche-refe.info,  Node: Let-values,  Next: String library,  Prev: Record types,  Up: Library modules - SRFIs

10.8 `srfi-11' - Let-values
===========================

 -- Module: srfi-11
     Defines two macros, `let-values' and `let*-values'.  They are
     convenient to use with multiple values (*Note [SRFI-11]: srfi-11.).


 -- Macro: let-values ((vars expr) ...) body ...
     [SRFI-11] VARS are a list of variables. EXPR is evaluated, and its
     first return value is bound to the first variable in VARS, its
     second return value to the second variable, and so on, then BODY
     is evaluated.  The scope of EXPRs are the outside of `let-values'
     form, like `let'.

          (let-values (((a b) (values 1 2))
                       ((c d) (values 3 4)))
            (list a b c d)) => (1 2 3 4)

          (let ((a 1) (b 2) (c 3) (d 4))
            (let-values (((a b) (values c d))
                         ((c d) (values a b)))
              (list a b c d))) => (3 4 1 2)

     VARS can be a dotted list or a single symbol, like the lambda
     parameters.

          (let-values (((x . y) (values 1 2 3 4)))
            y) => (2 3 4)

          (let-values ((x (values 1 2 3 4)))
            x) => (1 2 3 4)

     If the number of values returned by EXPR doesn't match what VARS
     expects, an error is signalled.

 -- Macro: let*-values ((vars expr) ...) body ...
     [SRFI-11] Same as `let-values', but each EXPR's scope includes the
     preceding VARS.

          (let ((a 1) (b 2) (c 3) (d 4))
            (let*-values (((a b) (values c d))
                          ((c d) (values a b)))
              (list a b c d))) => (3 4 3 4)


File: gauche-refe.info,  Node: String library,  Next: Character-set library,  Prev: Let-values,  Up: Library modules - SRFIs

10.9 `srfi-13' - String library
===============================

 -- Module: srfi-13
     Defines a large set of string-related functions.  In Gauche, those
     functions are splitted to number of files and the form `(use
     srfi-13)' merely sets up autoloading of those files.  So it is not
     likely to slow down the script startup.  See SRFI-13 (*Note
     [SRFI-13]: srfi-13.)  for the detailed specification and
     discussion of design issues.  This manual serves as a reference of
     function API.  Some SRFI-13 functions are Gauche built-in and not
     listed here.  Note: SRFI-13 documents suggests the name of the
     module that implements these functions to be "string-lib" and
     "string-lib-internals".  Gauche uses the name "srfi-13" for
     consistency.

* Menu:

* SRFI-13 General conventions::
* SRFI-13 String predicates::
* SRFI-13 String Constructors::
* SRFI-13 String Selection::
* SRFI-13 String Comparison::
* SRFI-13 String Prefixes & Suffixes::
* SRFI-13 String searching::
* SRFI-13 String case mapping::
* SRFI-13 String reverse & append::
* SRFI-13 String mapping::
* SRFI-13 String rotation::
* SRFI-13 other string operations::
* SRFI-13 String filtering::
* SRFI-13 Low-level string procedures::


File: gauche-refe.info,  Node: SRFI-13 General conventions,  Next: SRFI-13 String predicates,  Prev: String library,  Up: String library

10.9.1 General conventions
--------------------------

There are a few common factors in string library API, which I don't
repeat in each function description

_argument convention_
     The following argument names imply their types.
    S, S1, S2
          Those arguments must be strings.

    CHAR/CHAR-SET/PRED
          This argument can be a character, a character-set object, or
          a predicate that takes a single character and returns a
          boolean value.  "Applying CHAR/CHAR-SET/PRED to a character"
          means, if CHAR/CHAR-SET/PRED is a character, it is compared
          to the given character; if CHAR/CHAR-SET/PRED is a character
          set, it is checked if the character set contains the given
          character; if CHAR/CHAR-SET/PRED is a procedure, it is applied
          to the given character.  "A character satisfies
          CHAR/CHAR-SET/PRED" means such application to the character
          yields true value.

    START, END
          Lots of SRFI-13 functions takes these two optional arguments,
          which limit the area of input string from START-th character
          (inclusive) to END-th character (exclusive), where the
          operation is performed.  When specified, the condition 0 <=
          START <= END <= LENGTH OF THE STRING must be satisfied.
          Default value of START and END is 0 and the length of the
          string, respectively.

_`shared' variant_
     Some functions have variants with "/shared" attached to its name.
     SRFI-13 defines those functions to allow to share the part of input
     string, for better performance.  Gauche doesn't have a concept of
     shared string, and these functions are mere synonyms of their
     non-shared variants.  However, Gauche _internally_ shares the
     storage of strings, so generally you don't need to worry about the
     overhead of copying substrings.

_`right' variant_
     Most functions works from left to right of the input string.  Some
     functions have variants with "-right" to its name, that works from
     right to left.



File: gauche-refe.info,  Node: SRFI-13 String predicates,  Next: SRFI-13 String Constructors,  Prev: SRFI-13 General conventions,  Up: String library

10.9.2 String predicates
------------------------

 -- Function: string-null? s
     [SRFI-13] Returns `#t' if S is an empty string, `""'.

 -- Function: string-every char/char-set/pred s &optional start end
     [SRFI-13] Sees if every character in S satisfies
     CHAR/CHAR-SET/PRED.  If so, `string-every' returns the value that
     is returned at the last application of CHAR/CHAR-SET/PRED.  If any
     of the application returns `#f', `string-every' returns `#f'
     immediately.

 -- Function: string-any char/char-set/pred s &optional start end
     [SRFI-13] Sees if any character in S satisfies CHAR/CHAR-SET/PRED.
     If so, `string-any' returns the value that is returned by the
     application.   If no character satisfies CHAR/CHAR-SET/PRED, `#f'
     is returned.


File: gauche-refe.info,  Node: SRFI-13 String Constructors,  Next: SRFI-13 String Selection,  Prev: SRFI-13 String predicates,  Up: String library

10.9.3 String Constructors
--------------------------

 -- Function: string-tabulate proc len
     [SRFI-13] PROC must be a procedure that takes an integer argument
     and returns a character.  `string-tabulate' creates a string,
     whose I-th character is calculated by `(proc i)'.
          (string-tabulate
            (lambda (i) (integer->char (+ i #x30))) 10)
           => "0123456789"


 -- Function: reverse-list->string char-list
     [SRFI-13] == `(list->string (reverse char-list))'.


File: gauche-refe.info,  Node: SRFI-13 String Selection,  Next: SRFI-13 String Comparison,  Prev: SRFI-13 String Constructors,  Up: String library

10.9.4 String selection
-----------------------

 -- Function: substring/shared s start &optional end
     [SRFI-13] In Gauche, this is the same as `substring', except that
     the END argument is optional.
          (substring/shared "abcde" 2) => "cde"

 -- Function: string-copy! target tstart s &optional start end
     [SRFI-13] Copies a string S into a string TARGET from the position
     TSTART.  Optional START and END arguments limits the range of S.
     If the copied string run over the end of TARGET, an error is
     signalled.
          (define s (string-copy "abcde"))
          (string-copy! s 2 "ZZ")
          s => "abZZe"

 -- Function: string-take s nchars
 -- Function: string-drop s nchars
 -- Function: string-take-right s nchars
 -- Function: string-drop-right s nchars
     [SRFI-13] Returns the first NCHARS-character string of S
     (`string-take') or the string without first NCHARS
     (`string-drop').  The `*-right' variation counts from the end of
     string.  It is guaranteed that the returned string is always a
     copy of S, even no character is dropped.
          (string-take "abcde" 2) => "ab"
          (string-drop "abcde" 2) => "cde"

          (string-take-right "abcde" 2) => "de"
          (string-drop-right "abcde" 2) => "abc"

 -- Function: string-pad s len &optional char start end
 -- Function: string-pad-right s len &optional char start end
     [SRFI-13] If a string S is shorter than LEN, returns a string of
     LEN where CHAR is padded to the left or right, respectively.  If S
     is longer than LEN, the rightmost or leftmost LEN chars are taken.
     CHAR defaults to `#\space'.  If START and END are provided, the
     substring of S is used as the source.

          (string-pad "abc" 10)    => "       abc"
          (string-pad "abcdefg" 3) => "efg"

          (string-pad-right "abc" 10) => "abc       "

          (string-pad "abcdefg" 10 #\+ 2 5)
            => "+++++++cde"

 -- Function: string-trim s &optional char/char-set/pred start end
 -- Function: string-trim-right s &optional char/char-set/pred start end
 -- Function: string-trim-both s &optional char/char-set/pred start end
     [SRFI-13] Removes characters that match CHAR/CHAR-SET/PRED from S.
     `String-trim' removes the characters from left of S,
     `string-trim-right' does from right, and `string-trim-both' does
     from both sides.  CHAR/CHAR-SET/PRED defaults to `#[\s]', i.e. a
     char-set of whitespaces.  If START and END are provided, the
     substring of S is used as the source.

          (string-trim "   abc  ")       => "abc  "
          (string-trim-right "   abc  ") => "   abc"
          (string-trim-both "   abc  ")  => "abc"


File: gauche-refe.info,  Node: SRFI-13 String Comparison,  Next: SRFI-13 String Prefixes & Suffixes,  Prev: SRFI-13 String Selection,  Up: String library

10.9.5 String comparison
------------------------

 -- Function: string-compare s1 s2 proc< proc= proc> &optional start1
          end1 start2 end2
 -- Function: string-compare-ci s1 s2 proc< proc= proc> &optional
          start1 end1 start2 end2
     [SRFI-13]

 -- Function: string= s1 s2 &optional start1 end1 start2 end2
 -- Function: string`<>' s1 s2 &optional start1 end1 start2 end2
 -- Function: string`<' s1 s2 &optional start1 end1 start2 end2
 -- Function: string`<=' s1 s2 &optional start1 end1 start2 end2
 -- Function: string`>' s1 s2 &optional start1 end1 start2 end2
 -- Function: string`>=' s1 s2 &optional start1 end1 start2 end2
     [SRFI-13]

 -- Function: string-ci`=' s1 s2 &optional start1 end1 start2 end2
 -- Function: string-ci`<>' s1 s2 &optional start1 end1 start2 end2
 -- Function: string-ci`<' s1 s2 &optional start1 end1 start2 end2
 -- Function: string-ci`<=' s1 s2 &optional start1 end1 start2 end2
 -- Function: string-ci`>' s1 s2 &optional start1 end1 start2 end2
 -- Function: string-ci`>=' s1 s2 &optional start1 end1 start2 end2
     [SRFI-13]

 -- Function: string-hash s &optional bound start end
 -- Function: string-hash-ci s &optional bound start end
     [SRFI-13]


File: gauche-refe.info,  Node: SRFI-13 String Prefixes & Suffixes,  Next: SRFI-13 String searching,  Prev: SRFI-13 String Comparison,  Up: String library

10.9.6 String Prefixes & Suffixes
---------------------------------

 -- Function: string-prefix-length s1 s2 &optional start1 end1 start2
          end2
 -- Function: string-suffix-length s1 s2 &optional start1 end1 start2
          end2
 -- Function: string-prefix-length-ci s1 s2 &optional start1 end1
          start2 end2
 -- Function: string-suffix-length-ci s1 s2 &optional start1 end1
          start2 end2
     [SRFI-13]

 -- Function: string-prefix? s1 s2 &optional start1 end1 start2 end2
 -- Function: string-suffix? s1 s2 &optional start1 end1 start2 end2
 -- Function: string-prefix-ci? s1 s2 &optional start1 end1 start2 end2
 -- Function: string-suffix-ci? s1 s2 &optional start1 end1 start2 end2
     [SRFI-13]


File: gauche-refe.info,  Node: SRFI-13 String searching,  Next: SRFI-13 String case mapping,  Prev: SRFI-13 String Prefixes & Suffixes,  Up: String library

10.9.7 String searching
-----------------------

 -- Function: string-index s char/char-set/pred &optional start end
 -- Function: string-index-right s char/char-set/pred &optional start
          end
     [SRFI-13] Looks for the first element in a string S that matches
     CHAR/CHAR-SET/PRED, and returns its index.  If CHAR/CHAR-SET/PRED
     is not found in S, returns `#f'.  Optional START and END limit the
     range of S to search.
          (string-index "Aloha oe" #\a) => 4
          (string-index "Aloha oe" #[Aa]) => 0
          (string-index "Aloha oe" #[\s]) => 5
          (string-index "Aloha oe" char-lower-case?) => 1
          (string-index "Aloha oe" #\o 3) => 6

     See also the Gauche built-in procedure `string-scan' (*Note String
     utilities::), if you need speed over portability.

 -- Function: string-skip s char/char-set/pred &optional start end
 -- Function: string-skip-right s char/char-set/pred &optional start end
     [SRFI-13] Looks for the first element that does not match
     CHAR/CHAR-SET/PRED and returns its index.  If such element is not
     found, returns `#f'.  Optional START and END limit the range of S
     to search.

 -- Function: string-count s char/char-set/pred &optional start end
     [SRFI-13] Counts the number of elements in S that matches
     CHAR/CHAR-SET/PRED.  Optional START and END limit the range of S
     to search.

 -- Function: string-contains s1 s2 &optional start1 end1 start2 end2
 -- Function: string-contains-ci s1 s2 &optional start1 end1 start2 end2
     [SRFI-13] Looks for a string S2 inside another string S1.  If
     found, returns an index in S1 from where the matching string
     begins.  Returns `#f' otherwise.  Optional START1, END1, START2
     and END2 limits the range of S1 and S2.

     See also the Gauche built-in procedure `string-scan' (*Note String
     utilities::), if you need speed over portability.


File: gauche-refe.info,  Node: SRFI-13 String case mapping,  Next: SRFI-13 String reverse & append,  Prev: SRFI-13 String searching,  Up: String library

10.9.8 String case mapping
--------------------------

 -- Function: string-titlecase s &optional start end
 -- Function: string-titlecase! s &optional start end
     [SRFI-13]

 -- Function: string-upcase s &optional start end
 -- Function: string-upcase! s &optional start end
     [SRFI-13]

 -- Function: string-downcase s &optional start end
 -- Function: string-downcase! s &optional start end
     [SRFI-13]


File: gauche-refe.info,  Node: SRFI-13 String reverse & append,  Next: SRFI-13 String mapping,  Prev: SRFI-13 String case mapping,  Up: String library

10.9.9 String reverse & append
------------------------------

 -- Function: string-reverse s &optional start end
 -- Function: string-reverse! s &optional start end
     [SRFI-13] Returns a string in which the character positions are
     reversed from S.  `string-reverse!' modifies S.
          (string-reverse "mahalo") => "olaham"
          (string-reverse "mahalo" 3) => "ola"
          (string-reverse "mahalo" 1 4) => "aha"

          (let ((s (string-copy "mahalo")))
            (string-reverse! s 1 5)
            s)
            => "mlahao"

 -- Function: string-concatenate string-list
     [SRFI-13] Concatenates list of strings.
          (string-concatenate '("humuhumu" "nukunuku" "apua" "`a"))
            => "humuhumunukunukuapua`a"

 -- Function: string-concatenate/shared string-list
 -- Function: string-append/shared s ...
     [SRFI-13] "Shared" version of `string-concatenate' and
     `string-append'.  In Gauche, these are just synonyms of them.

 -- Function: string-concatenate-reverse string-list
 -- Function: string-concatenate-reverse/shared string-list
     [SRFI-13] Reverses STRING-LIST before concatenation.  "Shared"
     version works the same in Gauche.


File: gauche-refe.info,  Node: SRFI-13 String mapping,  Next: SRFI-13 String rotation,  Prev: SRFI-13 String reverse & append,  Up: String library

10.9.10 String mapping
----------------------

 -- Function: string-map proc s &optional start end
 -- Function: string-map! proc s &optional start end
     [SRFI-13] `string-map' applies PROC on every character of S, and
     collects the results into a string and returns it.  On the other
     hand, `string-map!' modifies S.
          (string-map char-upcase "wikiwiki") => "WIKIWIKI"
          (string-map char-upcase "wikiwiki" 4) => "WIKI"

          (let ((s (string-copy "wikiwiki")))
            (string-map! char-upcase s 4)
            s)
            => "wikiWIKI"

 -- Function: string-fold kons knil s &optional start end
 -- Function: string-fold-right kons knil s &optional start end
     [SRFI-13]

 -- Function: string-unfold p f g seed &optional base make-final
     [SRFI-13]

 -- Function: string-unfold-right p f g seed &optional base make-final
     [SRFI-13]

 -- Function: string-for-each proc s &optional start end
     [SRFI-13]

 -- Function: string-for-each-index proc s &optional start end
     [SRFI-13]


File: gauche-refe.info,  Node: SRFI-13 String rotation,  Next: SRFI-13 other string operations,  Prev: SRFI-13 String mapping,  Up: String library

10.9.11 String rotation
-----------------------

 -- Function: xsubstring s from &optional to start end
     [SRFI-13]

 -- Function: string-xcopy! target tstart s sfrom &optional sto start
          end
     [SRFI-13]


File: gauche-refe.info,  Node: SRFI-13 other string operations,  Next: SRFI-13 String filtering,  Prev: SRFI-13 String rotation,  Up: String library

10.9.12 Other string operations
-------------------------------

 -- Function: string-replace s1 s2 start1 end2 &optional start2 end2
     [SRFI-13]

 -- Function: string-tokenize s &optional token-set start end
     [SRFI-13] Splits the string S into a list of substrings, where
     each substring is a maximal non-empty contiguous sequence of
     characters from the character set TOKEN-SET.  The default of
     TOKEN-SET is `char-set:graphic' (*Note SRFI-14 Predefined
     character-set::).

     See also Gauche's built-in `string-split' (*Note String
     utilities::), which provides similar features but different
     criteria.


File: gauche-refe.info,  Node: SRFI-13 String filtering,  Next: SRFI-13 Low-level string procedures,  Prev: SRFI-13 other string operations,  Up: String library

10.9.13 String filtering
------------------------

 -- Function: string-filter s char/char-set/pred &optional start end
 -- Function: string-delete s char/char-set/pred &optional start end
     [SRFI-13]


File: gauche-refe.info,  Node: SRFI-13 Low-level string procedures,  Prev: SRFI-13 String filtering,  Up: String library

10.9.14 Low-level string procedures
-----------------------------------

 -- Function: string-parse-start+end proc s args
 -- Function: string-parse-final-start+end proc s args
     [SRFI-13]

 -- Macro: let-string-start+end (start end [rest]) proc-exp s-exp
          args-exp body ...
     [SRFI-13]

 -- Function: check-substring-spec proc s start end
 -- Function: substring-spec-ok? s start end
     [SRFI-13]

 -- Function: make-kmp-restart-vector s &optional c= start end
     [SRFI-13]

 -- Function: kmp-step pat rv c i c= p-start
     [SRFI-13]

 -- Function: string-kmp-partial-search pat rv s i &optional c= p-start
          s-start s-end
     [SRFI-13]


File: gauche-refe.info,  Node: Character-set library,  Next: Time data types and procedures,  Prev: String library,  Up: Library modules - SRFIs

10.10 `srfi-14' - Character-set library
=======================================

 -- Module: srfi-14
     Implements the character set library defined in SRFI-14 (*Note
     SRFI-14: srfi-14.).  Note that several basic character-set
     operations are Gauche's build-in functions.  *Note Character set::.

* Menu:

* SRFI-14 Character-set constructors::
* SRFI-14 Character-set Comparison::
* SRFI-14 Character-set iteration::
* SRFI-14 Character-set query::
* SRFI-14 Character-set algebra::
* SRFI-14 Predefined character-set::


File: gauche-refe.info,  Node: SRFI-14 Character-set constructors,  Next: SRFI-14 Character-set Comparison,  Prev: Character-set library,  Up: Character-set library

10.10.1 Character-set constructors
----------------------------------

 -- Function: list->char-set char-list &optional base-cs
 -- Function: list->char-set! char-list base-cs
     [SRFI-14] Constructs a character set from a list of characters
     CHAR-LIST.  If BASE-CS is given, it must be a character set, and
     the characters in it are added to the result character set.
     `List->char-set!' is allowed, but not required, to reuse BASE-CS
     to store the result.

 -- Function: string->char-set s &optional base-cs
 -- Function: string->char-set! s base-cs
     [SRFI-14] Like `list->char-set' and `list->char-set!', but take a
     list of characters from a string S.

 -- Function: char-set-filter pred char-set &optional base-cs
 -- Function: char-set-filter! pred char-set base-cs
     [SRFI-14] Returns a character set containing every character C in
     CHAR-SET such that `(PRED C)' returns true.  If a character set
     BASE-CS is given, its content is added to the result.  The linear
     update version `char-set-filter!' is allowed, but not required, to
     modify BASE-CS to store the result.

 -- Function: ucs-range->char-set lower upper &optional error? base-cs
 -- Function: ucs-range->char-set! lower upper error? base-cs
     [SRFI-14]


 -- Function: integer-range->char-set lower upper &optional error?
          base-cs
 -- Function: integer-range->char-set! lower upper error? base-cs

 -- Function: ->char-set x
     [SRFI-14]


File: gauche-refe.info,  Node: SRFI-14 Character-set Comparison,  Next: SRFI-14 Character-set iteration,  Prev: SRFI-14 Character-set constructors,  Up: Character-set library

10.10.2 Character-set comparison
--------------------------------

 -- Function: char-set= char-set1 ...
     [SRFI-14]

 -- Function: char-set`<=' char-set1 ...
     [SRFI-14]

 -- Function: char-set-hash char-set &optional bound
     [SRFI-14]


File: gauche-refe.info,  Node: SRFI-14 Character-set iteration,  Next: SRFI-14 Character-set query,  Prev: SRFI-14 Character-set Comparison,  Up: Character-set library

10.10.3 Character-set iteration
-------------------------------

 -- Function: char-set-cursor char-set
     [SRFI-14]

 -- Function: char-set-ref char-set cursor
     [SRFI-14]

 -- Function: char-set-cursor-next char-set cursor
     [SRFI-14]

 -- Function: end-of-char-set? ccursor
     [SRFI-14]

 -- Function: char-set-fold kons knil char-set
     [SRFI-14]

 -- Function: char-set-unfold pred fun gen seed &optional base-char-set
 -- Function: char-set-unfold! pred fun gen seed base-char-set
     [SRFI-14]

 -- Function: char-set-for-each proc char-set
     [SRFI-14]

 -- Function: char-set-map proc char-set
     [SRFI-14]


File: gauche-refe.info,  Node: SRFI-14 Character-set query,  Next: SRFI-14 Character-set algebra,  Prev: SRFI-14 Character-set iteration,  Up: Character-set library

10.10.4 Character-set query
---------------------------

 -- Function: char-set-size char-set
     [SRFI-14]

 -- Function: char-set-count pred char-set
     [SRFI-14]

 -- Function: char-set->list char-set
     [SRFI-14]

 -- Function: char-set->string char-set
     [SRFI-14]

 -- Function: char-set-every pred char-set
     [SRFI-14]

 -- Function: char-set-any pred char-set
     [SRFI-14]


File: gauche-refe.info,  Node: SRFI-14 Character-set algebra,  Next: SRFI-14 Predefined character-set,  Prev: SRFI-14 Character-set query,  Up: Character-set library

10.10.5 Character-set algebra
-----------------------------

 -- Function: char-set-adjoin char-set char1 ...
 -- Function: char-set-adjoin! char-set char1 ...
     [SRFI-14] Returns a character set that adds CHAR1 ... to CHAR-SET.

 -- Function: char-set-delete char-set char1 ...
 -- Function: char-set-delete! char-set char1 ...
     [SRFI-14]

 -- Function: char-set-complement char-set
 -- Function: char-set-complement! char-set
     [SRFI-14]

 -- Function: char-set-union char-set ...
 -- Function: char-set-union! char-set1 char-set2 ...
     [SRFI-14]

 -- Function: char-set-intersection char-set ...
 -- Function: char-set-intersection! char-set1 char-set2 ...
     [SRFI-14]

 -- Function: char-set-difference char-set1 char-set2 ...
 -- Function: char-set-difference! char-set1 char-set2 ...
     [SRFI-14]

 -- Function: char-set-xor char-set ...
 -- Function: char-set-xor! char-set1 char-set2 ...
     [SRFI-14]

 -- Function: char-set-diff+intersection char-set1 char-set2 ...
 -- Function: char-set-diff+intersection! char-set1 char-set2 char-set3
          ...
     [SRFI-14]


File: gauche-refe.info,  Node: SRFI-14 Predefined character-set,  Prev: SRFI-14 Character-set algebra,  Up: Character-set library

10.10.6 Predefined character-set
--------------------------------

 -- Variable: char-set:letter
     [SRFI-14]

 -- Variable: char-set:blank
     [SRFI-14]

 -- Variable: char-set:iso-control
     [SRFI-14]

 -- Variable: char-set:digit
 -- Variable: char-set:hex-digit
     [SRFI-14]

 -- Variable: char-set:graphic
     [SRFI-14]

 -- Variable: char-set:lower-case
 -- Variable: char-set:upper-case
 -- Variable: char-set:title-case
     [SRFI-14]

 -- Variable: char-set:printing
     [SRFI-14]

 -- Variable: char-set:punctuation
     [SRFI-14]

 -- Variable: char-set:whitespace
     [SRFI-14]

 -- Variable: char-set:symbol
     [SRFI-14]

 -- Variable: char-set:ascii
     [SRFI-14]

 -- Variable: char-set:empty
     [SRFI-14]

 -- Variable: char-set:full
     [SRFI-14]


File: gauche-refe.info,  Node: Time data types and procedures,  Next: Sources of random bits,  Prev: Character-set library,  Up: Library modules - SRFIs

10.11 `srfi-19' - Time data types and procedures
================================================

This SRFI defines various representations of time and date, and
conversion methods among them.

   On Gauche, time object is supported natively by `<time>' class
(*Note Time::).  Date object is supported by `<date>' class described
below.

* Menu:

* SRFI-19 Time types::
* SRFI-19 Time queries::
* SRFI-19 Time procedures::
* SRFI-19 Date::
* SRFI-19 Date reader and writer::


File: gauche-refe.info,  Node: SRFI-19 Time types,  Next: SRFI-19 Time queries,  Prev: Time data types and procedures,  Up: Time data types and procedures

10.11.1 Time types
------------------

Time type is represented by a symbol.  This module defines the
following constant variables that is bound to its name, for convenience.

 -- Constant: time-utc
     [SRFI-19] UTC time.  Gauche's built-in `current-time' always
     returns this type (*Note Time::).

 -- Constant: time-tai
     [SRFI-19] International Atomic Time.  This time is a bit larger
     than UTC, due to the leap seconds.

 -- Constant: time-monotonic
     [SRFI-19] Implementation-dependent monotonically increasing time.
     In Gauche, this is the same as `time-tai'.

 -- Constant: time-duration
     [SRFI-19] Duration between two absolute time points.

 -- Constant: time-process
     [SRFI-19] CPU time in current process.  Gauche calculates this
     from user time and system time returned by POSIX times(3).

 -- Constant: time-thread
     [SRFI-19] CPU time in current thread.  In the current
     implementation, this is the same as `time-process'.


File: gauche-refe.info,  Node: SRFI-19 Time queries,  Next: SRFI-19 Time procedures,  Prev: SRFI-19 Time types,  Up: Time data types and procedures

10.11.2 Time queries
--------------------

 -- Function: current-time &optional time-type
     [SRFI-19] Extends Gauche built-in `current-time' (*Note Time::) to
     take optional TIME-TYPE argument to specify the desired time type.
     TIME-TYPE must be one of the types described in *Note SRFI-19 Time
     types::.

 -- Function: current-date &optional tz-offset
     [SRFI-19] Returns the current date as an instance of `<date>' class
     (*Note SRFI-19 Date::).  If TZ-OFFSET is given, it must be an
     offset from UTC in number of seconds.  If TZ-OFFSET is not given,
     returns the date in local time zone.

 -- Function: current-julian-day
     [SRFI-19] Returns the current julian day, a point in time as a
     real number of days since -4714-11-24T12:00:00Z (November 24,
     -4714 at noon, UTC).

 -- Function: current-modified-julian-day
     [SRFI-19] Returns the current modified julian day, a point in time
     as a real number of days since 1858-11-17T00:00:00Z (November 17,
     1858 at midnight, UTC).

 -- Function: time-resolution
     [SRFI-19]


File: gauche-refe.info,  Node: SRFI-19 Time procedures,  Next: SRFI-19 Date,  Prev: SRFI-19 Time queries,  Up: Time data types and procedures

10.11.3 Time procedures
-----------------------

 -- Function: make-time type nanoseconds seconds
     [SRFI-19] Returns an instance of `<time>' class with specified
     initial values.  Equivalent to `(make <time> :type type :second
     seconds :nanosecond nanoseconds)'.

     (This funciton had been defined incorrectly before release 0.6.8;
     the arguments SECONDS and NANOSECONDS were switched.  Please check
     your code if it uses `make-time').

 -- Function: time-type time
 -- Function: time-second time
 -- Function: time-nanosecond time
 -- Function: set-time-type! time type
 -- Function: set-time-second! time second
 -- Function: set-time-nanosecond! time nanosecond
     [SRFI-19] Getter and setter of `<time>' object slots.

 -- Function: copy-time time
     [SRFI-19] Returns a new instance of `<time>' whose content is the
     same as given TIME

 -- Function: time=? time0 time1
 -- Function: time<? time0 time1
 -- Function: time<=? time0 time1
 -- Function: time>? time0 time1
 -- Function: time>=? time0 time1
     [SRFI-19] Compares two times.  Types of both times must match.

 -- Function: time-difference time0 time1
 -- Function: time-difference! time0 time1
     [SRFI-19] Returns the difference of two times, in `time-duration'
     time.  Types of both times must match.  `Time-difference!'
     modifies TIME0 to store the result.

 -- Function: add-duration time0 time-duration
 -- Function: add-duration! time0 time-duration
 -- Function: subtract-duration time0 time-duration
 -- Function: subtract-duration! time0 time-duration
     [SRFI-19] Adds or subtracts TIME-DURATION to or from TIME0.  Type
     of returned time is the same as TIME0.  Type of TIME-DURATION must
     be `time-duration'.  `add-duration!' and `subtract-duration!' reuse
     TIME0 to store the result.


File: gauche-refe.info,  Node: SRFI-19 Date,  Next: SRFI-19 Date reader and writer,  Prev: SRFI-19 Time procedures,  Up: Time data types and procedures

10.11.4 Date
------------

 -- Class: <date>
     Represents a date.

      -- Instance Variable of nanosecond:
          Nanosecond portion of the date by an integer between 0 and
          999,999,999, inclusive.

      -- Instance Variable of second:
          Second portion of the date by an integer between 0 and 60,
          inclusive.  (60 for leap second).

      -- Instance Variable of minute:
          Minute portion of the date by an integer between 0 and 59,
          inclusive.

      -- Instance Variable of hour:
          Hour portion of the date by an integer between 0 and 23,
          inclusive.

      -- Instance Variable of day:
          Day portion of the date by an integer between 0 and 31,
          inclusive.  The actual upper bound of the day is determined
          by the year and the month.  (Note: 1 is for the first day; 0
          is allowed by the specification, but I don't see why).

      -- Instance Variable of month:
          Month portion of the date by an integer between 1 and 12,
          inclusive.  1 for January, 2 for February, and so on.  (Note:
          this is different from POSIX's `<sys-tm>' convention).

      -- Instance Variable of year:
          Year portion of the date.

      -- Instance Variable of zone-offset:
          The number of seconds east of GMT for this timezone, by an
          integer.

 -- Function: make-date nanosecond second minute hour day month year
          zone-offset
     [SRFI-19] Makes a `<date>' object from the given values.  Note:
     this procedure does not check if the values are in the valid range.

 -- Function: date? obj
     [SRFI-19] Returns true iff OBJ is a `<date>' object.

 -- Function: date-nanosecond date
 -- Function: date-second date
 -- Function: date-minute date
 -- Function: date-hour date
 -- Function: date-day date
 -- Function: date-month date
 -- Function: date-year date
 -- Function: date-zone-offset date
     [SRFI-19] Accessors.

 -- Function: date-year-day date
 -- Function: date-week-day date
 -- Function: date-week-number date day-of-week-starting-week
     [SRFI-19] Calculates the day number in the year (1 for January
     1st), the day number in the week (0 for Sunday, 1 for Monday, ...),
     and the ordinal week of the year which holds this date, ignoring a
     first partial week, respectively.

     DAY-OF-WEEK-STARTING-WEEK is the integer corresponding to the day
     of the week which is to be considered the first day of the week
     (Sunday=0, Monday=1, etc.).

 -- 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
     [SRFI-19] Conversions from date to various date/time types.

 -- Function: julian-day->date jd &optional tz-offset
 -- Function: julian-day->time-monotonic jd
 -- Function: julian-day->time-tai jd
 -- Function: julian-day->time-utc jd
     [SRFI-19] Conversions from julian-day to various date/time types.

 -- Function: modified-julian-day->date jd &optional tz-offset
 -- Function: modified-julian-day->time-monotonic jd
 -- Function: modified-julian-day->time-tai jd
 -- Function: modified-julian-day->time-utc jd
     [SRFI-19] Conversions from modified julian-day to various
     date/time types.

 -- Function: time-monotonic->date time &optional tz-offset
 -- Function: time-monotonic->julian-day time
 -- Function: time-monotonic->modified-julian-day time
 -- Function: time-monotonic->time-tai time
 -- Function: time-monotonic->time-tai! time
 -- Function: time-monotonic->time-utc time
 -- Function: time-monotonic->time-utc! time
     [SRFI-19] Conversions from time-monotonic to various date/time
     types.

 -- Function: time-tai->date time &optional 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
     [SRFI-19] Conversions from time-tai to various date/time types.

 -- Function: time-utc->date time &optional 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
     [SRFI-19] Conversions from time-utc to various date/time types.


File: gauche-refe.info,  Node: SRFI-19 Date reader and writer,  Prev: SRFI-19 Date,  Up: Time data types and procedures

10.11.5 Date reader and writer
------------------------------

 -- Function: date->string date &optional format-string
     [SRFI-19]

 -- Function: string->date string template-string
     [SRFI-19]


File: gauche-refe.info,  Node: Sources of random bits,  Next: Localization,  Prev: Time data types and procedures,  Up: Library modules - SRFIs

10.12 `srfi-27' - Sources of Random Bits
========================================

 -- Module: srfi-27
     This module provides SRFI-27 pseudo random generator interface,
     using Mersenne Twister algorithm (*Note Mersenne-Twister random
     number generator::) as the backbone.

 -- Function: random-integer n
     [SRFI-27] Returns a random exact integer between [0, N-1],
     inclusive, using the default random source.  To set a random seed
     for this procedure, use `random-source-randomize!' or
     `random-source-pseudo-randomize!' on `default-random-source'.

 -- Function: random-real
     [SRFI-27] Returns a random real number between (0, 1), exclusive,
     using the default random source.  To set a random seed for this
     procedure, use `random-source-randomize!' or
     `random-source-pseudo-randomize!' on `default-random-source'.

 -- Variable: default-random-source
     [SRFI-27] Keeps the default random source that is used by
     `random-integer' and `random-real'.

 -- Function: make-random-source
     [SRFI-27] Creates and returns a new random source.  In the current
     Gauche implementation, it is just a `<mersenne-twister>' object.
     It may be changed in the future implementation.

 -- Function: random-source? obj
     [SRFI-27] Returns `#t' if OBJ is a random source object.

 -- Function: random-source-state-ref s
 -- Function: random-source-state-set! s state
     [SRFI-27] Gets and sets the "snapshot" of the state of the random
     source S.  STATE is an opaque object whose content depends on the
     backbone generator.

 -- Function: random-source-randomize! s
     [SRFI-27] Makes an effort to set the state of the random source S
     to a truly random state.  The current implementation uses the
     current time and the process ID to set the random seed.

 -- Function: random-source-pseudo-randomize! s i j
     [SRFI-27] Changes the state of the random source S into the
     initial state of the (I, J)-th independent random source, where I
     and J are non-negative integers.  This procedure can be used to
     reuse a random source S as large number of independent random
     source, indexed by two non-negative integers.  Note that this
     procedure is entirely deterministic.

 -- Function: random-source-make-integers s
     [SRFI-27] Returns a procedure, that takes one integer argument N
     and returns a random integer between 0 and N-1 inclusive for every
     invocation, from the random source S.

 -- Function: random-source-make-reals s &optional unit
     [SRFI-27] Returns a procedure, that takes no argument and returns
     a random real between 0 and 1 exclusive for every invocation, from
     the random source S.  If UNIT is given, the random real the
     returned procedure generates will be quantized by the given UNIT,
     where 0 < UNIT < 1.


File: gauche-refe.info,  Node: Localization,  Next: A program argument processor,  Prev: Sources of random bits,  Up: Library modules - SRFIs

10.13 `srfi-29' - Localization
==============================

 -- Module: srfi-29
     This module implements the message localization mechanism defined
     in SRFI-29.

     In fact, this module consists of two submodules, `srfi-29.bundle'
     and `srfi-29.format'.  The module `srfi-29' extends both
     submodules.  It is because srfi-29's definition of the `format'
     procedure is incompatible to Gauche's native `format' (thus Common
     Lisp's `format') in the handling of `~@*' directive.

     So I splitted the module into two, `srfi-29.format' which contains
     srfi-29's `format', and `srfi-29.bundle' which contains the rest
     ("bundle" API).  If a program wishes a complete compatibility of
     srfi-29, use `srfi-29' module, which overrides Gauche's native
     `format'.   If a program just wants srfi-29's "bundle" API, but
     wants to keep Gauche's `format', use `srfi-29.bundle'.

     A localization feature is also provided by `text.gettext' module
     (*Note Localized messages::), which is a preferable way of message
     localization in Gauche.  This module is provided mainly for
     porting code that uses srfi-29 features.

Bundle specifier
----------------

A _bundle specifier_ is an arbitrary list of symbols, but typically it
takes the form like:
     `(PACKAGE LANGUAGE COUNTRY DETAILS ...)'
   Where PACKAGE specifies the software package, LANGUAGE and COUNTRY
specifies language and country code, and DETAILS gives other
informations like encoding.

   The values for the default bundle specifier can be obtained by the
following parameters.

 -- Parameter: current-language
 -- Parameter: current-country
 -- Parameter: current-locale-details
     [SRFI-29] The `current-language' and `current-country' parameters
     keep the ISO 639-1 language code and ISO 3166-1 country code
     respectively, both as symbols.  The `current-locale-details' keeps
     a list of auxiliary local informations, such as encodings.

     These parameters are initialized if `LANG' environment variable is
     set in the form of `lang_country.encoding' format.  For example,
     if the `LANG' setting is `ja_JP.eucJP', those parameters are `ja',
     `jp', and `(eucjp)', respectively.   If `LANG' is `C' or undefined,
     the default values are `en', `us', and `()', respectively.

Bundle preparation
------------------

 -- Function: declare-bundle! bundle-specifier association-list
     [SRFI-29] Put the association list of template key (symbol) and
     the locale-specific message (string) into the bundle database,
     with BUNDLE-SPECIFIER as the key.

   Gauche currently supports only in-memory bundle database.  That is,
you have to call `declare-bundle!' within the application in order to
lookup the localized messages.

 -- Function: save-bundle! bundle-specifier
 -- Function: load-bundle! bundle-specifier
     [SRFI-29] Since Gauche doesn't support persistent bundle database
     yet, these procedures does nothing and returns `#f'.  (It is still
     conforming behavior of srfi-29).

Retrieving localized message
----------------------------

 -- Function: localized-template package-name message-template-name
     [SRFI-29] Retrieves localized message, associated with a symbol
     MESSAGE-TEMPLATE-NAME in the package PACKAGE-NAME.

Extended format procedure
-------------------------

 -- Function: format format-string args
     [SRFI-29] SRFI-29 extends SRFI-28's `format' procedure spec (which
     supports `~a', `~s', `~%' and `~~' directives), in order to
     support argument repositioning.

     A directive `~N@*', where N is an integer or can be omitted,
     causes the next directive to retrieve a value from N-th optional
     argument.  The referenced value isn't consumed, and won't affect
     the processing of subsequent directives.

     Although SRFI-28 spec is compatible to Gauche's native `format'
     (*Note Output::), this SRFI-29 extention isn't.  Specifically, the
     `~N@*' directive of Gauche's `format' changes the argument pointer
     to points N-th optional argument, thus it affects all the
     subsequent arugments.

     Because of this incompatibility, this function is defined in a
     separate module, `srfi-29.format'.  If you use `srfi-29', which
     extends `srfi-29.bundle' and `srfi-29.format', the `format'
     procedure will be overriden by srfi-29's `format' in your module.
     If you want to keep Gauche's native `format', use `srfi-29.bundle'
     only.


File: gauche-refe.info,  Node: A program argument processor,  Next: Eager comprehensions,  Prev: Localization,  Up: Library modules - SRFIs

10.14 `srfi-37' - args-fold: a program argument processor
=========================================================

 -- Module: srfi-37
     This module implements `args-fold', yet another procedure to
     process command-line arguments, defined in SRFI-37 (*Note
     [SRFI-37]: srfi-37.).

     Unlike `gauche.parseopt' (*Note Parsing command-line options::),
     `args-fold' provides functional interface, i.e.  the user's states
     are explicitly passed via parser's argument and return values, and
     also follows POSIX and GNU getopt guidelines, including long
     options.

 -- Function: args-fold args options unrecognized-proc operand-proc
          &rest seeds
     Processes program options ARGS from left to right, according to
     given option specification OPTIONS, and two procedures
     UNRECOGNIZED-PROC and OPERAND-PROC.

     OPTIONS is a list of option objects, explained below.  Each option
     object keeps the name(s) of the option, a flag to specify whether
     the option takes an argument or not, and a procedure to process
     that option (we'll call it _option procedure_).

     `Args-fold' recognizes both single-character options (short
     options) and long options.  A short option must begin with single
     hyphen (e.g. `-a'), while long option must begin with double
     hyphens (e.g. `--help').   Short options can be concatenated, e.g.
     `-abc' or `-a -b -c'.  Both a short option and a long option can
     take required or optional arguments.   Required short-option
     argument can appear with or without space after the option, e.g.
     `-afoo' or `-a foo'.  Long-option argument can appear after
     character '`='' or space, e.g. `--long=foo' or `--long foo'.

     When `args-fold' encounters a command-line argument that cannot be
     an option argument, and doesn't begin with hyphen, the argument is
     treated as an _operand_.   `Args-fold' allows operands and options
     to be interleaved.  However, if `args-fold' encounters '`--'', the
     rest of arguments are treated as operands, regardless of beginning
     with hyphen or not.

     When the given option matches one of option object in OPTIONS, the
     option procedure is called as follows:

          (OPTION-PROC OPTION NAME ARG SEED ...)

     where OPTION is the matched option object, NAME is the string
     actually used to specify the option, ARG is the option argument
     (or `#f' if there's none), and SEED ... is the user's state
     information.  OPTION-PROC must return as many arguments as SEEDs.

     When `args-fold' encounters an option that doesn't match any of
     the option objects, it creates a new option object for the option
     and calls UNRECOGNIZED-PROC with the same arguments as OPTION-PROC.

     When `args-fold' finds an operand, OPERAND-PROC is called as
     follows:

          (OPERAND-PROC OPERAND SEED ...)

     OPERAND-PROC must return as many arguments as SEEDs.

     The caller's state should be explicitly passed around seed
     arguments and return values.  The initial seed values are SEEDs
     given to `args-fold'.  The values returned from option procedure,
     UNRECOGNIZED-PROC and OPERAND-PROC are used as the seed arguments
     of next invocation of those procedures.  The values returned from
     the last call to the procedures are returned from `args-fold'.

 -- Function: option names require-arg? optional-arg? processor
     Creates an option object with the passed properties.

     NAMES is a list of characters and/or strings.  A character is used
     for a short option, and a string is used for a long option.

     Two flags, REQUIRE-ARG? and OPTIONAL-ARG?  indicates whether the
     option should take an option argument, or may take an option
     argument.

     PROCESSOR is the option processor procedure.

     Note that, if an option argument is passed using '`='' character,
     it is passed to the option procedure even if the option has `#f'
     in both REQUIRE-ARG?  and OPTIONAL-ARG?.  It is up to the option
     procedure to deal with the argument.

     It should also be noted that the optional option argument for a
     short option is only recognized if it is given without whitespace
     after the short option.  That is, if a short option '`d'' is
     marked to take optional option argument, then '`-dfoo'' is
     interpreted as '`-d'' with argument '`foo'', but '`-d foo'' is
     interpreted as '`-d'' without argument and an operand `foo'.  If
     '`d'' is marked to take required option argument, however, both
     are interpreted as '`-d'' with argument '`foo''.

 -- Function: option? obj
     Returns `#t' if OBJ is an option object, `#f' otherwise.

 -- Function: option-names option
 -- Function: option-required-arg? option
 -- Function: option-optional-arg? option
 -- Function: option-processor
     Returns the properties of an option object OPTION.

   A simple example:

     (use srfi-37)

     (define options
      (list (option '(#\d "debug") #f #t
                    (lambda (option name arg debug batch paths files)
                      (values (or arg "2") batch paths files)))
            (option '(#\b "batch") #f #f
                    (lambda (option name arg debug batch paths files)
                      (values debug #t paths files)))
            (option '(#\I "include") #t #f
                    (lambda (option name arg debug batch paths files)
                      (values debug batch (cons arg paths) files)))))

     (define (main args)
       (receive (debug-level batch-mode include-paths files)
         (args-fold (cdr args)
                    options
                    (lambda (option name arg . seeds)         ; unrecognized
                      (error "Unrecognized option:" name))
                    (lambda (operand debug batch paths files) ; operand
                      (values debug batch paths (cons operand files)))
                    0      ; default value of debug level
                    #f     ; default value of batch mode
                    '()    ; initial value of include paths
                    '()    ; initial value of files
                    )
          (print "debug level = " debug-level)
          (print "batch mode = " batch-mode)
          (print "include paths = " (reverse include-paths))
          (print "files = " (reverse files))
          0))


File: gauche-refe.info,  Node: Eager comprehensions,  Next: Requiring extensions,  Prev: A program argument processor,  Up: Library modules - SRFIs

10.15 `srfi-42' - Eager comprehensions
======================================

 -- Module: srfi-42
     This module provides a generic comprehension mechanism, which some
     other languages (e.g. Haskell and Python) provides as a built-in
     mechanism.  It provides rich set of operators so it can be used as
     not only a list generator but a generic loop construct (actually,
     some may say it is as powerful/evil as Common Lisp's _loop_ macro).

     It is also runs eagerly, that is, if it generates a list, it
     creates the entire list when evaluated, instead of generate the
     elements _on demand_.  Thus it can't represent an infinite
     sequence, which Haskell's comprehension naturally can.  In Scheme,
     you can use streams built on top of delayed evaluation for such
     purpose.

Eager comprehension examples
----------------------------

Let's begin with some examples.

   Generate a list of squares for the first five integers:
     (list-ec (: i 5) (* i i)) => (0 1 4 9 16)

   Generate set of pair of numbers `(x y)', where `x' is between 2
(inclusive) and 5 (exclusive), and `y' is between 1 (inclusive) and x
(exclusive).
     (list-ec (: x 2 5) (: y 1 x) (list x y))
       => ((2 1) (3 1) (3 2) (4 1) (4 2) (4 3))

   The above two examples can be written in Haskell as the followings:
     [ i*i   | i <- [0..4] ]
     [ (x,y) | x <- [2..4], y <- [1..x-1] ]
   Note the differences: (1) In Haskell, the body expression to yield
the elements comes first, followed by qualifiers (selectors).  In
srfi-42, the body expression comes last.  (2) In srfi-42, range
operator's lower bound is inclusive but its upper bound is exclusive.

   List a set of numbers `(a b c d)', where `a^3+b^3 = c^3+d^3':
     (define (taxi-number n)
       (list-ec (: a 1 n)
                (: b (+ a 1) n)
                (: c (+ a 1) b)
                (: d (+ c 1) b)
                (if (= (+ (expt a 3) (expt b 3))
                       (+ (expt c 3) (expt d 3))))
                (list a b c d)))

   You can generate not only a list, but other sequences:
     (vector-ec (: i 5) i) => #(0 1 2 3 4)
     (string-ec (: i 5) (integer->char (+ i 65))) => "ABCDE"

   Or apply folding operations:
     (sum-ec (: i 1 10) i)
       => 450    ;; sum of integers from 1 below 100.
     (product-ec (: i 1 10) i)
       => 362880 ;; ... and product of them.

Comprehension macros
--------------------

Each comprehension takes the following form.
     (COMPREHENSION-MACRO QUALIFIER ... BODY)

   Evaluates BODY repeatedly as specified by QUALIFIERs.  Depending on
the type of comprehension, the results of BODY may be either collected
to create an aggregate (list, vector, string, ...), folded by some
operator (sum, product, min, max, ...), or simply discarded.

   A few comprehensions takes extra values before QUALIFIERS or after
BODIES.

 -- Macro: do-ec qualifier ... body
     [SRFI-42]

 -- Macro: list-ec qualifier ... body
     [SRFI-42]

 -- Macro: append-ec qualifier ... body
     [SRFI-42]

 -- Macro: string-ec qualifier ... body
 -- Macro: string-append-ec qualifier ... body
     [SRFI-42]

 -- Macro: vector-ec qualifier ... body
     [SRFI-42]

 -- Macro: vector-of-length-ec qualifier ... body
     [SRFI-42]

 -- Macro: sum-ec qualifier ... body
 -- Macro: product-ec qualifier ... body
 -- Macro: min-ec qualifier ... body
 -- Macro: max-ec qualifier ... body
     [SRFI-42]

 -- Macro: any?-ec qualifier ... test
 -- Macro: every?-ec qualifier ... test
     [SRFI-42]

 -- Macro: first-ec default qualifier ... body
 -- Macro: last-ec default qualifier ... body
     [SRFI-42]

 -- Macro: fold-ec x0 qualifier ... expr f2
 -- Macro: fold3-ec x0 qualifier ... expr f1 f2
     [SRFI-42]

Qualifiers
----------

Control qualifiers
..................

 -- EC Qualifier: if test

 -- EC Qualifier: not test
 -- EC Qualifier: and test
 -- EC Qualifier: or test

 -- EC Qualifier: begin test

 -- EC Qualifier: nested test

Generational qualifiers
.......................

 -- EC Qualifier: : vars arg1 args ...

 -- EC Qualifier: :list vars arg1 args ...
 -- EC Qualifier: :vector vars arg1 args ...
 -- EC Qualifier: :string vars arg1 args ...

 -- EC Qualifier: :integers vars

 -- EC Qualifier: :range vars stop
 -- EC Qualifier: :range vars start stop
 -- EC Qualifier: :range vars start stop step

 -- EC Qualifier: :real-range vars stop
 -- EC Qualifier: :real-range vars start stop
 -- EC Qualifier: :real-range vars start stop step

 -- EC Qualifier: :char-range vars min max

 -- EC Qualifier: :port vars port
 -- EC Qualifier: :port vars port read-proc

 -- EC Qualifier: :dispatched vars dispatch arg1 args ...

 -- EC Qualifier: :do (lb ...) ne1? (ls ...)
 -- EC Qualifier: :do (let (ob ...) oc ...) (lb ...) ne1? (let (ib ...)
          ic ...) ne2? (ls ...)

 -- EC Qualifier: :let vars expr

 -- EC Qualifier: :parallel generator ...

 -- EC Qualifier: :while generator expr

 -- EC Qualifier: :until generator expr


File: gauche-refe.info,  Node: Requiring extensions,  Prev: Eager comprehensions,  Up: Library modules - SRFIs

10.16 `srfi-55' - Requiring extensions
======================================

 -- Module: srfi-55
     This module defines `require-extension' macro, a yet another way
     to write portable scripts.  See *Note Feature conditional:: and
     *Note Feature-based program configuration language:: for other
     means of ensuring specific features.

     This module is autoloaded when you use `require-extension', so you
     don't need explicitly say `(use srfi-55)'; for portable scripts,
     you shouldn't.

 -- Macro: require-extension clause ...
     Make extension(s) specified by CLAUSEs available in the rest of
     the program.

     A CLAUSE takes the following form:
          (EXTENSION-ID EXTENSION-ARG ...)

     Currently, only `srfi' is supported as EXTENSION-ID, and its
     arguments are SRFI numbers.

     For example, the following form:
          (require-extension (srfi 1 13 14))

     Roughly correspons to Gauche's `use' forms:
          (use srfi-1)
          (use srfi-13)
          (use srfi-14)


File: gauche-refe.info,  Node: Library modules - Utilities,  Next: References,  Prev: Library modules - SRFIs,  Up: Top

11 Library modules - Utilities
******************************

* Menu:

* Packing Binary Data::         (binary.pack)
* Generic DBM interface::       (dbm)
* File-system dbm::             (dbm.fsdbm)
* GDBM interface::              (dbm.gdbm)
* NDBM interface::              (dbm.ndbm)
* Original DBM interface::      (dbm.odbm)
* Filtering file content::      (file.filter)
* Filesystem utilities::        (file.util)
* Mathematic constants::        (math.const)
* Mersenne-Twister random number generator::  (math.mt-random)
* RFC822 message parsing::      (rfc.822)
* Base64 encoding/decoding::    (rfc.base64)
* HTTP cookie handling::        (rfc.cookie)
* HMAC keyed-hashing::          (rfc.hmac)
* HTTP::                        (rfc.http)
* MD5 message digest::          (rfc.md5)
* MIME message handling::       (rfc.mime)
* Quoted-printable encoding/decoding::  (rfc.quoted-printable)
* SHA1 message digest::         (rfc.sha1)
* URI parsing and construction::  (rfc.uri)
* SLIB::                        (slib)
* Functional XML parser::       (sxml.ssax)
* SXML Query Language::         (sxml.sxpath)
* manipulationg SXML structure::  (sxml.tools)
* CSV tables::                  (text.csv)
* Calculate difference of text streams::  (text.diff)
* Localized messages::          (text.gettext)
* Simple HTML document construction::  (text.html-lite)
* Parsing input stream::        (text.parse)
* Transliterate characters::    (text.tr)
* Lazy text construction::      (text.tree)
* Combination library::         (util.combinations)
* Message digester framework::  (util.digest)
* Determine isomorphism::       (util.isomorph)
* The longest common subsequence::  (util.lcs)
* Additional list library::     (util.list)
* Pattern matching::            (util.match)
* Queue::                       (util.queue)
* SLIB-compatible record type::  (util.record)
* Topological sort::            (util.toposort)
* CGI Utility::                 (www.cgi)
* CGI testing::                 (www.cgi-test)


File: gauche-refe.info,  Node: Packing Binary Data,  Next: Generic DBM interface,  Prev: Library modules - Utilities,  Up: Library modules - Utilities

11.1 `binary.pack' - Packing Binary Data
========================================

 -- Module: binary.pack
     This module provides an interface for packing and unpacking
     (writing and reading) binary data with templates.  The
     functionality was inspired largely by the Perl pack/unpack
     functions, with comparison of similar features from other
     languages, however an effort was made to make it more general and
     more efficient, to be usable for database-like processing.  To
     that end, the most notable differences are that any packable value
     is unpackable (and vice versa), and the default behavior is to
     pack and unpack using port I/O, so you can seek in a large file
     and unpack from it.  Also, templates may be stored as dispatch
     closures to pack, unpack or even skip over values without
     re-parsing the template.


 -- Function: pack template list &keyword :output :to-string?
     Writes the values in LIST to the current output port, according to
     the format specified by the string TEMPLATE.  The template string
     is a series of single character codes, optionally followed by a
     numeric count (which defaults to 1).  The format characters can
     generally be divided into string types, which interpret the count
     as a string byte size, and object types, which treat the count as
     a repetition indicator.  The count may be specified as the
     character `*', which means to use the full size of the string for
     string types, and use all remaining values for object types.
     Counts may also be specified as a template enclosed in brackets,
     which means the count is the byte size of the enclosed template.
     For example, `x[L]' skips a long.  The special format character
     `/' may be used to indicate a structure where the packed data
     contains a dynamic count followed by the value itself.  The
     template is written as `<count-item>/<value-item>', where
     `<count-item>' is any template character to be interpreted as a
     numeric count, and `<value-item>' is any other template character
     to use this count.  If a normal count is given after
     `<value-item>' it is ignored.  The format character `@' may be
     used with a count to pad to an absolute position since the start
     of the template.  Sub-templates may be grouped inside parentheses.
     If angle-brackets are used, then they also behave as group
     operators but recursively operate on nested lists.  The string
     types:
    `a'
          An arbitrary incomplete string, null padded.

    `A'
          A text string, space padded.

    `Z'
          A null terminated (ASCIZ) string, null padded.

    `b'
          A bit string (ascending bit order inside each byte).

    `B'
          A bit string (decending bit order inside each byte).

    `h'
          A hex string (low nybble first).

    `H'
          A hex string (high nybble first).

     The object types:

    `c'
          A single char value.

    `C'
          An unsigned char value, single-byte only.

    `s'
          A signed short (16 bit) value.

    `S'
          An unsigned short (16 bit) value.

    `i'
          A signed integer (>= 32 bit) value.

    `I'
          An unsigned integer (>= 32 bit) value.

    `l'
          A signed long (32 bit) value.

    `L'
          An unsigned long (32 bit) value.

    `n'
          An unsigned short (16 bit) in "network" (big-endian) order.

    `N'
          An unsigned long (32 bit) in "network" (big-endian) order.

    `v'
          An unsigned short (16 bit) in "VAX" (little-endian) order.

    `V'
          An unsigned long (32 bit) in "VAX" (little-endian) order.

    `q'
          A signed quad (64 bit) value.

    `Q'
          An unsigned quad (64 bit) value.

    `f'
          A single-precision float in the native format.

    `d'
          A double-precision float in the native format.

    `w'
          A BER compressed integer.  An unsigned integer in base 128,
          most significant digit first, where the high bit is set on
          all but the final (least significant) byte.  Thus any size
          integer can be encoded, but the encoding is efficient and
          small integers don't take up any more space than they would
          in normal char/short/int encodings.

    `x'
          A null byte.

    `o'
          An sexp, handled with `read' and `write'.


     If the optional keyword :OUTPUT is given that port is used instead
     of the current output port.  If :TO-STRING? is given and true,
     then pack accumulates and returns the output as a string.

     Note that the returned string may be an incomplete string if the
     packed string contains a byte sequence invalid as a character
     sequence.

          (pack "CCCC" '(65 66 67 68) :to-string? #t)
           => "ABCD"

          (pack "C/a*" '("hello") :to-string? #t)
           => "\x05hello"

 -- Function: unpack template &keyword :input :from-string
     The complement of pack, unpack reads values from the current input
     port assuming they've been packed according to the string template
     and returns the values as a list.  unpack accepts the same format
     strings as pack.  Further, the following tautology holds:

          (equal? x (unpack fmt :from-string (pack fmt x :to-string? #t)))

     for any list X and format string FMT.  The only exceptions to this
     are when the template includes a `*' and when the `o' template is
     used, since Scheme numeric literals cannot be reliably delimited
     (though future versions of `pack' may circumvent this by
     registering a new read syntax).

     If the optional keyword :INPUT is given that port is used instead
     of the current input port.  If :FROM-STRING is given, then pack
     reads input from that string.

          (unpack "CCCC" :from-string "ABCD")
           => '(65 66 67 68)

          (unpack "C/a*" :from-string "\x05hello")
           => '("hello")

     _Note:_ in the current version, `@' in `unpack' template has a bug
     and does not work as supposed.  It will be fixed in the future
     verson.

 -- Function: unpack-skip template &keyword :input
     unpack-skip is the same as unpack except it does not return the
     values.  In some cases, particulary with fixed-size templates, this
     can be much more efficient when you just want to skip over a value.

 -- Function: make-packer template
     The low-level interface.  This function returns a disptach closure
     that can be used to pack, unpack and skip over the same cached
     template.  The dispatch closure accepts symbol methods as follows:

    `'pack list'
          pack the items in list to the current output port.

    `'unpack'
          unpack items from the current input port.

    `'skip'
          skip items from the current input port.

    `'packer'
          return the cached 'pack closure

    `'unpacker'
          return the cached 'unpack closure.

    `'skipper'
          return the cached 'skip closure.

    `'length'
          return the known fixed length of the template.

    `'variable-length?'
          return #t if the template has variable length elements.


File: gauche-refe.info,  Node: Generic DBM interface,  Next: File-system dbm,  Prev: Packing Binary Data,  Up: Library modules - Utilities

11.2 `dbm' - Generic DBM interface
==================================

 -- Module: dbm
     DBM-like libraries provides an easy way to store values to a file,
     indexed by keys.  You can think it as a persistent associative
     memory.

     This modules defines `<dbm>' abstract class, which has a common
     interface to use various DBM-type database packages.  As far as
     you operate on the already opened database, importing `dbm' module
     is enough.

     To create or open a database, you need a concrete implementation
     of the database.  Gauche currently has the following
     impelentations.  Each module defines its own low-level accessing
     functions as well as the common interface.  Note that your system
     may not have one or more of those DBM libraries; Gauche defines
     only what the system provides.

    `dbm.fsdbm'
          file-system dbm (*Note File-system dbm::).

    `dbm.gdbm'
          GDBM library (*Note GDBM interface::).

    `dbm.ndbm'
          NDBM library (*Note NDBM interface::).

    `dbm.odbm'
          DBM library  (*Note Original DBM interface::).

The following code shows a typical usage of the database.

     (use dbm)         ; dbm abstract interface
     (use dbm.gdbm)    ; dbm concrete interface

     ; open the database
     (define *db* (dbm-open <gdbm> :path "mydb" :rw-mode :write))

     ; put the value to the database
     (dbm-put! *db* "key1" "value1")

     ; get the value from the database
     (define val (dbm-get *db* "key1"))

     ; iterate over the database
     (dbm-for-each *db* (lambda (key val) (foo key val)))

     ; close the database
     (dbm-close *db*)

* Menu:

* Opening and closing a dbm database::
* Accessing a dbm database::
* Iterating on a database::
* Managing dbm database instance::


File: gauche-refe.info,  Node: Opening and closing a dbm database,  Next: Accessing a dbm database,  Prev: Generic DBM interface,  Up: Generic DBM interface

11.2.1 Opening and closing a dbm database
-----------------------------------------

 -- Class: <dbm>
     An abstract class for dbm-style database.  Defindes the common
     database operations.   This class has the following instance slots.
     They must be set before the database is actually opened by
     `dbm-open'.

     The concrete class may add more slots for finer control on the
     database, such as locking.

      -- Instance Variable of <dbm>: path
          Pathname of the dbm database.  Some dbm implementation may
          append suffixes to this.

      -- Instance Variable of <dbm>: rw-mode
          Specifies read/write mode.  Can be either one of the
          following keywords:
         `:read'
               The database will be opened in read-only mode.  The
               database file must exist when `dbm-open' is called.
               This is the default value.

         `:write'
               The database will be opened in Read-write mode.  If the
               database file does not exist, `dbm-open' creates one.

         `:create'
               The database will be created and opened in Read-write
               mode.  If the database file exists, `dbm-open' truncates
               it.

      -- Instance Variable of <dbm>: file-mode
          Specifies the file permissions (as `sys-chmod') to create the
          database.  The default value is `#o664'.

      -- Instance Variable of <dbm>: key-convert
      -- Instance Variable of <dbm>: value-convert
          By default, you can use only strings for both key and values.
          With this option, however, you can specify how to convert
          other Scheme values to/from string to be stored in the
          database.   The possible values are the followings:
         `#f'
               The default value.  Keys (values) are not converted.
               They must be a string.

         `#t'
               Keys (values) are converted to its string
               representation, using `write', to store in the database,
               and converted back to Scheme values, using `read', to
               retrieve from the database.  The data must have an
               external representation that can be read back.  (But it
               is not checked when the data is written; you'll get an
               error when you read the data).  The key comparison is
               done in the string level, so the external representation
               of the same key must match.

         a list of two procedures
               Both procedure must take a single argument.  The first
               procedure must receive a Scheme object and returns a
               string.  It is used to convert the keys (values) to
               store in the database.  The second procedure must
               receive a string and returns a Scheme object.  It is
               used to convert the stored data in the database to a
               Scheme object.  The key comparison is done in the string
               level, so the external representation of the same key
               must match.

 -- Metaclass: <dbm-meta>
     A metaclass of `<dbm>' and its subclasses.

 -- Method: dbm-open (dbm <dbm>)
     Opens a dbm database.  DBM must be an instance of one of the
     concrete classes that derived from the `<dbm>' class, and its
     slots must be set appropriately.   On success, it returns the DBM
     itself.  On failure, it signals an error.

 -- Method: dbm-open (dbm-class <dbm-meta>) options ...
     A convenient method that creates dbm instance and opens it.  It is
     defined as follows.
          (define-method dbm-open ((class <class>) . initargs)
            (dbm-open (apply make class initargs)))

   Database file is closed when it is garbage collected.  However, to
ensure the modification is properly synchornized, you should close the
database explicitly.

 -- Method: dbm-close (dbm `<dbm>')
     Closes a database DBM.  Once the database is closed, any operation
     to access the database content raises an error.

 -- Method: dbm-closed? (dbm `<dbm>')
     Returns true if a database DBM is already closed, false otherwise.


File: gauche-refe.info,  Node: Accessing a dbm database,  Next: Iterating on a database,  Prev: Opening and closing a dbm database,  Up: Generic DBM interface

11.2.2 Accessing a dbm database
-------------------------------

Once a database is opened, you can use the following methods to access
individual key/value pairs.

 -- Method: dbm-put! (dbm `<dbm>') key value
     Put a VALUE with KEY.

 -- Method: dbm-get (dbm `<dbm>') key &optional default
     Get a value associated with KEY.  If no value exists for KEY and
     DEFAULT is specified, it is returned.  If no value exists for KEY
     and DEFAULT is not specified, an error is signalled.

 -- Method: dbm-exists? (dbm `<dbm>') key
     Return true if a value exists for KEY, false otherwise.

 -- Method: dbm-delete! (dbm `<dbm>') key
     Delete a value associated with KEY.


File: gauche-refe.info,  Node: Iterating on a database,  Next: Managing dbm database instance,  Prev: Accessing a dbm database,  Up: Generic DBM interface

11.2.3 Iterating on a dbm database
----------------------------------

To walk over the entire database, following methos are provided.

 -- Method: dbm-fold (dbm `<dbm>') procedure knil
     The basic iterator.  For each key/value pair, PROCEDURE is called
     as `(PROCEDURE KEY VALUE R)', where R is KNIL for the fist call of
     PROCEDURE, and the return value of the previous call for
     subsequent calls.  Returns the result of the last call of
     PROCEDURE.  If no data is in the database, KNIL is returned.

     The following method returns the sum of all the integer values.
          (dbm-fold dbm (lambda (k v r) (if (integer? v) (+ v r) r)) 0)

 -- Method: dbm-for-each (dbm `<dbm>') procedure
     For each key/value pair in the database DBM, PROCEDURE is called.
     Two arguments are passed to PROCEDURE--a key and a value.   The
     result of PROCEDURE is discarded.

 -- Method: dbm-map (dbm `<dbm>') procedure
     For each key/value pair in the database DBM, PROCEDURE is called.
     Two arguments are passed to PROCEDURE--a key and a value.   The
     result of PROCEDURE is accumulated to a list which is returned as
     a result of `dbm-map'.


File: gauche-refe.info,  Node: Managing dbm database instance,  Prev: Iterating on a database,  Up: Generic DBM interface

11.2.4 Managing dbm database instance
-------------------------------------

Each dbm implementation has its own way to store the database.  Legacy
dbm uses two files, whose names are generated by adding `.dir' and
`.pag' to the value of PATH slot.  `Fsdbm' creates a directory under
PATH.  If dbm database is backed up by some database server, PATH may
be used only as a key to the database in the server.  The following
methods hide such variations and provides a convenient way to manage a
database itself.   You have to pass a class that implements a concrete
dbm database to their first argument.

 -- Generic Function: dbm-db-exists? class name
     Returns `#t' if a database of class CLASS specified by NAME exists.

          ;; Returns #t if testdb.dir and testdb.pag exist
          (dbm-db-exists? <odbm> "testdb")

 -- Generic Function: dbm-db-remove class name
     Removes an entire database of class CLASS specified by NAME.

 -- Generic Function: dbm-db-copy class from to
     Copy a database of class CLASS specified by FROM to TO.

          (dbm-db-copy <gdbm> "testdb.dbm" "backup.dbm")

 -- Generic Function: dbm-db-move class from to
     Moves or renames a database of class CLASS specified by FROM to TO.


File: gauche-refe.info,  Node: File-system dbm,  Next: GDBM interface,  Prev: Generic DBM interface,  Up: Library modules - Utilities

11.3 `dbm.fsdbm' - File-system dbm
==================================

 -- Module: dbm.fsdbm
     Implements fsdbm.  Extends `dbm'.

 -- Class: <fsdbm>
     `Fsdbm' is a dbm implementation that directly uses the filesystem.
     Basically, it uses file names for keys, and file content for
     values.   Unlike other dbm implementations, this doesn't depend on
     external libraries--it is pure Scheme implementation--so it is
     always available, while other dbm implementations may not.
     Obviously, it is not suitable for the database that has lots of
     entries, or has entries deleted and added very frequently.  The
     advantage is when the number of entries are relatively small, and
     the values are relatively large while keys are small.  The
     database name given to `<fsdbm>' instance is used as a directory
     name that stores the data.  The data files are stored in
     subdirectories under PATH of `fsdbm' instance, hashed by the key.
     Non-alphanumeric characters in the key is encoded like `_3a' for
     '`:'', for example.  If a key is too long to be a file name, it is
     chopped to chunks, and each chunk but the last one is used as a
     directory name.  Note that a long key name may still cause a
     problem, for example, some of old 'tar' command can't deal with
     pathnames (not each pathname components, but the entire pathname)
     longer than 256 characters.

   Fsdbm implements all of the dbm protocol (see *Note Generic DBM
interface::).  It doesn't have any fsdbm-specific procedures.


File: gauche-refe.info,  Node: GDBM interface,  Next: NDBM interface,  Prev: File-system dbm,  Up: Library modules - Utilities

11.4 `dbm.gdbm' - GDBM interface
================================

 -- Module: dbm.gdbm
     Provides interface to the gdbm library.  Extends `dbm'.

 -- Class: <gdbm>
     Inherits `<dbm>'.  Provides an implementation for GDBM library.
     This module is only installed when your system already has GDBM
     (1.8.0 is preferred, but works with older 1.7.x with some
     limitations).

      -- Instance Variable of <gdbm>: sync

      -- Instance Variable of <gdbm>: nolock

      -- Instance Variable of <gdbm>: bsize

   Besides the unified DBM interface (*Note Generic DBM interface::),
this module provides the following low-level functions that provides
direct access to the gdbm API.  See gdbm manual for details of these
APIs.

 -- Function: gdbm-open path &optional size rwmode fmode error-callback
      -- Variable: GDBM_READER

      -- Variable: GDBM_WRITER

      -- Variable: GDBM_WRCREAT

      -- Variable: GDBM_NEWDB

      -- Variable: GDBM_FAST

      -- Variable: GDBM_SYNC

      -- Variable: GDBM_NOLOCK

 -- Function: gdbm-close gdbm-object

 -- Function: gdbm-closed? gdbm-object

 -- Function: gdbm-store key value &optional flag
      -- Variable: GDBM_INSERT

      -- Variable: GDBM_REPLACE


 -- Function: gdbm-fetch gdbm-object key

 -- Function: gdbm-delete gdbm-object key

 -- Function: gdbm-firstkey gdbm-object

 -- Function: gdbm-nextkey gdbm-object key

 -- Function: gdbm-reorganize gdbm-object

 -- Function: gdbm-sync gdbm-object

 -- Function: gdbm-exists gdbm-object key

 -- Function: gdbm-strerror errno

 -- Function: gdbm-setopt gdbm-object option value
      -- Variable: GDBM_CACHESIZE

      -- Variable: GDBM_FASTMODE

      -- Variable: GDBM_SYNCMODE

      -- Variable: GDBM_CENTFREE

      -- Variable: GDBM_COALESCEBLKS

 -- Function: gdbm-version

 -- Function: gdbm-errno


File: gauche-refe.info,  Node: NDBM interface,  Next: Original DBM interface,  Prev: GDBM interface,  Up: Library modules - Utilities

11.5 `dbm.ndbm' - NDBM interface
================================

 -- Module: dbm.ndbm
     Provides interface to the 'new' dbm library, a.k.a. ndbm.  Extends
     `dbm'.

 -- Class: <ndbm>
     Inherits `<dbm>'.  Provides an implementation for NDBM library.
     This module is only installed when your system already has NDBM.

   Besides the unified DBM interface (*Note Generic DBM interface::),
this module provides the following low-level functions that provides
direct access to the ndbm API.  See ndbm manual for details of these
APIs.

 -- Function: ndbm-open path flags mode

 -- Function: ndbm-close ndbm-object

 -- Function: ndbm-closed? ndbm-object

 -- Function: ndbm-store ndbm-object key content &optional flag

 -- Function: ndbm-fetch ndbm-object key

 -- Function: ndbm-delete ndbm-object key

 -- Function: ndbm-firstkey ndbm-object

 -- Function: ndbm-nextkey ndbm-object

 -- Function: ndbm-error ndbm-object

 -- Function: ndbm-clear-error ndbm-object


File: gauche-refe.info,  Node: Original DBM interface,  Next: Filtering file content,  Prev: NDBM interface,  Up: Library modules - Utilities

11.6 `dbm.odbm' - Original DBM interface
========================================

 -- Module: dbm.odbm
     Provides interface to the legacy dbm library.  Extends `dbm'.

 -- Class: <odbm>
     Inherits `<dbm>'.  Provides an implementation for legacy DBM
     library.  This module is only installed when your system already
     has DBM.

     The biggest limitation of the legacy DBM is that you can only open
     one database at a time.  You can create a multiple `<odbm>'
     instances, but you can open at most one of it at a time, or you'll
     get an error.

   Besides the unified DBM interface (*Note Generic DBM interface::),
this module provides the following low-level functions that provides
direct access to the dbm API.  See dbm manual for details of these APIs.

 -- Function: odbm-init path

 -- Function: odbm-close

 -- Function: odbm-store key value

 -- Function: odbm-fetch key

 -- Function: odbm-delete key

 -- Function: odbm-firstkey

 -- Function: odbm-nextkey key


File: gauche-refe.info,  Node: Filtering file content,  Next: Filesystem utilities,  Prev: Original DBM interface,  Up: Library modules - Utilities

11.7 `file.filter' - Filtering file content
===========================================

 -- Module: file.filter
     This module provides utilities for a common pattern in filter-type
     commands, that is, to take an input, to process the content, and
     to write the result.   The common occurring pattern is:

        * Input may be a specified file, or an input port (the current
          input port by default).

        * Output may be a specified file, or an output port (the
          current output port by default).

        * Output may be a temporary file, which will be renamed upon
          completion of the processing.

        * Output file may be removed when an error occurs in the
          processing.

 -- Function: file-filter proc &keyword input output temporary-file
          keep-output?
     Calls PROC with two arguments, an input port and an output port.
     Returns the result(s) of PROC.  The input port and output port are
     chosen depending on the keyword arguments.

    `input'
          The argument must be either an input port or a string that
          specifies a file name.  If it's an input port, it is passed
          to PROC as is.  If it's a string, the named file is opened
          for input and the resulting port is passed to PROC, and the
          port is closed when PROC returns.  If this argument is
          omitted, the current input port is passed.

    `output'
          The argument must be either an output port or a string that
          specifies a file name.  If it's an output port, it is passed
          to PROC as is.  If it's a string, the named file is opened
          for output (unless TEMPORARY-FILE is given, in that case a
          temporary file is opened instead), and the resulting port is
          passed to PROC.  This port is closed when PROC returns.  If
          this argument is omitted, the current output port is passed.

    `temporary-file'
          If a string file name is given to this argument, the named
          file is opened for output during the processing, instead of
          the file name as OUTPUT.   The output port PROC receives is
          connected to this file.  When PROC returns normally, the file
          is renamed to the name given to OUTPUT keyword argument.

          If the given file name begins with characters except `"/"',
          `"./"' or `"../"', the directory of the file name given to
          OUTPUT argument is attached before it.  Furthermore, a unique
          name is attached to the temporary file name (the temporary
          file is opened by `sys-mkstemp'.)

          This argument is ignored when OUTPUT argument is not a string
          file name.

    `keep-output?'
          If a true value is given, the output is not deleted even when
          PROC signals an error.  By default, the output (or the
          temporary file when TEMPORARY-FILE is given) will be deleted
          on error.


File: gauche-refe.info,  Node: Filesystem utilities,  Next: Mathematic constants,  Prev: Filtering file content,  Up: Library modules - Utilities

11.8 `file.util' - Filesystem utilities
=======================================

 -- Module: file.util
     Provides convenient utility functions handling files and
     directories.  Those functions are built on top of the primitive
     system procedures described in *Note Filesystems::.

     Many procedures in this module takes a keyword argument
     FOLLOW-LINK?, which specifies the behavior when the procedure sees
     a symbolic link.  If true value is given to FOLLOW-LINK? (which is
     the default), the procedure operates on the file referenced by the
     link; if false is given, it operates on the link itself.

   Note on the naming convention: Some Scheme implementations "create"
new directories and files, while the others "make" them.  Some
implementations "delete" them, while the others "remove" them.  It
seems that both conventions are equally popular.  So Gauche provides
_both_.

* Menu:

* Directory utilities::
* Pathname utilities::
* File attribute utilities::
* File operations::


File: gauche-refe.info,  Node: Directory utilities,  Next: Pathname utilities,  Prev: Filesystem utilities,  Up: Filesystem utilities

11.8.1 Directory utilities
--------------------------

 -- Function: current-directory &optional new-directory
     When called with no argument, this returns the pathname of the
     current working directory.  When called with a string argument
     NEW-DIRECTORY, this sets the current working directory of the
     process to it.  If the process can't change directory to
     NEW-DIRECTORY, an error is signalled.

     This function is in ChezScheme, MzScheme and some other Scheme
     implementations.

 -- Function: home-directory &optional user
     Returns the home directory of the given USER, which may be a
     string user name or an integer user id.  If USER is omitted, the
     current user is assumed.  If the given user cannot be found, or
     the home directory of the user cannot be determined, `#f' is
     returned.

 -- Function: temporary-directory
     Returns the name of the directory that can be used to create a
     temporary files.   Currently it always returns `/tmp', but in
     future it will take platform or system specific settings into
     account.

 -- Function: directory-list path &keyword children? add-path? filter
          filter-add-path?
     Returns a list of entries in the directory PATH.  The result is
     sorted by dictionary order.

     By default, only the basename (the last component) of the entries
     returned.   If ADD-PATH? is given and true, PATH is appended to
     each entry.  If CHILDREN? is given and true, `"."' and `".."' are
     excluded from the result.

     If FILTER is given, it must be a predicate that takes one argument.
     It is called on every element of the directory entry, and only the
     entries on which FILTER returns true are included in the result.
     The argument passed to FILTER is a basename of the directory entry
     by default, but when FILTER-ADD-PATH? is true, PATH is appended to
     the entry.

     If PATH is not a directory, an error is signalled.

          (directory-list "test")
           => ("." ".." "test.scm" "test.scm~")

          (directory-list "test" :add-path? #t)
           => ("test/." "test/.." "test/test.scm" "test/test.scm~")

          (directory-list "test" :children? #t)
           => ("test.scm" "test.scm~")

          (directory-list "test" :children? #t :add-path? #t
             :filter (lambda (e) (not (string-suffix? "~" e))))
           => ("test/test.scm")

 -- Function: directory-list2 path &keyword children? add-path? filter
          follow-link?
     Like `directory-list', but returns two values; the first one is a
     list of subdirectories, and the second one is a list of the rest.
     The keyword arguments CHILDREN?, `add-path?' and FILTER are the
     same as `directory-list'.

     Giving false value to FOLLOW-LINK? makes `directory-list2' not
     follow the symbolic links; if the PATH contains a symlink to a
     directory, it will be included in the first list if FOLLOW-LINK?
     is omitted or true, while it will be in the second list if
     FOLLOW-LINK? is false.

 -- Function: directory-fold path proc knil &keyword lister follow-link?
     A fundamental directory traverser.  Conceptually it works as
     follows, in recursive way.

        * If PATH is not a directory, calls `(PROC PATH KNIL)' and
          returns the result.

        * If PATH is a directory, calls `(LISTER PATH KNIL)'.  The
          procedure LISTER is expected to return a list of pathnames.
          Then `directory-fold' is called on each returned pathname.
          Each result of `directory-fold' is passed as the KNIL
          argument of the next recursive invocation.  Returns the
          result of the last recursive call.

     The default procedure of LISTER is just a call to `directory-list',
     as follows.
          (lambda (path knil)
            (directory-list path :add-path? #t :children? #t)))))

     Note that LISTER shouldn't return the given path itself (`"."')
     nor the parent directory (`".."'), or the recursion wouldn't
     terminate.  Also note LISTER is expected to return a path accesible
     from the current directory, i.e. if PATH is `"/usr/lib/foo"' and
     it contains `"libfoo.a"' and `"libfoo.so"', LISTER should return
     `'("/usr/lib/foo/libfoo.a" "/usr/lib/foo/libfoo.so")'.

     The keyword argument FOLLOW-LINK? is used to determine whether
     LISTER should be called on a symbolic link pointing to a directory.
     When FOLLOW-LINK? is true (default), LISTER is called with the
     symbolic link if it points to a directory.  When FOLLOW-LINK? is
     false, PROC is not called.

     The following examble returns a list of pathnames of the emacs
     backup files (whose name ends with "~") under the given path.
          (use srfi-13) ;; for string-suffix?
          (directory-fold path
                          (lambda (entry result)
                            (if (string-suffix? "~" entry)
                                (cons entry result)
                                result))
                          '())


 -- Function: make-directory* name &optional perm
 -- Function: create-directory* name &optional perm
     Creates a directory NAME.  If the intermediate path to the
     directory doesn't exist, they are also created (like `mkdir -p'
     command on Unix).   If the directory NAME already exist, these
     procedure does nothing.  PERM specifies the integer flag for
     permission bits of the directory.

 -- Function: remove-directory* name
 -- Function: delete-directory* name
     Deletes directory NAME and its content recursively (like `rm -r'
     command on Unix).   Symbolic links are not followed.


File: gauche-refe.info,  Node: Pathname utilities,  Next: File attribute utilities,  Prev: Directory utilities,  Up: Filesystem utilities

11.8.2 Pathname utilities
-------------------------

 -- Function: build-path base-path component ...
     Appends pathname components COMPONENT to the BASE-PATH.  COMPONENT
     can be a symbol `up' or `same'; in Unix, they are synonym to
     `".."' and `"."'.  This API is taken from MzScheme.

 -- Function: absolute-path? path
 -- Function: relative-path? path
     Returns `#t' if PATH is absolute or relative, respectively.

 -- Function: expand-path path
     Expands tilda-notation of PATH if it contains one.  Otherwise,
     PATH is returned.  This function does not check if PATH exists
     and/or readable.

 -- Function: resolve-path path
     Expands PATH like `expand-path', then resolve symbolic links for
     every components of the path.  If PATH does not exist, or contains
     dangling link, or contains unreadable directory, an error is
     signalled.

 -- Function: simplify-path path
     Remove 'up' (`".."') components and 'same' (`"."') components from
     PATH as much as possible.  This function does not access the
     filesystem.

 -- Function: decompose-path path
     Returns three values; the directory part of PATH, the basename
     without extension of PATH, and the extension of PATH.    If the
     pathname doesn't have an extension, the third value is `#f'.  If
     the pathname ends with a directory separator, the second and third
     values are `#f'. (Note: This treatment of the trailing directory
     separator differs from `sys-dirname'/`sys-basename'; those follow
     popular shell's convention, which ignores trailing slashes.)
          (decompose-path "/foo/bar/baz.scm")
            => "/foo/bar", "baz", "scm"
          (decompose-path "/foo/bar/baz")
            => "/foo/bar", "baz", #f

          (decompose-path "baz.scm")
            => ".", "baz", "scm"
          (decompose-path "/baz.scm")
            => "/", "baz", "scm"

          ;; Boundary cases
          (decompose-path "/foo/bar/baz.")
            => "/foo/bar", "baz", ""
          (decompose-path "/foo/bar/.baz")
            => "/foo/bar", ".baz", #f
          (decompose-path "/foo/bar.baz/")
            => "/foo/bar.baz", #f, #f

 -- Function: path-extension path
 -- Function: path-sans-extension path
     Returns an extension of PATH, and  a pathname of PATH without
     extension, respectively.  If PATH doesn't have an extension, `#f'
     and PATH is returnedm respectively.

          (path-extension "/foo/bar.c")       => "c"
          (path-sans-extension "/foo/bar.c")  => "/foo/bar"

          (path-extension "/foo/bar")         => #f
          (path-sans-extension "/foo/bar")    => "/foo/bar"

 -- Function: path-swap-extension path newext
     Returns a pathname in which the extension of PATH is replaced by
     NEWEXT.  If PATH doesn't have an extension, "." and NEWEXT is
     appended to PATH.

     If NEWEXT is `#f', it returns PATH without extension.

          (path-swap-extension "/foo/bar.c" "o")  => "/foo/bar.o"
          (path-swap-extension "/foo/bar.c" #f)   => "/foo/bar"

 -- Function: find-file-in-paths name &keyword paths pred
     Looks for a file that has name NAME in the given list of pathnames
     PATHS and that satisfies a predicate PRED.  If found, the absolute
     pathname of the file is returned.  Otherwise, `#f' is returned.

     If NAME is an absolute path, only the existence of NAME and
     whether it satisfies PRED are checked.

     The default value of PATHS is taken from the environment variable
     `PATH', and the default value of PRED is `file-is-executable?'
     (*Note File attribute utilities::).  That is, `find-file-in-paths'
     searches the named executable file in the command search paths by
     default.

          (find-file-in-paths "ls")
            => "/bin/ls"

          ;; example of searchin user preference file of my application
          (find-file-in-paths "userpref"
            :paths `(,(expand-path "~/.myapp")
                     "/usr/local/share/myapp"
                     "/usr/share/myapp")
            :pred  file-is-readable?)


File: gauche-refe.info,  Node: File attribute utilities,  Next: File operations,  Prev: Pathname utilities,  Up: Filesystem utilities

11.8.3 File attibute utilities
------------------------------

 -- Function: file-type path &keyword follow-link?
 -- Function: file-perm path &keyword follow-link?
 -- Function: file-mode path &keyword follow-link?
 -- Function: file-ino path &keyword follow-link?
 -- Function: file-dev path &keyword follow-link?
 -- Function: file-rdev path &keyword follow-link?
 -- Function: file-nlink path &keyword follow-link?
 -- Function: file-uid path &keyword follow-link?
 -- Function: file-gid path &keyword follow-link?
 -- Function: file-size path &keyword follow-link?
 -- Function: file-atime path &keyword follow-link?
 -- Function: file-mtime path &keyword follow-link?
 -- Function: file-ctime path &keyword follow-link?
     These functions return the attribute of file/directory specified by
     PATH.  The attribute name corresponds to the slot name of
     `<sys-stat>' class (*Note File stats::).  If the named path
     doesn't exist, `#f' is returned.

     If PATH is a symbolic link, these functions queries the attributes
     of the file pointed by the link, unless an optional argument
     FOLLOW-LINK? is given and false.

     MzScheme and Chicken have `file-size'.  Chicken also has
     `file-modification-time', which is `file-mtime'.

 -- Function: file-is-readable? path
 -- Function: file-is-writable? path
 -- Function: file-is-executable? path
     Returns `#t' if PATH exists and readable/writable/executable by
     the current effective user, respectively.  This API is taken from
     STk.

 -- Function: file-is-symlink? path
     Returns `#t' if PATH exists and a symbolic link.  See also
     `file-is-regular?' and `file-is-directory?' in *Note File stats::.

 -- Function: file-eq? path1 path2
 -- Function: file-eqv? path1 path2
 -- Function: file-equal? path1 path2
     Compares two files specified by PATH1 and PATH2.  `file-eq?' and
     `file-eqv?' checks if PATH1 and PATH2 refers to the identical
     file, that is, whether they are on the same device and have the
     identical inode number.  The only difference is when the last
     component of PATH1 and/or PATH2 is a symbolic link, `file-eq?'
     doesn't resolve the link (so compares the links themselves) while
     FILE-EQV? resolves the link and compares the files referred by the
     link(s).

     `file-equal?' compares PATH1 and PATH2 considering their content,
     that is, when two are not the identical file in the sense of
     `file-eqv?', `file-equal?' compares their content and returns `#t'
     if all the bytes match.

     The behavior of `file-equal?' is undefined when PATH1 and PATH2
     are both directories.  Later, it may be extended to scan the
     directory contents.

 -- Generic Function: file-mtime=? f1 f2
 -- Generic Function: file-mtime<? f1 f2
 -- Generic Function: file-mtime<=? f1 f2
 -- Generic Function: file-mtime>? f1 f2
 -- Generic Function: file-mtime>=? f1 f2
     Compares file modification time stamps.  There are a bunch of
     methods defined, so each argument can be either one of the
     followings.

        * String pathname.   The mtime of the specified path is used.

        * `<sys-stat>' object (*Note File stats::).  The mtime is taken
          from the stat structure.

        * `<time>' object.  The time is used as the mtime.

        * Number.  It is considered as the number of seconds since Unix
          Epoch, and used as mtime.

          ;; compare "foo.c" is newer than "foo.o"
          (file-mtime>? "foo.c" "foo.o")

          ;; see if "foo.log" is updated within last 24 hours
          (file-mtime>? "foo.c" (- (sys-time) 86400))

 -- Generic Function: file-ctime=? f1 f2
 -- Generic Function: file-atime=? f1 f2
     Same as `file-mtime=?', except these checks file's change time and
     access time, respectively.  All the variants of `<', `<=', `>',
     `>=' are also defined.


File: gauche-refe.info,  Node: File operations,  Prev: File attribute utilities,  Up: Filesystem utilities

11.8.4 File operations
----------------------

 -- Function: touch-file path
     Updates timestamp of PATH to the current time.  If PATH doesn't
     exist, a new file with size zero is created.  See also `sys-utime'
     (*Note File stats::).

 -- Function: copy-file src dst &keyword if-exists backup-suffix safe
          keep-timestamp
     Copies file from SRC to DST.  The source file SRC must exist.  The
     behavior when the destination DST exists varies by the keyword
     argument IF-EXISTS;

    `:error'
          (Default) Signals an error when DST exists.

    `:supersede'
          Replaces DST to the copy of `src'.

    `:backup'
          Keeps DST by renaming it.

    `#f'
          Doesn't copy and returns `#f' when DST exists.

     `Copy-file' returns `#t' after completion.

     If IF-EXISTS is `:backup', the keyword argument BACKUP-SUFFIX
     specifies the suffix attached to the DST to be renamed.  The
     default value is `".orig"'.

     By default, `copy-file' starts copying to DST directly.  However,
     if the keyword argument SAFE is a true value, it copies the file
     to a temporary file in the same directory of DST, then renames it
     to DST when copy is completed.  If copy is interrupted for some
     reason, the filesystem is "rolled back" properly.

     If the keyword argument KEEP-TIMESTAMP is true, `copy-file' sets
     the destination's timestamp to the same as the source's timestamp
     after copying.

 -- Function: move-file src dst &keyword if-exists backup-suffix
     Moves file SRC to DST.   The source SRC must exist.  The behavior
     when DST exists varies by the keyword argument IF-EXISTS, as
     follows.
    `:error'
          (Default) Signals an error when DST exists.

    `:supersede'
          Replaces DST by `src'.

    `:backup'
          Keeps DST by renaming it.

    `#f'
          Doesn't move and returns `#f' when DST exists.

     `Move-file' returns `#t' after completion.

     If IF-EXISTS is `:backup', the keyword argument BACKUP-SUFFIX
     specifies the suffix attached to the DST to be renamed.  The
     default value is `".orig"'.

     The file SRC and DST can be on the different filesystem.  In such
     a case, `move-file' first copies SRC to the temporary file on the
     same directory as DST, then renames it to DST, then removes SRC.

 -- Function: file->string filename options ...
 -- Function: file->list reader filename options ...
 -- Function: file->string-list filename options ...
 -- Function: file->sexp-list filename options ...
     Convenience procedures to read from a file FILENAME.  They first
     open the named file, then call `port->string', `port->list',
     `port->string-list' and `port->sexp-list' on the opened file,
     respectively.  (*Note Input utility functions::).  The file is
     closed if all the content is read or an error is signalled during
     reading.

     All the optional arguments OPTIONS ... are passed to
     `call-with-input-file' as they are.


File: gauche-refe.info,  Node: Mathematic constants,  Next: Mersenne-Twister random number generator,  Prev: Filesystem utilities,  Up: Library modules - Utilities

11.9 `math.const' - Mathematic constants
========================================

 -- Module: math.const
     This module defines several commonly-used mathematic constants.

 -- Constant: pi
 -- Constant: pi/2
 -- Constant: pi/4
 -- Constant: pi/180
 -- Constant: 1/pi
 -- Constant: 180/pi
     Bound to pi, pi/2, pi/4, pi/180, 1/pi and 180/pi, respectively.

 -- Constant: e
     e.


File: gauche-refe.info,  Node: Mersenne-Twister random number generator,  Next: RFC822 message parsing,  Prev: Mathematic constants,  Up: Library modules - Utilities

11.10 `math.mt-random' - Mersenne Twister Random number generator
=================================================================

 -- Module: math.mt-random
     Provides a pseudo random number generator (RNG) based on "Mersenne
     Twister" algorithm developed by Makoto Matsumoto and Takuji
     Nishimura.   It is fast, and has huge period of 2^19937-1.  See
     *Note MT: MT, for details about the algorithm.

 -- Class: <mersenne-twister>
     A class to encapsulate the state of Mersenne Twister RNG.  Each
     instance of this class has its own state, and can be used as an
     independent source of random bits if initialized by individual
     seed.

     The random seed value can be given at the instantiation time by
     `:seed' initialization argument, or by using `mt-random-set-seed!'
     described below.

          (define m (make <mersenne-twister> :seed (sys-time)))

          (mt-random-real m) => 0.10284287848537865
          (mt-random-real m) => 0.463227748348805
          (mt-random-real m) => 0.8628500643709712
          ...

 -- Function: mt-random-set-seed! mt seed
     Sets random seed value SEED to the Mersenne Twister RNG MT.  SEED
     can be an arbitrary positive exact integer, or arbitrary length of
     u32vector (*Note Homogeneous vectors::).  If it is an integer, the
     lower 32bits are used for initialization.  If it is a u32vector,
     up to 624 elements are used for initialization.

 -- Function: mt-random-get-state mt
 -- Function: mt-random-set-state! mt state
     Retrieves and reinstalls the state of Mersenne Twister RNG MT.
     The state is represented by a u32vector of 625 elements.  The state
     can be stored elsewhere, and then restored to an instance of
     `<mersenne-twister>' to continue to generate the pseudo random
     sequence.

 -- Function: mt-random-real mt
 -- Function: mt-random-real0 mt
     Returns a random real number between 0.0 and 1.0.  1.0 is not
     included in the range.  `Mt-random-real' doesn't include 0.0
     either, while `mt-random-real0' does.  Excluding 0.0 is from the
     draft SRFI-27.

 -- Function: mt-random-integer mt range
     Returns a random exact positive integer between 0 and RANGE-1.
     RANGE can be any positive exact integer.

 -- Function: mt-random-fill-u32vector! mt u32vector
 -- Function: mt-random-fill-f32vector! mt f32vector
 -- Function: mt-random-fill-f64vector! mt f64vector
     Fills the given uniform vector by the random numbers.  For
     `mt-random-fill-u32vector!', the elements are filled by exact
     positive integers between 0 and 2^32-1.  For
     `mt-random-fill-f32vector!' and `mt-random-fill-f64vector!', it is
     filled by an inexact real number between 0.0 and 1.0, exclusive.

     If you need a bunch of random numbers at once, these are much
     faster than getting one by one.


File: gauche-refe.info,  Node: RFC822 message parsing,  Next: Base64 encoding/decoding,  Prev: Mersenne-Twister random number generator,  Up: Library modules - Utilities

11.11 `rfc.822' - RFC822 message parsing
========================================

 -- Module: rfc.822
     Defines a set of functions that parses and constructs the "Internet
     Message Format", a text format used to exchange e-mails.  The most
     recent specification can be found in RFC2822 (*Note [RFC2822]:
     rfc2822.).  The format was originally defined in RFC 822, and
     people still call it "RFC822 format", hence I named this module.
     In the following document, I also refer to the format as "RFC822
     format".

     Say `(use rfc.822)' to use this module.

Parsing a message header
------------------------

 -- Function: rfc822-header->list iport &keyword strict? reader
     Reads RFC822 format message from an input port IPORT, until it
     reaches the end of the message header.  The header fields are
     unfolded, and broken into a list of the following format:
          ((name body) ...)
     NAME ... are the field names, and BODY ... are the corresponding
     field body, both as strings.  Field names are converted to
     lower-case characters.  Field bodies are not modified, except the
     folded line is concatenated, CRLFs removed.  The order of fields
     are preserved.

     By default, the parser works permissively.  If EOF is encountered
     during parsing header, it is taken as the end of the message.  And
     if a line that doesn't consist neither continuing (folded) line
     nor start a new header field, it is simply ignored.  You can
     change this behavior by giving true value to the keyword argument
     STRICT?; then the parser raises an error for such a malformed
     header.

     The keyword argument READER takes a procedure that reads a line
     from IPORT.  Its default is `read-line', which should be enough
     for most cases.

 -- Function: rfc822-header-ref header-list field-name &optional default
     An utility procedure to get a specific field from the parsed
     header list, which is returned by `rfc822-header->list'.

     FIELD-NAME specifies the field name in a lowercase string.  If the
     field with given name is in HEADER-LIST, the procedure returns its
     value in a string.  Otherwise, if DEFAULT is given, it is
     returned, and if not, `#f' is returned.

Basic field parsers
-------------------

Several procedures are provided to parse "structured" header fields of
RFC2822 messages.  These procedures deal with the body of a header
field, i.e. if the header field is "`To: Wandering Schemer
<schemer@example.com>'", they parse "`Wandering Schemer
<schemer@example.com>'".

   Most of procedures take an input port.  Usually you first parse the
entire header fields by `rfc822-header->list', obtain the body of the
header by `rfc822-header-ref', then open an input string port for the
body and use those procedures to parse them.

   The reason for this complexity is because you need different
tokenization schemes depending on the type of the field.  Rfc2822 also
allows comments to appear between tokens for most cases, so a
simple-minded regexp won't do the job, since rfc2822 comment can be
nested and can't be represented by regular grammar.  So, this layer of
procedures are designed flexible enough to handle various syntaxes.
For the standard header types, high-level parsers are also provided;
see "specific field parsers" below.

 -- Function: rfc822-next-token iport &optional tokenizer-specs
     A basic tokenizer.  First it skips whitespaces and/or comments
     (`CFWS') from IPORT, if any.  Then reads one token according to
     TOKENIZER-SPECS.  If IPORT reaches EOF before any token is read,
     EOF is returned.

     TOKENIZER-SPECS is a list of tokenizer spec, which is either a
     char-set or a cons of a char-set and a procedure.

     After skipping `CFWS', the procedure peeks a character at the head
     of IPORT, and checks it against the char-sets in TOKENIZER-SPECS
     one by one.  If a char-set that contains the character belongs to
     is found, then a token is retrieved as follows: If the tokenizer
     spec is just a char-set, a sequence of characters that belong to
     the char-set consists a token.  If it is a cons, the procedure is
     called with IPORT to read a token.

     If the head character doesn't match any char-sets, the character
     is taken from IPORT and returned.

     The default TOKENIZER-SPECS is as follows:
          (list (cons #["] rfc822-quoted-string)
                (cons *rfc822-atext-chars* rfc822-dot-atom))
     Where `rfc822-quoted-string' and `rfc822-dot-atom' are tokenizer
     procedures described below, and `*rfc822-atext-chars*' is bound to
     a char-set of `atext' specified in rfc2822.  This means
     `rfc822-next-token' retrieves a token either `quoted-string' or
     `dot-atom' specified in rfc2822 by default.

     Using TOKENIZER-SPECS, you can customize how the header field is
     parsed.  For example, if you want to retrieve a token that is
     either (1) a word constructed by alphabetic characters, or (2) a
     quoted string, then you can call `rfc822-next-token' by this:

          (rfc822-next-token iport
             `(#[[:alpha:]] (#["] . ,rfc822-quoted-string)))

 -- Function: rfc822-field->tokens field &optional tokenizer-specs
     A convenience procedure.  Creates an input string port for a field
     body FIELD, and calls `rfc822-next-token' repeatedly on it until
     it consumes all input, then returns a list of tokens.
     TOKENIZER-SPECS is passed to `rfc822-next-token'.

 -- Function: rfc822-skip-cfws iport
     A utility procedure that consumes any comments and/or whitespace
     characters from IPORT, and returns the head character that is
     neither a whitespece nor a comment.  The returned character
     remains in IPORT.

 -- Constant: *rfc822-atext-chars*
     Bound to a char-set that is a valid constituent of `atom'.

 -- Constant: *rfc822-standard-tokenizers*
     Bound to the default TOKENIZER-SPECS.

 -- Function: rfc822-atom iport
 -- Function: rfc822-dot-atom iport
 -- Function: rfc822-quoted-string iport
     Tokenizers for `atom', `dot-atom' and `quoted-string',
     respectively.  The double-quotes and escaping backslashes within
     `quoted-string' are removed by `rfc822-quoted-string'.

Specific field parsers
----------------------

 -- Function: rfc822-parse-date string
     Takes RFC-822 type date string, and returns eight values:
          year, month, day-of-month, hour, minutes, seconds, timezone, day-of-week.

     _Timezone_ is an offset from UT in minutes.  _Day-of-week_ is a
     day from sunday, and may be #f if that information is not
     available.  _Month_ is an integer between 1 and 12, inclusive.  If
     the string is not parsable, all the elements are #f.

 -- Function: rfc822-date->date string
     Parses RFC822 type date format and returns SRFI-19 `<date>' object
     (see *Note SRFI-19 Date::).  If STRING can't be parsed, returns
     `#f' instead.


File: gauche-refe.info,  Node: Base64 encoding/decoding,  Next: HTTP cookie handling,  Prev: RFC822 message parsing,  Up: Library modules - Utilities

11.12 `rfc.base64' - Base64 encoding/decoding
=============================================

 -- Module: rfc.base64
     This module defines a few functions to encode/decode Base64 format,
     defined in RFC 2045 (*Note [RFC2045]: rfc2045.), section 6.3.

 -- Function: base64-encode
     Reads byte stream from the current input port, encodes it in Base64
     format and writes the result character stream to the current
     output port.  The conversion ends when it reads EOF from the
     current input port.

 -- Function: base64-encode-string string
     Converts contents of STRING to Base64 encoded format.  Input
     string can be either complete or incomplete string; it is always
     interpreted as a byte sequence.

 -- Function: base64-decode
     Reads character stream from the current input port, decodes it
     from Base64 format and writes the result byte stream to the
     current output port.  The conversion ends when it reads EOF or the
     termination character (`=').  The characters which does not in
     legal Base64 encoded character set are silently ignored.

 -- Function: base64-decode-string string
     Decodes a Base64 encoded string STRING and returns the result as a
     string.  The conversion terminates at the end of STRING or the
     termination character (`=').  The characters which does not in
     legal Base64 encoded character set are silently ignored.


File: gauche-refe.info,  Node: HTTP cookie handling,  Next: HMAC keyed-hashing,  Prev: Base64 encoding/decoding,  Up: Library modules - Utilities

11.13 `rfc.cookie' - HTTP cookie handling
=========================================

 -- Module: rfc.cookie
     Defines a set of functions to parse and construct a "cookie"
     information defined in RFC 2965 (*Note RFC2965: rfc2965.).

 -- Function: parse-cookie-string string &optional version
     Parse a cookie string STRING, which is the value of "Cookie"
     request header.  Usually, the same information is available to CGI
     program via the environemnt variable `HTTP_COOKIE'.

     If the cookie version is known, via "Cookie2" request header, the
     integer version must be passed to VERSION.  Otherwise,
     `parse-cookie' figures out the version from STRING.

     The result has the following format.
          ((<name> <value> [:path <path>] [:domain <domain>] [:port <port>])
           ...)
     where <NAME> is the attribute name, and <VALUE> is the
     corresponding value.  If the attribute doesn't have value, <VALUE>
     is `#f'.  (Note that it differs from the attribute having null
     value, `""'.)  If the attribute has path, domain or port options,
     it is given as a form of keyword-value pair.

 -- Function: construct-cookie-string specs &optional version
     Given list of cookie specs, creates a cookie string suitable for
     `Set-cookie2' or `Set-cookie' header.

     Optional VERSION argument specifies cookie protocol version.  0
     for the old Netscape style format, and 1 for RFC2965 style format.
     When omitted, version 1 is assumed.

     Each cookie spec has the following format.
          (<name> <value> [:comment <comment>] [:comment-url <url>]
                          [:discard <bool>] [:domain <domain>]
                          [:max-age <age>] [:path <path>]
                          [:port <port-list>] [:secure <bool>]
                          [:version <version>] [:expires <date>])
     Where,
    `<name>'
          A string.  Name of the cookie.

    `<value>'
          Value of the cookie.  May be a string, or `#f' if no value is
          needed.

    `<comment> <url> <domain> <path> <port-list>'
          Strings.

    `<bool>'
          Boolean value

    `<age> <version>'
          Integers

    `<date>'
          Either an integer (seconds since Epoch) or a formatted date
          string following the netscape cookie specification.

     The attribute values are quoted appropriately.  If the specified
     attribute is irrelevant for the VERSION, it is ignored.  So you
     can pass the same specs to generate both old-style and new-style
     cookie strings.

     Return value is a list of cookie strings, each of which stands for
     each cookie.  For old-style protocol (using `Set-cookie' header)
     you must send each of them by individual header.  For new-style
     protocol (using `Set-cookie2' header), you can join them with
     comma and send it at once.  See RFC2965 for further details.

     Some examples:
          (construct-cookie-string
             `(("name" "foo" :domain "foo.com" :path "/"
                             :expires ,(+ (sys-time) 86400) :max-age 86400)))
           => ("name=foo;Domain=foo.com;Path=/;Max-age=86400")

          (construct-cookie-string
             `(("name" "foo" :domain "foo.com" :path "/"
                             :expires ,(+ (sys-time) 86400) :max-age 86400))
             0)
           =>
           ("name=foo;Domain=foo.com;Path=/;Expires=Sun, 09-Sep-2001 01:46:40 GMT")


File: gauche-refe.info,  Node: HMAC keyed-hashing,  Next: HTTP,  Prev: HTTP cookie handling,  Up: Library modules - Utilities

11.14 `rfc.hmac' - HMAC keyed-hashing
=====================================

 -- Module: rfc.hmac
     This module implements HMAC algorithm, Keyed-hashing for message
     authentication, defined in RFC 2104.

     For simple batched keyed hashing, you can use high-level API
     `hmac-digest' and `hmac-digest-string'.  Or you can create
     `<hmac>' object and update its state as the data coming in.

 -- Class: <hmac>
     Keeps state informatoin of HMAC algorithm.  Key and the hashing
     algorithm should be given at the construction time, using `:key'
     and `:hasher' keyword-arguments respectively.  You can pass any
     class object that implements message digest interface (*Note
     Message digester framework::), such as `<md5>' (*Note MD5 message
     digest::) or `<sha1>' (*Note SHA1 message digest::).

     Example:
          (make <hmac> :key (make-byte-string 16 #x0b) :hasher <md5>)

 -- Method: hmac-update! (hmac <hmac>) data
     Updates the internal state of HMAC by DATA, which must be
     represented by a (possibly incomplete) string.

 -- Method: hmac-final! (hmac <hmac>)
     Finalizes the internal state of HMAC and returns the hashed string
     in incomplete string.  You can use `digest-hexify' (*Note Message
     digester framework::) to obtain "hexified" result.  Once
     finalized, you can't call `hmac-update!' or `hmac-final!' on HMAC.

 -- Method: hmac-digest &keyword key hasher
     Creates an `<hmac>' object and hash the data stream from the
     current input port, then returns the hashed result in an
     incomplete string.

 -- Method: hmac-digest-string string &keyword key hasher
     Creates an `<hmac>' object and hash the data in STRING, then
     returns the hashed result in an incomplete string.


File: gauche-refe.info,  Node: HTTP,  Next: MD5 message digest,  Prev: HMAC keyed-hashing,  Up: Library modules - Utilities

11.15 `rfc.http' - HTTP
=======================

 -- Module: rfc.http
     This module provides a simple client API for HTTP/1.1, defined in
     RFC2616, "Hypertext Transfer Protocol - HTTP/1.1" (*Note
     [RFC2616]: rfc2616.).

     Current API implements only a part of the protocol.  Only GET,
     HEAD, and POST requests are supported, it doesn't talk with
     HTTP/1.0 server yet, and it doesn't support HTTP/1.1 advanced
     features such as persistent connection.  Support for those
     features may be added in the future versions.

 -- Function: http-get server request-uri &keyword sink flusher
          no-redirect ...
 -- Function: http-head server request-uri &keyword no-redirect ...
 -- Function: http-post server request-uri body &keyword sink flusher
          no-redirect ...
     Send http GET, HEAD and POST requests to the http SERVER,
     respectively, and returns the server's reply.

     If the server returns "3xx" redirection reply, these procedures
     try to follow the URI returned in the "location" reply message
     header by default.  See the "keyword arguments" heading below to
     suppress redirection following.

     *Required arguments:* The SERVER argument specifies http server
     name in a string.  A server name can be optionally followed by
     colon and a port number.  Examples: `"w3c.org"',
     `"mycompany.com:8080"'.

     The REQUEST-URI argument is the request-uri specified in RFC2616;
     usually, this is the path part of http url.

     `Http-post' takes the third argument, BODY, which is a string to
     be posted to the server.   The body is sent "as is"; the caller
     has to take care of necessary escaping or encoding.

     So, the most simple form of retrieving the content will be
     something like this:
          (http-get "www.shiro.dreamhost.com" "/scheme/index.html")

     Access via proxy can be done by specifying proxy server to SERVER
     and passing the entire URI to REQUEST-URI, but the author haven't
     tested yet.

     *Return values:* All procedures return three values.

     The first value is the status code defined in RFC2616 in a string
     (such as "200" for success, "404" for "not found").

     The second value is a list of parsed headers--each element of list
     is a list of `(HEADER-NAME VALUE ...)', where HEADER-NAME is a
     string name of the header (such as "content-type" or "location"),
     and VALUE is the corresponding value in a string.  The header name
     is converted to lowercase letters.  The value is untouched except
     that "soft line breaks" are removed, as defined in RFC2822.   If
     the server returns more than one headers with the same name, their
     values are consolidated to one list.  Except that, the order of
     the header list in the second return value is the same as the
     order in the server's reply.

     The third value is for the message body of the server's reply.  By
     default, it is a message body itself in a string.   If the server's
     reply doesn't have a body, the third value is `#f'.  You can
     change how the message body is handled by keyword arguments; for
     example, you can directly store the returned message body to a
     file without creating intermediate string.  The details are
     explained below.

     *Keyword arguments:* By default, these procedures only attaches
     `"Host"' header field to the request message.  You can give
     keyword arguments to add more header fields.
          (http-get "foo.bar.com" "/index.html"
            :accept-language "ja"
            :user-agent "My Scheme Program/1.0")

     The following keyword arguments are recognized by the procedure
     and do not appear in the request headers.

    NO-REDIRECT
          If a true value is given, suppress the redirection tracking;
          i.e. the procedures return "3xx" message as is.

    SINK, FLUSHER
          You can customize how the message body is handled by these
          keyword arguments.  You have to pass an output port to SINK,
          and a procedure that takes two arguments to FLUSHER.

          When the procedure starts receiving the message body, it
          feeds the received chunk to SINK.  When the procedure
          receives entire message body, FLUSHER method is called with
          SINK and a list of message header fields (in the same format
          to be returned in the second value from the procedure).  The
          return value of FLUSHER becomes the third return value from
          the procedure.

          So, the default value of SINK is a newly opened string port
          and the default value of FLUSHER is `(lambda (sink headers)
          (get-output-string sink))'.

          The following example saves the message body directly to a
          file, without allocating (potentially very big) string buffer.
               (call-with-output-file "page.html"
                 (lambda (out)
                   (http-get "www.schemers.org" "/"
                      :sink out :flusher (lambda _ #t))))




File: gauche-refe.info,  Node: MD5 message digest,  Next: MIME message handling,  Prev: HTTP,  Up: Library modules - Utilities

11.16 `rfc.md5' - MD5 message digest
====================================

 -- Module: rfc.md5
     This module implements MD5 message digest algorithm, defined in
     RFC 1321 (*Note [RFC1321]: rfc1321.).  The module extends
     util.digest (*Note Message digester framework::).

 -- Class: <md5>
     The instance of this class keeps internal state of MD5 digest
     algorithm.

     This class implements `util.digest' framework interface,
     `digest-update!', `digest-final!', `digest', and `digest-string'.
     *Note Message digester framework::, for detailed explanation of
     these methods.

   Besides the digester framework, this module provides to short-cut
procedures.

 -- Function: md5-digest
     Reads data from the current input port until EOF, and returns its
     digest in an incomplete string.

 -- Function: md5-digest-string string
     Digest the data in STRING, and returns the result in an incomplete
     string.


File: gauche-refe.info,  Node: MIME message handling,  Next: Quoted-printable encoding/decoding,  Prev: MD5 message digest,  Up: Library modules - Utilities

11.17 `rfc.mime' - MIME message handling
========================================

 -- Module: rfc.mime
     This module provides utility procedures to handle Multipurpose
     Internet Mail Extensions (MIME) messages, defined in RFC2045
     thorough RFC2049.  This module is supposed to be used with
     `rfc.822' module (*Note RFC822 message parsing::).

Utilities for header fields
---------------------------

A few utility procedures to parse MIME-specific header fields.

 -- Function: mime-parse-version field
     If FIELD is a valid header field for MIME-Version, returns its
     major and minor versions in a list.  Otherwise, returns `#f'.  It
     is allowed to pass `#f' to FIELD, so that you can directly pass
     the result of `rfc822-header-ref' to it.  Given parsed header list
     by `rfc822-header->list', you can get mime version (currently, it
     should be `(1 0)') by the following code.
          (mime-parse-version (rfc822-header-ref headers "mime-version"))

     Note: simple regexp such as `#/\d+\.\d+/' doesn't do this job, for
     FIELD may contain comments between tokens.

 -- Function: mime-parse-content-type field
     Parses the "content-type" header field, and returns a list such as:
          (type subtype (attribute . value) ...)
     where type and subtype are MIME media type and subtype in a
     string, respectively

          (mime-parse-content-type "text/html; charset=iso-2022-jp")
           => ("text" "html" ("charset" . "iso-2022-jp"))

     If FIELD is not a valid content-type field, `#f' is returned.

 -- Function: mime-decode-word word
     Decodes RFC2047-encoded word.  If WORD isn't an encoded word, it
     is returned as is.

          (mime-decode-word "=?iso-8859-1?q?this=20is=20some=20text?=")
           => "this is some text"

Streaming parser
----------------

The streaming parser is designed so that you can decide how to do with
the message body before the entire message is read.

 -- Function: mime-parse-message port headers handler
     The fundamental streaming parser.  PORT is an input port from
     where the mssage is read.  HEADERS is a list of headers parsed by
     `rfc822-header->list'; that is, this procedure is supposed to be
     called after the header part of the message is parsed from PORT:
          (let* ((headers (rfc822-header->list port)))
            (if (mime-parse-version (rfc822-header-ref headers "mime-version"))
               ;; parse MIME message
               (mime-parse-message port headers handler)
               ;; retrieve a non-MIME body
               ...))

     `Mime-parse-message' analyzes HEADERS, and calls HANDLER on each
     message body with two arguments:

          (handler PART-INFO XPORT)

     PART-INFO is a `<mime-part>' structure described below that
     encapsulates the information of this part of the message.  XPORT
     is an input port, initially points to the beginning of the body of
     message.  The handler can read from the port as if it is reading
     from the original PORT.  However, XPORT recognizes MIME boundary
     internally, and returns EOF when it reaches the end of the part.
     (Do not read from the original PORT directly, or it will mess up
     the internal state of VPORT).

     HANDLER can read the part into the memory, or save it to the disk,
     or even discard the part.  Whatever it does, it has to read from
     VPORT until it returns EOF.

     The return value of HANDLER will be set in the `content' slot of
     PART-INFO.  If the message has nested multipart messages, HANDLER
     is called for each "leaf" part, in depth-first order.  HANDLER can
     know its nesting level by examining PART-INFO structure.  The
     message doesn't need to be a multipart type; if it is a MIME
     `message' type, HANDLER is called on the body of enclosed message.
     If it is other media types such as `text' or `application',
     HANDLER is called on the (only) message body.

 -- Class: <mime-part>
     A structure that encloses metainformation about a MIME part.  It
     is constructed when the header of the part is read, and passed to
     the handler that reads the body of the part.

     It has the following slots:

      -- Instance Variable of <mime-part>: type
          MIME media type string.  If `content-type' header is omitted
          to the part, an appropriate default value is set.

      -- Instance Variable of <mime-part>: subtype
          MIME media subtype string.  If `content-type' header is
          omitted to the part, an appropriate default value is set.

      -- Instance Variable of <mime-part>: parameters
          Associative list of parameters given to `content-type' header
          field.

      -- Instance Variable of <mime-part>: transfer-encoding
          The value of `content-transfer-encoding' header field.  If
          the header field is omitted, an appropriate default value is
          set.

      -- Instance Variable of <mime-part>: headers
          The list of header fields, as parsed by `rfc822-header->list'.

      -- Instance Variable of <mime-part>: parent
          If this is a part of multipart message or encapsulated
          message, points to the enclosing part's `<mime-part>'
          structure.  Otherwise `#f'.

      -- Instance Variable of <mime-part>: index
          Sequence number of this part within the same parent.

      -- Instance Variable of <mime-part>: content
          If this part is multipart/* or message/* media type, this
          slot contains a list of parts within it.  Otherwise, the
          return value of HANDLER is stored.

 -- Function: mime-retrieve-body part-info xport outp
     A procedure to retrieve message body.  It is intended to to be a
     building block of HANDLER to be passed to `mime-parse-message'.

     PART-INFO is a `<mime-part>' object.  XPORT is an input port
     passed to the handler, from which the MIME part can be read.  This
     procedure read from XPORT until it returns EOF.  It also looks at
     the `transfer-encoding' of PART-INFO, and decodes the body
     accordingly; that is, base64 encoding and quoted-printable
     encoding is handled.  The result is written out to an output port
     OUTP.

     This procedure does not handle charset conversion.  The caller
     must use CES conversion port as OUTP (*Note Character code
     conversion::) if desired.

   A couple of convenience procedures are defined for typical cases on
top of `mime-retrieve-body'.

 -- Function: mime-body->string part-info xport
 -- Function: mime-body->file part-info xport filename
     Reads in the body of mime message, decoding transfer encoding, and
     returns it as a string or writes it to a file, respectively.

   The simplest form of MIME message parser would be like this:

     (let ((headers (rfc822-header->list port)))
       (mime-parse-message port headers
                           (cut mime-body->string <> <>)))

   This reads all the message on memory (i.e. the "leaf" `<mime-part>'
objects' `content' field would hold the part's body as a string), and
returns the top `<mime-part>' object.  Content transfer encoding is
recognized and handled, but character set conversion isn't done.

   You may want to feed the message body to a file directly, or even
want to skip some body according to mime media types and/or other
header information.  Then you can put the logic in the handler closure.
That's the reason that this module provides building blocks, instead
of all-in-one procedure.


File: gauche-refe.info,  Node: Quoted-printable encoding/decoding,  Next: SHA1 message digest,  Prev: MIME message handling,  Up: Library modules - Utilities

11.18 `rfc.quoted-printable' - Quoted-printable encoding/decoding
=================================================================

 -- Module: rfc.quoted-printable
     This module defines a few functions to encode/decode
     Quoted-printable format, defined in RFC 2045 (*Note [RFC2045]:
     rfc2045.), section 6.7.

 -- Function: quoted-printable-encode
     Reads byte stream from the current input port, encodes it in
     Quoted-printable format and writes the result character stream to
     the current output port.  The conversion ends when it reads EOF
     from the current input port.

 -- Function: quoted-printable-encode-string string
     Converts contents of STRING to Quoted-printable encoded format.
     Input string can be either complete or incomplete string; it is
     always interpreted as a byte sequence.

 -- Function: quoted-printable-decode
     Reads character stream from the current input port, decodes it
     from Quoted-printable format and writes the result byte stream to
     the current output port.  The conversion ends when it reads EOF.
     If it encounters illegal character sequence (such as '=' followed
     by non-hexadecimal characters), it copies them literally to the
     output.

 -- Function: quoted-printable-decode-string string
     Decodes a Quoted-printable encoded string STRING and returns the
     result as a string.


File: gauche-refe.info,  Node: SHA1 message digest,  Next: URI parsing and construction,  Prev: Quoted-printable encoding/decoding,  Up: Library modules - Utilities

11.19 `rfc.sha1' - SHA1 message digest
======================================

 -- Module: rfc.sha1
     This module implements US Secure Hash Algorithm 1 (SHA1), defined
     in RFC 3174 (*Note [RFC3174]: rfc3174.).  The module extends
     util.digest (*Note Message digester framework::).

 -- Class: <sha1>
     The instance of this class keeps internal state of SHA1 digest
     algorithm.

     This class implements `util.digest' framework interface,
     `digest-update!', `digest-final!', `digest', and `digest-string'.
     *Note Message digester framework::, for detailed explanation of
     these methods.

   Besides the digester framework, this module provides to short-cut
procedures.

 -- Function: sha1-digest
     Reads data from the current input port until EOF, and returns its
     digest in an incomplete string.

 -- Function: sha1-digest-string string
     Digest the data in STRING, and returns the result in an incomplete
     string.


File: gauche-refe.info,  Node: URI parsing and construction,  Next: SLIB,  Prev: SHA1 message digest,  Up: Library modules - Utilities

11.20 `rfc.uri' - URI parsing and construction
==============================================

 -- Module: rfc.uri
     Provides a set of functions to parse Uniform Resource Identifiers
     defined in RFC 2396 (*Note [RFC2396]: rfc2396.).

 -- Function: uri-parse uri
 -- Function: uri-scheme&specific uri
 -- Function: uri-decompose-hierarchical specific
 -- Function: uri-decompose-authority authority
     General parser of URI.  These functions does not decode URI
     encoding, since the parts to be decoded differ among the uri
     schemes.   After parsing uri, use `uri-decode' below to decode
     them.

     `uri-parse' is the most handy procedure.  It breaks the uri into
     the following parts and returns them as multiple values.  If the
     uri doesn't have the corresponding parts, `#f' are returned for
     the parts.

        * URI scheme as a string (e.g. `"mailto"' in
          `"mailto:foo@example.com"').

        * User-info in the authority part (e.g. `"anonymous"' in
          `ftp://anonymous@ftp.example.com/pub/foo').

        * Hostname in the authority part (e.g. `"ftp.example.com"' in
          `ftp://anonymous@ftp.example.com/pub/foo').

        * Port number in the authority part, as an integer (e.g. `8080'
          in `http://www.example.com:8080/').

        * Path part (e.g. `"/index.html"' in
          `http://www.example.com/index.html').

        * Query part (e.g. `"key=xyz&lang=en"' in
          `http://www.example.com/search?key=xyz&lang=en').

        * Fragment part (e.g. `"section4"' in
          `http://www.example.com/document.html#section4').

     The following procedures are finer grained and break up uris with
     different stages.

     `uri-scheme&specific' takes a URI URI, and returns two values, its
     scheme part and its scheme-specific part.  If URI doesn't have a
     scheme part, #F is returned for it.
          (uri-scheme&specific "mailto:sclaus@north.pole")
            => "mailto" and "sclaus@north.pole"
          (uri-scheme&specific "/icons/new.gif")
            => #f and "/icons/new.gif"

     If the URI scheme uses hierarchical notation, i.e.
     "`//AUTHORITY/PATH?QUERY#FRAGMENT'", you can pass the
     scheme-specific part to `uri-decompose-hierarchical' and it
     returns four values, AUTHORITY, PATH, QUERY and FRAGMENT.
          (uri-decompose-hierarchical "//www.foo.com/about/company.html")
            => "www.foo.com", "/about/company.html", #f and #f
          (uri-decompose-hierarchical "//zzz.org/search?key=%3fhelp")
            => "zzz.org", "/search", "key=%3fhelp" and #f
          (uri-decompose-hierarchical "//jjj.jp/index.html#whatsnew")
            => "jjj.jp", "/index.html", #f and "whatsnew"
          (uri-decompose-hierarchical "my@address")
            => #f, #f, #f and #f

     Furthermore, you can parse AUTHORITY part of the hierarchical URI
     by `uri-decompose-authority'.  It returns USERINFO, HOST and PORT.
          (uri-decompose-authority "yyy.jp:8080")
            => #f, "yyy.jp" and "8080"
          (uri-decompose-authority "mylogin@yyy.jp")
            => "mylogin", "yyy.jp" and #f

 -- Function: uri-compose &keyword scheme userinfo host port authority
          path path* query fragment specific
     Compose a URI from given components.  There can be various
     combinations of components to create a valid URI--the following
     diagram shows the possible 'paths' of combinations:

                  /-----------------specific-------------------\
                  |                                            |
           scheme-+------authority-----+-+-------path*---------+-
                  |                    | |                     |
                  \-userinfo-host-port-/ \-path-query-fragment-/

     If `#f' is given to a keyword argument, it is equivalent to the
     absense of that keyword argument.  It is particulary useful to
     pass the results of parsed uri.

     If a component contains a character that is not appropriate for
     that component, it must be properly escaped before being passed to
     `url-compose'.

     Some examples:
          (uri-compose :scheme "http" :host "foo.com" :port 80
                       :path "/index.html" :fragment "top")
            => "http://foo.com:80/index.html#top"

          (uri-compose :scheme "http" :host "foo.net"
                       :path* "/cgi-bin/query.cgi?keyword=foo")
            => "http://foo.net/cgi-bin/query.cgi?keyword=foo"

          (uri-compose :scheme "mailto" :specific "a@foo.org")
            => "mailto:a@foo.org"

          (receive (authority path query fragment)
             (uri-decompose-hierarchical "//foo.jp/index.html#whatsnew")
           (uri-compose :authority authority :path path
                        :query query :fragment fragment))
            => "//foo.jp/index.html#whatsnew"

 -- Function: uri-decode &keyword :cgi-decode
 -- Function: uri-decode-string string &keyword :cgi-decode
     Decodes "URI encoding", i.e. `%'-escapes.  `uri-decode' takes
     input from the current input port, and writes decoded result to
     the current output port.  `uri-decode-string' takes input from
     STRING and returns decoded string.

     If CGI-DECODE is true, also replaces `+' to a space character.

 -- Function: uri-encode &keyword :noescape
 -- Function: uri-encode-string string &keyword :noescape
     Encodes unsafe characters by `%'-escape.  `uri-encode' takes input
     from the current input port and writes the result to the current
     output port.  `uri-encode-string' takes input from STRING and
     returns the encoded string.

     By default, characters that are not specified "unreserved" in
     RFC2396 are escaped.  You can pass different character set to
     NOESCAPE argument to keep from being encoded.

     The multibyte characters are encoded as the octed stream of
     Gauche's native multibyte representation.


File: gauche-refe.info,  Node: SLIB,  Next: Functional XML parser,  Prev: URI parsing and construction,  Up: Library modules - Utilities

11.21 `slib' - SLIB interface
=============================

 -- Module: slib
     This module is the interface to the Aubrey Jaffer's SLIB.  To use
     SLIB, say `(use slib)'.   SLIB itself is not included in Gauche
     distribution.   If you don't have it on your system, get it from
     `http://www-swiss.ai.mit.edu/~jaffer/SLIB.html'.

     This module redefines `require', shadowing the Gauche's original
     `require'.  If it gets a symbol as an argument, it works as SLIB's
     `require', while if it gets a string, it works as Gauche's
     `require'.   The same applies to `provide' and `provided?'.

     All SLIB symbol bindings, loaded by `require', stay in the module
     `slib'.

     (use slib)         ; load and set up slib
     (require 'getopt)  ; load SLIB's getopt module
     (require "foo")    ; load Gauche's foo module


File: gauche-refe.info,  Node: Functional XML parser,  Next: SXML Query Language,  Prev: SLIB,  Up: Library modules - Utilities

11.22 `sxml.ssax' - Functional XML parser
=========================================

 -- Module: sxml.ssax
     `sxml.*' modules are the adaptation of Oleg Kiselyov's SXML
     framework (*Note SSAX: ssax.), which is based on S-expression
     representation of XML structure.

     SSAX is a parser part of SXML framework.  This is a quote from
     SSAX webpage:

          A SSAX functional XML parsing framework consists of a
          DOM/SXML parser, a SAX parser, and a supporting library of
          lexing and parsing procedures.  The procedures in the package
          can be used separately to tokenize or parse various pieces of
          XML documents.  The framework supports XML Namespaces,
          character, internal and external parsed entities, attribute
          value normalization, processing instructions and CDATA
          sections. The package includes a semi-validating SXML parser
          : a DOM-mode parser that is an instantiation of a SAX parser
          (called SSAX).

     The current version is based on the SSAX CVS version newer than
     the last 'official' release of SXML toolset (4.9), and
     SXML-gauche-0.9 package which was based on SXML-4.9.  There is an
     important change from that release.  Now the API uses lowercase
     letter suffix `ssax:' instead of uppercase `SSAX:'--the difference
     matters since Gauche is case sensitive by default.  Alias names
     are defined for backward compatibility, but the use of uppercase
     suffixed names are deprecated.

   I derived the content of this part of the manual from SSAX source
code, just by converting its comments into texinfo format.  The
original text is by Oleg Kiselyov.  Shiro Kawai should be responsible
for any typographical error or formatting error introduced by
conversion.

   The manual entries are ordered in "bottom-up" way, beginning from
the lower-level constructs towards the high-level utilities.  If you
just want to parse XML document and obtain SXML, check out
`ssax:xml->sxml' in *Note SSAX Highest-level parsers - XML to SXML::.

* Menu:

* SSAX data types::
* SSAX low-level parsing code::
* SSAX higher-level parsers and scanners::
* SSAX Highest-level parsers - XML to SXML::


File: gauche-refe.info,  Node: SSAX data types,  Next: SSAX low-level parsing code,  Prev: Functional XML parser,  Up: Functional XML parser

11.22.1 SSAX data types
-----------------------

_TAG-KIND_
     a symbol '`START', '`END', '`PI', '`DECL', '`COMMENT', '`CDSECT'
     or '`ENTITY-REF' that identifies a markup token.

_UNRES-NAME_
     a name (called `GI' in the XML Recommendation) as given in an xml
     document for a markup token: start-tag, `PI' target, attribute
     name.  If a `GI' is an `NCName', UNRES-NAME is this `NCName'
     converted into a Scheme symbol. If a `GI' is a `QName', UNRES-NAME
     is a pair of symbols: (PREFIX . LOCALPART)

_RES-NAME_
     An expanded name, a resolved version of an UNRES-NAME.  For an
     element or an attribute name with a non-empty namespace URI,
     RES-NAME is a pair of symbols, (URI-SYMB . LOCALPART).  Otherwise,
     it's a single symbol.

_ELEM-CONTENT-MODEL_
     A symbol:
     `ANY'                anything goes, expect an END tag.
     `EMPTY-TAG'          no content, and no END-tag is coming.
     `EMPTY'              no content, expect the END-tag as the next
                          token.
     `PCDATA'             expect character data only, and no children
                          elements.
     `MIXED'              
     `ELEM-CONTENT'       

_URI-SYMB_
     A symbol representing a namespace URI - or other symbol chosen by
     the user to represent URI. In the former case, URI-SYMB is created
     by `%'-quoting of bad URI characters and converting the resulting
     string into a symbol.

_NAMESPACES_
     A list representing namespaces in effect. An element of the list
     has one of the following forms:

    `(PREFIX URI-SYMB . URI-SYMB)'
          or,

    `(PREFIX USER-PREFIX . URI-SYMB)'
          USER-PREFIX is a symbol chosen by the user to represent the
          URI.

    `(#f USER-PREFIX . URI-SYMB)'
          Specification of the user-chosen prefix and a URI-SYMBOL.

    `(*DEFAULT* USER-PREFIX . URI-SYMB)'
          Declaration of the default namespace

    `(*DEFAULT* #f . #f)'
          Un-declaration of the default namespace. This notation
          represents overriding of the previous declaration

     A NAMESPACES list may contain several elements for the same PREFIX.
     The one closest to the beginning of the list takes effect.

_ATTLIST_
     An ordered collection of (NAME . VALUE) pairs, where NAME is a
     RES-NAME or an UNRES-NAME. The collection is an ADT.

_STR-HANDLER_
     A procedure of three arguments: `(STRING1 STRING2 SEED)' returning
     a new SEED.  The procedure is supposed to handle a chunk of
     character data STRING1 followed by a chunk of character data
     STRING2.  STRING2 is a short string, often "\n" and even ""

_ENTITIES_
     An assoc list of pairs:
            (NAMED-ENTITY-NAME . NAMED-ENTITY-BODY)
     where NAMED-ENTITY-NAME is a symbol under which the entity was
     declared, NAMED-ENTITY-BODY is either a string, or (for an
     external entity) a thunk that will return an input port (from
     which the entity can be read).  NAMED-ENTITY-BODY may also be
     `#f'. This is an indication that a NAMED-ENTITY-NAME is currently
     being expanded. A reference to this NAMED-ENTITY-NAME will be an
     error: violation of the WFC nonrecursion.

_XML-TOKEN_
     A record with two slots, KIND and TOKEN.  This record represents a
     markup, which is, according to the XML Recommendation, "takes the
     form of start-tags, end-tags, empty-element tags, entity
     references, character references, comments, CDATA section
     delimiters, document type declarations, and processing
     instructions."
    KIND
          a TAG-KIND

    HEAD
          an UNRES-NAME. For xml-tokens of kinds '`COMMENT' and
          '`CDSECT', the head is `#f'

     For example,
          <P>  => kind='START, head='P
          </P> => kind='END, head='P
          <BR/> => kind='EMPTY-EL, head='BR
          <!DOCTYPE OMF ...> => kind='DECL, head='DOCTYPE
          <?xml version="1.0"?> => kind='PI, head='xml
          &my-ent; => kind = 'ENTITY-REF, head='my-ent
     Character references are not represented by xml-tokens as these
     references are transparently resolved into the corresponding
     characters.

_XML-DECL_
     A record with three slots, ELEMS, ENTITIES, and NOTATIONS.

     The record represents a datatype of an XML document: the list of
     declared elements and their attributes, declared notations, list of
     replacement strings or loading procedures for parsed general
     entities, etc. Normally an xml-decl record is created from a DTD or
     an XML Schema, although it can be created and filled in in many
     other ways (e.g., loaded from a file).

     ELEMS: an (assoc) list of decl-elem or `#f'. The latter instructs
     the parser to do no validation of elements and attributes.

     DECL-ELEM: declaration of one element: `(ELEM-NAME ELEM-CONTENT
     DECL-ATTRS)'; ELEM-NAME is an UNRES-NAME for the element.
     ELEM-CONTENT is an ELEM-CONTENT-MODEL.  DECL-ATTRS is an ATTLIST,
     of `(ATTR-NAME . VALUE)' associations.  This element can declare a
     user procedure to handle parsing of an element (e.g., to do a
     custom validation, or to build a hash of IDs as they're
     encountered).

     DECL-ATTR: an element of an ATTLIST, declaration of one attribute
     `(ATTR-NAME CONTENT-TYPE USE-TYPE DEFAULT-VALUE)': ATTR-NAME is an
     UNRES-NAME for the declared attribute; CONTENT-TYPE is a symbol:
     `CDATA', NMTOKEN, NMTOKENS, ...; or a list of strings for the
     enumerated type.  USE-TYPE is a symbol: `REQUIRED', `IMPLIED',
     `FIXED' default-value is a string for the default value, or `#f'
     if not given.

 -- Function: make-empty-attlist
 -- Function: attlist-add attlist name-value
 -- Function: attlist-null?
 -- Function: attlist-remoev-top attlist
 -- Function: attlist->alist attlist
 -- Function: attlist-fold
     Utility procedures to deal with attribute list, which keeps
     name-value association.

 -- Function: make-xml-token kind head
 -- Function: xml-token? token
     A constructor and a predicate for a XML-TOKEN record.

 -- Macro: xml-token-kind token
 -- Macro: xml-token-head token
     Accessor macros of a XML-TOKEN record.


File: gauche-refe.info,  Node: SSAX low-level parsing code,  Next: SSAX higher-level parsers and scanners,  Prev: SSAX data types,  Up: Functional XML parser

11.22.2 SSAX low-level parsing code
-----------------------------------

They deal with primitive lexical units (Names, whitespaces, tags) and
with pieces of more generic productions. Most of these parsers must be
called in appropriate context. For example, `ssax:complete-start-tag'
must be called only when the start-tag has been detected and its `GI'
has been read.

 -- Function: ssax:skip-S port
     Skip the S (whitespace) production as defined by
           [3] S ::= (#x20 | #x9 | #xD | #xA)
     The procedure returns the first not-whitespace character it
     encounters while scanning the PORT. This character is left on the
     input stream.

 -- Function: ssax:ncname-starting-char? a-char
     Check to see if a-char may start a `NCName'.

 -- Function: ssax:read-NCName port
     Read a `NCName' starting from the current position in the PORT and
     return it as a symbol.

 -- Function: ssax:read-QName port
     Read a (namespace-) Qualified Name, `QName', from the current
     position in the PORT.

     From REC-xml-names:
           [6] QName ::= (Prefix ':')? LocalPart
           [7] Prefix ::= NCName
           [8] LocalPart ::= NCName

     Return: an UNRES-NAME.

 -- Variable: ssax:Prefix-XML
     The prefix of the pre-defined XML namespace, i.e. '`xml'.

 -- Function: ssax:read-markup-token port
     This procedure starts parsing of a markup token. The current
     position in the stream must be `#\<'. This procedure scans enough
     of the input stream to figure out what kind of a markup token it
     is seeing. The procedure returns an xml-token structure describing
     the token. Note, generally reading of the current markup is not
     finished! In particular, no attributes of the start-tag token are
     scanned.

     Here's a detailed break out of the return values and the position
     in the PORT when that particular value is returned:
    `PI-token'
          only `PI'-target is read.  To finish the Processing
          Instruction and disregard it, call `ssax:skip-pi'.
          `ssax:read-attributes' may be useful as well (for `PI's whose
          content is attribute-value pairs)

    `END-token'
          The end tag is read completely; the current position is right
          after the terminating `#\>' character.

    `COMMENT'
          is read and skipped completely. The current position is right
          after "`-->'" that terminates the comment.

    `CDSECT'
          The current position is right after "`<!CDATA['".  Use
          `ssax:read-cdata-body' to read the rest.

    `DECL'
          We have read the keyword (the one that follows "`<!'")
          identifying this declaration markup. The current position is
          after the keyword (usually a whitespace character)

    `START-token'
          We have read the keyword (`GI') of this start tag.  No
          attributes are scanned yet. We don't know if this tag has an
          empty content either.  Use `ssax:complete-start-tag' to
          finish parsing of the token.

 -- Function: ssax:skip-pi port
     The current position is inside a `PI'. Skip till the rest of the
     `PI'.

 -- Function: ssax:read-pi-body-as-string port
     The current position is right after reading the `PITarget'. We
     read the body of `PI' and return it as a string. The port will
     point to the character right after '`?>'' combination that
     terminates `PI'.
           [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'

 -- Function: ssax:skip-internal-dtd port
     The current pos in the port is inside an internal DTD subset
     (e.g., after reading `#\[ 'that begins an internal DTD subset)
     Skip until the "`]>'" combination that terminates this DTD

 -- Function: ssax:read-cdata-body port str-handler seed
     This procedure must be called after we have read a string
     "`<![CDATA['" that begins a `CDATA' section. The current position
     must be the first position of the `CDATA' body. This function
     reads _lines_ of the `CDATA' body and passes them to a
     STR-HANDLER, a character data consumer.

     The str-handler is a STR-HANDLER, a procedure `string1' STRING2
     SEED.  The first STRING1 argument to STR-HANDLER never contains a
     newline.  The second STRING2 argument often will. On the first
     invocation of the STR-HANDLER, the seed is the one passed to
     `ssax:read-cdata-body' as the third argument. The result of this
     first invocation will be passed as the seed argument to the second
     invocation of the line consumer, and so on. The result of the last
     invocation of the STR-HANDLER is returned by the
     `ssax:read-cdata-body'.  Note a similarity to the fundamental
     '`fold'' iterator.

     Within a `CDATA' section all characters are taken at their face
     value, with only three exceptions:
        * `CR', `LF', and `CRLF' are treated as line delimiters, and
          passed as a single `#\newline' to the STR-HANDLER.

        * "`]]>'" combination is the end of the `CDATA' section.

        * `&gt;' is treated as an embedded `#\>' character.  Note,
          `&lt;' and `&amp;' are not specially recognized (and are not
          expanded)!

 -- Function: ssax:read-char-ref port
           [66]  CharRef ::=  '&#' [0-9]+ ';'
                            | '&#x' [0-9a-fA-F]+ ';'
     This procedure must be called after we we have read "`&#'" that
     introduces a char reference.  The procedure reads this reference
     and returns the corresponding char.  The current position in PORT
     will be after "`;'" that terminates the char reference.  Faults
     detected: `WFC: XML-Spec.html#wf-Legalchar'.

     According to Section "4.1 Character and Entity References" of the
     XML Recommendation:

          "[Definition: A character reference refers to a specific
          character  in the ISO/IEC 10646 character set, for example
          one not directly  accessible from available input devices.]"
     Therefore, we use a `ucscode->char' function to convert a character
     code into the character - _regardless_ of the current character
     encoding of the input stream.

 -- Function: ssax:handle-parsed-entity port name entities
          content-handler str-handler seed
     Expand and handle a parsed-entity reference
        * PORT - a PORT

        * NAME - the name of the parsed entity to expand, a symbol.

        * ENTITIES - see ENTITIES

        * CONTENT-HANDLER - procedure PORT ENTITIES SEED that is
          supposed to return a SEED.

        * STR-HANDLER - a STR-HANDLER. It is called if the entity in
          question turns out to be a pre-declared entity
     The result is the one returned by CONTENT-HANDLER or STR-HANDLER.

     Faults detected:
            WFC: XML-Spec.html#wf-entdeclared
            WFC: XML-Spec.html#norecursion

 -- Function: ssax:read-attributes port entities
     This procedure reads and parses a production `Attribute*'
           [41] Attribute ::= Name Eq AttValue
           [10] AttValue ::=  '"' ([^<&"] | Reference)* '"'
                           | "'" ([^<&'] | Reference)* "'"
           [25] Eq ::= S? '=' S?
     The procedure returns an ATTLIST, of NAME (as UNRES-NAME), VALUE
     (as string) pairs.  The current character on the PORT is a
     non-whitespace character that is not an ncname-starting character.

     Note the following rules to keep in mind when reading an 'AttValue'
     "Before the value of an attribute is passed to the application or
     checked for validity, the XML processor must normalize it as
     follows:
        * a character reference is processed by appending the referenced
          character to the attribute value

        * an entity reference is processed by recursively processing the
          replacement text of the entity [see ENTITIES] [named entities
          amp lt gt quot apos are assumed pre-declared]

        * a whitespace character (`#x20', `#xD', `#xA', `#x9') is
          processed by appending `#x20' to the normalized value, except
          that only a single `#x20' is appended for a "`#xD#xA'"
          sequence that is part of an external parsed entity or the
          literal entity value of an internal parsed entity

        * other characters are processed by appending them to the
          normalized value "

     Faults detected:
           WFC: XML-Spec.html#CleanAttrVals
           WFC: XML-Spec.html#uniqattspec

 -- Function: ssax:resolve-name port unres-name namespaces
          apply-default-ns?
     Convert an UNRES-NAME to a RES-NAME given the appropriate
     NAMESPACES declarations.  The last parameter APPLY-DEFAULT-NS?
     determines if the default namespace applies (for instance, it does
     not for attribute names)

     Per `REC-xml-names/#nsc-NSDeclared', "xml" prefix is considered
     pre-declared and bound to the namespace name
     "`http://www.w3.org/XML/1998/namespace'".

     This procedure tests for the namespace constraints:
     `http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared'.

 -- Function: ssax:uri-string->symbol uri-str
     Convert a URI-STR to an appropriate symbol.

 -- Function: ssax:complete-start-tag tag port elems entities namespaces
     This procedure is to complete parsing of a start-tag markup. The
     procedure must be called after the start tag token has been read.
     TAG is an UNRES-NAME.  ELEM S is an instance of `xml-decl::elems';
     it can be `#f' to tell the function to do _no_ validation of
     elements and their attributes.

     This procedure returns several values:
    ELEM-GI
          a RES-NAME.

    ATTRIBUTES
          element's attributes, an ATTLIST of `(RES-NAME . STRING)'
          pairs. The list does _not_ include `xmlns' attributes.

    NAMESPACES
          the input list of namespaces amended with namespace
          (re-)declarations contained within the start-tag under parsing
          ELEM-CONTENT-MODEL.

     On exit, the current position in PORT will be the first character
     after `#\>' that terminates the start-tag markup.

     Faults detected:
           VC: XML-Spec.html#enum
           VC: XML-Spec.html#RequiredAttr
           VC: XML-Spec.html#FixedAttr
           VC: XML-Spec.html#ValueType
           WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are resolved)
           VC: XML-Spec.html#elementvalid
           WFC: REC-xml-names/#dt-NSName

     Note, although XML Recommendation does not explicitly say it,
     XMLNS and XMLNS: attributes don't have to be declared (although
     they can be declared, to specify their default value).

 -- Function: ssax:read-external-id port
     This procedure parses an `ExternalID' production.
           [75] ExternalID ::= 'SYSTEM' S SystemLiteral
                           | 'PUBLIC' S PubidLiteral S SystemLiteral
           [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
           [12] PubidLiteral ::=  '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
           [13] PubidChar ::=  #x20 | #xD | #xA | [a-zA-Z0-9]
                          | [-'()+,./:=?;!*#@$_%]
     This procedure is supposed to be called when an `ExternalID' is
     expected; that is, the current character must be either `#\S' or
     `#\P' that start correspondingly a `SYSTEM' or `PUBLIC' token.
     This procedure returns the `SystemLiteral' as a string. A
     `PubidLiteral' is disregarded if present.


File: gauche-refe.info,  Node: SSAX higher-level parsers and scanners,  Next: SSAX Highest-level parsers - XML to SXML,  Prev: SSAX low-level parsing code,  Up: Functional XML parser

11.22.3 SSAX higher-level parsers and scanners
----------------------------------------------

They parse productions corresponding to the whole (document) entity or
its higher-level pieces (prolog, root element, etc).

 -- Function: ssax:scan-Misc port
     Scan the `Misc' production in the context:
          [1]  document ::=  prolog element Misc*
          [22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
          [27] Misc ::= Comment | PI |  S
     The following function should be called in the prolog or epilog
     contexts.  In these contexts, whitespaces are completely ignored.
     The return value from `ssax:scan-Misc' is either a `PI'-token, a
     `DECL'-token, a `START' token, or EOF.  Comments are ignored and
     not reported.

 -- Function: ssax:read-char-data port expect-eof? str-handler seed
     This procedure is to read the character content of an XML document
     or an XML element.
           [43] content ::=
                  (element | CharData | Reference | CDSect | PI
                   | Comment)*
     To be more precise, the procedure reads `CharData', expands
     `CDSect' and character entities, and skips comments. The procedure
     stops at a named reference, EOF, at the beginning of a `PI' or a
     start/end tag.

    PORT
          a port to read

    EXPECT-EOF?
          a boolean indicating if EOF is normal, i.e., the character
          data may be terminated by the EOF. EOF is normal while
          processing a parsed entity.

    STR-HANDLER
          a STR-HANDLER.

    SEED
          an argument passed to the first invocation of STR-HANDLER.

     The procedure returns two results: SEED and TOKEN.

     The SEED is the result of the last invocation of STR-HANDLER, or
     the original seed if STR-HANDLER was never called.

     TOKEN can be either an eof-object (this can happen only if
     EXPECT-EOF? was `#t'), or:
        * an xml-token describing a START tag or an END-tag; For a
          start token, the caller has to finish reading it.

        * an xml-token describing the beginning of a `PI'. It's up to an
          application to read or skip through the rest of this `PI';

        * an xml-token describing a named entity reference.

     `CDATA' sections and character references are expanded inline and
     never returned. Comments are silently disregarded.

     As the XML Recommendation requires, all whitespace in character
     data must be preserved. However, a `CR' character (`#xD') must be
     disregarded if it appears before a `LF' character (`#xA'), or
     replaced by a `#xA' character otherwise. See Secs. 2.10 and 2.11
     of the XML Recommendation. See also the canonical XML
     Recommendation.

 -- Function: ssax:assert-token token kind gi error-cont
     Make sure that TOKEN is of anticipated KIND and has anticipated GI.
     Note GI argument may actually be a pair of two symbols, Namespace
     URI or the prefix, and of the localname.  If the assertion fails,
     ERROR-CONT is evaluated by passing it three arguments: TOKEN KIND
     GI.  The result of ERROR-CONT is returned.


File: gauche-refe.info,  Node: SSAX Highest-level parsers - XML to SXML,  Prev: SSAX higher-level parsers and scanners,  Up: Functional XML parser

11.22.4 SSAX Highest-level parsers - XML to SXML
------------------------------------------------

These parsers are a set of syntactic forms to instantiate a SSAX parser.
A user can instantiate the parser to do the full validation, or no
validation, or any particular validation. The user specifies which `PI'
he wants to be notified about. The user tells what to do with the
parsed character and element data. The latter handlers determine if the
parsing follows a SAX or a DOM model.

 -- Macro: ssax:make-pi-parser my-pi-handlers
     Create a parser to parse and process one Processing Element (`PI').

     MY-PI-HANDLERS: An assoc list of pairs (PI-TAG . PI-HANDLER) where
     PI-TAG is an NCNAME symbol, the `PI' target, and PI-HANDLER is a
     procedure PORT PI-TAG SEED where PORT points to the first symbol
     after the `PI' target.  The handler should read the rest of the
     `PI' up to and including the combination '`?>'' that terminates
     the `PI'. The handler should return a new seed.  One of the
     PI-TAGs may be a symbol `*DEFAULT*'. The corresponding handler
     will handle `PI's that no other handler will. If the `*DEFAULT*'
     PI-TAG is not specified, `ssax:make-pi-parser' will make one,
     which skips the body of the `PI'.

     The output of the `ssax:make-pi-parser' is a procedure PORT PI-TAG
     SEED, that will parse the current `PI' accoding to user-specified
     handlers.

 -- Macro: ssax:make-elem-parser my-new-level-seed my-finish-element
          my-char-data-handler my-pi-handlers
     Create a parser to parse and process one element, including its
     character content or children elements. The parser is typically
     applied to the root element of a document.

    MY-NEW-LEVEL-SEED
          procedure ELEM-GI ATTRIBUTES NAMESPACES EXPECTED-CONTENT SEED
          where ELEM-GI is a RES-NAME of the element about to be
          processed.  This procedure is to generate the seed to be
          passed to handlers that process the content of the element.

    MY-FINISH-ELEMENT
          procedure ELEM-GI ATTRIBUTES NAMESPACES PARENT-SEED SEED
          This procedure is called when parsing of ELEM-GI is finished.
          The SEED is the result from the last content parser (or from
          MY-NEW-LEVEL-SEED if the element has the empty content).
          PARENT-SEED is the same seed as was passed to
          MY-NEW-LEVEL-SEED.  The procedure is to generate a seed that
          will be the result of the element parser.

    MY-CHAR-DATA-HANDLER
          A STR-HANDLER.

    MY-PI-HANDLERS
          See `ssax:make-pi-handler' above.

     The generated parser is a: procedure START-TAG-HEAD PORT ELEMS
     ENTITIES NAMESPACES PRESERVE-WS? SEED.
     The procedure must be called after the start tag token has been
     read. START-TAG-HEAD is an UNRES-NAME from the start-element tag.
     ELEMS is an instance of `xml-decl::elems'.  See
     `ssax:complete-start-tag::preserve-ws?'

     Faults detected:
           VC: XML-Spec.html#elementvalid
           WFC: XML-Spec.html#GIMatch

 -- Macro: ssax:make-parser user-handler-tag user-handler-proc ...
     Create an XML parser, an instance of the XML parsing framework.
     This will be a SAX, a DOM, or a specialized parser depending on
     the supplied user-handlers.

     USER-HANDLER-TAG is a symbol that identifies a procedural
     expression that follows the tag. Given below are tags and
     signatures of the corresponding procedures. Not all tags have to
     be specified. If some are omitted, reasonable defaults will apply.

    `tag: DOCTYPE'
          handler-procedure: PORT DOCNAME SYSTEMID INTERNAL-SUBSET? SEED

          If INTERNAL-SUBSET? is `#t', the current position in the port
          is right after we have read `#\[' that begins the internal
          DTD subset.  We must finish reading of this subset before we
          return (or must call skip-internal-subset if we aren't
          interested in reading it).  The port at exit must be at the
          first symbol after the whole DOCTYPE declaration.

          The handler-procedure must generate four values:
          ELEMS ENTITIES NAMESPACES SEED
          See `xml-decl::elems' for ELEMS.  It may be `#f' to switch
          off the validation.  NAMESPACES will typically contain
          USER-PREFIXes for selected URI-SYMBs.  The default
          handler-procedure skips the internal subset, if any, and
          returns `(values #f '() '() seed)'.

    `tag: UNDECL-ROOT'
          handler-procedure: ELEM-GI SEED
          where ELEM-GI is an UNRES-NAME of the root element. This
          procedure is called when an XML document under parsing
          contains _no_ `DOCTYPE' declaration.  The handler-procedure,
          as a DOCTYPE handler procedure above, must generate four
          values:
          ELEMS ENTITIES NAMESPACES SEED
          The default handler-procedure returns `(values #f '() '()
          seed)'.

    `tag: DECL-ROOT'
          handler-procedure: ELEM-GI SEED
          where ELEM-GI is an UNRES-NAME of the root element. This
          procedure is called when an XML document under parsing does
          contains the `DOCTYPE' declaration.  The handler-procedure
          must generate a new `seed' (and verify that the name of the
          root element matches the doctype, if the handler so wishes).
          The default handler-procedure is the identity function.

    `tag: NEW-LEVEL-SEED'
          handler-procedure: see `ssax:make-elem-parser',
          MY-NEW-LEVEL-SEED

    `tag: FINISH-ELEMENT'
          handler-procedure: see `ssax:make-elem-parser',
          MY-FINISH-ELEMENT

    `tag: CHAR-DATA-HANDLER'
          handler-procedure: see `ssax:make-elem-parser',
          MY-CHAR-DATA-HANDLER

    `tag: PI'
          handler-procedure: see `ssax:make-pi-parser'.
          The default value is `'()'.

     The generated parser is a
     procedure PORT SEED

     This procedure parses the document prolog and then exits to an
     element parser (created by ssax:make-elem-parser) to handle the
     rest.

           [1]  document ::=  prolog element Misc*
           [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
           [27] Misc ::= Comment | PI |  S

           [28] doctypedecl ::=  '<!DOCTYPE' S Name (S ExternalID)? S?
                                  ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
           [29] markupdecl ::= elementdecl | AttlistDecl
                                | EntityDecl
                                | NotationDecl | PI
                                | Comment

   A few utility procedures that turned out useful.

 -- Function: ssax:reverse-collect-str fragments
     given the list of FRAGMENTS (some of which are text strings)
     reverse the list and concatenate adjacent text strings.

 -- Function: ssax:reverse-collect-str-drop-ws fragments
     given the list of fragments (some of which are text strings)
     reverse the list and concatenate adjacent text strings.  We also
     drop "unsignificant" whitespace, that is, whitespace in front,
     behind and between elements. The whitespace that is included in
     character data is not affected.  We use this procedure to
     "intelligently" drop "insignificant" whitespace in the parsed
     SXML. If the strict compliance with the XML Recommendation
     regarding the whitespace is desired, please use the
     `ssax:reverse-collect-str' procedure instead.

 -- Function: ssax:xml->sxml port namespace-prefix-assig
     This is an instance of a SSAX parser above that returns an SXML
     representation of the XML document to be read from PORT.
     NAMESPACE-PREFIX-ASSIG is a list of `(USER-PREFIX . URI-STRING)'
     that assigns USER-PREFIXes to certain namespaces identified by
     particular URI-STRINGs. It may be an empty list.  The procedure
     returns an SXML tree. The port points out to the first character
     after the root element.


File: gauche-refe.info,  Node: SXML Query Language,  Next: manipulationg SXML structure,  Prev: Functional XML parser,  Up: Library modules - Utilities

11.23 `sxml.sxpath' - SXML Query Language
=========================================

 -- Module: sxml.sxpath
     SXPath is a query language for SXML, an instance of XML Information
     set (Infoset) in the form of s-expressions.

     It is originally written by Oleg Kiselyov, and improved by Dmitry
     Lizorkin and Kirill Lisovsky.  This module also incorporates
     various procedures written for SXPath by Dmitry Lizorkin and
     Kirill Lisovsky.

     Current version is based on sxpathlib.scm,v 3.915, sxpath.scm,v
     1.1, and sxpath-ext.scm,v 1.911.

   This manual is mostly derived from the comments in the original
source files.

   The module consists of three layers.
  1. Basic converters and applicators, which provides the means to
     access and translate SXML tree.

  2. High-level query language compiler, which takes abbreviated SXPath
     and returns a Scheme function that selects a nodeset that
     satisfies the specified path from the given nodeset.

  3. Extension libraries, which implements SXML counterparts to W3C
     XPath Core Functions Library.

* Menu:

* SXPath basic converters and applicators::
* SXPath query language::
* SXPath extension::


File: gauche-refe.info,  Node: SXPath basic converters and applicators,  Next: SXPath query language,  Prev: SXML Query Language,  Up: SXML Query Language

11.23.1 SXPath basic converters and applicators
-----------------------------------------------

A converter is a function
       type Converter = Node|Nodeset -> Nodeset
   A converter can also play a role of a predicate: in that case, if a
converter, applied to a node or a nodeset, yields a non-empty nodeset,
the converter-predicate is deemed satisfied. Throughout this file a nil
nodeset is equivalent to `#f' in denoting a failure.

 -- Function: nodeset? x
     Returns `#t' if given object is a nodeset.

 -- Function: as-nodeset x
     If X is a nodeset - returns it as is, otherwise wrap it in a list.

 -- Function: sxml:element? obj
     Predicate which returns #T if OBJ is SXML element, otherwise
     returns #F.

 -- Function: ntype-names?? crit
     The function `ntype-names??' takes a list of acceptable node names
     as a criterion and returns a function, which, when applied to a
     node, will return `#t' if the node name is present in criterion
     list and `#f' othervise.
           ntype-names?? :: ListOfNames -> Node -> Boolean

 -- Function: ntype?? crit
     The function `ntype??' takes a type criterion and returns a
     function, which, when applied to a node, will tell if the node
     satisfies the test.
            ntype?? :: Crit -> Node -> Boolean

     The criterion CRIT is one of the following symbols:
    `id'
          tests if the Node has the right name (id)

    `@'
          tests if the Node is an ATTRIBUTES-LIST.

    `*'
          tests if the Node is an ELEMENT.

    `*text*'
          tests if the Node is a text node.

    `*data*'
          tests if the Node is a data node (text, number, boolean,
          etc., but not pair).

    `*PI*'
          tests if the Node is a `PI' node.

    `*COMMENT*'
          tests if the Node is a `COMMENT' node.

    `*ENTITY*'
          tests if the Node is a `ENTITY' node.

    `*any*'
          `#t' for any type of Node.

 -- Function: ntype-namespace-id?? ns-id
     This function takes a namespace-id, and returns a predicate `Node
     -> Boolean', which is `#t' for nodes with this very namespace-id.
     NS-ID is a string.  `(ntype-namespace-id?? #f)' will be `#t' for
     nodes with non-qualified names.

 -- Function: sxml:invert pred
     This function takes a predicate and returns it inverted .  That is
     if the given predicate yields `#f' or '`()' the inverted one
     yields the given node (`#t') and vice versa.

 -- Function: node-eq? other
 -- Function: node-equal? other
     Curried equivalence converter-predicates, i.e.
            ((node-eq? a) b)    == (eq? a b)
            ((node-equal? a) b) == (equal? a b)

 -- Function: node-pos n
           node-pos:: N -> Nodeset -> Nodeset, or
           node-pos:: N -> Converter

     Select the N'th element of a Nodeset and return as a singular
     Nodeset; Return an empty nodeset if the Nth element does not exist.
     `((node-pos 1) Nodeset)' selects the node at the head of the
     Nodeset, if exists; `((node-pos 2) Nodeset)' selects the Node
     after that, if exists.  N can also be a negative number: in that
     case the node is picked from the tail of the list.  `((node-pos
     -1) Nodeset)' selects the last node of a non-empty nodeset;
     `((node-pos -2) Nodeset)' selects the last but one node, if exists.

 -- Function: sxml:filter pred?
           filter:: Converter -> Converter

     A filter applicator, which introduces a filtering context. The
     argument converter is considered a predicate, with either `#f' or
     nil result meaning failure.

 -- Function: take-until pred?
           take-until:: Converter -> Converter, or
           take-until:: Pred -> Node|Nodeset -> Nodeset

     Given a converter-predicate and a nodeset, apply the predicate to
     each element of the nodeset, until the predicate yields anything
     but #F or nil. Return the elements of the input nodeset that have
     been processed till that moment (that is, which fail the
     predicate).  `take-until' is a variation of the filter above:
     `take-until' passes elements of an ordered input set till (but not
     including) the first element that satisfies the predicate.  The
     nodeset returned by `((take-until (not pred)) nset)' is a subset -
     to be more precise, a prefix - of the nodeset returned by
     `((filter pred) nset)'.

 -- Function: take-after pred?
          take-after:: Converter -> Converter, or
          take-after:: Pred -> Node|Nodeset -> Nodeset

     Given a converter-predicate and a nodeset, apply the predicate to
     each element of the nodeset, until the predicate yields anything
     but `#f' or nil. Return the elements of the input nodeset that
     have not been processed: that is, return the elements of the input
     nodeset that follow the first element that satisfied the predicate.
     `take-after' along with `take-until' partition an input nodeset
     into three parts: the first element that satisfies a predicate,
     all preceding elements and all following elements.

 -- Function: map-union proc lst
     Apply proc to each element of lst and return the list of results.
     If proc returns a nodeset, splice it into the result.

     From another point of view, `map-union' is a function
     Converter->Converter, which places an argument-converter in a
     joining context.

 -- Function: node-reverse node-or-nodeset
          node-reverse :: Converter, or
          node-reverse:: Node|Nodeset -> Nodeset

     Reverses the order of nodes in the nodeset.  This basic converter
     is needed to implement a reverse document order (see the XPath
     Recommendation).

 -- Function: node-trace title
           node-trace:: String -> Converter

     `(node-trace title)' is an identity converter. In addition it
     prints out a node or nodeset it is applied to, prefixed with the
     'title'.  This converter is very useful for debugging.

   What follow are Converter combinators, higher-order functions that
transmogrify a converter or glue a sequence of converters into a
single, non-trivial converter. The goal is to arrive at converters that
correspond to XPath location paths.

   From a different point of view, a combinator is a fixed, named
_pattern_ of applying converters. Given below is a complete set of such
patterns that together implement XPath location path specification. As
it turns out, all these combinators can be built from a small number of
basic blocks: regular functional composition, map-union and filter
applicators, and the nodeset union.

 -- Function: select-kids test-pred?
          select-kids:: Pred -> Node -> Nodeset
     Given a Node, return an (ordered) subset its children that satisfy
     the Pred (a converter, actually).

          select-kids:: Pred -> Nodeset -> Nodeset
     The same as above, but select among children of all the nodes in
     the Nodeset.

 -- Function: node-self pred
           node-self:: Pred -> Node -> Nodeset, or
           node-self:: Converter -> Converter

     Similar to select-kids but apply to the Node itself rather than to
     its children. The resulting Nodeset will contain either one
     component, or will be empty (if the Node failed the Pred).

 -- Function: node-join . selectors
           node-join:: [LocPath] -> Node|Nodeset -> Nodeset, or
           node-join:: [Converter] -> Converter

     join the sequence of location steps or paths as described in the
     title comments above.

 -- Function: node-reduce . converters
           node-reduce:: [LocPath] -> Node|Nodeset -> Nodeset, or
           node-reduce:: [Converter] -> Converter

     A regular functional composition of converters.  From a different
     point of view, `((apply node-reduce converters) nodeset)' is
     equivalent to `(foldl apply nodeset converters)' i.e., folding, or
     reducing, a list of converters with the nodeset as a seed.

 -- Function: node-or . converters
           node-or:: [Converter] -> Converter

     This combinator applies all converters to a given node and
     produces the union of their results.  This combinator corresponds
     to a union, '`|'' operation for XPath location paths.

 -- Function: node-closure test-pred?
           node-closure:: Converter -> Converter

     Select all _descendants_ of a node that satisfy a
     converter-predicate.  This combinator is similar to `select-kids'
     but applies to grand... children as well.  This combinator
     implements the "`descendant::'" XPath axis.  Conceptually, this
     combinator can be expressed as
           (define (node-closure f)
                (node-or
                  (select-kids f)
          	 (node-reduce (select-kids (ntype?? '*)) (node-closure f))))

     This definition, as written, looks somewhat like a fixpoint, and it
     will run forever.  It is obvious however that sooner or later
     `(select-kids (ntype?? '*))' will return an empty nodeset. At this
     point further iterations will no longer affect the result and can
     be stopped.


File: gauche-refe.info,  Node: SXPath query language,  Next: SXPath extension,  Prev: SXPath basic converters and applicators,  Up: SXML Query Language

11.23.2 SXPath query language
-----------------------------

 -- Function: sxpath abbrpath . ns-binding
     Evaluates an abbreviated SXPath

           sxpath:: AbbrPath -> Converter, or
           sxpath:: AbbrPath -> Node|Nodeset -> Nodeset

     ABBRPATH is a list. It is translated to the full SXPath according
     to the following rewriting rules:
           (sxpath '()) -> (node-join)
           (sxpath '(path-component ...)) ->
                          (node-join (sxpath1 path-component) (sxpath '(...)))
           (sxpath1 '//) -> (node-or
                               (node-self (ntype?? '*any*))
                               (node-closure (ntype?? '*any*)))
           (sxpath1 '(equal? x)) -> (select-kids (node-equal? x))
           (sxpath1 '(eq? x))    -> (select-kids (node-eq? x))
           (sxpath1 '(or@ ...))  -> (select-kids (ntype-names??
                                                    (cdr '(or@ ...))))
           (sxpath1 '(not@ ...)) -> (select-kids (sxml:invert
                                                   (ntype-names??
                                                    (cdr '(not@ ...)))))
           (sxpath1 '(ns-id:* x)) -> (select-kids
                                                (ntype-namespace-id?? x))
           (sxpath1 ?symbol)     -> (select-kids (ntype?? ?symbol))
           (sxpath1 ?string)     -> (txpath ?string)
           (sxpath1 procedure)   -> procedure
           (sxpath1 '(?symbol ...)) -> (sxpath1 '((?symbol) ...))
           (sxpath1 '(path reducer ...)) ->
                          (node-reduce (sxpath path) (sxpathr reducer) ...)
           (sxpathr number)      -> (node-pos number)
           (sxpathr path-filter) -> (filter (sxpath path-filter))

Some wrapper functions around `sxpath':

 -- Function: if-sxpath path
     `sxpath' always returns a list, which is `#t' in Scheme.
     `if-sxpath' returns `#f' instead of empty list.

 -- Function: if-car-sxpath path
     Returns first node found, if any.  Otherwise returns `#f'.

 -- Function: car-sxpath path
     Returns first node found, if any.  Otherwise returns empty list.

 -- Function: sxml:id-alist node . lpaths
     Built an index as a list of `(ID_VALUE . ELEMENT)' pairs for given
     node.  LPATHS are location paths for attributes of type ID.


File: gauche-refe.info,  Node: SXPath extension,  Prev: SXPath query language,  Up: SXML Query Language

11.23.3 SXPath extension
------------------------

SXML counterparts to W3C XPath Core Functions Library.

 -- Function: sxml:string object
     The counterpart to XPath `string' function (section 4.2 XPath Rec.)
     Converts a given object to a string.  NOTE:
       1. When converting a nodeset - a document order is not preserved

       2. NUMBER->STRING function returns the result in a form which is
          slightly different from XPath Rec. specification

 -- Function: sxml:boolean object
     The counterpart to XPath `boolean' function (section 4.3 XPath
     Rec.)  Converts its argument to a boolean.

 -- Function: sxml:number obj
     The counterpart to XPath `number' function (section 4.4 XPath Rec.)
     Converts its argument to a number NOTE:
       1. The argument is not optional (yet?).

       2. `string->number' conversion is not IEEE 754 round-to-nearest.

       3. NaN is represented as 0.

 -- Function: sxml:string-value node
     Returns a string value for a given node in accordance to XPath
     Rec. 5.1 - 5.7

 -- Function: sxml:node? node
     According to XPath specification 2.3, this test is true for any
     XPath node.  For SXML auxiliary lists and lists of attributes has
     to be excluded.

 -- Function: sxml:attr-list obj
     Returns the list of attributes for a given SXML node.  Empty list
     is returned if the given node is not an element, or if it has no
     list of attributes

 -- Function: sxml:id id-index
     Select SXML element by its unique IDs.  (XPath Rec. 4.1) Returns a
     converter that takes OBJECT, which is a nodeset or a datatype
     which can be converted to a string by means of a '`string''
     function.

     ID-INDEX is `( (id-value . element) (id-value . element) ... )'.

     This index is used for selection of an element by its unique ID.

   Comparators for XPath objects:

 -- Function: sxml:equality-cmp bool-op number-op string-op
     A helper for XPath equality operations: `=' , `!=' BOOL-OP,
     NUMBER-OP and 'STRING-OP are comparison operations for a pair of
     booleans,  numbers and strings respectively.

 -- Function: sxml:equal? a b
 -- Function: sxml:not-equal? a b
     Counterparts of XPath equality operations: `=' , `!=', using
     default equality tests.

 -- Function: sxml:relational-cmp op
     Creates a relational operation ( `<' , `>' , `<=' , `>=' ) for two
     XPath objects.  `op' is comparison procedure: `<' , `>' , `<=' or
     `>='.

   XPath axises.  An order in resulting nodeset is preserved.

 -- Function: sxml:attribute test-pred?
     Attribute axis.

 -- Function: sxml:child test-pred?
     Child axis.  This function is similar to '`select-kids'', but it
     returns an empty child-list for PI, Comment and Entity nodes.

 -- Function: sxml:parent test-pred?
     Parent axis.

     Given a predicate, it returns a function `RootNode -> Converter'
     which yields a ` node -> parent ' converter then applied to a
     rootnode.

     Thus, such a converter may be constructed using ` ((sxml:parent
     test-pred) rootnode) ' and returns a parent of a node it is
     applied to.  If applied to a nodeset, it returns the list of
     parents of nodes in the nodeset. The rootnode does not have to be
     the root node of the whole SXML tree - it may be a root node of a
     branch of interest.  The `parent::' axis can be used with any SXML
     node.

 -- Function: sxml:ancestor test-pred?
     Ancestor axis

 -- Function: sxml:ancestor-or-self test-pred?
     Ancestor-or-self axis

 -- Function: sxml:descendant test-pred?
     Descendant axis

 -- Function: sxml:descendant-or-self test-pred?
     Descendant-or-self axis

 -- Function: sxml:following test-pred?
     Following axis

 -- Function: sxml:following-sibling test-pred?
     Following-sibling axis

 -- Function: sxml:namespace test-pred?
     Namespace axis

 -- Function: sxml:preceding test-pred?
     Preceding axis

 -- Function: sxml:preceding-sibling test-pred?
     Preceding-sibling axis

   Popular shortcuts:

 -- Function: sxml:child-nodes nodeset
          ((sxml:child sxml:node?) nodeset)

 -- Function: sxml:child-elements nodeset
          ((select-kids sxml:element?) nodeset)


File: gauche-refe.info,  Node: manipulationg SXML structure,  Next: CSV tables,  Prev: SXML Query Language,  Up: Library modules - Utilities

11.24 `sxml.tools' - manipulationg SXML structure
=================================================

 -- Module: sxml.tools
     This module is a port of Kirill Lisofsky's sxml-tools, a
     collection of convenient procedures that work on SXML structure.
     The current version is derived from sxml-tools CVS revision 3.13.

     The manual entry is mainly derived from the comments in the
     original source code.

* Menu:

* SXML predicates::
* SXML accessors::
* SXML modifiers::
* SXPath auxiliary utilities::
* SXML to markup conversion::


File: gauche-refe.info,  Node: SXML predicates,  Next: SXML accessors,  Prev: manipulationg SXML structure,  Up: manipulationg SXML structure

11.24.1 SXML predicates
-----------------------

 -- Function: sxml:empty-element? obj
     A predicate which returns #T if given element OBJ is empty.  Empty
     element has no nested elements, text nodes, `PI's, Comments or
     entities but it may contain attributes or namespace-id.  It is a
     SXML counterpart of XML `empty-element'.

 -- Function: sxml:shallow-normalized? obj
     Returns `#t' if the given OBJ is shallow-normalized SXML element.
     The element itself has to be normalized but its nested elements
     are not tested.

 -- Function: sxml:normalized? obj
     Returns `#t' if the given OBJ is normalized SXML element.  The
     element itself and all its nested elements have to be normalised.

 -- Function: sxml:shallow-minimized? obj
     Returns `#t' if the given OBJ is shallow-minimized SXML element.
     The element itself has to be minimised but its nested elements are
     not tested.

 -- Function: sxml:minimized? obj
     Returns `#t' if the given OBJ is minimized SXML element.  The
     element itself and all its nested elements have to be minimised.


File: gauche-refe.info,  Node: SXML accessors,  Next: SXML modifiers,  Prev: SXML predicates,  Up: manipulationg SXML structure

11.24.2 SXML accessors
----------------------

 -- Function: sxml:name obj
     Returns a name of a given SXML node.  It's just an alias of `car',
     but introduced for the sake of encapsulation.

 -- Function: sxml:element-name obj
     A version of `sxml:name', which returns `#f' if the given OBJ is
     not a SXML element.  Otherwise returns its name.

 -- Function: sxml:node-name obj
     Safe version of `sxml:name', which returns `#f' if the given OBJ
     is not a SXML node.  Otherwise returns its name.

 -- Function: sxml:ncname obj
     Returns Local Part of Qualified Name (Namespaces in XML production
     [6]) for given obj, which is "`:'"-separated suffix of its
     Qualified Name.  If a name of a node given is `NCName' (Namespaces
     in XML production [4]), then it is returned as is.  Please note
     that while SXML name is a symbol this function returns a string.

 -- Function: sxml:name->ns-id sxml-name
     Returns namespace-id part of given name, or #F if it's LocalName

 -- Function: sxml:content obj
     Returns the content of given SXML element or nodeset (just text
     and element nodes) representing it as a list of strings and nested
     elements in document order.  This list is empty if OBJ is empty
     element or empty list.

 -- Function: sxml:content-raw obj
     Returns all the content of normalized SXML element except
     ATTR-LIST and AUX-LIST.  Thus it includes `PI', `COMMENT' and
     `ENTITY' nodes as well as `TEXT' and `ELEMENT' nodes returned by
     `sxml:content'.  Returns  a list of nodes in document order or
     empty list if OBJ is empty element or empty list.  This function
     is faster than `sxml:content'.

   In SXML normal form, an element is represented by a list as this:
       (NAME ATTR-LIST AUX-LIST CONTENT ...)
   where ATTR-LIST is a list beginning with `@', and AUX-LIST is a list
beginning with `@@'.

   In the minimized form, AUX-LIST can be omitted when it is empty.
ATTR-LIST can be omitted when it is empty _and_ AUX-LIST is absent.

   The following procedures extract ATTR-LIST and AUX-LIST.

 -- Function: sxml:attr-list-node obj
     Returns ATTR-LIST for a given OBJ, or `#f' if it is absent

 -- Function: sxml:attr-as-list obj
     Returns ATTR-LIST wrapped in list, or '`((@))' if it is absent and
     AUX-LIST is present, or '`()' if both lists are absent.

 -- Function: sxml:aux-list-node obj
     Returns AUX-LIST for a given OBJ, or `#f' if it is absent.

 -- Function: sxml:aux-as-list obj
     Returns AUX-LIST wrapped in list, or '`()' if it is absent.

 -- Function: sxml:attr-list-u obj
     Returns the list of attributes for given element or nodeset.
     Analog of `((sxpath '(@ *)) OBJ)'.  Empty list is returned if
     there is no list of attributes.

     The `-u' suffix indicates it can be used for non-normalized SXML
     node.  ('u' stands for 'universal').

 -- Function: sxml:aux-list obj
     Returns the list of auxiliary nodes for given element or nodeset.
     Analog of `((sxpath '(@@ *)) OBJ)'.  Empty list is returned if a
     list of auxiliary nodes is absent.

 -- Function: sxml:aux-list-u obj
     Returns the list of auxiliary nodes for given element or nodeset.
     Analog of `((sxpath '(@@ *)) OBJ)'.  Empty list is returned if a
     list of auxiliary nodes is absent.

     The `-u' suffix indicates it can be used for non-normalized SXML
     node.  ('u' stands for 'universal').

 -- Function: sxml:aux-node obj aux-name
     Return the first aux-node with AUX-NAME given in SXML element OBJ
     or `#f' is such a node is absent.  Note: it returns just the
     _first_ node found even if multiple nodes are present, so it's
     mostly intended for nodes with unique names .

 -- Function: sxml:aux-nodes obj aux-name
     Return a list of aux-node with AUX-NAME given in SXML element OBJ
     or '`()' if such a node is absent.

 -- Function: sxml:attr obj attr-name
     Accessor for an attribute ATTR-NAME of given SXML element OBJ.  It
     returns: the value of the attribute if the attribute is present, or
     #F if there is no such an attribute in the given element.

 -- Function: sxml:num-attr obj attr-name
     Accessor for a numerical attribute ATTR-NAME of given SXML element
     OBJ.  It returns: a value of the attribute as the attribute as a
     number if the attribute is present and its value may be converted
     to number using `string->number', or `#f' if there is no such an
     attribute in the given element or its value can't be converted to
     a number.

 -- Function: sxml:attr-u obj attr-name
     Accessor for an attribute ATTR-NAME of given SXML element OBJ which
     may also be an attributes-list or nodeset (usually content of SXML
     element).

     It returns: the value of the attribute if the attribute is present,
     or `#f' if there is no such an attribute in the given element.

     The `-u' suffix indicates it can be used for non-normalized SXML
     node.  ('u' stands for 'universal').

 -- Function: sxml:ns-list obj
     Returns the list of namespaces for given element.  Analog of
     `((sxpath '(@@ *NAMESPACES* *)) OBJ)' Empty list is returned if
     there is no list of namespaces.

 -- Function: sxml:ns-id->nodes obj namespace-id
     Returns the list of namespace-assoc's for given NAMESPACE-ID in
     SXML element OBJ.  Analog of `((sxpath '(@@ *NAMESPACES*
     namespace-id)) OBJ)'.  Empty list is returned if there is no
     namespace-assoc with NAMESPACE-ID given.

 -- Function: sxml:ns-id->uri obj namespace-id
     Returns a URI for NAMESPACE-ID given, or `#f' if there is no
     namespace-assoc with NAMESPACE-ID given.

 -- Function: sxml:ns-uri->id obj uri
     Returns a namespace-id for namespace URI given.

 -- Function: sxml:ns-id ns-assoc
     Returns namespace-id for given namespace-assoc list.

 -- Function: sxml:ns-uri ns-assoc
     Returns URI for given namespace-assoc list.

 -- Function: sxml:ns-prefix ns-assoc
     It returns namespace prefix for given namespace-assoc list.
     Original (as in XML document) prefix for namespace-id given has to
     be strored as the third element in namespace-assoc list if it is
     different from namespace-id.  If original prefix is omitted in
     namespace-assoc then namespace-id is used instead.


File: gauche-refe.info,  Node: SXML modifiers,  Next: SXPath auxiliary utilities,  Prev: SXML accessors,  Up: manipulationg SXML structure

11.24.3 SXML modifiers
----------------------

Constructors and mutators for normalized SXML data.  These functions
are optimized for normalized SXML data.  They are not applicable to
arbitrary non-normalized SXML data.

   Most of the functions are provided in two variants:
  1. side-effect intended functions for linear update of given elements.
     Their names are ended with exclamation mark.  Note that the
     returned value of this variant is unspecified, unless explicitly
     noted.  An example: `sxml:change-content!'.

  2. pure functions without side-effects which return modified elements.
     An example: `sxml:change-content'.

 -- Function: sxml:change-content obj new-content
 -- Function: sxml:change-content! obj new-content
     Change the content of given SXML element to NEW-CONTENT.  If
     NEW-CONTENT is an empty list then the OBJ is transformed to an
     empty element.  The resulting SXML element is normalized.

 -- Function: sxml:change-attrlist obj new-attrlist
 -- Function: sxml:change-attrlist! obj new-attrlist
     The resulting SXML element is normalized.  If NEW-ATTRLIST is
     empty, the cadr of OBJ is `(@)'.

 -- Function: sxml:change-name obj new-name
 -- Function: sxml:change-name! obj new-name
     Change a name of SXML element destructively.

 -- Function: sxml:add-attr obj attr
     Returns SXML element OBJ with attribute ATTR added, or `#f' if the
     attribute with given name already exists.  ATTR is `(ATTR-NAME
     ATTR-VALUE)'.  Pure functional counterpart to `sxml:add-attr!'.

 -- Function: sxml:add-attr! obj attr
     Add an attribute ATTR for an element OBJ.  Returns `#f' if the
     attribute with given name already exists.  The resulting SXML node
     is normalized.  Linear update counterpart to `sxml:add-attr'.

 -- Function: sxml:change-attr obj attr
     Returns SXML element OBJ with changed value of attribute ATTR, or
     `#f' if where is no attribute with given name.  ATTR is
     `(ATTR-NAME ATTR-VALUE)'.

 -- Function: sxml:change-attr! obj attr
     Change value of the attribute for element OBJ.  ATTR is
     `(ATTR-NAME ATTR-VALUE)'.  Returns `#f' if where is no such
     attribute.

 -- Function: sxml:set-attr obj attr
 -- Function: sxml:set-attr! obj attr
     Set attribute ATTR of element OBJ.  If there is no such attribute
     the new one is added.

 -- Function: sxml:add-aux obj aux-node
     Returns SXML element OBJ with an auxiliary node AUX-NODE added.

 -- Function: sxml:add-aux! obj aux-node
     Add an auxiliary node AUX-NODE for an element OBJ.

 -- Function: sxml:squeeze obj
 -- Function: sxml:squeeze! obj
     Eliminates empty lists of attributes and aux-lists for given SXML
     element OBJ and its descendants ("minimize" it).  Returns a
     minimized and normalized SXML element.

 -- Function: sxml:clean obj
     Eliminates empty lists of attributes and all aux-lists for given
     SXML element OBJ and its descendants.  Returns a minimized and
     normalized SXML element.


File: gauche-refe.info,  Node: SXPath auxiliary utilities,  Next: SXML to markup conversion,  Prev: SXML modifiers,  Up: manipulationg SXML structure

11.24.4 SXPath auxiliary utilities
----------------------------------

These are convenience utilities to extend SXPath functionalities.

 -- Function: sxml:add-parents obj . top-ptr
     Returns an SXML nodeset with a 'parent pointer' added.  A parent
     pointer is an aux node of the form `(*PARENT* THUNK)', where THUNK
     returns the parent element.

 -- Function: sxml:node-parent rootnode
     Returns a fast 'node-parent' function, i.e.  a function of one
     argument - SXML element - which returns its parent node using
     `*PARENT*' pointer in aux-list.  '`*TOP-PTR*' may be used as a
     pointer to root node.  It return an empty list when applyed to
     root node.

 -- Function: sxml:lookup id index
     Lookup an element using its ID.


File: gauche-refe.info,  Node: SXML to markup conversion,  Prev: SXPath auxiliary utilities,  Up: manipulationg SXML structure

11.24.5 SXML to markup conversion
---------------------------------

Procedures to generate XML or HTML marked up text from SXML.

 -- Function: sxml:clean-feed . fragments
     Filter the 'fragments'.  The fragments are a list of strings,
     characters, numbers, thunks, `#f' - and other fragments.  The
     function traverses the tree depth-first, and returns a list of
     strings, characters and executed thunks, and ignores `#f' and
     '`()'.

     If all the meaningful fragments are strings, then (APPLY
     STRING-APPEND ... ) to a result of this function will return its
     string-value.

     It may be considered as a variant of Oleg Kiselyov's
     `SRV:send-reply': While `SRV:send-reply' displays fragments, this
     function returns the list of meaningful fragments and filter out
     the garbage.

 -- Function: sxml:attr->xml attr
     Creates the XML markup for attributes.

 -- Function: sxml:string->xml string
     Return a string or a list of strings where all the occurences of
     characters `<', `>', `&', `"', or `'' in a given string are
     replaced by corresponding character entity references. See also
     `sxml:string->html'.

 -- Function: sxml:sxml->xml tree
     A version of dispatch-node specialized and optimized for SXML->XML
     transformation.

 -- Function: sxml:attr->html attr
     Creates the HTML markup for attributes.

 -- Function: sxml:string->html string
     Given a string, check to make sure it does not contain characters
     <, >, &, " that require encoding.  See also `html-escape-string'
     in *Note Simple HTML document construction::.

 -- Function: sxml:non-terminated-html-tag? tag
     This predicate yields `#t' for "non-terminated" HTML 4.0 tags.

 -- Function: sxml:sxml->html tree
     A version of dispatch-node specialized and optimized for SXML->HTML
     transformation.


File: gauche-refe.info,  Node: CSV tables,  Next: Calculate difference of text streams,  Prev: manipulationg SXML structure,  Up: Library modules - Utilities

11.25 `text.csv' - CSV tables
=============================

 -- Module: text.csv
     Provides a function to parse/generate CSV (comma separated value)
     tables.  Actually, the separater is not limited to comma; you can
     customize it.

     CSV format is widely used to exchange table-type data in plain
     text, although there are apparently no "formal" specification.

     CSV table is consisted by a series of RECORDS, separated by a
     newline.  Each record contains number of FIELDS, separated by a
     separator character (by default, a comma).  A field can contain
     comma or newline if quoted, i.e. surrounded by double-quote
     characters.  To include double-quote character in a quoted field,
     use two consecutive double-quote character.   Usually, the
     whitespaces around the field are ignored.


   Right now, the following two low-level procedures are exported.  A
plan is to provide higher features, such as labelling fields and
automatic conversions.

 -- Function: make-csv-reader separator &optional (quote-char #\")
     Returns a procedure with one argument, input port.  When the
     procedure is called, it reads one record from the port, and
     returns a list of fields.  If input reaches EOF, it returns EOF.

 -- Function: make-csv-writer separator &optional newline (quote-char
          #\")
     Returns a procedure with two arguments, output port and a list of
     fields.  When the procedure is called, it outputs a
     SEPARATOR-separated fields with proper escapes, to the output
     port.   You can also specify the record delimiter string by
     NEWLINE; for example, you can pass `"\r\n"' to prepare a file to
     be read by Windows programs.


File: gauche-refe.info,  Node: Calculate difference of text streams,  Next: Localized messages,  Prev: CSV tables,  Up: Library modules - Utilities

11.26 `text.diff' - Calculate difference of text streams
========================================================

 -- Module: text.diff
     This module calculates the difference of two text streams or
     strings, using `util.lcs' (*Note The longest common subsequence::).

 -- Function: diff src-a src-b &keyword reader eq-fn
     Generates an "edit list" from text sources SRC-A and SRC-B.

     Each of text sources, SRC-A and SRC-B, can be either an input port
     or a string.  If it is a string, it is converted to a string input
     port internally.  Then, the text streams from both sources are
     converted to sequences by calling READER repeatedly on them; the
     default of READER is `read-line', and those sequences are passed
     to `lcs-edit-list' to calculate the edit list.  The equality
     function EQ-FN is also passed to `lcs-edit-list'.

     An edit list is a set of commands that turn the text sequence from
     `src-a' to the one from `src-b'.  See the description of
     `lcs-edit-list' for the detailed explanation of the edit list.

          (diff "a\nb\nc\nd\n" "b\ne\nd\nf\n")
          =>
            (((- 0 "a"))
             ((- 2 "c") (+ 1 "e"))
             ((+ 3 "f")))

 -- Function: diff-report src-a src-b &keyword reader eq-fn writer
     A convenience procedure to take the diff of two text sources and
     display the result nicely.  This procedure calls `lcs-fold' to
     calculate the difference of two text sources.  The meanings of
     SRC-A, SRC-B, READER and EQ-FN are the same as `diff''s.

     WRITER is a procedure that takes two arguments, the text element
     and a type, which is either a symbol `+', a symbol `-', or `#f'.
     If the text element is only in SRC-A, WRITER is called with the
     element and `-'.  If the text element is only in SRC-B, it is
     called with the element and `+'.  If the text element is in both
     sources, it is called with the element and `#f'.   The default
     procedure of WRITER prints the passed text element to the current
     output port in unified-diff-like format:
          (diff-report "a\nb\nc\nd\n" "b\ne\nd\nf\n")
     displays:
          - a
            b
          - c
          + e
            d
          + f


File: gauche-refe.info,  Node: Localized messages,  Next: Simple HTML document construction,  Prev: Calculate difference of text streams,  Up: Library modules - Utilities

11.27 `text.gettext' - Localized messages
=========================================

 -- Module: text.gettext
     This module provides utilities to deal with localized messages.
     The API is compatible to GNU's gettext, and the messages are read
     from `*.po' and `*.mo' files, so that you can use the GNU texttext
     toolchain to prepare localized messages.  However, the code is
     written from scratch by Alex Shinn and doesn't depend on GNU's
     gettext library.

     This implementation extends GNU's gettext API in the following
     ways:
        * It can read from multiple message files in cascaded way,
          allowing applications to share a part of message files.

        * It supports multiple locale/domain simultaneously.

     SRFI-29 (*Note Localization::) provides another means of message
     localization.  A portable program may wish to use srfi-29, but
     generally `text.gettext' is recommended in Gauche scripts because
     of its flexibility and compatibility to existing message files.

Gettext-compatible API
----------------------

 -- Function: textdomain domain-name &optional locale dirs cdir cached?
          lookup-cached?
     Sets up the default domain and other parameters for the
     application.  The setting affects to the following `gettext' call.

     DOMAIN is a string or list of strings specifying the domain (name
     of `.mo' or `.po' files) as in C gettext.  You can pass `#f' as
     DOMAIN-NAME just to get the default domain accessor procedure.
     You can alo pass multiple domains to DOMAIN-NAME.
          (textdomain '("myapp" "gimp"))  ; search 1st myapp, then gimp
          (gettext "/File/Close")         ; "Close" from gimp unless overridden

     LOCALE is a string or list of strings in the standard Unix format
     of `LANG[_REGION][.ENCODING]'.  You can also pass a list of locales
     to specify fallbacks.

          (textdomain "myapp" '("ru" "uk"))  ; search 1st Russian then Ukranian,
          (gettext "Hello, World!")          ; which are somewhat similar

     DIRS is the search path of directories which should hold the
     `LOCALE/CDIR/' directories which contain the actual message
     catalogs.  This is always appended with the system default, e.g.
     `"/usr/share/locale"', and may also inherit from the
     `GETTEXT_PATH' colon-delimited environment variable.

     CDIR is the category directory, defaulting to either the
     `LC_CATEGORY' environment variable or the appropriate system
     default (e.g. `LC_MESSAGES').  You generally won't need this.

     CACHED?  means to cache individual messages, and defaults to `#t'.

     LOOKUP-CACHED?  means to cache the lookup dispatch generated by
     these parameters, and defaults to `#t'.

     `Textdomain' just passes these parameters to the internal
     `make-gettext', and binds the result to the global dispatch used
     by `gettext'.  You may build these closures manually for
     convenience in using multiple separate domains or locales at once
     (useful for server environments).  See the description of
     `make-gettext' below.

     `Textdomain' returns an _accessor procedure_ which packages
     information of the domain.  See `make-gettext' below for the
     details.

 -- Function: gettext msg-id
     Returns a translated message of MSG-ID.  If there's no translated
     message, MSG-ID itself is returned.

 -- Function: ngettext msg-id &optional msg-id2 num
     Similar to GETTEXT, but it can be used to handle plural forms.
     Pass a singular form to MSG-ID, and plural form to `msg-id2'.  The
     NUM argument is used to determine the plural form.  If no message
     catalog is found, MSG-ID is returnf when NUM is 1, and MSG-ID2
     otherwise.

 -- Function: bindtextdomain domain dirs
     Sets the search path of domain DOMAIN to DIRS, which may be just a
     single directory name or a list of directory names.

 -- Function: dgettext domain msg-id
 -- Function: dcgettext domain msg-id locale
     Returns a translated message of MSG-ID in DOMAIN.  `Dcgettext'
     takes LOCALE as well.

Low-level flexible API
----------------------

The following procedure is more flexible interface, on top of which the
gettext-compatible APIs are written.

 -- Function: make-gettext &optional domain locale dirs gettext-cached?
          lookup-cached?
     Creates and returns an _accessor procedure_, which encapsulates
     methods to retrieve localized messages.

     The meaning of arguments are the same as `textdomain' above.
     Indeed, `textdomain' just calls `make-gettext', and later it binds
     the result to the global parameter.   If you wish to have multiple
     independent domains within a single program, you can call
     `make-gettext' directly and manage the created accessor procedure
     by yourself.

          (define my-gettext (make-gettex "myapp"))
          (define (_ (my-gettext 'getter)))
          (_ "Hello, World!")


File: gauche-refe.info,  Node: Simple HTML document construction,  Next: Parsing input stream,  Prev: Localized messages,  Up: Library modules - Utilities

11.28 `text.html-lite' - Simple HTML document construction
==========================================================

 -- Module: text.html-lite
     Provides procedures to construct an HTML document easily.  For
     example, you can construct an HTML table by the following code:
          (html:table
            (html:tr (html:th "Item No") (html:th "Quantity"))
            (html:tr (html:td 1) (html:td 120))
            (html:tr (html:td 2) (html:td 30))
            (html:tr (html:td 3) (html:td 215)))
     See the description of `html:ELEMENT' below for details.

     This module does little check for the constructed html documents,
     such as whether the attributes are valid, and whether the content
     of the element matches DTD.  It does not provide a feature to parse
     the html document neither.  Hence the name `lite'.

 -- Function: html-escape
 -- Function: html-escape-string string
     Escapes the "unsafe" characters in HTML.  `html-escape' reads
     input string from the current input port and writes the result to
     the current output port.   `html-escape-string' takes the input
     from STRING and returns the result in a string.

 -- Function: html-doctype &keyword type
     Returns a doctype declaration for an HTML document.  TYPE can be
     either one of the followings (default is `:html-4.01-strict').
    `:html-4.01-strict, :html-4.01, :strict'
          HTML 4.01 Strict DTD

    `:html-4.01-transitional, :transitional'
          HTML 4.01 Transitional DTD

    `:html-4.01-frameset, :frameset'
          HTML 4.01 Frameset DTD

    `:xhtml-1.0-strict, :xhtml-1.0'
          XHTML 1.0 Strict DTD

    `:xhtml-1.0-transitional'
          XHTML 1.0 Transitional DTD

    `:xhtml-1.0-frameset'
          XHTML 1.0 Frameset DTD

    `:xhtml-1.1'
          XHTML 1.1 DTD

 -- Function: html:ELEMENT ARGS ...
     Construct an HTML element ELEMENT.  Right now, the following
     elements are provided.  (The elements defined in HTML 4.01 DTD,
     `http://www.w3.org/TR/html4/sgml/dtd.html').
          a        abbr       acronym    address     area      b
          base     bdo        big        blockquote  body      br
          button   caption    cite       code        col       colgroup
          dd       del        dfn        div         dl        dt
          em       fieldset   form       frame       frameset
          h1       h2         h3         h4          h5        h6
          head     hr         html       i           iframe    img
          input    ins        kbd        label       legend    li
          link     map        meta       nofrmaes    noscript  object
          ol       optgroup   option     p           param     pre
          q        samp       script     select      small     span
          strong   style      sub        sup         table     tbody
          td       textarea   tfoot      th          thead     title
          tr       tt         ul         var

     The result of these functions is a tree of text segments, which
     can be written out to a port by `write-tree' or can be converted
     to a string by `tree->string' (*Note Lazy text construction::).

     You can specify attributes of the element by using a keyword-value
     notation before the actual content.
          (tree->string (html:a :href "http://foo/bar" "foobar"))
            =>
            "<a href=\"http://foo/bar\">foobar</a>\n"

          (tree->string
            (html:table :width "100%" :cellpading 0 "content here"))
            =>
            "<table width=\"100%\" cellpadding=\"0\">content here</table>\n"

     The boolean value given to the attribute has a special meaning.
     If `#t' is given, the attribute is rendered without a value.  If
     `#f' is given, the attribute is not rendered.
          (tree->string (html:table :border #t))
            => "<table border></table>\n"

          (tree->string (html:table :border #f))
            => "<table></table>\n"

     Special characters in attribute values are escaped by the function,
     but the ones in the content are not.  It is caller's responsibility
     to escape them.

     The functions signal an error if a content is given to the HTML
     element that doesn't take a content.   They do not check if the
     given attribute is valid, neither if the given content is valid
     for the element.


File: gauche-refe.info,  Node: Parsing input stream,  Next: Transliterate characters,  Prev: Simple HTML document construction,  Up: Library modules - Utilities

11.29 `text.parse' - Parsing input stream
=========================================

 -- Module: text.parse
     A collection of utilities that does simple parsing from the input
     port.   The API is inspired, and compatible with Oleg Kiselyov's
     input parsing library (*Note OLEG1: oleg1.).  His library is used
     in lots of other libraries, notably, a full-Scheme XML
     parser/generator SSAX (*Note SSAX: ssax.).

     You can use this module in place of his `input-parse.scm' and
     `look-for-str.scm'.

     I reimplemented the functions to be efficient on Gauche.
     Especially, usage of `string-set!' is totally avoided.  I extended
     the interface a bit so that they can deal with character sets and
     predicates, as well as a list of characters.

     These functions work sequentially on the given input port, that
     is, they read from the port as much as they need, without
     buffering extra characters.

 -- Function: find-string-from-port? str in-port &optional max-no-chars
     Looks for a string STR from the input port IN-PORT.  The optional
     argument MAX-NO-CHARS limits the maximum number of characters to
     be read from the port; if omitted, the search span is until EOF.

     If STR is found, this function returns the number of characters it
     has read.   The next read from IN-PORT returns the next char of
     STR.  If STR is not found, it returns `#f'.

     Note: Although this procedure has ``?'' in its name, it may return
     non-boolean value, contrary to the Scheme convention.

 -- Function: peek-next-char &optional port
     Discards the current character and peeks the next character from
     PORT.  Useful to look ahead one character.  If PORT is omitted,
     the current input port is used.

   In the following functions, CHAR-LIST refers to one of the
followings:
   * A character set.

   * A list of characters, character sets and/or symbol `*eof*'.
   That denotes a set of characters.  If a symbol `*eof*' is included,
the EOF condition is also included.  Without `*eof*', the EOF condition
is regarded as an error.

 -- Function: assert-curr-char char-list string &optional port
     Reads a character from PORT.  If it is included in CHAR-LIST,
     returns the character.  Otherwise, signals an error with a message
     containing STRING.  If PORT is omitted, the current input port is
     used.

 -- Function: skip-until char-list/number &optional port
     CHAR-LIST/NUMBER is either a char-list or a number.  If it is a
     number; it reads that many characters and returns `#f'.  If the
     input is not long enough, an error is signalled.  If
     CHAR-LIST/NUMBER is a char-list, it reads from PORT until it sees
     a character that belongs to the char-list.  Then the character is
     returned.  If PORT is omitted, the current input port is used.

 -- Function: skip-while char-list &optional port
     Reads from PORT until it sees a character that does not belong to
     CHAR-LIST.  The character remains in the stream.  If it reaches
     EOF, an EOF is returned.  If PORT is omitted, the current input
     port is used.

     This example skips whitespaces from input.  Next read from port
     returns the first non-whitespace character.
          (skip-while #[\s] port)

 -- Function: next-token prefix-char-list break-char-list &optional
          comment port
     Skips any number of characters in PREFIX-CHAR-LIST, then collects
     the characters until it sees BREAK-CHAR-LIST.  The collected
     characters are returned as a string.  The break character remains
     in the PORT.

     If the function encounters EOF and `*eof*' is not included in
     BREAK-CHAR-LIST, an error is signalled with COMMENT is included in
     the message.

 -- Function: next-token-of char-list/pred &optional port
     Reads and collects the characters as far as it belongs to
     CHAR-LIST/PRED, then returns them as a string.  The first
     character that doesn't belong to CHAR-LIST/PRED remains on the
     port.

     CHAR-LIST/PRED may be a char-list or a predicate that takes a
     character.   If it is a predicate, each character is passed to it,
     and the character is regarded to "belong to" CHAR-LIST/PRED when
     it returns a true value.

 -- Function: read-string n &optional port
     Reads up to N characters, collects them into a string, and returns
     it.  If the input stream contains less characters, the returns
     string contains as many characters available.


File: gauche-refe.info,  Node: Transliterate characters,  Next: Lazy text construction,  Prev: Parsing input stream,  Up: Library modules - Utilities

11.30 `text.tr' - Transliterate characters
==========================================

 -- Module: text.tr
     This module implements a transliterate function, that substitutes
     characters of the input string.  This functionality is realized in
     Unix `tr(1)' command, and incorporated in various programs such as
     `sed(1)' and `perl'.

     Gauche's `tr' is aware of multibyte characters.

 -- Function: tr from-list to-list &keyword :complement :delete
          :squeeze :table-size :input :output
     Reads from INPUT and writes to OUTPUT, with transliterating
     characters in FROM-LIST to the corresponding ones in TO-LIST.
     Characters that doesn't appear in FROM-LIST are passed through.

     The default values of INPUT and OUTPUT are current input port and
     current output port, respectively.

     Both FROM-LIST and TO-LIST must be strings.  They may contain the
     following special syntax.  Other characters that doesn't fits in
     the syntax are taken as they are.

    `x-y'
          Expanded to the increasing sequence of characters from `x' to
          `y', inclusive.  The order is determined by the internal
          character encoding system; generally it is safer to limit use
          of this within the range of the same character class.   The
          character `x' must be before `y'.

    `x*n'
          Repeat `x' for `n' times.  `n' is a decimal number notation.
          Meaningful only in TO-LIST; it is an error to use this form
          in FROM-LIST.  If `n' is omitted or zero, `x' is repeated
          until TO-LIST matches the length of FROM-LIST (any character
          after it is ignored).

    ``\'x'
          Represents `x' itself.  Use this escape to avoid a special
          character to be interpreted as itself.   Note that if you
          place a backslash in a string, you must write `\\', for the
          Scheme reader also interprets backslash as a special
          character.

          There's no special sequence to represent non-graphical
          characters, for you can put such characters by the string
          syntax.

     Here's some basic examples.
          ;; swaps case of input
          (tr "A-Za-z" "a-zA-Z")

          ;; replaces 7-bit non-graphical characters to `?'
          (tr "\x00-\x19\x7f" "?*")

     If TO-LIST is shorter than FROM-LIST, the behavior depends on the
     keyword argument DELETE.  If a true value is given,  characters
     that appear in FROM-LIST but not in TO-LIST are deleted.
     Otherwise, the extra characters in FROM-LIST are just passed
     through.

     When a true value is specified to COMPLEMENT, the character set in
     FROM-LIST is complemented.  Note that it implies _huge_ set of
     characters, so it is not very useful unless either output character
     set is a single character (using `*') or used with `delete'
     keyword.

     When a true value is specified to SQUEEZE, the sequence of the
     same replaced characters is squeezed to one.  If TO-LIST is empty,
     the sequence of the same characters in FROM-LIST is squeezed.

     Internally, `tr' builds a table to map the characters for
     efficiency.  Since Gauche can deal with potentially huge set of
     characters, it limits the use of the table for only smaller
     characters (<256 by default).  If you want to transliterate
     multibyte characters on the large text, however, you might want to
     use larger table, trading off the memory usage.  You can specify
     the internal table size by TABLE-SIZE keyword argument.  For
     example, if you transliterate lots of EUC-JP hiragana text to
     katakana, you may want to set table size greater than 42483 (the
     character code of the last katakana).

     Note that the pre-calculation to build the transliterate table
     needs some overhead.  If you want to call `tr' many times inside
     loop, consider to use `build-transliterator' described below.

 -- Function: string-tr string from-list to-list &keyword :complement
          :delete :squeeze :table-size
     Works like `tr', except that input is taken from a string STRING.

 -- Function: build-transliterator from-list to-list &keyword
          :complement :delete :squeeze :table-size :input :output
     Returns a procedure that does the actual transliteration.  This
     effectively "pre-compiles" the internal data structure.   If you
     want to run `tr' with the same sets repeatedly, you may build the
     procedure once and apply it repeatedly, saving the overhead of
     initialization.

     A note for an edge case: When INPUT and/or OUTPUT keyword
     arguments are omitted, the created transliterator is set up to use
     current-input-port and/or current-output-port at the time
     transliterator is called.

          (with-input-from-file "huge-file.txt"
            (lambda ()
              (let loop ((line (read-line)))
                (unless (eof-object? line) (tr "A-Za-z" "a-zA-Z")))))

          ;; runs more efficiently...

          (with-input-from-file "huge-file.txt"
            (lambda ()
              (let ((ptr (build-transliterator "A-Za-z" "a-zA-Z")))
                (let loop ((line (read-line)))
                  (unless (eof-object? line) (ptr))))))



File: gauche-refe.info,  Node: Lazy text construction,  Next: Combination library,  Prev: Transliterate characters,  Up: Library modules - Utilities

11.31 `text.tree' - Lazy text construction
==========================================

 -- Module: text.tree
     Defines simple but commonly used functions for a text construction.

     When you generate a text by a program, It is a very common
     operation to concatenate text segments.  However, using
     string-append repeatedly causes unnecessary copying of
     intermediate strings, and sometimes such intermediate strings are
     discarded due to the error situation (for example, think about
     constucting an HTML document in the CGI script).

     The efficient technique is to delay concatenation of those text
     segments until it is needed.  In Scheme it is done very easily by
     just consing the text segments together, thus forming a tree of
     text, and then traverse the tree to construct a text.  You can
     even directly writes out the text during traversal, avoiding
     intermediate string buffer.  (Hans Boehm's "cord" library, which
     comes with his garbage collector library, uses this technique and
     proves it is very efficient for editor-type application).

     Although the traversal of the tree can be written in a few lines
     of Scheme, I provide this module in the spirits of
     OnceAndOnlyOnce.   Also it's easier if we have a common interface.

 -- Generic Function: write-tree tree &optional out
     Writes out an TREE as a tree of text, to the output port OUT.  If
     OUT is omitted, the current output port is used.

     Two methods are defined for this generic function, as shown below.
     If you have more complex behavior, you can define more methods to
     customize the behavior.

 -- Method: write-tree ((tree <list>) out)
 -- Method: write-tree ((tree <top>) out)
     Default methods.  For a list, `write-tree' is recursively called
     for each element.  Any objects other than list is written out
     using `display'.

 -- Function: tree->string tree
     Just calls the `write-tree' method for TREE using an output string
     port, and returns the result string.


File: gauche-refe.info,  Node: Combination library,  Next: Message digester framework,  Prev: Lazy text construction,  Up: Library modules - Utilities

11.32 `util.combinations' - Combination library
===============================================

 -- Module: util.combinations
     This module implements several useful procedures of combinations,
     permutations and related operations.

     Most procedures in the module have two variants: a procedure
     without star (e.g. `permutations') treats all elements in the given
     set distinct, while a procedure with star (e.g. `permutations*')
     considers duplication.  The procedures with star take optional EQ
     argument that is used to test equality, which defaults to `eqv?'.

 -- Function: permutations set
 -- Function: permutations* set &optional eq
     Returns a list of all permutations of a list SET.

          (permutations '(a b c))
            => ((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))

          (permutations '(a a b))
            => ((a a b) (a b a) (a a b) (a b a) (b a a) (b a a))

          (permutations* '(a a b))
            => ((a a b) (a b a) (b a a))

     The number of possible permutations explodes if SET has more than
     several elements.  Use with care.  If you want to process each
     permutation at a time, consider `permutations-for-each' below.

 -- Function: permutations-for-each proc set
 -- Function: permutations*-for-each proc set &optional eq
     For each permutation of a list SET, calls PROC.  Returns an
     undefined value.

 -- Function: combinations set n
 -- Function: combinations* set n &optional eq
     Returns a list of all possible combinations of N elements out of a
     list SET.

          (combinations '(a b c) 2)
            => ((a b) (a c) (b c))

          (combinations '(a a b) 2)
            => ((a a) (a b) (a b))

          (combinations* '(a a b) 2)
            => ((a a) (a b))

     Watch out the explosion of combinations when SET is large.

 -- Function: combinations-for-each proc set n
 -- Function: combinations*-for-each proc set n &optional eq
     Calls PROC for each combination of N elements out of SET.  Returns
     an undefined value.

 -- Function: power-set set
 -- Function: power-set* set &optional eq
     Returns power set (all subsets) of a list SET.

          (power-set '(a b c))
            => (() (a) (b) (c) (a b) (a c) (b c) (a b c))

          (power-set* '(a a b)
            => (() (a) (b) (a a) (a b) (a a b))

 -- Function: power-set-for-each proc set
 -- Function: power-set*-for-each proc set &optional eq
     Calls PROC for each subset of SET.

 -- Function: power-set-binary set
     Returns power set of SET, like `power-set', but in different order.
     `Power-set-binary' traverses subset space in depth-first order,
     while `power-set' in breadth-first order.

          (power-set-binary '(a b c))
            => (() (c) (b) (b c) (a) (a c) (a b) (a b c))

 -- Function: cartesian-product list-of-sets
 -- Function: cartesian-product-right list-of-sets
     Returns a cartesian product of sets in LIST-OF-SETS.
     `Cartesian-product' construct the result in left fixed order (the
     rightmost element varies first), while `cartesian-product-right'
     in right fixed order (the leftmost element varies first).

          (cartesian-product '((a b c) (0 1)))
            => ((a 0) (a 1) (b 0) (b 1) (c 0) (c 1))

          (cartesian-product-right '((a b c) (0 1)))
            => ((a 0) (b 0) (c 0) (a 1) (b 1) (c 1))


File: gauche-refe.info,  Node: Message digester framework,  Next: Determine isomorphism,  Prev: Combination library,  Up: Library modules - Utilities

11.33 `util.digest' - Message digester framework
================================================

 -- Module: util.digest
     This module provides a base class and common interface for message
     digest algorithms, such as MD5 (*Note MD5 message digest::) and
     SHA1 (*Note SHA1 message digest::).

 -- Class: <message-digest-algorithm-meta>
     A metaclass of message digest algorithm implementation.

 -- Class: <message-digest-algorithm>
     A base class of message digest algorithm implementation.

   The concrete subclass of message digest algorithm has to implement
the following methods.

 -- Generic function: digest-update! algorithm data
     Takes the instance of massage-digest algorithm, and updates it
     with the data DATA, represented in a (possibly incomplete) string.

 -- Generic function: digest-final! algorithm
     Finalizes the instance of message-digest algorithm, and returns
     the digest result in an incomplete string.

 -- Generic function: digest class
     A wrapper of digest routines.  Given message-digest algorithm
     CLASS, this function reads the input data from current input port
     until EOF, and returns the digest result in an incomplete string.

 -- Generic function: digest-string class string
     A wrapper of digest routines.  Given message-digest algorithm
     CLASS, this function reads the input data from STRING, and returns
     the digest result in an incomplete string.

 -- Function: digest-hexify digest-result
     An utility procedure.  Given the result of digest, DIGEST-RESULT,
     converts it to a hexified string.


File: gauche-refe.info,  Node: Determine isomorphism,  Next: The longest common subsequence,  Prev: Message digester framework,  Up: Library modules - Utilities

11.34 `util.isomorph' - Determine isomorphism
=============================================

 -- Module: util.isomorph
     Provides a procedure that determines whether two structures are
     isomorphic.

 -- Function: isomorphic? obj1 obj2 &optional context
     Returns `#t' if OBJ1 and OBJ2 are isomorphic.

     CONTEXT is used if you want to call `isomorphic?' recursively
     inside `object-isomorphic?' described below.

          (isomorphic? '(a b) '(a b)) => #t

          (define x (cons 0 0))
          (define y (cons 0 0))
          (isomorphic? (cons x x)
                       (cons x y))
           => #f
          (isomorphic? (cons x x)
                       (cons y y))
           => #t

 -- Generic Function: object-isomorphic? obj1 obj2 context
     With this method, you can customize how to determine isomorphism of
     two objects.  Basically, you will call `isomorphic?' recursively
     for each slots of object you want to traverse; the method should
     return `#t' if all of the test succeeds, or return `#f' otherwise.
     CONTEXT is an opaque structure that keeps the traversal context,
     and you should pass it to `isomorphic?' as is.

     The default method returns `#t' if OBJ1 and OBJ2 are equal (in the
     sense of `equal?').


File: gauche-refe.info,  Node: The longest common subsequence,  Next: Additional list library,  Prev: Determine isomorphism,  Up: Library modules - Utilities

11.35 `util.lcs' - The longest common subsequence
=================================================

 -- Module: util.lcs
     This module implements the algorithm to find the longest common
     subsequence of two given sequences.  The implemented algorithm is
     based on Eugene Meyers' O(ND) algorithm (*Note [Meyers86]:
     meyers86.).

     One of the applications of this algorithm is to calculate the
     difference of two text streams; see *Note Calculate difference of
     text streams::.

 -- Function: lcs seq-a seq-b &optional eq-fn
     Calculates and returns the longest common sequence of two lists,
     SEQ-A and SEQ-B.  Optional EQ-FN specifies the comparison
     predicate; if omitted, `equal?' is used.

          (lcs '(x a b y) '(p a q b))
           => (a b)

 -- Function: lcs-with-positions seq-a seq-b &optional eq-fn
     This is the detailed version of `lcs'.  The arguments are the same.

     Returns a list of the following structure:

          (LENGTH ((ELT A-POS B-POS) ...))

     LENGTH is an integer showing the length of the found LCS.  What
     follows is a list of elements of LCS; each sublist consists of the
     element, the integer position of the element in SEQ-A, then the
     integer position of the element in SEQ-B.

          (lcs-with-positions '(a) '(a))
           => (1 ((a 0 0)))

          (lcs-with-positions '(x a b y) '(p q a b))
           => (2 ((a 1 2) (b 2 3)))

          (lcs-with-positions '(x a b y) '(p a q b))
           => (2 ((a 1 1) (b 2 3)))

          (lcs-with-positions '(x y) '(p q))
           => (0 ())

 -- Function: lcs-fold a-proc b-proc both-proc seed a b &optional eq-fn
     A fundamental iterator over the "edit list" derived from two lists
     A and B.

     A-PROC, B-PROC, BOTH-PROC are all procedures that take two
     arguments.   The second argument is a intermediate state value of
     the calculation.  The first value is an element only in A for
     A-PROC, or an element only in B for B-PROC, or an element in both
     A and B for BOTH-PROC.  The return value of each procedure is used
     as the state value of the next call of either one of the
     procedures.  SEED is used as the initial value of the state value.
     The last state value is returned from `lcs-fold'.

     The three procedures are called in the following order: Suppose
     the sequence A consists of A'CA", and B consists of B'CB", where
     A', B', A", and B" are subsequences, and C is the head of the LCS
     of A and B.   Then A-PROC is called first on each element in A',
     B-PROC is called second on each element in B', then BOTH-PROC is
     called on C.  Afterwards, the process is repeated using A" and B".

 -- Function: lcs-edit-list a b &optional eq-fn
     Calculates 'edit-list' from two lists A and B, which is the
     smallest set of commands (additions and deletions) that changes A
     into B.  This procedure is built on top of `lcs-fold' above.

     Returns a list of _hunk_s, which is a contigous section of
     additions and deletions.  Each hunk consists of a list of
     directives, which is a form of:
          (+|- POSITION ELEMENT)

     Here's an example.  Suppose A and B are the following lists,
     respectively.

          A == ("A" "B" "C" "E" "H" "J" "L" "M" "N" "P")
          B == ("B" "C" "D" "E" "F" "J" "K" "L" "M" "R" "S" "T")

     Then, `(lcs-edit-list a b equal?)' returns the following list.
          (((- 0 "A"))
           ((+ 2 "D"))
           ((- 4 "H") (+ 4 "F"))
           ((+ 6 "K"))
           ((- 8 "N") (- 9 "P") (+ 9 "R") (+ 10 "S") (+ 11 "T"))
          )
     The result consists of five hunks.  The first hunk consists of one
     directive, `(- 0 "A")', which means the element `"A"' at the
     position 0 of list A has to be deleted.  The second hunk also
     consists of one directive, `(+ 2 "D")', meaning the element `"D"'
     at the position 2 of list B has to be added.  The third hunk means
     `"H"' at the position 4 of list A should be removed and `"F"' at
     the position 4 of list B should be added, and so on.

     If you are familiar with Perl's Algorithm::Diff module, you may
     notice that this is the same structure that its `diff' procedure
     returns.


File: gauche-refe.info,  Node: Additional list library,  Next: Pattern matching,  Prev: The longest common subsequence,  Up: Library modules - Utilities

11.36 `util.list' - Additional list library
===========================================

 -- Module: util.list
     This module provides list utility functions which are not in srfi-1
     (*Note List library::) but generally useful.

     See also *Note Collection framework:: and *Note Sequence
     framework::, for these modules also defines useful generic
     functions that can be used for lists.

 -- Function: take* list k &optional fill? padding
     Returns a list that consists of the first K elements in LIST, like
     SRFI-1's `take', except this procedure is more tolerant.  That is,
     if LIST is shorter than K, `take*' doesn't signals an error.
     Instead, it returns a copy of LIST by default (or the optional
     argument FILL? is `#f').   If FILL? is true, PADDING is added to
     the result to make its length K.  The default value of PADDING is
     `#f'.

          (take* '(a b c d) 3)       => (a b c)
          (take* '(a b c d) 6)       => (a b c d)
          (take* '(a b c d) 6 #t)    => (a b c d #f #f)
          (take* '(a b c d) 6 #t 'z) => (a b c d z z)

     Note: For generic subsequence extraction from any sequence, see
     `subseq' in *Note Slicing sequence::.

 -- Function: drop* list k
     Returns a list that the first K elements of LIST is dropped, like
     SRFI-1's `drop', except this procedure is more tolerant.  If LIST
     is shorter than K, an empty list is returned.

          (drop* '(a b c d) 3)       => (d)
          (drop* '(a b c d) 5)       => ()

 -- Function: take-right* list k &optional fill? padding
     Like `take*', but counts from right of LIST.  If needed, PADDING
     is added on left of the result.

 -- Function: drop-right* list k
     Like `drop*', but counts from right of LIST.

 -- Function: split-at* list k &optional fill? padding
     More tolerant version of SRFI-1's `split-at'.  Returns the results
     of `take*' and DROP*.

          (split-at* '(a b c d) 6 #t 'z)
            => (a b c d z z) and ()

 -- Function: slices list k &optional fill? padding
     Splits LIST into the sublists (slices) where the length of each
     slice is K.  If the length of LIST is not a multiple of K, the
     last slice is dealt in the same way as `take*'; that is, it is
     shorter than K by default, or added PADDING if FILL? is true.

          (slices '(a b c d e f g) 3)
            => ((a b c) (d e f) (g))
          (slices '(a b c d e f g) 3 #t 'z)
            => ((a b c) (d e f) (g z z))

 -- Function: intersperse item list
     Inserts ITEM between elements in the LIST.  (The order of
     arguments is taken from Haskell's intersperse).

          (intersperse '+ '(1 2 3))  => (1 + 2 + 3)
          (intersperse '+ '(1))      => (1)
          (intersperse '+ '())       => ()

 -- Macro: cond-list clause ...
     Construct a list by conditionally adding entries.  Each CLAUSE has
     a test and expressions.  When its test yields true, the result of
     associated expression is used to construct the resulting list.
     When the test yields false, nothing is inserted.

     CLAUSE must be either one of the following form:
    `(TEST EXPR ...)'
          TEST is evaluated, and when it is true, EXPR ... are
          evaluated, and the return value becomes a part of the result.
          If no EXPR is given, the result of TEST is used if it is not
          false.

    `(TEST => PROC)'
          TEST is evaluated, and when it is true, PROC is called with
          the value, and the return value is used to construct the
          result.

          (let ((alist '((x 3) (y -1) (z 6))))
           (cond-list ((assoc 'x alist) 'have-x)
                      ((assoc 'w alist) 'have-w)
                      ((assoc 'z alist) => cadr)))
            => (have-x 6)

 -- Function: alist->hash-table alist &optional cmp
     Creates and returns a hash table that has entries of each element
     in alist, using its car as the key and its cdr as the value.  CMP
     is a symbol specifying the comparison function of the created hash
     table; currently `eq?', `eqv?', `equal?' and `string=?' are
     supported.

 -- Function: hash-table->alist hash-table
            (hash-table-map h cons)

 -- Function: rassoc key alist &optional eq-fn
 -- Function: rassq key alist
 -- Function: rassv key alist
     Reverse associations--given KEY is matched to the _cdr_ of each
     element in ALIST, instead of the _car_.  Handy to realize
     bidirectional associative list.  `Rassoc' takes an optional
     comparison function, whose default is `equal?'.  `Rassq' and
     `rassv' uses EQ? and EQV?.

 -- Function: assoc-ref alist key &optional default eq-fn
 -- Function: assq-ref alist key &optional default
 -- Function: assv-ref alist key &optional default
     These procedures provide the access to the assoc list symmetric
     with other *-ref procedures.  This captures the common pattern of
     alist access:
          (assoc-ref alist key default eq-fn)
           ==
            (cond ((assoc key alist eq-fn) => cdr)
                  (else default))))

     If DEFAULT is omitted, `#f' is used.

     `Assoc-ref' takes an optional comparison function EQ-FN, whose
     default is `equal?'.  `Assq-ref' and `assv-ref' uses `eq?' and
     `eqv?', respectively.

 -- Function: rassoc-ref alist key &optional default eq-fn
 -- Function: rassq-ref alist key &optional default
 -- Function: rassv-ref alist key &optional default
     Reverse association version of `assoc-ref'.
          (rassoc-ref alist key default eq-fn)
           ==
            (cond ((rassoc key alist eq-fn) => car)
                  (else default))))
     The meanings of optional arguments are the same as `assoc-ref'.

 -- Function: assoc-set! alist key val &optional eq-fn
 -- Function: assq-set! alist key val
 -- Function: assv-set! alist key val
     Returns an alist who has `(key . val)' pair added to the `alist'.
     If `alist' already has an element with KEY, the element's _cdr_ is
     destructively modified for VAL.  If ALIST doesn't have an element
     with KEY, a new pair is created and appended in front of ALIST; so
     you should use the return value to guarantee KEY-VAL pair is added.

     `Assoc-set!' takes optional comparison function EQ-FN, whose
     default is `equal?'.  `Assq-set!' and `assv-set!' uses `eq?' and
     `eqv?', respectively.


File: gauche-refe.info,  Node: Pattern matching,  Next: Queue,  Prev: Additional list library,  Up: Library modules - Utilities

11.37 `util.match' - Pattern matching
=====================================

 -- Module: util.match
     This module is a port of Andrew Wright's pattern matching macro
     library.  It is widely used in Scheme world, and ported to various
     Scheme implementations, including Chez Scheme, PLT Scheme,
     Scheme48, Chicken, and SLIB.  It is similar to, but more powerful
     than Common Lisp's `destructuring-bind'.

     This version retains compatibility of the original Wright's macro,
     except (1) BOX is not supported since Gauche doesn't have one, and
     (2) structure matching is integrated to Gauche's object system.

   We show a list of APIs first, then the table of complete syntax of
patterns, folowed by examples.

Pattern matching API
--------------------

 -- Macro: match expr clause ...
     Each CLAUSE is either one of the followings:
          (PAT BODY ...)
          (PAT (=> IDENTIFIER) BODY ...)

     First, the EXPR is matched against PAT of each clauses.  The
     detailed syntax of the pattern is explained below.

     If a matching PAT is found, the _pattern variables_ in PAT are
     bound to the corresponding elements in EXPR, then BODY ... are
     evaluated.  Then `match' returns the value(s) of the last
     expression of BODY ....

     If the clause is the second form, IDENTIFIER is also bound to the
     failure continuation of the CLAUSE.  It is a procedure with no
     arguments, and when called, it jumps back to the matcher as if the
     matching of PAT is failed, and `match' continues to try the rest
     of clauses.  So you can perform extra tests within BODY ... and if
     you're not satisfied you can reject the match by calling
     `(IDENTIFIER)'.  See the examples below for more details.

     If no PAT matches, `match' reports an error.

 -- Macro: match-lambda clause ...
     Creates a function that takes one argument and performs `match' on
     it, using CLAUSE ....  It's functionally equivalent to the
     following expression:
          (lambda (expr) (match expr CLAUSE ...))

 -- Macro: match-lambda* clause ...
     Like `match-lambda', but performs `match' on the list of whole
     arguments.  It's functionally equivalent to the following
     expression:
          (lambda expr (match expr CLAUSE ...))

 -- Macro: match-let ((pat expr) ...) body-expr ...
 -- Macro: match-let name ((pat expr) ...) body-expr ...
 -- Macro: match-let* ((pat expr) ...) body-expr ...
 -- Macro: match-letrec ((pat expr) ...) body-expr ...
     Generalize `let', `let*', and `letrec' to allow patterns in the
     binding position rather than just variables.  Each EXPR is
     evaluated, and then matched to PAT, and the bound pattern
     variables are visible in BODY-EXPR ....

          (match-let (
                       (((ca . cd) ...)   '((a . 0) (b . 1) (c . 2)))
                     )
            (list ca cd))
           => ((a b c) (0 1 2))

     If you're sick of parenthesis, try `match-let1' below.

 -- Macro: match-let1 pat expr body-expr ...
     This is a Gauche extension and isn't found in the original
     Wright's code.  This one is equivalent to the following code:
          (match-let ((PAT EXPR)) BODY-EXPR ...)

     Syntactically, `match-let1' is very close to the Common Lisp's
     `destructuring-bind'.

 -- Macro: match-define pat expr
     Like toplevel `define', but allows a pattern instead of variables.

Pattern syntax
--------------

Here's a summary of pattern syntax. The asterisk `(*)' after
explanation means Gauche's extension which does not present in the
original Wright's code.

     pat : patvar                       ;; anything, and binds pattern var
         | _                            ;; anything
         | ()                           ;; the empty list
         | #t                           ;; #t
         | #f                           ;; #f
         | string                       ;; a string
         | number                       ;; a number
         | character                    ;; a character
         | keyword                      ;; a keyword (*)
         | 'sexp                        ;; an s-expression
         | 'symbol                      ;; a symbol (special case of s-expr)
         | (pat1 ... patN)              ;; list of n elements
         | (pat1 ... patN . patN+1)     ;; list of n or more
         | (pat1 ... patN patN+1 ooo)   ;; list of n or more, each element
                                        ;;   of remainder must match patN+1
         | #(pat1 ... patN)             ;; vector of n elements
         | #(pat1 ... patN patN+1 ooo)  ;; vector of n or more, each element
                                        ;;   of remainder must match patN+1
         | ($ class pat1 ... patN)      ;; an object (patK matches in slot order)
         | (struct class pat1 ... patN) ;; ditto (*)
         | (@ class (slot1 pat1) ...)   ;; an object (using slot names) (*)
         | (object class (slot1 pat1) ...) ;; ditto (*)
         | (= proc pat)                 ;; apply proc, match the result to pat
         | (and pat ...)                ;; if all of pats match
         | (or pat ...)                 ;; if any of pats match
         | (not pat ...)                ;; if all pats don't match at all
         | (? predicate pat ...)        ;; if predicate true and all pats match
         | (set! patvar)                ;; anything, and binds setter
         | (get! patvar)                ;; anything, and binds getter
         | `qp                          ;; a quasi-pattern

     patvar : a symbol except _, quote, $, struct, @, object, =, and, or,
              not, ?, set!, get!, backquote, ..., ___, ..k, __k.

     ooo : ...                          ;; zero or more
         | ___                          ;; zero or more
         | ..k                          ;; k or more
         | __k                          ;; k or more

   * A bare symbol is a "pattern variable"; it matches anything, and
     the matched part of the expression is bound to the symbol.  The
     following symbols have special meanings and cannot be used as a
     pattern variable: `_', `quote', `$', `struct', `@', `object', `=',
     `and', `or', `not', `?', `set!', `get!', `backquote', `...',
     `___', and `..k' and `__k' where _k_ is an integer.

   * A symbol `_' matches anything, without binding a patter variable.
     It can be used to show "don't care" placeholoder.

   * Literals such as emptylist, booleans, strings, numbers, characters
     and keywords match the same object (in the sense of `equal?').

   * Quoted expression matches the same experssion (in the sense of
     `equal?').  You can use a quoted symbol to match the symbol itself.

   * A list and a vector in general match a list or a vector whose
     elements matches the elements in the pattern recursively, unless
     the first element of the list is one of the special symbols listed
     above, it has a special meaning.

     As a special case, the last element of a vector or a list can be
     followed by a symbol `...'.  In that case, the pattern just before
     the symbol `...' can be applied repeatedly until it consumes all
     the elements in the given expression.  A symbol `___' can be used
     in place of `...'; it is useful when you want to produce a pattern
     by syntax-rules macro.

     For a list pattern, you can also use a symbol `..1', `..2', ...,
     which specifies the minimum number of repetition.

   * `($ class pat1 ...)' matches an instance of a class `class'.  Each
     pattern `pat1' ... matches each value of slots, in order of
     `(class-slots class)'.

     `(struct class pat1 ...)' has the same meaning.  Although the
     original Wright's code doesn't have `struct', PLT Scheme has it in
     its extended match feature, and it is more descriptive.

     This is an adaptation of the original feature that can match
     structures.  It is useful to match a simple instance that you know
     the order of slots; for example, a simple record created by srfi-9
     (*Note Record types::) would be easy to match by positioned values.

     If the instance's class uses inheritances, it is a bit difficult to
     match by positions.  You can use `@' or `object' pattern below to
     match using slot names.

   * `(object class (slot1 pat1) ...)' matches an instance of a class
     `class' whose value of SLOT1 ... matches PAT1 ....  This is
     Gauche's extension.  `@' can be used in place of `object', but
     `object' is recommended because of descriptiveness.

   * `(= proc pat)' first applies PROC to the corresponding expression,
     then match the result with PAT.

   * `(and pat ...)', `(or pat ...)', and `(not pat ...)' are boolean
     operations of patterns.

   * `(? predicate pat ...)' first applies a predicate to the
     corresponding expression, and if it returns true, applies each
     `pat' ... to the expression.

   * `(set! patvar)' matches anything, and binds an one-argument
     procedure to a pattern variable PATVAR.  If the procedure is
     called, it replaces the value of matched pattern for the given
     argument.

   * `(get! patvar)' matches anything, and binds a zero-argument
     procedure to a pattern variable PATVAR.  If the procedure is
     called, it returns the matched value.

   * ``qp' is a quasipattern.  QP is quoted, in the sense that it
     matches itself, _except_ the pattern that is unquoted.  (Don't
     confuse quasipatern to quasiquote, though the functions are
     similar.  Quasiquote turns off evaluation except unquoted subtree.
     Quasiquote turns off the special pattern syntax except unquoted
     subtree.  See the examples below).

Pattern examples
----------------

A simple structure decomposition:
     (match '(0 (1 2) (3 4 5))
       ((a (b c) (d e f))
        (list a b c d e f)))
      => (0 1 2 3 4 5)

   Using predicate patterns:
     (match 123
       ((? string? x) (list 'string x))
       ((? number? x) (list 'number x)))
      => (number 123)

   Extracting variables and expressions from `let'.  Uses repetition
and predicate patterns:
     (define let-analyzer
       (match-lambda
         (('let (? symbol?)
                ((var expr) ...)
            body ...)
          (format "named let, vars=~s exprs=~s" var expr))
         (('let ((var expr) ...)
            body ...)
          (format "normal let, vars=~s exprs=~s" var expr))
         (_
          (format "malformed let"))))

     (let-analyzer '(let ((a b) (c d)) e f g))
      => "normal let, vars=(a c) exprs=(b d)"

     (let-analyzer '(let foo ((x (f a b)) (y (f c d))) e f g))
      => "named let, vars=(x y) exprs=((f a b) (f c d))"

     (let-analyzer '(let (a) b c d))
      => "malformed let"

   Using `=' function application.  The pattern variable M is matched
to the result of application of the regular expression.
     (match "gauche-ref.texi"
       ((? string? (= #/(.*)\.([^.]+)$/ m))
        (format "base=~a suffix=~a" (m 1) (m 2))))
      => "base=gauche-ref suffix=texi"

   An example of quasipattern.   In the first expression, the pattern
except `value' is quoted, so the symbols `the', `answer', and `is' are
not pattern variables but literal symbols.   The second expression
shows that; input symbol `was' does not match the literal symbol `is'
in the pattern.  If we don't use quasiquote, all symbols in the pattern
are pattern variables, so any four-element list matches as the third
expression shows.
     (match '(the answer is 42)
       (`(the answer is ,value) value)
       (else #f))
      => 42

     (match '(the answer was 42)
       (`(the answer is ,value) value)
       (else #f))
      => #f

     (match '(a b c d)
       ((the answer is value) value)
       (else #f))
      => d


File: gauche-refe.info,  Node: Queue,  Next: SLIB-compatible record type,  Prev: Pattern matching,  Up: Library modules - Utilities

11.38 `util.queue' - Queue
==========================

 -- Module: util.queue
     Provides a queue (FIFO).   This implementation is tuned for speed
     than safety; a queue is simply a pair that keeps head and tail of
     the queue, and minimal check is done in most of the operations.

     SLIB (*Note SLIB::) provides the queue library that is safer.
     This API is upper compatible to the SLIB's.  The idea is that this
     queue is used inside other procedure or structure that you know
     you don't need the strict checks.  Use either one depending on
     your requirement.

 -- Function: make-queue
     Creates and returns an empty queue.

 -- Function: queue? obj
     Returns `#t' if OBJ is a queue.  This operation checks OBJ is
     really in a shape of the queue.

 -- Function: queue-empty? queue
     Returns `#t' if OBJ is an empty queue.

 -- Function: queue-length queue
     Returns the number of the items in the queue.

 -- Function: enqueue! queue obj &optional more-objs ...
     Add OBJ to the end of QUEUE.  You may give more than one object,
     and each of them are enqueued in order.  (Note: SLIB version
     doesn't take the optional arguments).

 -- Function: queue-push! queue obj &optional more-objs ...
     Add OBJ in front of QUEUE.  You may give more than one object, and
     each of them are pushed in order.  (Note: SLIB version doesn't
     take the optional arguments).

 -- Function: enqueue-unique! queue eq-proc obj &optional more-objs ...
 -- Function: queue-push-unique! queue eq-proc obj &optional more-objs
          ...
     Like `enqueue!' and `queue-push!', respectively, except that these
     don't modify QUEUE if it already contains OBJ (elements are
     compared by two-argument procedure EQ-PROC).

 -- Function: dequeue! queue
 -- Function: queue-pop! queue
     Take one object from the front of the queue QUEUE and returns it.
     Both function works the same, but `queue-pop!' may be used to
     emphasize it works with `queue-push!'.  An error is signalled if
     QUEUE is empty.

 -- Function: dequeue-all! queue
     Returns the whole content of the queue by a list, with emptying
     QUEUE.   If QUEUE is already empty, returns an empty list.  See
     also `queue->list' below.

 -- Function: queue-front queue
 -- Function: queue-rear queue
     Peek the head or the tail of the queue and returns the object,
     respectively.  UTIL.QUEUE - QUEUE is not modified.  An error is
     signalled if QUEUE is empty.

 -- Function: list->queue list
     Returns a new queue whose content is the elements in LIST, in the
     given order.

 -- Function: queue->list queue
     Returns a list whose content is the items in the queue in order.
     Unlike `dequeue-all!', the content of QUEUE remains intact.

     In Gauche, `queue->list' copies the content of the queue to a
     freshly allocated list, while `dequeue-all!' doesn't copy but
     directly returns the queue's internal list.   There are some Scheme
     systems that has `queue->list' but doesn't guarantee the content
     is copied, so if you're planning to share the code among these
     implementations, it's better not to rely on the fact that
     `queue->list' copies the content.

 -- Function: find-in-queue pred queue
     Returns the first item in QUEUE that satisfies a predicate PRED.
     The order of arguments follows `find' in SRFI-1 (*Note SRFI-1
     Searching::).

 -- Function: remove-from-queue! pred queue
     Removes all items in the queue that satisfies PRED.  Returns `#t'
     if any item is removed.  Otherwise returns `#f'.  The order of
     arguments follows `remove' in SRFI-1 (*Note SRFI-1 Filtering &
     Partitioning::).

   Note on portability: Scheme48 has `delete-from-queue!', which takes
object to remove rather than predicate, and also takes arguments in
reversed order (i.e. queue comes first).   Avoid conflicting with that
I intentionally left out `delete-from-queue!'; it's easy to write one
in either Scheme48 compatible way or consistent to SRFI-1 argument
order.


File: gauche-refe.info,  Node: SLIB-compatible record type,  Next: Topological sort,  Prev: Queue,  Up: Library modules - Utilities

11.39 `util.record' - SLIB-compatible record type
=================================================

 -- Module: util.record
     This module provides a Guile and SLIB compatible record type API.
     It is built on top of Gauche's object system.

     See also *Note Record types::, which provides a convenience macro
     `define-record-type'.

 -- Function: make-record-type type-name field-names
     Returns a new class which represents a new record type.  (It is
     what is called _record-type descriptor_ in SLIB).  In Gauche, the
     new class is a subclass of `<record>' (see *Note Record types::).

     TYPE-NAME is a string that is used for debugging purposes.  It is
     converted to a symbol and set as the name of the new class.
     FIELD-NAMES is a list of symbols of the names of fields.  Each
     field is implemented as a slot of the new class.

   In the following procedures, RTD is the record class created by
`make-record-type'.

 -- Function: record-constructor rtd &optional field-names
     Returns a procedure that constructs an instance of the record type
     of given RTD.  The returned procedure takes exactly as many
     arguments as FIELD-NAMES, which defaults to `'()'.  Each argument
     sets the initial value of the corresponding field in FIELD-NAMES.

 -- Function: record-predicate rtd
     Returns a procedure that takes one argument, which returns `#t'
     iff the given argument is of type of RTD.

 -- Function: record-accessor rtd field-name
     Returns an accessor procedure for the field named by FIELD-NAME of
     type RTD.  The accessor procedure takes an instance of RTD, and
     returns the value of the field.

 -- Function: record-modifier rtd field-name
     Returns a modifier procedure for the field named by FIELD-NAME of
     type RTD.  The modifier procedure takes two arguments, an instance
     of RTD and a value, and sets the value to the specified field.

     (define rtd (make-record-type "my-record" '(a b c)))

     rtd => #<class my-record>

     (define make-my-record (record-constructor rtd '(a b c)))

     (define obj (make-my-record 1 2 3))

     obj => #<my-record 0x819d9b0>

     ((record-predicate? rtd) obj)  => #t

     ((record-accessor rtd 'a) obj) => 1
     ((record-accessor rtd 'b) obj) => 2
     ((record-accessor rtd 'c) obj) => 3

     ((record-modifier rtd 'a) obj -1)

     ((record-accessor rtd 'a) obj) => -1


File: gauche-refe.info,  Node: Topological sort,  Next: CGI Utility,  Prev: SLIB-compatible record type,  Up: Library modules - Utilities

11.40 `util.toposort' - Topological sort
========================================

 -- Module: util.toposort
     Implements topological sort algorithm.

 -- Function: topological-sort graph &optional eqproc
     GRAPH represents a directed acyclic graph (DAG) by a list of
     connections, where each connection is the form
          (<node> <downstream> <downstream2> ...)
     that means a node `<node>' is connected to other nodes
     `<downstream>' etc.   `<node>' can be arbitrary object, as far as
     it can be compared by the procedure EQPROC, which is EQV? by
     default (*Note Equivalence::).  Returns a list of `<node>'s sorted
     topologically.

     If the graph contains circular reference, an error is signalled.


File: gauche-refe.info,  Node: CGI Utility,  Next: CGI testing,  Prev: Topological sort,  Up: Library modules - Utilities

11.41 `www.cgi' - CGI utility
=============================

 -- Module: www.cgi
     Provides a few basic functions useful to write a CGI script.

     In order to write CGI script easily, you may want to use other
     modules, such as `rfc.uri' (*Note URI parsing and construction::),
     `text.html-lite' (*Note Simple HTML document construction::) and
     `text.tree' (*Note Lazy text construction::).

     Note: it seems that there is no active formal specification for
     CGI.  See `http://w3c.org/CGI/' for more information.

Metavariables
-------------

 -- Parameter: cgi-metavariables &optional metavariables
     Normally, httpd passes a cgi progam various information via
     environment variables.  Most procedures in `www.cgi' refer to them
     (meta-variables).  However, it is sometimes inconvenient to
     require environment variable access while you're developing
     cgi-related programs.  With this parameter, you can overrides the
     information of meta-variables.

     METAVARIABLES should be a list of two-element lists.  Car of each
     inner list names the variable, and its cadr gives the value of the
     variable by string.

     For example, the following code overrides `REQUEST_METHOD' and
     `QUERY_STRING' meta-variables during execution of
     `my-cgi-procedure'.  (*Note Parameters::, for the details of
     `parameterize').

          (parameterize ((cgi-metavariables '(("REQUEST_METHOD" "GET")
                                              ("QUERY_STRING" "x=foo"))))
            (my-cgi-procedure))

 -- Function: cgi-get-metavariable name
     Returns a value of cgi metavariable NAME.  This function first
     searches the parameter `cgi-metavariables', and if the named
     variable is not found, calls `sys-getenv'.

     CGI scripts may want to use `cgi-get-metavariable' instead of
     directly calling `sys-getenv'; doing so makes reuse of the script
     easier.

Parameter extraction
--------------------

 -- Function: cgi-parse-parameters &keyword :query-string
          :merge-cookies :part-handlers
     Parses query string and returns associative list of parameters.
     When a keyword argument QUERY-STRING is given, it is used as a
     source query string.  Otherwise, the function checks the
     metavariable `REQUEST_METHOD' and obtain the query string
     depending on the value (either from stdin or from the metavariable
     `QUERY_STRING').  If such a metavariable is not defined and the
     current input port is a terminal, the function prompts the user to
     type parameters; it is useful for interactive debugging.

     If `REQUEST_METHOD' is `POST', this procedure can handle both
     `application/x-www-from-urlencoded' and `multipart/form-data' as
     the enctype.  The latter is usually used if the form has
     file-uploading capability.

     When the post data is sent by `multipart/form-data', each content
     of the part is treated as a value of the parameter.  That is, the
     content of uploaded file will be seen as one big chunk of a
     string.  The other information, such as the original file name, is
     discarded.   If it is not desirable to read entire file into a
     string, you can customize the behavior by the PART-HANDLER
     argument.  The details are explaned in the "Handling file uploads"
     section below.

     When a true value is given to MERGE-COOKIES, the cookie values
     obtained from the metavariable `HTTP_COOKIE' are appended to the
     result.

     Note that the query parameter may have multiple values, so `cdr'
     of each element in the result is a list, not an atom.  If no value
     is given to the parameter, `#t' is placed as its value.  See the
     following example:
          (cgi-parse-parameters
            :query-string "foo=123&bar=%22%3f%3f%22&bar=zz&buzz")
           => (("foo" "123") ("bar "\"??\"" "zz") ("buzz" #t))

 -- Function: cgi-get-parameter name params &keyword :default :list
          :convert
     A convenient function to obtain a value of the parameter NAME from
     parsed query string PARAMS, which is the value
     `cgi-parse-parameters' returns.

     Unless true value is given to LIST, the returned value is a scalar
     value.  If more than one value is associated to NAME, only the
     first value is returned.  If LIST is true, the returned value is
     always a list, even NAME has only one value.

     After the value is retrieved, you can apply a procedure to convert
     the string value to the appropriate type by giving a procedure to
     the CONVERT argument.  The procedure must take one string
     argument.  If LIST is true, the convert procedure is applied to
     each values.

     If no value is defined for NAME, a value given to the keyword
     argument DEFAULT is returned; the default value of DEFAULT is `#f'
     if LIST is false, or `()' otherwise.

Output generation
-----------------

 -- Function: cgi-header &keyword status content-type location cookies
     Creates a text tree (*Note Lazy text construction::) for the HTTP
     header of the reply message.  The most simple form is like this:
          (tree->string (cgi-header))
            => "Content-type: text/html\r\n\r\n"

     You can specify alternative content-type by the keyword argument
     CONTENT-TYPE.   If you want to set cookies to the client, specify
     a list of cookie strings to the keyword argument COOKIES.  You can
     use `construct-cookie-string' (*Note HTTP cookie handling::) to
     build such a list of cookie strings.

     The keyword argument LOCATION may be used to generate a
     `Location:' header to redirect the client to the specified URI.
     You can also specify the `Status:' header by the keyword argument
     STATUS.   A typical way to redirect the client is as follows:

          (cgi-header :status "302 Moved Temporarily"
                      :location target-uri)


 -- Parameter: cgi-output-character-encoding &optional encoding
     The value of this parameter specifies the character encoding
     scheme (CES) used for CGI output by `cgi-main' defined below.  The
     default value is Gauche's native encoding.  If the parameter is
     set other than the native encoding, `cgi-main' converts the output
     encoding by `gauche.charconv' module (*Note Character code
     conversion::).

Convenience procedures
----------------------

 -- Function: cgi-main proc &keyword on-error merge-cookies output-proc
          part-handlers
     A convenient wrapper function for CGI script.  This function calls
     `cgi-parse-parameters', then calls PROC with the result of
     `cgi-parse-parameters'.  The keyword argument MERGE-COOKIES is
     passed to `cgi-parse-parameters'.

     PROC has to return a tree of strings (*Note Lazy text
     construction::), including the HTTP header.  `cgi-main' outputs
     the returned tree to the current output port by `write-tree', then
     returns zero.

     If an error is signalled in PROC, it is caught and an HTML page
     reporting the error is generated.  You can customize the error
     page by providing a procedure to the ON-ERROR keyword argument.
     The procedure takes an `<condition>' object (*Note Conditions::),
     and has to return a tree of string for the error reporting HTML
     page, including an HTTP header.

     When output the result, `cgi-main' refers to the value of the
     parameter `cgi-output-character-encoding', and converts the
     character encoding if necessary.

     The output behavior of `cgi-main' can be customized by a keyword
     argument OUTPUT-PROC; if it is given, the text tree (either the
     normal return value of PROC, or an error page constructed by ther
     error handler) is passed to the procedure given to OUTPUT-PROC.
     The procedure is responsible to format and output a text to the
     current output port, including character conversions, if necessary.

     The keyword argument PART-HANDLERS are simply passed to
     `cgi-parse-parameters', by which you can customize how the file
     uploads should be handled.  See the "Handling file uploads"
     section below for the details.

     If you specify to use temporary file(s) by it, `cgi-main' makes
     sure to clean up them whenever PROC exits, even by error.   See
     `cgi-add-temporary-file' below to utilize this feature for other
     purpose.

     The following example shows the parameters given to the CGI
     program.

          #!/usr/local/bin/gosh

          (use text.html-lite)
          (use www.cgi)

          (define (main args)
            (cgi-main
              (lambda (params)
                `(,(cgi-header)
                  ,(html-doctype)
                  ,(html:html
                    (html:head (html:title "Example"))
                    (html:body
                     (html:table
                      :border 1
                      (html:tr (html:th "Name") (html:th "Value"))
                      (map (lambda (p)
                             (html:tr
                              (html:td (html-escape-string (car p)))
                              (html:td (html-escape-string (x->string (cdr p))))))
                           params))))
                 ))))

 -- Function: cgi-add-temporary-file filename
     This is supposed to be called inside PROC of `cgi-main'.  It
     registers FILENAME as a temporary file, which should be unlinked
     when PROC exits.  It is a convenient way to ensure that your cgi
     script won't leave garbages even if it throws an error.  It is OK
     in PROC to unlink or rename FILENAME after calling this procedure.

 -- Parameter: cgi-temporary-files
     Keeps a list of filenames registered by `cgi-add-temorary-file'.

Handling file uploads
---------------------

As explained in `cgi-parse-parameters' above, file uploads are handled
transparently by default, taking the file content as the value of the
parameter.   Sometimes you might want to change this behavior, for the
file might be quite big and you don't want to keep around a huge chunk
of a string in memory.  It is possible to customize handling of file
uploads of `cgi-parse-parameters' and `cgi-main' by PART-HANDLERS
argument.  (The argument is only effective for the form data submitted
by `multipart/form-data' enctype)

   The PART-HANDLERS argument is, if given, a list of lists; each inner
list is a form of `(NAME-PATTERN ACTION)'.  Each uploaded file with a
matching parameter name with NAME-PATTERN is handled according to
ACTION.  (Here, a parameter name is the 'name' attribute given to the
`input' element in the submitted form, not the name of the uploaded
file).

   NAME-PATTERN must be either a list of string (matches one of them),
a regexp, or `#t' (matches anything).

   ACTION must be either one of the followings:
`#f'
     Default action, i.e. the content of the uploaded file is turned
     into a string and becomes the value of the parameter.

`ignore'
     The uploaded content is discarded.

`file'
     The uploaded content is saved in a temporary file.  The value of
     the parameter is the pathname of the temporary file.

     For this action, you can write an entry like `(NAME-PATTERN file
     PREFIX)', to specify the prefix of the pathname of the temporary
     file.  For example, if you specify `("image" file
     "/var/mycgi/incoming/img")', the file uploaded as `"image"'
     parameter will be stored as something like
     `/var/mycgi/incoming/img49g2Ua'.

     The application should move the temporary file to appropriate
     location; if you're using `cgi-main', the temporary files created
     by this action will be unlinked when `cgi-main' exits.

`file+name'
     Like `file', but the value of the parameter is a list of tempoary
     filename and the filename passed by the client.  It is useful if
     you want to use client's filename (but do not blindly assume the
     client sends a valid pathname; for example, you shouldn't use it
     to rename the uploaded file without validating it).

`PROCEDURE'
     In this case, PROCEDURE is called to handle the uploaded contents.
     It is called with four arguments: `(procedure NAME FILENAME
     PART-INFO IPORT)'.

     NAME is the name of the parameter.  FILENAME is the name of the
     original file (pathname in the client).  PART-INFO is a
     `<mime-part>' object that keeps information about this mime part,
     and IPORT is where the body can be read from.  For the details
     about these arguments, see *Note MIME message handling::; you
     might be able to use procedures provided by `rfc.mime', such as
     `mime-retrieve-body', to construct your own procedure.

     If you create a temporary file in PROCEDURE, you can call
     `cgi-add-temporary-file' to make sure it is removed even if an
     error occurs during cgi processing.

   Note that the parameters that are not file uploads are not the
subject of PART-HANDLERS; such parameter values are always turned into
a string.

   Here's a short example.  Suppose you have a form like this:

     <form enctype="multipart/form-data" method="POST" action="mycgi.cgi">
     <input type="file" name="imagefile" />
     <input type="text" name="description" />
     <input type="hidden" name="mode" value="normal" />
     </form>

   If you use `cgi-parse-parameters' in `mycgi.cgi' without
PART-HANDLERS argument, you'll get something like the following as the
result.  (The actual values depend on how the web client filled the
form).

     (("imagefile" #*".....(image file content as a string)....")
      ("description" "my image")
      ("mode" "normal"))

   If you pass `'(("imagefile" file "/tmp/mycgi"))' to PART-HANDLERS
instead, you might get something like the following, with the content
of uploaded file saved in `/tmp/mycgi7gq0B'

     (("imagefile" "/tmp/mycgi7gq0B")
      ("description" "my image")
      ("mode" "normal"))

   If you use a symbol `file+name' instead of `file' above, you'll get
something like `("/tmp/mycgi7gq0B" "logo.jpg")' as the value of
`"imagefile"', where `"logo.jpg"' is the client-side filename.   (Note:
the client can send any string as the name of the file, so _never_
assume it is a valid pathname).


File: gauche-refe.info,  Node: CGI testing,  Prev: CGI Utility,  Up: Library modules - Utilities

11.42 `www.cgi-test' - CGI testing
==================================

 -- Module: www.cgi-test
     This module defines a useful procedures to test CGI script.  The
     test actually runs the named script, with specified enviornment
     variable settings, and retrieve the output.  Your test procedure
     then examine whether the output is as expected or not.

 -- Function: cgi-test-enviornment-ref envvar-name
 -- Function: (setter cgi-test-enviornment-ref) envvar-name value
     The module keeps a table of default values of enviornment variables
     with which the cgi script will be run.  These procedures allow the
     programmer to get/set those default values.

     Note that you can override these default values and/or pass
     additional environment variables for each call of cgi script.  The
     following environment variables are set by default.
     Name                               Value
     `SERVER_SOFTWARE'                  `cgitest/1.0'
     `SERVER_NAME'                      `localhost'
     `GATEWAY_INTERFACE'                `CGI/1.1'
     `SERVER_PROTOCOL'                  `HTTP/1.1'
     `SERVER_PORT'                      `80'
     `REQUEST_METHOD'                   `GET'
     `REMOTE_HOST'                      `remote'
     `REMOTE_ADDR'                      `127.0.0.1'

 -- Function: call-with-cgi-script script proc &keyword (environment
          ()) (parameters #f)
     Runs a script with given enviornment, and calls PROC with one
     argument, an input port which is connected to the pipe of script's
     standard output.  The argument SCRIPT should be a list of program
     name and its arguments.  Each element are passed to `x->string'
     first to stringify.  The script is run under the enviornment given
     by ENVIORNMENT variable and the default test environment described
     above.  The ENVIRONMENT argument must be an associative list, in
     which each key (`car') is the name of the enviornment variable and
     its `cdr' is the value.  Both are passed to `x->string' first.  If
     the same environment variable appears in ENVIRONMENT and the
     default test enviornment, the one in ENVIRONMENT is used.
     Additionally, if an associative list is given to the PARAMETERS
     argument, a query string is built from it and passed the script.
     The actual method to pass the query string depends on the value of
     `REQUEST_METHOD' environment variable in the setting.  If
     `REQUEST_METHOD' is either `GET' or `HEAD', the query string is
     put in an environment variable `QUERY_STRING'.  If it is `POST',
     the query string is fed to the standard input of the script.  In
     the latter case, `CONTENT_TYPE' is set to
     `application/x-www-form-urlencoded' and `CONTENT_LENGTH' are set
     to the length of `QUERY_STRING' automatically.  If
     `REQUEST_METHOD' is other values, PARAMETERS is ignored.  You can
     bypass this mechanism and set up enviornment variable
     `QUERY_STRING' directly, if you wish.

 -- Function: run-cgi-script->header&body script reader &keyword
          environment parameters
     A convenient wrapper of `call-with-cgi-script'.  The SCRIPT,
     ENVIRONMENT and PARAMETERS are passed to `call-with-cgi-script' as
     they are.  The output of the script is parsed by
     `run-cgi-script->header&body'.  First, the RFC2822 header fields
     are parsed by `rfc822-header->list' (*Note RFC822 message
     parsing::).  Then, the READER is called with an input port which
     is piped to the script's output.  `Run-cgi-script->header&body'
     returns two values, the list of headers (as parsed by
     `rfc822-header->list'), and the return value of READER.

 -- Function: run-cgi-script->sxml script &keyword environment
          parameters
     This is a procedure that uses `ssax:xml->sxml' (*Note Functional
     XML parser::) as the READER in `run-cgi-script->header&body'.
     Useful when you're testing a cgi script that produces well-formed
     HTML and/or XML document.

 -- Function: run-cgi-script->string script &keyword environment
          parameters
 -- Function: run-cgi-script->string-list script &keyword environment
          parameters
     These procedures use `port->string' and `port->string-list' (*Note
     Input utility functions::) as the READER in
     `run-cgi-script->header&body', respectively.

   An example:
     (run-cgi-script->string-list "bbs.cgi"
                                  :environment '((REMOTE_ADDR . "12.34.56.78"))
                                  :parameters '((command . "view")
                                                (page . 1234)))


File: gauche-refe.info,  Node: References,  Next: C to Scheme mapping,  Prev: Library modules - Utilities,  Up: Top

Appendix A References
*********************

[R5RS]
     R. Kelsey, W. Clinger, J. Rees (eds.), Revised^5 Report on the
     Algorithmic Language Scheme, Higher-Order and Symbolic
     Computation, 11(1), September, 1998 and ACM SIGPLAN Notices,
     33(9), October, 1998.
     `http://www.schemers.org/Documents/Standards/R5RS/'.

[1CC]
     Carl Bruggeman, Oscar Waddell and R. Kent Dybvig, Representing
     control in the presence of one-shot continuations, in Proceedings
     of SIGPLAN '96, pp. 99-107, 1996.

[Meyers86]
     Eugene Myers, An O(ND) Difference Algorithm and Its Variations,
     Algorithmica Vol. 1 No. 2, pp. 251-266, 1986.

[MOP]
     Gregor Kiczales, Jim Des Rivieres, Daniel Bobrow, The Art of
     Metaobject Protocol, The MIT Press.

[Dylan]
     Kim Barrett, Bob Cassels, Paul Haahr, David A. Moon, Keith
     Playford, P. Tucker Withington, A Monotonic Superclass
     Linearization for Dylan, in Proceedings of OOPSLA 96, October 1996.
     `http://www.webcom.com/~haahr/dylan/linearization-oopsla96.html'.

[FairThreads]
     F. Boussinot, Java Fair Threads,
     `http://www-sop.inria.fr/mimosa/rp/FairThreads/html/FairThreads.html'.

[RFC1321]
     R. Rivest, The MD5 Message-Digest Algorithm.
     April 1992.
     `ftp://ftp.isi.edu/in-notes/rfc1321.txt'.

[RFC2045]
     N. Freed, N. Borenstein: Multipurpose Internet Mail Extension
     (MIME) Part One: Format of Internet Message Bodies, November 1996.
     `ftp://ftp.isi.edu/in-notes/rfc2045.txt'.

[RFC2396]
     T. Berners-Lee, R. Fielding, L. Masinter, Uniform Resource
     Identifiers (URI): Generic Syntax, August 1998.
     `ftp://ftp.isi.edu/in-notes/rfc2396.txt'.

[RFC2616]
     R. Fielding et al, Hypertext Transfer Protocol - HTTP/1.1, June
     1999.
     `ftp://ftp.isi.edu/in-notes/rfc2616.txt'.

[RFC2822]
     P. Resnick (ed.), Internet Message Format, April 2001.
     `ftp://ftp.isi.edu/in-notes/rfc2822.txt'.

[RFC2965]
     D. Kristol, L. Montulli, HTTP State Management Mechanism, October
     2000.
     `ftp://ftp.isi.edu/in-notes/rfc2965.txt'.

[RFC3174]
     D. Eastlake, 3rd and P. Jones, US Secure Hash Algorithm 1 (SHA1).
     September 2001.
     `ftp://ftp.isi.edu/in-notes/rfc3174.txt'.

[SRFI-0]
     Marc Feeley, Feature-based conditional expansion construct, May
     1999.
     `http://srfi.schemers.org/srfi-0/srfi-0.html'.

[SRFI-1]
     Olin Shivers, List Library, October 1999.
     `http://srfi.schemers.org/srfi-1/srfi-1.html'.

[SRFI-2]
     Oleg Kiselyov, `AND-LET*': an `AND' with local bindings, a guarded
     `LET*' special form, March 1998.
     `http://srfi.schemers.org/srfi-2/srfi-2.html'.

[SRFI-4]
     Marc Feeley, Homogeneous numeric vector types, May 1999.
     `http://srfi.schemers.org/srfi-4/srfi-4.html'.

[SRFI-6]
     William D Clinger, Basic String Ports, July 1999.
     `http://srfi.schemers.org/srfi-6/srfi-6.html'.

[SRFI-8]
     John David Stone, receive: Binding to multiple values, August
     1999.
     `http://srfi.schemers.org/srfi-8/srfi-8.html'.

[SRFI-9]
     Richard Kelsey, Defining Record Types, September 1999.
     `http://srfi.schemers.org/srfi-9/srfi-9.html'.

[SRFI-10]
     Oleg Kiselyov, `#,' external form, January 2000.
     `http://srfi.schemers.org/srfi-10/srfi-10.html'.

[SRFI-11]
     Lars T Hansen, Syntax for receiving multiple values, March 2000.
     `http://srfi.schemers.org/srfi-11/srfi-11.html'.

[SRFI-13]
     Olin Shivers, String Libraries, December 2000.
     `http://srfi.schemers.org/srfi-13/srfi-13.html'.

[SRFI-14]
     Olin Shivers, Character-set Library, December 2000.
     `http://srfi.schemers.org/srfi-14/srfi-14.html'.

[SRFI-17]
     Per Bothner, Generalized `set!', July 2000.
     `http://srfi.schemers.org/srfi-17/srfi-17.html'.

[SRFI-18]
     Marc Feeley, Multithreading Support, April 2000.
     `http://srfi.schemers.org/srfi-18/srfi-18.html'.

[SRFI-19]
     Will Fitzgerald, Time Data Types and Procedures, August 2000.
     `http://srfi.schemers.org/srfi-19/srfi-19.html'.

[SRFI-21]
     Marc Feeley, Readl-time Multithreading Support, April 2000.
     `http://srfi.schemers.org/srfi-21/srfi-21.html'.

[SRFI-22]
     Martin Gasbichler and Michael Sperber, Running Scheme Scripts on
     Unix, January 2002.
     `http://srfi.schemers.org/srfi-22/srfi-22.html'.

[SRFI-23]
     Stephan Housen, Error reporting mechanism, April 2001.
     `http://srfi.schemers.org/srfi-23/srfi-23.html'.

[SRFI-25]
     Jussi Piitulainen, Multi-dimensional Array Primitives, June 2002.
     `http://srfi.schemers.org/srfi-25/srfi-25.html'.

[SRFI-26]
     Sebastian Egner, Notation for Specializing Parameters without
     Currying, June 2002.
     `http://srfi.schemers.org/srfi-26/srfi-26.html'.

[SRFI-27]
     Sebastian Egner, Sources of Random Bits, June 2002.
     `http://srfi.schemers.org/srfi-27/srfi-27.html'.

[SRFI-28]
     Scott G. Miller, Basic Format Strings, June 2002.
     `http://srfi.schemers.org/srfi-28/srfi-28.html'.

[SRFI-37]
     Anthony Carrico, Args-fold: a program argument processor, Jan.
     2003.
     `http://srfi.schemers.org/srfi-37/srfi-37.html'.

[SSAX]
     Oleg Kiselyov, XML and Scheme,
     `http://pobox.com/~oleg/ftp/Scheme/xml.html'.
     The SSAX distribution is also available at sourceforge:
     `http://ssax.sourceforge.net/'.

[MT]
     M. Matsumoto and T. Nishimura, "Mersenne Twister: A
     623-dimensionally equidistributed uniform pseudorandom number
     generator", ACM Trans. on Modeling and Computer Simulation Vol. 8,
     No. 1, Januray pp.3-30 1998.
     `http://www.math.keio.ac.jp/~matumoto/emt.html'

[OLEG1]
     Oleg Kiselyov, Making sense of an input stream,
     `http://pobox.com/~oleg/ftp/Scheme/parsing.html'.

[OLEG2]
     Oleg Kiselyov, General ways to traverse collections,,
     `http://pobox.com/~oleg/ftp/Scheme/enumerators-callcc.html'.  2000.


File: gauche-refe.info,  Node: C to Scheme mapping,  Next: Function and Syntax Index,  Prev: References,  Up: Top

Appendix B C to Scheme mapping
******************************

For the convenience of the programmers familiar to C, I composed a
simple table of C operators and library functions with the
corresponding Scheme functions.

`+'
     R5RS arithmetic procedure `+'.   *Note Arithmetics::.

`+='
     Gauche `inc!' macro.  *Note Assignments::.

`-'
     R5RS arithmetic procedure `-'.   *Note Arithmetics::.

`-='
     Gauche `dec!' macro.  *Note Assignments::.

`->'
     Gauche `slot-ref' is something close to this.  *Note Accessing
     instance::.

`* (binary)'
     R5RS arithmetic procedure `*'.   *Note Arithmetics::.

`* (unary)'
     No equivalent procedure.  Scheme doesn't have explicit notation of
     pointers.

`*='
     No equivalent procedure.

`/'
     R5RS arithmetic procedure `/'.   *Note Arithmetics::.

`/='
     No equivalent procedure.

`& (binary)'
     Gauche `logand'.  *Note Bitwise operations::.

`& (unary)'
     No equivalent procedure.  Scheme doesn't have explicit notation of
     pointers.

`&&'
     R5RS syntax `and'.  *Note Conditionals::.

`&='
     No equivalent procedure.

`|'
     Gauche `logior'.  *Note Bitwise operations::.

`||'
     R5RS syntax `or'.  *Note Conditionals::.

`|='
     No equivalent procedure.

`^'
     Gauche `logxor'.  *Note Bitwise operations::.

`='
     R5RS syntax `set!'.  *Note Assignments::.

`=='
     R5RS equivalence procedure, `eq?', `eqv?' and `equal?'.  *Note
     Equivalence::.

`<'
`<='
     R5RS arithmetic procedure `<' and `<='.  *Note Numerical
     comparison::.  Unlike C operator, Scheme version is transitive.

`<<'
     Gauche `ash'.  *Note Bitwise operations::.

`<<='
     No equivalent procedure.

`>'
`>='
     R5RS arithmetic procedure `>' and `>='.  *Note Numerical
     comparison::.  Unlike C operator, Scheme version is transitive.

`>>'
     Gauche `ash'.  *Note Bitwise operations::.

`>>='
     No equivalent procedure.

`%'
     R5RS operator `modulo' and `remainder'.  *Note Arithmetics::.

`%='
     No equivalent procedure.

`[]'
     R5RS `vector-ref' (*Note Vectors::) is something close.  Or you
     can use Gauche's generic function `ref' (*Note Sequence
     framework::) for arbitrary sequences.

`.'
     Gauche `slot-ref' is something close to this.  *Note Accessing
     instance::.

`~'
     Gauche `lognot'.  *Note Bitwise operations::.

`~='
     No equivalent procedure.

`!'
     R5RS procedure `not'.  *Note Booleans::.

`!='
     No equivalent procedure.

`abort'
     Gauche `sys-abort'.   *Note Program termination::.

`abs'
     R5RS `abs'.  *Note Arithmetics::.

`access'
     Gauche `sys-access'.  *Note File stats::.

`acos'
     R5RS `acos'.  *Note Arithmetics::.

`alarm'
     Gauche `sys-alarm'.   *Note Miscellaneous system calls::.

`asctime'
     Gauche `sys-asctime'.  *Note Time::.

`asin'
     R5RS `asin'.  *Note Arithmetics::.

`assert'
     No equivalent function in Gauche.

`atan'
`atan2'
     R5RS `atan'.  *Note Arithmetics::.

`atexit'
     No equivalent function in Gauche, but the "after" thunk of active
     dynamic handlers are called when `exit' is called.  *Note Program
     termination::, and *Note Continuation::.

`atof'
`atoi'
`atol'
     You can use `string->number'.  *Note Numerical conversions::.

`bsearch'
     Gauche ¤Ë¤ÏÆ±Åù¤Î´Ø¿ô¤Ï¤¢¤ê¤Þ¤»¤ó¡£

`calloc'
     Allocation is handled automatically in Scheme.

`ceil'
     R5RS `ceiling'.  *Note Arithmetics::.

`cfgetispeed'
`cfgetospeed'
`cfsetispeed'
`cfsetospeed'
     Gauche `sys-cfgetispeed', `sys-cfgetospeed', `sys-cfsetispeed',
     `sys-cfsetospeed'.  *Note Termios::.

`chdir'
     Gauche `sys-chdir'.   *Note Other file operations::.

`chmod'
     Gauche `sys-chmod'.   *Note File stats::.

`chown'
     Gauche `sys-chown'.   *Note File stats::.

`clearerr'
     Not supported yet.

`clock'
     No equivalent function in Gauche.  You can use `sys-times' to get
     information about CPU time.

`close'
     You can't directly close the file descriptor, but when you use
     `close-input-port' or `close-output-port', underlying file is
     closed.  Some port-related functions, such as
     `call-with-output-file', automatically closes the file when
     operation is finished.  The file is also closed when its governing
     port is garbage collected.  *Note Common port operations::.

`closedir'
     No equivalent function in Gauche.  You can use `sys-readdir' to
     read the directory entries at once.  *Note Directories::.

`cos'
`cosh'
     `cos' and `cosh'.  *Note Arithmetics::.

`creat'
     A file is implictly created by default when you open it for
     writing.  See *Note File ports:: for more control over the
     creation of files.

`ctermid'
     Gauche `sys-ctermid'.  *Note System Inquiry::.

`ctime'
     Gauche `sys-ctime'.  *Note Time::.

`cuserid'
     No equivalent function.  This is removed from the newer POSIX.
     You can use alternative functions, such as `sys-getlogin' or
     `sys-getpwuid' with `sys-getuid'.

`difftime'
     Gauche `sys-difftime'.  *Note Time::.

`div'
     You can use R5RS `quotient' and `remainder'.  *Note Arithmetics::.

`dup'
`dup2'
     No equivalent function.  If you want to use this function to set
     up I/Os for the child process, you can use `iomap' argument of
     `sys-exec'.  *Note Unix process management::.

`execl'
`execle'
`execlp'
`execv'
`execve'
`execvp'
     Gauche `sys-exec'.  *Note Unix process management::.  For higher
     level interface, *Note High Level Process Interface::.

`exit'

`_exit'
     Use `exit' or `sys-exit', depends on what you need.  *Note Program
     termination::.

`exp'
     R5RS `exp'.  *Note Arithmetics::.

`fabs'
     R5RS `abs'.  *Note Arithmetics::.

`fclose'
     You can't directly close the file stream, but when you use
     `close-input-port' or `close-output-port', underlying file is
     closed.  Some port-related functions, such as
     `call-with-output-file', automatically closes the file when
     operation is finished.  The file is also closed when its governing
     port is garbage collected.

`fcntl'
     Implemented as `sys-fcntl' in `gauche.fcntl' module.  *Note
     Low-level file operations::.

`fdopen'
     Gauche's `open-input-fd-port' or `open-output-fd-port'.  *Note
     File ports::.

`feof'
     Not supported yet.

`ferror'
     Not supported yet.

`fflush'
     Gauche's `flush'.   *Note Output::.

`fgetc'
     Use `read-char' or `read-byte'.  *Note Input::.

`fgetpos'
     Use Gauche's `port-tell' (*Note Common port operations::)

`fgets'
     Use `read-line' or `read-block'.    *Note Input::.

`fileno'
     `port-file-numer'.   *Note Common port operations::.

`floor'
     R5RS `floor'.   *Note Arithmetics::.

`fmod'
     Gauche's `fmod'.

`fopen'
     R5RS `open-input-file' or `open-output-file' corresponds to this
     operation.  *Note File ports::.

`fork'
     Gauche's `sys-fork'.   *Note Unix process management::.

`forkpty'
     Use `sys-forkpty'.  *Note Termios::.

`fpathconf'
     Not supported.

`fprintf'
     Not directly supported, but Gauche's `format' provides similar
     functionality.  *Note Output::.  SLIB has `printf' implementation.

`fputc'
     Use `write-char' or `write-byte'.  *Note Output::.

`fputs'
     Use `display'.  *Note Output::.

`fread'
     Not directly supported.  If you want to read a chunk of bytes, you
     may be able to use `read-block'.

`free'
     You don't need this in Scheme.

`freopen'
     Not supported.

`frexp'
     Gauche's `frexp'

`fscanf'
     Not supported.  For general case, you have to write a parser.  If
     you can keep the data in S-exp, you can use `read'.  If the syntax
     is very simple, you may be able to utilize `string-tokenize' in
     `srfi-14' (*Note String library::), and/or regular expression
     stuff (*Note Regular expression::, also *Note Regular expression
     utilities::.

`fseek'
     Use Gauche's `port-seek' (*Note Common port operations::)

`fsetpos'
     Use Gauche's `port-seek' (*Note Common port operations::)

`fstat'
     Gauche's `sys-stat'.  *Note File stats::.

`ftell'
     Use Gauche's `port-tell' (*Note Common port operations::)

`fwrite'
     Not directly supported.  If you want to write a chunk of bytes,
     you can simply use `display'.  *Note Output::.

`getc'
`getchar'
     Use `read-char' or `read-byte'.  *Note Input::.

`getcwd'
     Gauche's `sys-getcwd'.   *Note System Inquiry::.

`getdomainname'
     Gauche's `sys-getdomainname'.  *Note System Inquiry::.

`getegid'
     Gauche's `sys-getegid'.   *Note System Inquiry::.

`getenv'
     Gauche's `sys-getenv'.   *Note Environment Inquiry::.

`geteuid'
     Gauche's `sys-geteuid'.   *Note System Inquiry::.

`gethostname'
     Gauche's `sys-gethostname'.  *Note System Inquiry::.

`getgid'
     Gauche's `sys-getgid'.   *Note System Inquiry::.

`getgrgid'
`getgrnam'
     Gauche's `sys-getgrgid' and `sys-getgrnam'.  *Note Unix groups and
     users::.

`getgroups'
     Gauche's `sys-getgroups'.   *Note System Inquiry::.

`getlogin'
     Gauche's `sys-getlogin'.  *Note System Inquiry::.

`getpgrp'
     Gauche's `sys-getpgrp'.   *Note System Inquiry::.

`getpid'
`getppid'
     Gauche's `sys-getpid'.   *Note System Inquiry::.

`getpwnam'
`getpwuid'
     Gauche's `sys-getpwnam' and `sys-getpwuid'.  *Note Unix groups and
     users::.

`gets'
     Use `read-line' or `read-block'.  *Note Input::.

`gettimeofday'
     Gauche's `sys-gettimeofday'.   *Note Time::.

`getuid'
     Gauche's `sys-getuid'.  *Note System Inquiry::.

`gmtime'
     Gauche's `sys-gmtime'.   *Note Time::.

`isalnum'
     Not directly supported, but you can use R5RS `char-alphabetic?' and
     `char-numeric?'.  *Note Characters::.   You can also use character
     set.  *Note Character set::, also *Note Character-set library::.

`isalpha'
     R5RS `char-alphabetic?'.  *Note Characters::.  See also *Note
     Character set:: and *Note Character-set library::.

`isatty'
     Gauche's `sys-isatty'.   *Note Other file operations::.

`iscntrl'
     Not directly supported, but you can use `(char-set-contains?
     char-set:iso-control c)' with `srfi-14'.  *Note Character-set
     library::.

`isdigit'
     R5RS `char-numeric?'.  *Note Characters::.  You can also use
     `(char-set-contains? char-set:digit c)' with `srfi-14'.   *Note
     Character-set library::.

`isgraph'
     Not directly supported, but you can use `(char-set-contains?
     char-set:graphic c)' with `srfi-14'.  *Note Character-set
     library::.

`islower'
     R5RS `char-lower-case?'.  *Note Characters::.  You can also use
     `(char-set-contains? char-set:lower-case c)' with `srfi-14'.
     *Note Character-set library::.

`isprint'
     Not directly supported, but you can use `(char-set-contains?
     char-set:printing c)' with `srfi-14'.  *Note Character-set
     library::.

`ispunct'
     Not directly supported, but you can use `(char-set-contains?
     char-set:punctuation c)' with `srfi-14'.  *Note Character-set
     library::.

`isspace'
     R5RS `char-whitespace?'.  *Note Characters::.  You can also use
     `(char-set-contains? char-set:whitespace c)' with `srfi-14'.
     *Note Character-set library::.

`isupper'
     R5RS `char-upper-case?'.  *Note Characters::.  You can also use
     `(char-set-contains? char-set:upper-case c)' with `srfi-14'.
     *Note Character-set library::.

`isxdigit'
     Not directly supported, but you can use `(char-set-contains?
     char-set:hex-digit c)' with `srfi-14'.  *Note Character-set
     library::.

`kill'
     Gauche's `sys-kill'.  *Note Signal::.

`labs'
     R5RS `abs'.  *Note Arithmetics::.

`ldexp'
     Gauche's `ldexp'.

`ldiv'
     Use R5RS `quotient' and `remainder'.  *Note Arithmetics::.

`link'
     Gauche's `sys-link'.  *Note Directory manipulation::.

`localeconv'
     Gauche's `sys-localeconv'. *Note Locale::.

`localtime'
     Gauche's `sys-localtime'.  *Note Time::.

`log'
     R5RS `log'.  *Note Arithmetics::.

`log10'
     Not directly supported.  `log10(z)' == `(/ (log z) (log 10))'.

`longjmp'
     R5RS `call/cc' provides similar (superior) mechanism.  *Note
     Continuation::.

`lseek'
     Use Gauche's `port-seek' (*Note Common port operations::)

`malloc'
     Not necessary in Scheme.

`mblen'
`mbstowcs'
`mbtowc'
     Gauche handles multibyte strings internally, so generally you don't
     need to care about multibyte-ness of the string.   `string-length'
     always returns a number of characters for a string in supported
     encoding.   If you want to convert the character encoding, see
     *Note Character code conversion::.

`memcmp'
`memcpy'
`memmove'
`memset'
     No equivalent functions.

`mkdir'
     Gauche's `sys-mkdir'.  *Note Directory manipulation::.

`mkfifo'
     Gauche's `sys-mkfifo'.

`mkstemp'
     Gauche's `sys-mkstemp'.   *Note Directory manipulation::.  Use
     this instead of tmpnam.

`mktime'
     Gauche's `sys-mktime'.  *Note Time::.

`modf'
     Gauche's `modf'.

`open'
     Not directly supported.  R5RS `open-input-file' or
     `open-output-file' corresponds to this operation.  *Note File
     ports::.

`opendir'
     Not directly supported.  You can use `sys-readdir' to read the
     directory entries at once.  *Note Directories::.

`openpty'
     Use `sys-openpty'.  *Note Termios::.

`pathconf'
     Not supported.

`pause'
     Gauche's `sys-pause'.  *Note Miscellaneous system calls::.

`perror'
     No equivalent function in Gauche.  System calls generally throws an
     error (`<system-error>'), including the description of the reason
     of failure.

`pipe'
     Gauche's `sys-pipe'.  *Note Other file operations::.

`pow'
     R5RS `expt'.  *Note Arithmetics::.

`printf'
     Not directly supported, but Gauche's `format' provides similar
     functionality.  *Note Output::.  SLIB has `printf' implementation.

`putc'
`putchar'
     Use `write-char' or `write-byte'.  *Note Output::.

`puts'
     Use `display'.   *Note Output::.

`qsort'
     Gauche's `sort' and `sort!' provides a convenient way to sort list
     of items.  *Note Comparison and sorting::.

`raise'
     No equivalent function in Gauche.  Scheme function `raise'
     (SRFI-18) is to raise an exception.   You can use `(sys-kill
     (sys-getpid) SIG)' to send a signal `SIG' to the current process.

`rand'
     Not supported directly, but on most platforms a better RNG is
     available as `sys-random'.  *Note Miscellaneous system calls::.

`read'
     Not supported directly, but you may be able to use `read-block'
     (*Note Input::) or `read-block!' (*Note Uvector block I/O::).

`readdir'
     Not supported directly.   Gauche's `sys-readdir' reads the
     directory at once.  *Note Directories::.

`readlink'
     Gauche's `sys-readlink'.  *Note Directory manipulation::.  This
     function is available on systems that support symbolink links.

`realloc'
     Not necessary in Scheme.

`realpath'
     Gauche's `sys-normalize-pathname' or `sys-realpath'.  *Note
     Pathnames::.

`remove'
     Gauche's `sys-remove'.  *Note Directory manipulation::.

`rename'
     Gauche's `sys-rename'.  *Note Directory manipulation::.

`rewind'
     Not supported yet.

`rewinddir'
     Not supported directly.  You can use `sys-readdir' to read the
     directory entries at once.  *Note Directories::.

`rmdir'
     Gauche's `sys-rmdir'.  *Note Directory manipulation::.

`scanf'
     Not supported.  For general case, you have to write a parser.  If
     you can keep the data in S-exp, you can use `read'.  If the syntax
     is very simple, you may be able to utilize `string-tokenize' in
     `srfi-14' (*Note String library::), and/or regular expression
     stuff (*Note Regular expression::, also *Note Regular expression
     utilities::.

`select'
     Gauche's `sys-select'.  *Note I/O multiplexing::.

`setbuf'
     Not necessary.

`setgid'
     Gauche's `sys-setgid'.

`setjmp'
     R5RS `call/cc' provides similar (superior) mechanism.  *Note
     Continuation::.

`setlocale'
     Gauche's `sys-setlocale'.  *Note Locale::.

`setpgid'
     Gauche's `sys-setpgid'.  *Note System Inquiry::.

`setsid'
     Gauche's `sys-setsid'.  *Note System Inquiry::.

`setuid'
     Gauche's `sys-setuid'.  *Note System Inquiry::.

`setvbuf'
     Not necessary.

`sigaction'
     You can use `set-signal-handler!' to install signal handlers.
     *Note Handling signals::.

`sigaddset'
`sigdelset'
`sigemptyset'
`sigfillset'
     Gauche's `sys-sigset-add!' and `sys-sigset-delete!'.  *Note
     Signals and signal sets::.

`sigismember'
     Not supported yet.

`siglongjmp'
     R5RS `call/cc' provides similar (superior) mechanism.  *Note
     Continuation::.

`signal'
     You can use `with-signal-handlers' to install signal handlers.
     *Note Handling signals::.

`sigpending'
     Not supported yet.

`sigprocmask'
     Signal mask is handled internally.  *Note Handling signals::.

`sigsetjmp'
     R5RS `call/cc' provides similar (superior) mechanism.  *Note
     Continuation::.

`sigsuspend'
     Gauche's `sys-sigsuspend'.  *Note Masking and waiting signals::.

`sin'
`sinh'
     Use `sin' and `sinh'.   *Note Arithmetics::.

`sleep'
     Gauche's `sys-sleep'.  *Note Miscellaneous system calls::.

`sprintf'
     Not directly supported, but Gauche's `format' provides similar
     functionality.  *Note Output::.  SLIB has `printf' implementation.

`sqrt'
     R5RS `sqrt'.  *Note Arithmetics::.

`srand'
     Not supported directly, but on most platforms a better RNG is
     available as `sys-srandom'.  *Note Miscellaneous system calls::.

`sscanf'
     Not supported.  For general case, you have to write a parser.  If
     you can keep the data in S-exp, you can use `read'.  If the syntax
     is very simple, you may be able to utilize `string-tokenize' in
     `srfi-14' (*Note String library::), and/or regular expression
     stuff (*Note Regular expression::, also *Note Regular expression
     utilities::.

`stat'
     Gauche's `sys-stat'.  *Note File stats::.

`strcasecmp'
     R5RS `string-ci=?' and other comparison functions.  *Note String
     Comparison::.

`strcat'
     R5RS `string-append'.  *Note String utilities::.

`strchr'
     SRFI-13 `string-index'.  *Note SRFI-13 String searching::.

`strcmp'
     R5RS `string=?' and other comparison functions.  *Note String
     Comparison::.

`strcoll'
     Not supported yet.

`strcpy'
     R5RS `string-copy'.    *Note String utilities::.

`strcspn'
     Not directly supported, but you can use SRFI-13 `string-skip' with
     a character set.  *Note SRFI-13 String searching::.

`strerror'
     Not supported.

`strftime'
     Gauche's `sys-strftime'.  *Note Time::.

`strlen'
     R5RS `string-length'.  *Note String Accessors & Modifiers::.

`strncat'
     Not directly supported, but you can use `string-append' and
     `substring'.

`strncasecmp'
     SRFI-13 `string-compare-ci' provides the most flexible (but a bit
     difficult to use) functionality.  *Note SRFI-13 String
     Comparison::.  If what you want is just to check the fixed-length
     prefixes of two string matches, you can use SRFI-13
     `string-prefix-ci?'.

`strncmp'
     SRFI-13 `string-compare' provides the most flexible (but a bit
     difficult to use) functionality.  *Note SRFI-13 String
     Comparison::.  If what you want is just to check the fixed-length
     prefixes of two string matches, you can use SRFI-13
     `string-prefix?'.  *Note SRFI-13 String Prefixes & Suffixes::.

`strncpy'
     SRFI-13 `substring'.  *Note String utilities::.

`strpbrk'
     Not directly supported, but you can use SRFI-13 `string-skip' with
     a character set.  *Note SRFI-13 String searching::.

`strrchr'
     SRFI-13 `string-index-right'.  *Note SRFI-13 String searching::.

`strspn'
     Not directly supported, but you can use SRFI-13 `string-index'
     with a character set.  *Note SRFI-13 String searching::.

`strstr'
     SRFI-13 `string-contains'.  *Note SRFI-13 String searching::.

`strtod'
     You can use R5RS `string->number'.   *Note Numerical conversions::.

`strtok'
     SRFI-13 `string-tokenize'.  *Note SRFI-13 other string
     operations::.

`strtol'
`strtoul'
     You can use R5RS `string->number'.   *Note Numerical conversions::.

`strxfrm'
     Not supported yet.

`symlink'
     Gauche's `sys-symlink'.  *Note Directory manipulation::.  This
     function is available on systems that support symbolink links.

`sysconf'
     Not supported yet.

`system'
     Gauche's `sys-system'.   *Note Unix process management::.  It is
     generally recommended to use the process library (*Note High Level
     Process Interface::).

`tan'
`tanh'
     R5RS `tan' and Gauche `tanh'.  *Note Arithmetics::.

`tcdrain'

`tcflow'

`tcflush'

`tcgetattr'

`tcgetpgrp'

`tcsendbreak'

`tcsetattr'

`tcsetpgrp'
     Corresponding functions are: `sys-tcdrain', `sys-tcflow',
     `sys-tcflush', `sys-tcgetattr', `sys-tcgetpgrp',
     `sys-tcsendbreak', `sys-tcsetattr', `sys-tcsetpgrp'.  *Note
     Termios::

`time'
     Gauche's `sys-time'.  *Note Time::.

`times'
     Gauche's `sys-times'.  *Note System Inquiry::.

`tmpfile'
     Not exactly supported.

`tmpnam'
     Gauche's `sys-tmpnam'.  This function is provided since it is in
     POSIX, but its use is discouraged for the potential security risk.
     Use `sys-mkstemp' instead.   *Note Directory manipulation::.

`tolower'
`toupper'
     R5RS `char-upcase' and `char-downcase'.   *Note Characters::.

`ttyname'
     Gauche's `sys-ttyname'.  *Note Other file operations::.

`tzset'
     Not supported yet.

`umask'
     Gauche's `sys-umask'.  *Note Directory manipulation::.

`uname'
     Gauche's `sys-uname'.  *Note System Inquiry::.

`ungetc'
     Not directly supported.  You can use `peek-char' to look one
     character ahead, instead of pushing back.

`unlink'
     Gauche's `sys-unlink'.  *Note Directory manipulation::.

`utime'
     Gauche's `sys-utime'. *Note File stats::.

`va_arg'
`va_end'
`va_start'
     Not necessary, for Scheme handles variable number of arguments
     naturally.

`vfprintf'
`vprintf'
`vsprintf'
     Not directly supported, but Gauche's `format' provides similar
     functionality.  *Note Output::.  SLIB has `printf' implementation.

`wait'
     Gauche's `sys-wait'.  *Note Unix process management::.

`waitpid'
     Gauche's `sys-waitpid'.  *Note Unix process management::.

`wcstombs'
`wctomb'
     Gauche handles multibyte strings internally, so generally you don't
     need to care about multibyte-ness of the string.   `string-length'
     always returns a number of characters for a string in supported
     encoding.   If you want to convert the character encoding, see
     *Note Character code conversion::.

`write'
     R5RS `display' (*Note Output::).  Or `write-block' (*Note Uvector
     block I/O::).


File: gauche-refe.info,  Node: Function and Syntax Index,  Next: Module Index,  Prev: C to Scheme mapping,  Up: Top

Appendix C Function and Syntax Index
************************************

[index]
* Menu:

* %macroexpand:                          Macro expansion.     (line  18)
* %macroexpand-1:                        Macro expansion.     (line  19)
* (setter cgi-test-enviornment-ref):     CGI testing.         (line  14)
* (setter object-apply):                 Applicable objects.  (line  47)
* (setter port-buffering):               Common port operations.
                                                              (line  53)
* (setter ref) <1>:                      Hashtables.          (line 117)
* (setter ref) <2>:                      Fundamental sequence accessors.
                                                              (line  19)
* (setter ref):                          Accessing instance.  (line  50)
* (setter subseq):                       Slicing sequence.    (line  20)
* *:                                     Arithmetics.         (line   8)
* +:                                     Arithmetics.         (line   7)
* -:                                     Arithmetics.         (line  13)
* ->char-set:                            SRFI-14 Character-set constructors.
                                                              (line  37)
* /:                                     Arithmetics.         (line  14)
* ::                                     Eager comprehensions.
                                                              (line 133)
* :char-range:                           Eager comprehensions.
                                                              (line 149)
* :dispatched:                           Eager comprehensions.
                                                              (line 154)
* :do:                                   Eager comprehensions.
                                                              (line 158)
* :integers:                             Eager comprehensions.
                                                              (line 139)
* :let:                                  Eager comprehensions.
                                                              (line 160)
* :list:                                 Eager comprehensions.
                                                              (line 135)
* :parallel:                             Eager comprehensions.
                                                              (line 162)
* :port:                                 Eager comprehensions.
                                                              (line 151)
* :range:                                Eager comprehensions.
                                                              (line 142)
* :real-range:                           Eager comprehensions.
                                                              (line 145)
* :string:                               Eager comprehensions.
                                                              (line 137)
* :until:                                Eager comprehensions.
                                                              (line 166)
* :vector:                               Eager comprehensions.
                                                              (line 136)
* :while:                                Eager comprehensions.
                                                              (line 164)
* <:                                     Numerical comparison.
                                                              (line  15)
* <=:                                    Numerical comparison.
                                                              (line  16)
* =:                                     Numerical comparison.
                                                              (line   7)
* >:                                     Numerical comparison.
                                                              (line  17)
* >=:                                    Numerical comparison.
                                                              (line  18)
* abandoned-mutex-exception?:            Thread exceptions.   (line  48)
* abs:                                   Arithmetics.         (line  34)
* absolute-path?:                        Pathname utilities.  (line  12)
* acons:                                 List constructors.   (line  11)
* acos:                                  Arithmetics.         (line 121)
* acosh:                                 Arithmetics.         (line 132)
* add-duration:                          SRFI-19 Time procedures.
                                                              (line  41)
* add-duration!:                         SRFI-19 Time procedures.
                                                              (line  42)
* add-hook!:                             Hooks.               (line  42)
* add-load-path:                         Loading Scheme file. (line  48)
* alist->hash-table:                     Additional list library.
                                                              (line  97)
* alist-cons:                            SRFI-1 Association lists.
                                                              (line   7)
* alist-copy:                            SRFI-1 Association lists.
                                                              (line  11)
* alist-delete:                          SRFI-1 Association lists.
                                                              (line  24)
* alist-delete!:                         SRFI-1 Association lists.
                                                              (line  25)
* all-modules:                           Module introspection.
                                                              (line  51)
* allocate-instance:                     Creating instance.   (line  26)
* and <1>:                               Conditionals.        (line  80)
* and:                                   Eager comprehensions.
                                                              (line 123)
* and-let*:                              And-let*.            (line  10)
* angle:                                 Numerical conversions.
                                                              (line  16)
* any:                                   SRFI-1 Searching.    (line  32)
* any$:                                  SRFI-1 Searching.    (line  51)
* any-pred:                              Combinators.         (line  60)
* any?-ec:                               Eager comprehensions.
                                                              (line 102)
* append:                                Other list procedures.
                                                              (line   7)
* append!:                               Other list procedures.
                                                              (line  15)
* append-ec:                             Eager comprehensions.
                                                              (line  83)
* append-map:                            SRFI-1 Fold.         (line  82)
* append-map!:                           SRFI-1 Fold.         (line  83)
* append-reverse:                        SRFI-1 List miscellaneous routines.
                                                              (line  16)
* append-reverse!:                       SRFI-1 List miscellaneous routines.
                                                              (line  17)
* apply:                                 Procedures.          (line  12)
* apply$:                                Combinators.         (line  24)
* apply-generic:                         Customizing method application.
                                                              (line   7)
* apply-method:                          Customizing method application.
                                                              (line  15)
* apply-methods:                         Customizing method application.
                                                              (line  13)
* apropos:                               Interactive session. (line  17)
* args-fold:                             A program argument processor.
                                                              (line  19)
* arity:                                 Procedure arity.     (line  10)
* arity-at-least-value:                  Procedure arity.     (line  31)
* arity-at-least?:                       Procedure arity.     (line  28)
* array:                                 Arrays.              (line 121)
* array->list:                           Arrays.              (line 204)
* array->vector:                         Arrays.              (line 203)
* array-add-elements:                    Arrays.              (line 229)
* array-add-elements!:                   Arrays.              (line 230)
* array-concatenate:                     Arrays.              (line 206)
* array-div-elements:                    Arrays.              (line 236)
* array-div-elements!:                   Arrays.              (line 237)
* array-div-left:                        Arrays.              (line 226)
* array-div-right:                       Arrays.              (line 227)
* array-end:                             Arrays.              (line 138)
* array-expt:                            Arrays.              (line 224)
* array-flip:                            Arrays.              (line 212)
* array-flip!:                           Arrays.              (line 213)
* array-for-each-index:                  Arrays.              (line 188)
* array-inverse:                         Arrays.              (line 217)
* array-length:                          Arrays.              (line 139)
* array-map:                             Arrays.              (line 201)
* array-map!:                            Arrays.              (line 197)
* array-mul:                             Arrays.              (line 222)
* array-mul-elements:                    Arrays.              (line 234)
* array-mul-elements!:                   Arrays.              (line 235)
* array-rank:                            Arrays.              (line 128)
* array-ref:                             Arrays.              (line 163)
* array-retabulate!:                     Arrays.              (line 194)
* array-rotate-90:                       Arrays.              (line 210)
* array-set!:                            Arrays.              (line 170)
* array-shape:                           Arrays.              (line 134)
* array-size:                            Arrays.              (line 155)
* array-start:                           Arrays.              (line 137)
* array-sub-elements:                    Arrays.              (line 232)
* array-sub-elements!:                   Arrays.              (line 233)
* array-transpose:                       Arrays.              (line 208)
* array?:                                Arrays.              (line  87)
* as-nodeset:                            SXPath basic converters and applicators.
                                                              (line  17)
* ash:                                   Bitwise operations.  (line  14)
* asin:                                  Arithmetics.         (line 120)
* asinh:                                 Arithmetics.         (line 131)
* assert-curr-char:                      Parsing input stream.
                                                              (line  52)
* assoc:                                 Other list procedures.
                                                              (line  48)
* assoc$:                                SRFI-1 Association lists.
                                                              (line  32)
* assoc-ref:                             Additional list library.
                                                              (line 116)
* assoc-set!:                            Additional list library.
                                                              (line 143)
* assq:                                  Other list procedures.
                                                              (line  46)
* assq-ref:                              Additional list library.
                                                              (line 117)
* assq-set!:                             Additional list library.
                                                              (line 144)
* assv:                                  Other list procedures.
                                                              (line  47)
* assv-ref:                              Additional list library.
                                                              (line 118)
* assv-set!:                             Additional list library.
                                                              (line 145)
* atan:                                  Arithmetics.         (line 122)
* atanh:                                 Arithmetics.         (line 133)
* attlist->alist:                        SSAX data types.     (line 144)
* attlist-add:                           SSAX data types.     (line 141)
* attlist-fold:                          SSAX data types.     (line 145)
* attlist-null?:                         SSAX data types.     (line 142)
* attlist-remoev-top:                    SSAX data types.     (line 143)
* autoload:                              Autoload.            (line   7)
* base64-decode:                         Base64 encoding/decoding.
                                                              (line  22)
* base64-decode-string:                  Base64 encoding/decoding.
                                                              (line  29)
* base64-encode:                         Base64 encoding/decoding.
                                                              (line  11)
* base64-encode-string:                  Base64 encoding/decoding.
                                                              (line  17)
* begin <1>:                             Eager comprehensions.
                                                              (line 126)
* begin:                                 Sequencing.          (line   7)
* begin0:                                Sequencing.          (line  36)
* bignum?:                               Numerical predicates.
                                                              (line  62)
* bindtextdomain:                        Localized messages.  (line  86)
* bit-field:                             Bitwise operations.  (line  40)
* boolean?:                              Booleans.            (line  14)
* break:                                 SRFI-1 Searching.    (line  27)
* break!:                                SRFI-1 Searching.    (line  28)
* build-path:                            Pathname utilities.  (line   7)
* build-transliterator:                  Transliterate characters.
                                                              (line  96)
* caaaar:                                List accessors and modifiers.
                                                              (line  19)
* caaadr:                                List accessors and modifiers.
                                                              (line  19)
* caaar:                                 List accessors and modifiers.
                                                              (line  19)
* caadar:                                List accessors and modifiers.
                                                              (line  19)
* caaddr:                                List accessors and modifiers.
                                                              (line  19)
* caadr:                                 List accessors and modifiers.
                                                              (line  19)
* caar:                                  List accessors and modifiers.
                                                              (line  18)
* cadaar:                                List accessors and modifiers.
                                                              (line  19)
* cadadr:                                List accessors and modifiers.
                                                              (line  19)
* cadar:                                 List accessors and modifiers.
                                                              (line  19)
* caddar:                                List accessors and modifiers.
                                                              (line  19)
* cadddr:                                List accessors and modifiers.
                                                              (line  19)
* caddr:                                 List accessors and modifiers.
                                                              (line  19)
* cadr:                                  List accessors and modifiers.
                                                              (line  19)
* call-with-builder:                     Fundamental iterator creators.
                                                              (line  64)
* call-with-cgi-script:                  CGI testing.         (line  33)
* call-with-client-socket:               High-level network functions.
                                                              (line 140)
* call-with-current-continuation:        Continuation.        (line   7)
* call-with-input-conversion:            Conversion ports.    (line  73)
* call-with-input-file <1>:              Extended port procedures.
                                                              (line  10)
* call-with-input-file:                  File ports.          (line 132)
* call-with-input-process:               Process ports.       (line  57)
* call-with-input-string:                String ports.        (line  51)
* call-with-iterator:                    Fundamental iterator creators.
                                                              (line  13)
* call-with-iterators:                   Fundamental iterator creators.
                                                              (line  56)
* call-with-output-conversion:           Conversion ports.    (line  75)
* call-with-output-file <1>:             Extended port procedures.
                                                              (line  16)
* call-with-output-file:                 File ports.          (line 134)
* call-with-output-process:              Process ports.       (line  99)
* call-with-output-string:               String ports.        (line  52)
* call-with-process-io:                  Process ports.       (line 117)
* call-with-string-io:                   String ports.        (line  74)
* call-with-values:                      Multiple values.     (line  14)
* call/cc:                               Continuation.        (line   8)
* car:                                   List accessors and modifiers.
                                                              (line   7)
* car+cdr:                               SRFI-1 List selectors.
                                                              (line  19)
* car-sxpath:                            SXPath query language.
                                                              (line  48)
* cartesian-product:                     Combination library. (line  82)
* cartesian-product-right:               Combination library. (line  83)
* case:                                  Conditionals.        (line  51)
* case-lambda:                           Making Procedures.   (line  78)
* cdaaar:                                List accessors and modifiers.
                                                              (line  19)
* cdaadr:                                List accessors and modifiers.
                                                              (line  19)
* cdaar:                                 List accessors and modifiers.
                                                              (line  19)
* cdadar:                                List accessors and modifiers.
                                                              (line  19)
* cdaddr:                                List accessors and modifiers.
                                                              (line  19)
* cdadr:                                 List accessors and modifiers.
                                                              (line  19)
* cdar:                                  List accessors and modifiers.
                                                              (line  19)
* cddaar:                                List accessors and modifiers.
                                                              (line  19)
* cddadr:                                List accessors and modifiers.
                                                              (line  19)
* cddar:                                 List accessors and modifiers.
                                                              (line  19)
* cdddar:                                List accessors and modifiers.
                                                              (line  22)
* cddddr:                                List accessors and modifiers.
                                                              (line  23)
* cdddr:                                 List accessors and modifiers.
                                                              (line  19)
* cddr:                                  List accessors and modifiers.
                                                              (line  19)
* cdr:                                   List accessors and modifiers.
                                                              (line   8)
* ceiling:                               Arithmetics.         (line  91)
* ces-conversion-supported?:             Supported character encoding schemes.
                                                              (line  18)
* ces-convert:                           Conversion ports.    (line  64)
* ces-equivalent?:                       Supported character encoding schemes.
                                                              (line  38)
* ces-guess-from-string:                 Autodetecting the encoding scheme.
                                                              (line  19)
* ces-upper-compatible?:                 Supported character encoding schemes.
                                                              (line  53)
* cgi-add-temporary-file:                CGI Utility.         (line 213)
* cgi-get-metavariable:                  CGI Utility.         (line  42)
* cgi-get-parameter:                     CGI Utility.         (line  92)
* cgi-header:                            CGI Utility.         (line 115)
* cgi-main:                              CGI Utility.         (line 148)
* cgi-metavariables:                     CGI Utility.         (line  21)
* cgi-output-character-encoding:         CGI Utility.         (line 136)
* cgi-parse-parameters:                  CGI Utility.         (line  55)
* cgi-temporary-files:                   CGI Utility.         (line 220)
* cgi-test-enviornment-ref:              CGI testing.         (line  13)
* change-class:                          Changing classes.    (line  14)
* change-object-class:                   Changing classes.    (line  19)
* char:                                  Characters.          (line  78)
* char->integer:                         Characters.          (line 104)
* char->ucs:                             Characters.          (line 115)
* char-alphabetic?:                      Characters.          (line  93)
* char-ci:                               Characters.          (line  84)
* char-downcase:                         Characters.          (line 132)
* char-lower-case?:                      Characters.          (line  97)
* char-numeric?:                         Characters.          (line  94)
* char-ready?:                           Reading data.        (line  99)
* char-set <1>:                          SRFI-14 Character-set Comparison.
                                                              (line  10)
* char-set:                              Character set.       (line  93)
* char-set->list:                        SRFI-14 Character-set query.
                                                              (line  13)
* char-set->string:                      SRFI-14 Character-set query.
                                                              (line  16)
* char-set-adjoin:                       SRFI-14 Character-set algebra.
                                                              (line   7)
* char-set-adjoin!:                      SRFI-14 Character-set algebra.
                                                              (line   8)
* char-set-any:                          SRFI-14 Character-set query.
                                                              (line  22)
* char-set-complement:                   SRFI-14 Character-set algebra.
                                                              (line  15)
* char-set-complement!:                  SRFI-14 Character-set algebra.
                                                              (line  16)
* char-set-contains?:                    Character set.       (line  84)
* char-set-copy:                         Character set.       (line  97)
* char-set-count:                        SRFI-14 Character-set query.
                                                              (line  10)
* char-set-cursor:                       SRFI-14 Character-set iteration.
                                                              (line   7)
* char-set-cursor-next:                  SRFI-14 Character-set iteration.
                                                              (line  13)
* char-set-delete:                       SRFI-14 Character-set algebra.
                                                              (line  11)
* char-set-delete!:                      SRFI-14 Character-set algebra.
                                                              (line  12)
* char-set-diff+intersection:            SRFI-14 Character-set algebra.
                                                              (line  35)
* char-set-diff+intersection!:           SRFI-14 Character-set algebra.
                                                              (line  37)
* char-set-difference:                   SRFI-14 Character-set algebra.
                                                              (line  27)
* char-set-difference!:                  SRFI-14 Character-set algebra.
                                                              (line  28)
* char-set-every:                        SRFI-14 Character-set query.
                                                              (line  19)
* char-set-filter:                       SRFI-14 Character-set constructors.
                                                              (line  20)
* char-set-filter!:                      SRFI-14 Character-set constructors.
                                                              (line  21)
* char-set-fold:                         SRFI-14 Character-set iteration.
                                                              (line  19)
* char-set-for-each:                     SRFI-14 Character-set iteration.
                                                              (line  26)
* char-set-hash:                         SRFI-14 Character-set Comparison.
                                                              (line  13)
* char-set-intersection:                 SRFI-14 Character-set algebra.
                                                              (line  23)
* char-set-intersection!:                SRFI-14 Character-set algebra.
                                                              (line  24)
* char-set-map:                          SRFI-14 Character-set iteration.
                                                              (line  29)
* char-set-ref:                          SRFI-14 Character-set iteration.
                                                              (line  10)
* char-set-size:                         SRFI-14 Character-set query.
                                                              (line   7)
* char-set-unfold:                       SRFI-14 Character-set iteration.
                                                              (line  22)
* char-set-unfold!:                      SRFI-14 Character-set iteration.
                                                              (line  23)
* char-set-union:                        SRFI-14 Character-set algebra.
                                                              (line  19)
* char-set-union!:                       SRFI-14 Character-set algebra.
                                                              (line  20)
* char-set-xor:                          SRFI-14 Character-set algebra.
                                                              (line  31)
* char-set-xor!:                         SRFI-14 Character-set algebra.
                                                              (line  32)
* char-set=:                             SRFI-14 Character-set Comparison.
                                                              (line   7)
* char-set?:                             Character set.       (line  80)
* char-upcase:                           Characters.          (line 131)
* char-upper-case?:                      Characters.          (line  96)
* char-whitespace?:                      Characters.          (line  95)
* char?:                                 Characters.          (line  73)
* check-substring-spec:                  SRFI-13 Low-level string procedures.
                                                              (line  15)
* circular-list:                         SRFI-1 List constructors.
                                                              (line  23)
* circular-list?:                        SRFI-1 List predicates.
                                                              (line  10)
* clamp:                                 Arithmetics.         (line 101)
* class-direct-methods:                  Class object.        (line  60)
* class-direct-slots:                    Class object.        (line  54)
* class-direct-subclasses:               Class object.        (line  35)
* class-direct-supers:                   Class object.        (line  28)
* class-name:                            Class object.        (line  14)
* class-of:                              General Inquiry.     (line   7)
* class-precedence-list:                 Class object.        (line  19)
* class-slot-accessor:                   Class object.        (line  63)
* class-slot-bound?:                     Accessing instance.  (line  79)
* class-slot-definition:                 Class object.        (line  50)
* class-slot-ref:                        Accessing instance.  (line  77)
* class-slot-set!:                       Accessing instance.  (line  78)
* class-slots:                           Class object.        (line  40)
* close-input-port:                      Common port operations.
                                                              (line  39)
* close-output-port:                     Common port operations.
                                                              (line  40)
* code:                                  Feature-based program configuration language.
                                                              (line  45)
* coerce-to:                             Miscellaneous operations on collection.
                                                              (line  21)
* combinations:                          Combination library. (line  39)
* combinations*:                         Combination library. (line  40)
* combinations*-for-each:                Combination library. (line  56)
* combinations-for-each:                 Combination library. (line  55)
* compare:                               Comparison and sorting.
                                                              (line   7)
* complete-sexp?:                        Listener.            (line 123)
* complex?:                              Numerical predicates.
                                                              (line   8)
* compose:                               Combinators.         (line  37)
* compute-get-n-set:                     Customizing slot access.
                                                              (line   9)
* compute-slots:                         Customizing slot access.
                                                              (line   7)
* concatenate:                           SRFI-1 List miscellaneous routines.
                                                              (line  11)
* concatenate!:                          SRFI-1 List miscellaneous routines.
                                                              (line  12)
* cond:                                  Conditionals.        (line  22)
* cond-expand:                           Feature conditional. (line  14)
* cond-list:                             Additional list library.
                                                              (line  73)
* condition:                             Conditions.          (line 236)
* condition-has-type?:                   Conditions.          (line 205)
* condition-ref:                         Conditions.          (line 209)
* condition-type?:                       Conditions.          (line 192)
* condition-variable-broadcast!:         Synchronization primitives.
                                                              (line 201)
* condition-variable-name:               Synchronization primitives.
                                                              (line 189)
* condition-variable-signal!:            Synchronization primitives.
                                                              (line 197)
* condition-variable-specific:           Synchronization primitives.
                                                              (line 192)
* condition-variable-specific-set!:      Synchronization primitives.
                                                              (line 193)
* condition-variable?:                   Synchronization primitives.
                                                              (line 181)
* cons:                                  List constructors.   (line   7)
* cons*:                                 SRFI-1 List constructors.
                                                              (line  11)
* construct-cookie-string:               HTTP cookie handling.
                                                              (line  29)
* copy-bit:                              Bitwise operations.  (line  44)
* copy-bit-field:                        Bitwise operations.  (line  48)
* copy-file:                             File operations.     (line  13)
* copy-port:                             Common port operations.
                                                              (line 125)
* copy-time:                             SRFI-19 Time procedures.
                                                              (line  24)
* cos:                                   Arithmetics.         (line 118)
* cosh:                                  Arithmetics.         (line 129)
* count:                                 SRFI-1 List miscellaneous routines.
                                                              (line  52)
* count$:                                SRFI-1 List miscellaneous routines.
                                                              (line  62)
* create-directory*:                     Directory utilities. (line 119)
* current-class-of:                      General Inquiry.     (line  31)
* current-country:                       Localization.        (line  43)
* current-date:                          SRFI-19 Time queries.
                                                              (line  13)
* current-directory:                     Directory utilities. (line   7)
* current-error-port:                    Common port operations.
                                                              (line  23)
* current-exception-handler:             Handling exceptions. (line  93)
* current-input-port:                    Common port operations.
                                                              (line  18)
* current-julian-day:                    SRFI-19 Time queries.
                                                              (line  19)
* current-language:                      Localization.        (line  42)
* current-load-history:                  Loading Scheme file. (line  76)
* current-load-next:                     Loading Scheme file. (line  77)
* current-load-port:                     Loading Scheme file. (line  75)
* current-locale-details:                Localization.        (line  44)
* current-modified-julian-day:           SRFI-19 Time queries.
                                                              (line  24)
* current-module:                        Defining and selecting modules.
                                                              (line  24)
* current-output-port:                   Common port operations.
                                                              (line  19)
* current-thread:                        Thread procedures.   (line  46)
* current-time <1>:                      Time.                (line 118)
* current-time:                          SRFI-19 Time queries.
                                                              (line   7)
* cut:                                   Making Procedures.   (line  40)
* cute:                                  Making Procedures.   (line  41)
* d:                                     Interactive session. (line  36)
* date->julian-day:                      SRFI-19 Date.        (line  74)
* date->modified-julian-day:             SRFI-19 Date.        (line  75)
* date->string:                          SRFI-19 Date reader and writer.
                                                              (line   7)
* date->time-monotonic:                  SRFI-19 Date.        (line  76)
* date->time-tai:                        SRFI-19 Date.        (line  77)
* date->time-utc:                        SRFI-19 Date.        (line  78)
* date-day:                              SRFI-19 Date.        (line  56)
* date-hour:                             SRFI-19 Date.        (line  55)
* date-minute:                           SRFI-19 Date.        (line  54)
* date-month:                            SRFI-19 Date.        (line  57)
* date-nanosecond:                       SRFI-19 Date.        (line  52)
* date-second:                           SRFI-19 Date.        (line  53)
* date-week-day:                         SRFI-19 Date.        (line  63)
* date-week-number:                      SRFI-19 Date.        (line  64)
* date-year:                             SRFI-19 Date.        (line  58)
* date-year-day:                         SRFI-19 Date.        (line  62)
* date-zone-offset:                      SRFI-19 Date.        (line  59)
* date?:                                 SRFI-19 Date.        (line  49)
* dbm-close:                             Opening and closing a dbm database.
                                                              (line  92)
* dbm-closed?:                           Opening and closing a dbm database.
                                                              (line  96)
* dbm-db-copy:                           Managing dbm database instance.
                                                              (line  25)
* dbm-db-exists?:                        Managing dbm database instance.
                                                              (line  16)
* dbm-db-move:                           Managing dbm database instance.
                                                              (line  30)
* dbm-db-remove:                         Managing dbm database instance.
                                                              (line  22)
* dbm-delete!:                           Accessing a dbm database.
                                                              (line  21)
* dbm-exists?:                           Accessing a dbm database.
                                                              (line  18)
* dbm-fold:                              Iterating on a database.
                                                              (line   9)
* dbm-for-each:                          Iterating on a database.
                                                              (line  19)
* dbm-get:                               Accessing a dbm database.
                                                              (line  13)
* dbm-map:                               Iterating on a database.
                                                              (line  24)
* dbm-open:                              Opening and closing a dbm database.
                                                              (line  82)
* dbm-put!:                              Accessing a dbm database.
                                                              (line  10)
* dcgettext:                             Localized messages.  (line  91)
* debug-print:                           Debugging aid.       (line   7)
* dec!:                                  Assignments.         (line 126)
* declare-bundle!:                       Localization.        (line  59)
* decode-float:                          Numerical conversions.
                                                              (line  22)
* decompose-path:                        Pathname utilities.  (line  32)
* define:                                Definitions.         (line   7)
* define-class:                          Defining class.      (line   9)
* define-condition-type:                 Conditions.          (line 167)
* define-constant:                       Definitions.         (line  49)
* define-generic:                        Generic function and method.
                                                              (line  10)
* define-in-module:                      Definitions.         (line  58)
* define-macro:                          Traditional Macros.  (line   7)
* define-method:                         Generic function and method.
                                                              (line  23)
* define-module:                         Defining and selecting modules.
                                                              (line   7)
* define-reader-ctor:                    Read-time constructor.
                                                              (line  23)
* define-record-type:                    Record types.        (line  18)
* define-syntax:                         Hygienic Macros.     (line  12)
* define-values:                         Definitions.         (line  40)
* delay:                                 Delayed Evaludation. (line  10)
* delete:                                SRFI-1 Deletion.     (line   7)
* delete!:                               SRFI-1 Deletion.     (line   8)
* delete$:                               SRFI-1 Deletion.     (line  14)
* delete-directory*:                     Directory utilities. (line 127)
* delete-duplicates:                     SRFI-1 Deletion.     (line  17)
* delete-duplicates!:                    SRFI-1 Deletion.     (line  18)
* delete-hook!:                          Hooks.               (line  48)
* delete-keyword:                        Keywords.            (line  65)
* delete-keyword!:                       Keywords.            (line  66)
* denominator:                           Arithmetics.         (line  84)
* dequeue!:                              Queue.               (line  48)
* dequeue-all!:                          Queue.               (line  55)
* describe:                              Interactive session. (line  35)
* determinant:                           Arrays.              (line 219)
* determinant!:                          Arrays.              (line 220)
* dgettext:                              Localized messages.  (line  90)
* diff:                                  Calculate difference of text streams.
                                                              (line  11)
* diff-report:                           Calculate difference of text streams.
                                                              (line  32)
* digest:                                Message digester framework.
                                                              (line  29)
* digest-final!:                         Message digester framework.
                                                              (line  25)
* digest-hexify:                         Message digester framework.
                                                              (line  39)
* digest-string:                         Message digester framework.
                                                              (line  34)
* digest-update!:                        Message digester framework.
                                                              (line  21)
* digit->integer:                        Characters.          (line 140)
* directory-fold:                        Directory utilities. (line  75)
* directory-list:                        Directory utilities. (line  31)
* directory-list2:                       Directory utilities. (line  63)
* disasm:                                Debugging aid.       (line  14)
* display:                               Output.              (line  11)
* do:                                    Iteration.           (line   8)
* do-ec:                                 Eager comprehensions.
                                                              (line  77)
* dolist:                                Iteration.           (line  15)
* dotimes:                               Iteration.           (line  14)
* dotted-list?:                          SRFI-1 List predicates.
                                                              (line  13)
* drop:                                  SRFI-1 List selectors.
                                                              (line  23)
* drop*:                                 Additional list library.
                                                              (line  32)
* drop-right:                            SRFI-1 List selectors.
                                                              (line  45)
* drop-right!:                           SRFI-1 List selectors.
                                                              (line  64)
* drop-right*:                           Additional list library.
                                                              (line  44)
* drop-while:                            SRFI-1 Searching.    (line  21)
* dynamic-load:                          Loading dynamic library.
                                                              (line   7)
* dynamic-wind:                          Continuation.        (line  51)
* eighth:                                SRFI-1 List selectors.
                                                              (line  14)
* end-of-char-set?:                      SRFI-14 Character-set iteration.
                                                              (line  16)
* enqueue!:                              Queue.               (line  31)
* enqueue-unique!:                       Queue.               (line  41)
* eof-object?:                           Reading data.        (line  96)
* eq-hash:                               Hashtables.          (line  73)
* eq?:                                   Equivalence.         (line  10)
* equal?:                                Equivalence.         (line  41)
* eqv-hash:                              Hashtables.          (line  74)
* eqv?:                                  Equivalence.         (line  26)
* error:                                 Signalling exceptions.
                                                              (line  15)
* errorf:                                Signalling exceptions.
                                                              (line  30)
* eval:                                  Eval and repl.       (line   7)
* even?:                                 Numerical predicates.
                                                              (line  53)
* every:                                 SRFI-1 Searching.    (line  38)
* every$:                                SRFI-1 Searching.    (line  52)
* every-pred:                            Combinators.         (line  78)
* every?-ec:                             Eager comprehensions.
                                                              (line 103)
* exact->inexact:                        Numerical conversions.
                                                              (line  51)
* exact?:                                Numerical predicates.
                                                              (line  26)
* exit:                                  Program termination. (line   7)
* exp:                                   Arithmetics.         (line 115)
* expand-path:                           Pathname utilities.  (line  16)
* export:                                Using modules.       (line   7)
* export-all:                            Using modules.       (line  11)
* expt:                                  Arithmetics.         (line 142)
* extend:                                Module inheritance.  (line  18)
* extract-condition:                     Conditions.          (line 231)
* f32vector:                             Uvector basic operations.
                                                              (line  19)
* f32vector->list:                       Uvector conversion operations.
                                                              (line   7)
* f32vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* f32vector-add:                         Uvector numeric operations.
                                                              (line  12)
* f32vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* f32vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* f32vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* f32vector-copy:                        Uvector basic operations.
                                                              (line  76)
* f32vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* f32vector-div:                         Uvector numeric operations.
                                                              (line  37)
* f32vector-div!:                        Uvector numeric operations.
                                                              (line  37)
* f32vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* f32vector-length:                      Uvector basic operations.
                                                              (line  32)
* f32vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* f32vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* f32vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* f32vector-ref:                         Uvector basic operations.
                                                              (line  43)
* f32vector-set!:                        Uvector basic operations.
                                                              (line  58)
* f32vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* f32vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* f32vector?:                            Uvector basic operations.
                                                              (line  16)
* f64vector:                             Uvector basic operations.
                                                              (line  19)
* f64vector->list:                       Uvector conversion operations.
                                                              (line   7)
* f64vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* f64vector-add:                         Uvector numeric operations.
                                                              (line  12)
* f64vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* f64vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* f64vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* f64vector-copy:                        Uvector basic operations.
                                                              (line  76)
* f64vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* f64vector-div:                         Uvector numeric operations.
                                                              (line  37)
* f64vector-div!:                        Uvector numeric operations.
                                                              (line  37)
* f64vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* f64vector-length:                      Uvector basic operations.
                                                              (line  32)
* f64vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* f64vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* f64vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* f64vector-ref:                         Uvector basic operations.
                                                              (line  43)
* f64vector-set!:                        Uvector basic operations.
                                                              (line  58)
* f64vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* f64vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* f64vector?:                            Uvector basic operations.
                                                              (line  16)
* feature-cond:                          Feature-based program configuration language.
                                                              (line  48)
* fifth:                                 SRFI-1 List selectors.
                                                              (line  11)
* file->list:                            File operations.     (line  73)
* file->sexp-list:                       File operations.     (line  75)
* file->string:                          File operations.     (line  72)
* file->string-list:                     File operations.     (line  74)
* file-atime:                            File attribute utilities.
                                                              (line  17)
* file-atime<=?:                         File attribute utilities.
                                                              (line  90)
* file-atime<?:                          File attribute utilities.
                                                              (line  90)
* file-atime=?:                          File attribute utilities.
                                                              (line  90)
* file-atime>=?:                         File attribute utilities.
                                                              (line  90)
* file-atime>?:                          File attribute utilities.
                                                              (line  90)
* file-ctime:                            File attribute utilities.
                                                              (line  19)
* file-ctime<=?:                         File attribute utilities.
                                                              (line  90)
* file-ctime<?:                          File attribute utilities.
                                                              (line  90)
* file-ctime=?:                          File attribute utilities.
                                                              (line  89)
* file-ctime>=?:                         File attribute utilities.
                                                              (line  90)
* file-ctime>?:                          File attribute utilities.
                                                              (line  90)
* file-dev:                              File attribute utilities.
                                                              (line  11)
* file-eq?:                              File attribute utilities.
                                                              (line  43)
* file-equal?:                           File attribute utilities.
                                                              (line  45)
* file-eqv?:                             File attribute utilities.
                                                              (line  44)
* file-exists?:                          File stats.          (line   9)
* file-filter:                           Filtering file content.
                                                              (line  25)
* file-gid:                              File attribute utilities.
                                                              (line  15)
* file-ino:                              File attribute utilities.
                                                              (line  10)
* file-is-directory?:                    File stats.          (line  11)
* file-is-executable?:                   File attribute utilities.
                                                              (line  34)
* file-is-readable?:                     File attribute utilities.
                                                              (line  32)
* file-is-regular?:                      File stats.          (line  10)
* file-is-symlink?:                      File attribute utilities.
                                                              (line  39)
* file-is-writable?:                     File attribute utilities.
                                                              (line  33)
* file-mode:                             File attribute utilities.
                                                              (line   9)
* file-mtime:                            File attribute utilities.
                                                              (line  18)
* file-mtime<=?:                         File attribute utilities.
                                                              (line  66)
* file-mtime<?:                          File attribute utilities.
                                                              (line  65)
* file-mtime=?:                          File attribute utilities.
                                                              (line  64)
* file-mtime>=?:                         File attribute utilities.
                                                              (line  68)
* file-mtime>?:                          File attribute utilities.
                                                              (line  67)
* file-nlink:                            File attribute utilities.
                                                              (line  13)
* file-perm:                             File attribute utilities.
                                                              (line   8)
* file-rdev:                             File attribute utilities.
                                                              (line  12)
* file-size:                             File attribute utilities.
                                                              (line  16)
* file-type:                             File attribute utilities.
                                                              (line   7)
* file-uid:                              File attribute utilities.
                                                              (line  14)
* files:                                 Feature-based program configuration language.
                                                              (line  40)
* filter:                                SRFI-1 Filtering & Partitioning.
                                                              (line   7)
* filter!:                               SRFI-1 Filtering & Partitioning.
                                                              (line   8)
* filter$:                               SRFI-1 Filtering & Partitioning.
                                                              (line  34)
* filter-map:                            SRFI-1 Fold.         (line 105)
* filter-to:                             Selection and searching in collection.
                                                              (line  22)
* find <1>:                              Selection and searching in collection.
                                                              (line   7)
* find:                                  SRFI-1 Searching.    (line   7)
* find$:                                 SRFI-1 Searching.    (line  49)
* find-file-in-paths:                    Pathname utilities.  (line  80)
* find-in-queue:                         Queue.               (line  82)
* find-index:                            Mapping over sequences.
                                                              (line  43)
* find-module:                           Module introspection.
                                                              (line  20)
* find-string-from-port?:                Parsing input stream.
                                                              (line  26)
* find-tail:                             SRFI-1 Searching.    (line  11)
* find-tail$:                            SRFI-1 Searching.    (line  50)
* find-with-index:                       Mapping over sequences.
                                                              (line  32)
* first:                                 SRFI-1 List selectors.
                                                              (line   7)
* first-ec:                              Eager comprehensions.
                                                              (line 106)
* fixnum?:                               Numerical predicates.
                                                              (line  61)
* floor:                                 Arithmetics.         (line  90)
* fluid-let:                             Binding constructs.  (line  40)
* flush:                                 Output.              (line  64)
* flush-all-ports:                       Output.              (line  65)
* fmod:                                  Numerical conversions.
                                                              (line  33)
* fold <1>:                              SRFI-1 Fold.         (line   7)
* fold:                                  Mapping over collection.
                                                              (line  11)
* fold$ <1>:                             Mapping over collection.
                                                              (line 139)
* fold$:                                 SRFI-1 Fold.         (line 112)
* fold-ec:                               Eager comprehensions.
                                                              (line 110)
* fold-right:                            SRFI-1 Fold.         (line  24)
* fold-right$:                           SRFI-1 Fold.         (line 113)
* fold-with-index:                       Mapping over sequences.
                                                              (line  12)
* fold2:                                 Mapping over collection.
                                                              (line  44)
* fold3:                                 Mapping over collection.
                                                              (line  45)
* fold3-ec:                              Eager comprehensions.
                                                              (line 111)
* for-each <1>:                          Mapping.             (line  22)
* for-each:                              Mapping over collection.
                                                              (line 123)
* for-each$ <1>:                         Mapping over collection.
                                                              (line 141)
* for-each$:                             Combinators.         (line  26)
* for-each-with-index:                   Mapping over sequences.
                                                              (line  22)
* force:                                 Delayed Evaludation. (line  15)
* format <1>:                            Output.              (line  80)
* format <2>:                            Localization.        (line  84)
* format:                                Output.              (line  81)
* fourth:                                SRFI-1 List selectors.
                                                              (line  10)
* frexp:                                 Numerical conversions.
                                                              (line  35)
* gauche-architecture:                   Environment Inquiry. (line  17)
* gauche-architecture-directory:         Environment Inquiry. (line  19)
* gauche-character-encoding:             Characters.          (line 158)
* gauche-config:                         Configuration parameters.
                                                              (line  14)
* gauche-library-directory:              Environment Inquiry. (line  18)
* gauche-site-architecture-directory:    Environment Inquiry. (line  21)
* gauche-site-library-directory:         Environment Inquiry. (line  20)
* gauche-thread-type:                    Threads.             (line  19)
* gauche-version:                        Environment Inquiry. (line  16)
* gcd:                                   Arithmetics.         (line  78)
* gdbm-close:                            GDBM interface.      (line  42)
* gdbm-closed?:                          GDBM interface.      (line  44)
* gdbm-delete:                           GDBM interface.      (line  54)
* gdbm-errno:                            GDBM interface.      (line  81)
* gdbm-exists:                           GDBM interface.      (line  64)
* gdbm-fetch:                            GDBM interface.      (line  52)
* gdbm-firstkey:                         GDBM interface.      (line  56)
* gdbm-nextkey:                          GDBM interface.      (line  58)
* gdbm-open:                             GDBM interface.      (line  27)
* gdbm-reorganize:                       GDBM interface.      (line  60)
* gdbm-setopt:                           GDBM interface.      (line  68)
* gdbm-store:                            GDBM interface.      (line  46)
* gdbm-strerror:                         GDBM interface.      (line  66)
* gdbm-sync:                             GDBM interface.      (line  62)
* gdbm-version:                          GDBM interface.      (line  79)
* gensym:                                Symbols.             (line  45)
* get-keyword:                           Keywords.            (line  29)
* get-keyword*:                          Keywords.            (line  61)
* get-optional:                          Optional argument parsing.
                                                              (line  65)
* get-output-string:                     String ports.        (line  41)
* get-remaining-input-string:            String ports.        (line  21)
* get-signal-handler:                    Handling signals.    (line  67)
* get-signal-handlers:                   Handling signals.    (line  70)
* getter-with-setter:                    Assignments.         (line  68)
* gettext:                               Localized messages.  (line  75)
* group-collection:                      Selection and searching in collection.
                                                              (line  67)
* group-sequence:                        Selection and searching in sequence.
                                                              (line  11)
* guard:                                 Handling exceptions. (line  10)
* has-setter?:                           Assignments.         (line  65)
* hash:                                  Hashtables.          (line  34)
* hash-table:                            Hashtables.          (line  95)
* hash-table->alist:                     Additional list library.
                                                              (line 104)
* hash-table-delete!:                    Hashtables.          (line 123)
* hash-table-exists?:                    Hashtables.          (line 120)
* hash-table-fold:                       Hashtables.          (line 174)
* hash-table-for-each:                   Hashtables.          (line 169)
* hash-table-get:                        Hashtables.          (line 108)
* hash-table-keys:                       Hashtables.          (line 181)
* hash-table-map:                        Hashtables.          (line 170)
* hash-table-num-entries:                Hashtables.          (line  92)
* hash-table-pop!:                       Hashtables.          (line 140)
* hash-table-push!:                      Hashtables.          (line 130)
* hash-table-put!:                       Hashtables.          (line 113)
* hash-table-type:                       Hashtables.          (line  88)
* hash-table-update!:                    Hashtables.          (line 150)
* hash-table-values:                     Hashtables.          (line 182)
* hash-table?:                           Hashtables.          (line  85)
* hmac-digest:                           HMAC keyed-hashing.  (line  36)
* hmac-digest-string:                    HMAC keyed-hashing.  (line  41)
* hmac-final!:                           HMAC keyed-hashing.  (line  30)
* hmac-update!:                          HMAC keyed-hashing.  (line  26)
* home-directory:                        Directory utilities. (line  17)
* hook->list:                            Hooks.               (line  56)
* hook-empty?:                           Hooks.               (line  39)
* hook?:                                 Hooks.               (line  36)
* html-doctype:                          Simple HTML document construction.
                                                              (line  29)
* html-escape:                           Simple HTML document construction.
                                                              (line  22)
* html-escape-string:                    Simple HTML document construction.
                                                              (line  23)
* html:a:                                Simple HTML document construction.
                                                              (line  53)
* html:abbr:                             Simple HTML document construction.
                                                              (line  53)
* html:acronym:                          Simple HTML document construction.
                                                              (line  53)
* html:address:                          Simple HTML document construction.
                                                              (line  53)
* html:area:                             Simple HTML document construction.
                                                              (line  53)
* html:b:                                Simple HTML document construction.
                                                              (line  53)
* html:base:                             Simple HTML document construction.
                                                              (line  53)
* html:bdo:                              Simple HTML document construction.
                                                              (line  53)
* html:big:                              Simple HTML document construction.
                                                              (line  53)
* html:blockquote:                       Simple HTML document construction.
                                                              (line  53)
* html:body:                             Simple HTML document construction.
                                                              (line  53)
* html:br:                               Simple HTML document construction.
                                                              (line  53)
* html:button:                           Simple HTML document construction.
                                                              (line  53)
* html:caption:                          Simple HTML document construction.
                                                              (line  53)
* html:cite:                             Simple HTML document construction.
                                                              (line  53)
* html:code:                             Simple HTML document construction.
                                                              (line  53)
* html:col:                              Simple HTML document construction.
                                                              (line  53)
* html:colgroup:                         Simple HTML document construction.
                                                              (line  53)
* html:dd:                               Simple HTML document construction.
                                                              (line  53)
* html:del:                              Simple HTML document construction.
                                                              (line  53)
* html:dfn:                              Simple HTML document construction.
                                                              (line  53)
* html:div:                              Simple HTML document construction.
                                                              (line  53)
* html:dl:                               Simple HTML document construction.
                                                              (line  53)
* html:dt:                               Simple HTML document construction.
                                                              (line  53)
* html:em:                               Simple HTML document construction.
                                                              (line  53)
* html:fieldset:                         Simple HTML document construction.
                                                              (line  53)
* html:form:                             Simple HTML document construction.
                                                              (line  53)
* html:frame:                            Simple HTML document construction.
                                                              (line  53)
* html:frameset:                         Simple HTML document construction.
                                                              (line  53)
* html:h1:                               Simple HTML document construction.
                                                              (line  53)
* html:h2:                               Simple HTML document construction.
                                                              (line  53)
* html:h3:                               Simple HTML document construction.
                                                              (line  53)
* html:h4:                               Simple HTML document construction.
                                                              (line  53)
* html:h5:                               Simple HTML document construction.
                                                              (line  53)
* html:h6:                               Simple HTML document construction.
                                                              (line  53)
* html:head:                             Simple HTML document construction.
                                                              (line  53)
* html:hr:                               Simple HTML document construction.
                                                              (line  53)
* html:html:                             Simple HTML document construction.
                                                              (line  53)
* html:i:                                Simple HTML document construction.
                                                              (line  53)
* html:iframe:                           Simple HTML document construction.
                                                              (line  53)
* html:img:                              Simple HTML document construction.
                                                              (line  53)
* html:input:                            Simple HTML document construction.
                                                              (line  53)
* html:ins:                              Simple HTML document construction.
                                                              (line  53)
* html:kbd:                              Simple HTML document construction.
                                                              (line  53)
* html:label:                            Simple HTML document construction.
                                                              (line  53)
* html:legend:                           Simple HTML document construction.
                                                              (line  53)
* html:li:                               Simple HTML document construction.
                                                              (line  53)
* html:link:                             Simple HTML document construction.
                                                              (line  53)
* html:map:                              Simple HTML document construction.
                                                              (line  53)
* html:meta:                             Simple HTML document construction.
                                                              (line  53)
* html:noframes:                         Simple HTML document construction.
                                                              (line  53)
* html:noscript:                         Simple HTML document construction.
                                                              (line  53)
* html:object:                           Simple HTML document construction.
                                                              (line  53)
* html:ol:                               Simple HTML document construction.
                                                              (line  53)
* html:optgroup:                         Simple HTML document construction.
                                                              (line  53)
* html:option:                           Simple HTML document construction.
                                                              (line  53)
* html:p:                                Simple HTML document construction.
                                                              (line  53)
* html:param:                            Simple HTML document construction.
                                                              (line  53)
* html:pre:                              Simple HTML document construction.
                                                              (line  53)
* html:q:                                Simple HTML document construction.
                                                              (line  53)
* html:samp:                             Simple HTML document construction.
                                                              (line  53)
* html:script:                           Simple HTML document construction.
                                                              (line  53)
* html:select:                           Simple HTML document construction.
                                                              (line  53)
* html:small:                            Simple HTML document construction.
                                                              (line  53)
* html:span:                             Simple HTML document construction.
                                                              (line  53)
* html:strong:                           Simple HTML document construction.
                                                              (line  53)
* html:style:                            Simple HTML document construction.
                                                              (line  53)
* html:sub:                              Simple HTML document construction.
                                                              (line  53)
* html:sup:                              Simple HTML document construction.
                                                              (line  53)
* html:table:                            Simple HTML document construction.
                                                              (line  53)
* html:tbody:                            Simple HTML document construction.
                                                              (line  53)
* html:td:                               Simple HTML document construction.
                                                              (line  53)
* html:textarea:                         Simple HTML document construction.
                                                              (line  53)
* html:tfoot:                            Simple HTML document construction.
                                                              (line  53)
* html:th:                               Simple HTML document construction.
                                                              (line  53)
* html:thead:                            Simple HTML document construction.
                                                              (line  53)
* html:title:                            Simple HTML document construction.
                                                              (line  53)
* html:tr:                               Simple HTML document construction.
                                                              (line  53)
* html:tt:                               Simple HTML document construction.
                                                              (line  53)
* html:ul:                               Simple HTML document construction.
                                                              (line  53)
* html:var:                              Simple HTML document construction.
                                                              (line  53)
* http-get:                              HTTP.                (line  19)
* http-head:                             HTTP.                (line  20)
* http-post:                             HTTP.                (line  22)
* identifier->symbol:                    Identifiers.         (line  11)
* identifier?:                           Identifiers.         (line   9)
* identity-array:                        Arrays.              (line 215)
* if <1>:                                Conditionals.        (line   7)
* if:                                    Eager comprehensions.
                                                              (line 120)
* if-car-sxpath:                         SXPath query language.
                                                              (line  45)
* if-sxpath:                             SXPath query language.
                                                              (line  41)
* imag-part:                             Numerical conversions.
                                                              (line  14)
* import:                                Using modules.       (line  15)
* inc!:                                  Assignments.         (line 125)
* inexact->exact:                        Numerical conversions.
                                                              (line  52)
* inexact?:                              Numerical predicates.
                                                              (line  27)
* info:                                  Interactive session. (line  42)
* initialize:                            Creating instance.   (line  31)
* input-port?:                           Common port operations.
                                                              (line   8)
* instance-of:                           Singleton.           (line  26)
* integer->char:                         Characters.          (line 105)
* integer->digit:                        Characters.          (line 150)
* integer-length:                        Bitwise operations.  (line  52)
* integer-range->char-set:               SRFI-14 Character-set constructors.
                                                              (line  34)
* integer-range->char-set!:              SRFI-14 Character-set constructors.
                                                              (line  35)
* integer?:                              Numerical predicates.
                                                              (line  11)
* interaction-environment:               Eval and repl.       (line  15)
* intersperse:                           Additional list library.
                                                              (line  65)
* iota:                                  SRFI-1 List constructors.
                                                              (line  27)
* is-a?:                                 General Inquiry.     (line  14)
* isomorphic?:                           Determine isomorphism.
                                                              (line  11)
* join-timeout-exception?:               Thread exceptions.   (line  47)
* julian-day->date:                      SRFI-19 Date.        (line  81)
* julian-day->time-monotonic:            SRFI-19 Date.        (line  82)
* julian-day->time-tai:                  SRFI-19 Date.        (line  83)
* julian-day->time-utc:                  SRFI-19 Date.        (line  84)
* keyword->string:                       Keywords.            (line  26)
* keyword?:                              Keywords.            (line  20)
* kmp-step:                              SRFI-13 Low-level string procedures.
                                                              (line  22)
* lambda:                                Making Procedures.   (line   7)
* last:                                  SRFI-1 List selectors.
                                                              (line  78)
* last-ec:                               Eager comprehensions.
                                                              (line 107)
* last-pair:                             List accessors and modifiers.
                                                              (line  54)
* lazy-size-of:                          Miscellaneous operations on collection.
                                                              (line  13)
* lcm:                                   Arithmetics.         (line  79)
* lcs:                                   The longest common subsequence.
                                                              (line  17)
* lcs-edit-list:                         The longest common subsequence.
                                                              (line  69)
* lcs-fold:                              The longest common subsequence.
                                                              (line  49)
* lcs-with-positions:                    The longest common subsequence.
                                                              (line  25)
* ldexp:                                 Numerical conversions.
                                                              (line  36)
* length:                                List accessors and modifiers.
                                                              (line  33)
* length+:                               SRFI-1 List miscellaneous routines.
                                                              (line   7)
* let <1>:                               A compatible let form with signatures and rest arguments.
                                                              (line  12)
* let <2>:                               Iteration.           (line  11)
* let <3>:                               A compatible let form with signatures and rest arguments.
                                                              (line  11)
* let:                                   Binding constructs.  (line   7)
* let*:                                  Binding constructs.  (line   8)
* let*-values:                           Let-values.          (line  40)
* let-args:                              Parsing command-line options.
                                                              (line 162)
* let-keywords*:                         Optional argument parsing.
                                                              (line  79)
* let-optionals*:                        Optional argument parsing.
                                                              (line  11)
* let-string-start+end:                  SRFI-13 Low-level string procedures.
                                                              (line  12)
* let-syntax:                            Hygienic Macros.     (line  15)
* let-values:                            Let-values.          (line  12)
* let/cc:                                Continuation.        (line  47)
* let1:                                  Binding constructs.  (line  34)
* letrec:                                Binding constructs.  (line   9)
* letrec-syntax:                         Hygienic Macros.     (line  16)
* library-exists?:                       Operations on libraries.
                                                              (line  94)
* library-fold:                          Operations on libraries.
                                                              (line  18)
* library-for-each:                      Operations on libraries.
                                                              (line  77)
* library-has-module?:                   Operations on libraries.
                                                              (line 105)
* library-map:                           Operations on libraries.
                                                              (line  75)
* list:                                  List constructors.   (line  22)
* list*:                                 List constructors.   (line  27)
* list->char-set:                        SRFI-14 Character-set constructors.
                                                              (line   7)
* list->char-set!:                       SRFI-14 Character-set constructors.
                                                              (line   8)
* list->f32vector:                       Uvector conversion operations.
                                                              (line  30)
* list->f64vector:                       Uvector conversion operations.
                                                              (line  30)
* list->queue:                           Queue.               (line  66)
* list->s16vector:                       Uvector conversion operations.
                                                              (line  30)
* list->s32vector:                       Uvector conversion operations.
                                                              (line  30)
* list->s64vector:                       Uvector conversion operations.
                                                              (line  30)
* list->s8vector:                        Uvector conversion operations.
                                                              (line  30)
* list->string:                          String utilities.    (line  14)
* list->u16vector:                       Uvector conversion operations.
                                                              (line  30)
* list->u32vector:                       Uvector conversion operations.
                                                              (line  30)
* list->u64vector:                       Uvector conversion operations.
                                                              (line  30)
* list->u8vector:                        Uvector conversion operations.
                                                              (line  30)
* list->vector:                          Vectors.             (line  55)
* list-copy:                             List constructors.   (line  33)
* list-ec:                               Eager comprehensions.
                                                              (line  80)
* list-index:                            SRFI-1 Searching.    (line  44)
* list-ref:                              List accessors and modifiers.
                                                              (line  45)
* list-tabulate:                         SRFI-1 List constructors.
                                                              (line  18)
* list-tail:                             List accessors and modifiers.
                                                              (line  41)
* list=:                                 SRFI-1 List predicates.
                                                              (line  29)
* list?:                                 List predicates.     (line  13)
* listener-read-handler:                 Listener.            (line  93)
* listener-show-prompt:                  Listener.            (line 117)
* load:                                  Loading Scheme file. (line   8)
* load-bundle!:                          Localization.        (line  69)
* load-from-port:                        Loading Scheme file. (line  68)
* localized-template:                    Localization.        (line  77)
* log:                                   Arithmetics.         (line 116)
* log-format:                            User-level logging.  (line 123)
* log-open:                              User-level logging.  (line 113)
* logand:                                Bitwise operations.  (line  25)
* logbit?:                               Bitwise operations.  (line  37)
* logcount:                              Bitwise operations.  (line  50)
* logior:                                Bitwise operations.  (line  26)
* lognot:                                Bitwise operations.  (line  31)
* logtest:                               Bitwise operations.  (line  34)
* logxor:                                Bitwise operations.  (line  27)
* lset-adjoin:                           SRFI-1 Set operations.
                                                              (line  28)
* lset-diff+intersection:                SRFI-1 Set operations.
                                                              (line  50)
* lset-diff+intersection!:               SRFI-1 Set operations.
                                                              (line  58)
* lset-difference:                       SRFI-1 Set operations.
                                                              (line  40)
* lset-difference!:                      SRFI-1 Set operations.
                                                              (line  56)
* lset-intersection:                     SRFI-1 Set operations.
                                                              (line  37)
* lset-intersection!:                    SRFI-1 Set operations.
                                                              (line  55)
* lset-union:                            SRFI-1 Set operations.
                                                              (line  34)
* lset-union!:                           SRFI-1 Set operations.
                                                              (line  54)
* lset-xor:                              SRFI-1 Set operations.
                                                              (line  44)
* lset-xor!:                             SRFI-1 Set operations.
                                                              (line  57)
* lset<=:                                SRFI-1 Set operations.
                                                              (line  17)
* lset=:                                 SRFI-1 Set operations.
                                                              (line  22)
* macroexpand:                           Macro expansion.     (line   7)
* macroexpand-1:                         Macro expansion.     (line   8)
* magnitude:                             Numerical conversions.
                                                              (line  15)
* make <1>:                              Creating instance.   (line  11)
* make <2>:                              Class instantiation. (line 143)
* make:                                  Method instantiation.
                                                              (line   7)
* make-array:                            Arrays.              (line  91)
* make-byte-string:                      String Constructors. (line  24)
* make-client-socket:                    High-level network functions.
                                                              (line  20)
* make-compound-condition:               Conditions.          (line 222)
* make-condition:                        Conditions.          (line 199)
* make-condition-type:                   Conditions.          (line 196)
* make-condition-variable:               Synchronization primitives.
                                                              (line 185)
* make-csv-reader:                       CSV tables.          (line  28)
* make-csv-writer:                       CSV tables.          (line  34)
* make-date:                             SRFI-19 Date.        (line  45)
* make-directory*:                       Directory utilities. (line 118)
* make-empty-attlist:                    SSAX data types.     (line 140)
* make-f32array:                         Arrays.              (line 105)
* make-f32vector:                        Uvector basic operations.
                                                              (line  25)
* make-f64array:                         Arrays.              (line 106)
* make-f64vector:                        Uvector basic operations.
                                                              (line  25)
* make-gettext:                          Localized messages.  (line 102)
* make-hash-table:                       Hashtables.          (line  10)
* make-hook:                             Hooks.               (line  32)
* make-keyword:                          Keywords.            (line  23)
* make-kmp-restart-vector:               SRFI-13 Low-level string procedures.
                                                              (line  19)
* make-list:                             List constructors.   (line  16)
* make-module:                           Module introspection.
                                                              (line  24)
* make-mutex:                            Synchronization primitives.
                                                              (line  37)
* make-option-parser:                    Parsing command-line options.
                                                              (line 220)
* make-packer:                           Packing Binary Data. (line 180)
* make-parameter:                        Parameters.          (line  39)
* make-polar:                            Numerical conversions.
                                                              (line   8)
* make-queue:                            Queue.               (line  18)
* make-random-source:                    Sources of random bits.
                                                              (line  28)
* make-record-type:                      SLIB-compatible record type.
                                                              (line  14)
* make-rectangular:                      Numerical conversions.
                                                              (line   7)
* make-s16array:                         Arrays.              (line 102)
* make-s16vector:                        Uvector basic operations.
                                                              (line  25)
* make-s32array:                         Arrays.              (line 102)
* make-s32vector:                        Uvector basic operations.
                                                              (line  25)
* make-s64array:                         Arrays.              (line 102)
* make-s64vector:                        Uvector basic operations.
                                                              (line  25)
* make-s8array:                          Arrays.              (line 102)
* make-s8vector:                         Uvector basic operations.
                                                              (line  25)
* make-server-socket:                    High-level network functions.
                                                              (line  61)
* make-server-sockets:                   High-level network functions.
                                                              (line 103)
* make-sockaddrs:                        Socket address.      (line  71)
* make-socket:                           Low-level socket interface.
                                                              (line  11)
* make-string:                           String Constructors. (line   7)
* make-string-pointer:                   String Pointers.     (line  16)
* make-thread:                           Thread procedures.   (line  53)
* make-time:                             SRFI-19 Time procedures.
                                                              (line   7)
* make-u16array:                         Arrays.              (line 102)
* make-u16vector:                        Uvector basic operations.
                                                              (line  25)
* make-u32array:                         Arrays.              (line 102)
* make-u32vector:                        Uvector basic operations.
                                                              (line  25)
* make-u64array:                         Arrays.              (line 102)
* make-u64vector:                        Uvector basic operations.
                                                              (line  25)
* make-u8array:                          Arrays.              (line 101)
* make-u8vector:                         Uvector basic operations.
                                                              (line  25)
* make-vector:                           Vectors.             (line  22)
* make-weak-vector:                      Weak pointers.       (line  35)
* make-xml-token:                        SSAX data types.     (line 149)
* map <1>:                               Mapping over collection.
                                                              (line  60)
* map:                                   Mapping.             (line   7)
* map!:                                  SRFI-1 Fold.         (line  90)
* map$ <1>:                              Mapping over collection.
                                                              (line 140)
* map$:                                  Combinators.         (line  25)
* map-accum:                             Mapping over collection.
                                                              (line 104)
* map-in-order:                          SRFI-1 Fold.         (line  95)
* map-to:                                Mapping over collection.
                                                              (line  89)
* map-to-with-index:                     Mapping over sequences.
                                                              (line  21)
* map-union:                             SXPath basic converters and applicators.
                                                              (line 131)
* map-with-index:                        Mapping over sequences.
                                                              (line  20)
* match:                                 Pattern matching.    (line  24)
* match-define:                          Pattern matching.    (line  84)
* match-lambda:                          Pattern matching.    (line  47)
* match-lambda*:                         Pattern matching.    (line  53)
* match-let:                             Pattern matching.    (line  60)
* match-let*:                            Pattern matching.    (line  61)
* match-let1:                            Pattern matching.    (line  76)
* match-letrec:                          Pattern matching.    (line  62)
* max:                                   Numerical comparison.
                                                              (line  23)
* max-ec:                                Eager comprehensions.
                                                              (line  99)
* md5-digest:                            MD5 message digest.  (line  24)
* md5-digest-string:                     MD5 message digest.  (line  28)
* member:                                Other list procedures.
                                                              (line  32)
* member$:                               SRFI-1 Searching.    (line  48)
* memq:                                  Other list procedures.
                                                              (line  30)
* memv:                                  Other list procedures.
                                                              (line  31)
* method-more-specific?:                 Customizing method application.
                                                              (line  11)
* mime-body->file:                       MIME message handling.
                                                              (line 153)
* mime-body->string:                     MIME message handling.
                                                              (line 152)
* mime-decode-word:                      MIME message handling.
                                                              (line  41)
* mime-parse-content-type:               MIME message handling.
                                                              (line  30)
* mime-parse-message:                    MIME message handling.
                                                              (line  54)
* mime-parse-version:                    MIME message handling.
                                                              (line  18)
* mime-retrieve-body:                    MIME message handling.
                                                              (line 133)
* min:                                   Numerical comparison.
                                                              (line  24)
* min&max:                               Numerical comparison.
                                                              (line  28)
* min-ec:                                Eager comprehensions.
                                                              (line  98)
* modf:                                  Numerical conversions.
                                                              (line  34)
* modified-julian-day->date:             SRFI-19 Date.        (line  87)
* modified-julian-day->time-monotonic:   SRFI-19 Date.        (line  88)
* modified-julian-day->time-tai:         SRFI-19 Date.        (line  89)
* modified-julian-day->time-utc:         SRFI-19 Date.        (line  90)
* modifier:                              Fundamental sequence accessors.
                                                              (line  37)
* module-exports:                        Module introspection.
                                                              (line  57)
* module-imports:                        Module introspection.
                                                              (line  56)
* module-name:                           Module introspection.
                                                              (line  55)
* module-name->path:                     Module introspection.
                                                              (line  79)
* module-parents:                        Module introspection.
                                                              (line  68)
* module-precedence-list:                Module introspection.
                                                              (line  69)
* module-reload-rules:                   Reloading modules.   (line  57)
* module-table:                          Module introspection.
                                                              (line  58)
* module?:                               Module introspection.
                                                              (line  17)
* modulo:                                Arithmetics.         (line  44)
* move-file:                             File operations.     (line  46)
* mt-random-fill-f32vector!:             Mersenne-Twister random number generator.
                                                              (line  57)
* mt-random-fill-f64vector!:             Mersenne-Twister random number generator.
                                                              (line  58)
* mt-random-fill-u32vector!:             Mersenne-Twister random number generator.
                                                              (line  56)
* mt-random-get-state:                   Mersenne-Twister random number generator.
                                                              (line  37)
* mt-random-integer:                     Mersenne-Twister random number generator.
                                                              (line  52)
* mt-random-real:                        Mersenne-Twister random number generator.
                                                              (line  45)
* mt-random-real0:                       Mersenne-Twister random number generator.
                                                              (line  46)
* mt-random-set-seed!:                   Mersenne-Twister random number generator.
                                                              (line  30)
* mt-random-set-state!:                  Mersenne-Twister random number generator.
                                                              (line  38)
* mutex-lock!:                           Synchronization primitives.
                                                              (line  66)
* mutex-name:                            Synchronization primitives.
                                                              (line  42)
* mutex-specific:                        Synchronization primitives.
                                                              (line  45)
* mutex-specific-set!:                   Synchronization primitives.
                                                              (line  46)
* mutex-state:                           Synchronization primitives.
                                                              (line  49)
* mutex-unlock!:                         Synchronization primitives.
                                                              (line 109)
* mutex?:                                Synchronization primitives.
                                                              (line  33)
* ndbm-clear-error:                      NDBM interface.      (line  38)
* ndbm-close:                            NDBM interface.      (line  22)
* ndbm-closed?:                          NDBM interface.      (line  24)
* ndbm-delete:                           NDBM interface.      (line  30)
* ndbm-error:                            NDBM interface.      (line  36)
* ndbm-fetch:                            NDBM interface.      (line  28)
* ndbm-firstkey:                         NDBM interface.      (line  32)
* ndbm-nextkey:                          NDBM interface.      (line  34)
* ndbm-open:                             NDBM interface.      (line  20)
* ndbm-store:                            NDBM interface.      (line  26)
* negative?:                             Numerical predicates.
                                                              (line  48)
* nested:                                Eager comprehensions.
                                                              (line 128)
* newline:                               Output.              (line  61)
* next-method:                           Generic function and method.
                                                              (line 101)
* next-token:                            Parsing input stream.
                                                              (line  77)
* next-token-of:                         Parsing input stream.
                                                              (line  87)
* ngettext:                              Localized messages.  (line  79)
* ninth:                                 SRFI-1 List selectors.
                                                              (line  15)
* node-closure:                          SXPath basic converters and applicators.
                                                              (line 206)
* node-eq?:                              SXPath basic converters and applicators.
                                                              (line  77)
* node-equal?:                           SXPath basic converters and applicators.
                                                              (line  78)
* node-join:                             SXPath basic converters and applicators.
                                                              (line 183)
* node-or:                               SXPath basic converters and applicators.
                                                              (line 199)
* node-pos:                              SXPath basic converters and applicators.
                                                              (line  83)
* node-reduce:                           SXPath basic converters and applicators.
                                                              (line 190)
* node-reverse:                          SXPath basic converters and applicators.
                                                              (line 139)
* node-self:                             SXPath basic converters and applicators.
                                                              (line 175)
* node-trace:                            SXPath basic converters and applicators.
                                                              (line 147)
* nodeset?:                              SXPath basic converters and applicators.
                                                              (line  14)
* not <1>:                               Booleans.            (line  10)
* not:                                   Eager comprehensions.
                                                              (line 122)
* not-pair?:                             SRFI-1 List predicates.
                                                              (line  22)
* ntype-names??:                         SXPath basic converters and applicators.
                                                              (line  24)
* ntype-namespace-id??:                  SXPath basic converters and applicators.
                                                              (line  66)
* ntype??:                               SXPath basic converters and applicators.
                                                              (line  31)
* null-environment:                      Eval and repl.       (line  13)
* null-list?:                            SRFI-1 List predicates.
                                                              (line  18)
* null?:                                 List predicates.     (line  10)
* number->string:                        Numerical conversions.
                                                              (line  68)
* number?:                               Numerical predicates.
                                                              (line   7)
* numerator:                             Arithmetics.         (line  83)
* object-apply:                          Applicable objects.  (line   9)
* object-compare:                        Comparison and sorting.
                                                              (line   9)
* object-equal?:                         Equivalence.         (line  58)
* object-hash:                           Hashtables.          (line  51)
* object-isomorphic?:                    Determine isomorphism.
                                                              (line  28)
* odbm-close:                            Original DBM interface.
                                                              (line  26)
* odbm-delete:                           Original DBM interface.
                                                              (line  32)
* odbm-fetch:                            Original DBM interface.
                                                              (line  30)
* odbm-firstkey:                         Original DBM interface.
                                                              (line  34)
* odbm-init:                             Original DBM interface.
                                                              (line  24)
* odbm-nextkey:                          Original DBM interface.
                                                              (line  36)
* odbm-store:                            Original DBM interface.
                                                              (line  28)
* odd?:                                  Numerical predicates.
                                                              (line  52)
* open-coding-aware-port:                Coding-aware ports.  (line  14)
* open-input-conversion-port:            Conversion ports.    (line   8)
* open-input-fd-port:                    File ports.          (line 186)
* open-input-file <1>:                   Extended port procedures.
                                                              (line   8)
* open-input-file:                       File ports.          (line   8)
* open-input-process-port:               Process ports.       (line   8)
* open-input-string:                     String ports.        (line   9)
* open-input-uvector:                    Virtual ports.       (line 288)
* open-output-conversion-port:           Conversion ports.    (line  49)
* open-output-fd-port:                   File ports.          (line 187)
* open-output-file <1>:                  Extended port procedures.
                                                              (line  14)
* open-output-file:                      File ports.          (line  10)
* open-output-process-port:              Process ports.       (line  80)
* open-output-string:                    String ports.        (line  34)
* open-output-uvector:                   Virtual ports.       (line 294)
* option:                                A program argument processor.
                                                              (line  74)
* option-names:                          A program argument processor.
                                                              (line 103)
* option-optional-arg?:                  A program argument processor.
                                                              (line 105)
* option-processor:                      A program argument processor.
                                                              (line 106)
* option-required-arg?:                  A program argument processor.
                                                              (line 104)
* option?:                               A program argument processor.
                                                              (line 100)
* or <1>:                                Conditionals.        (line  93)
* or:                                    Eager comprehensions.
                                                              (line 124)
* output-port?:                          Common port operations.
                                                              (line   9)
* pa$:                                   Combinators.         (line  10)
* pack:                                  Packing Binary Data. (line  22)
* pair-fold:                             SRFI-1 Fold.         (line  42)
* pair-fold-right:                       SRFI-1 Fold.         (line  43)
* pair-for-each:                         SRFI-1 Fold.         (line 101)
* pair?:                                 List predicates.     (line   7)
* parameter-observer-add!:               Parameters.          (line  63)
* parameter-observer-delete!:            Parameters.          (line  85)
* parameter-post-observers:              Parameters.          (line  93)
* parameter-pre-observers:               Parameters.          (line  92)
* parameterize:                          Parameters.          (line  48)
* parse-cookie-string:                   HTTP cookie handling.
                                                              (line  11)
* parse-options:                         Parsing command-line options.
                                                              (line  19)
* partition <1>:                         SRFI-1 Filtering & Partitioning.
                                                              (line  23)
* partition:                             Selection and searching in collection.
                                                              (line  47)
* partition!:                            SRFI-1 Filtering & Partitioning.
                                                              (line  24)
* partition$:                            SRFI-1 Filtering & Partitioning.
                                                              (line  36)
* partition-to:                          Selection and searching in collection.
                                                              (line  58)
* path->module-name:                     Module introspection.
                                                              (line  82)
* path-extension:                        Pathname utilities.  (line  58)
* path-sans-extension:                   Pathname utilities.  (line  59)
* path-swap-extension:                   Pathname utilities.  (line  70)
* peek-byte:                             Reading data.        (line  45)
* peek-char:                             Reading data.        (line  34)
* peek-next-char:                        Parsing input stream.
                                                              (line  38)
* permutations:                          Combination library. (line  17)
* permutations*:                         Combination library. (line  18)
* permutations*-for-each:                Combination library. (line  35)
* permutations-for-each:                 Combination library. (line  34)
* pop!:                                  Assignments.         (line 108)
* port->list:                            Input utility functions.
                                                              (line   8)
* port->sexp-list:                       Input utility functions.
                                                              (line  10)
* port->string:                          Input utility functions.
                                                              (line   7)
* port->string-list:                     Input utility functions.
                                                              (line   9)
* port-buffering:                        Common port operations.
                                                              (line  52)
* port-closed?:                          Common port operations.
                                                              (line  14)
* port-current-line:                     Common port operations.
                                                              (line  65)
* port-file-number:                      Common port operations.
                                                              (line  70)
* port-fold:                             Input utility functions.
                                                              (line  23)
* port-fold-right:                       Input utility functions.
                                                              (line  24)
* port-for-each:                         Input utility functions.
                                                              (line  25)
* port-map:                              Input utility functions.
                                                              (line  26)
* port-name:                             Common port operations.
                                                              (line  47)
* port-seek:                             Common port operations.
                                                              (line  74)
* port-tell:                             Common port operations.
                                                              (line 108)
* port-type:                             Common port operations.
                                                              (line  43)
* port?:                                 Common port operations.
                                                              (line   7)
* positive?:                             Numerical predicates.
                                                              (line  47)
* power-set:                             Combination library. (line  60)
* power-set*:                            Combination library. (line  61)
* power-set*-for-each:                   Combination library. (line  71)
* power-set-binary:                      Combination library. (line  74)
* power-set-for-each:                    Combination library. (line  70)
* print:                                 Output.              (line  54)
* procedure-arity-includes?:             Procedure arity.     (line  35)
* procedure?:                            Procedures.          (line   9)
* process-alive?:                        Process object.      (line  81)
* process-command:                       Process object.      (line  61)
* process-continue:                      Process object.      (line 129)
* process-error:                         Process object.      (line  66)
* process-exit-status:                   Process object.      (line 117)
* process-input:                         Process object.      (line  64)
* process-kill:                          Process object.      (line 127)
* process-list:                          Process object.      (line  86)
* process-output:                        Process object.      (line  65)
* process-output->string:                Process ports.       (line 128)
* process-output->string-list:           Process ports.       (line 129)
* process-pid:                           Process object.      (line  58)
* process-send-signal:                   Process object.      (line 122)
* process-stop:                          Process object.      (line 128)
* process-wait:                          Process object.      (line  92)
* process-wait-any:                      Process object.      (line 104)
* process?:                              Process object.      (line  55)
* product-ec:                            Eager comprehensions.
                                                              (line  97)
* profiler-reset:                        Profiler API.        (line  23)
* profiler-show:                         Profiler API.        (line  27)
* profiler-start:                        Profiler API.        (line  13)
* profiler-stop:                         Profiler API.        (line  17)
* program:                               Feature-based program configuration language.
                                                              (line  23)
* promise?:                              Delayed Evaludation. (line  25)
* proper-list?:                          SRFI-1 List predicates.
                                                              (line   7)
* provide:                               Require and provide. (line  16)
* provided?:                             Require and provide. (line  24)
* push!:                                 Assignments.         (line  80)
* quasiquote:                            Quasiquotation.      (line   7)
* queue->list:                           Queue.               (line  70)
* queue-empty?:                          Queue.               (line  25)
* queue-front:                           Queue.               (line  60)
* queue-length:                          Queue.               (line  28)
* queue-pop!:                            Queue.               (line  49)
* queue-push!:                           Queue.               (line  36)
* queue-push-unique!:                    Queue.               (line  43)
* queue-rear:                            Queue.               (line  61)
* queue?:                                Queue.               (line  21)
* quote:                                 Literals.            (line   7)
* quoted-printable-decode:               Quoted-printable encoding/decoding.
                                                              (line  23)
* quoted-printable-decode-string:        Quoted-printable encoding/decoding.
                                                              (line  31)
* quoted-printable-encode:               Quoted-printable encoding/decoding.
                                                              (line  12)
* quoted-printable-encode-string:        Quoted-printable encoding/decoding.
                                                              (line  18)
* quotient:                              Arithmetics.         (line  42)
* quotient&remainder:                    Arithmetics.         (line  74)
* raise:                                 Signalling exceptions.
                                                              (line  39)
* random-integer:                        Sources of random bits.
                                                              (line  12)
* random-real:                           Sources of random bits.
                                                              (line  18)
* random-source-make-integers:           Sources of random bits.
                                                              (line  55)
* random-source-make-reals:              Sources of random bits.
                                                              (line  60)
* random-source-pseudo-randomize!:       Sources of random bits.
                                                              (line  47)
* random-source-randomize!:              Sources of random bits.
                                                              (line  42)
* random-source-state-ref:               Sources of random bits.
                                                              (line  36)
* random-source-state-set!:              Sources of random bits.
                                                              (line  37)
* random-source?:                        Sources of random bits.
                                                              (line  33)
* rassoc:                                Additional list library.
                                                              (line 107)
* rassoc-ref:                            Additional list library.
                                                              (line 133)
* rassq:                                 Additional list library.
                                                              (line 108)
* rassq-ref:                             Additional list library.
                                                              (line 134)
* rassv:                                 Additional list library.
                                                              (line 109)
* rassv-ref:                             Additional list library.
                                                              (line 135)
* rational?:                             Numerical predicates.
                                                              (line  10)
* read:                                  Reading data.        (line   7)
* read-block:                            Reading data.        (line  67)
* read-block!:                           Uvector block I/O.   (line  10)
* read-byte:                             Reading data.        (line  40)
* read-char:                             Reading data.        (line  27)
* read-eval-print-loop:                  Eval and repl.       (line  33)
* read-from-string:                      String ports.        (line  89)
* read-line:                             Reading data.        (line  50)
* read-string:                           Parsing input stream.
                                                              (line  98)
* read-with-shared-structure:            Reading data.        (line  20)
* read/ss:                               Reading data.        (line  21)
* real-part:                             Numerical conversions.
                                                              (line  13)
* real?:                                 Numerical predicates.
                                                              (line   9)
* rec:                                   Binding constructs.  (line  83)
* receive:                               Binding constructs.  (line  58)
* record-accessor:                       SLIB-compatible record type.
                                                              (line  37)
* record-constructor:                    SLIB-compatible record type.
                                                              (line  27)
* record-modifier:                       SLIB-compatible record type.
                                                              (line  42)
* record-predicate:                      SLIB-compatible record type.
                                                              (line  33)
* reduce:                                SRFI-1 Fold.         (line  47)
* reduce$:                               SRFI-1 Fold.         (line 114)
* reduce-right:                          SRFI-1 Fold.         (line  48)
* reduce-right$:                         SRFI-1 Fold.         (line 115)
* ref <1>:                               Accessing instance.  (line  49)
* ref <2>:                               Hashtables.          (line 116)
* ref:                                   Fundamental sequence accessors.
                                                              (line   7)
* referencer:                            Fundamental sequence accessors.
                                                              (line  35)
* regexp->string:                        Regular expression.  (line 160)
* regexp-quote:                          Regular expression utilities.
                                                              (line 201)
* regexp-replace:                        Regular expression utilities.
                                                              (line 161)
* regexp-replace-all:                    Regular expression utilities.
                                                              (line 162)
* regexp?:                               Regular expression.  (line 157)
* relative-path?:                        Pathname utilities.  (line  13)
* relnum-compare:                        Comparing version numbers.
                                                              (line 100)
* reload:                                Reloading modules.   (line  44)
* reload-modified-modules:               Reloading modules.   (line  49)
* reload-verbose:                        Reloading modules.   (line  63)
* remainder:                             Arithmetics.         (line  43)
* remove <1>:                            SRFI-1 Filtering & Partitioning.
                                                              (line  15)
* remove:                                Selection and searching in collection.
                                                              (line  30)
* remove!:                               SRFI-1 Filtering & Partitioning.
                                                              (line  16)
* remove$:                               SRFI-1 Filtering & Partitioning.
                                                              (line  35)
* remove-directory*:                     Directory utilities. (line 126)
* remove-from-queue!:                    Queue.               (line  87)
* remove-hook!:                          Hooks.               (line  49)
* remove-to:                             Selection and searching in collection.
                                                              (line  39)
* require:                               Require and provide. (line   7)
* require-extension:                     Requiring extensions.
                                                              (line  17)
* requires:                              Feature-based program configuration language.
                                                              (line  32)
* reset-hook!:                           Hooks.               (line  53)
* resolve-path:                          Pathname utilities.  (line  21)
* reverse:                               Other list procedures.
                                                              (line  21)
* reverse!:                              Other list procedures.
                                                              (line  25)
* reverse-list->string:                  SRFI-13 String Constructors.
                                                              (line  16)
* rfc822-atom:                           RFC822 message parsing.
                                                              (line 131)
* rfc822-date->date:                     RFC822 message parsing.
                                                              (line 150)
* rfc822-dot-atom:                       RFC822 message parsing.
                                                              (line 132)
* rfc822-field->tokens:                  RFC822 message parsing.
                                                              (line 113)
* rfc822-header->list:                   RFC822 message parsing.
                                                              (line  21)
* rfc822-header-ref:                     RFC822 message parsing.
                                                              (line  44)
* rfc822-next-token:                     RFC822 message parsing.
                                                              (line  76)
* rfc822-parse-date:                     RFC822 message parsing.
                                                              (line 141)
* rfc822-quoted-string:                  RFC822 message parsing.
                                                              (line 133)
* rfc822-skip-cfws:                      RFC822 message parsing.
                                                              (line 119)
* round:                                 Arithmetics.         (line  93)
* run-cgi-script->header&body:           CGI testing.         (line  60)
* run-cgi-script->string:                CGI testing.         (line  79)
* run-cgi-script->string-list:           CGI testing.         (line  81)
* run-cgi-script->sxml:                  CGI testing.         (line  72)
* run-hook:                              Hooks.               (line  59)
* run-process:                           Process object.      (line  22)
* rxmatch:                               Regular expression.  (line 164)
* rxmatch-after:                         Regular expression.  (line 211)
* rxmatch-before:                        Regular expression.  (line 212)
* rxmatch-case:                          Regular expression utilities.
                                                              (line 110)
* rxmatch-cond:                          Regular expression utilities.
                                                              (line  66)
* rxmatch-end:                           Regular expression.  (line 179)
* rxmatch-if:                            Regular expression utilities.
                                                              (line  47)
* rxmatch-let:                           Regular expression utilities.
                                                              (line  23)
* rxmatch-num-matches:                   Regular expression.  (line 192)
* rxmatch-start:                         Regular expression.  (line 178)
* rxmatch-substring:                     Regular expression.  (line 180)
* s16vector:                             Uvector basic operations.
                                                              (line  19)
* s16vector->list:                       Uvector conversion operations.
                                                              (line   7)
* s16vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* s16vector-add:                         Uvector numeric operations.
                                                              (line  12)
* s16vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* s16vector-and:                         Uvector numeric operations.
                                                              (line  49)
* s16vector-and!:                        Uvector numeric operations.
                                                              (line  49)
* s16vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* s16vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* s16vector-copy:                        Uvector basic operations.
                                                              (line  76)
* s16vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* s16vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* s16vector-ior:                         Uvector numeric operations.
                                                              (line  49)
* s16vector-ior!:                        Uvector numeric operations.
                                                              (line  49)
* s16vector-length:                      Uvector basic operations.
                                                              (line  32)
* s16vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* s16vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* s16vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* s16vector-ref:                         Uvector basic operations.
                                                              (line  43)
* s16vector-set!:                        Uvector basic operations.
                                                              (line  58)
* s16vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* s16vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* s16vector-xor:                         Uvector numeric operations.
                                                              (line  49)
* s16vector-xor!:                        Uvector numeric operations.
                                                              (line  49)
* s16vector?:                            Uvector basic operations.
                                                              (line  16)
* s32vector:                             Uvector basic operations.
                                                              (line  19)
* s32vector->list:                       Uvector conversion operations.
                                                              (line   7)
* s32vector->string:                     Uvector conversion operations.
                                                              (line 100)
* s32vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* s32vector-add:                         Uvector numeric operations.
                                                              (line  12)
* s32vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* s32vector-and:                         Uvector numeric operations.
                                                              (line  49)
* s32vector-and!:                        Uvector numeric operations.
                                                              (line  49)
* s32vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* s32vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* s32vector-copy:                        Uvector basic operations.
                                                              (line  76)
* s32vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* s32vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* s32vector-ior:                         Uvector numeric operations.
                                                              (line  49)
* s32vector-ior!:                        Uvector numeric operations.
                                                              (line  49)
* s32vector-length:                      Uvector basic operations.
                                                              (line  32)
* s32vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* s32vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* s32vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* s32vector-ref:                         Uvector basic operations.
                                                              (line  43)
* s32vector-set!:                        Uvector basic operations.
                                                              (line  58)
* s32vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* s32vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* s32vector-xor:                         Uvector numeric operations.
                                                              (line  49)
* s32vector-xor!:                        Uvector numeric operations.
                                                              (line  49)
* s32vector?:                            Uvector basic operations.
                                                              (line  16)
* s64vector:                             Uvector basic operations.
                                                              (line  19)
* s64vector->list:                       Uvector conversion operations.
                                                              (line   7)
* s64vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* s64vector-add:                         Uvector numeric operations.
                                                              (line  12)
* s64vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* s64vector-and:                         Uvector numeric operations.
                                                              (line  49)
* s64vector-and!:                        Uvector numeric operations.
                                                              (line  49)
* s64vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* s64vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* s64vector-copy:                        Uvector basic operations.
                                                              (line  76)
* s64vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* s64vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* s64vector-ior:                         Uvector numeric operations.
                                                              (line  49)
* s64vector-ior!:                        Uvector numeric operations.
                                                              (line  49)
* s64vector-length:                      Uvector basic operations.
                                                              (line  32)
* s64vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* s64vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* s64vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* s64vector-ref:                         Uvector basic operations.
                                                              (line  43)
* s64vector-set!:                        Uvector basic operations.
                                                              (line  58)
* s64vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* s64vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* s64vector-xor:                         Uvector numeric operations.
                                                              (line  49)
* s64vector-xor!:                        Uvector numeric operations.
                                                              (line  49)
* s64vector?:                            Uvector basic operations.
                                                              (line  16)
* s8vector:                              Uvector basic operations.
                                                              (line  19)
* s8vector->list:                        Uvector conversion operations.
                                                              (line   7)
* s8vector->string:                      Uvector conversion operations.
                                                              (line  80)
* s8vector->vector:                      Uvector conversion operations.
                                                              (line  18)
* s8vector-add:                          Uvector numeric operations.
                                                              (line  12)
* s8vector-add!:                         Uvector numeric operations.
                                                              (line  12)
* s8vector-and:                          Uvector numeric operations.
                                                              (line  49)
* s8vector-and!:                         Uvector numeric operations.
                                                              (line  49)
* s8vector-clamp:                        Uvector numeric operations.
                                                              (line  94)
* s8vector-clamp!:                       Uvector numeric operations.
                                                              (line  94)
* s8vector-copy:                         Uvector basic operations.
                                                              (line  76)
* s8vector-copy!:                        Uvector basic operations.
                                                              (line  84)
* s8vector-dot:                          Uvector numeric operations.
                                                              (line  59)
* s8vector-ior:                          Uvector numeric operations.
                                                              (line  49)
* s8vector-ior!:                         Uvector numeric operations.
                                                              (line  49)
* s8vector-length:                       Uvector basic operations.
                                                              (line  32)
* s8vector-mul:                          Uvector numeric operations.
                                                              (line  12)
* s8vector-mul!:                         Uvector numeric operations.
                                                              (line  12)
* s8vector-range-check:                  Uvector numeric operations.
                                                              (line  63)
* s8vector-ref:                          Uvector basic operations.
                                                              (line  43)
* s8vector-set!:                         Uvector basic operations.
                                                              (line  58)
* s8vector-sub:                          Uvector numeric operations.
                                                              (line  12)
* s8vector-sub!:                         Uvector numeric operations.
                                                              (line  12)
* s8vector-xor:                          Uvector numeric operations.
                                                              (line  49)
* s8vector-xor!:                         Uvector numeric operations.
                                                              (line  49)
* s8vector?:                             Uvector basic operations.
                                                              (line  16)
* save-bundle!:                          Localization.        (line  68)
* scheme-report-environment:             Eval and repl.       (line  14)
* second:                                SRFI-1 List selectors.
                                                              (line   8)
* seconds->time:                         Time.                (line 128)
* select-kids:                           SXPath basic converters and applicators.
                                                              (line 166)
* select-module:                         Defining and selecting modules.
                                                              (line  11)
* selector-add!:                         Simple dispatcher.   (line  16)
* selector-delete!:                      Simple dispatcher.   (line  38)
* selector-select:                       Simple dispatcher.   (line  47)
* set!:                                  Assignments.         (line   7)
* set!-values:                           Assignments.         (line  30)
* set-car!:                              List accessors and modifiers.
                                                              (line  11)
* set-cdr!:                              List accessors and modifiers.
                                                              (line  12)
* set-signal-handler!:                   Handling signals.    (line  48)
* set-time-nanosecond!:                  SRFI-19 Time procedures.
                                                              (line  21)
* set-time-second!:                      SRFI-19 Time procedures.
                                                              (line  20)
* set-time-type!:                        SRFI-19 Time procedures.
                                                              (line  19)
* setter:                                Assignments.         (line  43)
* seventh:                               SRFI-1 List selectors.
                                                              (line  13)
* sha1-digest:                           SHA1 message digest. (line  24)
* sha1-digest-string:                    SHA1 message digest. (line  28)
* shape:                                 Arrays.              (line 110)
* shape-for-each:                        Arrays.              (line 190)
* share-array:                           Arrays.              (line 176)
* simplify-path:                         Pathname utilities.  (line  27)
* sin:                                   Arithmetics.         (line 117)
* sinh:                                  Arithmetics.         (line 128)
* sixth:                                 SRFI-1 List selectors.
                                                              (line  12)
* size-of:                               Miscellaneous operations on collection.
                                                              (line   7)
* skip-until:                            Parsing input stream.
                                                              (line  58)
* skip-while:                            Parsing input stream.
                                                              (line  66)
* slices:                                Additional list library.
                                                              (line  54)
* slot-bound-using-class?:               Accessing instance.  (line  89)
* slot-bound?:                           Accessing instance.  (line  31)
* slot-defininion-setter:                Slot definition object.
                                                              (line  26)
* slot-definition-accessor:              Slot definition object.
                                                              (line  27)
* slot-definition-allocation:            Slot definition object.
                                                              (line  22)
* slot-definition-getter:                Slot definition object.
                                                              (line  25)
* slot-definition-name:                  Slot definition object.
                                                              (line  15)
* slot-definition-option:                Slot definition object.
                                                              (line  31)
* slot-definition-options:               Slot definition object.
                                                              (line  19)
* slot-exists?:                          Accessing instance.  (line  39)
* slot-missing:                          Accessing instance.  (line  67)
* slot-push!:                            Accessing instance.  (line  42)
* slot-ref:                              Accessing instance.  (line  10)
* slot-ref-using-accessor:               Customizing slot access.
                                                              (line  11)
* slot-ref-using-class:                  Accessing instance.  (line  85)
* slot-set!:                             Accessing instance.  (line  23)
* slot-set-using-accessor:               Customizing slot access.
                                                              (line  12)
* slot-set-using-class!:                 Accessing instance.  (line  87)
* slot-unbound:                          Accessing instance.  (line  59)
* sockaddr-addr:                         Socket address.      (line  46)
* sockaddr-family:                       Socket address.      (line  38)
* sockaddr-name:                         Socket address.      (line  61)
* sockaddr-port:                         Socket address.      (line  49)
* socket-accept:                         Low-level socket interface.
                                                              (line  59)
* socket-address:                        High-level network functions.
                                                              (line 119)
* socket-bind:                           Low-level socket interface.
                                                              (line  44)
* socket-close:                          High-level network functions.
                                                              (line 131)
* socket-connect:                        Low-level socket interface.
                                                              (line  68)
* socket-fd:                             Low-level socket interface.
                                                              (line  28)
* socket-getpeername:                    Low-level socket interface.
                                                              (line  87)
* socket-getsockname:                    Low-level socket interface.
                                                              (line  83)
* socket-getsockopt:                     Low-level socket interface.
                                                              (line 134)
* socket-input-port:                     High-level network functions.
                                                              (line 123)
* socket-listen:                         Low-level socket interface.
                                                              (line  54)
* socket-output-port:                    High-level network functions.
                                                              (line 124)
* socket-recv:                           Low-level socket interface.
                                                              (line 103)
* socket-recvfrom:                       Low-level socket interface.
                                                              (line 104)
* socket-send:                           Low-level socket interface.
                                                              (line  90)
* socket-sendto:                         Low-level socket interface.
                                                              (line  91)
* socket-setsockopt:                     Low-level socket interface.
                                                              (line 133)
* socket-shutdown:                       Low-level socket interface.
                                                              (line  72)
* socket-status:                         Low-level socket interface.
                                                              (line  31)
* sort:                                  Comparison and sorting.
                                                              (line  11)
* sort!:                                 Comparison and sorting.
                                                              (line  12)
* sort-applicable-methods:               Customizing method application.
                                                              (line   9)
* span:                                  SRFI-1 Searching.    (line  25)
* span!:                                 SRFI-1 Searching.    (line  26)
* split-at:                              SRFI-1 List selectors.
                                                              (line  70)
* split-at!:                             SRFI-1 List selectors.
                                                              (line  71)
* split-at*:                             Additional list library.
                                                              (line  47)
* sqrt:                                  Arithmetics.         (line 137)
* ssax:assert-token:                     SSAX higher-level parsers and scanners.
                                                              (line  71)
* ssax:complete-start-tag:               SSAX low-level parsing code.
                                                              (line 216)
* ssax:handle-parsed-entity:             SSAX low-level parsing code.
                                                              (line 146)
* ssax:make-elem-parser:                 SSAX Highest-level parsers - XML to SXML.
                                                              (line  33)
* ssax:make-parser:                      SSAX Highest-level parsers - XML to SXML.
                                                              (line  70)
* ssax:make-pi-parser:                   SSAX Highest-level parsers - XML to SXML.
                                                              (line  14)
* ssax:ncname-starting-char?:            SSAX low-level parsing code.
                                                              (line  20)
* ssax:read-attributes:                  SSAX low-level parsing code.
                                                              (line 165)
* ssax:read-cdata-body:                  SSAX low-level parsing code.
                                                              (line  97)
* ssax:read-char-data:                   SSAX higher-level parsers and scanners.
                                                              (line  21)
* ssax:read-char-ref:                    SSAX low-level parsing code.
                                                              (line 126)
* ssax:read-external-id:                 SSAX low-level parsing code.
                                                              (line 252)
* ssax:read-markup-token:                SSAX low-level parsing code.
                                                              (line  41)
* ssax:read-NCName:                      SSAX low-level parsing code.
                                                              (line  23)
* ssax:read-pi-body-as-string:           SSAX low-level parsing code.
                                                              (line  85)
* ssax:read-QName:                       SSAX low-level parsing code.
                                                              (line  27)
* ssax:resolve-name:                     SSAX low-level parsing code.
                                                              (line 200)
* ssax:reverse-collect-str:              SSAX Highest-level parsers - XML to SXML.
                                                              (line 154)
* ssax:reverse-collect-str-drop-ws:      SSAX Highest-level parsers - XML to SXML.
                                                              (line 158)
* ssax:scan-Misc:                        SSAX higher-level parsers and scanners.
                                                              (line  10)
* ssax:skip-internal-dtd:                SSAX low-level parsing code.
                                                              (line  92)
* ssax:skip-pi:                          SSAX low-level parsing code.
                                                              (line  81)
* ssax:skip-S:                           SSAX low-level parsing code.
                                                              (line  13)
* ssax:uri-string->symbol:               SSAX low-level parsing code.
                                                              (line 213)
* ssax:xml->sxml:                        SSAX Highest-level parsers - XML to SXML.
                                                              (line 169)
* stable-sort:                           Comparison and sorting.
                                                              (line  34)
* stable-sort!:                          Comparison and sorting.
                                                              (line  35)
* standard-error-port:                   Common port operations.
                                                              (line  28)
* standard-input-port:                   Common port operations.
                                                              (line  26)
* standard-output-port:                  Common port operations.
                                                              (line  27)
* string <1>:                            String Comparison.   (line  14)
* string <2>:                            SRFI-13 String Comparison.
                                                              (line  15)
* string <3>:                            String Constructors. (line  29)
* string <4>:                            SRFI-13 String Comparison.
                                                              (line  14)
* string:                                String Comparison.   (line  13)
* string->char-set:                      SRFI-14 Character-set constructors.
                                                              (line  15)
* string->char-set!:                     SRFI-14 Character-set constructors.
                                                              (line  16)
* string->date:                          SRFI-19 Date reader and writer.
                                                              (line  10)
* string->list:                          String utilities.    (line  13)
* string->number:                        Numerical conversions.
                                                              (line  69)
* string->regexp:                        Regular expression.  (line 149)
* string->s32vector:                     Uvector conversion operations.
                                                              (line  90)
* string->s8vector:                      Uvector conversion operations.
                                                              (line  55)
* string->s8vector!:                     Uvector conversion operations.
                                                              (line  67)
* string->symbol:                        Symbols.             (line  37)
* string->u32vector:                     Uvector conversion operations.
                                                              (line  91)
* string->u8vector:                      Uvector conversion operations.
                                                              (line  56)
* string->u8vector!:                     Uvector conversion operations.
                                                              (line  68)
* string-any:                            SRFI-13 String predicates.
                                                              (line  17)
* string-append:                         String utilities.    (line  10)
* string-append-ec:                      Eager comprehensions.
                                                              (line  87)
* string-append/shared:                  SRFI-13 String reverse & append.
                                                              (line  26)
* string-byte-ref:                       String Accessors & Modifiers.
                                                              (line  26)
* string-byte-set!:                      String Accessors & Modifiers.
                                                              (line  42)
* string-ci <1>:                         SRFI-13 String Comparison.
                                                              (line  24)
* string-ci <2>:                         String Comparison.   (line   8)
* string-ci <3>:                         SRFI-13 String Comparison.
                                                              (line  21)
* string-ci:                             String Comparison.   (line  18)
* string-compare:                        SRFI-13 String Comparison.
                                                              (line   8)
* string-compare-ci:                     SRFI-13 String Comparison.
                                                              (line  10)
* string-complete->incomplete:           Incomplete strings.  (line   7)
* string-concatenate:                    SRFI-13 String reverse & append.
                                                              (line  20)
* string-concatenate-reverse:            SRFI-13 String reverse & append.
                                                              (line  30)
* string-concatenate-reverse/shared:     SRFI-13 String reverse & append.
                                                              (line  31)
* string-concatenate/shared:             SRFI-13 String reverse & append.
                                                              (line  25)
* string-contains:                       SRFI-13 String searching.
                                                              (line  35)
* string-contains-ci:                    SRFI-13 String searching.
                                                              (line  36)
* string-copy:                           String utilities.    (line  17)
* string-copy!:                          SRFI-13 String Selection.
                                                              (line  12)
* string-count:                          SRFI-13 String searching.
                                                              (line  30)
* string-delete:                         SRFI-13 String filtering.
                                                              (line   8)
* string-downcase:                       SRFI-13 String case mapping.
                                                              (line  15)
* string-downcase!:                      SRFI-13 String case mapping.
                                                              (line  16)
* string-drop:                           SRFI-13 String Selection.
                                                              (line  22)
* string-drop-right:                     SRFI-13 String Selection.
                                                              (line  24)
* string-ec:                             Eager comprehensions.
                                                              (line  86)
* string-every:                          SRFI-13 String predicates.
                                                              (line  10)
* string-fill!:                          String utilities.    (line  20)
* string-filter:                         SRFI-13 String filtering.
                                                              (line   7)
* string-fold:                           SRFI-13 String mapping.
                                                              (line  20)
* string-fold-right:                     SRFI-13 String mapping.
                                                              (line  21)
* string-for-each:                       SRFI-13 String mapping.
                                                              (line  30)
* string-for-each-index:                 SRFI-13 String mapping.
                                                              (line  33)
* string-hash:                           SRFI-13 String Comparison.
                                                              (line  29)
* string-hash-ci:                        SRFI-13 String Comparison.
                                                              (line  30)
* string-immutable?:                     String Predicates.   (line  10)
* string-incomplete->complete:           Incomplete strings.  (line   9)
* string-incomplete?:                    String Predicates.   (line  13)
* string-index:                          SRFI-13 String searching.
                                                              (line   7)
* string-index-right:                    SRFI-13 String searching.
                                                              (line   9)
* string-join:                           String utilities.    (line  28)
* string-kmp-partial-search:             SRFI-13 Low-level string procedures.
                                                              (line  26)
* string-length:                         String Accessors & Modifiers.
                                                              (line   7)
* string-map:                            SRFI-13 String mapping.
                                                              (line   7)
* string-map!:                           SRFI-13 String mapping.
                                                              (line   8)
* string-null?:                          SRFI-13 String predicates.
                                                              (line   7)
* string-pad:                            SRFI-13 String Selection.
                                                              (line  36)
* string-pad-right:                      SRFI-13 String Selection.
                                                              (line  37)
* string-parse-final-start+end:          SRFI-13 Low-level string procedures.
                                                              (line   8)
* string-parse-start+end:                SRFI-13 Low-level string procedures.
                                                              (line   7)
* string-pointer-byte-index:             String Pointers.     (line  35)
* string-pointer-copy:                   String Pointers.     (line  20)
* string-pointer-index:                  String Pointers.     (line  34)
* string-pointer-next!:                  String Pointers.     (line  27)
* string-pointer-prev!:                  String Pointers.     (line  28)
* string-pointer-set!:                   String Pointers.     (line  30)
* string-pointer-substring:              String Pointers.     (line  32)
* string-pointer?:                       String Pointers.     (line  24)
* string-prefix-ci?:                     SRFI-13 String Prefixes & Suffixes.
                                                              (line  19)
* string-prefix-length:                  SRFI-13 String Prefixes & Suffixes.
                                                              (line   8)
* string-prefix-length-ci:               SRFI-13 String Prefixes & Suffixes.
                                                              (line  12)
* string-prefix?:                        SRFI-13 String Prefixes & Suffixes.
                                                              (line  17)
* string-ref:                            String Accessors & Modifiers.
                                                              (line  17)
* string-replace:                        SRFI-13 other string operations.
                                                              (line   7)
* string-reverse:                        SRFI-13 String reverse & append.
                                                              (line   7)
* string-reverse!:                       SRFI-13 String reverse & append.
                                                              (line   8)
* string-scan:                           String utilities.    (line  68)
* string-set!:                           String Accessors & Modifiers.
                                                              (line  32)
* string-size:                           String Accessors & Modifiers.
                                                              (line  10)
* string-skip:                           SRFI-13 String searching.
                                                              (line  23)
* string-skip-right:                     SRFI-13 String searching.
                                                              (line  24)
* string-split:                          String utilities.    (line 116)
* string-suffix-ci?:                     SRFI-13 String Prefixes & Suffixes.
                                                              (line  20)
* string-suffix-length:                  SRFI-13 String Prefixes & Suffixes.
                                                              (line  10)
* string-suffix-length-ci:               SRFI-13 String Prefixes & Suffixes.
                                                              (line  14)
* string-suffix?:                        SRFI-13 String Prefixes & Suffixes.
                                                              (line  18)
* string-tabulate:                       SRFI-13 String Constructors.
                                                              (line   7)
* string-take:                           SRFI-13 String Selection.
                                                              (line  21)
* string-take-right:                     SRFI-13 String Selection.
                                                              (line  23)
* string-titlecase:                      SRFI-13 String case mapping.
                                                              (line   7)
* string-titlecase!:                     SRFI-13 String case mapping.
                                                              (line   8)
* string-tokenize:                       SRFI-13 other string operations.
                                                              (line  10)
* string-tr:                             Transliterate characters.
                                                              (line  92)
* string-trim:                           SRFI-13 String Selection.
                                                              (line  52)
* string-trim-both:                      SRFI-13 String Selection.
                                                              (line  54)
* string-trim-right:                     SRFI-13 String Selection.
                                                              (line  53)
* string-unfold:                         SRFI-13 String mapping.
                                                              (line  24)
* string-unfold-right:                   SRFI-13 String mapping.
                                                              (line  27)
* string-upcase:                         SRFI-13 String case mapping.
                                                              (line  11)
* string-upcase!:                        SRFI-13 String case mapping.
                                                              (line  12)
* string-xcopy!:                         SRFI-13 String rotation.
                                                              (line  11)
* string=:                               SRFI-13 String Comparison.
                                                              (line  13)
* string=?:                              String Comparison.   (line   7)
* string?:                               String Predicates.   (line   7)
* subseq:                                Slicing sequence.    (line   7)
* substring:                             String utilities.    (line   7)
* substring-spec-ok?:                    SRFI-13 Low-level string procedures.
                                                              (line  16)
* substring/shared:                      SRFI-13 String Selection.
                                                              (line   7)
* subtract-duration:                     SRFI-19 Time procedures.
                                                              (line  43)
* subtract-duration!:                    SRFI-19 Time procedures.
                                                              (line  44)
* sum-ec:                                Eager comprehensions.
                                                              (line  96)
* supported-character-encodings:         Characters.          (line 173)
* sxml:add-attr:                         SXML modifiers.      (line  35)
* sxml:add-attr!:                        SXML modifiers.      (line  40)
* sxml:add-aux:                          SXML modifiers.      (line  60)
* sxml:add-aux!:                         SXML modifiers.      (line  63)
* sxml:add-parents:                      SXPath auxiliary utilities.
                                                              (line   9)
* sxml:ancestor:                         SXPath extension.    (line  95)
* sxml:ancestor-or-self:                 SXPath extension.    (line  98)
* sxml:attr:                             SXML accessors.      (line  97)
* sxml:attr->html:                       SXML to markup conversion.
                                                              (line  38)
* sxml:attr->xml:                        SXML to markup conversion.
                                                              (line  25)
* sxml:attr-as-list:                     SXML accessors.      (line  56)
* sxml:attr-list:                        SXPath extension.    (line  39)
* sxml:attr-list-node:                   SXML accessors.      (line  53)
* sxml:attr-list-u:                      SXML accessors.      (line  66)
* sxml:attr-u:                           SXML accessors.      (line 110)
* sxml:attribute:                        SXPath extension.    (line  73)
* sxml:aux-as-list:                      SXML accessors.      (line  63)
* sxml:aux-list:                         SXML accessors.      (line  74)
* sxml:aux-list-node:                    SXML accessors.      (line  60)
* sxml:aux-list-u:                       SXML accessors.      (line  79)
* sxml:aux-node:                         SXML accessors.      (line  87)
* sxml:aux-nodes:                        SXML accessors.      (line  93)
* sxml:boolean:                          SXPath extension.    (line  17)
* sxml:change-attr:                      SXML modifiers.      (line  45)
* sxml:change-attr!:                     SXML modifiers.      (line  50)
* sxml:change-attrlist:                  SXML modifiers.      (line  26)
* sxml:change-attrlist!:                 SXML modifiers.      (line  27)
* sxml:change-content:                   SXML modifiers.      (line  20)
* sxml:change-content!:                  SXML modifiers.      (line  21)
* sxml:change-name:                      SXML modifiers.      (line  31)
* sxml:change-name!:                     SXML modifiers.      (line  32)
* sxml:child:                            SXPath extension.    (line  76)
* sxml:child-elements:                   SXPath extension.    (line 127)
* sxml:child-nodes:                      SXPath extension.    (line 124)
* sxml:clean:                            SXML modifiers.      (line  72)
* sxml:clean-feed:                       SXML to markup conversion.
                                                              (line   9)
* sxml:content:                          SXML accessors.      (line  29)
* sxml:content-raw:                      SXML accessors.      (line  35)
* sxml:descendant:                       SXPath extension.    (line 101)
* sxml:descendant-or-self:               SXPath extension.    (line 104)
* sxml:element-name:                     SXML accessors.      (line  11)
* sxml:element?:                         SXPath basic converters and applicators.
                                                              (line  20)
* sxml:empty-element?:                   SXML predicates.     (line   7)
* sxml:equal?:                           SXPath extension.    (line  61)
* sxml:equality-cmp:                     SXPath extension.    (line  56)
* sxml:filter:                           SXPath basic converters and applicators.
                                                              (line  96)
* sxml:following:                        SXPath extension.    (line 107)
* sxml:following-sibling:                SXPath extension.    (line 110)
* sxml:id:                               SXPath extension.    (line  44)
* sxml:id-alist:                         SXPath query language.
                                                              (line  51)
* sxml:invert:                           SXPath basic converters and applicators.
                                                              (line  72)
* sxml:lookup:                           SXPath auxiliary utilities.
                                                              (line  21)
* sxml:minimized?:                       SXML predicates.     (line  27)
* sxml:name:                             SXML accessors.      (line   7)
* sxml:name->ns-id:                      SXML accessors.      (line  26)
* sxml:namespace:                        SXPath extension.    (line 113)
* sxml:ncname:                           SXML accessors.      (line  19)
* sxml:node-name:                        SXML accessors.      (line  15)
* sxml:node-parent:                      SXPath auxiliary utilities.
                                                              (line  14)
* sxml:node?:                            SXPath extension.    (line  34)
* sxml:non-terminated-html-tag?:         SXML to markup conversion.
                                                              (line  46)
* sxml:normalized?:                      SXML predicates.     (line  18)
* sxml:not-equal?:                       SXPath extension.    (line  62)
* sxml:ns-id:                            SXML accessors.      (line 139)
* sxml:ns-id->nodes:                     SXML accessors.      (line 126)
* sxml:ns-id->uri:                       SXML accessors.      (line 132)
* sxml:ns-list:                          SXML accessors.      (line 121)
* sxml:ns-prefix:                        SXML accessors.      (line 145)
* sxml:ns-uri:                           SXML accessors.      (line 142)
* sxml:ns-uri->id:                       SXML accessors.      (line 136)
* sxml:num-attr:                         SXML accessors.      (line 102)
* sxml:number:                           SXPath extension.    (line  21)
* sxml:parent:                           SXPath extension.    (line  80)
* sxml:preceding:                        SXPath extension.    (line 116)
* sxml:preceding-sibling:                SXPath extension.    (line 119)
* sxml:relational-cmp:                   SXPath extension.    (line  66)
* sxml:set-attr:                         SXML modifiers.      (line  55)
* sxml:set-attr!:                        SXML modifiers.      (line  56)
* sxml:shallow-minimized?:               SXML predicates.     (line  22)
* sxml:shallow-normalized?:              SXML predicates.     (line  13)
* sxml:squeeze:                          SXML modifiers.      (line  66)
* sxml:squeeze!:                         SXML modifiers.      (line  67)
* sxml:string:                           SXPath extension.    (line   9)
* sxml:string->html:                     SXML to markup conversion.
                                                              (line  41)
* sxml:string->xml:                      SXML to markup conversion.
                                                              (line  28)
* sxml:string-value:                     SXPath extension.    (line  30)
* sxml:sxml->html:                       SXML to markup conversion.
                                                              (line  49)
* sxml:sxml->xml:                        SXML to markup conversion.
                                                              (line  34)
* sxpath:                                SXPath query language.
                                                              (line   7)
* symbol->string:                        Symbols.             (line  31)
* symbol-bound?:                         Module introspection.
                                                              (line  75)
* symbol?:                               Symbols.             (line  23)
* syntax-error:                          Macro utilities.     (line   7)
* syntax-errorf:                         Macro utilities.     (line   8)
* syntax-rules:                          Hygienic Macros.     (line  19)
* sys-abort:                             Program termination. (line  20)
* sys-access:                            File stats.          (line 109)
* sys-alarm:                             Miscellaneous system calls.
                                                              (line  17)
* sys-asctime:                           Time.                (line  87)
* sys-basename:                          Pathnames.           (line  39)
* sys-cfgetispeed:                       Termios.             (line 105)
* sys-cfgetospeed:                       Termios.             (line 107)
* sys-cfsetispeed:                       Termios.             (line 106)
* sys-cfsetospeed:                       Termios.             (line 108)
* sys-chdir:                             Other file operations.
                                                              (line   7)
* sys-chmod:                             File stats.          (line 133)
* sys-chown:                             File stats.          (line 138)
* sys-closelog:                          Syslog.              (line  49)
* sys-crypt:                             Unix groups and users.
                                                              (line  81)
* sys-ctermid:                           System Inquiry.      (line  79)
* sys-ctime:                             Time.                (line  79)
* sys-difftime:                          Time.                (line  83)
* sys-dirname:                           Pathnames.           (line  40)
* sys-exec:                              Unix process management.
                                                              (line  49)
* sys-exit:                              Program termination. (line  14)
* sys-fcntl:                             Low-level file operations.
                                                              (line  11)
* sys-fdset-max-fd:                      I/O multiplexing.    (line  27)
* sys-fdset-ref:                         I/O multiplexing.    (line  15)
* sys-fdset-set!:                        I/O multiplexing.    (line  16)
* sys-fork:                              Unix process management.
                                                              (line  22)
* sys-fork-and-exec:                     Unix process management.
                                                              (line  84)
* sys-forkpty:                           Termios.             (line 134)
* sys-fstat:                             File stats.          (line  62)
* sys-getaddrinfo:                       Netdb interface.     (line 136)
* sys-getcwd:                            System Inquiry.      (line  19)
* sys-getdomainname:                     System Inquiry.      (line  15)
* sys-getegid:                           System Inquiry.      (line  26)
* sys-getenv:                            Environment Inquiry. (line   7)
* sys-geteuid:                           System Inquiry.      (line  34)
* sys-getgid:                            System Inquiry.      (line  25)
* sys-getgrgid:                          Unix groups and users.
                                                              (line  26)
* sys-getgrnam:                          Unix groups and users.
                                                              (line  27)
* sys-getgroups:                         System Inquiry.      (line  41)
* sys-gethostbyaddr:                     Netdb interface.     (line  31)
* sys-gethostbyname:                     Netdb interface.     (line  22)
* sys-gethostname:                       System Inquiry.      (line  11)
* sys-getlogin:                          System Inquiry.      (line  44)
* sys-getpgid:                           System Inquiry.      (line  52)
* sys-getpgrp:                           System Inquiry.      (line  49)
* sys-getpid:                            System Inquiry.      (line  71)
* sys-getppid:                           System Inquiry.      (line  72)
* sys-getprotobyname:                    Netdb interface.     (line  97)
* sys-getprotobynumber:                  Netdb interface.     (line 107)
* sys-getpwnam:                          Unix groups and users.
                                                              (line  69)
* sys-getpwuid:                          Unix groups and users.
                                                              (line  68)
* sys-getservbyname:                     Netdb interface.     (line  60)
* sys-getservbyport:                     Netdb interface.     (line  72)
* sys-gettimeofday:                      Time.                (line  33)
* sys-getuid:                            System Inquiry.      (line  33)
* sys-gid->group-name:                   Unix groups and users.
                                                              (line  32)
* sys-glob:                              Directories.         (line  15)
* sys-gmtime:                            Time.                (line  73)
* sys-group-name->gid:                   Unix groups and users.
                                                              (line  33)
* sys-isatty:                            Other file operations.
                                                              (line  34)
* sys-kill:                              Sending signals.     (line   9)
* sys-link:                              Directory manipulation.
                                                              (line  30)
* sys-localeconv:                        Locale.              (line  23)
* sys-localtime:                         Time.                (line  74)
* sys-logmask:                           Syslog.              (line  59)
* sys-lstat:                             File stats.          (line  73)
* sys-mkdir:                             Directory manipulation.
                                                              (line  50)
* sys-mkfifo:                            Other file operations.
                                                              (line  29)
* sys-mkstemp:                           Directory manipulation.
                                                              (line  22)
* sys-mktime:                            Time.                (line  94)
* sys-nanosleep:                         Miscellaneous system calls.
                                                              (line  33)
* sys-normalize-pathname:                Pathnames.           (line  10)
* sys-openlog:                           Syslog.              (line  17)
* sys-openpty:                           Termios.             (line 120)
* sys-pause:                             Miscellaneous system calls.
                                                              (line   7)
* sys-pipe:                              Other file operations.
                                                              (line  11)
* sys-putenv:                            Environment Inquiry. (line  11)
* sys-random:                            Miscellaneous system calls.
                                                              (line  47)
* sys-readdir:                           Directories.         (line   9)
* sys-readlink:                          Directory manipulation.
                                                              (line  44)
* sys-realpath:                          Pathnames.           (line  64)
* sys-remove:                            Directory manipulation.
                                                              (line   7)
* sys-rename:                            Directory manipulation.
                                                              (line  12)
* sys-rmdir:                             Directory manipulation.
                                                              (line  57)
* sys-select:                            I/O multiplexing.    (line  30)
* sys-select!:                           I/O multiplexing.    (line  31)
* sys-setgid:                            System Inquiry.      (line  30)
* sys-setlocale:                         Locale.              (line   7)
* sys-setlogmask:                        Syslog.              (line  52)
* sys-setpgid:                           System Inquiry.      (line  60)
* sys-setsid:                            System Inquiry.      (line  67)
* sys-setuid:                            System Inquiry.      (line  38)
* sys-sigmask:                           Masking and waiting signals.
                                                              (line  16)
* sys-signal-name:                       Signals and signal sets.
                                                              (line  71)
* sys-sigset-add!:                       Signals and signal sets.
                                                              (line  58)
* sys-sigset-delete!:                    Signals and signal sets.
                                                              (line  59)
* sys-sigset-empty!:                     Signals and signal sets.
                                                              (line  68)
* sys-sigset-fill!:                      Signals and signal sets.
                                                              (line  67)
* sys-sigsuspend:                        Masking and waiting signals.
                                                              (line  29)
* sys-sleep:                             Miscellaneous system calls.
                                                              (line  24)
* sys-srandom:                           Miscellaneous system calls.
                                                              (line  48)
* sys-stat:                              File stats.          (line  61)
* sys-stat->atime:                       File stats.          (line 102)
* sys-stat->ctime:                       File stats.          (line 104)
* sys-stat->dev:                         File stats.          (line  96)
* sys-stat->file-type:                   File stats.          (line 105)
* sys-stat->gid:                         File stats.          (line 101)
* sys-stat->ino:                         File stats.          (line  95)
* sys-stat->mode:                        File stats.          (line  94)
* sys-stat->mtime:                       File stats.          (line 103)
* sys-stat->nlink:                       File stats.          (line  98)
* sys-stat->rdev:                        File stats.          (line  97)
* sys-stat->size:                        File stats.          (line  99)
* sys-stat->uid:                         File stats.          (line 100)
* sys-strftime:                          Time.                (line  90)
* sys-symlink:                           Directory manipulation.
                                                              (line  39)
* sys-system:                            Unix process management.
                                                              (line  14)
* sys-tcdrain:                           Termios.             (line  66)
* sys-tcflow:                            Termios.             (line  81)
* sys-tcflush:                           Termios.             (line  69)
* sys-tcgetattr:                         Termios.             (line  41)
* sys-tcgetpgrp:                         Termios.             (line  98)
* sys-tcsendbreak:                       Termios.             (line  61)
* sys-tcsetattr:                         Termios.             (line  45)
* sys-tcsetpgrp:                         Termios.             (line 101)
* sys-time:                              Time.                (line  25)
* sys-times:                             System Inquiry.      (line  76)
* sys-tm->alist:                         Time.                (line  98)
* sys-tmpnam:                            Directory manipulation.
                                                              (line  17)
* sys-ttyname:                           Other file operations.
                                                              (line  39)
* sys-uid->user-name:                    Unix groups and users.
                                                              (line  74)
* sys-umask:                             Directory manipulation.
                                                              (line  62)
* sys-uname:                             System Inquiry.      (line   7)
* sys-unlink:                            Directory manipulation.
                                                              (line  34)
* sys-user-name->uid:                    Unix groups and users.
                                                              (line  75)
* sys-utime:                             File stats.          (line 144)
* sys-wait:                              Unix process management.
                                                              (line  97)
* sys-wait-exit-status:                  Unix process management.
                                                              (line 128)
* sys-wait-exited?:                      Unix process management.
                                                              (line 127)
* sys-wait-signaled?:                    Unix process management.
                                                              (line 135)
* sys-wait-stopped?:                     Unix process management.
                                                              (line 143)
* sys-wait-stopsig:                      Unix process management.
                                                              (line 144)
* sys-wait-termsig:                      Unix process management.
                                                              (line 136)
* sys-waitpid:                           Unix process management.
                                                              (line 104)
* tabulate-array:                        Arrays.              (line 192)
* take:                                  SRFI-1 List selectors.
                                                              (line  22)
* take!:                                 SRFI-1 List selectors.
                                                              (line  63)
* take*:                                 Additional list library.
                                                              (line  15)
* take-after:                            SXPath basic converters and applicators.
                                                              (line 118)
* take-right:                            SRFI-1 List selectors.
                                                              (line  44)
* take-right*:                           Additional list library.
                                                              (line  40)
* take-until:                            SXPath basic converters and applicators.
                                                              (line 103)
* take-while:                            SRFI-1 Searching.    (line  16)
* take-while!:                           SRFI-1 Searching.    (line  17)
* tan:                                   Arithmetics.         (line 119)
* tanh:                                  Arithmetics.         (line 130)
* temporary-directory:                   Directory utilities. (line  24)
* tenth:                                 SRFI-1 List selectors.
                                                              (line  16)
* terminated-thread-exception?:          Thread exceptions.   (line  49)
* test:                                  Unit testing.        (line  46)
* test*:                                 Unit testing.        (line  89)
* test-end:                              Unit testing.        (line 111)
* test-module:                           Unit testing.        (line  95)
* test-section:                          Unit testing.        (line 108)
* test-start:                            Unit testing.        (line 103)
* textdomain:                            Localized messages.  (line  31)
* third:                                 SRFI-1 List selectors.
                                                              (line   9)
* thread-join!:                          Thread procedures.   (line 110)
* thread-name:                           Thread procedures.   (line  64)
* thread-sleep!:                         Thread procedures.   (line  80)
* thread-specific:                       Thread procedures.   (line  67)
* thread-specific-set!:                  Thread procedures.   (line  68)
* thread-start!:                         Thread procedures.   (line  72)
* thread-terminate!:                     Thread procedures.   (line  92)
* thread-yield!:                         Thread procedures.   (line  76)
* thread?:                               Thread procedures.   (line  49)
* time:                                  Measure timings.     (line  13)
* time->seconds:                         Time.                (line 127)
* time-counter-reset!:                   Measure timings.     (line  73)
* time-counter-start!:                   Measure timings.     (line  56)
* time-counter-stop!:                    Measure timings.     (line  57)
* time-counter-value:                    Measure timings.     (line  77)
* time-difference:                       SRFI-19 Time procedures.
                                                              (line  35)
* time-difference!:                      SRFI-19 Time procedures.
                                                              (line  36)
* time-monotonic->date:                  SRFI-19 Date.        (line  94)
* time-monotonic->julian-day:            SRFI-19 Date.        (line  95)
* time-monotonic->modified-julian-day:   SRFI-19 Date.        (line  96)
* time-monotonic->time-tai:              SRFI-19 Date.        (line  97)
* time-monotonic->time-tai!:             SRFI-19 Date.        (line  98)
* time-monotonic->time-utc:              SRFI-19 Date.        (line  99)
* time-monotonic->time-utc!:             SRFI-19 Date.        (line 100)
* time-nanosecond:                       SRFI-19 Time procedures.
                                                              (line  18)
* time-resolution:                       SRFI-19 Time queries.
                                                              (line  29)
* time-second:                           SRFI-19 Time procedures.
                                                              (line  17)
* time-tai->date:                        SRFI-19 Date.        (line 104)
* time-tai->julian-day:                  SRFI-19 Date.        (line 105)
* time-tai->modified-julian-day:         SRFI-19 Date.        (line 106)
* time-tai->time-monotonic:              SRFI-19 Date.        (line 107)
* time-tai->time-monotonic!:             SRFI-19 Date.        (line 108)
* time-tai->time-utc:                    SRFI-19 Date.        (line 109)
* time-tai->time-utc!:                   SRFI-19 Date.        (line 110)
* time-type:                             SRFI-19 Time procedures.
                                                              (line  16)
* time-utc->date:                        SRFI-19 Date.        (line 113)
* time-utc->julian-day:                  SRFI-19 Date.        (line 114)
* time-utc->modified-julian-day:         SRFI-19 Date.        (line 115)
* time-utc->time-monotonic:              SRFI-19 Date.        (line 116)
* time-utc->time-monotonic!:             SRFI-19 Date.        (line 117)
* time-utc->time-tai:                    SRFI-19 Date.        (line 118)
* time-utc->time-tai!:                   SRFI-19 Date.        (line 119)
* time<=?:                               SRFI-19 Time procedures.
                                                              (line  30)
* time<?:                                SRFI-19 Time procedures.
                                                              (line  29)
* time=?:                                SRFI-19 Time procedures.
                                                              (line  28)
* time>=?:                               SRFI-19 Time procedures.
                                                              (line  32)
* time>?:                                SRFI-19 Time procedures.
                                                              (line  31)
* time?:                                 Time.                (line 124)
* topological-sort:                      Topological sort.    (line  10)
* touch-file:                            File operations.     (line   7)
* tr:                                    Transliterate characters.
                                                              (line  16)
* tree->string:                          Lazy text construction.
                                                              (line  44)
* truncate:                              Arithmetics.         (line  92)
* u16vector:                             Uvector basic operations.
                                                              (line  19)
* u16vector->list:                       Uvector conversion operations.
                                                              (line   7)
* u16vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* u16vector-add:                         Uvector numeric operations.
                                                              (line  12)
* u16vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* u16vector-and:                         Uvector numeric operations.
                                                              (line  49)
* u16vector-and!:                        Uvector numeric operations.
                                                              (line  49)
* u16vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* u16vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* u16vector-copy:                        Uvector basic operations.
                                                              (line  76)
* u16vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* u16vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* u16vector-ior:                         Uvector numeric operations.
                                                              (line  49)
* u16vector-ior!:                        Uvector numeric operations.
                                                              (line  49)
* u16vector-length:                      Uvector basic operations.
                                                              (line  32)
* u16vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* u16vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* u16vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* u16vector-ref:                         Uvector basic operations.
                                                              (line  43)
* u16vector-set!:                        Uvector basic operations.
                                                              (line  58)
* u16vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* u16vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* u16vector-xor:                         Uvector numeric operations.
                                                              (line  49)
* u16vector-xor!:                        Uvector numeric operations.
                                                              (line  49)
* u16vector?:                            Uvector basic operations.
                                                              (line  16)
* u32vector:                             Uvector basic operations.
                                                              (line  19)
* u32vector->list:                       Uvector conversion operations.
                                                              (line   7)
* u32vector->string:                     Uvector conversion operations.
                                                              (line 101)
* u32vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* u32vector-add:                         Uvector numeric operations.
                                                              (line  12)
* u32vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* u32vector-and:                         Uvector numeric operations.
                                                              (line  49)
* u32vector-and!:                        Uvector numeric operations.
                                                              (line  49)
* u32vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* u32vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* u32vector-copy:                        Uvector basic operations.
                                                              (line  76)
* u32vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* u32vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* u32vector-ior:                         Uvector numeric operations.
                                                              (line  49)
* u32vector-ior!:                        Uvector numeric operations.
                                                              (line  49)
* u32vector-length:                      Uvector basic operations.
                                                              (line  32)
* u32vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* u32vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* u32vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* u32vector-ref:                         Uvector basic operations.
                                                              (line  43)
* u32vector-set!:                        Uvector basic operations.
                                                              (line  58)
* u32vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* u32vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* u32vector-xor:                         Uvector numeric operations.
                                                              (line  49)
* u32vector-xor!:                        Uvector numeric operations.
                                                              (line  49)
* u32vector?:                            Uvector basic operations.
                                                              (line  16)
* u64vector:                             Uvector basic operations.
                                                              (line  19)
* u64vector->list:                       Uvector conversion operations.
                                                              (line   7)
* u64vector->vector:                     Uvector conversion operations.
                                                              (line  18)
* u64vector-add:                         Uvector numeric operations.
                                                              (line  12)
* u64vector-add!:                        Uvector numeric operations.
                                                              (line  12)
* u64vector-and:                         Uvector numeric operations.
                                                              (line  49)
* u64vector-and!:                        Uvector numeric operations.
                                                              (line  49)
* u64vector-clamp:                       Uvector numeric operations.
                                                              (line  94)
* u64vector-clamp!:                      Uvector numeric operations.
                                                              (line  94)
* u64vector-copy:                        Uvector basic operations.
                                                              (line  76)
* u64vector-copy!:                       Uvector basic operations.
                                                              (line  84)
* u64vector-dot:                         Uvector numeric operations.
                                                              (line  59)
* u64vector-ior:                         Uvector numeric operations.
                                                              (line  49)
* u64vector-ior!:                        Uvector numeric operations.
                                                              (line  49)
* u64vector-length:                      Uvector basic operations.
                                                              (line  32)
* u64vector-mul:                         Uvector numeric operations.
                                                              (line  12)
* u64vector-mul!:                        Uvector numeric operations.
                                                              (line  12)
* u64vector-range-check:                 Uvector numeric operations.
                                                              (line  63)
* u64vector-ref:                         Uvector basic operations.
                                                              (line  43)
* u64vector-set!:                        Uvector basic operations.
                                                              (line  58)
* u64vector-sub:                         Uvector numeric operations.
                                                              (line  12)
* u64vector-sub!:                        Uvector numeric operations.
                                                              (line  12)
* u64vector-xor:                         Uvector numeric operations.
                                                              (line  49)
* u64vector-xor!:                        Uvector numeric operations.
                                                              (line  49)
* u64vector?:                            Uvector basic operations.
                                                              (line  16)
* u8vector:                              Uvector basic operations.
                                                              (line  19)
* u8vector->list:                        Uvector conversion operations.
                                                              (line   7)
* u8vector->string:                      Uvector conversion operations.
                                                              (line  81)
* u8vector->vector:                      Uvector conversion operations.
                                                              (line  18)
* u8vector-add:                          Uvector numeric operations.
                                                              (line  12)
* u8vector-add!:                         Uvector numeric operations.
                                                              (line  12)
* u8vector-and:                          Uvector numeric operations.
                                                              (line  49)
* u8vector-and!:                         Uvector numeric operations.
                                                              (line  49)
* u8vector-clamp:                        Uvector numeric operations.
                                                              (line  94)
* u8vector-clamp!:                       Uvector numeric operations.
                                                              (line  94)
* u8vector-copy:                         Uvector basic operations.
                                                              (line  76)
* u8vector-copy!:                        Uvector basic operations.
                                                              (line  84)
* u8vector-dot:                          Uvector numeric operations.
                                                              (line  59)
* u8vector-ior:                          Uvector numeric operations.
                                                              (line  49)
* u8vector-ior!:                         Uvector numeric operations.
                                                              (line  49)
* u8vector-length:                       Uvector basic operations.
                                                              (line  32)
* u8vector-mul:                          Uvector numeric operations.
                                                              (line  12)
* u8vector-mul!:                         Uvector numeric operations.
                                                              (line  12)
* u8vector-range-check:                  Uvector numeric operations.
                                                              (line  63)
* u8vector-ref:                          Uvector basic operations.
                                                              (line  43)
* u8vector-set!:                         Uvector basic operations.
                                                              (line  58)
* u8vector-sub:                          Uvector numeric operations.
                                                              (line  12)
* u8vector-sub!:                         Uvector numeric operations.
                                                              (line  12)
* u8vector-xor:                          Uvector numeric operations.
                                                              (line  49)
* u8vector-xor!:                         Uvector numeric operations.
                                                              (line  49)
* u8vector?:                             Uvector basic operations.
                                                              (line  16)
* ucs->char:                             Characters.          (line 116)
* ucs-range->char-set:                   SRFI-14 Character-set constructors.
                                                              (line  28)
* ucs-range->char-set!:                  SRFI-14 Character-set constructors.
                                                              (line  29)
* uncaught-exception-reason:             Thread exceptions.   (line  54)
* uncaught-exception?:                   Thread exceptions.   (line  50)
* unfold:                                SRFI-1 Fold.         (line  59)
* unfold-right:                          SRFI-1 Fold.         (line  72)
* unless:                                Conditionals.        (line 108)
* unpack:                                Packing Binary Data. (line 147)
* unpack-skip:                           Packing Binary Data. (line 175)
* unwrap-syntax:                         Macro utilities.     (line  30)
* unzip1:                                SRFI-1 List miscellaneous routines.
                                                              (line  36)
* unzip2:                                SRFI-1 List miscellaneous routines.
                                                              (line  37)
* unzip3:                                SRFI-1 List miscellaneous routines.
                                                              (line  38)
* unzip4:                                SRFI-1 List miscellaneous routines.
                                                              (line  39)
* unzip5:                                SRFI-1 List miscellaneous routines.
                                                              (line  40)
* update!:                               Assignments.         (line 133)
* uri-compose:                           URI parsing and construction.
                                                              (line  78)
* uri-decode:                            URI parsing and construction.
                                                              (line 115)
* uri-decode-string:                     URI parsing and construction.
                                                              (line 116)
* uri-decompose-authority:               URI parsing and construction.
                                                              (line  14)
* uri-decompose-hierarchical:            URI parsing and construction.
                                                              (line  13)
* uri-encode:                            URI parsing and construction.
                                                              (line 124)
* uri-encode-string:                     URI parsing and construction.
                                                              (line 125)
* uri-parse:                             URI parsing and construction.
                                                              (line  11)
* uri-scheme&specific:                   URI parsing and construction.
                                                              (line  12)
* use:                                   Using modules.       (line  26)
* uvector-alias:                         Uvector conversion operations.
                                                              (line 107)
* values:                                Multiple values.     (line   7)
* values-ref:                            Multiple values.     (line  21)
* vector:                                Vectors.             (line  27)
* vector->f32vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->f64vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->list:                          Vectors.             (line  54)
* vector->s16vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->s32vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->s64vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->s8vector:                      Uvector conversion operations.
                                                              (line  42)
* vector->u16vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->u32vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->u64vector:                     Uvector conversion operations.
                                                              (line  42)
* vector->u8vector:                      Uvector conversion operations.
                                                              (line  42)
* vector-copy:                           Vectors.             (line  76)
* vector-ec:                             Eager comprehensions.
                                                              (line  90)
* vector-fill!:                          Vectors.             (line  68)
* vector-length:                         Vectors.             (line  30)
* vector-of-length-ec:                   Eager comprehensions.
                                                              (line  93)
* vector-ref:                            Vectors.             (line  36)
* vector-set!:                           Vectors.             (line  46)
* vector?:                               Vectors.             (line  19)
* version-compare:                       Comparing version numbers.
                                                              (line  95)
* version<=?:                            Comparing version numbers.
                                                              (line  88)
* version<?:                             Comparing version numbers.
                                                              (line  87)
* version=?:                             Comparing version numbers.
                                                              (line  86)
* version>=?:                            Comparing version numbers.
                                                              (line  90)
* version>?:                             Comparing version numbers.
                                                              (line  89)
* weak-vector-length:                    Weak pointers.       (line  38)
* weak-vector-ref:                       Weak pointers.       (line  41)
* weak-vector-set!:                      Weak pointers.       (line  50)
* when:                                  Conditionals.        (line 107)
* with-builder:                          Fundamental iterator creators.
                                                              (line 104)
* with-error-handler:                    Handling exceptions. (line  45)
* with-error-to-port:                    Common port operations.
                                                              (line  34)
* with-exception-handler:                Handling exceptions. (line  96)
* with-input-conversion:                 Conversion ports.    (line 111)
* with-input-from-file <1>:              Extended port procedures.
                                                              (line  12)
* with-input-from-file:                  File ports.          (line 149)
* with-input-from-port:                  Common port operations.
                                                              (line  32)
* with-input-from-process:               Process ports.       (line  69)
* with-input-from-string:                String ports.        (line  53)
* with-iterator:                         Fundamental iterator creators.
                                                              (line  48)
* with-locking-mutex:                    Synchronization primitives.
                                                              (line 138)
* with-module:                           Defining and selecting modules.
                                                              (line  20)
* with-output-conversion:                Conversion ports.    (line 113)
* with-output-to-file <1>:               File ports.          (line 151)
* with-output-to-file:                   Extended port procedures.
                                                              (line  18)
* with-output-to-port:                   Common port operations.
                                                              (line  33)
* with-output-to-process:                Process ports.       (line 111)
* with-output-to-string:                 String ports.        (line  54)
* with-port-locking:                     Port and threads.    (line  24)
* with-signal-handlers:                  Handling signals.    (line  76)
* with-string-io:                        String ports.        (line  75)
* with-time-counter:                     Measure timings.     (line  82)
* wrap-with-input-conversion:            Conversion ports.    (line 120)
* wrap-with-output-conversion:           Conversion ports.    (line 122)
* write:                                 Output.              (line  10)
* write*:                                Output.              (line  26)
* write-block:                           Uvector block I/O.   (line  41)
* write-byte:                            Output.              (line  76)
* write-char:                            Output.              (line  73)
* write-object:                          Output.              (line  58)
* write-to-string:                       String ports.        (line  88)
* write-tree:                            Lazy text construction.
                                                              (line  38)
* write-with-shared-structure:           Output.              (line  24)
* write/ss:                              Output.              (line  25)
* x->integer:                            Numerical conversions.
                                                              (line  87)
* x->number:                             Numerical conversions.
                                                              (line  86)
* x->string:                             String Constructors. (line  32)
* xcons:                                 SRFI-1 List constructors.
                                                              (line   7)
* xml-token-head:                        SSAX data types.     (line 154)
* xml-token-kind:                        SSAX data types.     (line 153)
* xml-token?:                            SSAX data types.     (line 150)
* xsubstring:                            SRFI-13 String rotation.
                                                              (line   7)
* zero?:                                 Numerical predicates.
                                                              (line  39)
* zip:                                   SRFI-1 List miscellaneous routines.
                                                              (line  21)


File: gauche-refe.info,  Node: Module Index,  Next: Class Index,  Prev: Function and Syntax Index,  Up: Top

Appendix D Module Index
***********************

[index]
* Menu:

* binary.pack:                           Packing Binary Data.  (line  7)
* dbm:                                   Generic DBM interface.
                                                               (line  7)
* dbm.fsdbm:                             File-system dbm.      (line  7)
* dbm.gdbm:                              GDBM interface.       (line  7)
* dbm.ndbm:                              NDBM interface.       (line  7)
* dbm.odbm:                              Original DBM interface.
                                                               (line  7)
* file.filter:                           Filtering file content.
                                                               (line  7)
* file.util:                             Filesystem utilities. (line  7)
* gauche:                                Predefined modules.   (line 22)
* gauche.array:                          Arrays.               (line  7)
* gauche.charconv:                       Character code conversion.
                                                               (line  7)
* gauche.collection:                     Collection framework. (line  7)
* gauche.config:                         Configuration parameters.
                                                               (line  7)
* gauche.fcntl:                          Low-level file operations.
                                                               (line  7)
* gauche.hook:                           Hooks.                (line  7)
* gauche.interactive:                    Interactive session.  (line  7)
* gauche.listener:                       Listener.             (line  7)
* gauche.logger:                         User-level logging.   (line  7)
* gauche.mop.singleton:                  Singleton.            (line  7)
* gauche.mop.validator:                  Slot with validator.  (line  7)
* gauche.net:                            Networking.           (line  7)
* gauche.parameter:                      Parameters.           (line  7)
* gauche.parseopt:                       Parsing command-line options.
                                                               (line  7)
* gauche.process:                        High Level Process Interface.
                                                               (line  7)
* gauche.regexp:                         Regular expression utilities.
                                                               (line  7)
* gauche.reload:                         Reloading modules.    (line  7)
* gauche.selector:                       Simple dispatcher.    (line  7)
* gauche.sequence:                       Sequence framework.   (line  7)
* gauche.syslog:                         Syslog.               (line  7)
* gauche.termios:                        Termios.              (line  7)
* gauche.test:                           Unit testing.         (line  7)
* gauche.threads:                        Threads.              (line 10)
* gauche.time:                           Measure timings.      (line  7)
* gauche.uvector:                        Uniform vectors.      (line  7)
* gauche.version:                        Comparing version numbers.
                                                               (line  7)
* gauche.vport:                          Virtual ports.        (line  7)
* math.const:                            Mathematic constants. (line  7)
* math.mt-random:                        Mersenne-Twister random number generator.
                                                               (line  7)
* null:                                  Predefined modules.   (line  9)
* rfc.822:                               RFC822 message parsing.
                                                               (line  7)
* rfc.base64:                            Base64 encoding/decoding.
                                                               (line  7)
* rfc.cookie:                            HTTP cookie handling. (line  7)
* rfc.hmac:                              HMAC keyed-hashing.   (line  7)
* rfc.http:                              HTTP.                 (line  7)
* rfc.md5:                               MD5 message digest.   (line  7)
* rfc.mime:                              MIME message handling.
                                                               (line  7)
* rfc.quoted-printable:                  Quoted-printable encoding/decoding.
                                                               (line  7)
* rfc.sha1:                              SHA1 message digest.  (line  7)
* rfc.uri:                               URI parsing and construction.
                                                               (line  7)
* scheme:                                Predefined modules.   (line 13)
* slib:                                  SLIB.                 (line  7)
* srfi-0:                                Feature conditional.  (line  7)
* srfi-1:                                List library.         (line  7)
* srfi-11:                               Let-values.           (line  7)
* srfi-13:                               String library.       (line  7)
* srfi-14:                               Character-set library.
                                                               (line  7)
* srfi-2:                                And-let*.             (line  7)
* srfi-27:                               Sources of random bits.
                                                               (line  7)
* srfi-29:                               Localization.         (line  7)
* srfi-29.bundle:                        Localization.         (line  7)
* srfi-29.format:                        Localization.         (line  7)
* srfi-37:                               A program argument processor.
                                                               (line  7)
* srfi-4:                                Homogeneous vectors.  (line  7)
* srfi-42:                               Eager comprehensions. (line  7)
* srfi-5:                                A compatible let form with signatures and rest arguments.
                                                               (line  7)
* srfi-55:                               Requiring extensions. (line  7)
* srfi-7:                                Feature-based program configuration language.
                                                               (line  7)
* srfi-9:                                Record types.         (line  7)
* sxml.ssax:                             Functional XML parser.
                                                               (line  7)
* sxml.sxpath:                           SXML Query Language.  (line  7)
* sxml.tools:                            manipulationg SXML structure.
                                                               (line  7)
* text.csv:                              CSV tables.           (line  7)
* text.diff:                             Calculate difference of text streams.
                                                               (line  7)
* text.gettext:                          Localized messages.   (line  7)
* text.html-lite:                        Simple HTML document construction.
                                                               (line  7)
* text.parse:                            Parsing input stream. (line  7)
* text.tr:                               Transliterate characters.
                                                               (line  7)
* text.tree:                             Lazy text construction.
                                                               (line  7)
* user:                                  Predefined modules.   (line 26)
* util.combinations:                     Combination library.  (line  7)
* util.digest:                           Message digester framework.
                                                               (line  7)
* util.isomorph:                         Determine isomorphism.
                                                               (line  7)
* util.lcs:                              The longest common subsequence.
                                                               (line  7)
* util.list:                             Additional list library.
                                                               (line  7)
* util.match:                            Pattern matching.     (line  7)
* util.queue:                            Queue.                (line  7)
* util.record:                           SLIB-compatible record type.
                                                               (line  7)
* util.toposort:                         Topological sort.     (line  7)
* www.cgi:                               CGI Utility.          (line  7)
* www.cgi-test:                          CGI testing.          (line  7)


File: gauche-refe.info,  Node: Class Index,  Next: Variable Index,  Prev: Module Index,  Up: Top

Appendix E Class Index
**********************

For readability, the surrounding `<' and `>' are stripped off.

[index]
* Menu:

* abandoned-mutex-exception:             Thread exceptions.   (line  22)
* array:                                 Arrays.              (line  59)
* array-base:                            Arrays.              (line  44)
* boolean:                               Booleans.            (line   7)
* buffered-input-port:                   Virtual ports.       (line 197)
* buffered-output-port:                  Virtual ports.       (line 250)
* char:                                  Characters.          (line   7)
* char-set:                              Character set.       (line   7)
* class:                                 Class instantiation. (line  78)
* complex:                               Number classes.      (line  10)
* compound-condition:                    Conditions.          (line  48)
* condition:                             Conditions.          (line  45)
* condition-meta:                        Conditions.          (line  37)
* condition-variable:                    Synchronization primitives.
                                                              (line 147)
* date:                                  SRFI-19 Date.        (line   7)
* dbm:                                   Opening and closing a dbm database.
                                                              (line   7)
* dbm-meta:                              Opening and closing a dbm database.
                                                              (line  73)
* error:                                 Conditions.          (line  80)
* f32array:                              Arrays.              (line  59)
* f32vector:                             Uvector basic operations.
                                                              (line   7)
* f64array:                              Arrays.              (line  59)
* f64vector:                             Uvector basic operations.
                                                              (line   7)
* fsdbm:                                 File-system dbm.     (line  10)
* gdbm:                                  GDBM interface.      (line  10)
* hash-table:                            Hashtables.          (line   7)
* hmac:                                  HMAC keyed-hashing.  (line  15)
* hook:                                  Hooks.               (line  24)
* identifier:                            Identifiers.         (line   7)
* integer:                               Number classes.      (line  10)
* io-closed-error:                       Conditions.          (line 155)
* io-error:                              Conditions.          (line 134)
* io-read-error:                         Conditions.          (line 145)
* io-unit-error:                         Conditions.          (line 159)
* io-write-error:                        Conditions.          (line 150)
* join-timeout-exception:                Thread exceptions.   (line  18)
* keyword:                               Keywords.            (line   7)
* list:                                  Pair and null class. (line   7)
* log-drain:                             User-level logging.  (line  15)
* md5:                                   MD5 message digest.  (line  12)
* mersenne-twister:                      Mersenne-Twister random number generator.
                                                              (line  13)
* message-condition:                     Conditions.          (line  71)
* message-digest-algorithm:              Message digester framework.
                                                              (line  15)
* message-digest-algorithm-meta:         Message digester framework.
                                                              (line  12)
* mime-message:                          MIME message handling.
                                                              (line  93)
* module:                                Module introspection.
                                                              (line  14)
* mutex:                                 Synchronization primitives.
                                                              (line   7)
* ndbm:                                  NDBM interface.      (line  11)
* null:                                  Pair and null class. (line  18)
* number:                                Number classes.      (line  10)
* odbm:                                  Original DBM interface.
                                                              (line  10)
* pair:                                  Pair and null class. (line  21)
* parameter:                             Parameters.          (line  35)
* port:                                  Ports.               (line   7)
* port-error:                            Conditions.          (line 138)
* procedure:                             Procedures.          (line   7)
* process:                               Process object.      (line   7)
* process-time-counter:                  Measure timings.     (line  51)
* read-error:                            Conditions.          (line 111)
* real:                                  Number classes.      (line  10)
* real-time-counter:                     Measure timings.     (line  51)
* regexp:                                Regular expression.  (line  11)
* regmatch:                              Regular expression.  (line  19)
* s16array:                              Arrays.              (line  59)
* s16vector:                             Uvector basic operations.
                                                              (line   7)
* s32array:                              Arrays.              (line  59)
* s32vector:                             Uvector basic operations.
                                                              (line   7)
* s64array:                              Arrays.              (line  59)
* s64vector:                             Uvector basic operations.
                                                              (line   7)
* s8array:                               Arrays.              (line  59)
* s8vector:                              Uvector basic operations.
                                                              (line   7)
* selector:                              Simple dispatcher.   (line  12)
* serious-compound-condition:            Conditions.          (line  63)
* serious-condition:                     Conditions.          (line  57)
* sha1:                                  SHA1 message digest. (line  12)
* singleton-meta:                        Singleton.           (line  10)
* singleton-mixin:                       Singleton.           (line  30)
* sockaddr:                              Socket address.      (line   7)
* sockaddr-in:                           Socket address.      (line  22)
* sockaddr-in6:                          Socket address.      (line  64)
* sockaddr-un:                           Socket address.      (line  52)
* socket:                                High-level network functions.
                                                              (line   7)
* string:                                Strings.             (line   7)
* string-pointer:                        String Pointers.     (line   7)
* symbol:                                Symbols.             (line   7)
* sys-addrinfo:                          Netdb interface.     (line 118)
* sys-fdset:                             I/O multiplexing.    (line  10)
* sys-flock:                             Low-level file operations.
                                                              (line 104)
* sys-group:                             Unix groups and users.
                                                              (line  10)
* sys-hostent:                           Netdb interface.     (line   7)
* sys-passwd:                            Unix groups and users.
                                                              (line  39)
* sys-protoent:                          Netdb interface.     (line  84)
* sys-servent:                           Netdb interface.     (line  43)
* sys-sigset:                            Signals and signal sets.
                                                              (line  54)
* sys-stat:                              File stats.          (line  20)
* sys-termios:                           Termios.             (line  12)
* sys-tm:                                Time.                (line  40)
* system-error:                          Conditions.          (line  95)
* system-time-counter:                   Measure timings.     (line  51)
* terminated-thread-exception:           Thread exceptions.   (line  30)
* thread:                                Thread procedures.   (line   7)
* thread-exception:                      Thread exceptions.   (line  11)
* time:                                  Time.                (line 106)
* time-counter:                          Measure timings.     (line  36)
* u16array:                              Arrays.              (line  59)
* u16vector:                             Uvector basic operations.
                                                              (line   7)
* u32array:                              Arrays.              (line  59)
* u32vector:                             Uvector basic operations.
                                                              (line   7)
* u64array:                              Arrays.              (line  59)
* u64vector:                             Uvector basic operations.
                                                              (line   7)
* u8array:                               Arrays.              (line  59)
* u8vector:                              Uvector basic operations.
                                                              (line   7)
* uncaught-exception:                    Thread exceptions.   (line  39)
* user-time-counter:                     Measure timings.     (line  51)
* validator-meta:                        Slot with validator. (line  10)
* vector:                                Vectors.             (line   7)
* virtual-input-port:                    Virtual ports.       (line  27)
* virtual-output-port:                   Virtual ports.       (line 123)
* weak-vector:                           Weak pointers.       (line  28)


File: gauche-refe.info,  Node: Variable Index,  Prev: Class Index,  Up: Top

Appendix F Variable Index
*************************

[index]
* Menu:

* :                                      SRFI-19 Date.        (line  14)
* &condition:                            Conditions.          (line  45)
* &error:                                Conditions.          (line  80)
* &io-closed-error:                      Conditions.          (line 155)
* &io-error:                             Conditions.          (line 134)
* &io-port-error:                        Conditions.          (line 138)
* &io-read-error:                        Conditions.          (line 145)
* &io-write-error:                       Conditions.          (line 150)
* &read-error:                           Conditions.          (line 111)
* &serious:                              Conditions.          (line  57)
* *argv*:                                Writing Scheme scripts.
                                                              (line  44)
* *load-path*:                           Loading Scheme file. (line  40)
* *program-name*:                        Writing Scheme scripts.
                                                              (line  54)
* *rfc822-atext-chars*:                  RFC822 message parsing.
                                                              (line 125)
* *rfc822-standard-tokenizers*:          RFC822 message parsing.
                                                              (line 128)
* *test-error*:                          Unit testing.        (line  68)
* *test-report-error*:                   Unit testing.        (line  75)
* 1/pi:                                  Mathematic constants.
                                                              (line  14)
* 180/pi:                                Mathematic constants.
                                                              (line  15)
* accessors:                             Class instantiation. (line  98)
* addr:                                  Netdb interface.     (line 134)
* addresses:                             Netdb interface.     (line  17)
* addrlen:                               Netdb interface.     (line 132)
* AF_INET:                               Low-level socket interface.
                                                              (line  19)
* AF_UNIX:                               Low-level socket interface.
                                                              (line  18)
* aliases:                               Netdb interface.     (line  51)
* atime:                                 File stats.          (line  55)
* bsize:                                 GDBM interface.      (line  20)
* category:                              Class instantiation. (line 135)
* cc:                                    Termios.             (line  23)
* cflag:                                 Termios.             (line  19)
* char-set:ascii:                        SRFI-14 Predefined character-set.
                                                              (line  40)
* char-set:blank:                        SRFI-14 Predefined character-set.
                                                              (line  10)
* char-set:digit:                        SRFI-14 Predefined character-set.
                                                              (line  16)
* char-set:empty:                        SRFI-14 Predefined character-set.
                                                              (line  43)
* char-set:full:                         SRFI-14 Predefined character-set.
                                                              (line  46)
* char-set:graphic:                      SRFI-14 Predefined character-set.
                                                              (line  20)
* char-set:hex-digit:                    SRFI-14 Predefined character-set.
                                                              (line  17)
* char-set:iso-control:                  SRFI-14 Predefined character-set.
                                                              (line  13)
* char-set:letter:                       SRFI-14 Predefined character-set.
                                                              (line   7)
* char-set:lower-case:                   SRFI-14 Predefined character-set.
                                                              (line  23)
* char-set:printing:                     SRFI-14 Predefined character-set.
                                                              (line  28)
* char-set:punctuation:                  SRFI-14 Predefined character-set.
                                                              (line  31)
* char-set:symbol:                       SRFI-14 Predefined character-set.
                                                              (line  37)
* char-set:title-case:                   SRFI-14 Predefined character-set.
                                                              (line  25)
* char-set:upper-case:                   SRFI-14 Predefined character-set.
                                                              (line  24)
* char-set:whitespace:                   SRFI-14 Predefined character-set.
                                                              (line  34)
* class:                                 Unix groups and users.
                                                              (line  64)
* close:                                 Virtual ports.       (line 264)
* column:                                Conditions.          (line 126)
* content:                               MIME message handling.
                                                              (line 128)
* cpl:                                   Class instantiation. (line  90)
* ctime:                                 File stats.          (line  57)
* default-random-source:                 Sources of random bits.
                                                              (line  24)
* defined-modules:                       Class instantiation. (line 128)
* dev:                                   File stats.          (line  47)
* dir:                                   Unix groups and users.
                                                              (line  58)
* direct-methods:                        Class instantiation. (line 119)
* direct-slots:                          Class instantiation. (line 107)
* direct-subclasses:                     Class instantiation. (line 115)
* direct-supers:                         Class instantiation. (line  94)
* e:                                     Mathematic constants.
                                                              (line  18)
* environment:                           Listener.            (line  76)
* errno:                                 Conditions.          (line 102)
* error-handler:                         Listener.            (line  86)
* error-port:                            Listener.            (line  48)
* evaluator:                             Listener.            (line  58)
* F_DUPFD:                               Low-level file operations.
                                                              (line  66)
* F_GETFD:                               Low-level file operations.
                                                              (line  21)
* F_GETFL:                               Low-level file operations.
                                                              (line  37)
* F_GETLK:                               Low-level file operations.
                                                              (line  72)
* F_GETOWN:                              Low-level file operations.
                                                              (line  86)
* F_OK:                                  File stats.          (line 124)
* F_RDLCK:                               Low-level file operations.
                                                              (line 117)
* F_SETFD:                               Low-level file operations.
                                                              (line  29)
* F_SETFL:                               Low-level file operations.
                                                              (line  55)
* F_SETLK:                               Low-level file operations.
                                                              (line  78)
* F_SETLKW:                              Low-level file operations.
                                                              (line  78)
* F_SETOWN:                              Low-level file operations.
                                                              (line  93)
* F_UNLCK:                               Low-level file operations.
                                                              (line 123)
* F_WRLCK:                               Low-level file operations.
                                                              (line 120)
* family:                                Netdb interface.     (line 126)
* FD_CLOEXEC:                            Low-level file operations.
                                                              (line  21)
* file-mode:                             Opening and closing a dbm database.
                                                              (line  37)
* filenum:                               Virtual ports.       (line 267)
* fill:                                  Virtual ports.       (line 202)
* finalizer:                             Listener.            (line  81)
* flags:                                 Netdb interface.     (line 124)
* flush:                                 Virtual ports.       (line 160)
* GDBM_CACHESIZE:                        GDBM interface.      (line  69)
* GDBM_CENTFREE:                         GDBM interface.      (line  75)
* GDBM_COALESCEBLKS:                     GDBM interface.      (line  77)
* GDBM_FAST:                             GDBM interface.      (line  36)
* GDBM_FASTMODE:                         GDBM interface.      (line  71)
* GDBM_INSERT:                           GDBM interface.      (line  47)
* GDBM_NEWDB:                            GDBM interface.      (line  34)
* GDBM_NOLOCK:                           GDBM interface.      (line  40)
* GDBM_READER:                           GDBM interface.      (line  28)
* GDBM_REPLACE:                          GDBM interface.      (line  49)
* GDBM_SYNC:                             GDBM interface.      (line  38)
* GDBM_SYNCMODE:                         GDBM interface.      (line  73)
* GDBM_WRCREAT:                          GDBM interface.      (line  32)
* GDBM_WRITER:                           GDBM interface.      (line  30)
* gecos:                                 Unix groups and users.
                                                              (line  55)
* getb:                                  Virtual ports.       (line  36)
* getc:                                  Virtual ports.       (line  49)
* gets:                                  Virtual ports.       (line  63)
* gid <1>:                               Unix groups and users.
                                                              (line  16)
* gid <2>:                               File stats.          (line  51)
* gid:                                   Unix groups and users.
                                                              (line  48)
* headers:                               MIME message handling.
                                                              (line 117)
* hour:                                  Time.                (line  50)
* iflag:                                 Termios.             (line  15)
* index:                                 MIME message handling.
                                                              (line 125)
* initargs:                              Class instantiation. (line 123)
* ino:                                   File stats.          (line  46)
* input-port:                            Listener.            (line  38)
* isdst:                                 Time.                (line  68)
* key-convert:                           Opening and closing a dbm database.
                                                              (line  41)
* LC_ALL:                                Locale.              (line  14)
* LC_COLLATE:                            Locale.              (line  15)
* LC_CTYPE:                              Locale.              (line  16)
* LC_MONETARY:                           Locale.              (line  17)
* LC_NUMERIC:                            Locale.              (line  18)
* LC_TIME:                               Locale.              (line  19)
* len:                                   Low-level file operations.
                                                              (line 133)
* lflag:                                 Termios.             (line  21)
* line:                                  Conditions.          (line 121)
* lock-policy:                           User-level logging.  (line  85)
* mday:                                  Time.                (line  53)
* mem:                                   Unix groups and users.
                                                              (line  22)
* message:                               Conditions.          (line  75)
* min:                                   Time.                (line  47)
* mode:                                  File stats.          (line  45)
* mon:                                   Time.                (line  56)
* MSG_CTRUNC:                            Low-level socket interface.
                                                              (line 118)
* MSG_DONTROUTE:                         Low-level socket interface.
                                                              (line 119)
* MSG_EOR:                               Low-level socket interface.
                                                              (line 120)
* MSG_OOB:                               Low-level socket interface.
                                                              (line 121)
* MSG_PEEK:                              Low-level socket interface.
                                                              (line 122)
* MSG_TRUNC:                             Low-level socket interface.
                                                              (line 123)
* MSG_WAITALL:                           Low-level socket interface.
                                                              (line 124)
* mtime:                                 File stats.          (line  56)
* mutex:                                 Thread exceptions.   (line  27)
* name <1>:                              Unix groups and users.
                                                              (line  13)
* name <2>:                              Netdb interface.     (line  88)
* name <3>:                              Class instantiation. (line  86)
* name <4>:                              Thread procedures.   (line  38)
* name <5>:                              Synchronization primitives.
                                                              (line 157)
* name:                                  Unix groups and users.
                                                              (line  42)
* nanosecond:                            Time.                (line 115)
* nlink:                                 File stats.          (line  49)
* nolock:                                GDBM interface.      (line  18)
* num-instance-slots:                    Class instantiation. (line 112)
* O_ACCMODE:                             Low-level file operations.
                                                              (line  40)
* O_APPEND:                              Low-level file operations.
                                                              (line  46)
* O_CREAT:                               Low-level file operations.
                                                              (line  43)
* O_EXCL:                                Low-level file operations.
                                                              (line  43)
* O_NOCTTY:                              Low-level file operations.
                                                              (line  50)
* O_NONBLOCK:                            Low-level file operations.
                                                              (line  48)
* O_RDONLY:                              Low-level file operations.
                                                              (line  40)
* O_RDWR:                                Low-level file operations.
                                                              (line  40)
* O_TRUNC:                               Low-level file operations.
                                                              (line  43)
* O_WRONLY:                              Low-level file operations.
                                                              (line  40)
* oflag:                                 Termios.             (line  17)
* output-port:                           Listener.            (line  43)
* parameters:                            MIME message handling.
                                                              (line 108)
* parent:                                MIME message handling.
                                                              (line 120)
* passwd:                                Unix groups and users.
                                                              (line  51)
* path <1>:                              Opening and closing a dbm database.
                                                              (line  16)
* path:                                  User-level logging.  (line  21)
* perm:                                  File stats.          (line  40)
* PF_INET:                               Low-level socket interface.
                                                              (line  15)
* PF_UNIX:                               Low-level socket interface.
                                                              (line  14)
* pi:                                    Mathematic constants.
                                                              (line  10)
* pi/180:                                Mathematic constants.
                                                              (line  13)
* pi/2:                                  Mathematic constants.
                                                              (line  11)
* pi/4:                                  Mathematic constants.
                                                              (line  12)
* pid:                                   Low-level file operations.
                                                              (line 136)
* port <1>:                              Netdb interface.     (line  54)
* port:                                  Conditions.          (line 141)
* position:                              Conditions.          (line 127)
* prefix:                                User-level logging.  (line  30)
* printer:                               Listener.            (line  64)
* program-name:                          User-level logging.  (line  81)
* prompter:                              Listener.            (line  70)
* proto:                                 Netdb interface.     (line  57)
* protocol:                              Netdb interface.     (line 130)
* putb:                                  Virtual ports.       (line 131)
* putc:                                  Virtual ports.       (line 140)
* puts:                                  Virtual ports.       (line 150)
* R_OK:                                  File stats.          (line 114)
* RAND_MAX:                              Miscellaneous system calls.
                                                              (line  63)
* rdev:                                  File stats.          (line  48)
* reader:                                Listener.            (line  53)
* ready:                                 Virtual ports.       (line  82)
* reason:                                Thread exceptions.   (line  44)
* redefined:                             Class instantiation. (line 131)
* rw-mode:                               Opening and closing a dbm database.
                                                              (line  20)
* sec:                                   Time.                (line  44)
* second:                                Time.                (line 112)
* seek:                                  Virtual ports.       (line 103)
* shell:                                 Unix groups and users.
                                                              (line  61)
* SIGABRT:                               Signals and signal sets.
                                                              (line  13)
* SIGALRM:                               Signals and signal sets.
                                                              (line  14)
* SIGBUS:                                Signals and signal sets.
                                                              (line  36)
* SIGCHLD:                               Signals and signal sets.
                                                              (line  15)
* SIGCONT:                               Signals and signal sets.
                                                              (line  16)
* SIGFPE:                                Signals and signal sets.
                                                              (line  17)
* SIGHUP:                                Signals and signal sets.
                                                              (line  18)
* SIGILL:                                Signals and signal sets.
                                                              (line  19)
* SIGINT:                                Signals and signal sets.
                                                              (line  20)
* SIGIO:                                 Signals and signal sets.
                                                              (line  45)
* SIGIOT:                                Signals and signal sets.
                                                              (line  35)
* SIGKILL:                               Signals and signal sets.
                                                              (line  21)
* SIGPIPE:                               Signals and signal sets.
                                                              (line  22)
* SIGPOLL:                               Signals and signal sets.
                                                              (line  44)
* SIGPROF:                               Signals and signal sets.
                                                              (line  42)
* SIGPWR:                                Signals and signal sets.
                                                              (line  46)
* SIGQUIT:                               Signals and signal sets.
                                                              (line  23)
* SIGSEGV:                               Signals and signal sets.
                                                              (line  24)
* SIGSTKFLT:                             Signals and signal sets.
                                                              (line  37)
* SIGSTOP:                               Signals and signal sets.
                                                              (line  25)
* SIGTERM:                               Signals and signal sets.
                                                              (line  26)
* SIGTRAP:                               Signals and signal sets.
                                                              (line  34)
* SIGTSTP:                               Signals and signal sets.
                                                              (line  27)
* SIGTTIN:                               Signals and signal sets.
                                                              (line  28)
* SIGTTOU:                               Signals and signal sets.
                                                              (line  29)
* SIGURG:                                Signals and signal sets.
                                                              (line  38)
* SIGUSR1:                               Signals and signal sets.
                                                              (line  30)
* SIGUSR2:                               Signals and signal sets.
                                                              (line  31)
* SIGVTALRM:                             Signals and signal sets.
                                                              (line  41)
* SIGWINCH:                              Signals and signal sets.
                                                              (line  43)
* SIGXCPU:                               Signals and signal sets.
                                                              (line  39)
* SIGXFSZ:                               Signals and signal sets.
                                                              (line  40)
* size:                                  File stats.          (line  52)
* slots:                                 Class instantiation. (line 102)
* SO_BROADCAST:                          Low-level socket interface.
                                                              (line 198)
* SO_ERROR:                              Low-level socket interface.
                                                              (line 206)
* SO_KEEPALIVE:                          Low-level socket interface.
                                                              (line 179)
* SO_OOBINLINE:                          Low-level socket interface.
                                                              (line 183)
* SO_PRIORITY:                           Low-level socket interface.
                                                              (line 202)
* SO_REUSEADDR:                          Low-level socket interface.
                                                              (line 189)
* SO_TYPE:                               Low-level socket interface.
                                                              (line 194)
* SOCK_DGRAM:                            Low-level socket interface.
                                                              (line  23)
* SOCK_RAW:                              Low-level socket interface.
                                                              (line  24)
* SOCK_STREAM:                           Low-level socket interface.
                                                              (line  22)
* socktype:                              Netdb interface.     (line 128)
* SOL_IP:                                Low-level socket interface.
                                                              (line 173)
* SOL_SOCKET:                            Low-level socket interface.
                                                              (line 171)
* SOL_TCP:                               Low-level socket interface.
                                                              (line 172)
* span:                                  Conditions.          (line 128)
* specific <1>:                          Synchronization primitives.
                                                              (line 160)
* specific:                              Thread procedures.   (line  43)
* ssax:Prefix-XML:                       SSAX low-level parsing code.
                                                              (line  38)
* start:                                 Low-level file operations.
                                                              (line 130)
* state:                                 Synchronization primitives.
                                                              (line  24)
* subtype:                               MIME message handling.
                                                              (line 104)
* sync:                                  GDBM interface.      (line  16)
* syslog-facility:                       User-level logging.  (line 105)
* syslog-option:                         User-level logging.  (line 104)
* syslog-priority:                       User-level logging.  (line 106)
* TCIFLUSH:                              Termios.             (line  72)
* TCIOFF:                                Termios.             (line  90)
* TCIOFLUSH:                             Termios.             (line  78)
* TCION:                                 Termios.             (line  94)
* TCOFLUSH:                              Termios.             (line  75)
* TCOOFF:                                Termios.             (line  84)
* TCOON:                                 Termios.             (line  87)
* TCSADRAIN:                             Termios.             (line  54)
* TCSAFLUSH:                             Termios.             (line  57)
* TCSANOW:                               Termios.             (line  51)
* terminator:                            Thread exceptions.   (line  35)
* thread:                                Thread exceptions.   (line  15)
* time-duration:                         SRFI-19 Time types.  (line  22)
* time-monotonic:                        SRFI-19 Time types.  (line  18)
* time-process:                          SRFI-19 Time types.  (line  25)
* time-tai:                              SRFI-19 Time types.  (line  14)
* time-thread:                           SRFI-19 Time types.  (line  29)
* time-utc:                              SRFI-19 Time types.  (line  10)
* transfer-encoding:                     MIME message handling.
                                                              (line 112)
* type <1>:                              Low-level file operations.
                                                              (line 113)
* type <2>:                              Time.                (line 107)
* type <3>:                              File stats.          (line  24)
* type:                                  MIME message handling.
                                                              (line 100)
* uid <1>:                               File stats.          (line  50)
* uid:                                   Unix groups and users.
                                                              (line  45)
* value-convert:                         Opening and closing a dbm database.
                                                              (line  42)
* W_OK:                                  File stats.          (line 117)
* wday:                                  Time.                (line  62)
* whence:                                Low-level file operations.
                                                              (line 127)
* X_OK:                                  File stats.          (line 120)
* yday:                                  Time.                (line  65)
* year:                                  Time.                (line  59)



Tag Table:
Node: Top244
Node: Introduction816
Node: Overview of Gauche2406
Node: Notations5442
Node: Concepts8040
Node: Standard conformance8436
Node: Multibyte Strings13785
Node: Multibyte scripts16459
Node: Case-sensitivity18588
Node: Integerated Object System20396
Node: Module system24424
Node: Compilation26466
Node: Programming in Gauche28477
Node: Invoking Gosh28807
Node: Interactive development34148
Node: Writing Scheme scripts35432
Node: Debugging39705
Node: Profiling and tuning41040
Node: Using profiler42236
Node: Performance tips46642
Node: Writing Gauche modules50934
Node: Using extension packages53960
Node: Core syntax57965
Node: Lexical structure58294
Node: Literals62135
Node: Making Procedures62895
Node: Assignments66947
Node: Conditionals72190
Node: Binding constructs76880
Node: Sequencing80761
Node: Iteration82052
Node: Quasiquotation82938
Node: Definitions83133
Node: Modules85878
Node: Module semantics86329
Node: Modules and libraries90787
Node: Defining and selecting modules92471
Node: Using modules93888
Node: Module inheritance96276
Node: Module introspection98789
Node: Predefined modules102624
Node: Macros103642
Node: Hygienic Macros104288
Node: Traditional Macros104990
Node: Macro expansion105673
Node: Macro utilities106326
Node: Core library107863
Node: Equivalence108384
Node: Numbers112002
Node: Number classes112699
Node: Numerical predicates113665
Node: Numerical comparison115912
Node: Arithmetics116880
Node: Numerical conversions121815
Node: Bitwise operations126152
Node: Booleans127883
Node: Pairs and Lists128295
Node: Pair and null class129068
Node: List predicates129805
Node: List constructors130419
Node: List accessors and modifiers131678
Node: Other list procedures133499
Node: Symbols135877
Node: Keywords137345
Node: Identifiers140191
Node: Characters140434
Node: Character set147092
Node: Strings150120
Node: String syntax150826
Node: String Predicates152612
Node: String Constructors153071
Node: String interpolation154817
Node: String Accessors & Modifiers157942
Node: String Comparison160025
Node: String utilities160657
Node: String Pointers166101
Node: Incomplete strings167325
Node: Regular expression167563
Node: Vectors176785
Node: Hashtables180170
Node: Weak pointers188104
Node: Control features190016
Node: Procedures190281
Node: Mapping190965
Node: Combinators192168
Node: Optional argument parsing195260
Node: Procedure arity199715
Node: Applicable objects201147
Node: Continuation202899
Node: Multiple values206296
Node: Delayed Evaludation207496
Node: Exceptions209190
Node: Exception handling overview210252
Node: Signalling exceptions216733
Node: Handling exceptions219263
Node: Conditions225134
Node: Eval and repl235435
Node: Input and output238415
Node: Ports238721
Node: Port and threads240831
Node: Common port operations242698
Node: File ports248591
Node: String ports257410
Node: Coding-aware ports261555
Node: Input263214
Node: Reading data263566
Node: Read-time constructor268815
Node: Input utility functions272361
Node: Output274161
Node: Loading Programs284908
Node: Loading Scheme file285206
Node: Loading dynamic library289942
Node: Require and provide291397
Node: Autoload292463
Node: Operations on libraries294299
Node: Comparison and sorting299738
Node: System interface301461
Node: Program termination303035
Node: Environment Inquiry303974
Node: Filesystems304863
Node: Directories305290
Node: Directory manipulation306483
Node: Pathnames309231
Node: File stats312178
Node: Other file operations317806
Node: Unix groups and users319443
Node: Locale321952
Node: Signal323922
Node: Signals and signal sets324679
Node: Sending signals327014
Node: Handling signals327842
Node: Masking and waiting signals332750
Node: Signals and threads334165
Node: System Inquiry336875
Node: Time339878
Node: Unix process management344621
Node: I/O multiplexing351564
Node: Miscellaneous system calls354367
Node: Development helper API357204
Node: Debugging aid357487
Node: Profiler API358371
Node: Object system359614
Node: Introduction to the object system360206
Node: General Inquiry380117
Node: Class381630
Node: Defining class381954
Node: Inheritance389023
Node: Class object395094
Node: Slot definition object397988
Node: Class redefinition399408
Node: Class definition examples403943
Node: Instance408324
Node: Creating instance408604
Node: Accessing instance411485
Node: Changing classes415664
Node: Generic function and method420270
Node: Metaobject protocol424749
Node: Class instantiation425964
Node: Customizing slot access431917
Node: Method instantiation432316
Node: Customizing method application432573
Node: Library modules - Overview433060
Node: Library modules - Gauche extensions435821
Node: Arrays436624
Node: Character code conversion446161
Node: Supported character encoding schemes447223
Node: Autodetecting the encoding scheme453558
Node: Conversion ports454770
Node: Extended port procedures461738
Node: Collection framework463046
Node: Mapping over collection465810
Node: Selection and searching in collection472856
Node: Miscellaneous operations on collection476591
Node: Fundamental iterator creators477971
Node: Implementing collections485058
Node: Configuration parameters486389
Node: Low-level file operations487496
Node: Hooks493091
Node: Interactive session495390
Node: Listener498176
Node: User-level logging506217
Node: Singleton512574
Node: Slot with validator513972
Node: Networking516570
Node: Socket address517390
Node: High-level network functions521206
Node: Low-level socket interface528776
Node: Netdb interface537412
Node: Parameters543179
Node: Parsing command-line options547635
Node: High Level Process Interface556665
Node: Process object557371
Node: Process ports562974
Node: Regular expression utilities569812
Node: Reloading modules578398
Node: Simple dispatcher581761
Node: Sequence framework585499
Node: Fundamental sequence accessors586458
Node: Slicing sequence587657
Node: Mapping over sequences588951
Node: Selection and searching in sequence591088
Node: Implementing sequence592651
Node: Syslog592835
Node: Termios595556
Node: Unit testing601747
Node: Threads606368
Node: Thread programming tips607538
Node: Thread procedures610543
Node: Synchronization primitives616006
Node: Thread exceptions624481
Node: Measure timings626793
Node: Uniform vectors631450
Node: Uvector basic operations635362
Node: Uvector conversion operations640052
Node: Uvector numeric operations646065
Node: Uvector block I/O651085
Node: Comparing version numbers653718
Node: Virtual ports658322
Node: Library modules - SRFIs673278
Node: Feature conditional674128
Node: List library677071
Node: SRFI-1 List constructors677849
Node: SRFI-1 List predicates678991
Node: SRFI-1 List selectors680268
Node: SRFI-1 List miscellaneous routines683432
Node: SRFI-1 Fold686156
Node: SRFI-1 Filtering & Partitioning691053
Node: SRFI-1 Searching692626
Node: SRFI-1 Deletion694698
Node: SRFI-1 Association lists695655
Node: SRFI-1 Set operations696804
Node: And-let*699197
Node: Homogeneous vectors701162
Node: A compatible let form with signatures and rest arguments701588
Node: Feature-based program configuration language702627
Node: Record types705461
Node: Let-values708030
Node: String library709702
Node: SRFI-13 General conventions711073
Node: SRFI-13 String predicates713300
Node: SRFI-13 String Constructors714238
Node: SRFI-13 String Selection714889
Node: SRFI-13 String Comparison717739
Node: SRFI-13 String Prefixes & Suffixes719109
Node: SRFI-13 String searching719995
Node: SRFI-13 String case mapping722067
Node: SRFI-13 String reverse & append722639
Node: SRFI-13 String mapping723987
Node: SRFI-13 String rotation725173
Node: SRFI-13 other string operations725543
Node: SRFI-13 String filtering726336
Node: SRFI-13 Low-level string procedures726705
Node: Character-set library727497
Node: SRFI-14 Character-set constructors728177
Node: SRFI-14 Character-set Comparison729812
Node: SRFI-14 Character-set iteration730237
Node: SRFI-14 Character-set query731042
Node: SRFI-14 Character-set algebra731605
Node: SRFI-14 Predefined character-set732871
Node: Time data types and procedures733785
Node: SRFI-19 Time types734418
Node: SRFI-19 Time queries735553
Node: SRFI-19 Time procedures736782
Node: SRFI-19 Date738747
Node: SRFI-19 Date reader and writer743403
Node: Sources of random bits743727
Node: Localization746722
Node: A program argument processor751347
Node: Eager comprehensions757874
Node: Requiring extensions762991
Node: Library modules - Utilities764134
Node: Packing Binary Data766256
Node: Generic DBM interface773616
Node: Opening and closing a dbm database775559
Node: Accessing a dbm database779900
Node: Iterating on a database780744
Node: Managing dbm database instance782079
Node: File-system dbm783436
Node: GDBM interface785124
Node: NDBM interface787087
Node: Original DBM interface788202
Node: Filtering file content789344
Node: Filesystem utilities792458
Node: Directory utilities793624
Node: Pathname utilities799430
Node: File attribute utilities803643
Node: File operations807651
Node: Mathematic constants810776
Node: Mersenne-Twister random number generator811330
Node: RFC822 message parsing814349
Node: Base64 encoding/decoding821491
Node: HTTP cookie handling823053
Node: HMAC keyed-hashing826649
Node: HTTP828546
Node: MD5 message digest833739
Node: MIME message handling834817
Node: Quoted-printable encoding/decoding842523
Node: SHA1 message digest844069
Node: URI parsing and construction845199
Node: SLIB851265
Node: Functional XML parser852256
Node: SSAX data types854611
Node: SSAX low-level parsing code860920
Node: SSAX higher-level parsers and scanners872479
Node: SSAX Highest-level parsers - XML to SXML875772
Node: SXML Query Language883901
Node: SXPath basic converters and applicators885248
Node: SXPath query language894424
Node: SXPath extension896886
Node: manipulationg SXML structure901204
Node: SXML predicates901898
Node: SXML accessors903141
Node: SXML modifiers909568
Node: SXPath auxiliary utilities912713
Node: SXML to markup conversion913626
Node: CSV tables915617
Node: Calculate difference of text streams917491
Node: Localized messages919883
Node: Simple HTML document construction925017
Node: Parsing input stream929546
Node: Transliterate characters934209
Node: Lazy text construction939631
Node: Combination library941835
Node: Message digester framework945362
Node: Determine isomorphism947113
Node: The longest common subsequence948554
Node: Additional list library952960
Node: Pattern matching959484
Node: Queue971405
Node: SLIB-compatible record type975598
Node: Topological sort978147
Node: CGI Utility979025
Node: CGI testing993369
Node: References998109
Ref: r5rs998273
Ref: onecont998560
Ref: meyers86998745
Ref: mop998877
Ref: dylan998991
Ref: fairthreads999268
Ref: rfc1321999397
Ref: rfc2045999522
Ref: rfc2396999719
Ref: rfc2616999894
Ref: rfc28221000032
Ref: rfc29651000150
Ref: rfc31741000290
Ref: srfi-01000440
Ref: srfi-11000582
Ref: srfi-21000691
Ref: srfi-41000863
Ref: srfi-61000987
Ref: srfi-81001104
Ref: srfi-91001244
Ref: srfi-101001366
Ref: srfi-111001485
Ref: srfi-131001620
Ref: srfi-141001737
Ref: srfi-171001859
Ref: srfi-181001973
Ref: srfi-191002092
Ref: srfi-211002224
Ref: srfi-221002354
Ref: srfi-231002514
Ref: srfi-251002639
Ref: srfi-261002775
Ref: srfi-271002933
Ref: srfi-281003055
Ref: srfi-371003175
Ref: ssax1003319
Ref: MT1003512
Ref: oleg11003801
Ref: oleg21003918
Node: C to Scheme mapping1004059
Node: Function and Syntax Index1026954
Node: Module Index1267899
Node: Class Index1276906
Node: Variable Index1287461

End Tag Table
