@node Library modules - SRFIs, Library modules - Utilities, Library modules - R7RS standard libraries, Top
@chapter Library modules - SRFIs
@c NODE ライブラリモジュール - SRFI

@c EN
This chapter lists modules that provides SRFI functionalities.
Note that some of SRFI features are built in Gauche core and
not listed here.  The SRFIs that have been adopted to R7RS-large
are described in @ref{Library modules - R7RS standard libraries}.

@xref{Standard conformance}, for entire list
of supported SRFIs.

(Even if a srfi is not listed here, you can still say
@code{(use srfi-N)} or @code{(import (srfi N))}, as far as
srfi N is supported by Gauche.)
@c JP
この章ではSRFIの機能を提供するモジュールをリストします。
一部のSRFIはGaucheのコアに組み込まれており、
この章には挙げられていないことに注意して下さい。
また、R7RS-largeに取り入れられたsrfiは@ref{Library modules - R7RS standard libraries}で解説しています。

サポートされている全てのSRFIのリストは@ref{Standard conformance}にあります。

(ここに挙げられていないSRFIでも、サポートされているものについては
@code{(use srfi-N)}や@code{(import (srfi N))}と書くことができます。)
@c COMMON

@c ----------------------------------------------------------------------
@menu
* SRFIs that have become R7RS-large::
* Homogeneous vectors::         srfi-4
* A compatible let form with signatures and rest arguments::  srfi-5
* Feature-based program configuration language::  srfi-7
* String library::              srfi-13
* Time data types and procedures::  srfi-19
* Sources of random bits::      srfi-27
* Localization::                srfi-29
* A program argument processor::  srfi-37
* Eager comprehensions::        srfi-42
* Vector library (Legacy)::     srfi-43
* Requiring extensions::        srfi-55
* Integers as bits::            srfi-60
* A Scheme API for test suites::  srfi-64
* Octet vectors::               srfi-66
* Basic hash tables::           srfi-69
* Octet-addressed binary blocks::  srfi-74
* Lightweight testing::         srfi-78
* Accessing environment variables::  srfi-98
* Basic socket interface::      srfi-106
* Purely functional random-access pairs and lists::  srfi-101
* Portable runtime environment inquiry::  srfi-112
* Comparators::                 srfi-114
* Simple adjustable-size strings::  srfi-118
* Cursor-based string library::  srfi-130
* String library (reduced)::    srfi-152
* First-class dynamic extents::  srfi-154
* Homogeneous numeric vector libraries::  srfi-160
* Comparator sublibrary::       srfi-162
* POSIX API::                   srfi-170
* Hooks (srfi)::                srfi-173
* POSIX timespecs::             srfi-174
* ASCII character library::     srfi-175
* Bitvector library::           srfi-178
* JSON::                        srfi-180
* Custom ports::                srfi-181
* Linear adjustable-length strings::  srfi-185
* Maybe and Either optional container types::  srfi-189
* Port positioning::            srfi-192
* Command line::                srfi-193
@end menu


@node SRFIs that have become R7RS-large, Homogeneous vectors, Library modules - SRFIs, Library modules - SRFIs
@section SRFIs that have become R7RS-large
@c NODE R7RS-largeになったSRFI

@c EN
Here's a list of SRFIs that have become a part of R7RS-large,
ordered by SRFI numbers.
@c JP
以下に、R7RS-largeに取り入れられたSRFIのリストを番号順に示します。
@c COMMON

@table @asis
@item srfi-1 List library
@code{scheme.list} (@pxref{R7RS lists}).
@item srfi-14 Character-set library
@code{scheme.char-set} (@pxref{R7RS character sets}).
@item srfi-41 Streams
@code{scheme.stream} (@pxref{R7RS stream}).
@item srfi-101 Purely functional random-access pairs and lists
@code{scheme.rlist} (@pxref{R7RS random-access lists}).
@item srfi-111 Boxes
@code{scheme.box} (@pxref{R7RS boxes}).
@item srfi-113 Sets and bags
@code{scheme.set} (@pxref{R7RS sets}).
@item srfi-115 Scheme Regular Expressions
@code{scheme.regex} (@pxref{R7RS regular expressions}).
@item srfi-116 Immutable list library
@code{scheme.ilist}
@item srfi-117 Queues based on lists
@code{scheme.list-queue} (@pxref{R7RS list queues}).
@item srfi-121 Generators
@code{scheme.generator} (@pxref{R7RS generators}).
@item srfi-124 Ephemerons
@code{scheme.ephemeron} (@pxref{R7RS ephemerons}).
@item srfi-125 Intermediate hash tables
@code{scheme.hash-table} (@pxref{R7RS hash tables}).
@item srfi-127 Lazy sequences
@code{scheme.lseq} (@pxref{R7RS lazy sequences}).
@item srfi-128 Comparators (reduced)
@code{scheme.comparator} (@pxref{R7RS comparators}).
@item srfi-132 Sort library
@code{scheme.sort} (@pxref{R7RS sort}).
@item srfi-133 Vector library
@code{scheme.vector} (@pxref{R7RS vectors}).
@item srfi-134 Immutable deques
@code{scheme.ideque} (@pxref{R7RS immutable deques}).
@item srfi-135 Immutable texts
@code{scheme.text} (@pxref{R7RS immutable texts}).
@item srfi-141 Integer division
@code{scheme.division} (@pxref{R7RS integer division}).
@item srfi-143 Fixnums
@code{scheme.fixnum} (@pxref{R7RS fixnum}).
@item srfi-144 Flonums
@code{scheme.flonum} (@pxref{R7RS flonum}).
@item srfi-146 Mappings
@code{scheme.mapping}, @code{scheme.mapping.hash} (@pxref{R7RS mappings}).
@item srfi-151 Bitwise operations
@code{scheme.bitwise} (@pxref{R7RS bitwise operations}).
@item srfi-158 Generators and accumulators
@code{scheme.generator} (@pxref{R7RS generators}).
@item srfi-159 Combinator formatting
@code{scheme.show}
@item srfi-160 Homogeneous numeric vector libraries
@code{scheme.vector.@@} (@pxref{R7RS uniform vectors}).
@end table


@c ----------------------------------------------------------------------
@node Homogeneous vectors, A compatible let form with signatures and rest arguments, SRFIs that have become R7RS-large, Library modules - SRFIs
@section @code{srfi-4} - Homogeneous vectors
@c NODE 単一型のベクタ, @code{srfi-4} - 単一型のベクタ

@deftp {Module} srfi-4
@mdindex srfi-4
@c EN
SRFI-4 is now implemented in @code{gauche.uvector} module
@xref{Uniform vectors}.
This module simply inherits @code{gauche.uvector} for backward-compatibility.
@c JP
SRFI-4は、@code{gauche.uvector}モジュールとして実装されています。
@ref{Uniform vectors}参照。
このモジュールは後方互換性のために単に@code{gauche.uvector}を継承しています。
@c COMMON
@end deftp

@c ----------------------------------------------------------------------
@node A compatible let form with signatures and rest arguments, Feature-based program configuration language, Homogeneous vectors, Library modules - SRFIs
@section @code{srfi-5} - A compatible let form with signatures and rest arguments
@c NODE シグネチャとrest引数に互換性のあるlet形式, @code{srfi-5} - シグネチャとrest引数に互換性のあるlet形式

@deftp {Module} srfi-5
@mdindex srfi-5
@c EN
This module provides srfi-5's extended @code{let} syntax.
@c JP
このモジュールは SRFI-5 の拡張 @code{let} 構文を提供します。
@c COMMON
@end deftp

@defmac let ((var val) @dots{} [. (rest val @dots{})]) body @dots{}
@defmacx let name ((var val) @dots{} [. (rest val @dots{})]) body @dots{}
@defmacx let (name (var val) @dots{} [. (rest val @dots{})]) body @dots{}
[SRFI-5]
@c MOD srfi-5
@c EN
The @code{let} syntax is extended in two ways.
@c JP
@code{let} 構文は 2通りの拡張がされています。
@c COMMON

@c EN
@itemize @bullet
@item
The extended @code{let} syntax accepts the @var{name} identifier (for
named let syntax) within the list of bindings (as in the third
syntax above).
@item
The extended @code{let} syntax accepts the rest parameter binding
which works like the rest parameter in the @code{lambda} syntax.
@end itemize

See SRFI-5 document for rationale of this extension.
@c JP
@itemize @bullet
@item
拡張 @code{let} 構文は、@var{name} 束縛リスト中で(名前付き let 構文用の)
識別子を許します(上の3つめの構文)。
@item
拡張 @code{let} 構文は、@code{lambda} 構文の rest パラメータと同様の
働きをする rest パラメータ束縛を許します。
@end itemize

この拡張に関する理論的根拠については SRFI-5 のドキュメントを参照してください。
@c COMMON
@end defmac

@c ----------------------------------------------------------------------
@node Feature-based program configuration language, String library, A compatible let form with signatures and rest arguments, Library modules - SRFIs
@section @code{srfi-7} - Feature-based program configuration language
@c NODE 機能ベースプログラム設定言語, @code{srfi-7} - 機能ベースプログラム設定言語

@deftp {Module} srfi-7
@mdindex srfi-7
@c EN
This module provides a program configuration metalanguage
(@code{program} form) defined in srfi-7.
@c JP
このモジュールは、SRFI-7 で定義されている
プログラム設定メタ言語(@code{program} フォーム)を提供します。

@c EN
Gauche autoloads srfi-7 module, so you don't need
to say @code{(use srfi-7)} explicitly.
@c JP
Gauche は srfi-7 モジュールを autoload しますので、@code{(use srfi-7)} と
明示的に書く必要はありません。

@c EN
Note that the @code{program} form isn't necessary to be a
Scheme expression.  Srfi-7 allows an implementation to preprocess
the @code{program} form to produce a Scheme program, then
executes it with different means.
@c JP
@code{program} フォームは Scheme の式である必要がないことに注意してください。
SRFI-7 では、この @code{program}フォームを処理して Scheme プログラムを
生成してから、それを別の方法で実行するような実装を許しています。

@c EN
Gauche implements @code{program} form as a macro, so it can
evaluates the form directly.  Nonetheless, it doesn't make sense
to mix @code{program} form and other forms in one file,
or expecting a return value of @code{program} form.
@c JP
Gauche @code{program} フォームをマクロとして実装しています。それゆえ、
そのフォームを直接、評価することができます。とはいえ、@code{program}
フォームと他のフォームを一つのファイル中で混在させたり、@code{program}
フォームの返り値を期待するのは、よいことではありません。

@c EN
A typical usage of @code{program} form is to prepare a single
file which just contains @code{program} form.  (It can load
other files using @code{files} clause (see below) within the
@code{program} form.)   To execute such a program file in Gauche,
you can just load it.
@c JP
@code{program}フォームの典型的な使い方は、@code{program} フォームのみを
含む単一のファイルを用意することです。(@code{program}フォーム中で
@code{files} 節(後述)を用いて他のファイルをロードするとが可能です。)
このようなプログラムファイルを Gauche で実行するには、単にそれを
ロードするだけです。
@c COMMON
@end deftp

@deffn {Configuration Language} program program-clause program-clause2 @dots{}
[SRFI-7]
@c MOD srfi-7
@c EN
This is a configuration language to structure a Scheme program,
based on availability of the features.

A Scheme program is constructed from the @code{program} form.
Gauche evaluates the constructed Scheme program on-the-fly.

Each @var{program-clause} needs to be one of the "Program Clauses" below.
@c JP
これは Scheme プログラムを構成する設定言語で、機能の利用可能性に基づいて
います。

Scheme のプログラムは、この @code{program}フォームから構築されます。
Gauche は構築された Scheme のプログラムをそのまま実行します。

各 @var{program-clause} は以下の "Program Clause" のどれか一つである
必要があります。
@c COMMON
@end deffn

@deffn {Program Clause} requires feature-id feature-id2 @dots{}
[SRFI-7]
@c EN
The @var{feature-id}'s are the same as @code{srfi-0}'s
(@pxref{Feature conditional}).
It tells that the following code requires these @var{feature-id}'s.

If a feature-id which is not supported in Gauche is given,
an error is signaled.
@c JP
@var{feature-id} は @code{srfi-0} のものと同じです
(@pxref{Feature conditional})。
あとに続くコードが @var{feature-id} を必要とすることを教えます。

Gauche ではサポートされていない feature-id が与えられた場合には、
エラーシグナルが発生します。
@c COMMON
@end deffn

@deffn {Program Clause} files filename @dots{}
[SRFI-7]
@c EN
Inserts the content of the @var{filename}s into a program.
In Gauche, this clause just causes @var{filename}s to be loaded
into the current module.
@c JP
プログラムに @var{filename}の内容を挿入します。Gauche では
単に、現在のモジュール中への @var{filename} のロードをひきおこします。
@c COMMON
@end deffn

@deffn {Program Clause} code scheme-expression @dots{}
[SRFI-7]
@c EN
The @var{scheme-expression}s are inserted into a program.
@c JP
@var{scheme-expression} がプログラムに挿入されます。
@c COMMON
@end deffn

@deffn {Program Clause} feature-cond clause clause2 @dots{}
[SRFI-7]
@c EN
@var{Clause} is a following form:
@c JP
@var{clause} は以下のようなフォームです。
@c COMMON
@example
(@var{requirement} @var{program-clause} @var{program-clause2} @dots{})
@end example

@c EN
Where @var{requirement} should be one of the following:
@c JP
ここでは、@var{requirement} は以下のもののどれかひとつでなければなりません。
@c COMMON
@itemize @bullet
@item
@var{feature-id}
@item
@code{(and @var{requirement} @dots{})}
@item
@code{(or @var{requirement} @dots{})}
@item
@code{(not @var{requirement})}
@end itemize

@c EN
The @var{requirement} of the last @var{clause} may be @code{else}.

Gauche checks each @var{requirement} one by one, and if it finds
a fulfilled @var{requirement}, inserts the @var{program-clause}s
in that @var{clause} into the program.
@c JP
最後の @var{clause} の @var{requirement} は @code{else} になるでしょう。

Gauche はそれぞれの @var{requirement} をひとつずつチェックし、
満された @var{requirement} が見つかると、その@var{clause}中の
@var{program-clause} をプログラムに挿入します。
@c COMMON
@end deffn

@c ----------------------------------------------------------------------
@node String library, Time data types and procedures, Feature-based program configuration language, Library modules - SRFIs
@section @code{srfi-13} - String library
@c NODE 文字列ライブラリ, @code{srfi-13} - 文字列ライブラリ

@deftp {Module} srfi-13
@mdindex srfi-13
@c EN
Defines a large set of string-related functions.
In Gauche, those functions are splitted to number of files
and the form @code{(use srfi-13)} merely sets up autoloading of
those files.  So it is not likely to slow down the script startup.
@c JP
文字列に関連する関数の大きなセットを定義しています。
Gaucheでは、それらの関数はいくつかのファイルに分割されており、
@code{(use srfi-13)}というフォームは単にそれらのファイルの
オートロードのセットアップをするだけです。
したがって、スクリプトのスタートアップを遅くするようなことは
ありません。
@c COMMON
@c EN
See SRFI-13 (@uref{https://srfi.schemers.org/srfi-13/srfi-13.html})
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.
@c JP
詳細な仕様とデザインに関する議論については、SRFI-13
(@uref{https://srfi.schemers.org/srfi-13/srfi-13.html})
を参照して下さい。
このマニュアルは、関数のAPIのリファレンスとして提供されます。
いくつかのSRFI-13の関数は、Gaucheのビルトインになっており、
ここにはリストされていないものもあります。
@c COMMON
@c EN
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.
@c JP
注意: SRFI-13のドキュメントは、これらの関数を実装するモジュールの
名前を``string-lib''と``string-lib-internals''とすることを推奨しています。
Gaucheでは、一貫性のために``srfi-13''と名付けています。
@c COMMON
@end deftp

@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::
@end menu

@node SRFI-13 General conventions, SRFI-13 String predicates, String library, String library
@subsection General conventions
@c NODE 一般規約

@c EN
There are a few common factors in string library API, which I don't
repeat in each function description
@c JP
文字列ライブラリのAPIにはいくつか共通するものがありますが、
それぞれの関数の説明において繰り返しません。
@c COMMON

@table @emph
@c EN
@item argument convention
@c JP
@item 引数の仕様
@c EN
The following argument names imply their types.
@c JP
以下の引数名はその型を暗に表しています。
@c COMMON
@table @asis
@item @var{s}, @var{s1}, @var{s2}
@c EN
Those arguments must be strings.
@c JP
これらの引数は文字列でなければなりません。
@c COMMON
@item @var{char/char-set/pred}
@c EN
This argument can be a character, a character-set object,
or a predicate that takes a single character and returns a boolean value.
``Applying @var{char/char-set/pred} to a character'' means,
if @var{char/char-set/pred} is a character, it is compared to the given
character; if @var{char/char-set/pred} is a character set, it is
checked if the character set contains the given character; if
@var{char/char-set/pred} is a procedure, it is applied
to the given character.  ``A character satisfies @var{char/char-set/pred}''
means such application to the character yields true value.
@c JP
この引数は、文字、文字集合オブジェクト、あるいは1つの文字を引数に取り
真偽値を返す述語のいずれかです。``文字に@var{char/char-set/pred}を適用する''
の意味はそれぞれ、@var{char/char-set/pred}が文字ならば与えられた文字と比較される、
@var{char/char-set/pred}が文字集合ならばその文字集合に与えられた文字が
含まれるかを検査する、@var{char/char-set/pred}が述語ならばそれを与えられた
文字に適用する、となります。``ある文字が@var{char/char-set/pred}を満足する''
とは、その文字への前述のような適用が真値を返すという意味になります。
@c COMMON

@item @var{start}, @var{end}
@c EN
Lots of SRFI-13 functions takes these two optional arguments, which
limit the area of input string from @var{start}-th character
(inclusive) to @var{end}-th character (exclusive),
where the operation is performed.
When specified, the condition
0 <= @var{start} <= @var{end} <= @var{length of the string} must be
satisfied.  Default value of @var{start} and @var{end} is
0 and the length of the string, respectively.
@c JP
SRFI-13の関数の多くは、その操作が実行される対象入力文字列の
範囲を限定する開始インデックスと終了インデックスをオプショナルな
引数として取ります。開始(@var{start}番目)の文字は含まれ、
終了(@var{end}番目)の文字は含まれません。
これらが指定されるとき、0 <= @var{start} <= @var{end} <= @var{length of the string}が
満たされなければなりません。@var{start}と@var{end}のデフォルト値は、
それぞれ0と文字列の長さです。
@c COMMON
@end table

@c EN
@item @code{shared} variant
@c JP
@item @code{shared}バージョン
@c EN
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 @emph{internally} shares
the storage of strings, so generally you don't need to worry
about the overhead of copying substrings.
@c JP
いくつかの関数は、その名前に``/shared''が付きます。
SRFI-13では、それらの関数はより良いパフォーマンスのために
入力文字列の一部を共有しても良いと定義しています。
Gaucheは、共有文字列という概念を持っていませんし、
それらの関数は単に共有でないバージョンの変名に過ぎません。
しかし、Gaucheは@emph{内部的には}文字列の保存場所を共有しているので、
一般的には部分文字列をコピーするオーバヘッドについて心配する
必要はありません。
@c COMMON

@c EN
@item @code{right} variant
@c JP
@item @code{right}バージョン
@c EN
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.
@c JP
ほとんどの関数は、入力文字列を左から右へと扱います。
いくつかの関数は、その名前に``-right''が付き、右から左へと
扱うものがあります。
@c COMMON

@end table

@node SRFI-13 String predicates, SRFI-13 String constructors, SRFI-13 General conventions, String library
@subsection String predicates
@c NODE 文字列についての述語

@defun string-null? s
[SRFI-13]
@c MOD srfi-13
@c EN
Returns @code{#t} if @var{s} is an empty string, @code{""}.
@c JP
@var{s}が空文字列、@code{""}なら、@code{#t}を返します。
@c COMMON
@end defun

@defun string-every char/char-set/pred s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Sees if every character in @var{s} satisfies
@var{char/char-set/pred}.  If so, @code{string-every} returns
the value that is returned at the last application of @var{char/char-set/pred}.
If any of the application returns @code{#f}, @code{string-every}
returns @code{#f} immediately.
@c JP
@var{s}に含まれる全ての文字が@var{char/char-set/pred}を
満足するかを検査します。満足するならば、@code{string-every}は
最後に適用された@var{char/char-set/pred}が返した値を戻り値とします。
どの適用も@code{#f}を返した場合は、@code{string-every}はすぐに
@code{#f}を返します。
@c COMMON
@end defun

@defun string-any char/char-set/pred s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Sees if any character in @var{s} satisfies
@var{char/char-set/pred}.  If so, @code{string-any} returns
the value that is returned by the application.   If no character
satisfies @var{char/char-set/pred}, @code{#f} is returned.
@c JP
@var{s}に含まれるいずれかの文字が@var{char/char-set/pred}
を満足するかを検査します。いずれかの文字が満足するならば、
@code{string-any}はその適用が返した値を戻り値とします。
どの文字も@var{char/char-set/pred}を満たさなければ、@code{#f}が返ります。
@c COMMON
@end defun

@node SRFI-13 String constructors, SRFI-13 String selection, SRFI-13 String predicates, String library
@subsection String constructors
@c NODE 文字列の構築子

@defun string-tabulate proc len
[SRFI-13]
@c MOD srfi-13
@c EN
@var{proc} must be a procedure that takes an integer
argument and returns a character.  @code{string-tabulate}
creates a string, whose @var{i}-th character is calculated by
@code{(proc i)}.
@c JP
@var{proc}は整数を1つ引数として取り文字を返す手続きで
なければなりません。@code{string-tabulate}は、その@var{i}番目の
文字が@code{(proc i)}で計算されるような文字列を返します。
@c COMMON
@example
(string-tabulate
  (lambda (i) (integer->char (+ i #x30))) 10)
 @result{} "0123456789"
@end example
@end defun

@defun string-unfold p f g seed :optional base make-final
[SRFI-13]
@c MOD srfi-13
@c EN
A fundamental string builder.  The @var{p}, @var{f} and @var{g} are
procedures, taking the current seed value.  The stop predicate @var{p}
determines when to stop: If it returns a true value, string building
stops.  The mapping function @var{f} returns a character
from the current seed value.  The next seed function @var{g} returns
a next seed value from the current seed value.  The @var{seed} argument
gives the initial seed value.
@c JP
基本的な文字列構築手続きです。
@var{p}、@var{f}、@var{g}は手続きで、現在のシード値を受けとります。
停止述語@var{p}はいつ繰り返しを止めるかを判断します。それが真の値を返したら、
文字列構築は終了し、それまでに生成された文字が集められて文字列として返されます。
@var{f}はシード値から文字を生成する手続きです。@var{g}はシード値から次のシード値を
生成します。@var{seed}引数はシード値の初期値を指定します。
@c COMMON

@example
(string-unfold (^n (= n 10))
               (^n (integer->char (+ n 48)))
               (^n (+ n 1))
               0)
  @result{} "0123456789"
@end example

@c EN
The optional argument @var{base} is, when given, prepended to the
result string.  Another optional argument @var{make-final}
is a procedure that takes the last return value of @var{g} and
returns a string that becomes the suffix of the result string.
@c JP
省略可能引数@var{base}は、与えられれば生成される文字列のプレフィクスとなります。
@var{make-final}は手続きで、繰り返しが終了した後の最後のシード値を受け取り、
文字列のサフィックスを返します。
@c COMMON

@example
(string-unfold (^n (= n 10))
               (^n (integer->char (+ n 48)))
               (^n (+ n 1))
               0 "foo" x->string)
  @result{} "foo012345678910"
@end example
@end defun

@defun string-unfold-right p f g seed :optional base make-final
[SRFI-13]
@c MOD srfi-13
@c EN
Another fundamental string builder.  The meanings of arguments
are the same as @code{string-unfold}.  The only difference is
that the string is build right-to-left.  The optional @var{base},
if given, becomes the suffix of result, and the result of
@var{make-final} becomes the prefix.
@c JP
もうひとつの基本的な文字列構築器です。引数の意味は@code{string-unfold}と
同じですが、@var{f}の返す文字が右から左へと並べられます。
また、章句可能な@var{base}引数はサフィックスに、
@var{make-final}が返す文字列はプレフィクスになります。
@c COMMON

@example
(string-unfold-right (^n (= n 10))
                     (^n (integer->char (+ n 48)))
                     (^n (+ n 1))
                     0 "foo" x->string)
  @result{} "109876543210foo"
@end example
@end defun


@defun reverse-list->string char-list
[SRFI-13]
@c MOD srfi-13
@equiv{} @code{(list->string (reverse char-list))}.
@end defun

@node SRFI-13 String selection, SRFI-13 String comparison, SRFI-13 String constructors, String library
@subsection String selection
@c NODE 文字列の選択

@defun substring/shared s start :optional end
[SRFI-13]
@c MOD srfi-13
@c EN
In Gauche, this is the same as @code{substring}, except
that the @var{end} argument is optional.
@c JP
Gaucheでは、引数@var{end}がオプショナルであることを除いて、
@code{substring}と同じです。
@c COMMON
@example
(substring/shared "abcde" 2) @result{} "cde"
@end example
@end defun

@defun string-copy! target tstart s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Copies a string @var{s} into a string
@var{target} from the position @var{tstart}.
The @var{target} string must be mutable.
Optional @var{start} and @var{end} arguments limits the range of @var{s}.
If the copied string run over the end of @var{target}, an error is
signaled.
@c JP
文字列@var{s}を、文字列@var{target}の@var{tstart}番目以降へコピーします。
@var{target}文字列は変更可能でなければなりません。
オプションの引数@var{start}と@var{end}は、@var{s}の範囲を制限します。
コピーされた文字列が@var{target}の終端を越えたらエラーが通知されます。
@c COMMON
@example
(define s (string-copy "abcde"))
(string-copy! s 2 "ZZ")
s @result{} "abZZe"
@end example

@c EN
It is ok to pass the same string to @var{target} and @var{s}; this
always work even if the regions of source and destination are overlapping.
@c JP
@var{target}と@var{s}に同じ文字列を渡しても構いません。コピー元とコピー先の
領域が重なっていても、コピーは常に正しく行われます。
@c COMMON

@c EN
Note that Gauche encourages you to treat strings as immutable objects.
Internally, a string is an indirect pointer to a immutable entity, and 
mutating a string means copying the original entity and creating a new one.
It doesn't ``save allocations''.
Always use the functional version @code{string-copy} unless you
absolutely need to replace a string in-place.
@xref{String utilities}.
@c JP
Gaucheでは、文字列を変更不可なオブジェクトとして扱うことを強く推奨しています。
内部的に、文字列オブジェクトは変更不可な文字列の実体へのポインタとなっています。
文字列を変更すると、新たな文字列実体がアロケートされそれが変更されるので、
破壊的手続きを使えばメモリアロケーションが節約できるということはありません。
どうしても文字列そのものを破壊的変更したい場合でない限りは、
非破壊版の@code{string-copy}を使いましょう。@ref{String utilities}参照。
@c COMMON
@end defun

@defun string-take s nchars
@defunx string-drop s nchars
@defunx string-take-right s nchars
@defunx string-drop-right s nchars
[SRFI-13]
@c MOD srfi-13
@c EN
Returns the first @var{nchars}-character string of @var{s}
(@code{string-take}) or the string without first @var{nchars}
(@code{string-drop}).  The @code{*-right} variation counts from
the end of string.  It is guaranteed that the returned string is
always a copy of @var{s}, even no character is dropped.
@c JP
@code{string-take}は、@var{s}の最初の@var{nchars}文字からなる文字列を返します。
@code{string-drop}は、@var{s}から最初の@var{nchars}文字からなる文字列を
除いた残りを返します。@code{*-right}バージョンは、文字列の最後から数えます。
返される文字列はいつも@var{s}のコピーであり、どの文字も削除されないことが
保証されています。
@c COMMON
@example
(string-take "abcde" 2) @result{} "ab"
(string-drop "abcde" 2) @result{} "cde"

(string-take-right "abcde" 2) @result{} "de"
(string-drop-right "abcde" 2) @result{} "abc"
@end example
@end defun

@defun string-pad s len :optional char start end
@defunx string-pad-right s len :optional char start end
[SRFI-13]
@c MOD srfi-13
@c EN
If a string @var{s} is shorter than @var{len},
returns a string of @var{len} where @var{char} is
padded to the left or right, respectively.
If @var{s} is longer than @var{len}, the rightmost
or leftmost @var{len} chars are taken.
@var{Char} defaults to @code{#\space}.
If @var{start} and @var{end} are provided,
the substring of @var{s} is used as the source.
@c JP
文字列@var{s}が@var{len}より短い場合は、@var{char}がそれぞれ左か
右にパディングされた長さ@var{len}の文字列を返します。
@var{s}が@var{len}よりも長い場合は、@var{len}文字が右端か左端から
取り除かれます。@var{Char}のデフォルト値は@code{#\space}です。
@var{start}と@var{end}が与えられると、@var{s}の部分文字列がソース
文字列として使われます。
@c COMMON

@example
(string-pad "abc" 10)    @result{} "       abc"
(string-pad "abcdefg" 3) @result{} "efg"

(string-pad-right "abc" 10) @result{} "abc       "

(string-pad "abcdefg" 10 #\+ 2 5)
  @result{} "+++++++cde"
@end example
@end defun

@defun string-trim s :optional char/char-set/pred start end
@defunx string-trim-right s :optional char/char-set/pred start end
@defunx string-trim-both s :optional char/char-set/pred start end
[SRFI-13]
@c MOD srfi-13
@c EN
Removes characters that match @var{char/char-set/pred}
from @var{s}.  @code{String-trim} removes the characters from
left of @var{s}, @code{string-trim-right} does from right,
and @code{string-trim-both} does from both sides.
@c JP
@var{s}から@var{char/char-set/pred}にマッチする文字を削除します。
@code{String-trim}は@var{s}の左から文字を削除し、
@code{string-trim-right}は右から、@code{string-trim-both}は
両端から削除します。
@c COMMON
@c EN
@var{Char/char-set/pred} defaults to @code{#[\s]}, i.e. a char-set
of whitespaces.
If @var{start} and @var{end} are provided,
the substring of @var{s} is used as the source.
@c JP
@var{Char/char-set/pred}のデフォルト値は@code{#[\s]}、つまり空白文字の
文字集合です。@var{start}と@var{end}が与えられると、@var{s}の部分文字列が
ソース文字列として使われます。
@c COMMON

@example
(string-trim "   abc  ")       @result{} "abc  "
(string-trim-right "   abc  ") @result{} "   abc"
(string-trim-both "   abc  ")  @result{} "abc"
@end example
@end defun

@node SRFI-13 String comparison, SRFI-13 String prefixes & suffixes, SRFI-13 String selection, String library
@subsection String comparison
@c NODE 文字列の色々な比較

@defun string-compare s1 s2 proc< proc= proc> :optional start1 end1 start2 end2
@defunx string-compare-ci s1 s2 proc< proc= proc> :optional start1 end1 start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Compares two strings @var{s1} and @var{s2} codepoint-wise from left.
When mismatch is found at the index @var{k} of @var{s1},
calls @var{proc<} with @var{k} if @var{s1}'s codepoint is smaller than
the corresponding @var{s2}'s, or calls @var{proc>} if @var{s1}'s one is
greater than @var{s2}'s.  If two strings are the same, calls @var{proc=}
with the index of the last compared position in @var{s1}.
@c JP
文字列@var{s1}と@var{s2}をコードポイント毎に左から比較します。
不一致が@var{s1}のインデックス@var{k}で見つかった場合、対応する@var{s2}の
コードポイントより@var{s1}のコードポイントの方が小さければ
@var{proc<}を@var{k}を引数にして呼び出し、逆に大きければ
@var{proc>}を@var{k}を引数にして呼び出します。
二つの文字列が等しければ、@var{proc=}が、@var{s1}の比較された最後のインデックスを
引数にして呼び出されます。
@c COMMON

@example
(string-compare "abcd" "abzd"
                (^i `(< ,i)) (^i `(= ,i)) (^i `(> ,i)))
  @result{} (< 2)

(string-compare "abcd" "abcd"
                (^i `(< ,i)) (^i `(= ,i)) (^i `(> ,i)))
  @result{} (= 3)
@end example

@c EN
The optional arguments restricts
the range of the input strings; however, the index passed to one 
of the procedures is always an index from the beginning of @var{s1}.
@c JP
省略可能引数は入力の文字列の比較すべき範囲を制限します。
但し、@var{proc<}、@var{proc=}、@var{proc>}に渡されるインデックスは
常に@var{s1}の最初から数えたものになります。
@c COMMON

@example
(string-compare "zzabcdyy" "abcz"
   (^i `(< ,i)) (^i `(= ,i)) (^i `(> ,i)) 2 6 0 4)
 @result{} (< 5)

(string-compare "zzabcdyy" "abcz"
   (^i `(< ,i)) (^i `(= ,i)) (^i `(> ,i)) 2 5 0 3)

 @result{} (= 4)
@end example

@c EN
The case-insensitive variant, @code{string-compare-ci}, compares
each codepoint with character-wise case-folding.  It won't consider
special case folding such as German eszett.
@c JP
@code{string-compare-ci}は大文字小文字を区別しない比較です。
文字毎の大文字小文字変換を行って比較するので、文字列の長さが変わる
大文字小文字変換のケース (ドイツ語のエスツェット等) は考慮されません。
@c COMMON
@end defun

@defun string= s1 s2 :optional start1 end1 start2 end2
@defunx string<> s1 s2 :optional start1 end1 start2 end2
@defunx string< s1 s2 :optional start1 end1 start2 end2
@defunx string<= s1 s2 :optional start1 end1 start2 end2
@defunx string> s1 s2 :optional start1 end1 start2 end2
@defunx string>= s1 s2 :optional start1 end1 start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Compare two strings @var{s1} and @var{s2}.  Optional arguments
can limit the portion of strings to be compared.
Comparison is done by character-wise.

Note: The builtin procedures @code{string=?} etc. can also be
used for character-wise string comparison, but they take
arguments differently.  @xref{String comparison}.
@c JP
二つの文字列@var{s1}と@var{s2}を比較します。省略可能引数で
それぞれの文字列の一部のみを比較するように指定できます。
比較は文字ごとに行われます。

註: 組み込み手続きの@code{string=?}等も文字毎の比較に使えますが、
引数の取り方が違います。@ref{String comparison}参照。
@c COMMON
@end defun

@defun string-ci= s1 s2 :optional start1 end1 start2 end2
@defunx string-ci<> s1 s2 :optional start1 end1 start2 end2
@defunx string-ci< s1 s2 :optional start1 end1 start2 end2
@defunx string-ci<= s1 s2 :optional start1 end1 start2 end2
@defunx string-ci> s1 s2 :optional start1 end1 start2 end2
@defunx string-ci>= s1 s2 :optional start1 end1 start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Compare two strings @var{s1} and @var{s2} in case-insensitive way.
Optional arguments can limit the portion of strings to be compared.
Case folding and comparison is done by character-wise, so they don't
consider case folding that affects multiple characters.

Note: We have two other sets of string comparison operations,
both are named as @code{string-ci=?} etc.
The builtin version (@pxref{String comparison}) does character-wise
comparison.  The one in @code{gauche.unicode} uses full-string
case conversion (@pxref{Full string case conversion}).
R7RS version is the latter.
@c JP
二つの文字列@var{s1}と@var{s2}を、大文字小文字を区別せずに比較します。
省略可能引数でそれぞれの文字列の一部のみを比較するように指定できます。
大文字小文字の畳み込みと比較は文字ごとに行われます。複数の文字に
影響を与えるような大文字小文字の畳み込みは考慮しません。

註: Gaucheには他に2種類の大文字小文字を区別しない文字列比較手続き群があります。
どちらも@code{string-ci=?}等のようにクエスチョンマーク付きの名前を持っています。
Gauche組み込みのものは文字毎に大文字小文字を畳み込みます
(@ref{String comparison}参照)。一方、@code{gauche.unicode}にあるものは
文字列としての畳み込みを行います(@ref{Full string case conversion}参照)。
R7RS版は後者です。
@c COMMON
@end defun

@defun string-hash s :optional bound start end
@defunx string-hash-ci s :optional bound start end
[SRFI-13]
@c MOD srfi-13
@c EN
(Note: Gauche has builtin @code{string-hash} and @code{string-ci-hash}
according to SRFI-128. @xref{Hashing}, for the details.
SRFI-13's API is upper-compatible to SRFI-128's.  The underlying
hash algorithm is the same as the builtin ones, so @code{string-hash}
returns the same value as the builtin ones for the same string
if optional arguments are omitted.
On the other hand, the builtin @code{string-ci-hash} uses string case
folding (e.g. German eszett and @code{SS} are the same), while
SRFI-13's @code{string-hash-ci} uses character-wise case folding.
Unless there's a strong reason, we recommend new code should use
builtin SRFI-128 version instead of SRFI-13.)

Calculates hash value of a string @var{s}.  For @code{string-hash-ci},
character-wise case folding is done before calculating the hash value.

If the optional @var{bound} argument is given, it must be a positive
exact integer, and the return value is limited below it.
The optional @var{start} and @var{end} arguments allows
using that portion for calculation.
@c JP
(註: Gaucheは、SRFI-128に準拠した@code{string-hash}と@code{string-ci-hash}を
組み込みで持っています。詳しくは@ref{Hashing}参照。
SRFI-13のAPIはSRFI-128の上位互換になっています。内部で使っているハッシュ
アルゴリズムは一緒なので、省略可能引数を全て省略したSRFI-13の@code{string-hash}は、
組み込みの@code{string-hash}と同じ値を返します。
一方、組み込みの@code{string-ci-hash}は文字列として大文字小文字の畳み込みを
行います(ドイツ語のエスツェットと@code{SS}は等しく扱われます)が、SRFI-13の
@code{string-hash-ci}は文字毎に大文字小文字を畳み込むように定められているので、
結果が異なる可能性があります。特に強い理由がなければ、新しいコードは
組み込みのSRFI-128版を使うことをおすすめします。)

文字列@var{s}のハッシュ値を計算して返します。@code{string-hash-ci}では
ハッシュ値を計算する前に各文字について大文字小文字を畳み込みを行います。

省略可能引数@var{bound}は、与えられたなら正の正確な整数でなければならず、
返される値は0から@code{(- bound 1)}までの値に制限されます。
@var{start}と@var{end}は、与えられれば@var{s}中の対象となる部分文字列を
指定します。
@c COMMON
@end defun

@node SRFI-13 String prefixes & suffixes, SRFI-13 String searching, SRFI-13 String comparison, String library
@subsection String prefixes & suffixes
@c NODE 文字列のプリフィックスとサフィックス

@defun string-prefix-length s1 s2 :optional start1 end1 start2 end2
@defunx string-suffix-length s1 s2 :optional start1 end1 start2 end2
@defunx string-prefix-length-ci s1 s2 :optional start1 end1 start2 end2
@defunx string-suffix-length-ci s1 s2 :optional start1 end1 start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Returns the length of the longest common prefix/suffix of two strings,
@var{s1} and @var{s2}.  The optional arguments restrict the range of
search.  The @code{*-ci} variations use case folding character comparison.
@c JP
二つの文字列@var{s1}と@var{s2}の、共通するプレフィクスもしくはサフィックスの
長さを返します。省略可能引数はそれぞれの文字列の探索範囲を限定します。
@code{*-ci}版は文字ごとに、大文字小文字を区別しない比較を行います。
@c COMMON

@example
(string-prefix-length "abacus" "abalone")   @result{} 3
(string-prefix-length "machine" "umbrella") @result{} 0
(string-suffix-length "peeking" "poking")   @result{} 4

(string-prefix-length "obvious" "oblivious" 2 7 4 9)
  @result{} 5
@end example
@end defun

@defun string-prefix? s1 s2 :optional start1 end1 start2 end2
@defunx string-suffix? s1 s2 :optional start1 end1 start2 end2
@defunx string-prefix-ci? s1 s2 :optional start1 end1 start2 end2
@defunx string-suffix-ci? s1 s2 :optional start1 end1 start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Returns true iff @var{s1} is a prefix or suffix of @var{s2}, respectively.
The optional arguments limit the range of @var{s1} and @var{s2} to look at.
The @code{*-ci} variations use case folding character comparison.
@c JP
それぞれ、@var{s1}が@var{s2}のプレフィクスまたはサフィックスになっていた場合に
@code{#t}を、それ以外の場合に@code{#f}を返します。
省略可能引数はそれぞれの文字列の探索範囲を限定します。
@code{*-ci}版は文字ごとに、大文字小文字を区別しない比較を行います。
@c COMMON

@example
(string-prefix? "sch" "scheme")   @result{} #t
(string-prefix? "lisp" "scheme")  @result{} #f

(string-suffix? "eme" "scheme")   @result{} #t
(string-suffix? "eme" "lisp")     @result{} #f

(string-prefix? "mit-scheme" "scheme-family" 4) @result{} #t
@end example
@end defun

@node SRFI-13 String searching, SRFI-13 String case mapping, SRFI-13 String prefixes & suffixes, String library
@subsection String searching
@c NODE 文字列の探索

@defun string-index s char/char-set/pred :optional start end
@defunx string-index-right s char/char-set/pred :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Looks for the first element in a string @var{s}
that matches @var{char/char-set/pred}, and returns its index.
If @var{char/char-set/pred} is not found in @var{s}, returns @code{#f}.
Optional @var{start} and @var{end} limit the range of @var{s} to search.
@c JP
文字列@var{s}の中で、@var{char/char-set/pred}にマッチする
最初の要素を探し、そのインデックスを返します。
@var{s}の中に@var{char/char-set/pred}が見つからない場合は、@code{#f}を
返します。オプションの@var{start}と@var{end}は、@var{s}の中で検索対象と
なる範囲を制限します。
@c COMMON
@example
(string-index "Aloha oe" #\a) @result{} 4
(string-index "Aloha oe" #[Aa]) @result{} 0
(string-index "Aloha oe" #[\s]) @result{} 5
(string-index "Aloha oe" char-lower-case?) @result{} 1
(string-index "Aloha oe" #\o 3) @result{} 6
@end example

@c EN
See also the Gauche built-in procedure @code{string-scan}
(@ref{String utilities}), if you need speed over portability.
@c JP
ポータビリティよりも速度を重視する場合は、Gaucheのビルトイン手続き
@code{string-scan}(@ref{String utilities})を参照して下さい。
@c COMMON
@end defun

@defun string-skip s char/char-set/pred :optional start end
@defunx string-skip-right s char/char-set/pred :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Looks for the first element that does not match
@var{char/char-set/pred} and returns its index.
If such element is not found, returns @code{#f}.
Optional @var{start} and @var{end} limit the range of @var{s} to search.
@c JP
@var{char/char-set/pred}にマッチしない最初の要素を探し、
そのインデックスを返します。そのような要素が見つからない場合、@code{#f}を
返します。オプションの@var{start}と@var{end}は、@var{s}の中で検索対象と
なる範囲を制限します。
@c COMMON
@end defun

@defun string-count s char/char-set/pred :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Counts the number of elements in @var{s}
that matches @var{char/char-set/pred}.
Optional @var{start} and @var{end} limit the range of @var{s} to search.
@c JP
@var{s}の中で、@var{char/char-set/pred}にマッチする要素の数を
カウントします。オプションの@var{start}と@var{end}は、@var{s}の中で検索対象と
なる範囲を制限します。
@c COMMON
@end defun

@defun string-contains s1 s2 :optional start1 end1 start2 end2
@defunx string-contains-ci s1 s2 :optional start1 end1 start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Looks for a string @var{s2} inside another string @var{s1}.
If found, returns an index in @var{s1} from where the matching string
begins.  Returns @code{#f} otherwise.
Optional @var{start1}, @var{end1}, @var{start2} and @var{end2}
limits the range of @var{s1} and @var{s2}.

See also the Gauche built-in procedure @code{string-scan}
(@ref{String utilities}), if you need speed over portability.
@c JP
@var{s1}の中で、文字列@var{s2}を探します。見つかった場合は、
@var{s1}でマッチした文字列が始まるインデックスを返します。そうでなければ、
@code{#f}を返します。
オプションの@var{start1}、@var{end1}、@var{start2}、@var{end2}は、
@var{s1}と@var{s2}の範囲を制限します。

ポータビリティよりも速度を重視する場合は、Gaucheのビルトイン手続き
@code{string-scan}(@ref{String utilities})を参照して下さい。
@c COMMON
@end defun

@node SRFI-13 String case mapping, SRFI-13 String reverse & append, SRFI-13 String searching, String library
@subsection String case mapping
@c NODE 文字列のケース(大文字小文字)マッピング

@defun string-titlecase s :optional start end
@defunx string-titlecase! s :optional start end
@defunx string-upcase s :optional start end
@defunx string-upcase! s :optional start end
@defunx string-downcase s :optional start end
@defunx string-downcase! s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Converts a string @var{s} to titlecase, upcase or downcase,
respectively.  These operations uses character-by-character
mapping provided by @code{char-upcase} etc.  That is, @code{string-upcase}
and @code{string-downcase} can be understood as follow:
@c JP
文字列@var{s}をタイトルケース、大文字、小文字にそれぞれ変換します。
これらの手続きは、文字ごとに@code{char-upcase}等を使った変換を行います。
すなわち、@code{string-upcase}と@code{string-downcase}は以下の操作と
考えることができます。
@c COMMON

@example
(string-upcase s)
  @equiv{} (string-map char-upcase s)
(string-downcase s)
  @equiv{} (string-map char-downcase s)
@end example

@c EN
If you need full case mapping that handles the case when
a character is mapped to more than one characters, use
the procedures with the same name in @code{gauche.unicode} module
(@pxref{Full string case conversion}).
@c JP
一文字がケース変換によって複数文字になるような場合も考慮したい場合は、
@code{gauche.unicode}モジュールに定義されている同名の手続きを使ってください
(@ref{Full string case conversion}参照)。
@c COMMON

@c EN
The linear-update version @code{string-titlecase!}, @code{string-upcase!}
and @code{string-downcase!} destroys @var{s} to store the result.
Note that in Gauche, using those procedures doesn't save anything,
since string mutation is expensive by design.  They are provided merely
for completeness.
@c JP
@code{string-titlecase!}、@code{string-upcase!}、
@code{string-downcase!}はその場で更新するバージョンで、@var{s}を破壊的に
変更します。ただし、Gaucheでは文字列の変更は新たな文字列を作るのと効率的に
何ら変わりがありません。これらの手続きは互換性のためだけに用意されています。
@c COMMON
@end defun


@node SRFI-13 String reverse & append, SRFI-13 String mapping, SRFI-13 String case mapping, String library
@subsection String reverse & append
@c NODE 文字列の反転と追加

@defun string-reverse s :optional start end
@defunx string-reverse! s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Returns a string in which the character positions are reversed
from @var{s}.  @code{string-reverse!} modifies @var{s}.
@c JP
@var{s}の文字の位置を逆順にした文字列を返します。
@code{string-reverse!}は@var{s}そのものを変更します。
@c COMMON
@example
(string-reverse "mahalo") @result{} "olaham"
(string-reverse "mahalo" 3) @result{} "ola"
(string-reverse "mahalo" 1 4) @result{} "aha"

(let ((s (string-copy "mahalo")))
  (string-reverse! s 1 5)
  s)
  @result{} "mlahao"
@end example
@end defun

@defun string-concatenate string-list
[SRFI-13]
@c MOD srfi-13
@c EN
Concatenates list of strings.
@c JP
文字列のリストを連結します。
@c COMMON
@example
(string-concatenate '("humuhumu" "nukunuku" "apua" "`a"))
  @result{} "humuhumunukunukuapua`a"
@end example
@end defun

@defun string-concatenate/shared string-list
@defunx string-append/shared s @dots{}
[SRFI-13]
@c MOD srfi-13
@c EN
``Shared'' version of @code{string-concatenate} and
@code{string-append}.  In Gauche, these are just synonyms of them.
@c JP
@code{string-concatenate}と@code{string-append}の``共有''
バージョンです。Gaucheでは、これらは単に別名です。
@c COMMON
@end defun

@defun string-concatenate-reverse string-list
@defunx string-concatenate-reverse/shared string-list
[SRFI-13]
@c MOD srfi-13
@c EN
Reverses @var{string-list} before concatenation.
``Shared'' version works the same in Gauche.
@c JP
@var{string-list}を連結する前に逆順にします。
Gaucheでは、``共有''バージョンは全く同じ動作をします。
@c COMMON
@end defun

@node SRFI-13 String mapping, SRFI-13 String rotation, SRFI-13 String reverse & append, String library
@subsection String mapping
@c NODE 文字列のマッピング

@defun string-map! proc s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
@code{string-map!} applies @var{proc} on every character of @var{s},
and stores the results into @var{s}.  It is an error if @var{proc} returns
non-character.
@c JP
@code{string-map!}は、@var{s}の全ての文字に対して@var{proc}を
適用し、その結果を@var{s}に格納します。
@var{proc}は文字を返さねばなりません。
@c COMMON
@example
(let ((s (string-copy "wikiwiki")))
  (string-map! char-upcase s 4)
  s)
  @result{} "wikiWIKI"
@end example
@end defun

@defun string-fold kons knil s :optional start end
@defunx string-fold-right kons knil s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Like @var{fold} and @var{fold-right} (@pxref{Walking over lists}),
but works on a string instead of a list.
@c JP
文字列に対して動作する@var{fold}や@var{fold-right} (@ref{Walking over lists}参照)
です。
@c COMMON

@example
(string-fold cons '() "abcde")
  @result{} (#\e #\d #\c #\b #\a)
(string-fold-right cons '() "abcde")
  @result{} (#\a #\b #\c #\d #\e)
@end example
@end defun

@defun string-for-each-index proc s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Call @var{proc} on each index of the string @var{s}, from left to right.
The result of @var{proc} is discarded.
The optional @var{start} and @var{end} arguments can be an integer
index or a string cursor, restricting the range
of the input string to be traversed.
@c JP
@var{proc}を@var{s}の各文字について、左から右の順に呼びます。@var{proc}の結果は
捨てられます。
省略可能な@var{start}と@var{end}引数は整数の文字インデックスか
文字列カーソルで、対象となる文字列の範囲を制限します。
@c COMMON
@end defun

@node SRFI-13 String rotation, SRFI-13 Other string operations, SRFI-13 String mapping, String library
@subsection String rotation
@c NODE 文字列のローテーション

@defun xsubstring s from :optional to start end
[SRFI-13]
@c MOD srfi-13
@c EN
Takes a substring of infinite repetition of string @var{s}
between index @var{from} (inclusive) and index @var{to} (exclusive).
If @var{to} is omitted, the length of @var{s} is assumed.
@c JP
@var{s}が左右に無限に繰り替えされているとみなし、その整数インデックス
の@var{from}から@var{to}までを切り出して返します。
@var{to}が省略された場合は@var{s}の長さが使われます。
@c COMMON

@c EN
For example, if @var{s} is @code{"abcde"}, we repeat it
infinitely to both sides.  So @var{5n}-th character for integer @var{n}
is always @code{#\a}, which extends negative @var{n} as well.
@c JP
例えば、@var{s}が@code{abcde}の場合、まずそれを無限の
文字列@code{...abcdeabcdeabcde...}とみなします。
つまり整数@var{n}に対して@var{5n}番目の文字は常に@code{#\a}です。
これは@var{n}が負の領域にも拡張されます。
@c COMMON

@example
(xsubstring "abcde" 2 10)
  @result{} "cdeabcde"
(xsubstring "abcde" -9 -2)
  @result{} "bcdeabc"
@end example

@c EN
The optional @var{start} and @var{end} arguments can be an integer
index or a string cursor, it works as
@code{(xsubstring (substring s start end) from to)}.
@c JP
省略可能な@var{start}と@var{end}引数は整数の文字インデックスか
文字列カーソルで、与えられた場合、
@code{(xsubstring (substring s start end) from to)}と同じ動作となります。
@c COMMON
@end defun

@defun string-xcopy! target tstart s sfrom :optional sto start end
[SRFI-13]
@c MOD srfi-13
@c EN
It works as 
@code{(string-copy! target tstart (xsubstring s sfrom sto start end))}.
@c JP
@code{(string-copy! target tstart (xsubstring s sfrom sto start end))}
と同じ動作をします。
@c COMMON
@end defun

@node SRFI-13 Other string operations, SRFI-13 String filtering, SRFI-13 String rotation, String library
@subsection Other string operations
@c NODE 他の文字列操作

@defun string-replace s1 s2 start1 end1 :optional start2 end2
[SRFI-13]
@c MOD srfi-13
@c EN
Returns a new string whose content is a copy of a string @var{s1}, except
the part beginning from the index
@var{start1} (inclusive) and ending at the index @var{end1} (exclusive)
are replaced by a string @var{s2}.   When optional @var{start2} and @var{end2}
arguments are given, @var{s2} is trimmed first according to them.
The size of the @emph{gap}, @code{(- @var{end1} @var{start1})}, doesn't
need to be the same as the size of the inserted string.
Effectively, this is the same as the following code.
@c JP
文字列@var{s1}の@var{start1}文字目(inclusive)から@var{end1}文字目(exclusive)
までを文字列@var{s2}に置き換えた文字列を新たに作って返します。@var{s1}, @var{s2}は
変更されません。
オプショナルな引数@var{start2}、@var{end2}が与えられた場合は、
@var{s2}がまずそれらによって切り取られて置換文字列として使われます。
置き換える隙間の大きさ、つまり@code{(- @var{end1} @var{start1})}は
@var{s2}と同じ長さである必要はありません。
実質的に、この手続きは次のコードと等価です。
@c COMMON

@example
(string-append (substring s1 0 start1)
               (substring s2 start2 end2)
               (substring s1 end1 (string-length s1)))
@end example
@end defun

@defun string-tokenize s :optional token-set start end
[SRFI-13]
@c MOD srfi-13
@c EN
Splits the string @var{s} into a list of substrings,
where each substring is a maximal non-empty contiguous
sequence of characters from the character set @var{token-set}.
The default of @var{token-set} is @code{char-set:graphic}
(@pxref{Predefined character sets}).

See also Gauche's built-in @code{string-split} (@pxref{String utilities}),
which provides similar features but different criteria.
@c JP
文字列 @var{s} を、@var{token-set} で指定される文字集合で
構成される、空でない最大限連続した文字のシーケンスのそれぞれを
要素とするリストを返します。
@var{token-set} のデフォルト値は @code{char-set:graphic}
(@ref{Predefined character sets}参照)。

同様の機能を提供する、しかし異なる基準を持つ、Gauche の組み込み手続き
@code{string-split} (@ref{String utilities} 参照) も見て下さい。
@c COMMON
@end defun

@node SRFI-13 String filtering, SRFI-13 Low-level string procedures, SRFI-13 Other string operations, String library
@subsection String filtering
@c NODE 文字列のフィルタリング

@defun string-filter char/char-set/pred s :optional start end
@defunx string-delete char/char-set/pred s :optional start end
[SRFI-13]
@c MOD srfi-13
@c EN
Returns a string consists of characters in a string @var{s} 
that passes (or don't pass) the test indicated by @var{char/char-set/pred},
respectively.  
@c JP
それぞれ、文字列@var{s}中の文字のうち@var{char/char-set/pred}で示される
テストを通る、または通らない文字からなる文字列を返します。
@c COMMON

@example
(string-filter char-upper-case? "Hello, World!")
  @result{} "HW"

(string-delete char-upper-case? "Hello, World!")
  @result{} "ello, orld!"

(string-delete #\l "Hello, World!")
  @result{} "Heo, Word!"

(string-filter #[\w] "Hello, World!")
  @result{} "HelloWorld"
@end example

@c EN
Note: Srfi-13 was revised after finalization to switch
the order of arguments @var{char/char-set/pred} and @var{s} was.
At the time of finalization, the order was
@code{(string-filter s pred)} and Gauche implemented it accordingly.
However, most existing implementations follows the revised order,
since that was what the srfi-13 reference implementation had.

So, from 0.9.4, we revised the API to comply the current
srfi-13 spec, but we also accept the old order as well
not to break the old code.
We recommend the new code to use the new order.
@c JP
註: srfi-13は制定後に改訂され、引数@var{char/char-set/pred}と@var{s}の
順序が逆になりました。制定時点では引数順は
@code{(string-filter s pred)}で、Gaucheもそれに従って実装していました。
しかし既存の実装のほとんどは@code{(string-filter pred s)}という順序に
なっています。srfi-13の参照実装がそうだったからです。

0.9.4からGaucheも現在のsrfi-13の実装に合わせましたが、
以前の仕様で書かれたコードとの互換性を保つため、
引数順を逆にしても動作するようになっています。
新しく書かれるコードは、現在のsrfi-13の引数順を使うのが良いでしょう。
@c COMMON
@end defun

@node SRFI-13 Low-level string procedures,  , SRFI-13 String filtering, String library
@subsection Low-level string procedures
@c NODE 低レベルな文字列に関する手続き

@defun string-parse-start+end proc s args
@defunx string-parse-final-start+end proc s args
[SRFI-13]
@c MOD srfi-13
@end defun

@defmac let-string-start+end (start end [rest]) proc-exp s-exp args-exp body @dots{}
[SRFI-13]
@c MOD srfi-13
@end defmac

@defun check-substring-spec proc s start end
@defunx substring-spec-ok? s start end
[SRFI-13]
@c MOD srfi-13
@end defun

@defun make-kmp-restart-vector s :optional c= start end
[SRFI-13]
@c MOD srfi-13
@end defun

@defun kmp-step pat rv c i c= p-start
[SRFI-13]
@c MOD srfi-13
@end defun

@defun string-kmp-partial-search pat rv s i :optional c= p-start s-start s-end
[SRFI-13]
@c MOD srfi-13
@end defun

@c ----------------------------------------------------------------------
@node Time data types and procedures, Sources of random bits, String library, Library modules - SRFIs
@section @code{srfi-19} - Time data types and procedures
@c NODE 時間のデータ型と手続き, @code{srfi-19} - 時間のデータ型と手続き

@deftp {Module} srfi-19
@mdindex srfi-19
@c EN
This SRFI defines various representations of time and date, and
conversion methods among them.
@c JP
このSRFIは、時間と日付に関する様々な表現と、それらの間の変換メソッドを提供します。
@c COMMON

@c EN
On Gauche, time object is supported natively by @code{<time>} class
(@pxref{Time}).  Date object is supported by @code{<date>} class
described below.
@c JP
Gaucheでは、timeオブジェクトは@code{<time>}クラスとして組み込みで
サポートされています(@ref{Time}参照)。dateオブジェクトは以下で説明する
@code{<date>}クラスとしてサポートされます。
@c COMMON
@end deftp

@menu
* SRFI-19 Time types::
* SRFI-19 Time queries::
* SRFI-19 Time procedures::
* SRFI-19 Date::
* SRFI-19 Date reader and writer::
@end menu

@node SRFI-19 Time types, SRFI-19 Time queries, Time data types and procedures, Time data types and procedures
@subsection Time types
@c NODE 時間のタイプ

@c EN
Time type is represented by a symbol.  This module defines
the following constant variables that is bound to its name, for
convenience.
@c JP
時間のタイプはシンボルで表現されます。
このモジュールでは以下の定数が自分の名前に束縛された形で提供されています。
@c COMMON

@defvr {Constant} time-utc
[SRFI-19]
@c MOD srfi-19
@c EN
UTC time.  Gauche's built-in @code{current-time} always returns
this type (@pxref{Time}).
@c JP
UTC timeです。Gaucheの組み込みの@code{current-time}は常にこのタイプの時間を
返します (@ref{Time}参照)。
@c COMMON
@end defvr

@defvr {Constant} time-tai
[SRFI-19]
@c MOD srfi-19
@c EN
International Atomic Time.  This time is a bit larger than UTC, due to
the leap seconds.
@c JP
International Atomic Time。この時間は閏秒による調整を受けないため、
UTCより若干大きな値を取ります。
@c COMMON
@end defvr

@defvr {Constant} time-monotonic
[SRFI-19]
@c MOD srfi-19
@c EN
Implementation-dependent monotonically increasing time.
In Gauche, this is the same as @code{time-tai}.
@c JP
実装依存の、単調増加する時間。Gaucheの実装ではこれは@code{time-tai}と同じです。
@c COMMON
@end defvr

@defvr {Constant} time-duration
[SRFI-19]
@c MOD srfi-19
@c EN
Duration between two absolute time points.
@c JP
二つの絶対的な時点の間の期間。
@c COMMON
@end defvr

@defvr {Constant} time-process
[SRFI-19]
@c MOD srfi-19
@c EN
CPU time in current process.
Gauche calculates this from user time and system time returned by
POSIX times(3).
@c JP
現在のプロセスのCPU時間。
Gaucheは、POSIX time(3)コールが返すユーザ時間とシステム時間の合計からこの値を
計算します。
@c COMMON
@end defvr

@defvr {Constant} time-thread
[SRFI-19]
@c MOD srfi-19
@c EN
CPU time in current thread.
In the current implementation, this is the same as @code{time-process}.
@c JP
現在のスレッドのCPU時間。
現在の実装ではこれは@code{time-process}と同じです。
@c COMMON
@end defvr

@node SRFI-19 Time queries, SRFI-19 Time procedures, SRFI-19 Time types, Time data types and procedures
@subsection Time queries
@c NODE 時間に関する問い合わせ

@defun current-time :optional time-type
[SRFI-19]
@c MOD srfi-19
@c EN
Extends Gauche built-in @code{current-time} (@pxref{Time}) to take
optional @var{time-type} argument to specify the desired time type.
@var{time-type} must be one of the types described in @ref{SRFI-19 Time types}.
@c JP
Gauche組み込みの@code{current-time} (@ref{Time}参照)を拡張して、
必要な時間のタイプを省略可能な引数@var{time-type}で指定できるようにしています。
可能な@var{time-type}の値は@ref{SRFI-19 Time types}で説明されているものです。
@c COMMON
@end defun

@defun current-date :optional tz-offset
[SRFI-19]
@c MOD srfi-19
@c EN
Returns the current date as an instance of @code{<date>} class
(@pxref{SRFI-19 Date}).  If @var{tz-offset} is given, it must be
an offset from UTC in number of seconds.  If @var{tz-offset} is
not given, returns the date in local time zone.
@c JP
現在の日付を@code{<date>}クラスのインスタンスとして返します(@ref{SRFI-19 Date}参照)。
@var{tz-offset}が与えられた場合、それがUTCからのオフセットを表す秒数として
使われます。@var{tz-offset}が与えられなかった場合はローカルタイムゾーンで
表現された日付が返されます。
@c COMMON
@end defun

@defun current-julian-day
[SRFI-19]
@c MOD srfi-19
@c EN
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).
@c JP
現在のユリウス日(Julian day)を返します。Julian dayは
-4714-11-24T12:00:00Z (November 24, -4714 at noon, UTC) からの日数を
実数で表現したものです。
@c COMMON
@end defun

@defun current-modified-julian-day
[SRFI-19]
@c MOD srfi-19
@c EN
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).
@c JP
現在の修正ユリウス日(Modified julian day)を返します。Modified julian dayは
1858-11-17T00:00:00Z (November 17, 1858 at midnight, UTC)
からの日数を実数で表現したものです。
@c COMMON
@end defun

@defun time-resolution
[SRFI-19]
@c MOD srfi-19
@end defun


@node SRFI-19 Time procedures, SRFI-19 Date, SRFI-19 Time queries, Time data types and procedures
@subsection Time procedures
@c NODE 時間に関する手続き

@defun make-time type nanoseconds seconds
[SRFI-19]
@c MOD srfi-19
@c EN
Returns an instance of @code{<time>} class with specified initial values.
Equivalent to @code{(make <time> :type type :second seconds :nanosecond nanoseconds)}.

(This function had been defined incorrectly before release 0.6.8;
the arguments @var{seconds} and @var{nanoseconds} were switched.
Please check your code if it uses @code{make-time}).
@c JP
与えられた初期値を持つ@code{<time>}クラスのインスタンスを返します。
@code{(make <time> :type type :second seconds :nanosecond nanoseconds)}
と等価です。

(この関数は0.6.8より前のリリースでは間違って定義されていました。
@var{seconds}と@var{nanoseconds}の引数が逆になっていたのです。
@code{make-time}を使っているコードは注意して下さい)。
@c COMMON
@end defun

@defun time-type time
@defunx time-second time
@defunx time-nanosecond time
@defunx set-time-type! time type
@defunx set-time-second! time second
@defunx set-time-nanosecond! time nanosecond
[SRFI-19]
@c MOD srfi-19
@c EN
Getter and setter of @code{<time>} object slots.
@c JP
@code{<time>}オブジェクトのスロットのアクセサです。
@c COMMON
@end defun

@defun copy-time time
[SRFI-19]
@c MOD srfi-19
@c EN
Returns a new instance of @code{<time>} whose content is the same as
given @var{time}
@c JP
与えられた@var{time}と同じ内容の新しい@code{<time>}オブジェクトを返します。
@c COMMON
@end defun

@defun time=? time0 time1
@defunx time<? time0 time1
@defunx time<=? time0 time1
@defunx time>? time0 time1
@defunx time>=? time0 time1
[SRFI-19]
@c MOD srfi-19
@c EN
Compares two times.  Types of both times must match.
@c JP
二つの時間を比較します。時間のタイプは一致していなければなりません。
@c COMMON
@end defun

@defun time-difference time0 time1
@defunx time-difference! time0 time1
[SRFI-19]
@c MOD srfi-19
@c EN
Returns the difference of two times, in @code{time-duration} time.
Types of both times must match.
@code{Time-difference!} modifies @var{time0} to store the result.
@c JP
二つの時間の差を@code{time-duration}タイプの時間として返します。
二つの時間のタイプは一致していなければなりません。
@code{Time-difference!}は結果を格納するために@var{time0}を変更します。
@c COMMON
@end defun

@defun add-duration time0 time-duration
@defunx add-duration! time0 time-duration
@defunx subtract-duration time0 time-duration
@defunx subtract-duration! time0 time-duration
[SRFI-19]
@c MOD srfi-19
@c EN
Adds or subtracts @var{time-duration} to or from @var{time0}.
Type of returned time is the same as @var{time0}.  Type of
@var{time-duration} must be @code{time-duration}.
@code{add-duration!} and @code{subtract-duration!} reuse
@var{time0} to store the result.
@c JP
@var{time-duration}を@var{time0}に加算、または@var{time0}から減算します。
返される時間のタイプは@var{time0}と同じです。@var{time-duration}のタイプは
@code{time-duration}でなければなりません。
@code{add-duration!}と@code{subtract-duration!}は結果を格納するのに
@var{time0}を再利用します。
@c COMMON
@end defun

@node SRFI-19 Date, SRFI-19 Date reader and writer, SRFI-19 Time procedures, Time data types and procedures
@subsection Date
@c NODE 日付

@deftp {Class} <date>
@clindex date
@c MOD srfi-19
@c EN
Represents a date.
@c JP
日付を表現します。
@c COMMON

@defivar <date> nanosecond
@c EN
Nanosecond portion of the date by an integer between 0 and 999,999,999,
inclusive.
@c JP
日付のナノ秒部分、0 から 999,999,999 までの整数です。
@c COMMON
@end defivar

@defivar <date> second
@c EN
Second portion of the date by an integer between 0 and 60, inclusive.
(60 for leap second).
@c JP
日付の秒部分、0 から 60 までの整数です。(60 は閏秒)
@c COMMON
@end defivar

@defivar <date> minute
@c EN
Minute portion of the date by an integer between 0 and 59, inclusive.
@c JP
日付の分部分、0 から 59 までの整数です。
@c COMMON
@end defivar

@defivar <date> hour
@c EN
Hour portion of the date by an integer between 0 and 23, inclusive.
@c JP
日付の時部分、0 から 23 までの整数です。
@c COMMON
@end defivar

@defivar <date> day
@c EN
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).
@c JP
日付の日部分、0 から 31 日までの整数です。実際の上限は年と月によって決定
されます。(註: 1 は朔日(ついたち)、0 は仕様では認められていますが、
なぜなのかはわかりません。)
@c COMMON
@end defivar

@defivar <date> month
@c EN
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 @code{<sys-tm>} convention).
@c JP
日付の月部分、1 から 12 までの整数です。1 は一月、2 は二月、以下同様です。
(註: これは POSIX の @code{<sys-tm>} の命名法とは異ります。)
@c COMMON
@end defivar

@defivar <date> year
@c EN
Year portion of the date.
@c JP
日付の年部分です。
@c COMMON
@end defivar

@defivar <date> zone-offset
@c EN
The number of seconds east of GMT for this timezone, by an integer.
@c JP
このタイムゾーンが GMT より何秒東にあるかを示す整数です。
@c COMMON
@end defivar
@end deftp

@defun make-date nanosecond second minute hour day month year zone-offset
[SRFI-19]
@c MOD srfi-19
@c EN
Makes a @code{<date>} object from the given values.
Note: this procedure does not check if the values are in the valid range.
@c JP
与えられた値から @code{<date>} オブジェクトを作成します。
註: この手続きは与えられた値が正しい範囲であるかどうかをチェックしません。
@c COMMON
@end defun

@defun date? obj
[SRFI-19]
@c MOD srfi-19
@c EN
Returns true iff @var{obj} is a @code{<date>} object.
@c JP
@var{obj} が @code{<date>} オブジェクトである場合にかぎり真を返します。
@c COMMON
@end defun

@defun date-nanosecond date
@defunx date-second date
@defunx date-minute date
@defunx date-hour date
@defunx date-day date
@defunx date-month date
@defunx date-year date
@defunx date-zone-offset date
[SRFI-19]
@c MOD srfi-19
@c EN
Accessors.
@c JP
アクセサです。
@c COMMON
@end defun

@defun date-year-day date
@defunx date-week-day date
@defunx date-week-number date day-of-week-starting-week
[SRFI-19]
@c MOD srfi-19
@c EN
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.

@var{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.).
@c JP
それぞれ、一年の何日目(一月一日が 1)か、何曜日(日曜日が 0、月曜日が 1
など)か、一年のうち何週目(一年の最初の週が一週間に満たない場合はその
週は無視)かを計算します。
@c COMMON
@end defun

@defun date->julian-day date
@defunx date->modified-julian-day date
@defunx date->time-monotonic date
@defunx date->time-tai date
@defunx date->time-utc date
[SRFI-19]
@c MOD srfi-19
@c EN
Conversions from date to various date/time types.
@c JP
日付から様々な様式の日付/時間に変換します。
@c COMMON
@end defun

@defun julian-day->date jd :optional tz-offset
@defunx julian-day->time-monotonic jd
@defunx julian-day->time-tai jd
@defunx julian-day->time-utc jd
[SRFI-19]
@c MOD srfi-19
@c EN
Conversions from julian-day to various date/time types.
@c JP
ユリウス日からから様々な様式の日付/時間に変換します。
@c COMMON
@end defun

@defun modified-julian-day->date jd :optional tz-offset
@defunx modified-julian-day->time-monotonic jd
@defunx modified-julian-day->time-tai jd
@defunx modified-julian-day->time-utc jd
[SRFI-19]
@c MOD srfi-19
@c EN
Conversions from modified julian-day to various date/time types.
@c JP
修正ユリウス日から様々な様式の日付/時間に変換します。
@c COMMON
@end defun

@defun time-monotonic->date time :optional tz-offset
@defunx time-monotonic->julian-day time
@defunx time-monotonic->modified-julian-day time
@defunx time-monotonic->time-tai time
@defunx time-monotonic->time-tai! time
@defunx time-monotonic->time-utc time
@defunx time-monotonic->time-utc! time
[SRFI-19]
@c MOD srfi-19
@c EN
Conversions from time-monotonic to various date/time types.
@c JP
time-monotonic形式から様々な様式の日付/時間に変換します。
@c COMMON
@end defun

@defun time-tai->date time :optional tz-offset
@defunx time-tai->julian-day time
@defunx time-tai->modified-julian-day time
@defunx time-tai->time-monotonic time
@defunx time-tai->time-monotonic! time
@defunx time-tai->time-utc time
@defunx time-tai->time-utc! time
[SRFI-19]
@c MOD srfi-19
@c EN
Conversions from time-tai to various date/time types.
@c JP
time-tai形式から様々な様式の日付/時間に変換します。
@c COMMON
@end defun

@defun time-utc->date time :optional tz-offset
@defunx time-utc->julian-day time
@defunx time-utc->modified-julian-day time
@defunx time-utc->time-monotonic time
@defunx time-utc->time-monotonic! time
@defunx time-utc->time-tai time
@defunx time-utc->time-tai! time
[SRFI-19]
@c MOD srfi-19
@c EN
Conversions from time-utc to various date/time types.
@c JP
UTC 形式から様々な様式の日付/時間に変換します。
@c COMMON
@end defun

@node SRFI-19 Date reader and writer,  , SRFI-19 Date, Time data types and procedures
@subsection Date reader and writer
@c NODE 日付の読み書き

@defun date->string date :optional format-string
[SRFI-19+]
@c MOD srfi-19
@c EN
Converts a @code{<date>} object to a string, according
to the format specified by @var{format-string}.
If @var{format-string} is omitted, @code{"~c"} is assumed.
@c JP
@code{<date>}オブジェクトを文字列に変換します。書式は
@var{format-string}で指定します。@var{format-string}が省略された場合に
は@code{"~c"}が指定されたものとします。
@c COMMON

@c EN
A format string is copied to output, except a sequence begins with
@code{~} which is replaced with the following rules:
@c JP
書式文字列は出力にコピーされます。ただし、@code{~}で始まる並びの部分は
以下の規則にしたがって書き換えられます。
@c COMMON

@c EN
@table @code
@item ~~
A literal @code{~}.
@item ~a
Locale's abbreviated weekday name (Sun...Sat).
@item ~A
Locale's full weekday name (Sunday...Saturday).
@item ~b
Locale's abbreviate month name (Jan...Dec).
@item ~B
Locale's full month name (January...December).
@item ~c
Locale's date and time (e.g., "Fri Jul 14 20:28:42-0400 2000").
@item ~d
Day of month, zero padded (01...31).
@item ~D
Date (mm/dd/yy).
@item ~e
Day of month, blank padded ( 1...31).
@item ~f
Seconds+fractional seconds, using locale's decimal separator (e.g. 5.2).
@item ~h
Same as ~b.
@item ~H
Hour, zero padded, 24-hour clock (00...23).
@item ~I
Hour, zero padded, 12-hour clock (01...12).
@item ~j
Day of year, zero padded.
@item ~k
Hour, blank padded, 24-hour clock ( 0...23).
@item ~l
Hour, blank padded, 12-hour clock ( 1...12).
@item ~m
Month, zero padded (01...12).
@item ~M
Minute, zero padded (00...59).
@item ~n
New line.
@item ~N
Nanosecond, zero padded.
@item ~p
Locale's AM or PM.
@item ~r
Time, 12 hour clock, same as "~I:~M:~S ~p".
@item ~s
Number of full seconds since "the epoch" (in UTC).
@item ~S
Second, zero padded (00...60).
@item ~t
Horizontal tab.
@item ~T
Time, 24 hour clock, same as "~H:~M:~S".
@item ~U
Week number of year with Sunday as first day of week (01...53).
@item ~V
Week number of year with Monday as first day of week (00...52).
@item ~w
Day of week (0...6).
@item ~W
Week number of year with Monday as first day of week (00...52).
@item ~x
Locale's date representation, for example: "07/31/00".
@item ~X
Locale's time representation, for example: "06:51:44".
@item ~y
Last two digits of year (00...99).
@item ~Y
Year.
@item ~z
Time zone in RFC-822 style.
@c @item ~Z
@c Symbol time zone (not-implemented).
@item ~1
ISO-8601 year-month-day format.
@item ~2
ISO-8601 hour-minute-second-timezone format.
@item ~3
ISO-8601 hour-minute-second format.
@item ~4
ISO-8601 year-month-day-hour-minute-second-timezone format.
@item ~5
ISO-8601 year-month-day-hour-minute-second format.
@end table
@c JP
@table @code
@item ~~
文字@code{~}そのもの。
@item ~a
ロケールによる曜日省略形(Sun...Sat)
@item ~A
ロケールによる曜日完全形(Sunday...Saturday)
@item ~b
ロケールによる月省略形(Jan...Dec)
@item ~B
ロケールによる月完全形(January...December)
@item ~c
ロケールによる日付時刻(たとえば、"Fri Jul 14 20:28:42-0400 2000")
@item ~d
月日にち、0を補填(01...31)
@item ~D
日付(mm/dd/yy)
@item ~e
月日にち、空白補填( 1...31)
@item ~f
秒 + 小数秒、小数点はロケールによるセパレータ(たとえば、5.2)
@item ~h
~b に同じ
@item ~H
時、0を補填、24時制(00...23)
@item ~I
時、0を補填、12時制(01...12)
@item ~j
年日にち、0補填(001...366)
@item ~k
時、空白補填、24時制( 0...23)
@item ~l
時、空白補填、12時制( 1...12)
@item ~m
月、0補填、(01...12)
@item ~M
分、0補填、(00...59)
@item ~n
改行
@item ~N
ナノ秒、0補填
@item ~p
ロケールによるAM、PM
@item ~r
時刻、12時制、"~I:~M:~S ~p"と同じ
@item ~s
エポックからの経過秒(UTC)
@item ~S
秒、0補填(00...60)
@item ~t
水平タブ
@item ~T
時刻、24時制、"~H:~M:~S"と同じ
@item ~U
年経過週、週は日曜はじまり(01...53)
@item ~V
年経過週、週は月曜はじまり(00...52)
@item ~w
曜日を表す数字、日曜が0 (0...6)
@item ~W
年経過週、週は月曜日はじまり(00...52)
@item ~x
ロケールによる日付、例えば、"07/31/00"
@item ~X
ロケールによる時刻、24時制、例えば、"06:51:44"
@item ~y
西暦の下2桁(00...99)
@item ~Y
西暦
@item ~z
RFC-2822スタイルのタイムゾーン
@c @item ~Z
@c Symbol time zone (not-implemented).
@item ~1
ISO-8601 の「年-月-日」形式
@item ~2
ISO-8601 の「時-分-秒タイムゾーン」形式
@item ~3
ISO-8601 の「時:分:秒」形式
@item ~4
ISO-8601 の「西暦-月-日T時:分:秒タイムゾーン」形式
@item ~5
ISO-8601 の「西暦-月-日T時:分:秒」形式
@end table
@c COMMON

@c EN
Note: currently Gauche doesn't honor process's locale setting,
and it always formats the date as if the locale is "C".  It may
be changed in future, so you shouldn't rely on, for example,
@code{~a} always formatted as "Sun".."Sat".
@c JP
注意：現時点でGaucheはロケールの設定には従っておらず、常にロケールが
"C" に設定されているものとしてフォーマットします。これについては将来変
更する可能性がありますので、現在の振舞いを前提として、たとえば、
@code{~a}が常に"Sun".."Sat"のようにフォーマットされることを前提にプロ
グラムしてはいけません。
@c COMMON

@c EN
There's no portable way to ensure you'll get "C" locale formats
since there's no standard way to set process's locale yet.
However, Gauche provides a way to ensure the locale to be "C",
as an extension to srfi-19.
Insert @code{@@} between @code{~} and the directive
character, such as @code{~@@a}.
@c JP
いまのところプロセスのロケールを設定する標準的な方法がないので、
"C"ロケール形式を取得できるかどうかを確かめるポータブルな方法がありま
せん。とはいえ、Gaucheでは SRFI-19の拡張として"C"ロケールであることを
確認する方法を提供しています。@code{@@} を @code{~} とディレクティブ文
字の間に挿入し、@code{~@@a} のようにします。
@c COMMON
@end defun

@defun string->date string template-string
[SRFI-19]
@c MOD srfi-19
@c   [NB] srfi-19's string->date is broken, in both spec and reference
@c   implementation.  I'm wondering whether I should change string->date
@c   to make usable, or introduce another procedure, like string->date*,
@c   which fixes the problem.
@c
@c Both procedures parse a string representation of date in @var{string},
@c according to the format given in @var{template-string}.

@c The input string must match the @var{template-string},
@c except tilde-directives described below, which matches
@c one or more component(s) of the date.  If the input string
@c is parsed successfully, a @code{<date>} object is returned
@c with the matched components are filled.

@c If the input string does not match @var{template-string},
@c an error is signaled.  (The SRFI-19 spec doesn't explicitly
@c state what happens if @code{string->date} doesn't accept the
@c input, which actually reduces usability of @code{string->date}

@c but the reference implementation signals an error, and
@c it would be safe to assume


@c @table @code
@c @item ~~
@c Matches literal @code{~}.
@c @item ~a
@c Skip to an alphanumeric character, then matches abbreviated
@c weekday in locale.  Match result is ignored.
@c @item ~A
@c Skip to an alphanumeric character, then matches full
@c weekday in locale.  Match result is ignored.
@c @item ~b
@c Skip to an alphanumeric character, then matches abbreviated
@c month name in locale.  Sets the month component of the date.
@c @item ~B
@c Skip to an alphanumeric character, then matches full
@c month name in locale.  Sets the month component of the date.
@c @item ~d
@c Skip to a numeric character, then matches the day of month.
@c Sets the month component of the date.
@c @item ~e

@c ~e	any	day of month, blank padded	date-day
@c ~h	char-alphabetic?	same as ~b	nothing
@c ~H	char-numeric?	hour	date-hour
@c ~k	any	hour, blank padded	date-hour
@c ~m	char-numeric?	month	date-month
@c ~M	char-numeric?	minute	date-minute
@c ~S	char-numeric?	second	date-second
@c ~y	any	2-digit year	date-year within 50 years
@c ~Y	char-numeric?	year	date-year
@c ~z	any	time zone	date-zone-offset@end table

@end defun

@c ----------------------------------------------------------------------
@node Sources of random bits, Localization, Time data types and procedures, Library modules - SRFIs
@section @code{srfi-27} - Sources of Random Bits
@c NODE ランダムビットのソース, @code{srfi-27} - ランダムビットのソース

@deftp {Module} srfi-27
@mdindex srfi-27
@c EN
This module provides SRFI-27 pseudo random generator interface,
using Mersenne Twister algorithm
(@pxref{Mersenne-Twister random number generator}) as the backbone.
@c JP
このモジュールはメルセンヌツイスタアルゴリズム
(@ref{Mersenne-Twister random number generator} 参照)
を基礎に用いたSRFI-27疑似乱数発生器インタフェースを提供します。
@c COMMON
@end deftp

@defun random-integer n
[SRFI-27]
@c MOD srfi-27
@c EN
Returns a random exact integer between [0, @var{n}-1], inclusive,
using the default random source.
To set a random seed for this procedure, use @code{random-source-randomize!}
or @code{random-source-pseudo-randomize!} on @code{default-random-source}.
@c JP
デフォルトの乱数発生源を用いて、0 から @var{n}-1 までの正確な整数の乱数を
返します。この手続きの乱数のシードを設定するには
@code{default-random-source} に対して
@code{random-source-randomize!} あるいは、
@code{random-source-pseudo-randomize!} を用います。
@c COMMON
@end defun

@defun random-real
[SRFI-27]
@c MOD srfi-27
@c EN
Returns a random real number between (0, 1), exclusive,
using the default random source.
To set a random seed for this procedure, use @code{random-source-randomize!}
or @code{random-source-pseudo-randomize!} on @code{default-random-source}.
@c JP
デフォルトの乱数発生源を用いて、0 より大きく、1 未満の実数乱数を返します。
この手続きの乱数のシードを設定するには @code{default-random-source} に対して
@code{random-source-randomize!} あるいは、
@code{random-source-pseudo-randomize!} を用います。
@c COMMON
@end defun

@defvar default-random-source
[SRFI-27]
@c MOD srfi-27
@c EN
Keeps the default random source that is used by @code{random-integer}
and @code{random-real}.
@c JP
@code{random-integer} および @code{random-real} が利用するデフォルトの
乱数発生源を保持しています。
@c COMMON
@end defvar

@defun make-random-source
[SRFI-27]
@c MOD srfi-27
@c EN
Creates and returns a new random source.
In the current Gauche implementation, it is just a @code{<mersenne-twister>}
object.  It may be changed in the future implementation.
@c JP
乱数の発生源を生成し返します。
現在の Gauche の実装では、これは @code{<mersenne-twister>} のオブジェクトです。
将来の実装では変更される可能性があります。
@c COMMON
@end defun

@defun random-source? obj
[SRFI-27]
@c MOD srfi-27
@c EN
Returns @code{#t} if @var{obj} is a random source object.
@c JP
@var{obj} が乱数発生源オブジェクトであれば、@code{#t} を返します。
@c COMMON
@end defun

@defun random-source-state-ref s
@defunx random-source-state-set! s state
[SRFI-27]
@c MOD srfi-27
@c EN
Gets and sets the "snapshot" of the state of the random source @var{s}.
@var{State} is an opaque object whose content depends on the backbone
generator.
@c JP
乱数発生源 @var{s} の状態の「スナップショット」を獲得あるいは設定します。
@var{state} は背後にある発生器に依存する内容をもつ不透明なオブジェクトです。
@c COMMON
@end defun

@defun random-source-randomize! s
[SRFI-27]
@c MOD srfi-27
@c EN
Makes an effort to set the state of the random source @var{s} to
a truly random state.  The current implementation uses the current
time and the process ID to set the random seed.
@c JP
乱数発生源 @var{s} の状態を完全にランダムな状態にしようとします。
現在の実装では乱数のシードを設定するのに、現在の時刻とプロセス ID を
使います。
@c COMMON
@end defun

@defun random-source-pseudo-randomize! s i j
[SRFI-27]
@c MOD srfi-27
@c EN
Changes the state of the random source @var{s} into the initial state
of the (@var{i}, @var{j})-th independent random source,
where @var{i} and @var{j} are non-negative integers.
This procedure can be used to reuse a random source @var{s} as large
number of independent random source, indexed by two non-negative integers.
Note that this procedure is entirely deterministic.
@c JP
乱数発生源 @var{s} の状態を発生源とは独立した (@var{i}, @var{j}) 番の
初期状態に設定します。@var{i} および @var{j} は非負の整数です。
この手続きは乱数発生源 @var{s} を二つの非負整数でインデックス付した、
大規模の独立の乱数発生源として再利用するときに利用できます。
この手続きは、完全な決定性があることに注意してください。
@c COMMON
@end defun

@defun random-source-make-integers s
[SRFI-27]
@c MOD srfi-27
@c EN
Returns a procedure, that takes one integer argument @var{n} and
returns a random integer between 0 and @var{n}-1 inclusive for every
invocation, from the random source @var{s}.
@c JP
呼出しのたびに乱数発生源 @var{s} より、 0 から @var{n}-1 までの整数の
乱数を返す、一つの整数 @var{n} を引数としてとる手続きを、返します。
@c COMMON
@end defun

@defun random-source-make-reals s :optional unit
[SRFI-27]
@c MOD srfi-27
@c EN
Returns a procedure, that takes no argument and
returns a random real between 0 and 1 exclusive for
every invocation, from the random source @var{s}.
If @var{unit} is given, the random real the returned procedure
generates will be quantized by the given @var{unit}, where
0 < @var{unit} < 1.
@c JP
呼出しのたびに乱数発生源 @var{s} から 0 より大きく 1 未満の実数乱数を
返す、無引数の手続きを返します。
@var{unit} が与えられた場合、返された手続きが生成する実数乱数は
@var{unit} 単位に量子化されます。@var{unit} は、 0 より大きく 1 未満で
なければなりません。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node Localization, A program argument processor, Sources of random bits, Library modules - SRFIs
@section @code{srfi-29} - Localization
@c NODE 地域化, @code{srfi-29} - 地域化

@deftp {Module} srfi-29
@mdindex srfi-29
@mdindex srfi-29.bundle
@mdindex srfi-29.format
@c EN
This module implements the message localization mechanism
defined in SRFI-29.

In fact, this module consists of two submodules,
@code{srfi-29.bundle} and @code{srfi-29.format}.
The module @code{srfi-29} extends both submodules.
It is because srfi-29's definition of the @code{format}
procedure is incompatible to Gauche's native @code{format}
(thus Common Lisp's @code{format}) in the handling of
@code{~@@*} directive.

So I splitted the module into two, @code{srfi-29.format}
which contains srfi-29's @code{format}, and @code{srfi-29.bundle}
which contains the rest ("bundle" API).
If a program wishes a complete compatibility of
srfi-29, use @code{srfi-29} module, which overrides
Gauche's native @code{format}.   If a program just wants
srfi-29's "bundle" API, but wants to keep Gauche's @code{format},
use @code{srfi-29.bundle}.

A localization feature is also provided by @code{text.gettext} module
(@pxref{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.
@c JP
このモジュールは SRFI-29 で定義されたメッセージの地域化機構を実装したものです。

実際には、このモジュールは2つのサブモジュール、@code{srfi-29.bundle}
および @code{srfi-29.format} で構成されています。@code{srfi-29}モジュールは
このふたつのモジュールをextendしています。このようにしているのは、
SRFI-29 での @code{format} 手続きの定義が Gauche ネイティヴの(すなわち
Common Lisp の) @code{format} とでは @code{~@@*} 指令の扱い
において互換性がないからです。

そんなわけで、SRFI-29 の @code{format} を含む @code{srfi-29.format} と
それ以外(「バンドル」API)を含む @code{srfi-29.bundle} に分離しました。
プログラムを SRFI-29 と完全に互換性のあるものにしたければ、@code{srfi-29}
モジュールを使って下さい。こうすると Gauche ネイティヴの
@code{format} が上書きされます。SRFI-29 の「バンドル」API を使いたいだけで、
Gauche の @code{format} をそのままにしておきたいなら、@code{srfi-29.bundle}
を使って下さい。

地域化機能は @code{text.gettext} モジュールによっても提供され
(@pxref{Localized messages})、Gauche でメッセージの地域化をするのなら
@code{text.gettext} を使うのが好ましい方法です。@code{srfi-29} モジュールは
主として SRFI-29 の機能を使っているコードをポーティングするためにあります。
@c COMMON
@end deftp

@c EN
@subheading Bundle specifier
@c JP
@subheading バンドル指定子
@c COMMON

@c EN
A @emph{bundle specifier} is an arbitrary list of symbols,
but typically it takes the form like:
@c JP
@emph{バンドル指定子}はシンボルを要素とする任意のリストです。しかし
典型的には以下のようなフォームになります。
@c COMMON
@example
@code{(@var{package} @var{language} @var{country} @var{details} @dots{})}
@end example
@c EN
Where @var{package} specifies the software package,
@var{language} and @var{country} specifies language and country code,
and @var{details} gives other informations like encoding.

The values for the default bundle specifier can be obtained
by the following parameters.
@c JP
ここで、@var{package} はソフトウェアパッケージを指定し、
@var{language} および @var{country} は言語と国コードを指定、そして、
@var{details} はエンコーディングのようなそのほかの情報を指定します。

デフォルトのバンドル指定子の値は以下のようなパラメータで取得可能です。
@c COMMON

@deffn {Parameter} current-language
@deffnx {Parameter} current-country
@deffnx {Parameter} current-locale-details
[SRFI-29]
@c MOD srfi-29
@c EN
The @code{current-language} and @code{current-country} parameters
keep the ISO 639-1 language code and ISO 3166-1 country code
respectively, both as symbols.
The @code{current-locale-details} keeps a list of auxiliary
local informations, such as encodings.

These parameters are initialized if @code{LANG} environment
variable is set in the form of @code{lang_country.encoding} format.
For example, if the @code{LANG} setting is @code{ja_JP.eucJP},
those parameters are @code{ja}, @code{jp}, and @code{(eucjp)},
respectively.   If @code{LANG} is @code{C} or undefined,
the default values are @code{en}, @code{us}, and @code{()}, respectively.
@c JP
@code{current-language} および @code{current-country} パラメータは
ISO 639-1 の言語コードと ISO 3166-1 の国コードをそれぞれシンボルで
保持しています。@code{current-locale-details} はエンコーディングのような
補助的な地域情報のリストを保持しています。

これらのパラメータは、環境変数 @code{LANG} が @code{lang_country.encoding}
フォーマットの形式で設定されていれば、初期化されます。たとえば、
@code{LANG} が @code{ja_JP.eucJP} に設定されていれば、それらの
パラメータはそれぞれ @code{ja}、@code{jp}、@code{(eucjp)} に設定されます。
@code{LANG} が @code{C} であるかあるいは定義されていなければ、
デフォルト値は、それぞれ @code{en}、@code{us}、@code{()} です。
@c COMMON
@end deffn

@c EN
@subheading Bundle preparation
@c JP
@subheading バンドル準備
@c COMMON

@defun declare-bundle! bundle-specifier association-list
[SRFI-29]
@c MOD srfi-29
@c EN
Put the association list of template key (symbol) and the locale-specific
message (string) into the bundle database, with @var{bundle-specifier}
as the key.
@c JP
テンプレートキー(シンボル)と特定ロケールのメッセージ(文字列)の連想リストを
@var{bundle-specifier} をキーとして、バンドルデータベースに入れます。
@c COMMON
@end defun

@c EN
Gauche currently supports only in-memory bundle database.
That is, you have to call @code{declare-bundle!} within the application
in order to lookup the localized messages.
@c JP
Gauche は現在のところメモリ上のバンドルデータベースのみサポートしています。
つまり、地域化されてメッセージを探しあてるには、そのアプリケーション内で
@code{declare-bundle!} を呼ぶ必要があるということです。
@c COMMON

@defun save-bundle! bundle-specifier
@defunx load-bundle! bundle-specifier
[SRFI-29]
@c MOD srfi-29
@c EN
Since Gauche doesn't support persistent bundle database yet,
these procedures does nothing and returns @code{#f}.
(It is still conforming behavior of srfi-29).
@c JP
Gauche は今のところ永続バンドルデータベースをサポートしていないので、
これらの手続きはなにもせず @code{#f} を返します
(これはいまのところ srfi-29 の振舞いと適合しています)。
@c COMMON
@end defun

@c EN
@subheading Retrieving localized message
@c JP
@subheading 地域化されたメッセージの検索
@c COMMON

@defun localized-template package-name message-template-name
[SRFI-29]
@c MOD srfi-29
@c EN
Retrieves localized message, associated with a symbol
@var{message-template-name} in the package @var{package-name}.
@c JP
地域化されたメッセージを検索します。当該メッセージは
@var{package-name} パッケージの中で、@var{message-template-name}
シンボルと関連つけられています。
@c COMMON
@end defun

@c EN
@subheading Extended format procedure
@c JP
@subheading 拡張された format 手続き
@c COMMON

@defun format format-string args
[SRFI-29]
@c MOD srfi-29
@c EN
SRFI-29 extends SRFI-28's @code{format} procedure spec
(which supports @code{~a}, @code{~s}, @code{~%} and @code{~~} directives),
in order to support argument repositioning.

A directive @code{~N@@*}, where N is an integer or can be omitted,
causes the next directive to retrieve a value from @var{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 @code{format} (@pxref{Output}),
this SRFI-29 extension isn't.
Specifically, the @code{~N@@*} directive of Gauche's @code{format}
changes the argument pointer to points @var{N}-th optional argument,
thus it affects all the subsequent arguments.

Because of this incompatibility, this function is defined in
a separate module, @code{srfi-29.format}.  If you use @code{srfi-29},
which extends @code{srfi-29.bundle} and @code{srfi-29.format},
the @code{format} procedure will be overridden by srfi-29's @code{format}
in your module.  If you want to keep Gauche's native @code{format},
use @code{srfi-29.bundle} only.
@c JP
SRFI-29 は SRFI-28 の @code{format} 手続きの仕様(これは @code{~a}、
@code{~s}、@code{~%} および @code{~~} 指令をサポートしている)を
引数再配置をサポートするために拡張しています。

@code{~N@@*} 指令は @var{N}-番目のオプション引数から値を引き出す次の
指令の契機となります。参照された値が消費されることはありません。また、
参照された値がその後につづく指令の処理に影響を与えることはありません。

SRFI-28 の仕様は Gauche ネイティヴの @code{format} (@pxref{Output}) と
互換性がありますが、この SRFI-29 の拡張には互換性がありません。
具体的には、Gauche ネイティヴの @code{format} の @code{~N@@*} 指定は
引数ポインタを @var{N}-番目のオプション引数を指すように変更します。
それゆえ、そのあとに続くすべての引数に影響をあたえます。

この非互換性があるために、この関数は、分離したモジュール
@code{srfi-29.format} で定義されています。@code{srfi-29.bundle} と
@code{srfi-29.format} を拡張する @code{srfi-29} を使うと、@code{format}
手続きは SRFI-29 の @code{format} でそのモジュール内で上書きされます。
Gauche ネイティヴの @code{format} を使いたければ、@code{srfi-29.bundle}
だけを使うようにしてください。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node A program argument processor, Eager comprehensions, Localization, Library modules - SRFIs
@section @code{srfi-37} - args-fold: a program argument processor
@c NODE args-fold プログラム引数処理, @code{srfi-37} - args-fold プログラム引数処理

@deftp {Module} srfi-37
@mdindex srfi-37
@c EN
This module implements @code{args-fold},
yet another procedure to process command-line
arguments, defined in SRFI-37 (@uref{https://srfi.schemers.org/srfi-37/srfi-37.html}).

Unlike @code{gauche.parseopt}
(@pxref{Parsing command-line options}),
@code{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.
@c JP
このモジュールは、@code{args-fold} を実装しています。
これは、SRFI-37 (@uref{https://srfi.schemers.org/srfi-37/srfi-37.html}) で定義されている
コマンドライン引数の処理をするもうひとつの手続きです。

@code{gauche.parseopt} (@ref{Parsing command-line options}
参照) とは違って、@code{args-fold} は関数的なインタフェースです。すなわち、
利用者側の状態は、パーザの引数を通じて明示的に渡され、値が返ります。
また、ロングオプションを含む、POSIX および GNU の getopt のガイドラインに
準拠しています。
@c COMMON
@end deftp

@defun args-fold args options unrecognized-proc operand-proc :rest seeds
@c MOD srfi-37
@c EN
Processes program options @var{args} from left to right,
according to given option specification @var{options},
and two procedures @var{unrecognized-proc} and @var{operand-proc}.

@var{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 @emph{option procedure}).

@code{Args-fold} recognizes both single-character options (short options)
and long options.  A short option must begin with single hyphen
(e.g. @code{-a}), while long option must begin with double hyphens
(e.g. @code{--help}).   Short options can be
concatenated, e.g. @code{-abc} or @code{-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.
@code{-afoo} or @code{-a foo}.
Long-option argument can appear after character '@code{=}' or
space, e.g. @code{--long=foo} or @code{--long foo}.

When @code{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 @emph{operand}.   @code{Args-fold} allows operands and
options to be interleaved.  However, if @code{args-fold} encounters
'@code{--}', 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 @var{options},
the option procedure is called as follows:
@c JP
与えられたオプション仕様 @var{options} および、ふたつの手続き
@var{unrecognized-proc} と @var{operand-proc} とにしたがって、プログラム
引数 @var{args} を左から右へ処理します。

@var{options} はオプションオブジェクトのリストで以下のようなものです。
各オプションオブジェクトはオプションの名前、そのオプションが引数を
とるかどうかを指定するフラグ、そのオプションを処理する手続き
(今後これを @emph{オプション手続き}とよびます)を保持しています。

@code{args-fold} は単一文字のオプション(ショートオプション)と
ロングオプションの両方を認識します。ショートオプションは単一の
ハイフンで始まって(たとえば、@code{-a})いなければなりません。一方、
ロングオプションは二つのハイフンで始まって(たとえば、@code{--help})
いなければなりません。ショートオプションは連結することが可能で、
たとえば、@code{-abc} あるいは @code{-a -b -c} と書くことができます。
ショートオプション、ロングオプションはともに、必須引数あるいはオプショナル
引数を取ることができます。ショートオプションの必須引数は当該オプション
あとに空白なしあるいは空白をいれて指定することができます。たとえば、
@code{-afoo} あるいは @code{-a foo} が可能です。ロングオプションの
引数は'@code{=}'文字あるいは空白をはさみます。たとえば、
@code{--long=foo} または @code{--long foo} です。

@code{args-fold} はオプションの引数ではなく、ハイフンで始まっていない
コマンドライン引数を@emph{オペランド}としてとりあつかいます。
@code{args-fold} はオペランドとオプションが交互に出現するのを許します。
しかし、'@code{--}' に出逢うと、のこりは、ハイフンで始まっていようと
なかろうと、オペランドとして扱われます。

与えられたオプションが @var{options} 内のオプションオブジェクトのひとつ
にマッチすれば、オプション手続きが以下のように呼出されます。
@c COMMON

@example
(@var{option-proc} @var{option} @var{name} @var{arg} @var{seed} @dots{})
@end example

@c EN
where @var{option} is the matched option object, @var{name} is
the string actually used to specify the option, @var{arg} is
the option argument (or @code{#f} if there's none), and
@var{seed} @dots{} is the user's state information.
@var{Option-proc} must return as many arguments as @var{seed}s.

When @code{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 @var{unrecognized-proc}
with the same arguments as @var{option-proc}.

When @code{args-fold} finds an operand, @var{operand-proc}
is called as follows:
@c JP
ここで、@var{option} はマッチしたオプションオブジェクトで、@var{name}
は実際にオプションを指定するのに使われた文字列、@var{arg} はそのオプション
の引数(あるいは存在しなければ、@code{#f})、そして @var{seed} @dots{} は
利用者側の状態情報です。@var{option-proc} は @var{seed} と同じ数だけ
値を返さなければなりません。

@code{args-fold} がオペランドを見つけたら、@var{operand-proc} が
以下のように呼出されます。
@c COMMON

@example
(@var{operand-proc} @var{operand} @var{seed} @dots{})
@end example

@c EN
@var{Operand-proc} must return as many arguments as @var{seed}s.

The caller's state should be explicitly passed around seed arguments
and return values.  The initial seed values are @var{seed}s given
to @code{args-fold}.  The values returned from option procedure,
@var{unrecognized-proc} and @var{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 @code{args-fold}.
@c JP
@var{operand-proc} は @var{seed} と同じ数だけ
値を返さなければなりません。

呼出し側の状態は明示的にシード引数で渡され、戻されます。初期のシード値は
@code{args-fold} に与えた @var{seed} です。この値は、オプション手続き
@var{unrecognized-proc} と @var{operand-proc} によって戻され、
次にこれらのオプション手続きの呼出し時にシード引数として使われます。
これらの手続きの最後の呼出しから返されたこの値は @code{args-fold} によって
返されます。
@c COMMON
@end defun

@defun option names require-arg? optional-arg? processor
@c MOD srfi-37
@c EN
Creates an option object with the passed properties.

@var{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, @var{require-arg?} and @var{optional-arg?}
indicates whether the option should take an option argument,
or may take an option argument.

@var{Processor} is the option processor procedure.

Note that, if an option argument is passed using '@code{=}'
character, it is passed to the option procedure even if
the option has @code{#f} in both @var{require-arg?}
and @var{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 '@code{d}' is marked to take optional option argument,
then '@code{-dfoo}' is interpreted as '@code{-d}' with argument '@code{foo}',
but '@code{-d foo}' is interpreted as '@code{-d}' without argument
and an operand @code{foo}.  If '@code{d}' is marked to
take required option argument, however, both are interpreted
as '@code{-d}' with argument '@code{foo}'.
@c JP
渡されたプロパティでオプションオブジェクトを作成します。

@var{names} は文字と(あるいは)文字列のリストです。文字はショートオプションに
使い、文字列はロングオプションに使います。

ふたつのフラグ @var{require-arg?} と @var{optional-arg?} はオプションが
必須引数をとるか、あるいは、オプショナル引数をとるかを示します。

@var{processor} はそのオプションの処理をする手続きです。

オプションの引数が '@code{=}' つきで渡された場合には、
たとえ @var{require-arg?}、@var{optional-arg?} がともに @code{#f}
であっても、そのオプションの引数はオプション処理手続きに渡されることに
注意してください。オプション手続きにその引数を処理させようとします。

ショートオプションに対するオプショナルなオプションの引数は、オプションに
つづいてスペースなしで指定されたときにだけ認識されることにも
注意してください。たとえば、ショートオプション @code{d} がオプショナル
引数をもつことになっているとき、'@code{-dfoo}' は '@code{-d}' が引数
'@code{foo}' をもつと解釈されますが、'@code{-d foo}' は引数なしの
'@code{-d}' とオペランド '@code{foo}' と解釈されてしまいます。もし、
'@code{-d}' が必須引数をもつと設定されているなら、両方ともに
'@code{-dfoo}' は '@code{-d}' が引数 '@code{foo}' をもつと解釈されます。
@c COMMON
@end defun

@defun option? obj
@c MOD srfi-37
@c EN
Returns @code{#t} if @var{obj} is an option object,
@code{#f} otherwise.
@c JP
@var{obj} がオプションオブジェクトなら @code{#t} を返し、
そうでなければ、@code{#f} を返します。
@c COMMON
@end defun

@defun option-names option
@defunx option-required-arg? option
@defunx option-optional-arg? option
@defunx option-processor
@c MOD srfi-37
@c EN
Returns the properties of an option object @var{option}.
@c JP
オプションオブジェクト @var{option} のプロパティを返します。
@c COMMON
@end defun

@c EN
A simple example:
@c JP
簡単な例:
@c COMMON

@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))
@end example

@c ----------------------------------------------------------------------
@node Eager comprehensions, Vector library (Legacy), A program argument processor, Library modules - SRFIs
@section @code{srfi-42} - Eager comprehensions
@c NODE 先行評価的内包表記, @code{srfi-42} - 先行評価的内包表記

@deftp {Module} srfi-42
@mdindex srfi-42
@c EN
This module provides a generic comprehension mechanism, which some other
languages (e.g. Haskell and Python) offer as a built-in mechanism.
It provides a rich set of operators so it can be used not only as a list
generator but as a generic loop construct (actually, some may say
it is as powerful/evil as Common Lisp's @emph{loop} macro).
@c JP
このモジュールはジェネリックな内包表記(comprehension)機構を提供します。
この機構は他の言語(Haskell、Pythonなど)では組み込みの機構になっていま
す。この機構は豊富な操作手続を提供しているので、リストジェネレータとい
うだけではなく、ジェネリックなループ構文(Common Lisp の @emph{loop} マ
クロ並みに強力/邪悪だという人もいます)を提供しています。
@c COMMON

@c EN
It runs eagerly as the name suggests, that is, if it generates a list, it
creates the entire list when evaluated, instead of generate the
elements @emph{on demand}.  Thus it can't represent an infinite
sequence, which Haskell's comprehension naturally does.  Gauche offers
a few alternatives to deal with lazy, possibly infinite, sequences:
See @ref{Lazy sequences}, @ref{Generators} and @ref{Stream library}.
@c JP
この機構は名前の通り、先行評価的に走ります。すなわち、リストを生成する場合、評価時
にすべてのリストを生成します。要素を@emph{要求駆動的}に生成するわけで
はありません。それゆえ、無限列を表現することはできません。それが自然に
できる Haskell とは違います。Gaucheは、遅延生成される有限/無限列を
扱う方法を他にいくつか提供しています。
@ref{Lazy sequences}、@ref{Generators}、@ref{Stream library}を
参照してください。
@c COMMON
@end deftp

@c EN
@subheading Eager comprehension examples
@c JP
@subheading 先行評価的内包表記の例
@c COMMON

@c EN
Let's begin with some examples.
@c JP
いくつかの例からはじめましょう。
@c COMMON

@c EN
Generate a list of squares for the first five integers:
@c JP
5番目までの整数の自乗のリストを生成しましょう。
@c COMMON
@example
(list-ec (: i 5) (* i i)) @result{} (0 1 4 9 16)
@end example

@c EN
@code{list-ec} is a comprehension macro that generates a list.
The first form @code{(: i 5)} is called a @var{qualifier}, which
specifies a set of values to repeat over (here it is each integer
from 0 below 5).
The last form
@code{(* i i)} is called a @var{body}, which is an ordinary Scheme expression
evaluated for each values generated by the @var{qualifier}.
@c JP
@code{list-ec}はリストを生成する内包表記マクロです。
最初のフォーム@code{(: i 5)}は@var{qualifier}と呼ばれ、
繰り返しを行う値の集合を指定します (この例では0以上5未満の整数)。
最後のフォーム@code{(* i i)}は@var{body}と呼ばれ、
@var{qualifier}によって生成される値それぞれにつき評価される通常のScheme式です。
@c COMMON

@c EN
A comprehension can have more than one qualifiers.
Next example generate set of pair of numbers @code{(x y)}, where @code{x}
is between 2 (inclusive) and 5 (exclusive),
and @code{y} is between 1 (inclusive) and x (exclusive).
@c JP
内包表記は複数のqualifierを持つことができます。
次の例は数の対@code{(x y)}の集合を生成します。ここで@code{x}は
2以上 5未満、@code{y}は1以上 x 未満です。
@c COMMON

@example
(list-ec (: x 2 5) (: y 1 x) (list x y))
  @result{} ((2 1) (3 1) (3 2) (4 1) (4 2) (4 3))
@end example

@c EN
The qualifiers works as @emph{nested}; that is, @code{(: x 2 5)}
specifies to repeat the rest of the clauses---@code{(: y 1 x)} and
@code{(list x y)}.
@c JP
複数のqualifierはネストするように動作します。つまり、@code{(: x 2 5)}は
残りの節---@code{(: y 1 x)} および @code{(list x y)} を繰り返すように
指定しているということです。
@c COMMON

@c EN
The above two examples can be written in Haskell as the followings:
@c JP
上の2つの例はHaskellで書くと以下のようになります。
@c COMMON

@example
[ i*i   | i <- [0..4] ]
[ (x,y) | x <- [2..4], y <- [1..x-1] ]
@end example

@c EN
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.
@c JP
違いに注意：(1) Haskellでは要素になる本体部が先にきて、そのあとに修飾
部(セレクタ)がきます。SRFI-42では本体部は最後になります。(2) SRFI-42で
は範囲指定の下限はそれを含み、上限はそれを含みません。
@c COMMON

@c EN
List a set of numbers @code{(a b c d)}, where @code{a^3+b^3 = c^3+d^3}:
@c JP
@code{a^3+b^3 = c^3+d^3}を満すような数字の集合@code{(a b c d)}を列挙し
ましょう。
@c COMMON
@example
(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)))
@end example

@c EN
If you want to change values of more than one variable
simultaneously, instead of nesting, you can bundle the qualifiers
like this:
@c JP
複数の変数を(ネストするのではなく)同時に変化させたい場合は、
複数のqualifierを次のようにまとめることができます。
@c COMMON

@example
(list-ec (:parallel (: x '(a b c d)) (: y '(1 2 3 4)))
         (list x y))
  @result{} ((a 1) (b 2) (c 3) (d 4))
@end example

@c EN
You can generate not only a list, but other sequences:
@c JP
リストだけではなく、他のシーケンスも生成できます。
@c COMMON
@example
(vector-ec (: i 5) i) @result{} #(0 1 2 3 4)
(string-ec (: i 5) (integer->char (+ i 65))) @result{} "ABCDE"
@end example

@c EN
Or apply folding operations:
@example
(sum-ec (: i 1 100) i)
  @result{} 4950    ;; sum of integers from 1 below 100.
(product-ec (: i 1 10) i)
  @result{} 362880 ;; ... and product of them.
@end example
@c JP
畳み込み演算も適用できます。
@example
(sum-ec (: i 1 100) i)
  @result{} 4950    ;; 1以上100未満の整数の和
(product-ec (: i 1 10) i)
  @result{} 362880 ;;  1以上10未満の整数の積
@end example
@c COMMON

@c EN
@subheading Comprehension macros
@c JP
@subheading 内包表記マクロ
@c COMMON

@c EN
Each comprehension takes the following form.
@c JP
それぞれの内包表記は以下のような形式になります。
@c COMMON
@example
(@var{comprehension-macro} @var{qualifier} @dots{} @var{body})
@end example

@c EN
It evaluates @var{body} repeatedly as specified by @var{qualifier} @dots{}.
Depending on the type of comprehension,
the results of @var{body} may be either collected to create an
aggregate (list, vector, string, ...), folded by some operator
(sum, product, min, max, ...), or simply discarded.
@c JP
@var{qualifier} @dots{}の指定に従って@var{body}をくりかえし評価します。内包表記の種類
によって、@var{body}の結果は(リスト、ベクタ、文字列などに)集約されるか、
(sum、product、min、maxなどによって)畳み込まれるか、あるいは、単に捨て
られます。
@c COMMON

@c EN
Each @var{qualifier} specifies how to repeat the following
@var{qualifiers} and @var{body}.  A @var{qualifier} can be a
generational qualifier that yields a set of values to loop
over, or a control qualifier that specify a condition
to exclude some values.  See the Qualifiers heading below.
@c JP
それぞれの@var{qualifier}は、それ以降の@var{qualifier}と@var{body}
をどのように繰り返すかを指定します。@var{qualifier}には、繰り返しに
使う値を生成する生成的@var{qualifier}と、条件によって値を繰り返しから
省く制御的@var{qualifier}があります。以下のQualifiersの節を参照してください。
@c COMMON

@c EN
A few comprehensions takes extra values before @var{qualifiers} or
after @var{body}.
@c JP
いくつかの内包表記では、追加の値が@var{qualifiers}の前か、@var{body}
の後に置かれます。
@c COMMON

@defmac do-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
@c EN
Repeats @var{body}.  The results of @var{body} is discarded.
This is for side-effecting operations.
@c JP
@var{body}を繰り返します。@var{body}の返り値は捨てられます。
この形式は副作用目的で使います。
@c COMMON
@end defmac

@defmac list-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
@c EN
Repeats @var{body} and collects the results into a list.
@c JP
@var{body}を繰り返し、結果をリストに集めて返します。
@c COMMON
@end defmac

@defmac append-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
@c EN
Repeats @var{body}, which must yield a list.
Returns a list which is the concatenation of all lists returned by @var{body}.
@c JP
@var{body}を繰り返し、その結果のリストを結合して返します。
@var{body}は必ずリストを返さなければなりません。
@c COMMON
@end defmac

@defmac string-ec qualifier @dots{} body
@defmacx string-append-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
@c EN
Repeats @var{body}, which must yield a character (in @code{string-ec})
or a string (in @code{string-append-ec}).  Returns a string that
consists of the results of @var{body}.
@c JP
@var{body}を繰り返します。@var{body}は@code{string-ec}では文字へ、
@code{string-append-ec}では文字列へと評価されなければなりません。
結果を集め、または結合した文字列が買えされます。
@c COMMON
@end defmac

@defmac vector-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
Repeats @var{body} and collects the results into a vector.
@end defmac

@defmac vector-of-length-ec k qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
This is like @code{vector-ec}, except that the length of the
result vector is known to be @var{k}.  It can be more efficient
than @code{vector-ec}.  Unless the comprehension repeats exactly
@code{k} times, an error is signaled.
@end defmac

@defmac sum-ec qualifier @dots{} body
@defmacx product-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
@var{body} must yield a numeric value.  Returns sum of and product of
the results, respectively.
@end defmac

@defmac min-ec qualifier @dots{} body
@defmacx max-ec qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
@var{body} must yield a numeric value.  Returns maximum and minimum value
of the results, respectively.  @var{body} must be evaluated at least once,
or an error is signaled.
@end defmac

@defmac any?-ec qualifier @dots{} test
@defmacx every?-ec qualifier @dots{} test
[SRFI-42]
@c MOD srfi-42
@c EN
Evaluates @var{test} for each iteration, and returns
@code{#t} as soon as it yields non-@code{#f} (for @code{any?-ec}),
or returns @code{#f} as soon as it yields @code{#f} (for @code{every?-ec}).
Unlink the comprehensions introduced above, these stop evaluating
@var{test} as soon as the condition meets.
If the qualifiers makes no iteration, @code{#f} and @code{#t} are
returned, respectively.
@c JP
繰り返しのたびに@var{test}を評価し、@code{any?-ec}では@var{test}が偽でない
値を返したら直ちにその値を、@code{every?-ec}では@var{test}が偽を返したら
直ちに@code{#f}を、それぞれ返します。これまで上で説明してきた
内包表記とは異なり、これらは@var{test}が条件を満たしたら繰り返しを打ち切ります。
もし繰り返しが一度もなされなかった場合、それぞれ@code{#f}と@code{#t}が戻り値となります。
@c COMMON
@end defmac

@defmac first-ec default qualifier @dots{} body
@defmacx last-ec default qualifier @dots{} body
[SRFI-42]
@c MOD srfi-42
First initializes the result by the value of the expression @var{default},
then start iteration, and returns the value of the first and last
evaluation of @var{body}, respectively.  In fact, @code{first-ec}
only evaluates @var{body} at most once.

These procedures are most useful when used with control qualifiers.
For example, the following @code{first-ec} returns the @emph{first}
set of distinct integers (@var{x}, @var{y}, @var{z}),
where @var{x}*@var{x}+@var{y}*@var{y}+@var{z}*@var{z} becomes a square
of another integer @var{w}.

@example
(first-ec #f (:integers w) (: z 1 w) (: y 1 z) (: x 1 y)
          (if (= (* w w) (+ (* x x) (* y y) (* z z))))
          (list x y z w))
@end example

Note that the first qualifier, @code{(:integers w)}, generates
infinite number of integers; if you use @code{list-ec} instead of
@code{first-ec} it won't stop.
@end defmac

@defmac fold-ec seed qualifier @dots{} expr proc
@defmacx fold3-ec seed qualifier @dots{} expr init proc
[SRFI-42]
@c MOD srfi-42
Reduces the values produced by @var{expr}.

Suppose @var{expr} produces a sequence of values
@var{x0}, @var{x1}, @dots{}, @var{xN}.  @code{Fold-ec}
calculates the following value:

@example
(@var{proc} @var{xN} (@dots{}(@var{proc} @var{x1} (@var{proc} @var{x0} @var{seed}))@dots{}))
@end example

It's similar to @code{fold}, except that @var{proc} is evaluated
within the scope of @var{qualifier} @dots{} so you can refer to the
variables introduced by them.  On the other hand,
@var{seed} is outside of the scope of @var{qualifier}s.

@code{Fold-ec3} is almost the same but the initial value calculation.
In @code{fold-ec3}, @var{seed} is only used when @var{qualifier}s
makes no iteration.  Otherwise it calculates the following value:

@example
(@var{proc} @var{xN} (@dots{}(@var{proc} @var{x1} (@var{init} @var{x0}))@dots{}))
@end example

@end defmac

@subheading Qualifiers

@c EN
@subsubheading Generational qualifiers
@c JP
@subsubheading 生成的qualifier
@c COMMON

@c EN
This type of qualifiers generates (possibly infinite) values
over which the rest of clauses iterate.
@c JP
このタイプのqualifierは、いくつかの値(無限個のこともあります)を次々に
生成し、各値について残りの節を繰り返します。
@c COMMON

@c EN
In the following descriptions, @var{vars} refers to either
a single identifier, or a series of identifier and a form
@code{(index @var{identifier2})}.  The single identifier
in the former case and the first identifier in the latter case
name the variable to which each generated value is bound.
The @var{identifier2} in the latter case names a variable
to which a series of integers, increasing with each generated
element, is bound.   See the following example:
@c JP
以下の説明において、@var{vars}というのはひとつの識別子か、
識別子とフォーム@code{(index @var{identifier2})}の並びです。
最初の形式での識別子、あるいは二番目の形式での最初の識別子は、
生成された値が束縛される変数です。二番目の形式の@var{identifier2}は、
0から始まり値が生成されるたびにインクリメントされる整数値が束縛されます。
次の例を見てください。
@c COMMON

@example
(list-ec (: x '(a b c)) x)
  @result{} (a b c)
(list-ec (: x (index y) '(a b c)) (cons x y))
  @result{} ((a . 0) (b . 1) (c . 2))
@end example

@deffn {EC Qualifier} : vars arg1 args @dots{}
@c EN
A generic dispatcher of generational qualifiers.
An appropriate generational qualifier is selected based on the
types of @var{arg1} @var{args} @dots{}.
@c JP
@var{arg1} @var{args} @dots{} の型に基づいて、以下の生成的qualifierの
いずれかにディスパッチされる、汎用的なqualifierです。
@c COMMON
@end deffn

@deffn {EC Qualifier} :list vars arg1 args @dots{}
@deffnx {EC Qualifier} :vector vars arg1 args @dots{}
@deffnx {EC Qualifier} :uvector vars arg1 args @dots{}
@deffnx {EC Qualifier} :string vars arg1 args @dots{}
@c EN
@var{Arg1} @var{args} @dots{} should be all lists, vectors, uniform vectors
or strings,
respectively.  Repeats the subsequent clauses while binding
each element from those args bound to @var{vars}.
(The @code{:uvector} qualifier is Gauche's extension.)
@c JP
それぞれのフォームにおいて、
@var{arg1} @var{args} @dots{}は全てリスト、ベクタ、ユニフォームベクタ、
あるいは文字列でなければなりません。
各要素を@var{vars}に束縛して続く節を繰り返します。
(@code{:uvector}はGaucheの独自拡張です。)
@c COMMON

@example
(list-ec (:string c "ab" "cd") c) @result{} (#\a #\b #\c #\d)
@end example

@c EN
If the arguments given to the generic qualifier @code{:} are
all lists, vectors, uniform vectors or strings, then these qualifiers are used.
@c JP
汎用qualifier@code{:}に渡された引数が全てリスト、ベクタ、ユニフォームベクタあるいは文字列
であった場合は、これらのqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :integers vars
@c EN
Generates infinite series of increasing integers, starting from 0.
@c JP
0から始まり1づつ増加しつづける無限正確整数列を生成します。
@c COMMON
@end deffn

@deffn {EC Qualifier} :range vars stop
@deffnx {EC Qualifier} :range vars start stop
@deffnx {EC Qualifier} :range vars start stop step
@c EN
Generates a series of exact integers, starting from
@var{start} (defaults to 0) and stops below @var{stop},
stepping by @var{step} (defaults to 1).  Giving a negative
integer to @var{step} makes a decreasing series.
@c JP
@var{start}から始まり、@var{step}づつ増加し、@var{stop}を越えないような
正確な整数列を生成します。@var{start}が省略された場合は0、
@var{step}が省略された場合は1が使われます。
@var{step}に負数を与えれば減少列も作れます。
@c COMMON

@example
(list-ec (:range v 5) v)      @result{} (0 1 2 3 4)
(list-ec (:range v 3 8) v)    @result{} (3 4 5 6 7)
(list-ec (:range v 1 8 2) v)  @result{} (1 3 5 7)
(list-ec (:range v 8 1 -2) v) @result{} (8 6 4 2)
@end example

@c EN
If one, two or three exact integer(s) is/are given to the generic
qualifier @code{:}, this qualifier is used.
@c JP
汎用qualifier@code{:}に1個から3個の正確な整数が与えられた場合は、
このqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :real-range vars stop
@deffnx {EC Qualifier} :real-range vars start stop
@deffnx {EC Qualifier} :real-range vars start stop step
@c EN
Generates a series of real numbers, starting from
@var{start} (defaults to 0) and stops below @var{stop},
stepping by @var{step} (defaults to 1).  If all the arguments
are exact numbers, the result consists of exact numbers; if any
of the arguments are inexact, the result consists of inexact numbers.
@c JP
@var{start}から始まり、@var{step}づつ増加し、@var{stop}を越えないような
実数列を生成します。@var{start}が省略された場合は0、
@var{step}が省略された場合は1が使われます。
全ての引数が正確数であれば正確な数列が、ひとつでも非正確数が混じって入れば
非正確な数列が生成されます。
@c COMMON

@example
(list-ec (:real-range v 5.0) v)
  @result{} (0.0 1.0 2.0 3.0 4.0)
(list-ec (:real-range v 1 4 1/3) v)
  @result{} (1 4/3 5/3 2 7/3 8/3 3 10/3 11/3)
(list-ec (:real-range v 1 5.0 1/2) v)
  @result{} (1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5)
@end example

@c EN
If one, two or three real numbers is/are given to the generic
qualifier @code{:}, and any one of them isn't an exact integer,
then this qualifier is used.
@c JP
汎用qualifier@code{:}に1個から3個の実数が与えられ、そのうちどれかひとつでも
正確な整数でないものがあれば、このqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :char-range vars min max
@c EN
Generates a series of characters, starting from @var{min} and
ending at @var{max} (inclusive).  The characters are enumerated
in the order defined by @code{char<=?} (@pxref{Characters}).
@c JP
文字@var{min}から@var{max}まで(両端含む)の文字を順に生成します。
文字順は@code{char<=?}で比べられるのと同じ順になります (@ref{Characters}参照)。
@c COMMON

@example
(list-ec (:char-range v #\a #\e) v)
  @result{} (#\a #\b #\c #\d #\e)
@end example

@c EN
If two characters are given to the generic
qualifier @code{:}, this qualifier is used.
@c JP
汎用qualifier@code{:}に2つの文字が与えられた場合は、
このqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :port vars port
@deffnx {EC Qualifier} :port vars port read-proc
@c EN
Generates a series of values read from an input port @var{port},
by the procedure @var{read-proc} (defaults to @code{read}).  The
series terminates when EOF is read.
@c JP
入力ポート@var{port}から、@var{read-proc}を使って読まれる値を、
EOFに出会うまで次々に生成します。@var{read-proc}が省略された場合は@code{read}
が使われます。
@c COMMON

@example
(call-with-input-string "a \"b\" :c"
  (^p (list-ec (:port v p) v)))
  @result{} (a "b" :c)
@end example

@c EN
If one or two arguments are given to the generic
qualifier @code{:} and the first one is an input port,
then this qualifier is used.
@c JP
汎用qualifier@code{:}に2つの引数が与えられ、最初の引数が入力ポートであれば、
このqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :generator vars gen
@c EN
This is Gauche's extension and not defined in SRFI-42.
@var{gen} must be a procedure with zero arguments.
This qualifier repeats until @var{gen} returns EOF.

Gauche has a set of utilities to create and operate on
such procedures; see @ref{Generators}.
@c JP
これはSRFI-42には定義さていない、Gauche独自の拡張です。
@var{gen}は引数と取らない手続きです。このqualifierは
@var{gen}がEOFを返すまで繰り返します。

Gaucheは、そのような手続きを作ったり操作したりする便利な関数群を
提供しています。@ref{Generators}を参照してください。
@c COMMON

@example
(use gauche.generator)
(list-ec (:generator v (grange 1 8)) v)
  @result{} (1 2 3 4 5 6 7)
@end example

@c EN
If one argument is given to the generic
qualifier @code{:} and it is applicable without arguments,
then this qualifier is used.
@c JP
汎用qualifier@code{:}に1つの引数が与えられ、それが引数無しで呼び出し可能なものであれば、
このqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :collection vars coll
@c EN
This is Gauche's extension and not defined in SRFI-42.
@var{coll} must be an instance of @code{<collection>} or its subclass.
(@pxref{Collection framework}).
This qualifier repeats over the elements in the collection.

If srfi-42 has a specialized qualifier, it is faster to use it
(e.g. a vector is also a collection, but using @code{:vector} is
faster than @code{:collection}).
@c JP
これはSRFI-42には定義さていない、Gauche独自の拡張です。
@var{coll}は@code{<collection>}クラスかそのサブクラスのインスタンスでなければなりません
(@ref{Collection framework}参照)。
このqualifierはコレクションの各要素に対して繰り返します。

特定の型に特化したqualifierがある場合はそちらを使う方が速いです
(例えば、ベクタはコレクションでもありますが、@code{:collection}を使うより
@code{:vector}を使う方が速いです。)
@c COMMON

@c EN
If one argument is given to the generic
qualifier @code{:} and it is a collection other than the specific
types suppored directly in srfi-42, this qualifer is used.
@c JP
汎用qualifier@code{:}に1つの引数が与えられ、
それがsrfi-42で用意されている型以外のコレクションであれば、
このqualifierが使われます。
@c COMMON
@end deffn

@deffn {EC Qualifier} :parallel generator @dots{}
@c EN
This is used to run through multiple generators in parallel.
It terminates when any one of @var{generator} is exhausted.
@c JP
複数のジェネレータ節を並列に走査するのに使います。
@var{generator}のどれかが値を使い切った時点で止まります。
@c COMMON

@example
(list-ec (:parallel (: x '(a b c))
                    (: y "defg"))
  (cons x y))
 @result{} ((a . #\d) (b . #\e) (c . #\f))

;; Compare with this:
(list-ec (: x '(a b c))
         (: y "defg")
  (cons x y))
 @result{} ((a . #\d) (a . #\e) (a . #\f) (a . #\g)
     (b . #\d) (b . #\e) (b . #\f) (b . #\g)
     (c . #\d) (c . #\e) (c . #\f) (c . #\g))
@end example
@end deffn

@deffn {EC Qualifier} :let vars expr
@c EN
Evaluate @var{expr}, and bind the result to @var{vars} and execure
the following clauses once.
If @var{vars} has an index var, it is bound to 0.
It is effectively the same as @code{(:list vars (list expr))}.
@c JP
@var{expr}を評価し、その値を@var{vars}に束縛して1回だけ以降の節を実行します。
@var{vars}にインデックス変数があればそれは0に束縛されます。
実効的には@code{(:list vars (list expr))}と同じです。
@c COMMON
@end deffn

@deffn {EC Qualifier} :while g-qualifier expr
@deffnx {EC Qualifier} :until generator expr
@c EN
Generates values from  @var{g-qualifier} while/until @var{expr} evaluates true. 
Here, @var{g-qualifier} is one of generative EC qualifiers.  The variable
bound in @var{g-qualifier} is visible from @var{expr}.
@c JP
@var{g-qualifier}は生成的qualifierです。@var{g-qualifier}が生成する値によって
@var{expr}が真の値である間/真の値になるまで、値を生成しつづけます。@var{expr}内では
@var{g-qualifier}が束縛する変数が使えます。
@c COMMON

@c EN
@c JP
@c COMMON

@example
(use math.prime)
(sum-ec (:while (: p (index k) *primes*) (<= k 100)) p)
@end example
@end deffn


@deffn {EC Qualifier} :dispatched vars dispatch arg1 args @dots{}
@end deffn

@deffn {EC Qualifier} :do (lb @dots{}) ne1? (ls @dots{})
@deffnx {EC Qualifier} :do (let (ob @dots{}) oc @dots{}) (lb @dots{}) ne1? (let (ib @dots{}) ic @dots{}) ne2? (ls @dots{})
@end deffn

@subsubheading Control qualifiers

@deffn {EC Qualifier} if test
@end deffn

@deffn {EC Qualifier} not test
@deffnx {EC Qualifier} and test @dots{}
@deffnx {EC Qualifier} or test @dots{}
@end deffn

@deffn {EC Qualifier} begin command @dots{} expr
@end deffn

@deffn {EC Qualifier} nested qualifier @dots{}
@end deffn


@c ----------------------------------------------------------------------
@node Vector library (Legacy), Requiring extensions, Eager comprehensions, Library modules - SRFIs
@section @code{srfi-43} - Vector library (legacy)
@c NODE ベクタライブラリ(旧式), @code{srfi-43} - ベクタライブラリ(旧式)

@deftp {Module} srfi-43
@mdindex srfi-43
@c EN
This module is effectively superseded by R7RS and @code{srfi-133}.  
There are a few procedures that are not compatible with R7RS and 
@code{srfi-133}, and this module remains to support
legacy code that depends on them.  

@xref{Vectors}, and @pxref{R7RS vectors}, for the ``modern'' versions
of vector library.  New code should use them.

The following procedures in srfi-43 are built-in.
@xref{Vectors}, for the description.
@c JP
このモジュールは実効的に、R7RSと@code{srfi-133}に取って代わられています。
いくつかの手続きはR7RSや@code{srfi-133}の同名の手続きとは非互換で、
このモジュールは@code{srfi-43}に依存している既存のコードのためだけに
残されています。

「現代的な」ベクタライブラリは、@ref{Vectors}と@ref{R7RS vectors}
で説明されています。新たなコードはそちらを使うべきです。

以下の@code{srfi-43}の手続きは組み込みになっています。
説明は@ref{Vectors}を参照してください。
@c COMMON

@example
make-vector     vector          vector?         vector-ref
vector-set!     vector-length   vector-fill!    vector-copy
vector-copy!    vector-append   vector->list    list->vector
reverse-list->vector
@end example

@c EN
The following procedures in srfi-43 are supported by srfi-133.
@xref{R7RS vectors}, for the description.
@c JP
以下の@code{srfi-43}の手続きは@code{srfi-133}でも同様にサポートされています。
説明は@ref{R7RS vectors}を参照してください。
@c COMMON

@example
vector-unfold         vector-unfold-right   vector-reverse-copy
vector-reverse-copy!  vector-concatenate    vector-empty?
vector=               vector-index          vector-index-right
vector-skip           vector-skip-right     vector-binary-search
vector-any            vector-every          vector-swap!    
reverse-vector->list
@end example

@c EN
We explain the procedures that are not listed above.
@c JP
ここでは上に挙げられていない手続きを説明します。
@c COMMON
@end deftp

@defun vector-fold kons knil vec1 vec2 @dots{}
@defunx vector-fold-right kons knil vec1 vec2 @dots{}
[SRFI-43]
@c MOD srfi-43
@c EN
Like @code{vector-fold} and @code{vector-fold-right}
in @code{srfi-133}, but @var{kons}
takes an extra argument, the current index, as its first argument.
So @var{kons} must accept @var{n}+2 arguments, where
@var{n} is the number of given vectors.
It is called as @code{(kons <index> <cumulated-value> <elt1> <elt2> ...)}.
@c JP
@code{srfi-133}の@code{vector-fold}と@code{vector-fold-right}と似ていますが、
@var{kons}手続きは追加で、現在のインデックスを第一引数として取ります。
従って、@var{n}を引数で与えられたベクタの数とすると、
@var{kons}は@var{n+2}個の引数を取らなければなりません。
@var{kons}は@code{(kons <index> <cumulated-value> <elt1> <elt2> ...)}
のように呼ばれます。
@c COMMON

@c EN
Gauche has @code{fold-with-index} (@pxref{Mapping over sequences})
that can be used to fold vectors with index, but the argument order
of @var{kons} is slightly different: It passes the index, each
element from argument vectors, then cumulated values.  
@c JP
Gaucheには@code{fold-with-index}があって、ベクタをインデックスつきで
foldするのに使えます(@ref{Mapping over sequences})が、
@var{kons}が受け取る引数の順序が違います: インデックスの次に
各ベクタの要素、そして最後に累積された値が来ます。
@c COMMON

@example
(use srfi-43)
(vector-fold list '() '#(a b c) '#(d e f))
  @result{} (2 (1 (0 () a d) b e) c f)

(use gauche.sequence)
(fold-with-index list '() '#(a b c) '#(d e f))
  @result{} (2 c f (1 b e (0 a d ())))
@end example
@end defun

@defun vector-map f vec1 vec2 @dots{}
@defunx vector-map! f vec1 vec2 @dots{}
@defunx vector-for-each f vec1 vec2 @dots{}
@defunx vector-count f vec1 vec2 @dots{}
[SRFI-43]
@c MOD srfi-43
@c EN
Like @code{vector-map} and @code{vector-for-each} of R7RS,
and @code{vector-map!} and @code{vector-count} in @code{srfi-133},
except @var{f} takes
an extra argument, the current index, as its first argument.
@c JP
R7RSの@code{vector-map}および@code{vector-for-each}、
そして@code{srfi-133}の@code{vector-map!}および@code{vector-cout}と
ほぼ同じですが、@var{f}が現在のインデックスを最初の引数として(他の引数より前に)
取ります。
@c COMMON

@c EN
Gauche provides @code{vector-map-with-index},
@code{vector-map-with-index!} and @code{vector-for-each-with-index}
which are the same as @code{srfi-43}'s @code{vector-map}, @code{vector-map!}
and @code{vector-for-each}, respectively.  @xref{Vectors}.
@c JP
Gaucheは@code{srfi-43}の@code{vector-map}、@code{vector-map!}、
@code{vector-for-each}互換な手続きをそれぞれ
@code{vector-map-with-index}、
@code{vector-map-with-index!}、@code{vector-for-each-with-index}という
名前で提供しています。@ref{Vectors}参照。
@c COMMON

@example
(vector-map list '#(a b c))
 @result{} #((0 a) (1 b) (2 c))
(vector-map list '#(a b c) '#(d e f g))
 @result{} #((0 a d) (1 b e) (2 c f))
(vector-count = '#(0 2 2 4 4))
 @result{} 3
@end example

@c EN
(Note: The @code{vector-count} example calls @code{=} with
two arguments, the current index and the element, for each element
of the input vector.  So it counts the number of
occasions when the element is equal to the index.)
@c JP
(註: @code{vector-count}は@code{=}を二つの引数、現在のインデックスと
ベクタの要素で呼び出します。従ってこの例は、ベクタの要素がインデックスと一致する
場合を数えています。)
@c COMMON

@c EN
The generic @code{map} and @code{for-each}
in @code{gauche.collection} can be used
on vectors, but the mapped procedure is called without index, and the result
is returned as a list.
@code{(vector-map f vec1 vec2 @dots{})} is operationally equivalent to
@code{(map-to-with-index <vector> f vec1 vec2 @dots{})}.
See @ref{Collection framework} and @ref{Sequence framework}.
@c JP
@code{gauche.collection}のジェネリックな@code{map}や@code{for-each}は
ベクタに対しても使えますが、マップされる手続きはインデックスを取らず、
また結果はリストになります。
@code{(vector-map f vec1 vec2 @dots{})}は機能的には
@code{(map-to-with-index <vector> f vec1 vec2 @dots{})}と同じになります。
詳しくは@ref{Collection framework}と@ref{Sequence framework}を参照してください。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node Requiring extensions, Integers as bits, Vector library (Legacy), Library modules - SRFIs
@section @code{srfi-55} - Requiring extensions
@c NODE Requiring extensions, @code{srfi-55} - require の拡張

@deftp {Module} srfi-55
@mdindex srfi-55
@c EN
This module defines @code{require-extension} macro, a yet another way
to write portable scripts.  See @ref{Feature conditional} and
@ref{Feature-based program configuration language} for other means of
ensuring specific features.
@c JP
このモジュールでは @code{require-extension} マクロが定義されています。
これは、ポータブルなスクリプトを書くためのもうひとつ別の方法です。
指定した特性を確認する他の方法については、@ref{Feature conditional}
および@ref{Feature-based program configuration language}を見てください。
@c COMMON

@c EN
This module is autoloaded when you use @code{require-extension}, so
you don't need explicitly say @code{(use srfi-55)}; for portable scripts,
you shouldn't.
@c JP
このモジュールは、@code{require-extension}を使った際に自動的にロードさ
れます。それゆえ明示的に@code{(use srfi-55)}する必要はありませんし、ポー
タビリティのためにはするべきではありません。
@c COMMON
@end deftp

@defmac require-extension clause @dots{}
@c MOD srfi-55
@c EN
Make extension(s) specified by @var{clause}s available in the rest
of the program.
@c JP
@var{clause}で指定した拡張を以降のプログラムで利用可能にします。
@c COMMON

@c EN
A @var{clause} takes the following form:
@c JP
@var{clause}は以下の形式になります。
@c COMMON
@example
(@var{extension-id} @var{extension-arg} @dots{})
@end example

@c EN
Currently, only @code{srfi} is supported as @var{extension-id}, and
its arguments are SRFI numbers.
@c JP
現時点では、@code{srfi}のみ@var{extension-id}として使えます。その引数
はSRFIの番号です。
@c COMMON

@c EN
For example, the following form:
@c JP
たとえば、以下の
@c COMMON
@example
(require-extension (srfi 1 13 14))
@end example

@c EN
Roughly corresponds to Gauche's @code{use} forms:
@c JP
は以下の Gauche の @code{use} 形式にほぼ対応します。
@c COMMON
@example
(use srfi-1)
(use srfi-13)
(use srfi-14)
@end example
@end defmac

@c ----------------------------------------------------------------------
@node Integers as bits, A Scheme API for test suites, Requiring extensions, Library modules - SRFIs
@section @code{srfi-60} - Integers as bits
@c NODE 整数に対するビット操作, @code{srfi-60} - 整数に対するビット操作

@deftp {Module} srfi-60
@mdindex srfi-60
This srfi provides bit operations on integers, regarding them
as 2's complement representation.  It is compatible to SLIB's @code{logical}
module.

The newer srfi-151 (@pxref{R7RS bitwise operations}) provides the same
functionality and more, with more consistent naming.  We recommend
new code to use srfi-151, while we keep srfi-60 for the backward
compatibility.

The following procedures are Gauche built-in.
@xref{Basic bitwise operations}, for the description.

@example
lognot           logand           logior           logxor
logtest          logcount         integer-length   logbit?
copy-bit         bit-field        copy-bit-field   ash
@end example

The following procedures are defined in srfi-151.
@xref{R7RS bitwise operations}, for the description.

@example
bitwise-not      bitwise-and      bitwise-ior      bitwise-xor
arithmetic-shift bit-count        bitwise-if       bit-set?
copy-bit         first-set-bit    
@end example
@end deftp

We describe procedures that are unique in srfi-60 below.

@defun bitwise-merge mask n0 n1
[SRFI-60]
@c MOD srfi-60
Same as @code{bitwise-if} (@pxref{R7RS bitwise operations}).
@end defun

@defun any-bits-set? mask n
[SRFI-60]
@c MOD srfi-60
Same as builtin @code{logtest} (@pxref{Basic bitwise operations}).
It is also called @code{any-bit-set?} in srfi-151 (@pxref{R7RS bitwise operations}).
@end defun

@defun log2-binary-factors n
[SRFI-60]
@c MOD srfi-60
It is also called as @code{first-set-bit} in this srfi, which is also
in srfi-151 (@pxref{R7RS bitwise operations}).
This is equivalent to Gauche's built-in  @code{twos-exponent-factor}
(@pxref{Basic bitwise operations}).
@end defun

@defun rotate-bit-field n count start end
[SRFI-60]
@c MOD srfi-60
This is equivalent to @code{bit-field-rotate} in srfi-151
(@pxref{R7RS bitwise operations}).
@end defun

@defun reverse-bit-field n start end
[SRFI-60]
@c MOD srfi-60
This is equivalent to @code{bit-field-reverse} in srfi-151
(@pxref{R7RS bitwise operations}).
@end defun

@defun integer->list n :optional len
[SRFI-60]
@c MOD srfi-60
Breaks @var{n} to each bits, representing @code{1} as @code{#t} and
@code{0} as @code{#f}, LSB last, and returns a list of them.
If a nonnegative integer @var{len} is given, it specifies the length
of the result.   If it is omitted, @code{(integer-length n)} is used.

@example
(integer->list 10)   @result{} (#t #f #t #f)
(integer->list 10 6) @result{} (#f #f #t #f #t #f)
@end example

Srfi-151 has similar procedure @code{bits->list}, with a reversed bit
order (LSB first) (@pxref{R7RS bitwise operations}).
@end defun

@defun list->integer lis
[SRFI-60]
@c MOD srfi-60
Takes a list of boolean values, replaces the true value for @code{1}
and the false value for @code{0}, and compose an integer regarding
each value as a binary digit.  If @var{n} is nonnegative integer,
@code{(eqv? (list->integer (integer->list n)) n)} is true.

@example
(list->integer '(#f #t #f #t #f)) @result{} 10
@end example

Srfi-151 has similar procedure @code{list->bits}, with a reversed bit
order (LSB first) (@pxref{R7RS bitwise operations}).
@end defun

@defun booleans->integer bool @dots{}
[SRFI-60]
@c MOD srfi-60
@equiv{} @code{(list->integer (list @var{bool} @dots{}))}

Srfi-151 has similar procedure @code{bits}, with a reversed bit
order (LSB first) (@pxref{R7RS bitwise operations}).
@end defun

@c ----------------------------------------------------------------------
@node A Scheme API for test suites, Octet vectors, Integers as bits, Library modules - SRFIs
@section @code{srfi-64} - A Scheme API for test suites
@c NODE SchemeテストスイートAPI, @code{srfi-64} - SchemeテストスイートAPI

@deftp {Module} srfi-64
@mdindex srfi-64
This module defines API to write a portable test suite.  In Gauche,
it is adapted to work with @code{gauche.test} native test framework
(@pxref{Unit testing}).

If srfi-64 tests are run with the default runner during @code{gauche.test}
is active, the tests becomes a part of the whole @code{gauche.test} suite.

The recommended way is to write a test suite in pure srfi-64, then include
it from the gauche test script:

@example
(use gauche.test)
(test-start "the tests")
;; portable test
(include "test-suite-in-srfi-64")

;; gauche-specific test, if needed
...

(test-end)
@end example

If @file{test-suite-in-srfi-64.scm} is run by itself, it uses srfi-64's
default reporting system.  If it is run within @code{gauche.test} script,
the results are reported via @code{gauche.test}, consolidated with other
Gauche test results.
@end deftp

@menu
* Srfi-64 test API::
* Srfi-64 test runner::
@end menu

@node Srfi-64 test API, Srfi-64 test runner, A Scheme API for test suites, A Scheme API for test suites
@subsection Test API

@node Srfi-64 test runner,  , Srfi-64 test API, A Scheme API for test suites
@subsection Test runner


@c ----------------------------------------------------------------------
@node Octet vectors, Basic hash tables, A Scheme API for test suites, Library modules - SRFIs
@section @code{srfi-66} - Octet vectors
@c NODE オクテットベクタ, @code{srfi-66} - オクテットベクタ

@deftp {Module} srfi-66
@mdindex srfi-66
@c EN
This module defines procedures to deal with @code{u8vector}s; they are
almost a subset of @code{srfi-160} and @code{gauche.uvector}
(@pxref{Uniform vectors}, except one procedure, @code{u8vector-copy!},
which has different argument orders (unfortunate historical artifacts).
@c JP
このモジュールは@code{u8vector}に特化した手続きを定義します。
ほぼ@code{srfi-160}および@code{gauche.uvector}のサブセットです。
(@pxref{Uniform vectors})。例外は@code{u8vector-copy!}で、
これは不幸な歴史的事情から、@code{gauche.uvector}と引数順が異なります。
@c COMMON

@c EN
There's no reason to use this srfi except porting code that relies
on @code{srfi-66}.
@c JP
@var{srfi-66}に依存するコードを移植するのでなければ、
このモジュールを使う場面は無いでしょう。
@c COMMON

@c EN
The following procedures are the same as @code{gauche.uvector}:
@c JP
以下の手続きは@code{gauche.uvector}と同じです。
@c COMMON

@example
u8vector?       make-u8vector      u8vector
u8vector->list  list->u8vector
u8vector-length u8vector-ref       u8vector-set!
u8vector=?      u8vector-compare   u8vector-copy
@end example
@end deftp

@defun u8vector-copy! src sstart target tstart n
[SRFI-66]
@c MOD srfi-66
@c EN
Copy the content of an u8vector @var{src}, starting from @var{sstart}
for @var{n} octets, into an u8vector @var{target} beginning from
@var{tstart}.  The @var{target} u8vector must be mutable.
@c JP
u8vectorである@var{src}の、インデックス@var{sstart}から@var{n}オクテットを、
u8vector @var{target}のインデックス@var{tstart}からにコピーします。
@var{target}は変更可能なu8vectorでなければなりません。
@c COMMON

@c EN
Note that @code{gauche.uvector} has also @code{u8vector-copy!},
but its argument order is as follows, where @var{send} 
is @code{(+ @var{sstart} @var{n})}:
@c JP
@code{gauche.uvector}も@code{u8vector-copy!}を提供しますが、
引数が異なります。@var{send}を@code{(+ @var{sstart} @var{n})}として、
次のとおりです:
@c COMMON

@example
(u8vector-copy! target tstart src sstart send)
@end example

@c EN
Gauche's argument order is consistent with @code{vector-copy!} of
R7RS, srfi-43 and srfi-133.

We recommend to use @code{srfi-66} only for porting third-party
libraries to avoid confusion.
@c JP
Gaucheの引数順は、R7RS、srfi-43およびsrfi-133の@var{vector-copy!}と
一貫性があります。

混乱を避けるため、
@code{srfi-66}モジュールはサードパーティライブラリを移植する際に必要な場合に限り
使うと良いでしょう。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node Basic hash tables, Octet-addressed binary blocks, Octet vectors, Library modules - SRFIs
@section @code{srfi-69} - Basic hash tables
@c NODE 基本的なハッシュテーブル, @code{srfi-69} - 基本的なハッシュテーブル

@deftp {Module} srfi-69
@mdindex srfi-69
This module has been superseded by R7RS @code{scheme.hash-table}
(@pxref{R7RS hash tables}).  New code should use it instead.

This is a thin adaptor on Gauche's built-in hashtables
(@pxref{Hashtables}).  This is provided for the compatibility
to the portable libraries; the hashtable object created by
this module's @code{make-hash-table} is the same as the one
created by Gauche's built-in, and you can pass the table to
both APIs.
@end deftp

Here's a summary of difference between srfi-69 and Gauche's built-in
hash table API:

@itemize
@item
The constructor @code{make-hash-table}, as well as @code{alist->hash-table},
takes equality predicate and hash function, instead of a single
comparator argument.
@item
The hash function passed to @code{srfi-69}'s @code{make-hash-table}
takes two arguments, an object to calculate a hash value,
and a positive integer that limits the range of the hash value.
@item
@code{Srfi-69}'s primary hash table accessor is @code{hash-table-ref},
which takes a thunk to be called when the table doesn't have an
entry for the given key, while Gauche's @code{hash-table-get} takes
a fallback value for that.
@code{Srfi-69} also has @code{hash-table-ref/default},
which takes a fallback value like Gauche's @code{hash-table-get},
but the default value can't be omitted.
@item
The basic iterator of @code{srfi-69} is called @code{hash-table-walk},
which is Gauche's @code{hash-table-for-each}.  The srfi name is chosen
to avoid conflict with existing Scheme implementations.
@end itemize

The following procedures are the same as Gauche's built-in ones.
@xref{Hashtables}, for the details.

@example
hash-table?       hash-table-delete!   hash-table-exists?
hash-table-keys   hash-table-values    hash-table-fold
hash-table->alist hash-table-copy 
@end example


@defun make-hash-table :optional eq-pred hash-proc :rest args
[SRFI-69]
@c MOD srfi-69
Creates a new hashtable and returns it.  This is the same name
as Gauche's built-in procedure, but the arguments are different.

The @var{eq-pred} argument is an equality predicate; it takes
two arguments and returns @code{#t} if two are the same,
and @code{#f} if not.  When omitted, @code{equal?} is used.

The @var{hash-proc} argument is a hash function.
It takes two arguments: an object to hash, and a positive
integer to limit the range of the hash value.  (Note that
Gauche's native hash functions takes only one argument.)
When omitted, Gauche tries to choose appropriate hash function
if @code{eq-pred} is known one (@code{eq?}, @code{eqv?},
@code{equal?}, @code{string=?} or @code{string-ci=?}).
Otherwise we use Gauche's @code{hash} procedure, but there's
no guarantee that it works appropriately; you should give
suitable @var{hash-proc} if you pass custom @var{eq-pred}.

The returned hash table is an instance of Gauche's native
hash table.  You can pass it to Gauche's builtin procedures.

@code{Srfi-69} allows implementation-specific arguments @var{args} to be
passed to @code{make-hash-table}.  At this moment, Gauche
ignores them.
@end defun

@defun alist->hash-table alist :optional eq-pred hash-fn :rest args
[SRFI-69]
@c MOD srfi-69
Like Gauche's builtin @code{alist->hash-table}, but takes
@var{eq-pred} and @var{hash-fn} separately,
instead of a single comparator.

The @var{alist} argument is a list of pairs.  The car of each
pair is used for a key, and the cdr for its value.

See @code{make-hash-table} above for the description of
@var{eq-pred}, @var{hash-fn} and @var{args}.
@end defun

@defun hash-table-equivalence-function ht
@defunx hash-table-hash-function ht
[SRFI-69]
@c MOD srfi-69
Returns equivalence function and hash function of the
hashtable @var{ht}.

The hash function returned from @code{hash-table-hash-function}
takes two arguments, an object to hash and bound, a positive exact integer.
Note that the function returned by @code{hash-table-hash-function} may not
be @code{eq?} to the one you gave to @code{make-hash-table}.
@end defun

@defun hash-table-ref ht key :optional thunk
[SRFI-69]
@c MOD srfi-69
Looks up the value corresponding to @var{key} in a hash table @var{ht}.
If there's no entry for @var{key}, @var{thunk} is called
without arguments.  The default of @var{thunk} is to signal an error.
@end defun

@defun hash-table-ref/default ht key default
[SRFI-69]
@c MOD srfi-69
Looks up the value corresponding to @var{key} in a hash table @var{ht}.
This is like Gauche's @code{hash-table-get}, but @var{default} can't be
omitted.
@end defun

@defun hash-table-set! ht key val
[SRFI-69]
@c MOD srfi-69
This is the same as Gauche's @code{hash-table-put!}.
@end defun

@defun hash-table-update! ht key proc :optional thunk
@defunx hash-table-update!/default ht key proc default
[SRFI-69]
@c MOD srfi-69
@end defun

@defun hash-table-size ht
[SRFI-69]
@c MOD srfi-69
Returns the number of entries in a hash table @var{ht}.  The same as Gauche's
@code{hash-table-num-entries}.
@end defun
          
@defun hash-table-walk ht proc
[SRFI-69]
@c MOD srfi-69
For each entry in a hash table @var{ht}, 
calls @var{proc} with two arguments, a key and its value.
It's the same as Gauche's @code{hash-table-for-each}.
@end defun

@defun hash-table-merge! ht1 ht2
[SRFI-69]
@c MOD srfi-69
Add all entries in a hash table @var{ht2} into a hash table @var{ht1},
and returns @var{ht1}.
@end defun

@defun hash obj :optional bound
[SRFI-69]
@c MOD srfi-69
Like Gauche's @code{hash}, except this one can take bound argument;
if provided, it must be a positive integer, and the return value
is limited between 0 and @code{(- bound 1)}, inclusive.
@end defun

@defun string-hash obj :optional bound
@defunx string-ci-hash obj :optional bound
[SRFI-69]
@c MOD srfi-69
These are like @code{srfi-13}'s (@pxref{String library}), except
these don't take @var{start} and @var{end} argument.
@end defun

@defun hash-by-identity obj :optional bound
[SRFI-69]
@c MOD srfi-69
This is Gauche's @code{eq-hash}, except this one can take bound argument.
@end defun

@c ----------------------------------------------------------------------
@node Octet-addressed binary blocks, Lightweight testing, Basic hash tables, Library modules - SRFIs
@section @code{srfi-74} - Octet-addressed binary blocks

@deftp {Module} srfi-74
@mdindex srfi-74
This module provides procedures to deal with @emph{blob},
or a sequence of octets.  In Gauche, a blob is simply an u8vector.

Most functionalities of this module is available
in @code{binary.io} module (@pxref{Binary I/O}), and in fact
this module is a thin wrapper to it.
We provide this module for the compatibility.
If you're writing Gauche-specific code, we recommend to use
@code{binary.io} directly.
@end deftp

@defmac endianness e
[SRFI-74]
@c MOD srfi-74
The argument @var{e} must be either @code{big}, @code{little},
or @code{native}.  It expands to the implementation-specific
endianness designator.  In Gauche, the result is one of the
symbols; @pxref{Endianness}, for the details.
@end defmac

@defun make-blob size
[SRFI-74]
@c MOD srfi-74
Returns a freshly created blob that can hold @var{size} octets.
In Gauche, this is the same as @code{(make-u8vector size)}.
@end defun

@defun blob? obj
[SRFI-74]
@c MOD srfi-74
Returns @code{#t} if @var{obj} is a blob, @code{#f} otherwise.
In Gauche, this is the same as @code{(u8vector? obj)}.
@end defun

@defun blob-length blob
[SRFI-74]
@c MOD srfi-74
Returns the size of the blob, in octets.  In Gauche,
this is the same as @code{(u8vector-length blob)}.
@end defun

@defun blob-uint-ref size endian blob pos
@defunx blob-sint-ref size endian blob pos
[SRFI-74]
@c MOD srfi-74
Read an unsigned or signed integer of @var{size} octets beginning
at the position of @var{pos} from @var{blob}, respectively.

These are wrappers of @code{(get-uint size blob pos endian)}
and @code{(get-sint size blob pos endian)} in @code{binary.io}
module (@pxref{Binary I/O}), except that
@code{blob-uint-ref}/@code{blob-sint-ref} only accept u8vector
as @var{blob}.
@end defun

@defun blob-uint-set! size endian blob pos val
@defunx blob-sint-set! size endian blob pos val
[SRFI-74]
@c MOD srfi-74
Store an unsigned or signed integer @var{val} of @var{size} octets
into @var{blob} starting at the position of @var{pos}, respectively.

These are wrappers of @code{(put-uint! size blob pos val endian)}
and @code{(put-sint! size blob pos val endian)} in @code{binary.io}
module (@pxref{Binary I/O}), except that
@code{blob-uint-set!}/@code{blob-sint-set!} only accept u8vector
as @var{blob}.
@end defun

@defun blob-u8-ref blob pos
@defunx blob-u8-set! blob pos val
@defunx blob-s8-ref blob pos
@defunx blob-s8-set! blob pos val
[SRFI-74]
@c MOD srfi-74
Get/set an unsigned or signed integer as a octet at @var{pos}
from/to @var{blob}.

These are wrappers of @code{get-u8}, @code{put-u8!},
@code{get-s8} and @code{put-s8!} in @code{binary.io}, respectively.
@end defun

@defun blob-u16-ref endian blob pos
@defunx blob-u16-set! endian blob pos val
@defunx blob-s16-ref endian blob pos
@defunx blob-s16-set! endian blob pos val
@defunx blob-u32-ref endian blob pos
@defunx blob-u32-set! endian blob pos val
@defunx blob-s32-ref endian blob pos
@defunx blob-s32-set! endian blob pos val
@defunx blob-u64-ref endian blob pos
@defunx blob-u64-set! endian blob pos val
@defunx blob-s64-ref endian blob pos
@defunx blob-s64-set! endian blob pos val
[SRFI-74]
@c MOD srfi-74
Get/set an unsigned or signed integer of the indicated length
at @var{pos} from/to @var{blob}, using the specified @var{endian}.

These are wrappers of corresponding @code{get-XX} and @code{put-XX!}
in @code{binary.io}; note that the argument orders differ, though.
@end defun

@defun blob-u16-native-ref blob pos
@defunx blob-u16-native-set! blob pos val
@defunx blob-s16-native-ref blob pos
@defunx blob-s16-native-set! blob pos val
@defunx blob-u32-native-ref blob pos
@defunx blob-u32-native-set! blob pos val
@defunx blob-s32-native-ref blob pos
@defunx blob-s32-native-set! blob pos val
@defunx blob-u64-native-ref blob pos
@defunx blob-u64-native-set! blob pos val
@defunx blob-s64-native-ref blob pos
@defunx blob-s64-native-set! blob pos val
[SRFI-74]
@c MOD srfi-74
Get/set an unsigned or signed integer of the indicated length
at @var{pos} from/to @var{blob}, using the native endianness.

These are wrappers of corresponding @code{get-XX} and @code{put-XX!}
in @code{binary.io}; note that the argument orders differ, though.
@end defun

@defun blob=? blob1 blob2
[SRFI-74]
@c MOD srfi-74
This is the same as @code{u8vector=?} in @code{gauche.uvector}.
@end defun

@defun blob-copy! src sstart target tstart n
[SRFI-74]
@c MOD srfi-74
Copy @var{n} octets from the source blob @var{src} starting from @var{sstart}
into the target blob @var{target} starting from @var{tstart}.

Note that the order of arguments differs from other @code{*-copy!}
procedures (e.g. R7RS's @code{string-copy!} and @code{vector-copy!},
and @code{gauche.uvector}'s @code{u8vector-copy!})), which have the
following signature: @code{(*-copy! target tstart src sstart send)}
@end defun

@defun blob-copy blob
[SRFI-74]
@c MOD srfi-74
Returns a fresh copy of @var{blob}.  The same as @code{u8vector-copy}
in @code{gauche.uvector}.
@end defun

@defun blob->u8-list blob
@defunx u8-list->blob list
[SRFI-74]
@c MOD srfi-74
Wrappers of @code{u8vector->list} and @code{list->u8vector}, except
those don't take optional start/end arguments.
@end defun

@defun blob->uint-list size endian blob
@defunx blob->sint-list size endian blob
[SRFI-74]
@c MOD srfi-74
Read a sequence of unsigned or signed integers of @var{size} octets from
@var{blob} with @var{endian}, and returns them as a list.

@example
(blob->uint-list 3 (endianness big) '#u8(0 0 1 0 0 2 0 0 3))
  @result{} (1 2 3)
@end example
@end defun

@defun uint-list->blob size endian list
@defunx sint-list->blob size endian list
[SRFI-74]
@c MOD srfi-74
Convert a @var{list} of unsigned or signed integers to a blob.
The resulting blob has @code{(* size (length list))} octets.
Each integer occupies @var{size} octets.

@example
(uint-list->blob 3 (endianness little) '(1 2 3))
  @result{} #u8(1 0 0 2 0 0 3 0 0)
@end example
@end defun

@c ----------------------------------------------------------------------
@node Lightweight testing, Accessing environment variables, Octet-addressed binary blocks, Library modules - SRFIs
@section @code{srfi-78} - Lightweight testing
@c NODE 軽量なテスト, @code{srfi-78} - 軽量なテスト

@deftp {Module} srfi-78
@mdindex srfi-78
@c EN
This srfi defines @code{check} and @code{check-ec} macro, along
with a few helper procedures, to write tests.  Especially,
@code{check-ec} uses the same comprehension style as @code{srfi-42}
to run test expressions with various combinations of input easily.
@c JP
このsrfiは、テストを書くためのマクロ@code{check}と@code{check-ec}、
およびいくつかの補助手続きを定義します。
特に、@code{check-ec}は@code{srfi-42}スタイルの内包表記で
パラメータを様々に変えてテストしたい式を評価することができます。
@c COMMON

@c EN
We implemented this module to work with @code{gauche.test}
(@pxref{Unit testing}).
Specifically,
if the check macros are invoked while @code{gauche.test} is active
(that is, between @code{test-start} and @code{test-end}), the check
macros are simply a wrapper of Gauche's @code{test} macro; the results
are tracked and reported by @code{gauche.test}.
@c JP
Gaucheでは、このモジュールは@code{gauche.test}とうまく協働するようになっています
(@ref{Unit testing}参照)。
@code{gauche.test}がアクティブ (つまり@code{test-start}と@code{test-end}の間)に
checkマクロが呼ばれた場合、それは@code{gauche.test}の@code{test}マクロの
ラッパーとなり、テストの結果は@code{gauche.test}側でまとめられて報告されます。
@c COMMON

@c EN
If this module is used without @code{gauche.test}, however, it works as
specified by the srfi, including reporting.  So, a tests using this srfi
can be run in both ways---if it is loaded by itself, it runs as vanilla srfi-78,
and if it is included in a test file that uses @code{gacuhe.test}, it runs
as a part of @code{gauche.test}.
@c JP
このモジュールが@code{gauche.test}と一緒ではなく、単独で使われた場合は、
結果報告も含めsrfiで述べられている通りに動きます。つまり、このsrfiで書かれた
テストは2通りの方法で実行できるということです。それ単独でロードされた場合は
素のsrfi-78として、そして@code{gauche.test}を使うテストファイルからincludeされた
場合は@code{gauche.test}の一部として。
@c COMMON
@end deftp

@defmac check expr => expected
@defmacx check expr (=> equal) expected
[SRFI-78]
@c MOD srfi-78
@c EN
Evaluate @var{expected} and @var{equal}, then evaluate @var{expr} and
compare the results of @var{expected} and @var{expr} using @var{equal}.
In the first form, @code{equal?} is used as @var{equal}.
@c JP
@var{expected}と@var{equal}を評価し、次に@var{expr}を評価してその結果を
@var{expected}の結果と@var{equal}を使って比べます。
最初の形式では、@var{equal}として@code{equal?}が使われます。
@c COMMON
@end defmac

@defmac check-ec qualifier @dots{} expr => expected (argument @dots{})
@defmacx check-ec qualifier @dots{} expr (=> equal) expected (argument @dots{})
@defmacx check-ec qualifier @dots{} expr => expected
@defmacx check-ec qualifier @dots{} expr (=> equal) expected
[SRFI-78]
@c MOD srfi-78
@c EN
Evaluates @var{expr}, @var{equal} and @var{expected} repeatedly
in the environment where the @var{qualifier}s bind variables,
and each time the results of @var{expr} and @var{equal} are
compared with @var{equal}.  If the results don't agree,
the failure is recorded with the given @var{argument} @dots{}, which can
be useful to diagnose which combination of bindings the test failed on.
Single failure stops the iteration.  If the results of @var{expr} and
@var{expected} agrees on all the iterations, the entire @code{check-ec}
is regarded as success.
@c JP
@var{qualifier}で指定される変数束縛の全ての組み合わせの下で、
@var{expr}、@var{equal}、@var{expected}を繰り返し評価し、
その度に@var{expr}と@var{expected}を@var{equal}で比較します。
もし異なっていれば、それが失敗として記録され、@code{check-ec}全体が失敗として
終了します。全ての組み合わせにおいて@var{expr}と@var{expected}の結果が一致すれば、
@code{check-ec}全体が成功とみなされます。
@c COMMON

@c EN
The way @var{qualifier}s work is the same as srfi-42.
@xref{Eager comprehensions}, for the details.
@c JP
@var{qualifier}の指定方法はsrfi-42に準じます。
詳しくは@ref{Eager comprehensions}を参照してください。
@c COMMON

@c EN
The following example tests Fermat numbers (2^2^n + 1) are primes.
It fails since F_5 is a composite.
@c JP
次のテストは、フェルマー数 (2^2^n + 1) が素数かどうかを順に調べています。
F_5は合成数なのでテストは失敗します。
@c COMMON

@example
(use math.prime)
(check-ec (: n 6)
          (:let fn (+ (expt 2 (expt 2 n)) 1))
          (bpsw-prime? fn)
          => #t (n))
 @result{}
 @r{prints} Checking (bpsw-prime? fn), expecting #t => ERROR: got #f, with n: 5
@end example

@c EN
The entire @code{check-ec} form is treated as one check for the sake of
reporting.
@c JP
レポートの観点からは、@code{check-ec}全体がひとつのチェックとして扱われます。
@c COMMON
@end defmac

@defun check-report
[SRFI-78]
@c MOD srfi-78
@c EN
If this module is used stand-alone, prints the summary of test results
to the current output port.

If this module is running inside @code{gauche.test}, this does nothing.
Reporting is done by @code{gauche.test}.
@c JP
このモジュールが単独で使われた場合、現在の出力ポートにこれまでのテスト結果のまとめを
出力します。

このモジュールが@code{gauche.test}と一緒に使われた場合は何もしません。
テスト結果報告は@code{gauche.test}によって行われます。
@c COMMON
@end defun

@defun check-set-mode! mode
[SRFI-78]
@c MOD srfi-78
@c EN
Sets how the test progress and result will be reported.  This only has
an effect when check is run without @code{gauche.test}.
@c JP
テストの進行と結果をどう報告するかを指定します。これは@code{gauche.test}と一緒に
使われた時には意味を持ちません。
@c COMMON

@c EN
Valid @var{mode} is one of the following symbols:
@c JP
@var{mode}には次のシンボルのいずれかを指定します。
@c COMMON
@table @code
@item off
@c EN
Do not report the result at all, even from @code{(check-report)}.
@c JP
@code{(check-report)}も含め、結果は一切報告しません。
@c COMMON
@item summary
@c EN
Report the summary of the results when @code{(chec-report)} is called.
@c JP
@code{(chec-report)}が呼ばれた時にまとめを報告するだけです。
@c COMMON
@item report-failed
@c EN
In addition to @code{summary}, report any failed checks as they occur.
@c JP
@code{summary}の動作に加え、チェックが失敗した場合にその都度報告します。
@c COMMON
@item report
@c EN
In addition to @code{summary}, report each result of check as they occur.
@c JP
@code{summary}の動作に加え、チェック毎にその成功失敗を報告します。
@c COMMON
@end table

@c EN
The default is @code{report}.
@c JP
デフォルトは@code{report}です。
@c COMMON
@end defun

@defun check-reset!
[SRFI-78]
@c MOD srfi-78
@c EN
Clears the internal state to keep track of number of performed checks and
failed checks, etc.  This doesn't affect @code{gauche.test} bookkeeping.
@c JP
内部のテスト結果記録をクリアします。@code{gauche.test}の結果記録には影響を及ぼしません。
@c COMMON
@end defun

@defun check-passed? expected-total-count
[SRFI-78]
@c MOD srfi-78
@c EN
This can be used to programatically query whether the expected number
of tests are passed since the last @code{check-reset!} or the beginning.
The @var{expected-total-count} must be a number, and it returns @code{#t}
iff the internal count of passed test matches it and there is no failed checks.

This works even if checks are run with @code{gauche.test}.
However, only the tests using @code{check} and @code{check-ec} are counted.
@c JP
これはプログラム内から、最後の@code{check-reset!}もしくはプログラム開始以降に
期待した数のテストが成功したかどうかを調べるのに使えます。
@var{expected-total-count}には期待される成功したテストの数を渡します。
テスト失敗がなく、成功したテストの数が@var{expected-total-count}に一致すれば
@code{#t}が、そうでなければ@code{#f}が返されます。

これは@code{gauche.test}と一緒に使った場合でも有効です。ただし、
カウントされるのは@code{check}と@code{check-ec}の結果のみです。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node Accessing environment variables, Basic socket interface, Lightweight testing, Library modules - SRFIs
@section @code{srfi-98} - Accessing environment variables
@c NODE 環境変数へのアクセス, @code{srfi-98} - 環境変数へのアクセス

@deftp {Module} srfi-98
@mdindex srfi-98
@c EN
This srfi defines a portable way to access the underlying system's
environment variables.  Gauche supports such procedures built-in
(@pxref{Environment inquiry}),
but portable programs may want to use srfi API instead.
@c JP
このsrfiはシステムの環境変数にアクセスするポータブルな方法を定義しています。
Gaucheは組み込みで環境変数にアクセスする手続きを持っていますが
(@ref{Environment inquiry}参照)、
ポータブルなコードを書くにはこちらのAPIを使うのが良いでしょう。
@c COMMON
@end deftp

@defun get-environment-variable name
[SRFI-98]
@c MOD srfi-98
@c EN
Returns a string value of an environment variable named by a string @var{name}.
If the named environment variable doesn't exist, @code{#f} is returned.

This is equivalent to @code{sys-getenv}.
@c JP
文字列@var{name}で指定される名前を持つ環境変数の値を文字列で返します。
そのような環境変数が存在しなければ、@code{#f}が返されます。

この手続きは@code{sys-getenv}と等価です。
@c COMMON
@example
(get-environment-variable "PATH")
  @result{} "/bin:/usr/sbin:/usr/bin"
@end example
@end defun

@defun get-environment-variables
[SRFI-98]
@c MOD srfi-98
@c EN
Returns an assoc list of the name and the value of each environment
variable.

This is equivalent to @code{sys-environ->alist} without
the optional argument.
@c JP
全ての環境変数の名前と値の連想リストを返します。

この手続きは、省略引数を取らない時の@code{sys-environ->alist}と等価です。
@c COMMON
@example
(get-environment-variables)
  @result{} (("PATH" . "/bin:/usr/sbin:/usr/bin")
        @dots{})
@end example
@end defun

@c ----------------------------------------------------------------------
@node Basic socket interface, Purely functional random-access pairs and lists, Accessing environment variables, Library modules - SRFIs
@section @code{srfi-106} - Basic socket interface
@c NODE 基本的なソケットインタフェース, @code{srfi-106} - 基本的なソケットインタフェース

@deftp {Module} srfi-106
@mdindex srfi-106
@c EN
A portable basic socket interface.

Although comprehensive network API is provided by @code{gauche.net}
(@pxref{Networking}), it is Gauche-specific.  This srfi provides
a small subset of socket operations, but it offers a portable way
to create applications that needs simple networking.

Note that some procedures have the same name as the ones in @code{gauche.net},
but the interface may differ.

A socket object created by this srfi's API is an instance
of Gauche's @code{<socket>}, so it can be passed to the API
in @code{gauche.net} and vice versa.

The following procedures are exactly the same as defined in @code{gauche.net}.
@xref{Networking}, for the details.
@c JP
ポータブルなソケットインタフェースです。

Gaucheは@code{gauche.net}モジュールで包括的なネットワークAPIを提供しています
(@ref{Networking}参照)。しかしそれはGauche特有のものです。
このsrfiはソケット操作の小さなサブセットを提供し、
簡単なネットワーキングを必要とするアプリケーションをポータブルに書けるようにします。

@code{gauche.net}と同じ名前を持ち、インタフェースが異なる手続きがあることに注意してください。

このsrfiのAPIで作られるソケットオブジェクトはGaucheの@code{<socket>}オブジェクト
そのものなので、@code{gauche.net}のAPIに渡したり、またその逆も可能です。

以下にあげる手続きは@code{gauche.net}のものと全く同一です。
説明は@ref{Networking}を参照してください。
@c COMMON

@example
socket-accept        socket-shutdown       socket-close
socket-input-port    socket-output-port
@end example
@end deftp

@c EN
@subheading Socket object
@c JP
@subheading ソケットオブジェクト
@c COMMON

@defun make-client-socket node service :optional ai-family ai-socktype ai-flags ai-protocol
[SRFI-106]
@c MOD srfi-106
@c EN
Creates and returns a socket to
communicate with the node @var{node} and @var{service}.
If the socket type is connection-oriented (that is, @var{ai-socktype} is
@code{*sock-stream*}, which is the default),
the returned socket is already connected.
@c JP
ノード@var{node}のサービス@var{service}と通信するためのソケットを作って返します。
ソケットの型がコネクション指向なら(つまり、@var{ai-socktype}が
@code{*sock-stream*}なら、これはデフォルトですが)、
返されるソケットは既にコネクトされた状態になっています。
@c COMMON

@c EN
Both @var{node} and @var{service} must be strings.
The @var{node} argument is passed to @code{getaddrinfo(3)} to resolve
to the server IP address(es).
A service name solely consists of decimal digits is interpreted as
a port number.
@c JP
@var{node}と@var{service}は文字列でなければなりません。
@var{node}は@code{getaddrinfo(3)}に渡されてサーバのIPアドレスに解決されます。
@var{service}が数字のみで構成されていた場合はポート番号とみなされます。
@c COMMON

@c EN
The default value of optional arguments are as follows:
@code{*af-inet*} for @var{ai-family},
@code{*sock-stream*} for @var{ai-socktype},
@code{(socket-merge-flags *ai-v4mapped* *ai-addrconfig*)} for
@var{ai-flags}, and @code{*ipproto-ip*} for @var{ai-protocol}.
See below for valid flag values.
@c JP
省略可能引数のデフォルト値は次の通りです:
@var{ai-family}は@code{*af-inet*}、
@var{ai-socktype}は@code{*sock-stream*}、
@var{ai-flags}は@code{(socket-merge-flags *ai-v4mapped* *ai-addrconfig*)}、
そして@var{ai-protocol}は@code{*ipproto-ip*}。
有効なフラグの種類については下を参照してください。
@c COMMON

@c EN
This API differs from @code{make-client-socket} in @code{gauche.net}.
@c JP
@code{gauche.net}の@code{make-client-socket}とはAPIが異なることに注意してください。
@c COMMON

@example
(make-client-socket "127.0.0.1" "80")
 @result{} a <socket> connected to port 80 of localhost
@end example
@end defun

@defun make-server-socket service :optional ai-family ai-socktype ai-protocol
[SRFI-106]
@c MOD srfi-106
@c EN
Creates and returns a server socket that binds and listens at
the port specified by
@var{service}, which must be a string.  A service name solely consists
of decimal digits is interpreted as a port number.
@c JP
@var{service}で指定されるポートで待ち受けるサーバソケットを作って返します。
@var{service}は文字列でなければなりません。@var{service}が全て数字で構成されていた
場合はポート番号と解釈されます。
@c COMMON

@c EN
The default value of optional arguments are as follows:
@code{*af-inet*} for @var{ai-family},
@code{*sock-stream*} for @var{ai-socktype},
and @code{*ipproto-ip*} for @var{ai-protocol}.
See below for valid flag values.
@c JP
省略可能引数のデフォルト値は次の通りです:
@var{ai-family}は@code{*af-inet*}、
@var{ai-socktype}は@code{*sock-stream*}、
@var{ai-protocol}は@code{*ipproto-ip*}。
有効なフラグの種類については下を参照してください。
@c COMMON

@c EN
This API differs from @code{make-server-socket} in @code{gauche.net}.
@c JP
@code{gauche.net}の@code{make-server-socket}とはAPIが異なることに注意してください。
@c COMMON
@end defun

@defun socket? obj
[SRFI-106]
@c MOD srfi-106
@c EN
Equivalent to @code{(is-a? obj <socket>)}.
@c JP
@code{(is-a? obj <socket>)}と同じです。
@c COMMON
@end defun

@c EN
@subheading Communication
@c JP
@subheading 通信
@c COMMON

@defun socket-send socket u8vector :optional flags
[SRFI-106]
@c MOD srfi-106
@c EN
Almost same as @code{socket-send} in @code{gauche.net}, except that
this procedure only accepts a u8vector as the message.
(The one in @code{gauche.net} can take a string as well.)

Returns the number of octets that are actually sent.
@c JP
@code{gauche.net}の@code{socket-send}とほぼ同じですが、
@code{gauche.net}のものが文字列も引数に取ることができるのに対し、
こちらはu8vectorのみを受け付けます。

実際に送られたオクテット数を返します。
@c COMMON
@end defun

@defun socket-recv socket size :optional flags
[SRFI-106]
@c MOD srfi-106
@c EN
This is like @code{socket-recv} in @code{gauche.net}, except that
this procedure returns the received data in u8vector,
instead of a string.  If the peer has shut down the connection,
this procedure returns an empty u8vector, @code{#u8()}.

The @var{size} argument specifies the maximum size of the receiving
data.  The returned vector may be shorter if that much data is received.
@c JP
@code{gauche.net}の@code{socket-recv}に似ていますが、こちらは
文字列ではなくu8vectorを返します。もし通信の相手がコネクションを閉じていた場合は、
空のu8vector @code{#u8()}が返されます。

@var{size}引数は受信データの最大のサイズを指定します。
受信データがそれより小さい場合は返されるベクタもそれに合わせて短くなります。
@c COMMON
@end defun

@c EN
@subheading Flags
@c JP
@subheading フラグ
@c COMMON

@c EN
The srfi provides common names for constants of typical socket flags,
as well as macros that map symbolic name(s) to the flags.
@c JP
このsrfiでは、典型的なソケットフラグを表す定数と、
名前からフラグ値を求めるマクロも提供しています。
@c COMMON

@defun socket-merge-flags flag @dots{}
[SRFI-106]
@c MOD srfi-106
@c EN
Merge bitwise flags.  This is simply @code{logior} in Gauche.
@c JP
与えられた@var{flag} @dots{}をビット演算でマージします。
Gauche組み込みの@code{logior}と実質的に同じです。
@c COMMON
@end defun

@defun socket-purge-flags base-flag flag @dots{}
[SRFI-106]
@c MOD srfi-106
@c EN
Drop the bitwise flags in @var{base-flag} that are set
in @var{flag} @dots{}.
@c JP
@var{base-flag}のビットのうち、@var{flag} @dots{}で示されるビットを0にします。
@c COMMON
@end defun

@subsubheading Address family

@multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaa}
@vindex *af-inet*
@vindex *af-inet6*
@vindex *af-unspec*
@item @code{*af-inet*} @tab @code{AF_INET}
@item @code{*af-inet6*} @tab @code{AF_INET6}
@item @code{*af-unspec*} @tab @code{AF_UNSPEC}
@end multitable

@defmac address-family name
@c MOD srfi-106
@c EN
@var{Name} can be either one of symbols
@code{inet}, @code{inet6}, or @code{unspec}, and
the macro expands into the value of @code{*af-inet*},
@code{*af-inet6*} or @code{*af-unspec*}, respectively.

If @var{name} is other object, an error is signaled.
@c JP
@var{name}がシンボル@code{inet}、@code{inet6}、@code{unspec}のいずれかであれば、
それぞれ@code{*af-inet*}、@code{*af-inet6*}、@code{*af-unspec*}の値へと展開されます。

@var{name}がそれ以外のオブジェクトならエラーが報告されます。
@c COMMON
@end defmac


@subsubheading Socket domain

@multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaa}
@vindex *sock-stream*
@vindex *sock-dgram*
@item @code{*sock-stream*} @tab @code{SOCK_STREAM}
@item @code{*sock-dgram*} @tab @code{SOCK_DGRAM}
@end multitable

@defmac socket-domain name
@c MOD srfi-106
@c EN
@var{Name} can be either one of symbols
@code{stream} or @code{datagram}, and the macro
expands into the value of @code{*sock-stream*} and
@code{*sock-dgram*}, respectively.

If @var{name} is other object, an error is signaled.
@c JP
@var{name}がシンボル@code{stream}、@code{datagram}のいずれかであれば、
それぞれ@code{*sock-stream*}、@code{*sock-dgram*}の値へと展開されます。

@var{name}がそれ以外のオブジェクトならエラーが報告されます。
@c COMMON
@end defmac


@subsubheading Address info

@multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaa}
@vindex *ai-canonname*
@vindex *ai-numerichost*
@vindex *ai-v4mapped*
@vindex *ai-all*
@vindex *ai-addrconfig*
@item @code{*ai-canonname*} @tab @code{AI_CANONNAME}
@item @code{*ai-numerichost*} @tab @code{AI_NUMERICHOST}
@item @code{*ai-v4mapped*} @tab @code{AI_V4MAPPED}
@item @code{*ai-all*} @tab @code{AI_ALL}
@item @code{*ai-addrconfig*} @tab @code{AI_ADDRCONFIG}
@end multitable

@defmac address-info name @dots{}
@c MOD srfi-106
@c EN
Maps combination of names @code{canoname}, @code{numerichost},
@code{v4mapped}, @code{all} and @code{addrconfig}
to the combination of corresponding flags.

An error is signaled if other symbols are passed.
(Note: @code{canoname} for @code{*ai-canonname*}).
@c JP
シンボル@code{canoname}、@code{numerichost}、
@code{v4mapped}、@code{all}、@code{addrconfig}の組み合わせを、
対応するビットフラグの組み合わせへと展開します。

他のシンボルが渡された場合はエラーが報告されます。
(註: @code{*ai-canonname*}に対応するのは@code{canoname}です)。
@c COMMON
@end defmac

@c EN
@subsubheading Protocol
@c JP
@subsubheading プロトコル
@c COMMON

@multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaa}
@vindex *ipproto-ip*
@vindex *ipproto-tcp*
@vindex *ipproto-udp*
@item @code{*ipproto-ip*} @tab @code{IPPROTO_IP}
@item @code{*ipproto-tcp*} @tab @code{IPPROTO_TCP}
@item @code{*ipproto-udp*} @tab @code{IPPROTO_UDP}
@end multitable

@defmac ip-protocol name
@c MOD srfi-106
@c EN
Maps one of names @code{ip}, @code{tcp}, and @code{udp}
to the corresponding flag value.  An error is signaled
if other symbol is passed.
@c JP
シンボル@code{ip}、@code{tcp}、and @code{udp}を
それぞれ対応するフラグの値へと展開します。
他のシンボルが渡されたらエラーを報告します。
@c COMMON
@end defmac

@c EN
@subsubheading Message type
@c JP
@subsubheading メッセージタイプ
@c COMMON

@multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaa}
@vindex *msg-none*
@vindex *msg-peek*
@vindex *msg-oob*
@vindex *msg-waitall*
@item @code{*msg-none*} @tab 0
@item @code{*msg-peek*} @tab  @code{MSG_PEEK}
@item @code{*msg-oob*} @tab   @code{MSG_OOB}
@item @code{*msg-waitall*} @tab @code{MSG_WAITALL}
@end multitable

@defmac message-type name @dots{}
@c MOD srfi-106
@c EN
Maps combination of names @code{none}, @code{peek},
@code{oob} and @code{wait-all}
to the combination of corresponding flags.

An error is signaled if other symbols are passed.
(Note: @code{wait-all} for @code{*msg-waitall*}).
@c JP
シンボル@code{none}、@code{peek}、
@code{oob}、@code{wait-all}の組み合わせを、
対応するビットフラグの組み合わせへと展開します。

他のシンボルが渡された場合はエラーが報告されます。
(註: @code{*msg-waitall*}に対応するのは@code{wait-all}です)。
@c COMMON
@end defmac

@c EN
@subsubheading Shutdown method
@c JP
@subsubheading シャットダウン
@c COMMON

@multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaa}
@vindex *shut-rd*
@vindex *shut-wr*
@vindex *shut-rdwr*
@item @code{*shut-rd*} @tab @code{SHUT_RD}
@item @code{*shut-wr*} @tab @code{SHUT_WR}
@item @code{*shut-rdwr*} @tab @code{SHUT_RDWR}
@end multitable

@defmac shutdown-method name @dots{}
@c MOD srfi-106
@c EN
Maps combination of names @code{read} and @code{write}
to the combination of corresponding flags.

An error is signaled if other symbols are passed.
@c JP
シンボル@code{code}と@code{write}の組み合わせを対応するビットマスクの値へと展開します。

他のシンボルが渡された場合はエラーが報告されます。
@c COMMON
@end defmac

@c ----------------------------------------------------------------------
@node Purely functional random-access pairs and lists, Portable runtime environment inquiry, Basic socket interface, Library modules - SRFIs
@section @code{srfi-101} - Purely functional random-access pairs and lists
@c NODE 純粋に関数的でランダムアクセス可能なペアとリスト, @code{srfi-101} - 純粋に関数的でランダムアクセス可能なペアとリスト

@deftp {Module} srfi-101
@mdindex srfi-101
@c EN
SRFI-101 has become a part of R7RS large.
@xref{R7RS random-access lists}.
@c JP
SRFI-101はR7RS largeに採り入れられました。
@ref{R7RS random-access lists}を参照してください。
@c COMMON

@c EN
Special treatment of @code{cond-expand}: The feature conditional
@code{cond-expand} implicitly makes the checked library loaded
if available.  That is, you can usually say
@code{(cond-expand (srfi-N <code>))} where @code{<code>} can assume
@code{srfi-N} is already available, without saying @code{(use srfi-N)}.

However, @code{srfi-101} exports the names that conflicts with
standard primitive pair and list operators, and it is generally
useless to import it without prefix or renaming.  Currently @code{cond-expand}
has no way to specify such renaming, so we don't import
@code{srfi-101} by @code{cond-expand}.
You have to say @code{(cond-expand (srfi-101 (use srfi-101 :prefix ra:)))},
for example.
@c JP
@code{cond-expand}の特別な扱いについて: @code{cond-expand}は
チェックした機能が使える場合には、必要なライブラリを暗黙にロードしまう。
つまり、@code{(cond-expand (srfi-N <code>))} とした場合、@code{srfi-N}が
サポートされていれば@code{<code>}の中で@code{(use srfi-N)}とする必要はありません。

しかし、@code{srfi-101}は組み込みの重要なリストやペア操作手続きと同じ名前の
手続きをたくさんエクスポートしているので、プレフィクスやリネーム無しで
インポートすることはあまり実用的ではありません。@code{cond-expand}では
インポート時のプレフィクスやリネームは指定できないので、
@code{srfi-101}に限り、@code{cond-expand}ではインポートしないようにしています。
@code{(cond-expand (srfi-101 (use srfi-101 :prefix ra:)))} などとしてください。
@c COMMON
@end deftp

@c ----------------------------------------------------------------------
@node Portable runtime environment inquiry, Comparators, Purely functional random-access pairs and lists, Library modules - SRFIs
@section @code{srfi-112} - Environment inquiry
@c NODE ポータブルな実行環境の問い合わせ, @code{srfi-112} - 実行環境の問い合わせ

@deftp {Module} srfi-112
@mdindex srfi-112
@c EN
This srfi provides a portable way to obtain runtime information.
@c JP
このsrfiは実行時の情報を問い合わせるポータブルな方法を提供します。
@c COMMON
@end deftp

@defun implementation-name
[SRFI-112]
@c MOD srfi-112
@c EN
The name of the implementation.
Returns a string @code{"Gauche"}.
@c JP
実装の名前。文字列@code{"Gauche"}が返ります。
@c COMMON
@end defun

@defun implementation-version
[SRFI-112]
@c MOD srfi-112
@c EN
Returns a string of Gauche's version.  The same as @code{gauche-version}
(@pxref{Environment inquiry}).
@c JP
Gaucheのバージョンを示す文字列が返ります。
@code{gauche-version}と同じです (@ref{Environment inquiry}参照)。
@c COMMON
@end defun

@defun cpu-architecture
[SRFI-112]
@c MOD srfi-112
@c EN
Returns a string of CPU architecture info, such as @code{"x86_64"}.
Same as the @code{machine} field of the return value of @code{sys-uname}
(@pxref{System inquiry}).
@c JP
CPUアーキテクチャの情報(@code{"x86_64"}など)を文字列で返します。
@code{sys-uname}の@code{machine}フィールドと同じです(@ref{System inquiry}参照)。
@c COMMON
@end defun

@defun machine-name
[SRFI-112]
@c MOD srfi-112
@c EN
Returns the host name.  Same as the @code{nodename} field of
the return value of @code{sys-uname}.
(@pxref{System inquiry}).
@c JP
ホスト名を返します。@code{sys-uname}の@code{nodename}フィールドと同じです
(@ref{System inquiry}参照)。
@c COMMON
@end defun

@defun os-name
[SRFI-112]
@c MOD srfi-112
@c EN
Returns the OS name.  Same as the @code{sysname} field
of the return value of @code{sys-uname}.
@c JP
OSの名前を返します。@code{sys-uname}の@code{sysname}フィールドと同じです
(@ref{System inquiry}参照)。
@c COMMON
@end defun

@defun os-version
[SRFI-112]
@c MOD srfi-112
@c EN
Returns the OS version.  Same as the @code{release} field
of the return value of @code{sys-uname}.
@c JP
OSのバージョンを返します。@code{sys-uname}の@code{release}フィールドと同じです
(@ref{System inquiry}参照)。
@c COMMON
@end defun

@c EN
Here's an example of output.  It is likely to differ on your environment.
@c JP
出力の例を示します。あなたの実行環境では多分違った値になるでしょう。
@c COMMON

@example
gosh> (implementation-name)
"Gauche"
gosh> (implementation-version)
"0.9.5"
gosh> (cpu-architecture)
"x86_64"
gosh> (machine-name)
"scherzo"
gosh> (os-name)
"Linux"
gosh> (os-version)
"3.2.0-89-generic"
@end example


@c ----------------------------------------------------------------------
@node Comparators, Simple adjustable-size strings, Portable runtime environment inquiry, Library modules - SRFIs
@section @code{srfi-114} - Comparators
@c NODE 比較器, @code{srfi-114} - 比較器

@deftp {Module} srfi-114
@mdindex srfi-114
This module is provided for the compatibility of code using srfi-114.
The new code should use srfi-128, which is fully built-in.
@end deftp

The following procedures are built-in.  @xref{Basic comparators}, for
the detailed documentation.   Those are also exported from @code{srfi-114}
for the compatibility.

@table @asis
@item Predicates
@code{comparator?},

@item Standard comparators
@code{boolean-comparator},
@code{char-comparator},
@code{char-ci-comparator},
@code{string-comparator},
@code{string-ci-comparator},
@code{symbol-comparator},
@code{exact-integer-comparator},
@code{integer-comparator},
@code{rational-comparator},
@code{real-comparator},
@code{complex-comparator},
@code{number-comparator},
@code{pair-comparator},
@code{list-comparator},
@code{vector-comparator},
@code{bytevector-comparator},
@code{uvector-comparator}

@item The default comparator
@code{default-comparator}

@item Wrapped equality predicates
@code{eq-comparator},
@code{eqv-comparator},
@code{equal-comparator}

@item Accessors
@code{comparator-equality-predicate},
@code{comparator-comparison-procedure},
@code{comparator-hash-function}

@item Primitive applicators
@code{comparator-test-type},
@code{comparator-check-type},
@code{comparator-compare},
@code{comparator-hash}

@item Comparison predicates
@code{=?},
@code{<?},
@code{<=?},
@code{>?},
@code{>=?}
@end table

@subsubheading Basic comparator interface

@defun make-comparator type-test equal compare hash :optional name
[SRFI-114+]
@c MOD srfi-114
This is SRFI-114 style comparator constructor.  The optional @var{name}
argument is Gauche's extension.

This is the same as built-in @code{make-comparator/compare}.
@xref{Basic comparators}, for the details.

Do not confuse this with built-in (SRFI-128) @code{make-comparator};
if you @code{(use srfi-114)}, this one shadows the built-in one.

Note that a comparator works for both SRFI-114 and SRFI-128 procedures,
regardless of how it is constructed.
@end defun

@defun comparator-comparison-procedure? c
@defunx comparator-hash-function? c
[SRFI-114]
@c MOD srfi-114
Returns true iff a comparator @var{c} can be used to order objects
or to hash them, respectively.  These are aliases of
built-in @code{comparator-ordered?} and @code{comparator-hashable?}.
@end defun

@defun comparator-type-test-procedure c
[SRFI-114]
@c MOD srfi-114
Returns type test predicate of a comparator @var{c}.
This is an alias of built-in @code{comparator-type-test-predicate}.
@end defun

@defun comparator-equal? c a b
[SRFI-114]
@c MOD srfi-114
Checks equality of @var{a} and @var{b} using the equality predicate
of a comparator @var{c}.  This can be also written in @code{=?}, which
is built-in (@pxref{Comparator predicates and accessors}).
@example
(=? c a b)
@end example
@end defun


@subsubheading Auxiliary comparator constructors

@defun make-inexact-real-comparator epsilon rounding nan-handling
[SRFI-114]
@c MOD srfi-114
Returns a comparator for inexact real numbers, taking into
account of errors and NaNs.

The basic idea is that we compare two finite real numbers
after rounding them to @var{epsilon} interval, which must be
a nonnegative real number.
(Note that it's not to compare two numbers ``close enough'', as often
being done to compare inexact numbers.  ``Close enough'' scheme
won't be transitive.)

The rounding mode is specified by the @var{rounding} argument.
It can be either one of the symbols @code{round}, @code{ceiling},
@code{floor} or @code{truncate}, or a procedure that takes
two arguments, a real number and an epsilon, and returns
the rounded result of the first argument according to the
given epsilon.

The @var{nan-handling} argument determines how to handle the
case to compare NaN and non-NaN numbers.  (If both are NaNs,
this comparator regards them as equal).  It can be either
one of the followings:
@table @asis
@item @code{min}
If it's a symbol @code{min}, NaN is compared as smaller than
all other real numbers, even than @code{-inf.0}.
@item @code{max}
If it's a symbol @code{min}, NaN is compared as greater than
all other real numbers, even than @code{+inf.0}.
@item @code{error}
If it's a symbol @code{error}, an error is signaled.
@item a procedure taking one argument
The procedure is invoked with the real number which is not NaN.
If it ever returns, it must return either 1, 0 or -1, for
it's used as the result of the comparison procedure of
the comparator.  However, since the procedure doesn't know
@emph{which} argument is non-NaN, it's hard to have consistent
semantics; the best bet is to throw a custom error.
@end table

@example
(define c (make-inexact-real-comparator 0.1 'round 'error))

(comparator-compare c 0.112 0.098) @result{} 0
(comparator-compare c 0.131 0.172) @result{} -1
@end example

Note: Rounding to the nearest epsilon interval would involve
scaling inexact numbers, and that may reveal small difference
between the actual number and its notation.  For example,
an inexact real number denoted as @code{0.15} is actually
slightly smaller than @code{15/100}, and rounding with epsilon
@code{0.1} would result @code{0.1}, not @code{0.2}.
@end defun

@defun make-car-comparator cmpr
@defunx make-cdr-comparator cmpr
[SRFI-114]
@c MOD srfi-114
@c EN
Returns comparators that accept pairs, and compare them with
their car or cdr by @var{cmpr}, respectively.

Using @code{make-key-comparator}, these cam be written as follows
(@pxref{Combining comparators}, for @code{make-key-comparator}).
@c JP
ペアを受け取り、その@code{car}のみまたは@code{cdr}のみを@var{cmpr}で
比較するような比較器を返します。

@code{make-key-comparator}を使えばこれらは以下の通りに書けます。
(@code{make-key-comparator}については@ref{Combining comparators}を参照)。
@c COMMON
@example
(define (make-car-comparator cmpr)
  (make-key-comparator cmpr pair? car))

(define (make-cdr-comparator cmpr)
  (make-key-comparator cmpr pair? cdr))
@end example
@end defun

@defun make-list-comparator element-comparator
@defunx make-vector-comparator element-comparator
@defunx make-bytevector-comparator element-comparator
@c MOD srfi-114
[SRFI-114]
Returns a new comparator that compares lists, vectors and
bytevectors element-wise using @var{element-comparator},
respectively.  These are more general versions of
@code{list-comparator}, @code{vector-comparator} and
@code{bytevector-comparator}, which use @code{default-comparator}
as @var{element-comparator}.

For a list comparator, it is an error to pass improper lists.

Note that comparing sequences of different lengths is slightly
different between lists and vector/bytevectors.  List comparator
uses ``dictionary'' order, so @code{(1 3)} comes after @code{(1 2 3)},
assuming elements are compared numerically.
For vectors and bytevectors, shorter one always precedes the other,
so @code{#(1 3)} comes before @code{#(1 2 3)}.
@end defun

@defun make-listwise-comparator type-test element-comparator empty? head tail
[SRFI-114]
@c MOD srfi-114
More general version of @code{make-list-comparator}.
Returns a comparator that compares structures which can be
traversed using three procedures, @var{empty?}, @var{head} and @var{tail}.
Each of those procedure receives a structure to be compared, and @var{empty?}
must return @code{#t} iff the structure is empty, @var{head}
must return the first element in the structure, and @var{tail}
must return the same type of structure containing all the elements
but the head.  The @var{type-test} predicate checks if the arguments
passed to the comparator to be a suitable structure.

That is, @code{make-list-comparator} can be written in
@code{make-listwise-comparator} as follows.
@example
(make-list-compartator element-comparator)
  @equiv{}
  (make-listwise-comparator list? element-comparator null? car cdr)
@end example

This can be used to compare list-like structures.  For example,
the following call returns a comparator that compares elements
of two lazy streams (@pxref{Stream library}).

@example
(make-listwise-comparator stream?
                          element-comparator
                          stream-null?
                          stream-car
                          stream-cdr)
@end example
@end defun

@defun make-vectorwise-comparator type-test element-comparator length ref
[SRFI-114]
@c MOD srfi-114
More general version of @code{make-vector-comparator}.
Returns a comparator that compares structures which can be
traversed using two procedures, @var{length} and @var{ref}.
The @var{length} procedure must return the number of elements in the
structure.  The @var{ref} procedure receives a structure and a nonnegative
exact integer index @var{k}, and must return @var{k}-th element
of the structure.

That is, the following equivalence holds:
@example
(make-vector-comparator element-comparator)
  @equiv{}
  (make-vectorwise-comparator vector? element-comparator
                              vector-length vector-ref)

(make-bytevector-comparator element-comparator)
  @equiv{}
  (make-vectorwise-comparator u8vector? element-comparator
                              u8vector-length u8vector-ref)
@end example
@end defun

@defun make-pair-comparator car-comparator cdr-comparator
[SRFI-114]
@c MOD srfi-114
Creates a comparator that compares pairs, with their cars
by @var{car-comparator} and their cdrs by @var{cdr-comparator}.
@end defun

@defun make-improper-list-comparator element-comparator
[SRFI-114]
@c MOD srfi-114
This may be understood as recursive pair comparator; if objects
to be compared are pairs, we recurse their cars then their cdrs.
If objects to be compared are not pairs, we use @var{element-comparator}
to compare them.
@end defun

@defun make-selecting-comparator comparator1 comparator2 @dots{}
[SRFI-114]
@c MOD srfi-114
This creates a comparator that works any one of the given comparators;
the objects to be compared are type-tested with each of the comparators
in order, and the first comparator that accepts all objects will be used.
@end defun

@defun make-refining-comparator comparator1 comparator2 @dots{}
[SRFI-114]
@c MOD srfi-114
This is similar to @code{make-selecting-comparator}, except that
if the first comparator that accepts given objects to compare finds
they are equal (or 0 by the comparison procedure), it tries other
comparators down the list, if any.
@end defun

@defun make-reverse-comparator comparator
[SRFI-114]
@c MOD srfi-114
Returns a comparator that just reverses the comparison order of
@var{comparator}.
@end defun

@defun make-debug-comparator comparator
[SRFI-114]
@c MOD srfi-114
@end defun

@subsubheading Comparison procedure constructors

@defun make-comparison< lt-pred
@defunx make-comparison> gt-pred
@defunx make-comparison<= le-pred
@defunx make-comparison>= ge-pred
@defunx make-comparison=/< eq-pred lt-pred
@defunx make-comparison=/> eq-pred gt-pred
[SRFI-114]
@c MOD srfi-114
Utility procedures to create a comparison procedure (the one returns
-1, 0, or 1) from the given predicate.  For example, 
@code{make-comparison<} can be defined as follows:

@example
(define (make-comparison< pred)
  (^[a b] (cond [(pred a b) -1]
                [(pred b a) 1]
                [else 0])))
@end example
@end defun

@subsubheading Comparison syntax

@defmac if3 expr less equal greater
[SRFI-114]
@c MOD srfi-114
Three-way @code{if}: Evaluates @var{expr}, and then evaluates
either one of @var{less}, @var{equal}, or @var{greater},
depending on the value of @var{expr} is either less than zero,
equal to zero, or greater than zero, respectively.
@end defmac

@defmac if=? expr consequent :optional alternate
@defmacx if<? expr consequent :optional alternate
@defmacx if>? expr consequent :optional alternate
@defmacx if<=? expr consequent :optional alternate
@defmacx if>=? expr consequent :optional alternate
@defmacx if-not=? expr consequent :optional alternate
[SRFI-114]
@c MOD srfi-114
Conditional evaluation according to comparison expression @var{expr};
that is, @code{if@var{OP}?} evaluates @var{consequent} if
@code{(@var{OP} expr 0)} is true, otherwise it evaluates @var{alternate}
when provided.

@example
(if<? (compare 10 20) 'yes)      @result{} yes
(if>=? (compare 10 20) 'yes 'no) @result{} no
@end example
@end defmac

@subsubheading Comparison predicate constructors

@defun make=? comparator
@defunx make<? comparator
@defunx make>? comparator
@defunx make<=? comparator
@defunx make>=? comparator
[SRFI-114]
@c MOD srfi-114
@example
((make=? comparator) obj1 obj2 obj3 @dots{})
  @equiv{} (=? comparator obj1 obj2 obj3 @dots{})
@end example
@end defun

@subsubheading Interval comparison predicates


@defun in-open-interval? [comparator] obj1 obj2 obj3
@defunx in-closed-interval? [comparator] obj1 obj2 obj3
@defunx in-open-closed-interval? [comparator] obj1 obj2 obj3
@defunx in-closed-open-interval? [comparator] obj1 obj2 obj3
[SRFI-114]
@c MOD srfi-114
Check if @var{obj1}, @var{obj2} and @var{obj3} has the following
relationships:

@example
(and (op1 obj1 obj2) (op2 obj2 obj3))
@end example

Where each of @var{op1} and @var{op2} can be
@code{(make<? comparator)} (if that end is @emph{open}),
or @code{(make<=? comparator)} (if that end is @emph{closed}).

When @var{comparator} is omitted, the default comparator is used.

@example
(use srfi-42)
(list-ec (: x 0 5) (list x (in-closed-open-interval? 1 x 3)))
  @result{} ((0 #f) (1 #t) (2 #t) (3 #f) (4 #f))
@end example
@end defun

@subsubheading Min/max comparison procedures

@code{comparator-min} and @code{comparator-max} are the
same as @code{srfi-162}.  @xref{Comparator sublibrary}.


@c ----------------------------------------------------------------------
@node Simple adjustable-size strings, Cursor-based string library, Comparators, Library modules - SRFIs
@section @code{srfi-118} - Simple adjustable-size strings
@c NODE 簡単な可変長文字列, @code{srfi-118} - 簡単な可変長文字列

@deftp {Module} srfi-118
@mdindex srfi-118
@c EN
This SRFI defines two string mutating operations that can change
the length of the string: @code{string-append!} and @code{string-replace!}.

Note that, in Gauche, the body of strings is immutable; when you mutate
a string, Gauche creates a fresh new string body and just switch a pointer
in the original string to point the new string body.  So it is not a
problem to implement this SRFI in Gauche, but it also means you won't
get any performance benefit by using these operations.  Using immutable
counterparts (@code{string-append} and @code{string-replace}) gives
you the same performance.  (Be aware that the interface is slightly
different from the immutable versions.)

We provide this module only for the compatibility.  Gauche-specific
programs should stay away from this module.  Particularly, avoid
code like the example in SRFI-118 document (build a string by
@code{append!}-ing small chunks at a time)---they're quadratic on Gauche.
@c JP
このSRFIは、文字列の長さを変えるような破壊的変更を行う文字列操作ルーチンを
提供します。

Gaucheでは、文字列の本体は変更不可になっています。
文字列の破壊的変更は、
実際には新たな文字列本体を作成して、元の文字列が指している本体とポインタを
置き換えることで実現されます。
ですのでこのsrfiをGaucheに実装すること自体は全く問題ないのですが、
これらのAPIを使ったからといって性能上の恩恵にあずかれるわけではありません。
変更不可な文字列を@code{string-append} and @code{string-replace}で
切り貼りするのと、性能的には何ら変わりません。
(このモジュールのAPIは、変更不可文字列を扱うAPIと若干異なることに注意してください。)

このモジュールは、互換性のためだけ提供されます。
Gaucheに依存したプログラムはこのモジュールを使う必要はないでしょう。
特に、srfi-118のドキュメントにある例は避けるのが懸命です
(文字列を、小さな塊ごとに破壊的にappendしてゆくという実装ですが、
Gaucheではそれは文字列の長さの2乗に比例した時間がかかってしまいます)。
@c COMMON
@end deftp

@defun string-append! string values @dots{}
[SRFI-118]
@c MOD srfi-118
@c EN
The @var{string} argument must be a mutable string.
Modify @var{string} by appending @var{values}, each of which is
either a character or a string.
@c JP
@var{string}引数は変更可能な文字列でなければなりません。
残りの引数@var{values}はそれぞれ文字または文字列です。それらを@var{string}に
破壊的に追加します。
@c COMMON

@example
(rlet1 a (string-copy "abc")
  (string-append! a #\X "YZ"))
 @result{} "abcXYZ"
@end example
@end defun

@defun string-replace! dst dst-start dst-end src :optional src-start src-end
[SRFI-118]
@c MOD srfi-118
@c EN
The @var{dst} argument must be a mutable string.
Replace @var{dst} between @var{dst-start} (inclusive) and
@var{dst-end} (exclusive) with a string @var{src}.  The optional
arguments @var{src-start} and @var{src-end} limits the region of
@var{src} to be used.
@c JP
@var{dst}引数は変更可能な文字列でなければなりません。
@var{dst}中の、@var{dst-start}(inclusive)から@var{dst-end}(exclusive)までの
内容が文字列@var{src}で置き換えられます。省略可能引数
@var{src-start}と@var{src-end}で、@var{src}の使う部分を制限することができます。
@c COMMON

@c EN
Be aware that the order of arguments differ from
SRFI-13's @code{string-replace} (@pxref{SRFI-13 Other string operations});
@code{string-replace!} resembles to @code{string-copy!} (also in SRFI-13),
rather than @code{string-replace}.
@c JP
引数の順序がSRFI-13の@code{string-replace}とは異なることに
注意して下さい (@ref{SRFI-13 Other string operations}参照)。
@code{string-replace!}の引数順は同じくSRFI-13にある@code{string-copy!}に
似せてあります。
@c COMMON

@example
(rlet1 a (string-copy "abc")
  (string-replace! a 1 2 "XYZ"))
 @result{} "aXYZc"
@end example
@end defun


@c ----------------------------------------------------------------------
@node Cursor-based string library, String library (reduced), Simple adjustable-size strings, Library modules - SRFIs
@section @code{srfi-130} - Cursor-based string library

@deftp {Module} srfi-130
@mdindex srfi-130
This is an reduced version of @code{srfi-13} that supports cursors in
addition to indexes. The consistency with R7RS and recent srfis are
also considered.

The following are built-in.  @xref{String cursors}, for the details.

@example
string-cursor?        string-cursor-start    string-cursor-end
string-cursor-next    strig-cursor-prev      string-cursor-forward
string-cursor-back    string-cursor=?        string-cursor<?
string-cursor<=?      string-cursor>?        string-cursor>=?
string-cursor-diff    string-cursor->index   string-index->cursor
@end example

The following procedures are simply aliases of the builtin version
without the @code{/cursor} or @code{/cursors} suffix.

@example
string->list/cursors  string->vector/cursors string-copy/cursors
string-ref/cursor     substring/cursors
@end example

The following procedures are defined in srfi-13.  @xref{String library},
for the details.  Note: Some of those procedures in srfi-13 accept
only indexes (e.g. @code{string-index}).  In srfi-130, both indexes
and cursors are accepted.  Our srfi-13 implementation shares the same
procedure with srfi-130, so they accept both indexes and cursors but
such code won't be portable as srfi-13.

@example
string-null?       string-any         string-every       string-tabulate
string-unfold      string-unfold-right                   reverse-list->string
string-take        string-drop        string-take-right  string-drop-right
string-pad         string-pad-right   string-trim        string-trim-right
string-trim-both   string-replace     string-prefix-length
string-suffix-length                  string-prefix?     string-suffix
string-concatenate string-concatenate-reverse            string-count
string-filter      string-reverse
@end example

The following procedures are also defined in srfi-13 and redefined in
srfi-130. However, for operations going from left to right, the
srfi-130 version returns a cursor instead of an index when found or
@code{(string-cursor-end)} of the input string when not found.  For
operations going from right to left, it returns a cursor representing
a @emph{successor} of the matching character when found, or
@code{(string-cursor-begin)} of the input string when not found. In
contrast, the srfi-13 version returns either an index when found or
@code{#f} otherwise.

@example
string-fold        string-fold-right   string-index
string-index-right string-skip         string-skip-right
@end example

@code{string-contains} is defined the same as srfi-13. However the
srfi-130 returns a cursor when a string is found, and @code{#f}
otherwise. In contrast, the srfi-13 version returns an index or
@code{#f}. @code{string-contains-right} is similar to
@code{string-contains} except that the searching start from the end of
the string.

@code{string-for-each-cursor} is similar to
@code{string-for-each-index} from srfi-13 but @code{proc} will take
the cursor instead of the index.

@code{xsubstring} and @code{string-delete} in srfi-13 are renamed
@code{string-replicate} and @code{string-remove} respectively in
srfi-130. Similar to srfi-152, the @var{to} argument is required in
@code{string-replicate}.

@code{string-split} is the same as one from srfi-152 or
@code{gauche.stringutil} module.

@end deftp



@c ----------------------------------------------------------------------
@node String library (reduced), First-class dynamic extents, Cursor-based string library, Library modules - SRFIs
@section @code{srfi-152} - String library (reduced)
@c NODE 文字列ライブラリ(簡略版), @code{srfi-152} - 文字列ライブラリ(簡略版)

@deftp {Module} srfi-152
@mdindex srfi-152
@c EN
This is an improved version of @code{srfi-13}.  The spec is actually smaller
than srfi-13 (hence 'reduced' in the title) by removing bells and whistles.
The consistency with R7RS and recent srfis are also considered.

The following are built-in.  @xref{Strings}, for the details.
@c JP
これは@code{srfi-13}の改良版です。
@code{srfi-13}から余分なものを取り除き、R7RSや最近のsrfiとの一貫性を
改善したもので、実際は@code{srfi-13}より小さくなっています。

以下に示す手続きは組み込みです。詳しくは@ref{Strings}を参照してください。
@c COMMON

@example
string?            make-string        string             string-length
string->vector     string->list       vector->string     list->string
string-ref         string-set!        substring          string-copy
string=?           string<?           string<=?          string>?
string>=?          string-append      string-join        string-split
string-map         string-for-each    read-string        write-string
string-fill!
@end example

@c EN
The following procedures are defined to use Unicode string case folding,
and @code{gauche.unicode} module provides them.
@xref{Full string case conversion}, for the details.
Note that Gauche's
built-in versions uses character-wise case folding, which differs
from string case folding on some characters (German eszett, for example).
@c JP
以下に示す手続きはUnicodeの文字列の大文字小文字変換を使うように定義されていて、
元は@code{gauche.unicode}で提供されています。
説明は@ref{Full string case conversion}を参照してください。
Gaucheの組み込みにも同名の手続きがありますが、それらは文字ごとに
大文字小文字変換を行うので、文字列としての大文字小文字変換とは異なります
(ドイツ語のエスツェット等)。
@c COMMON

@example
string-ci=?   string-ci<?   string-ci<=?  string-ci>?   string-ci>=?
@end example

@c EN
The following procedures are defined in srfi-13.  @xref{String library},
for the details.  Note: Some of those procedures in srfi-13 that require
predicate allows a char-set or a character to be passed instead
(e.g. @code{string-filter}).  In srfi-152, only predicate is allowed.
Our srfi-152 implementation shares the same procedure with srfi-13, so
they accept the same arguments as srfi-13's, but such code won't be
portable as srfi-152.
@c JP
以下に示す手続きはsrfi-13で定義されています。
説明は@ref{String library}を参照してください。
srfi-13ではこれらの手続きのいくつかは、述語引数として手続きだけでなく文字集合や
文字を取ることができます(例: @code{string-filter})。
srfi-152では手続きしか許していません。Gaucheの実装ではこれらの手続きは
srfi-13のものと同じなのでsrfi-13のような使い方ができますが、
srfi-152として移植性のあるコードを書く際には手続きだけを渡すように気をつけてください。
@c COMMON

@example
string-null?       string-any         string-every       string-tabulate
string-unfold      string-unfold-right      reverse-list->string
string-take        string-drop        string-take-right  string-drop-right
string-pad         string-pad-right   string-trim        string-trim-right
string-trim-both   string-replace     string-prefix-length string-suffix-length
string-prefix?     string-suffix?     string-index       string-index-right
string-skip        string-skip-right  string-contains    string-concatenate
string-concatenate-reverse            string-fold        string-fold-right
string-count       string-filter      string-copy!
@end example
@end deftp

@c EN
We describe procedures unique to this module below.
@c JP
以降では、srfi-152特有の手続きについて説明します。
@c COMMON

@defun string-remove pred string :optional start end
[SRFI-152]
@c MOD srfi-152
@c EN
Returns a substring of @var{string} between @var{start} and @var{end},
except characters that satisfy @var{pred}.   In other words,
it is @code{(string-filter (complement pred) string start end)}.

This is called @var{string-delete} in @code{srfi-13}.  Being changed
to take only a predicate (but not a character), it is renamed for
the consistency of other srfi (e.g. @code{filter}, @code{remove} and
@code{delete} in srfi-1.)
@c JP
@var{string}の@var{start}と@var{end}インデックス間から、
述語@var{pred}を満たす文字を除いた部分文字列を返します。
@code{(string-filter (complement pred) string start end)}と同じです。

これは@code{srfi-13}で@var{string-delete}と呼ばれていた手続きに相当します。
第一引数に述語手続きだけを取るようにし、また他のsrfiとの一貫性を重視して
名前が変えられました(例えばsrfi-1の@code{filter}、@code{remove}、@code{delete}の
関係を考えてください)。
@c COMMON

@example
(string-remove char-whitespace?
               "Quick fox jumps over the lazy dog"
               3 22)
 @result{} "ckfoxjumpsovert"
@end example
@end defun

@defun string-replicate string from to :optional start end
[SRFI-152]
@c MOD srfi-152
@c EN
Extended substring.  It is called @code{xsubstring} in srfi-13, but
renamed for the consistency.

Extract a substring of @var{string} between @var{start} and @var{end},
and conceptually create a bidirectional infinite string by repeating
the substring to both direction.  For example, suppose @var{string}
is @code{"abcde"}, @var{start} is 1, and @var{end} is 4.  So we repeat
the substring @code{"bcd"}, with one @code{b} falling on the index zero:
@c JP
拡張版substringです。srfi-13では@code{xsubstring}と呼ばれていましたが、
一貫性のため名前が変えられました。

@var{string}のインデックス@var{start}から@var{end}までの部分文字列をとり、
それを両側に無限に繰り返した文字悦を考えます。
例えば@var{string}が@code{"abcde"}であり、@var{start}が1、@var{end}が4なら、
@code{"bcd"}が無限に繰り替えされた文字列を考えます。この文字列がソース文字列となります。
@code{b}がインデックスの起点です。
@c COMMON

@example
... b  c  d  b  c  d  b  c  d  b  c  d  b ... 
   -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6
@end example

@c EN
Then we extract a substring between @var{from} and @var{to}
out of this infinite string.
@c JP
このソース文字列から、インデックス@var{from}と@var{to}の間の部分文字列を取り出し返します。
@c COMMON

@example
(string-replicate "abcde" 2 10 1 4)
  @result{} "dbcdbcdb"
(string-replicate "abcde" -5 -3 1 4)
  @result{} "cdbcdbcd"
@end example
@end defun

@defun string-segment string k
[SRFI-152]
@c MOD srfi-152
@c EN
Splits @var{string} by every @var{k} characters and returns
a list of those strings.  The last string may be shorter than @var{k}.
@c JP
@var{string}を@var{k}文字ごとに分割して、そのリストを返します。
最後の文字列は@var{k}文字より短いかもしれません。
@c COMMON

@example
(string-segment "abcdefghijklmn" 3)
 @result{} ("abc" "def" "ghi" "jkl" "mn")
@end example

@c EN
We have a similar procedure on lists, @code{slices}
(@pxref{List accessors and modifiers}).
@c JP
類似の手続きとして、@code{slices}があります。
(@ref{List accessors and modifiers}参照)。
@c COMMON
@end defun

@defun string-contains-right string1 string2 :optional start1 end1 start2 end2
[SRFI-152]
@c MOD srfi-152
@c EN
Like @code{string-contains}, looks for a needle @var{string2} from
a haystack @var{string1}, but if it is found, returns the start index
of the @emph{last} match, instead of the first match.  The returned index
is in @var{string1}.  The optional arguments limit the range of a needle
and a haystack.  If a needle isn't found, @code{#f} is returned.

An edge case: If a needle is empty (e.g. @var{string2} is empty,
or @var{start2} = @var{end2}), it always matches right after the haystack,
so @var{end1} is returned.
@c JP
@code{string-contains}と同様、
ソース文字列@var{string1}から探索文字列@var{string2}を探しますが、
見つかった場合は最初ではなく最後のマッチの開始インデックスを返します。
開始インデックスは@var{string1}に対するものです。
省略可能引数は@var{string1}、@var{string2}それぞれの対象とする文字列を制限します。
探索文字列@var{string2}が見つからなかった場合は@code{#f}が返されます。

エッジケースとして、探索文字列が空文字列の場合 (@var{string2}が空であるとか、
@var{start2} = @var{end2}である場合)は、
それは常にソース文字列の一番右端とマッチします。つまり@var{end1}が戻り値になります。
@c COMMON

@example
(string-contains-right "Little Lisper" "Li")
  @result{} 7
@end example
@end defun

@defun string-take-while string pred :optional start end
@defunx string-take-while-right string pred :optional start end
[SRFI-152]
@c MOD srfi-152
@c EN
Returns the longest prefix or suffix of @var{string} in which all characters
satisfy @var{pred}.

Note: The order of @var{pred} and the source object is different from
other @code{take-while}-style procedures, such as @code{take-while}
(@ref{R7RS lists}), @code{ideque-take-while} (@ref{R7RS immutable deques}),
and @code{lseq-take-while} (@ref{R7RS lazy sequences}).
@c JP
@var{string}から、全ての文字が述語@var{pred}を満たすような最長のプレフィクスまたは
サフィックスを返します。

註: @var{pred}引数と対象とするオブジェクトの順序が、
他の@code{take-while}系手続き、
@code{take-while}(@ref{R7RS lists})、
@code{ideque-take-while} (@ref{R7RS immutable deques})、
@code{lseq-take-while} (@ref{R7RS lazy sequences})等とは逆であることに
注意してください。
@c COMMON
@end defun

@defun string-drop-while string pred :optional start end
@defunx string-drop-while-right string pred :optional start end
[SRFI-152]
@c MOD srfi-152
@c EN
Returns the longest prefix or suffix of @var{string} in which all characters
does not satisfy @var{pred}.

Note: The order of @var{pred} and the source object is different from
other @code{drop-while}-style procedures, such as @code{drop-while}
(@ref{R7RS lists}), @code{ideque-drop-while} (@ref{R7RS immutable deques}),
and @code{lseq-drop-while} (@ref{R7RS lazy sequences}).
@c JP
@var{string}から、全ての文字が述語@var{pred}を満たさないような最長のプレフィクスまたは
サフィックスを返します。

註: @var{pred}引数と対象とするオブジェクトの順序が、
他の@code{drop-while}系手続き、
@code{drop-while}(@ref{R7RS lists})、
@code{ideque-drop-while} (@ref{R7RS immutable deques})、
@code{lseq-drop-while} (@ref{R7RS lazy sequences})等とは逆であることに
注意してください。
@c COMMON
@end defun

@defun string-span string pred :optional start end
@defunx string-break string pred :optional start end
[SRFI-152]
@c MOD srfi-152
@c EN
Find the longest prefix of @var{string} between @var{start} and @var{end}
in which all characters satisy / do not satisfy @var{pred}, and returns
the prefix and the rest of substring as two values.
@c JP
@var{string}の@var{start}から@var{end}までの範囲のうち、
全ての文字が述語@var{pred}を満たす、あるいは満たさないような最長のプレフィクスをみつけ、
そのプレフィクスと、残りの部分文字列を二つの値として返します。
@c COMMON

@example
(string-break "foo@@example.com" (cut eqv? <> #\@@))
 @result{} "foo" @r{and} "@@example.com"

(string-break "foo@@example.com" (cut eqv? <> #\@@) 1 10)
 @result{} "oo" "@@exampl"

@c EN
;; This is Gauche specific - a char-set can work as a predicate:
@c JP
;; Gaucheでは文字集合を述語手続きとしても使える
@c COMMON
(string-span "VAR_1 = $VAR_2" #[\w])
 @result{} "VAR_1" @r{and} " = $VAR_2"
@end example

@c EN
Note: The order of @var{pred} and the source object is different from
@code{span} and @code{break} in @code{scheme.list}
(@pxref{R7RS lists}).
@c JP
@var{pred}引数とソースオブジェクトの順が、
@code{scheme.list}の@code{span}、@code{break}と逆であることに注意
(@ref{R7RS lists}参照)。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node First-class dynamic extents, Homogeneous numeric vector libraries, String library (reduced), Library modules - SRFIs
@section @code{srfi-154} - First-class dynamic extents
@c NODE 第一級の動的エクステント, @code{srfi-154} - 第一級の動的エクステント

@deftp {Module} srfi-154
@mdindex srfi-154
@c EN
This module provides a convenient way to reify the dynamic environment.
A continuation captured by @code{call/cc} includes the dynamic environment,
as well as the control flow.  Sometimes you only want the dynamic environment
part.  A dynamic extent is a reified dynamic environment.
@c JP
このモジュールは、動的環境を簡単に取り出す手段を提供します。
@code{call/cc}によって捕捉される継続は、制御フローと同時に動的環境を保持しますが、
時には動的環境だけが欲しい場合があります。
動的エクステントは、具象化された動的環境です。
@c COMMON

@c EN
Let's see an example.  You want a procedure that prints out
a message to the error port, so you wrote this @code{print-error}:
@c JP
例で見てみましょう。メッセージをエラー出力に出したいので、
こんな@code{print-error}を書いたとします:
@c COMMON

@example
(define print-error
  (lambda (msg) (display msg (current-error-port))))
@end example

@c EN
However, if @code{print-error} is called while the current error port
is altered, it is affected.  It is supposed to be so, that's
the point of @code{current-error-port}.
@c JP
ところで、@code{print-error}が呼ばれた時点で現在のエラー出力ポートが置き換えられていたら、
出力先は変わります。もちろん、そのための@code{current-error-port}なのですから、
これは想定された動作です。
@c COMMON

@example
(call-with-output-string
  (^p (with-error-to-port p (^[] (print-error "abc\n")))))
 @result{} "abc\n"
@end example

@c EN
If you do want @code{print-error} to use the error port
at the time it is defined, you have to extract the dynamic value
at the moment.
@c JP
けれども、@code{print-error}が定義された時点でのエラー出力ポートを常に使いたい
場合はどうすれば良いでしょうか。ひとつの方法は、定義時のエラー出力ポートの
動的な値を保存しておくことです：
@c COMMON

@example
(define print-error
  (let1 eport (current-error-port)
    (lambda (msg) (display msg eport))))
@end example

@c EN
This would be quickly cumbersome when you need to capture multiple
dynamic values, or the original @code{print-error} is called indirectly
and you can't modify it the way shown above.
@c JP
しかし、これは捕捉したい動的な値が増えればややこしくなりますし、
@code{print-error}が自分の触れない箇所で定義されていて書き換えられない場合も
面倒です。
@c COMMON

@c EN
Using @code{dynamic-lambda} addresses this issue.  It not only captures
the lexical environment, but also the dynamic environment when it
is evaluated.  So the @code{current-error-port} in its body
returns the current error port at the time of @code{print-error}
being defined, not when it is called:
@c JP
@code{dynamic-lambda}は、レキシカルな環境だけでなくそれが評価された時点の
動的環境をも捕捉することでこの問題を解決します。
次の例では、@code{current-error-port}は@code{print-error}が定義された時点の
値を返します：
@c COMMON

@example
(define print-error
  (dynamic-lambda (msg) (display msg (current-error-port))))
@end example
@end deftp

@defun current-dynamic-extent
[SRFI-154]
@c MOD srfi-154
@c EN
Returns a dynamic-extent object that reifies the current dynamic
environment.
@c JP
現在の動的環境を具象化した動的エクステントオブジェクトを返します。
@c COMMON
@end defun

@defun dynamic-extent? obj
[SRFI-154]
@c MOD srfi-154
@c EN
Returns @code{#t} iff @var{obj} is a dynamic-extent object.
@c JP
@var{obj}が動的エクステントオブジェクトの時のみ@code{#t}を返します。
@c COMMON
@end defun

@defun with-dynamic-extent dynext thunk
[SRFI-154]
@c MOD srfi-154
@c EN
Calls the @var{thunk} in the dynamic extent @var{dynext}, and
returns the values yielded by @var{thunk}.
@c JP
動的環境を動的エクステント@var{dynext}で置き換えた状態で
@var{thunk}を呼びます。@var{thunk}が返した値が戻り値となります。
@c COMMON
@end defun

@defmac dynamic-lambda formals body @dots{}
[SRFI-154]
@c MOD srfi-154
@c EN
Like @code{lambda}, but this not only captures the lexical environment,
but also the dynamic environment.  Yields a procedure.

Note: Since @code{dynamic-lambda} needs to swap the dynamic environment
after executing @var{body}, the last expression of @var{body} isn't
called in the tail context even if the procedure created by
@code{dynamic-lambda} is called in tail context.
@c JP
@code{lambda}のように振る舞いますが、レキシカルな環境だけでなく、
評価時の動的環境も捕捉します。手続きを返します。

註: @code{dynamic-lambda}は最後の@var{body}の実行が終わった後で動的環境を
戻さなければならないので、@code{dynamic-lambda}で作られた手続きが末尾呼び出し
されたとしても、@var{body}の末尾式は末尾呼び出しにはなりません。
@c COMMON
@end defmac



@c ----------------------------------------------------------------------
@node Homogeneous numeric vector libraries, Comparator sublibrary, First-class dynamic extents, Library modules - SRFIs
@section @code{srfi-160} - Homogeneous numeric vector libraries
@c NODE 均質な数値ベクタライブラリ, @code{srfi-160} - 均質な数値ベクタライブラリ

@deftp {Module} srfi-160
@mdindex srfi-160
This is an enhancement of srfi-4, Homogeneous vectors
(@pxref{Homogeneous vectors}), and then become a part
of R7RS-large (@pxref{R7RS uniform vectors}).

In Gauche, all the procedures in this module are provided
as a part of @code{gauche.uvector} module
(@pxref{Uniform vectors}, and described there.

This module only exports the procedures defined in @code{srfi-160}.
@end deftp

@c ----------------------------------------------------------------------
@node Comparator sublibrary, POSIX API, Homogeneous numeric vector libraries, Library modules - SRFIs
@section @code{srfi-162} - Comparator sublibrary
@c NODE 比較器のサブライブラリ, @code{srfi-162} - 比較器のサブライブラリ

@deftp {Module} srfi-162
@mdindex srfi-162
This is a supplement of srfi-128, comparators.  It provides
a few comparator procedures, as well as several useful
pre-defined comparators, listed below.
Theese pre-defined comparators are already built in Gauche,
so see @ref{Predefined comparators} for the details.

@example
default-comparator    boolean-comparator    real-comparator
char-comparator       char-ci-comparator    string-comparator
string-ci-comparator  pair-comparator       list-comparator
vector-comparator     eq-comparator         eqv-comparator
equal-comparator
@end example
@end deftp

@defun comparator-min comparator obj obj2 @dots{}
@defunx comparator-max comparator obj obj2 @dots{}
[SRFI-162]
@c MOD srfi-162
Find the object in @var{obj1} @var{obj2} @dots{} that is
minimum or maximum compared by @var{comparator}.
Note: Srfi-114 provides the same procedures.

@example
(comparator-min list-comparator '(a c b) '(a d) '(a c))
  @result{} (a c)
@end example
@end defun

@defun comparator-min-in-list comparator list
@defunx comparator-min-in-list comparator list
[SRFI-162]
@c MOD srfi-162
Find the object in @var{list} that is minimum or maximum compared
by @var{comparator}.  It is an error if @var{list} is empty.
@end defun

@c ----------------------------------------------------------------------
@node POSIX API, Hooks (srfi), Comparator sublibrary, Library modules - SRFIs
@section @code{srfi-170} - POSIX API

@deftp {Module} srfi-170
@mdindex srfi-170
This module provides a portable interface to a part of POSIX API,
mainly filesystem interface.

In Gauche, it is a thin wrapper of Gauche's native system interface
(@pxref{System interface}).  You may want to use this module for
a portable code.
@end deftp

@subheading POSIX Error

@defun posix-error? obj
[SRFI-170]
@c MOD srfi-170
Returns @code{#t} iff @var{obj} is a condition thrown due to
underlying POSIX-layer error.  On Gauche, POSIX-layer condition
is the same as @code{<system-error>} (@pxref{Conditions}).
@end defun

@defun posix-error-name err
[SRFI-170]
@c MOD srfi-170
The argument must be a POSIX-layer condition (@code{<system-error>} object).
Returns the POSIX error name such as @code{ENOENT}.

See also @code{sys-errno->symbol} (@pxref{System inquiry}).
@end defun

@defun posix-error-message err
[SRFI-170]
@c MOD srfi-170
The argument must be a POSIX-layer condition (@code{<system-error>} object).
Returns the error message describing the error.

See also @code{sys-strerror} (@pxref{System inquiry}).
@end defun

@subheading I/O

@defun open-file fname port-type flags :optional permission buffer-mode
[SRFI-170]
@c MOD srfi-170
Opens a file named by @var{fname} and returns a port to read or write
the file.  You have finer control than
@code{open-input-file}/@code{open-output-file}.

The @code{port-type} argument must be either one of the value
of the constant @code{binary-input}, @code{textual-input},
@code{binary-output}, @code{textual-output} and
@code{binary-input/output}.  The direction of the returned port
is determined by this argument.

Gauche doesn't distinguish textual ports and binary ports.

The @var{flags} argument is a bitwise ior of
zero or more of the following bitmasks:
@code{open/append}, @code{open/create}, @code{open/exclusive},
@code{open/nofollow} and @code{open/truncate}.  These corresponds
to the POSIX flags @code{O_APPEND}, @code{O_CREAT}, @code{O_EXCL},
@code{O_NOFOLLOW} and @code{O_TRUNC}.  Gauche exposes the POSIX flags
in @code{gauche.fcntl} (@pxref{Low-level file operations}).

Note: POSIX @code{open(2)} also requires one of the bitmasks
@code{O_RDONLY}, @code{O_WRONLY} and @code{O_RDWR}.  These flags
are deduced from the @var{port-type} argument.

The optional @var{permission} is an integer permission bits
to be used when a new file is created.  The actual permission bits
are also affected by the current @code{umask}.

The optional @var{buffer-mode} is a value of either one of the followings:
@code{buffer-none}, @code{buffer-block}, and @code{buffer-line}.
@end defun

@defun fd->port fd port-type :optional buffer-mode
[SRFI-170]
@c MOD srfi-170
Creates a Scheme port wrapping an integer file descriptor @var{fd}.
The descriptor shouldn't be used by other Scheme ports.  After calling
this procedure, no I/O should be done via @var{fd} directly; the descriptor
is ``owned'' by the port, and will be closed once the port is closed.

The @code{port-type} argument must be either one of the value
of the constant @code{binary-input}, @code{textual-input},
@code{binary-output}, @code{textual-output} and
@code{binary-input/output}.  The direction must match how @var{fd} was
opened.

The optional @var{buffer-mode} is a value of either one of the followings:
@code{buffer-none}, @code{buffer-block}, and @code{buffer-line}.
@end defun

@defvr {Constant} binary-input
@defvrx {Constant} textual-input
@defvrx {Constant} binary-output
@defvrx {Constant} textual-output
@defvrx {Constant} binary-input/output
[SRFI-170]
@c MOD srfi-170
Constants to be used as @var{port-type} argument of
@code{open-file} and @code{fd->port}.
@end defvr

@defvr {Constant} buffer-none
@defvrx {Constant} buffer-block
@defvrx {Constant} buffer-line
[SRFI-170]
@c MOD srfi-170
Constants to be used as @var{buffer-mode} argument of
@code{open-file} and @code{fd->port}.
@end defvr

@defvr {Constant} open/append
@defvrx {Constant} open/create
@defvrx {Constant} open/exclusive
@defvrx {Constant} open/nofollow
@defvrx {Constant} open/truncate
[SRFI-170]
@c MOD srfi-170
Bitmask constants to be used as @var{flags} argument of
@code{open-file}.
@end defvr

@subheading File System

@defun create-directory fname :optional permission
@defunx create-fifo fname :optional permission
@defunx create-hard-link old-fname new-fname
@defunx create-symlink old-fname new-fname
[SRFI-170]
@c MOD srfi-170
Corresponds to Gauche's built-in @code{sys-mkdir}, @code{sys-mkfifo},
@code{sys-link} and @code{sys-symlink}.

The default value of @var{permission} is @code{#o775} for 
@code{create-directory}, and @code{#o664} for @code{create-fifo}
(It's not optoinal for Gauche's built-in).

On Windows, @code{create-fifo} and @code{create-symlink} are
not supported.  Procedures exist, but raise an error when called.
@end defun

@defun read-symlink name
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-readlink}.
@end defun

@defun rename-file old new
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-rename}.
@end defun

@defun delete-directory name
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-rmdir}.  The directory must be empty.
@end defun

@defun set-file-owner fname uid gid
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-chown}.  The @var{uid} and @var{gid} arguments
should be an integer uid/gid, or the value of the constant
@code{owner/unchanged} and @code{group/unchanged}, respectively,
to indicate to keep the original value.
@end defun

@defvr {Constant} owner/unchanged
@defvrx {Constant} group/unchanged
[SRFI-170]
@c MOD srfi-170
Constants to be passed as @var{uid} and @var{gid} arguments
of @code{set-file-owner}, respectively.
@end defvr


@defun set-file-times funame :optional atime mtime
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-utime}.  The @var{atime} and @var{mtime}
arguments must be a @code{<time>} object (@pxref{Time}), or
either one of the values of constants @code{time/now} or
@code{time/unchanged}.  The constant @code{time/now}
indicates the time when the procedure is called,
and the constant @code{time/unchanged} indicates the
corresponding timestamp remains the same.
@end defun

@defvr {Constant} time/now
@defvrx {Constant} time/unchanged
[SRFI-170]
@c MOD srfi-170
Constants that can be passed to @var{atime} and @var{mtime}
arguments of @code{set-file-times}.
@end defvr

@defun truncate-file fname-or-port len
[SRFI-170]
@c MOD srfi-170
The first argument can be a string filename or a open port associated
to a file.  If it is a filename, @code{sys-truncate} is called,
and if it is a port, @code{sys-ftruncate} is called.
@end defun

@defun file-info fname-or-port follow?
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-stat}, @code{sys-lstat} or @code{sys-fstat}.

The first argument can be a string filename or a open port associated
to a file.  If it is a filename, @code{sys-stat} or @code{sys-lstat}
is called depending on whether @var{follow?} is @code{#t} or @code{#f}.
If it is a port, @code{sys-fstat} is called.

Returns a file-info object, which is a @code{<sys-stat>} instance
in Gauche (@pxref{File stats}).
@end defun

@defun file-info? obj
[SRFI-170]
@c MOD srfi-170
Returns @code{#t} iff @var{obj} is a file-info object, which is
a @code{<sys-stat>} instance in Gauche (@pxref{File stats}).
@end defun

@defun file-info:device file-info
@defunx file-info:inode file-info
@defunx file-info:mode file-info
@defunx file-info:nlinks file-info
@defunx file-info:uid file-info
@defunx file-info:gid file-info
@defunx file-info:rdev file-info
@defunx file-info:size file-info
@defunx file-info:blksize file-info
@defunx file-info:blocks file-info
@defunx file-info:atime file-info
@defunx file-info:mtime file-info
@defunx file-info:ctime file-info
[SRFI-170]
@c MOD srfi-170
Accessorso of file-info object (@code{<sys-stat>}) (@pxref{File stats}).
Access its @code{dev}, @code{ino}, @code{mode}, @code{nlink},
@code{uid}, @code{gid}, @code{rdev}, @code{size},
@code{blksize}, @code{blocks}, @code{atim}, @code{mtim}, @code{ctim}
slots, respectively.

Note: @code{<sys-stat>}'s @code{atime}, @code{mtime} and @code{ctime}
contains integer for the backward compatibility, while
@code{file-info:atime}, @code{file-info:mtime} and @code{file-info:ctime}
returns @code{<time>} object.
@end defun

@defun file-info-directory? file-info
@defunx file-info-fifo? file-info
@defunx file-info-symlink? file-info
@defunx file-info-regular? file-info
@defunx file-info-socket? file-info
@defunx file-info-device? file-info
[SRFI-170]
@c MOD srfi-170
Returns true iff the file-info object (@code{<sys-stat>} is of the
respective type.  (@code{file-info-device?} returns true if
the file is either block or character device).
It corresponds to the @code{type} slot of @code{<sys-stat>}.
@end defun

@defun set-file-mode fname mode-bits
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-chmod}.
@end defun

@defun directory-files dir :optional dotfiles?
[SRFI-170]
@c MOD srfi-170
Returns a list of filenames in the directory named @var{dir}.
Similar to @code{directory-list} in @code{file.util}
(@pxref{Directory utilities}), but (1) it never includes
@code{.} and @code{..} (as true value is given to @code{:children?}
argument of @code{directory-list}), and (2) it doesn't include
files beginning with @code{.} by default, unless @code{dotfiles?} is true.
@end defun

@defun make-directory-files-generator dir :optional dotfiles?
[SRFI-170]
@c MOD srfi-170
Returns a generator (@pxref{Generators}) that generates file names
in the directory named @var{dir}.  The names never include
@code{.} and @code{..}, and the filenames beginning with @code{.} is
omitted unless @var{dotfiles?} is true.
@end defun

@defun open-directory dir :optional dotfiles?
@defunx read-directory dir-object
@defunx close-directory dir-object
[SRFI-170]
@c MOD srfi-170
This is a directory scanner API more close to POSIX @code{opendir},
@code{readdir} and @code{closedir}.  A directory object is opened
with @code{open-directory}, and its entries (filenames) can be read
one by one using @code{read-directory}.  If the file names are exausted,
@code{read-directory} returns an EOF object.  A directory object
must be closed with @code{close-directory}.

The filenames to be retrieved are the same as @code{directory-files}; that is,
@code{.} and @code{..} are never included, and names beginning with @code{.}
is exluded unless @var{dotfiles?} is true.
@end defun

@defun real-path path
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-realpath}.
@end defun

@defun file-space path-or-port
[SRFI-170]
@c MOD srfi-170
Returns the free space of a file system where a file specified by
@var{path-or-port} resides, in number of bytes.
@end defun

@deffn {Parameter} temp-file-prefix
[SRFI-170]
@c MOD srfi-170
A parameter holding a path prefix to be used by @code{create-temp-file}
and @code{call-with-temporary-filename}.  In Gauche,
the default value is set to
@code{(build-path (temporary-directory) (x->string (sys-getpid)))}.
@xref{Temporary files and directories}, for the description of
@code{temporary-directory}.
@end deffn

@defun create-temp-file :optional prefix
[SRFI-170]
@c MOD srfi-170
@end defun

@defun call-with-temporary-filename maker :optional prefix
[SRFI-170]
@c MOD srfi-170
@end defun

@subheading Process state

Note: For srfi-170's @code{current-directory}, we reuse
@code{file.util}'s one.  @xref{Directory utilities}, for the description.

@defun umask
[SRFI-170]
@c MOD srfi-170
Returns the current umask value.
Gauche's @code{sys-umask} without argument.
@end defun

@defun set-umask! mask
[SRFI-170]
@c MOD srfi-170
Sets @var{mask}, which must be a nonnegative exact integer, 
as the current umask.
Gauche's @code{sys-umask}, except that it returns unspecified value.
@end defun

@defun set-current-directory! dir
[SRFI-170]
@c MOD srfi-170
Sets the process's current working directory to @var{dir}.
Gauche's @code{sys-chdir}.
It can also be done with @code{current-working-directory} in @code{file.util}
(@pxref{Directory utilities}).
@end defun

@defun pid
[SRFI-170]
@c MOD srfi-170
Returns the current process id.  Gauche's @code{sys-getpid}.
@end defun

@defun nice :optional delta
[SRFI-170]
@c MOD srfi-170
Increments the current process's nice value by @var{delta}, which must
be an exact integer.  The lower the nice value is, the more chance
the process gets run.  If omitted, @var{delta} is assumed to be 1.
Gauche's @code{sys-nice}.
@end defun

@defun user-uid
@defunx user-gid
@defunx user-effective-uid
@defunx user-effecitve-gid
@defunx user-supplementary-gids
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-getuid}, @code{sys-getgid}, @code{sys-geteuid},
@code{sys-getegid}, and @code{sys-getgroups}, respectievly.
@end defun

@subheading User and group database access

@defun user-info uid-or-name
[SRFI-170]
@c MOD srfi-170
Returns a user-info object, which is a @code{<sys-passwd>} instance
in Gauche, of a user specified by @var{uid-or-name}, which must be
an exact integer uid or a string username.
If it is an uid, @var{sys-getpwuid} is called, and if it is a username
@code{sys-getpwnam} is called.
@end defun

@defun user-info? obj
[SRFI-170]
@c MOD srfi-170
Returns @code{#t} iff @var{obj} is a user-info object (@code{<sys-passwd>}).
@end defun

@defun user-info:name uinfo
@defunx user-info:uid uinfo
@defunx user-info:gid uinfo
@defunx user-info:home-dir uinfo
@defunx user-info:shell uinfo
@defunx user-info:full-name uinfo
[SRFI-170]
@c MOD srfi-170
Returns the value of @var{name}, @code{uid}, @code{gid}, @code{dir},
@code{shell} and @var{gecos} slots of a user-info object (@code{<sys-passwd})
@var{uinfo}.
@end defun

@defun user-info:parsed-full-name uinfo
[SRFI-170]
@c MOD srfi-170
@end defun

@defun group-info gid-or-name
[SRFI-170]
@c MOD srfi-170
Returns a group-info object, which is a @code{<sys-group>} instance
in Gauche, of a group specified by @var{gid-or-name}, which must be
an exact integer gid or a string groupname.
If it is an gid, @var{sys-getgrgid} is called, and if it is a groupname
@code{sys-getgrnam} is called.
@end defun

@defun group-info? obj
[SRFI-170]
@c MOD srfi-170
Returns @code{#t} iff @var{obj} is a group-info object (@code{<sys-group}).
@end defun

@defun group-info:name ginfo
@defunx group-info:gid ginfo
[SRFI-170]
@c MOD srfi-170
Returns the value of @code{name} and @code{gid} slot of a group info
(@code{<sys-group>}).
@end defun

@subheading Time

@defun posix-time
[SRFI-170]
@c MOD srfi-170
Same as @code{current-time} (@pxref{Time}).  Return value is a @code{<time>}
instance of @code{time-utc}.
@end defun

@defun monotonic-time
[SRFI-170]
@c MOD srfi-170
Returns a @code{<time>} instance of @code{time-monotonic}, representing
a elapsed time since an unspecified epoch.  It is guaranteed to monotonically
increasing during the lifetime of the process, even if the system clock
is modified.
@end defun

@subheading Environment variables

@xref{Accessing environment variables}, for getting environment variables.
This srfi defines the means to modify them.

@defun set-enviroment-variable! name value
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-setenv} with the third argument being @code{#t}
(overwrite the existing value).
@end defun

@defun delete-environment-variable! name
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-unsetenv}.
@end defun

@subheading Terminal device control

@defun terminal? port
[SRFI-170]
@c MOD srfi-170
Gauche's @code{sys-isatty}.
@end defun

@c ----------------------------------------------------------------------
@node Hooks (srfi), POSIX timespecs, POSIX API, Library modules - SRFIs
@section @code{srfi-173} - Hooks (srfi)
@c NODE フック(srfi), @code{srfi-173} - フック(srfi)

@deftp {Module} srfi-173
@mdindex srfi-173
@c EN
This module provides hooks, which manages a list of
closures to be called.

It is based on Guile's hooks, which Gauche supports in
@code{gauche.hook} module (@pxref{Hooks}).  This srfi
is a thin layer on top of @code{gauche.hook}.

The following procedures are the same as @code{gauche.hook}:
@c JP
このモジュールは、呼ばれるべきクロージャのリストを管理する「フック」を提供します。

GaucheではもともとGuileにあったhookの仕様を
@code{gauche.hook}モジュールとして採り入れています
(@ref{Hooks}参照)。
このsrfiは@code{gauche.hook}に薄いレイヤをかぶせたものです。

以下の手続きは@code{gauche.hook}のものと同じです。
@c COMMON

@example
make-hook     hook?      hook->list
@end example
@end deftp

@defun hook-add! hook proc
[SRFI-173]
@c MOD srfi-173
@c EN
Add a procedure @var{proc} to a hook @var{hook}.   The procedure
must accept the number of arguments that matches the arity of the hook.
It is the same as @code{(add-hook! hook proc)} of @code{gauche.hook}.
@c JP
手続き@var{proc}をフック@var{hook}に追加します。手続きは、フックのアリティと
同じ数の引数を受け付けなければなりません。
これは@code{gauche.hook}の@code{(add-hook! hook proc)}と同じです。
@c COMMON
@end defun

@defun hook-delete! hook proc
[SRFI-173]
@c MOD srfi-173
@c EN
Delete @var{proc} from @var{hook}.  If @var{proc} isn't in @var{hook},
do nothing.  It is the same as @code{(delete-hook! hook proc)}
of @code{gauche.hook}.
@c JP
@var{proc}を@var{hook}から削除します。@var{proc}が@var{hook}に登録されていない
場合は何もしません。
@code{gauche.hook}の@code{(delete-hook! hook proc)}と同じです。
@c COMMON
@end defun

@defun hook-reset! hook
[SRFI-173]
@c MOD srfi-173
@c EN
Remove all the procedures registered in @var{hook}.
It is the same as @code{(reset-hook! hook)} of @code{gauche.hook}.
@c JP
@var{hook}に登録された全ての手続きを削除します。
@code{gauche.hook}の@code{(reset-hook! hook)}と同じです。
@c COMMON
@end defun

@defun hook-run hook args @dots{}
[SRFI-173]
@c MOD srfi-173
@c EN
Apply all the procedures from @var{hook} to the @var{args}.
The order of the procedure isn't specified in the srfi, though
Gauche preserves the order (see @code{run-hook}
(@pxref{Hooks}).
@c JP
@var{hook}に登録された手続き全てを順次、@var{args}を引数として呼び出します。
srfiでは手続きを呼び出す順番は指定されていません。
Gaucheは登録された順序で呼び出します
(@ref{Hooks}の@code{run-hook}参照)。
@c COMMON
@end defun

@defun list->hook arity list
[SRFI-173]
@c MOD srfi-173
@c EN
Creates a new hook with specified @var{arity} (which is a non-negative
exact integer), which has the procedures in @var{list}.
All the procedures must accept @var{arity} number of arguments.
@c JP
アリティ@var{arity} (非負の正確な整数) を持つフックを作り、
手続きのリスト@var{list}中の手続きをフックに登録して、そのフックを返します。
全ての手続きは@var{arity}個の引数を受け付けなくてはなりません。
@c COMMON
@end defun

@defun list->hook! hook list
[SRFI-173]
@c MOD srfi-173
@c EN
Replace the list of procedures in @var{hook} with procedures
in @var{list}.
All the procedures must accept the number of arguments
the same as @var{hook}'s arity.
@c JP
フック@var{hook}に登録された手続きのリストを、@var{list}にある手続きと
置き換えます。
全ての手続きは@var{arity}個の引数を受け付けなくてはなりません。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node POSIX timespecs, ASCII character library, Hooks (srfi), Library modules - SRFIs
@section @code{srfi-174} - POSIX timespecs

@deftp {Module} srfi-174
@mdindex srfi-174
Note: This srfi is originally intended to be used with srfi-170
(@pxref{POSIX API}), but it turned out this was not enough to support
the latter--notably, we need srfi-19 type argument in the constructor.

Consequently, it is likely that this srfi will be superseded later.
We deprecate using this srfi; if you need a portable time representation,
srfi-19 is the best choice at this moment.  @xref{Time data types and procedures},
for the details.
@end deftp

@defun timespec secs nsecs
[SRFI-174]
@c MOD srfi-174
Creates and returns a timespec, whose second part is @var{secs} and
nanosecond part is @var{nsecs}.  The second part must be an exact
integer; if it is positive, it's the number of seconds since
Epoch (Jan 1, 1970 UTC), and if it's negative, it's before the Epoch.
The nanosecond part is a nonnegative integer less than 1e9, and represents
the fraction of seconds in nanosecond resolution.  Note that if the second
part is negative, the nanosecond part counts toward past.

This is the same as @code{(make-time time-utc nsecs secs)} of
srfi-19.  Note the order of arguments.
@end defun

@defun timespec? obj
[SRFI-174]
@c MOD srfi-174
Returns @code{#t} iff @var{obj} is a @code{<time>} object.  It doesn't
check the type of time.
@end defun

@defun timespec-seconds ts
@defunx timespec-nanosecods ts
[SRFI-174]
@c MOD srfi-174
Returns second and nanosecond part of the @code{<time>} object.
Same as @code{time-second} and @code{time-nanosecond} of srfi-19
(note that we use plurals in this srfi).
@end defun

@defun inexact->timespec v
[SRFI-174]
@c MOD srfi-174
Convert an inexact real number @var{v} to a timespec.  The integral part
of @var{v} is the seconds after (when @var{v} is positive)  
or before (when @var{v} is negative) the Epoch, and the fractional part
is rounded into nanosecond resolution.
@end defun

@defun timespec->inexact ts
[SRFI-174]
Convert a timespec into an inexact real number in seconds.
@c MOD srfi-174
@end defun

@defun timespec=? ts1 ts2
[SRFI-174]
@c MOD srfi-174
Returns @code{#t} iff two timespecs are the same.
It is the same as @code{time=?} in srfi-19.
@end defun

@defun timespec<? ts1 ts2
[SRFI-174]
@c MOD srfi-174
Returns @code{#t} iff a timespec @var{ts1} is strictly before
the timespec @var{ts2}.  It is the same as @code{time<?} in srfi-19.
@end defun

@defun timespec-hash ts
[SRFI-174]
@c MOD srfi-174
Compute a hash value of a timespec @var{ts}.  It is same as
passing a @code{<time>} object to @code{default-hash}, and
affected by the current hash salt value (@pxref{Hashing}).
@end defun

@c ----------------------------------------------------------------------
@node ASCII character library, Bitvector library, POSIX timespecs, Library modules - SRFIs
@section @code{srfi-175} - ASCII character library
@c NODE ASCII文字ライブラリ, @code{srfi-175} - ASCII文字ライブラリ

@deftp {Module} srfi-175
@mdindex srfi-175
@c EN
This module provides a set of character/string utilities that deal with
ASCII characters and codepoints.  It is particulary useful for small
Scheme implementations that only handles, and a portable
code that only concerns, ASCII characters.
@c JP
ASCII文字とASCIIコードポイントを扱うユーティリティを提供するモジュールです。
ASCIIだけを対象とする小さなScheme実装や、ASCIIだけを対象とするポータブルな
コードを書きたい場合に便利です。
@c COMMON

@c EN
Since Gauche supports full Unicode (if it is compiled with utf-8 internal
encoding, which is the default), you may not need to use this module
to write Gauche-specific code.  This is mainly for the compatibility.
@c JP
Gaucheは(内部エンコーディングをデフォルトのutf-8でコンパイルしていれば)
Unicodeの全ての文字を扱えるので、Gauche用のコードを書いている時には
敢えてこのモジュールを使う必要は無いでしょう。互換性のために用意しています。
@c COMMON

@c EN
One of the characteristics of this module is that many procedures can
take an integer in place of a character; an integer between 0 and 127
is interpreted as an ASCII codepoint.  An integer outside the range
is interpreted as an non-ASCII codepoint.  Such argument is noted
as @var{char-or-code} in the description.  It is handy while you're
dealing with a binary file which may contain some ASCII text in it.
@c JP
このモジュールに特徴的なのは、多くの手続きで、文字のかわりに整数を取れることです。
0と127の間の正確な整数はASCIIコードポイントと解釈されます。
それ以外の整数は非ASCIIコードポイントと解釈されます。
文字と整数の両方を取れる引数は、@var{char-or-code}と表記しています。
例えばバイナリファイルの一部にASCIIテキストが含まれるものを扱う際に便利でしょう。
@c COMMON
@end deftp

@defun ascii-codepoint? obj
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{obj} is an exact integer between 0 and 127,
inclusive.
@c JP
@var{obj}が0..127の範囲の正確な整数であれば@code{#t}を、そうでなければ@code{#f}を
返します。
@c COMMON
@end defun

@defun ascii-bytevecotr? obj
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{obj} is a bytevector (@code{u8vector}) and
all of its elements are between 0 and 127, inclusive.
@c JP
@var{obj}がバイトベクタ(@code{u8vector})で、全ての要素が0..127の範囲に収まっていれば
@code{#t}を、そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@defun ascii-char? obj
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{obj} is an ASCII character.
@c JP
@var{obj}がASCII文字であれば@code{#t}を、そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@defun ascii-string? obj
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{obj} is a string and all of its elements
are ASCII characters.
@c JP
@var{obj}が文字列で、その中の全ての文字がASCII文字なら@code{#t}を、そうでなければ
@code{#f}を返します。
@c COMMON
@end defun

@defun ascii-control? char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{char-or-code} is in the range of
ASCII control characters
@c JP
@var{char-or-code}がASCII制御文字の範囲なら@code{#t}を、そうでなければ@code{#f}を
返します。
@c COMMON

@example
(ascii-control? #\tab) @result{} #t
(ascii-control? #\A)   @result{} #f

(ascii-control? 127)   @result{} #t
(ascii-control? 255)   @result{} #f
@end example

@c EN
Note: The accepted character range corresponds to
@code{char-set:ascii-control} (@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は@code{char-set:ascii-control}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-non-control? char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{char-or-code} is in the range of ASCII but
not a control character.
@c JP
@var{char-or-code}がASCIIの範囲でかつ制御文字でなければ@code{#t}を、
そうでなければ@code{#f}を
返します。
@c COMMON
@end defun

@defun ascii-space-or-tab? char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{char-or-code} is a tab or a whitespace.
@c JP
@var{char-or-code}がタブ文字かASCII空白文字であれば@code{#t}を、
そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@defun ascii-other-graphic? char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{char-or-code} is in the range of ASCII
graphic characters but not a letter nor a digit.
@c JP
@var{char-or-code}がASCIIの範囲で、アルファベットと数字以外の
グラフィック文字であれば@code{#t}を返します。
@c COMMON

@c EN
Note: The accepted character range corresponds to
@code{(char-set-difference char-set:ascii-graphic char-set:ascii-letter+digit)}
(@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は
@code{(char-set-difference char-set:ascii-graphic char-set:ascii-letter+digit)}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-alphanumeric? char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{char-or-code} is in the ASCII alphabet or digit
range.
@c JP
@var{char-or-code}がASCIIアルファベットか数字であれば@code{#t}を、
そうでなければ@code{#f}を返します。
@c COMMON

@c EN
Note: The accepted character range corresponds to
@code{char-set:ascii-letter+digit}
(@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は
@code{char-set:ascii-letter+digit}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-alphabetic? char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{#t} iff @var{char-or-code} is in the ASCII alphabet range.
@c JP
@var{char-or-code}が
@c COMMON

@c EN
Note: The accepted character range corresponds to
@code{char-set:ascii-letter}
(@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は
@code{char-set:ascii-letter}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-numeric? char-or-code
[SRFI-175]
@c MOD srfi-175
Returns @code{#t} iff @var{char-or-code} is in the ASCII digit range.

@c EN
Note: The accepted character range corresponds to
@code{char-set:ascii-digit}
(@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は
@code{char-set:ascii-digit}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-whitespace? char-or-code
[SRFI-175]
@c MOD srfi-175
Returns @code{#t} iff @var{char-or-code} is one of the ASCII whitespaces.

@c EN
Note: The accepted character range corresponds to
@code{char-set:ascii-whitespace}
(@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は
@code{char-set:ascii-whitespace}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-upper-case? char-or-code
@defunx ascii-lower-case? char-or-code
[SRFI-175]
@c MOD srfi-175
Returns @code{#t} iff @var{char-or-code} is one of upper/lower case
ASCII alphabets.

@c EN
Note: The accepted character range corresponds to
@code{char-set:ascii-upper-case}/@code{char-set:ascii-lower-case}
(@pxref{Predefined character sets}).
@c JP
@code{#t}が返される文字の集合は
@code{char-set:ascii-upper-case}/@code{char-set:ascii-lower-case}と
一致します (@ref{Predefined character sets}参照)。
@c COMMON
@end defun

@defun ascii-ci=? char-or-code1 char-or-code2
@defunx ascii-ci<? char-or-code1 char-or-code2
@defunx ascii-ci<=? char-or-code1 char-or-code2
@defunx ascii-ci>? char-or-code1 char-or-code2
@defunx ascii-ci>=? char-or-code1 char-or-code2
[SRFI-175]
@c MOD srfi-175
@c EN
Each argument may be a character or a codepoint.  If the argument
falls into ASCII upper case letters, it is converted to the corresponding
lower case letter codepoint, and then two are compared as codepoints.
Two arguments don't need to be of the same type.
@c JP
各引数は文字かコードポイントです。引数がASCIIの大文字に相当する場合、それは対応する小文字の
コードポイントに変換され、その後コードポイント同士の比較結果が返されます。
二つの引数の型が一致している必要はありません。
@c COMMON

@c EN
It is allowed to pass non-ascii range; if it is a non-ASCII character,
its codepoint of the native encoding is taken (no case-folding is considered),
and compared as codepoints.  Of course the result are not portable, except
that any non-ASCII character has a codepoint greater than any ASCII characters.
@c JP
ASCII範囲外の引数を渡すことは許されます。非ASCII文字は内部エンコーディングによるコードポイント
に変換されます(大文字小文字は考慮されません)。非ASCII文字はASCII文字より大きい、
ということ以外、結果は処理系依存になります。
@c COMMON
@end defun

@defun ascii-string-ci=? string1 string2
@defunx ascii-string-ci<? string1 string2
@defunx ascii-string-ci<=? string1 string2
@defunx ascii-string-ci>? string1 string2
@defunx ascii-string-ci>=? string1 string2
[SRFI-175]
@c MOD srfi-175
@c EN
Compares two strings with ASCII case folding.   Argument strings may
contain non-ASCII characters; such characters are compared without
case folding.
@c JP
ASCII文字の範囲で大文字小文字を考慮せずに、二つの文字列を比較します。
文字列は非ASCII文字を含んでいても構いません。それらについては大文字小文字の考慮はせず、
内部エンコーディングのコードポイントを使って比較します。
@c COMMON
@end defun

@defun ascii-upcase char-or-code
@defunx ascii-downcase char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
If the argument represents a ASCII upper/lower case letter,
returns the corresponding lower/upper case character or codepoint.
The type of the return value is the same as the argument.
If the argument is a character or a codepoint other than that,
it is returned as is.
@c JP
引数がASCIIの大文字/小文字に相当する場合、対応する小文字/大文字の文字またはコードポイントを
返します。戻り値は引数と同じ型になります。
引数がそれ以外の文字に相当する場合は、そのまま返されます。
@c COMMON
@end defun

@defun ascii-control->graphic char-or-code
@defunx ascii-graphic->control char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
ASCII control characters (@code{#\x00}, @code{#\x01} .. @code{#\x1f}, 
and @code{#\x7f})
are sometimes noted as @code{^@@}, @code{^A} .. @code{^_}, and @code{^?}.
These procedures converts the control character and corresponding
graphical character (the one comes after @code{^}), and vice versa.
The type of the return value is the same as the argument.
@c JP
ASCII制御文字(@code{#\x00}, @code{#\x01} .. @code{#\x1f}, 
and @code{#\x7f})はしばしば、
@code{^@@}, @code{^A} .. @code{^_} および @code{^?} のように
表記されます。これらの手続きは、制御文字とその表記 (@code{^}の後に来る文字)とを
相互に変換するものです。
戻り値の型は引数と同じになります。
@c COMMON

@c EN
If the argument isn't an ASCII control character / a graphical character
that corresponds to an ASCII control character, @code{#f} is returned.
@c JP
引数がASCII制御文字/制御文字に対応するASCII表示文字でなければ、@code{#f}が返ります。
@c COMMON
@end defun

@defun ascii-mirror-bracket char-or-code
[SRFI-175]
@c MOD srfi-175
@c EN
There are four pairs of brackets in ASCII: @code{(} and @code{)},
@code{@{} and @code{@}}, @code{[} and @code{]}, and @code{<} and @code{>}.
If @var{char-or-code} is either one of these eight chars or codepoints,
returns the corresponding bracket.
The type of the return value is the same as the argument.
@c JP
ASCIIには4ペアの括弧があります。@code{(}と@code{)}、
@code{@{}と@code{@}}、@code{[}と@code{]}、そして@code{<}と@code{>}です。
引数@var{char-or-code}がこれら8文字のいずれかに相当する場合に、
それと対になる文字またはコードポイントを返します。
戻り値の型は引数と同じになります。
@c COMMON

@c EN
If the argument is a char or a codepoint other than those brackets,
@code{#f} is returned.
@c JP
引数が括弧の文字またはコードポイントでなければ、@code{#f}が返されます。
@c COMMON
@end defun

@defun ascii-nth-digit n
[SRFI-175]
@c MOD srfi-175
@c EN
Returns a digit character representing the number @var{n}.
If @var{n} is not an exact integer between 0 and 9, inclusive,
@code{#f} is returned.
@c JP
数値@var{n}を表すASCII数字文字を返します。@var{n}が0から9までの正確な整数でない
場合は@code{#f}を返します。
@c COMMON

@example
(ascii-nth-digit 3) @result{} #\3
@end example

@c EN
See also @code{integer->digit} (@pxref{Characters}).
@c JP
@code{integer->digit} (@ref{Characters})も参照。
@c COMMON
@end defun

@defun ascii-nth-upper-case n
@defunx ascii-nth-lower-case n
[SRFI-175]
@c MOD srfi-175
@c EN
Returns @code{(modulo @var{n} 26)}-th character of upper/lower case
ASCII alphabet.
@c JP
@code{(modulo @var{n} 26)}番目のASCII大文字/小文字アルファベットを返します。
@c COMMON

@example
(ascii-nth-upper-case 0) @result{} #\A
(ascii-nth-lower-case 1) @result{} #\b

(ascii-nth-upper-case 25) @result{} #\Z
(ascii-nth-lower-case 26) @result{} #\a
@end example

@c EN
See also @code{integer->digit} (@pxref{Characters}).
@c JP
@code{integer->digit} (@ref{Characters})も参照。
@c COMMON
@end defun

@defun ascii-digit-value char-or-code limit
[SRFI-175]
@c MOD srfi-175
@c EN
If @var{char-or-code} represents an ASCII decimal digits and
the corresponding number is less than @var{limit},
returns the number.  Otherwise, returns @code{#f}.
@c JP
@var{char-or-code}がASCII数字文字またはそのコードポイントであり、
それが表す数値が@var{limit}未満であればその数値を、
そうでなければ@code{#f}を返します。
@c COMMON

@example
(ascii-digit-value #\5 10) @result{} 5
(ascii-digit-value #\9 8)  @result{} #f

(ascii-digit-value 48 10)  @result{} 0
@end example

@c EN
See also @code{digit->integer} (@pxref{Characters}).
@c JP
@code{digit->integer} (@ref{Characters})も参照。
@c COMMON
@end defun

@defun ascii-upper-case-value char-or-code offset limit
@defunx ascii-lower-case-value char-or-code offset limit
[SRFI-175]
@c MOD srfi-175
@c EN
If @var{char-or-code} is n-th ASCII upper/lower case alphabet,
and @var{n} is less than @var{limit}, returns @code{(+ @var{n} @var{offset})}.
Otherwise returns @code{#f}.
@c JP
@var{char-or-code}がn番目のASCII大文字/小文字またはそのコードポイントで、
nが@var{limit}未満であれば、@code{(+ @var{n} @var{offset})}を返します。
そうでなければ@code{#f}を返します。
@c COMMON

@example
(ascii-upper-case-value #\E 10 6) @result{} 14
(ascii-lower-case-value #\z 0 26) @result{} 25
@end example

@c EN
See also @code{digit->integer} (@pxref{Characters}).
@c JP
@code{digit->integer} (@ref{Characters})も参照。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node Bitvector library, JSON, ASCII character library, Library modules - SRFIs
@section @code{srfi-178} - Bitvector library
@c NODE ビットベクタライブラリ, @code{srfi-178} - ビットベクタライブラリ

@deftp {Module} srfi-178
@mdindex srfi-178
Gauche supports bitvectors as a native type, but the core library only
offers a handful of primitives.  This module complements the comprehensive
operations on bitvectors.

The following procedures are built-in.  @xref{Bitvectors}, for the description.

@example
bit->integer      bit->boolean
bitvector         make-bitvector     list->bitvector
bitvector?        bitvector-length
string->bitvector bitvector->string
bitvector-ref/int bitvector-ref/bool
bitvector-set!    bitvector-copy     bitvector-copy!
@end example
@end deftp

@subheading Constructors

@defun bitvector-unfold f length seed @dots{}
@defunx bitvector-unfold-right f length seed @dots{}
[SRFI-178]
@c MOD srfi-178
Creates a bitvector of length @var{length}, and fill its contents by
repeatedly applying @var{f}.  The procedure @var{f} must take one more
than the number of seeds, and must return the same number
of values.  First, @var{f} is applied to the index and @var{seed} @dots{},
then its first return value (which must be a bit, i.e. 0, 1 or a boolean
value) is used to initialize the first element of the bitvector,
and the rest of the return value is used as the next argument to @var{f}.
It is repeated @var{length} times.

While @code{bitvector-unfold} fills the bits from left to right,
@code{bitvector-unfold-right} does from right to left.

@example
(use math.prime)
(bitvector-unfold (^[index n]
                    (values (small-prime? n) (+ n 1))) 
                  20 0)
  @result{} #*00110101000101000101
(bitvector-unfold-right (^[index n] 
                          (values (small-prime? n) (+ n 1))) 
                        20 0)
  @result{} #*10100010100010101100  
@end example

Note: This procedure follows the protocol of @code{vector-unfold}
(@pxref{R7RS vectors}), and has a different protocol from other
@code{unfold} procedures (@pxref{R7RS lists}).
@end defun

@defun bitvector-reverse-copy bv :optional start end
[SRFI-178]
@c MOD srfi-178
Copies a bitvector @var{bv} in reverse order.  Optional @var{start}
and @var{end} arguments limits the range of the input.

@example
(bitvector-reverse-copy #*10110011100011110000 4 16)
  @result{} #*111100011100
@end example
@end defun

@defun bitvector-append bv @dots{}
[SRFI-178]
@c MOD srfi-178
All arguments must be bytevectors.  Returns a fresh bytevector
which is concatenation of all arguments.
@end defun

@defun bitvector-concatenate bvs
[SRFI-178]
The argument must be a list of bytevectors.  Returns a fresh bytevector
which is concatenation of all arguments.
@c MOD srfi-178
@end defun

@defun bitvector-append-subbitvectors bv start end @dots{}
[SRFI-178]
@c MOD srfi-178
The number of arguments must be a multiple of 3.  Each triplet of
the arguments is a bytevector followed by start and end index,
specifying the input bytevector range.  Returns a fresh bytevector
which is concatenation of all the subvectors.
@end defun

@subheading Predicates

@defun bitvector-emtpy? bv
[SRFI-178]
@c MOD srfi-178
Returns @code{#t} iff @var{bv} is an empty bytevector.
@end defun

@defun bitvector=? bv @dots{}
[SRFI-178]
@c MOD srfi-178
Returns @code{#t} iff all the bytevectors have the same content.
If there's zero or one argument, it returns @code{#t}.
@end defun

@subheading Iteration

@defun bitvector-take bv n
@defunx bitvector-take-right bv n
[SRFI-178]
@c MOD srfi-178
Returns a new bitvector with the first/last @var{n} bits of a bitvector @var{bv}.
An error is thrown if length of @var{bv} is less than @var{n}.

In Gauche, you can also use generic @code{(subseq bv 0 n)} to take the
first @var{n} bits.  @xref{Sequence framework}.
@end defun

@defun bitvector-drop bv n
@defunx bitvector-drop-right bv n
[SRFI-178]
@c MOD srfi-178
Returns a new bitvector with bits except first/last @var{n} bits of 
a bitvector @var{bv}.
An error is thrown if length of @var{bv} is less than @var{n}.

In Gauche, you can also use generic @code{(subseq bv n)}
to drop the first @var{n} bits.  @xref{Sequence framework}.
@end defun

@defun bitvector-segment bv n
[SRFI-178]
@c MOD srfi-178
Slices a bitvector @var{bv} with @var{n}-bits each, and returns
a list of bitvectors.  If the length of @var{bv} isn't a multiple
of @var{n}, the last bitvector may be shorter.
@end defun

@defun bitvector-fold/int kons knil bv1 bv2 @dots{}
@defunx bitvector-fold/bool kons knil bv1 bv2 @dots{}
@defunx bitvector-fold-right/int kons knil bv1 bv2 @dots{}
@defunx bitvector-fold-right/bool kons knil bv1 bv2 @dots{}
[SRFI-178]
@c MOD srfi-178
Fold @var{kons} over the elements of bitvectors with @var{knil} as
the initial state value.

The @var{kons} procedure is always called as
@code{(kons state e1 e2 @dots{})}, where @var{e1} @var{e2} @dots{}
are elements from each bitvectors, as integer 0/1 (for @code{/int} procdures)
or boolean @code{#f}/@code{#t} (for @code{/bool} procedures).
This is the same order as @code{vector-fold} in
@code{scheme.vector} module (@pxref{R7RS vectors}).
(Note that list @code{fold} procedure calls the @var{knil} procedure
with different order; @pxref{Walking over lists}).

All bitvectors must have the same length; otherwise, an error is thrown.
@end defun

@defun bitvector-map/int f bv1 bv2 @dots{}
@defunx bitvector-map/bool f bv1 bv2 @dots{}
[SRFI-178]
@c MOD srfi-178
Apply a procedure @var{f} over each element taken from given bitvectors.
The result of the procedure is gathered as a fresh bitvector and returned.

All bitvectors must have the same length; otherwise, an error is thrown.
@end defun

@defun bitvector-map!/int f bv1 bv2 @dots{}
@defunx bitvector-map!/bool f bv1 bv2 @dots{}
[SRFI-178]
@c MOD srfi-178
Apply a procedure @var{f} over each element taken from given bitvectors.
The result of the procedure is set into @var{bv1}.

These procedure returns undefined value; you should count on the
side effect onto @var{bv1.}

All bitvectors must have the same length; otherwise, an error is thrown.
@end defun

@defun bitvector-map->list/int f bv1 bv2 @dots{}
@defunx bitvector-map->list/bool f bv1 bv2 @dots{}
[SRFI-178]
@c MOD srfi-178
Apply a procedure @var{f} over each element taken from given bitvectors.
The result of the procedure is gathered as a list and returned.

All bitvectors must have the same length; otherwise, an error is thrown.
@end defun

@defun bitvector-for-reach/int f bv1 bv2 @dots{}
@defunx bitvector-for-reach/bool f bv1 bv2 @dots{}
[SRFI-178]
@c MOD srfi-178
Apply a procedure @var{f} over each element taken from given bitvectors.
The result of the procedure is discarded.

All bitvectors must have the same length; otherwise, an error is thrown.
@end defun

@subheading Prefixes, suffixes, trimming and padding

@defun bitvector-prefix-length bv1 bv2
@defunx bitvector-suffix-length bv1 bv2
[SRFI-178]
@c MOD srfi-178
Returns the length of common prefix/suffix of two bitvectors
@var{bv1} and @var{bv2}.

@example
(bitvector-prefix-length #*1100101001 #*110001101) @result{} 4
(bitvector-suffix-length #*1100101001 #*110001101) @result{} 2
@end example
@end defun

@defun bitvector-prefix? needle haystack
@defunx bitvector-suffix? needle haystack
[SRFI-178]
@c MOD srfi-178
Both arguments must be bitvectors.  Returns @code{#t}
iff  @var{needle} is a prefix/suffix of @var{haystack}.

@example
(bitvector-prefix? #*101 #*1010100) @result{} #t
(bitvector-prefix? #*101 #*1000110) @result{} #f
(bitvector-suffix? #*110 #*1000110) @result{} #t
(bitvector-suffix? #*110 #*1010100) @result{} #f
@end example
@end defun

@defun bitvector-pad bit bv len
@defunx bitvector-pad-right bit bv len
[SRFI-178]
@c MOD srfi-178
If the length of a bitvector @var{bv} is smaller than @var{len},
returns a bitvector of length @var{len} by adding @var{bit} before/after
@var{bv}.  If the length of @var{bv} is equal to or greater than @var{len},
@var{bv} is returned as is.

@example
(bitvector-pad 1 #*00010 10) @result{} #*1111100010
(bitvector-pad-right 1 #*00010 10) @result{} #*0001011111
@end example
@end defun

@defun bitvector-trim bit bv
@defunx bitvector-trim-right bit bv
@defunx bitvector-trim-both bit bv
[SRFI-178]
@c MOD srfi-178
Returns a bitvector without preceding and/or trailing consecutive
@var{bit} from @var{bv}.

@example
(bitvector-trim 0 #*000101000) @result{} #*101000
(bitvector-trim-right 0 #*000101000) @result{} #*000101
(bitvector-trim-both 0 #*000101000) @result{} #*101
@end example
@end defun


@subheading Mutators

@defun bitvector-swap! bv i j
[SRFI-178]
@c MOD srfi-178
Swap the @var{i}-th value and @var{j}-th value of a bitvector @var{bv}.
If the index is out of range, an error is thrown.
@end defun

@defun bitvector-reverse! bv :optional start end
[SRFI-178]
@c MOD srfi-178
Reverse the order of the content of a bitvector @var{bv} destructively.
The optional @var{start}/@var{end} indexes limit the range of the operation;
elements outside of the range won't be affected.
@end defun

@defun bitvector-reverse-copy! to tstart from :optional start end
[SRFI-178]
@c MOD srfi-178
Same as @code{(bitvector-copy! to start (bitvector-reverse-copy from start end))}, 
but potentially more efficient.
@end defun

@subheading Conversion

@defun bitvector->list/int bv :optional start end
@defunx bitvector->list/bool bv :optional start end
@defunx reverse-bitvector->list/int bv :optional start end
@defunx reverse-bitvector->list/bool bv :optional start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun reverse-list->bitvector lis
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector->vector/int bv :optional start end
@defunx bitvector->vector/bool bv :optional start end
@defunx revrese-bitvector->vector/int bv :optional start end
@defunx reverse-bitvector->vector/bool bv :optional start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun vector->bitvetor vec :optional start end
@defunx reverse-vector->bitvector vec :optional start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector->integer bv
@defunx integer->bitvector n :optional len
[SRFI-178]
@c MOD srfi-178
@end defun

@subheading Generators

@defun make-bitvector/int-generator bv
@defunx make-bitvector/bool-generator bv
[SRFI-178]
@c MOD srfi-178
@end defun

@defun make-bitvector-accumulator
[SRFI-178]
@c MOD srfi-178
@end defun

@subheading Bitwise operations

@defun bitvector-not bv
@defunx bitvector-not! bv
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-and bv1 bv2 bv @dots{}
@defunx bitvector-and! bv1 bv2 bv @dots{}
@defunx bitvector-ior bv1 bv2 bv @dots{}
@defunx bitvector-ior! bv1 bv2 bv @dots{}
@defunx bitvector-xor bv1 bv2 bv @dots{}
@defunx bitvector-xor! bv1 bv2 bv @dots{}
@defunx bitvector-eqv bv1 bv2 bv @dots{}
@defunx bitvector-eqv! bv1 bv2 bv @dots{}
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-nand bv1 bv2
@defunx bitvector-nand! bv1 bv2
@defunx bitvector-nor bv1 bv2
@defunx bitvector-nor! bv1 bv2
@defunx bitvector-andc1 bv1 bv2
@defunx bitvector-andc1! bv1 bv2
@defunx bitvector-andc2 bv1 bv2
@defunx bitvector-andc2! bv1 bv2
@defunx bitvector-orc1 bv1 bv2
@defunx bitvector-orc1! bv1 bv2
@defunx bitvector-orc2 bv1 bv2
@defunx bitvector-orc2! bv1 bv2
[SRFI-178]
@c MOD srfi-178
@end defun

@subheading Quasi-integer operations

@defun bitvector-logical-shift bv count bit
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-count bit bv
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-count-run bit bv start
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-if bv-if bv-then bv-else
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-first-bit bit bv
[SRFI-178]
@c MOD srfi-178
@end defun

@subheading Bit field operations

@defun bitvector-field-any? bv start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-field-every? bv start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-field-clear bv start end
@defunx bitvector-field-clear! bv start end
@defunx bitvector-field-set bv start end
@defunx bitvector-field-set! bv start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-field-replace to from start end
@defunx bitvector-field-replace! to from start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-field-replace-same to from start end
@defunx bitvector-field-replace-same! to from start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-field-rotate bv count start end
[SRFI-178]
@c MOD srfi-178
@end defun

@defun bitvector-field-flip bv start end
@defunx bitvector-field-flip! bv start end
[SRFI-178]
@c MOD srfi-178
@end defun

@c ----------------------------------------------------------------------
@node JSON, Custom ports, Bitvector library, Library modules - SRFIs
@section @code{srfi-180} - JSON

@deftp {Module} srfi-180
@mdindex srfi-180
This srfi defines the means of parsing and constructin JSON.

In Gauche, this module is implemented on top of @code{rfc.json} module
(@pxref{JSON parsing and construction}).
Notably, the parameter @code{json-nesting-depth-limit} is the same
as the one in @code{rfc.json}.

Gauche's @code{rfc.json} is more flexible in terms of mapping
JSON objects to Scheme objects.  On the other hand, @code{srfi-180}
provides a streaming parser/generator, which allows the caller
to process input as it is read, instead of waiting the entire
input to be parsed.
@end deftp

@subheading Predicates and parameters

@defun json-error? obj
[SRFI-180]
@c MOD srfi-180
JSON reader and writer raise a condition that satisfies
this predicate when it encounters invalid JSON syntax and/or object,
or the input exceeds the limits specified by
@code{json-nesting-depth-limit} or
@code{json-number-of-character-limit} parameters.

Since @code{srfi-180} is implemented on top of @code{rfc.json},
which raises a condition @code{<json-parse-error>} for input and
@code{<json-construct-error>} for the output, this predicate simply
returns @code{#t} iff @var{obj} is an instance of either class.
@xref{JSON parsing and construction}, for the detail of these conditions.
@end defun

@defun json-error-reason err
[SRFI-180]
@c MOD srfi-180
Returns a string explaining the reasonfor the error @var{err},
if @var{err} is a JSON error object (an object that satisfies
@code{json-error?}).

In Gauche, a JSON error object is an instance of either
@code{<json-parse-error>} or @code{<json-construct-error>})
conditions, and @code{json-error-reason} simply returns the content of
its @code{message} slot.
@end defun

@defun json-null? obj
[SRFI-180]
@c MOD srfi-180
Returns @code{#t} iff @var{obj} is the symbol @code{null}.
@end defun

@deffn {Parameter} json-number-of-character-limit
[SRFI-180]
@c MOD srfi-180
A parameter that holds a real value.  If the number of characters
of input JSON text exceeds the value while @code{json-generator},
@code{json-fold} or @code{json-read} is processing the input,
a JSON error is thrown.
@end deffn

@subheading JSON reader

@defun json-generator :optional port-or-generator
[SRFI-180]
@c MOD srfi-180
Streaming parser.  The input @var{port-or-generator} must be
an input port, or a char generator.

Each time it is called, it returns one of the following values, parsed
from the input.

@table @asis
@item string
JSON string.
@item real number
JSON number.
@item @code{#t}, @code{#f}
JSON @code{true} and @code{false}
@item @code{null}
JSON @code{null}
@item @code{array-start}
The beginning of an array.  What follows is the array's element,
up to the matching @code{array-end}.
@item @code{array-end}
The ending of an array.
@item @code{object-start}
The beginning of an object.  What follows is alternating
string keys and JSON values, up to the matching @code{object-end}.
@item @code{object-end}
The ending of an object.
@item EOF
After one top-level JSON value is read, the generator returns EOF.
@end table

The generator internally tracks the state, and raises
@code{<json-parse-error>} when the input contains invalid JSON text.
See also @code{json-error?} above.

If the input contains more than one toplevel JSON value, you have to
call @code{json-generator} after the previous generator is exhausted.

Note that if a toplevel JSON value is a number, @code{true}, @code{false}
or @code{null}, the parser need to read one character ahead to recognize
the value.  So the subsequent call of @code{json-generator} won't read
a character immediately following those values.

Generally, multiple toplevel values uses delimiters for each values
so it won't be an issue.  See @code{json-lines-read} and
@code{json-sequence-read} below.
@end defun

@defun json-fold proc array-start array-end object-start object-end seed :optional port-or-generator
[SRFI-180]
@c MOD srfi-180
A procedure to translate JSON pasring result to Scheme object on the fly.

The @var{port-or-generator} argument is either an input port,
or a char generator, defaulted to the current input port.
It is first passed to @code{json-generator} to
get a generator of parser events.  Then, @code{json-fold} retrieves
value from the generator and take one of the following actions:

@itemize
@item
If it generates a string, a number, a boolean or @code{null},
calls @code{(proc obj seed)} where @var{obj} is the generated value
and @var{seed} is the current seed value, and make the result a new seed value.
@item
If it generates @code{array-start}, save the current seed, calls
@code{(array-start seed)} and make the result a new seed value.
@item
If it generates @code{array-end}, calls @code{(array-end seed)}, let
the result be @var{arr}, recover the seed value saved
at the corresponding @code{array-start}, and calls
@code{(proc arr recovered-seed)}.  Let the result a new seed value.
@item
If it generates @code{object-start}, save the current seed, calls
@code{(object-start seed)} and make the result a new seed value.
@item
If it generates @code{object-end}, calls @code{(object-end seed)}, let
the result be @var{obj}, recover the seed value saved
at the corresponding @code{object-start}, and calls
@code{(proc obj recovered-seed)}.  Let the result a new seed value.
@item
If it generates EOF, returns the seed value as the result of
@code{json-fold}.
@end itemize
@end defun

@defun json-read :optional port-or-generator
[SRFI-180]
@c MOD srfi-180
Read one JSON value or object from @var{port-or-generator}, which
should be an input port or a char generator.  If it is omitted,
the current input port is used.

JSON strings and numbers are mapped to Scheme strings and numbers.
JSON @code{true} and @code{false} become @code{#t} and @code{#f}.
JSON @code{null} becomes a symbol @code{null}.
JSON arrays become Scheme vectors, and JSON objects
become Scheme alist, in which keys are converted to symbols.

If the input contains invalid JSON text, a @code{<json-parse-error>}
is thrown.

See also @code{parse-json} in @code{rfc.json}
(@pxref{JSON parsing and construction}).

@example
(call-with-input-string 
  "[@{\"a\":1@}, @{\"b\":true, \"c\":\"foo\"@}, null]"
  json-read)
  @result{} #(((a . 1))
      ((b . #t) (c . "foo"))
      null)
@end example
@end defun

@defun json-lines-read :optional port-or-generator
[SRFI-180]
@c MOD srfi-180
Read JSON Lines format
(@url{http://jsonlines.org/}), which contains multiple
toplevel JSON values separated with @code{#\newline}.
The input @var{port-or-generator} should be an input port
or a char generator, defaulted to the current input port.

See @code{json-read} above about the mapping from JSON values to Scheme
values.

Returns a list of read JSON values.  A @code{<json-parse-error>}
is thrown if it encounters invalid JSON text.
@end defun

@defun json-sequence-read :optional port-or-generator
[SRFI-180]
@c MOD srfi-180
Read JSON Text Sequence format (RFC7464, @url{https://tools.ietf.org/html/rfc7464}) from @var{port-or-generator}, which should be an input port
or a char generator, defaulted to the current input port.

JSON Text Sequence can contain multiple JSON values,
each one leaded by one or more consecutive U+001E.
If it encounters text unparsable as JSON, that segment (until next U+001E)
is silently ignored.  Returns a list of read JSON values.

See @code{json-read} above about the mapping from JSON values to Scheme
values.

See also @code{construct-json} in @code{rfc.json}
(@pxref{JSON parsing and construction}).
@end defun

@subheading JSON writer

@defun json-accumulator port-or-accumlator
[SRFI-180]
@c MOD srfi-180
This is dual to @code{json-generator}.  The @code{port-or-accumulator}
should be an output port or an accumulator that accepts a character or
a string.  This procedure
returns an accumulator that accepts the events such as
@code{json-generator} generates.  
@end defun

@defun json-write obj :optional port-or-accumulator
[SRFI-180]
@c MOD srfi-180
Write @var{obj} as a JSON to @var{port-or-accumulator}, which
must be an output port or an accumulator that accepts a character or
a string.
@end defun

@c ----------------------------------------------------------------------
@node Custom ports, Linear adjustable-length strings, JSON, Library modules - SRFIs
@section @code{srfi-181} - Custom ports
@c NODE カスタムポート, @code{srfi-181} - カスタムポート

@deftp {Module} srfi-181
@mdindex srfi-181
This srfi defins a way to implement a port in Scheme.
Gauche has native support of such ports (@pxref{Virtual ports}),
but this srfi is useful for portable code.

The interface is upper compatible to R6RS.

Note that R7RS Scheme distinguishes binary and textual ports,
while Gauche ports can handle both.
@end deftp

@subheading Creating custom ports

@defun make-custom-binary-input-port id read! get-pos set-pos! close
@defunx make-custom-textual-input-port id read! get-pos set-pos! close
[SRFI-181]
@c MOD srfi-181
Creates a new binary and textual input port and returns it, respectively.

The @var{id} argument is an arbitrary Scheme procedure.  SRFI doesn't
specify how it is used.  In Gauche, @var{id} will be returned
with @code{port-name} procedure (@pxref{Common port operations}).

The @var{read!} argument is a procedure to be called
as @code{(read! @var{buffer} @var{start} @var{count})}.
For @code{make-custom-binary-input-port}, @var{buffer} is a bytevector.
For @code{make-custom-textual-input-port}, @var{buffer} is either
a string or a vector of characters (Gauche's implementation always
use a vector, but portable code should handle both).

It should generate up to @var{count} bytes/characters of data and fill 
@var{buffer} beginning from @var{start}, then return the number of 
bytes/characters generated.
It should generate at least 1 byte/character if there's still data. 
To indicate the end of the data, it writs no data and returns 0.

The @var{get-pos} argument is a procedure to be called without arguments,
and returns an implementation-dependent object that indicates
the current position of the input stream.  The `current position' is
where next @var{read!} will generate the data.  This can be @code{#f}
if the port doesn't provide positions.

For @code{make-custom-binary-input-port}, there's a special rule that
if @var{get-pos} returns an exact integer, it should be a byte position
in the stream.

The @var{set-pos!} argument is a procedure to be called with one argument, 
a new position.
It should set the source's position so that next @var{read!} starts
generating data from there.  The passed position is something that has
been returned by @var{get-pos}, or, for @code{make-custom-binary-input-port},
an exact integer that indicates the byte offset from the beginning of
the input.   This argument can be @code{#f} if the port doesn't
support setting positions.  The returned value of @var{set-pos!} is
ignored.

If the position passed to @var{set-pos!} is invalid,
an error that satisfy @code{i/o-invalid-position-error?} should be
thrown.  Portably, it can be done by throwing a condition created
by @code{make-i/o-invalid-position-error} (@pxref{Port positioning}).
For Gauche-specific code, you can throw a condition
@code{<io-invalid-position-error>}.

The @var{close} argument is a procedure to be called without
argument, when the port is closed.  It can be @code{#f} if you
don't need a special cleanup.
@end defun

@defun make-custom-binary-output-port id write! get-pos set-pos! close :optional flush
@defunx make-custom-textual-output-port id write! get-pos set-pos! close :optional flush
[SRFI-181]
@c MOD srfi-181
Creates a new binary and textual out port and returns it, respectively.

The @var{id} argument is an arbitrary Scheme procedure.  SRFI doesn't
specify how it is used.  In Gauche, @var{id} will be returned
with @code{port-name} procedure (@pxref{Common port operations}).

The @var{write!} argument is a procedure to be called as
@code{(write! @var{buffer} @var{start} @var{count})}.
For @code{make-custom-binary-output-port}, @var{buffer} is a bytevector.
For @code{make-custom-textual-output-port}, @var{buffer} is either
a string or a vector of characters (Gauche's implementation always
use a vector, but portable code should handle both).

The @var{write!} procedure needs to consume data in @var{buffer}
starting from @var{start}, upto @var{count} items.  It must return
the actual number of items consumed.

The @var{get-pos} argument should be a procedure without taking argument,
or @code{#f}.  If it is a procedure, it should return the position
of the sink where the next @var{write!} writes to.  The position
can be an arbitrary Scheme object, but for
@code{make-custom-binary-output-port}, a position represented as
an exact integer should correspond to the byte offset in the port.

The @var{set-pos!} argument is a procedure to be called with one argument, 
a new position.
It should set the sink's position so that next @var{write!} starts
to write data from there.  The passed position is something that has
been returned by @var{get-pos}, or, for @code{make-custom-binary-output-port},
an exact integer that indicates the byte offset from the beginning of
the output.   This argument can be @code{#f} if the port doesn't
support setting positions.  The returned value of @var{set-pos!} is
ignored.

If the position passed to @var{set-pos!} is invalid,
an error that satisfy @code{i/o-invalid-position-error?} should be
thrown.  Portably, it can be done by throwing a condition created
by @code{make-i/o-invalid-position-error} (@pxref{Port positioning}).
For Gauche-specific code, you can throw a condition
@code{<io-invalid-position-error>}.

The @var{close} argument is a procedure to be called without
argument, when the port is closed.  It can be @code{#f} if you
don't need a special cleanup.

The @var{flush} argument, if provided and not @code{#f}, 
should be a procedure taking no arguments.  It is called when
the port is requested to flush the data buffered in the sink, if any.
@end defun

@defun make-custom-binary-input/output-port id read! write! get-pos set-pos! close :optional flush
[SRFI-181]
@c MOD srfi-181
Creates a bidirectional binary i/o port.  Since Gauche doesn't distinguish
binary and textual ports, you can use the returned port for textual i/o as well,
but portable code must avoid it.

(The reason textual input/output port is not defined in the SRFI is that
it is difficult to define a consistent semantics agnostic to the internal
representation of character stream.  In Gauche, we immediately convert
characters to the octet stream of internal character encoding.)

The arguments, @var{id}, @var{read!}, @var{write!},
@var{get-pos}, @var{set-pos!}, @var{close} and @var{flush} are
the same as @code{make-custom-binary-input-port} and
@code{make-custom-binary-output-port}.
@end defun

@subheading Transcoded ports

A transcoded port is a portable way to read/write characters in
an encodings other than the system's default one.  This API is
defined first in R6RS, and adopted in srfi-181.

In srfi-181 (and R6RS) world, strings and characters are all
an abstract entity without the concept of encodings (internally,
you can think them being encoded in the system's native encoding),
and the explicit encodings only matter when you refer to the outside
resource, e.g. files or a binary data represented in a bytevector.
Therefore, conversions are only defined between binary ports (external world)
and textual ports (internal), or a bytevector (external world) and
a string (internal).

Here's some terms:

@table @emph
@item Codec
A codec names a character encoding scheme.
@item EOL-style
Specifies (non)converson of EOL character(s).
@item Transcoder
A transcoder bundles a codec, an eol-style, and error handling mode.
@end table

@subsubheading Transcoders

@defun make-transcoder codec eol-style handling-mode
[SRFI-181]
@c MOD srfi-181
Creates and returns a transcoder with the given parameters.
A transcoder is an immutable object.
@end defun

@defun native-transcoder
[SRFI-181]
@c MOD srfi-181
Returns a singleton of the transcoder representing systems native
(internal) codec and eol-style.  In Gauche, the native codec
is the same as Gauche's native encoding 
(returned by @code{gauche-character-encoding}, @pxref{Characters}),
and eol-style is @code{none}.
@end defun

@defun transcoded-port binary-port transcoder
[SRFI-181]
@c MOD srfi-181
Creates a transcoded port wrapping @var{binary-port}, performing the
conversion specified by @var{transcoder}.

If @var{binary-port} is an input port, it returns an input port,
converting the CES specified in @var{transcoder} to the system's
native encoding.

If @var{binary-port} is an output port, it returns an output port,
converting the system's native encoding to the CES specified in
@var{transcoder}.

In Gauche, conversion is done by conversion ports.
@xref{Conversion ports}, for the details.
@end defun

@defun bytevector->string bytevector transcoder
[SRFI-181]
@c MOD srfi-181
Decode the binary data in @var{bytevector} as the CES specified
by @var{transcoder}, and returns a string in the native encoding.

It is a wrapper of Gauche's @code{ces-convert}; @pxref{Conversion ports}.
@end defun

@defun string->bytevector string transcoder
[SRFI-181]
@c MOD srfi-181
Encode the string in the CES specified by @var{transcoder},
and returns a bytevector.

It is a wrapper of Gauche's @code{ces-convert-to}; @pxref{Conversion ports}.
@end defun

@subsubheading Codecs

@defun make-codec name
[SRFI-181]
@c MOD srfi-181
Returns a coded representing a character encoding scheme named by
@var{name}.  A portable code should only use string for @var{name},
while Gauche accepts a symbol as well.

If @var{name} isn't recognized as a supported codec name,
a condition that satisfies @code{unknown-encoding-error?} is thrown.
@end defun

@defun unknown-encoding-error? obj
[SRFI-181]
@c MOD srfi-181
If the system sees unknown or unsupported codec, a condition
that satisfies this predicate is thrown.
@end defun

@defun unknown-encoding-error-name obj
[SRFI-181]
@c MOD srfi-181
The argument must be an unknown encoding error condition
that satisfies @code{unknown-encoding-error?}.  It returns
the name that caused the condition to be thrown.
@end defun

@defun latin-1-codec
@defunx utf-8-codec
@defunx utf-16-codec
[SRFI-181]
@c MOD srfi-181
A pre-defined codecs for @code{latin-1} (ISO8859-1),
@code{utf-8}, and @code{utf-16}.

The @code{utf-16} codec recognizes
BOM when used for input; if no BOM is found, UTF-16BE is assumed.
When used for output, @code{utf-16} always attaches BOM.
@end defun

@subsubheading EOL style

@defun native-eol-style
[SRFI-181]
@c MOD srfi-181
Returns the default eol style.  In Gauche, it is @code{none}.
@end defun

@subsubheading Transcoding errors

@defun i/o-decoding-error? obj
[SRFI-181]
@c MOD srfi-181
When an input transcoded port encounters a sequence that's not valid
for the input codec, a condition that satisfies this predicate
is thrown.

In Gauche, such condition is @code{<io-decoding-error>}.
@end defun

@defun i/o-encoding-error? obj
[SRFI-181]
@c MOD srfi-181
When an output transcoded port encounters a character that can't be
encoded in the output codec, and the handling mode is @code{raise},
a condition that satisfies this predicate is thrown.

In Gauche, such condition is @code{<io-encoding-error>}.
@end defun

@defun i/o-encoding-error-char i/o-encoding-condition
[SRFI-181]
@c MOD srfi-181
Retries the character that caused the @code{<io-encoding-error>} is thrown.
@end defun


@c ----------------------------------------------------------------------
@node Linear adjustable-length strings, Maybe and Either optional container types, Custom ports, Library modules - SRFIs
@section @code{srfi-185} - Linear adjustable-length strings
@c NODE 線形更新な可変長文字列, @code{srfi-185} - 線形更新な可変長文字列

@deftp {Module} srfi-185
@mdindex srfi-185
@c EN
This module provides a linear-update version of @code{string-append}
and @code{string-replace}.  ``Linear update'' means the caller
won't access the first string argument, hence the implementation
@emph{can} reuse it to store the result, for the efficiency.
@c JP
このモジュールは@code{string-append}と@code{string-replace}の線形更新版を提供します。
「線形更新」とは、この関数を呼び出した後は引数が使われないことが前提になっているという
意味で、従って処理系は結果を格納するために引数を破壊的に再利用することが許されています。
@c COMMON

@c EN
Note that, in Gauche, a string is just a pointer to an immutable
string body.  Mutation of a string is actually constructing a new
string body and swapping the pointer, so it has no performance
advantage to immutable versions.  And in fact, we implement
these without mutating their arguments.
@c JP
しかしGaucheでは、文字列は変更不可な文字列本体へのポインタであって、
文字列の変更は新たな文字列本体を作ってポインタを差し替える操作にすぎず、
文字列を破壊的に再利用するメリットは全くありません。
従ってこのsrfiのAPIは単に非破壊版を呼び出すだけになっています。
@c COMMON

@c EN
This module also provides macros with the same name as @code{srfi-118}
procedures (@pxref{Simple adjustable-size strings}), which @code{set!}
the result to its first argument, so they can work as a drop-in
replacement to @code{srfi-118}.
@c JP
このモジュールはまた、@code{srfi-118}の手続き(@ref{Simple adjustable-size strings}参照)
と同名のマクロを提供しています。マクロは結果を引数に渡された式に
@code{set!}する式に展開されるので、一見@code{srfi-118}と同じように使うことができます。
@c COMMON
@end deftp

@defun string-append-linear! dst str-or-char @dots{}
[SRFI-185]
@c MOD srfi-185
@c EN
Returns a string which is a concatenation of a string @var{dst}
and the arguments.  The second argument an after can be
a string or a character.  The caller shouldn't access @var{dst}
after calling this procedure, for the implementation may destructively
reuse the string passed to @var{dst}.   Although Gauche won't
mutate @var{dst}, other implementations may, so portable code
should adhere this restriction.
@c JP
文字列@var{dst}と他の引数を全部つなげた文字列を返します。
2番目以降の引数は文字でも文字列でも構いません。呼び出し元は、この関数を読んだ後は
@var{dst}が指す文字列にアクセスしてはいけません。実装は@var{dst}が指す文字列を
破壊的に再利用して結果を格納することが許されています。Gaucheは@var{dst}を
破壊しませんが、ポータブルなコードでは@var{dst}を使わないようにしてください。
@c COMMON

@c EN
You can't count on @var{dst} being mutated; you always have to use the returned
string.
@c JP
@var{dst}が破壊することをあてにしてはいけません。
常に戻り値の文字列を使うようにしてください。
@c COMMON

@example
(string-append-linear! "abc" "def" #\g "hij")
  @result{} "abcdefghij"
@end example
@end defun

@defun stirng-replace-linear! dst dst-start dst-end src :optional src-start src-end
[SRFI-185]
@c MOD srfi-185
@c EN
Returns copy of a string @var{dst} except
the portion of from @var{dst-start} (inclusive)
to @var{dst-end} (exclusive), by a string @var{src} (from @var{src-start}
to @var{src-end}).
The caller shouldn't access @var{dst}
after calling this procedure, for the implementation may destructively
reuse the string passed to @var{dst}.   Although Gauche won't
mutate @var{dst}, other implementations may, so portable code
should adhere this restriction.
@c JP
文字列@var{dst}のうち、@var{dst-start}(含まれる)から@var{dst-end}(含まれない)
までの範囲を、文字列@var{src}(の@var{src-start}と@var{src-end}の範囲)で置き換えた
文字列を返します。
呼び出し元は、この関数を読んだ後は
@var{dst}が指す文字列にアクセスしてはいけません。実装は@var{dst}が指す文字列を
破壊的に再利用して結果を格納することが許されています。Gaucheは@var{dst}を
破壊しませんが、ポータブルなコードでは@var{dst}を使わないようにしてください。
@c COMMON

@c EN
Gauche allows string cursors, as well as integer character index,
in @var{dst-start}, @var{dst-end}, @code{src-start} and @var{src-end} arguments.
(@xref{String cursors}).
@c JP
Gaucheでは、@var{dst-start}、@var{dst-end}、@code{src-start}、@var{src-end}
引数に、整数の文字インデックスだけでなく文字列カーソルも使えます。
(@ref{String cursors}参照)。
@c COMMON
@end defun

@defmac string-append! dst string-or-char @dots{}
@defmacx string-replace! dst dst-start dst-end src :optional src-start src-end
[SRFI-185]
@c MOD srfi-185
@c EN
These macros expand into the following forms:
@c JP
これらのマクロは次の形に展開されます。
@c COMMON

@example
(set! dst (string-append-linear! dst string-or-char @dots{}))

(set! dst (string-replace-linear! dst dst-start dst-end src src-start src-end))
@end example

@c EN
Hence they can be used for the code that expects @var{dst} to contain
the result after calling these macros.
Gauche supports generalized @code{set!}, so @var{dst} can be
a procedure call with a setter defined.
@c JP
つまり、呼び出した後に@var{dst}に変更された文字列が格納されることを想定している
箇所に使えます。Gaucheは一般化された@code{set!}を持っているので、
@var{dst}にはセッターが定義されている手続き呼び出しも使えます。
@c COMMON

@example
(define x (list (string-copy "abc")))

(string-append! (car x) #\d #\e #\f)

x @result{} ("abcdef")
@end example

@c EN
The code that uses srfi-118 (@pxref{Simple adjustable-size strings}) is
likely to be replaced using these macros.
@c JP
srfi-118 (@ref{Simple adjustable-size strings}参照)を使っているコードは、
このマクロで置き換えられることも多いでしょう。
@c COMMON
@end defmac

@c ----------------------------------------------------------------------
@node Maybe and Either optional container types, Port positioning, Linear adjustable-length strings, Library modules - SRFIs
@section @code{srfi-189} - Maybe and Either: optional container types
@c NODE MaybeとEither、オプショナルなコンテナ型, @code{srfi-189} - MaybeとEither、オプショナルなコンテナ型

@deftp {Module} srfi-189
@mdindex srfi-189
Maybe and Either types are immutable container types
that can ``wrap'' zero or more values.  Maybe can be used
in the context where the value(s) may be missing (as opposed to
``zero values'').  Either can be used in the context where
the value(s) can be correct ones or erroneous ones.

If you're familiar with functional languages like Haskell, you may
already know them.  They are useful when used in the monadic pattern; that is,
you can code as if the chain of calculations never fails, 
yet whenever the calculation fail at one place,
the rest of chain is canceled and just the failure is returned.

Maybe is a union of two types, Just and Nothing.  Just wraps
valid value(s), while Nothing indicates there's no meaningful values.
Either is a union of two types, Right and Left.  Right wraps
valid value(s), while Left indicates an error, carrying some information
as its payload.
@end deftp

@menu
* Maybe and Either types and predicates::
* Maybe and Either constructors::
* Maybe and Either accessors::
* Maybe and Either sequence operations::
* Maybe and Either protocol converters::
* Maybe and Either syntactic utilities::
* Trivalent logic::
@end menu

@node Maybe and Either types and predicates, Maybe and Either constructors, Maybe and Either optional container types, Maybe and Either optional container types
@subsection Types and predicates

@deftp {Class} <maybe>
@deftpx {Class} <just>
@deftpx {Class} <nothing>
@c MOD srfi-189
Maybe classes.  @code{<just>} and @code{<nothing>} are subclasses of
@code{<maybe>}.  An instance of @code{<just>} carries zero or more
values (payload), while an instance of @code{<nothing>} doesn't carry
information.

The @code{<maybe>} class is an abstract class and can't
create an instance of its own.
Instances of @code{<just>} and @code{<nothing>} should be created with
constructor procedures @code{just} and @code{nothing}.
@end deftp

@deftp {Class} <either>
@deftpx {Class} <right>
@deftpx {Class} <left>
@c MOD srfi-189
Either classes.  @code{<right>} and @code{<left>} are subclasses of
@code{<either>}.  An instance of either class carry zero or more
values (payload); it is customary to use @code{<right>} to propagate
the legitimate results of compuation, while use @code{<left>} to
propagate erroneous conditions whose payload describes what's wrong.

The @code{<either>} class is an abstract class and can't
create an instance of its own.
Instances of @code{<right>} and @code{<left>} should be created with
constructor procedures @code{right} and @code{left}.
@end deftp

@defun maybe? obj
@defunx just? obj
@defunx nothing? obj
@c MOD srfi-189
[SRFI-189]
Type predicates.
Returns @code{#t} iff @var{obj} is a Maybe, a Just, or a Nothing,
respectively.
@end defun

@defun either? obj
@defunx right? obj
@defunx left? obj
@c MOD srfi-189
[SRFI-189]
Type predicates.
Returns @code{#t} iff @var{obj} is a Either, a Right, or a Left,
respectively.
@end defun

@defun maybe= elt= maybe1 maybe @dots{}
@c MOD srfi-189
[SRFI-189]
Equality predicate of Maybes.  It returns @code{#t} iff
all of @var{maybe1} @var{maybe} @dots{} are Nothings,
or Justs with their respective payload objects are the same
using @var{elt=}.
@end defun

@defun either= elt= either1 either @dots{}
@c MOD srfi-189
[SRFI-189]
Equality predicate of Eithers.  It returns @code{#t} iff
all of @var{either11} @var{either} @dots{} are the same
types (all Rights, or all Lefts), with
respective payload objects are the same
using @var{elt=}.
@end defun

@node Maybe and Either constructors, Maybe and Either accessors, Maybe and Either types and predicates, Maybe and Either optional container types
@subsection Constructors

@defun just obj @dots{}
@c MOD srfi-189
[SRFI-189]
Returns a Just with @var{obj} @dots{} as its payload.
@end defun

@defun nothing
@c MOD srfi-189
[SRFI-189]
Returns a Nothing.
@end defun

@defun right obj @dots{}
@defunx left obj @dots{}
@c MOD srfi-189
[SRFI-189]
Returns a Right or a Left respectively, with @var{obj} @dots{}
as its payload.
@end defun

@defun list->just objs
@defunx list->right objs
@defunx list->left objs
@c MOD srfi-189
[SRFI-189]
Returns a Just, Right or Left respectively, with
@var{objs} as its payload.
@end defun

@defun maybe->either maybe obj @dots{}
@c MOD srfi-189
[SRFI-189]
The @var{maybe} argument must be a Maybe.
If it is a Just, then a Right with the same payload is returned.
If it is a Nothing, a Left with @var{obj} @dots{} as its payload.
@end defun

@defun either->maybe either
@c MOD srfi-189
[SRFI-189]
The @var{either} argument must be an Either.
If it is a Right, then a Just with the same payload is returned.
If it is a Left, a Nothing is returned.
@end defun

@defun either-swap either
@c MOD srfi-189
[SRFI-189]
The @var{either} argument must be an Either.
If it is a Right, a Left with the same payload argument is returned.
If it is a Left, a Right with the same payload argument is returned.
@end defun

@node Maybe and Either accessors, Maybe and Either sequence operations, Maybe and Either constructors, Maybe and Either optional container types
@subsection Accessors

@defun maybe-ref maybe failure :optional success
@c MOD srfi-189
[SRFI-189]
The @var{maybe} arugment must be a Maybe.  If it's a Nothing,
a procedure @var{failure} is tail-called with no arguments.
If it's Just, a procedure @var{success} is tail-called with its
payload object(s).  If @var{success} is omitted, @code{values} is used.

@example
(maybe-ref (just 1 2) (^[] (error 'huh?)) +)
  @result{} 3
@end example
@end defun

@defun either-ref either failure :optional success
@c MOD srfi-189
[SRFI-189]
The @var{either} argument must be an Either.
If it's a Left, a procedure @var{failure} is called with
its payload object(s).  If it's a Right, a procedure
@var{success} is called with its payload object(s).
If @var{success} is omitted, @code{values} is used.
@end defun

@defun maybe-ref/default maybe default @dots{}
@c MOD srfi-189
[SRFI-189]
The @var{maybe} argument must be a Maybe.  If it's a Nothing,
@var{default} @dots{} are returned as multiple values.
If it's a Just, its payload object(s) is/are returned as multiple values.
@end defun

@defun either-ref/default maybe default @dots{}
@c MOD srfi-189
[SRFI-189]
The @var{either} argument must be an Either.  If it's a Left,
@var{default} @dots{} are returned as multiple values (the Left's payload
is discarded).
If it's a Right, its payload object(s) is/are returned as multiple values.
@end defun

@defun maybe-join maybe
@c MOD srfi-189
[SRFI-189]
If @var{maybe} is a Nothing,
it is returned.  If it's a Maybe and its only payload is a Maybe,
the inner Maybe is returned.  Other cases raise an error.
@end defun

@defun either-join either
@c MOD srfi-189
[SRFI-189]
If @var{either} is a Left, it is returned.
If it is a Right and its only payload is an Either,
the inner Either is returned.  Other cases raise an error.
@end defun

@defun maybe-bind maybe mproc mproc2 @dots{}
@c MOD srfi-189
[SRFI-189]
Monadic @var{bind} operation.  The @var{maybe} argument must be a Maybe.
If it is a Nothing, it is returned.
If it is a Just, its payload object(s) is/are applied to a procedure
@var{mproc}, which must return a Maybe.  If @var{mproc2} @dots{} are
given, the same operation is repeated on them.

@example
(maybe-bind m p p2)
  @equiv{} (maybe-bind (maybe-bind m p) p2)
@end example
@end defun

@defun either-bind either mproc mproc2 @dots{}
@c MOD srfi-189
[SRFI-189]
Monadic @var{bind} operation.  The @var{either} argument must be an Either.
If it is a Left, it is returned as is.
If it is a Right, its payload object(s) is/are applied to a procedure
@var{mproc}, which must return an Either.  If @var{mproc2} @dots{} are
given, the same operation is repeated on them.

@example
(either-bind e p p2)
  @equiv{} (either-bind (either-bind e p) p2)
@end example
@end defun

@defun maybe-compose mproc mproc2 @dots{}
@defunx either-compose mproc mproc2 @dots{}
@c MOD srfi-189
[SRFI-189]
Each argument must be a procedure taking zero or more arguments
and return a Maybe/an Either.   Returns a procedure that accepts zero or more
arguments and returns a Maybe/an Either.

When the returned procedure is called, it first calls @var{mproc};
if it returns a Nothing/Left, or there's no more mprocs, the result is
returned.  If the result is a Just, its payload is applied
to the next mproc, and so on.

@example
(maybe-bind m p p2 ...)
  @result{} (maybe-ref m (^[] (nothing))
              (maybe-compose p p2 ...))
@end example
@end defun


@node Maybe and Either sequence operations, Maybe and Either protocol converters, Maybe and Either accessors, Maybe and Either optional container types
@subsection Sequence operations

A Maybe and an Either can be a container of zero or one element, and
we have several procedures that employ this view.
(Note: For this purpose, we treat multiple payload values as a whole,
since they are processed in one step---as if we don't regard
multiple procedure arguments and multiple return values as a sequence
of individual values.)

@defun maybe-length maybe
@defunx either-length either
@c MOD srfi-189
[SRFI-189]
Returns 0 if @var{maybe}/@var{either} is a Nothing/Left, and
1 if it is a Just/Right.  An error is thrown if the argument
isn't a Maybe/an Either.
@end defun

@defun maybe-filter pred maybe
@defunx either-filter pred either obj @dots{}
@c MOD srfi-189
[SRFI-189]
If @var{maybe}/@var{either} is a Nothing/Left,
returns a Nothing/a Left of @var{obj} @dots{}.
If @var{maybe}/@var{either} is a Just/a Right, apply @var{pred} on
its payload value(s).  If @var{pred} returns a true value,
@var{maybe}/@var{either} is returned; otherwise,
a Nothing/a Left of @var{obj} @dots{} is returned.

An error is thrown if @var{maybe}/@var{either} isn't a Maybe/an Either.
@end defun

@defun maybe-remove pred maybe
@defunx either-remove pred either obj @dots{}
@c MOD srfi-189
[SRFI-189]
Like @code{maybe-filter}/@code{either-filter}, but the meaning of
@var{pred} is reversed.
@end defun

@defun maybe-sequence mappable cmap :optional aggregator
@defunx either-sequence mappable cmap :optional aggregator
@c MOD srfi-189
[SRFI-189]
This converts a collection of Maybes/Eithers to a Mayber/an Either of
a collection.  The input collection and the collection in the output can
be of different type.

It's easier to explain using Haskell-ish type signatures, although
it's not precisely specified.  Suppose @code{Container x} is
some kind of a collection of
type @var{x}, and @code{a*} is multiple values of arbitrary types.

@example
Mappable   = Container Maybe a*
CMap       = ((Maybe a* -> b) -> Container Maybe a* -> Container' b
Aggregator = a* -> b

maybe-sequence :: Mappable -> CMap -> Aggregator -> Container' b
@end example

The @var{cmap} maps @var{proc} over the input container (@var{mappable}),
and gathers the result into another container.  It can be any containers,
as long as it matches the @var{mappable} argument.  For example, @var{mappable}
may be a vector of Maybes, and @var{cmap} can be @code{vector-map}--in that case,
both @code{Container} and @code{Container'} are @code{Vector}.
Or, @var{mappable} may be a list of Maybes, and @var{cmap} can be
@code{(cut map-to <string> <> <>)}, then @code{Container} is a list and
@code{Container'} is a string.

The types @code{a*} and @code{b} is determined by the @var{aggregator}
procedure, whose default value is @code{list}.
@end defun

@defun maybe-map proc maybe
@defunx either-map proc either
@c MOD srfi-189
[SRFI-189]
If @var{maybe}/@var{either} is a Nothing/Left, it is returned as is.
If it is a Just/Right, its payload value(s) is/are passed to @var{proc},
and the result is returned.
@end defun

@defun maybe-for-each proc maybe
@defunx either-for-each proc either
@c MOD srfi-189
[SRFI-189]
If @var{maybe}/@var{either} is a Nothing/Left, these procedures do nothing.
Otherwise, @var{proc} is applied to the argument's payload values.
The result of @var{proc} is discarded.  Returns an unspecified vlaue.
@end defun

@defun maybe-fold kons knil maybe
@defunx either-fold kons knil either
@c MOD srfi-189
[SRFI-189]
If @var{maybe}/@var{either} is a Nothing/Left, @var{knil} is returned.
Otherwise, @var{kons} is called with the argument's payload values, plus
@var{knil}.  What @var{kons} returns becomes the result.
@end defun

@defun maybe-unfold p f g seed @dots{}
@defunx either-unfold p f g seed @dots{}
@c MOD srfi-189
[SRFI-189]
First, the stop predicate @var{p} is applied to @var{seed} @dots{}.
If it returns a true value, a Nothing / a Left of @var{seed} @dots{} is
returned.  Otherwise, @var{g} is applied to @var{seed} @dots{},
which should return the same number of values as seeds, and passed
to @var{p}.  If @var{p} returns false, it is an error.
If @var{p} returns true, @var{mapper} is applied to @var{seed} @dots{},
then the results are wrapped in a Just/Right to be returned.
@end defun


@node Maybe and Either protocol converters, Maybe and Either syntactic utilities, Maybe and Either sequence operations, Maybe and Either optional container types
@subsection Protocol converters

@defun maybe->list maybe
@c MOD srfi-189
[SRFI-189]
If @var{maybe} is a Just, returns a list of its payload values.
If it is a Nothing, an empty list is retured.
@end defun

@defun list->maybe lis
@c MOD srfi-189
[SRFI-189]
If @var{lis} is an empty list, a Nothing is returned.
Otherwise, a Just that has elements in @var{lis} as payload values
is returned.

Note that @code{(list->maybe (maybe->list x))} isn't an identity
mapping---if @var{x} is a Just with zero payload values, you'll get
a Nothing.
@end defun

@defun either->list either
@c MOD srfi-189
[SRFI-189]
If @var{either} is a Right, returns a list of its payload values.
If it is a Left, returns an empty string.
@end defun

@defun list->either lis obj @dots{}
@c MOD srfi-189
[SRFI-189]
If @var{lis} is an empty list, a Left of @var{obj} @dots{} is returned.
Otherwise, a Right that has elements in @var{lis} as payload values
is returned.
@end defun

@defun maybe->truth maybe
@c MOD srfi-189
[SRFI-189]
If @var{maybe} is a Nothing, @code{#f} is returned.
Otherwise, it must be a Just with one value, and its value is returned.

If @var{maybe} is a Just and it doesn't have exactly one value, an error
is thrown.  If you want to deal with arbitrary number of payload values,
use @code{maybe->list-truth}.
@end defun

@defun truth->maybe obj
@c MOD srfi-189
[SRFI-189]
If @var{obj} is @code{#f}, returns a Nothing.
Otherwise, returns a Just with @var{obj} as its payload.

Note that @code{(truth->maybe (maybe->truth x))} isn't an identity mapping---
if @var{x} is a Just wrapping @code{#f}, you'll get a Nothing.
@end defun

@defun either->truth either
@c MOD srfi-189
[SRFI-189]
If @var{either} is a Left, @code{#f} is returned.
Otherwise, it must be a Right with one value, and its value is returned.

If @var{either} is a Right and it doesn't have exactly one value, an error
is thrown.  If you want to deal with arbitrary number of payload values,
use @code{either->list-truth}.
@end defun

@defun truth->either obj fail-obj @dots{}
@c MOD srfi-189
[SRFI-189]
If @var{obj} is @code{#f}, returns a Left with @var{fail-obj} @dots{} is
returned.
Otherwise, returns a Right with @var{obj} as its payload.
@end defun

@defun maybe->list-truth maybe
@c MOD srfi-189
[SRFI-189]
Like @code{maybe->list}, it returns @code{#f} if @var{maybe} is a Nothing.
If @var{maybe} is a Just, however, it returns a list of its payload values.
@end defun

@defun list-truth->maybe lis-or-false
@c MOD srfi-189
[SRFI-189]
The argument must be @code{#f} of a list.  If it is @code{#f}, a Nothing
is returned.  If it is a list, a Just with elements of the list is
returned.

@code{(list-truth->maybe (maybe->list-truth x))} is an identity mapping.
@end defun

@defun either->list-truth either
@c MOD srfi-189
[SRFI-189]
Like @code{either->list}, it returns @code{#f} if @var{either} is a Left.
If @var{either} is a Right, however, it returns a list of its payload values.
@end defun

@defun list-truth->either lis-or-false fail-objs @dots{}
@c MOD srfi-189
[SRFI-189]
The @var{list-or-false} argument must be @code{#f} of a list.  
If it is @code{#f}, a Left with @var{fail-objs} @dots{}
is returned.  If it is a list, a Right with elements of the list is
returned.
@end defun

@defun maybe->generation maybe
@c MOD srfi-189
[SRFI-189]
If @var{maybe} is a Nothing, an EOF object is returned.
Otherwise, it must be a Just with one value, and its value is returned.
If @var{maybe} is a Just and it doesn't have exactly one value, an error
is thrown.
@end defun

@defun generation->maybe obj
@c MOD srfi-189
[SRFI-189]
If @var{obj} is an EOF value, a Nothing is returned.
Otherwise, a Just wrapping @var{obj} is returned.
@end defun

@defun either->generation either
@c MOD srfi-189
[SRFI-189]
If @var{either} is a Left, an EOF object is returned.
Otherwise, it must be a Right with one value, and its value is returned.
If @var{either} is a Right and it doesn't have exactly one value, an error
is thrown.
@end defun

@defun generation->either obj fail-objs @dots{}
@c MOD srfi-189
[SRFI-189]
If @var{obj} is an EOF value, a Left with @var{fail-objs} @dots{} is returned.
Otherwise, a Right wrapping @var{obj} is returned.
@end defun

@defun maybe->values maybe
@c MOD srfi-189
[SRFI-189]
If @var{maybe} is a Just, returns its payload as multiple values.
If it is a Nothing, returns no values.
(Note that a Just with zero values also returns no values.)
@end defun

@defun values->maybe producer
@c MOD srfi-189
[SRFI-189]
It first invokes a procedure @var{producer} with no values.
If it returns zero values, a Nothing is returned; otherwise,
a Just with those values are returned.
@end defun

@defun either->values either
@c MOD srfi-189
[SRFI-189]
If @var{either} is a Right, returns its payload as multiple values.
If it is a Left, returns no values.
(Note that a Right with zero values also returns no values.)
@end defun

@defun values->either producer fail-obj @dots{}
@c MOD srfi-189
[SRFI-189]
It first invokes a procedure @var{producer} with no values.
If it returns zero values, a Left with @var{fail-obj} @dots{} as
its payload is returned.
If it returns one or more values,
a Right with those values are returned.
@end defun

@defun maybe->two-values maybe
@c MOD srfi-189
[SRFI-189]
If @var{maybe} is a Just with exactly one value, the value and @code{#t}
is returned.  If @var{maybe} is a Nothing, two @code{#f} is returned.
An error is thrown if @var{maybe} has a Just with zero or more than two
values.
@end defun

@defun two-values->maybe producer
@c MOD srfi-189
[SRFI-189]
The inverse of @code{maybe->two-values}.  A procedure @var{producer}
is called with no arguments.  It must return two values, a possible
payload value, and a boolean.  If the second value is true,
a Just with the first value is returned.  If the second value is @code{#f},
a Nothing is returned (the first return value is ignored).
@end defun

@defun exception->either pred thunk
@c MOD srfi-189
[SRFI-189]
A procedure @var{thunk} is called without argument, wrapped by an
exception handler.  If @var{thunk} raises a condition, it is
examined by @var{pred}.  If @var{pred} returns true on the condition, 
the exception is wrapped by a Left and returned.  
If @var{pred} returns @code{#f}, the exception is reraised.
If no exception is raised, the result(s) of @var{thunk} is wrapped
by a Right and returned.
@end defun

@node Maybe and Either syntactic utilities, Trivalent logic, Maybe and Either protocol converters, Maybe and Either optional container types
@subsection Syntactic utilities

@defmac maybe-if mtest then else
@c MOD srfi-189
[SRFI-189]
If the @var{mtest} expression yields a Just, evaluates @var{then}.
If the @var{mtest} expression yeilds a Nothing, evaluates @var{else}.
If the @var{mtest} expression doesn't produce a Maybe, an error
is thrown.
@end defmac

@defmac maybe-and maybe @dots{}
@defmacx either-and either @dots{}
@c MOD srfi-189
[SRFI-189]
Evaluates @var{maybe}/@var{either} from left to right, as far as
each yields a Just/Right.  If every expression yields a Just/Right,
the last one is returned.  If it encounters an expression that
yields a Nothing/Left, it stops evaluating the rest of expressions and
returns the Nothing/Left.

If expressions yield something other than Maybe/Either, an error is thrown.
@end defmac

@defmac maybe-or maybe @dots{}
@defmacx either-or either @dots{}
@c MOD srfi-189
[SRFI-189]
Evaluates @var{maybe}/@var{either} from left to right, as far as
each yields a Nothing/Left.   If it encounters an expression that
yields a Just/Right, it stops evaluating the rest of expressions and
returns it.  

If expressions yield something other than Maybe/Either, an error is thrown.
@end defmac

@defmac maybe-let* ( claw @dots{} ) body @dots{}
@defmacx either-let* ( claw @dots{} ) body @dots{}
@c MOD srfi-189
[SRFI-189]
This is a Maybe/Either version of @code{and-let*}.
@end defmac

@defmac maybe-let*-values ( mv-claw @dots{} ) body @dots{}
@defmacx either-let*-values ( mv-claw @dots{} ) body @dots{}
@c MOD srfi-189
[SRFI-189]
@end defmac

@defmac either-guard (pred) body @dots{}
@c MOD srfi-189
[SRFI-189]
@end defmac

@node Trivalent logic,  , Maybe and Either syntactic utilities, Maybe and Either optional container types
@subsection Trivalent logic

@defun tri-not maybe
@c MOD srfi-189
[SRFI-189]
@end defun

@defun try=? maybe @dots{}
@c MOD srfi-189
[SRFI-189]
@end defun

@defun try-and maybe @dots{}
@c MOD srfi-189
[SRFI-189]
@end defun

@defun try-or maybe @dots{}
@c MOD srfi-189
[SRFI-189]
@end defun

@defun try-merge maybe @dots{}
@c MOD srfi-189
[SRFI-189]
@end defun

@c ----------------------------------------------------------------------
@node Port positioning, Command line, Maybe and Either optional container types, Library modules - SRFIs
@section @code{srfi-192} - Port positioning
@c NODE ポート位置,  @code{srfi-192} - ポート位置

@deftp {Module} srfi-192
@mdindex srfi-192
This srfi defines procedures to get and set the current position of
the port.

This feature is already supported in the Gauche core, so the following
procedure is described in @ref{Common port operations}.
@example
port-position
port-has-port-position?
set-port-position!
port-has-set-port-position?
@end example
@end deftp

@defun make-i/o-invalid-position-error pos
[SRFI-192]
@c MOD srfi-192
This portably creates a condition suitable to be raised from
@code{set-port-position!} when the given position object can't
be accepted.  The @var{pos} argument is the offending position object.

In Gauche, such condition is represented by 
@code{<io-invalid-position-error>} class, which is a subclass
of @code{<port-error>}.

If you raise a condition created with this procedure from
the @code{set-position!} callback of the custom ports
(@pxref{Custom ports}), Gauche intercepts it and adds
the port information to the condition.
@end defun

@defun i/o-invalid-position-error? obj
[SRFI-192]
@c MOD srfi-192
Returns @code{#t} iff @var{obj} is an i/o-invalid-position-error
condition (or a compound condition that includes it).

In Gauche, it is the same as
@code{(condition-has-type? @var{obj} <io-invalid-position-error>)}.
@end defun

@c ----------------------------------------------------------------------
@node Command line,  , Port positioning, Library modules - SRFIs
@section @code{srfi-193} - Command line
@c NODE コマンドライン,  @code{srfi-193} - コマンドライン

@deftp {Module} srfi-193
@mdindex srfi-193
This srfi clarifying how the command line arguments can be accessed
via R7RS @code{command-line}, plus a few supporting APIs.

The following procedures are built-in.  @xref{Command-line arguments},
for the details.

@example
command-line          script-file
@end example
@end deftp

@defun command-name
[SRFI-193]
@c MOD srfi-193
If the first element of @code{command-line} is an empty string,
returns @code{#f}.  Otherwise, returns the first element without directory
name and obvious extension (@code{.scm}, @code{.exe}) stripped.

This is useful for diagnostic messages, for example.
@end defun

@defun command-args
[SRFI-193]
@c MOD srfi-193
Returns the cdr of @code{command-line}.
@end defun

@defun script-directory
[SRFI-193]
@c MOD srfi-193
Returns the directory part of @code{script-file}.  It always ends with
the directory separator.
@end defun

@c Local variables:
@c mode: texinfo
@c coding: utf-8
@c end:

