@node Library modules - R7RS standard libraries, Library modules - SRFIs, Library modules - Gauche extensions, Top
@chapter Library modules - R7RS standard libraries

@c NODE ライブラリモジュール - R7RS標準ライブラリ

@c EN
Gauche predates R7RS, and for the convenience, Gauche makes quite a few
procedures as built-in (@pxref{Core library}).  Although the set of
Gauche's core features are mostly superset of R7RS, some functions
and syntaxes have different names and/or interface from R7RS.

R7RS fully-compatible syntaxes and functions are available
in the set of modules described in this chapter.  Since R7RS
programs and libraries needs to follow a specific format
(@code{import} declaration or @code{define-library} form),
generally there's no ambiguity in whether you're looking at R7RS code
or Gauche-specific code.  Also, it is totally transparent to load
R7RS library into Gauche-specific code or vice versa.
However, you need to be aware of which ``world'' you're in when
you code.
@c JP
GaucheはR7RS以前からあり、使い勝手のために非常に多くの組み込み手続きを
持っています(@ref{Core library}参照)。そのほとんどはR7RSのスーパーセットと
なっていますが、いくつかの手続きや構文は違う名前であったり、
違うインタフェースを取っていたりします。

R7RSと完全に互換な構文と関数は、本章で説明されるモジュール群によって提供されます。
R7RSプログラムとライブラリは特定の形式で書かれるので
(@code{import}宣言で始まるか、もしくは@code{define-library}フォーム)、
通常はR7RSのコードを見ているのかGauche特有のコードを見ているのかははっきり区別できます。
また、Gauche特有のコードからR7RSライブラリをロードすることも、その逆も、
全く透過的にできます。
但し、コードを書く時には、どちらの「世界」にいるのかを意識する必要があります。
@c COMMON

@c EN
If you're familiar with Gauche, take a look at
the section @ref{R7RS integration}, which describes how you can
go back and forth between Gauche and R7RS.
@c JP
Gaucheに慣れているプログラマは、まず@ref{R7RS integration}に目を通してください。
どうやってGaucheとR7RSの世界を行き来するか説明してあります。
@c COMMON

@menu
* R7RS integration::
* R7RS small language::
* R7RS large::
@end menu


@node R7RS integration, R7RS small language, Library modules - R7RS standard libraries, Library modules - R7RS standard libraries
@section R7RS integration
@c NODE R7RS統合

@menu
* Traveling between two worlds back and forth::
* Three forms of import::
@end menu

@node Traveling between two worlds back and forth, Three forms of import, R7RS integration, R7RS integration
@subsection Traveling between two worlds back and forth
@c NODE 二つの世界を往き来する

@c EN
When you start Gauche, either in REPL or as a script, you're in
@code{user} module, which @emph{inherits} @code{gauche} module.
Likewise, when you read a library, the initial module inherits
@code{gauche} module (until you call @code{select-module}).
That's why you can access all the built-in procedures of Gauche
without saying @code{(use something)}.  (@xref{Module inheritance}, for
the details about inheriting modules).
@c JP
Gaucheを起動した直後は、それがREPLであってもスクリプトファイルの実行であっても、
トップレベルは@code{user}モジュールになっています。@code{user}モジュールは
@code{gauche}モジュールを@emph{継承}しています。
また、ライブラリを読み込む際にも、(@code{select-module}が呼ばれるまでは)
トップレベルは@code{gauche}を継承したモジュールになっています。
これが、@code{(use something)}等といちいち書かないでも
Gaucheの組み込み手続きを使える理由です。
(モジュールの継承については@ref{Module inheritance}を参照してください)。
@c COMMON

@c EN
On the other hand, R7RS requires to be explicit about which namespaces
you'll be using, by @code{import} form, e.g. @code{(import (scheme base))}.
Besides, R7RS library must be explicitly enclosed by @code{define-library} form.
Before the first @code{import} form of a program, or outside of
@code{define-library}, is beyond R7RS world---the standard defines
nothings about it.
@c JP
一方、R7RSでは@code{import}フォームによってどの名前空間を利用するか明示することが
求められています(例: @code{(import (scheme base))})。
また、R7RSライブラリはそれぞれ@code{define-library}フォームで囲う必要があります。
プログラムの最初の@code{import}より前、あるいはライブラリの@code{define-library}の
外側は、R7RSの世界の外であり、標準では何も規定していません。
@c COMMON

@c EN
These facts let Gauche to set up appropriate ``world'',
and you can use R7RS code and traditional Gauche code transparently.
@c JP
Gaucheはこれを利用して、適切な「世界」を設定し、R7RSコードと既存のGaucheコードを
透過的に混ぜられるようにしています。
@c COMMON

@c EN
NB: As explained in @ref{Three forms of import},
R7RS @code{import} is rather different from Gauche
@code{import}, so we note the former @code{r7rs#import} and the latter
@code{gauche#import} in this section for clarity.  When you write code
don't use prefixes @code{r7rs#} and @code{gauche#}; just write @code{import}.
@c JP
註：@ref{Three forms of import}で説明しますが、
R7RSの@code{import}はGaucheの@code{import}と異なります。この節では
区別が必要な時は前者を@code{r7rs#import}、後者を@code{gauche#import}と
表記しますが、実際のコードでは@code{r7rs#}や@code{gauche#}といったプレフィクスを
つけずに、単に@code{import}と書いてください。
@c COMMON

@c EN
@subheading Loading R7RS libraries
@c JP
@subheading R7RSライブラリをロードする
@c COMMON

@c EN
The @code{define-library} form is defined as a macro in @code{gauche} module;
it sets up R7RS environment before evaluating its contents.
So, when you load an R7RS library (either from Gauche code via @code{use}
form, or from R7RS code via @code{r7rs#import} form),
Gauche starts loading the file in @code{gauche} module, but immediately
see @code{define-library} form, and the rest is handled in R7RS
environment.
@c JP
@code{define-library}フォーム自身は、@code{gauche}モジュール内のマクロとして
定義されていて、R7RS環境を設定してその中身を評価するコードに展開されます。
(Gaucheコードから@code{use}を使うか、
R7RSコードから@code{r7rs#import}フォームを使うかして)R7RSライブラリをロードすると、
Gaucheはファイルの評価を@code{gauche}モジュール内で始めますが、すぐに
@code{define-library}フォームに当たるので、その中身はR7RS環境で処理されることになります。
@c COMMON

@c EN
Suppose you have an R7RS library @code{(mylib foo)} with the following code:
@c JP
以下のコードを持つ、R7RSライブラリ@code{(mylib foo)}があるとしましょう。
@c COMMON

@example
(define-library (mylib foo)
  (import (scheme base))
  (export snoc)
  (begin
    (define (snoc x y) (cons y x))))
@end example

@c EN
It should be saved as @file{mylib/foo.scm} in one of the directories in
@code{*load-path*}.
@c JP
このファイルは@code{*load-path*}にあるディレクトリのどれかの下に、
@file{mylib/foo.scm}という名前で保存されなければなりません。
@c COMMON

@c EN
From R7RS code, this library can be loaded by @code{r7rs#import}:
@c JP
R7RSコードからは、このライブラリは@code{r7rs#import}フォームでロードできます。
@c COMMON

@example
(import (mylib foo))

(snoc 1 2) @result{} (2 . 1)
@end example

@c EN
To use this library from Gauche code, concatenate elements of library
names by @code{.} to get a module name, and @code{use} it:
@c JP
Gaucheコードからこのライブラリを使うには、ライブラリ名の各要素を@code{.}で
つなげたものをモジュール名として、@code{use}します。
@c COMMON

@example
(use mylib.foo)

(snoc 1 2) @result{} (2 . 1)
@end example

@c EN
@subheading Loading Gauche libraries
@c JP
@subheading Gaucheライブラリのロード
@c COMMON

@c EN
To use Gauche library @code{foo.bar} from R7RS code,
split the module name by @code{.} to make a list for the name
of the library.  For example, @code{gauche.lazy} module can be
used from R7RS as follows:
@c JP
Gaucheライブラリの@code{foo.bar}をR7RSコードから使うには、
モジュール名を@code{.}で区切った名前のリストをライブラリ名として使います。
例えば@code{gauche.lazy}モジュールは次のとおりR7RSから使えます。
@c COMMON

@example
(import (gauche lazy))
@end example

@c EN
For SRFI modules, R7RS implementations have a convention to
name it as @code{(srfi n)}, and Gauche follows it.
The following code loads srfi-1 and srfi-13 from R7RS code:
@c JP
SRFIモジュールについては、R7RSでは慣習的に@code{(srfi n)}という
名前を使うので、Gaucheもそれに合わせています。R7RSコードから
srfi-1とsrfi-13を使うには、次のようにします。
@c COMMON

@example
(import (srfi 1) (srfi 13))
@end example

@c EN
(It's not that Gauche treat @code{srfi} name specially; installation
of Gauche includes adapter libraries such as @file{srfi/1.scm}.)
@c JP
(これが動くのは、Gaucheが@code{srfi}という名前を特別扱いしているのではなく、
Gaucheをインストールした時に@code{srfi/1.scm}等のアダプタライブラリが作られているからです)
@c COMMON

@c EN
A tip: To use Gauche's built-in features (the bindings that are
available by default in Gauche code) from R7RS code, import
@code{(gauche base)} library (@pxref{Importing gauche built-ins}):
@c JP
ヒント: Gaucheの組み込みの機能 (Gaucheコードでは最初から使える束縛) を
R7RSコードから使いたい場合は、@code{(gauche base)}ライブラリをimportしてください
(@ref{Importing gauche built-ins}参照)。
@c COMMON

@example
(import (gauche base))

filter @result{} #<closure filter>
@end example

@c EN
@subheading Running R7RS scripts
@c JP
@subheading R7RSスクリプトの実行
@c COMMON

@c EN
R7RS scripts always begin with @code{import} form.  However, @code{r7rs#import}
has a different syntax and semantics
from @code{gauche#import}---so we employ a trick.
@c JP
R7RSスクリプトは必ず@code{import}フォームで始まります。
しかし、@code{r7rs#import}は@code{gauche#import}と文法や意味が異なります。
そこで、ちょっとしたトリックを使っています。
@c COMMON

@c EN
When @code{gosh} is started, it loads the given script file
in @code{user} module.  We have a separate @code{user#import} macro, which
examines its arguments and if it is R7RS import syntax, switch to the
@code{r7rs.user} module and run the @code{r7rs#import}.  Otherwise, it
runs @code{gauche#import}.  @xref{Three forms of import}, for the details.
@c JP
@code{gosh}がスクリプトファイルを読み込むのは@code{user}モジュールです。
そこには@code{user#import}というマクロが用意してあり、
そのマクロは引数を調べて、それがR7RSのimportの構文であれば
@code{r7rs.user}モジュールに切り替えて@code{r7rs#import}を実行し、
そうでなければ@code{gauche#import}を実行します。
詳しくは@ref{Three forms of import}を参照してください。
@c COMMON

@c EN
An example of R7RS script:
@c JP
R7RSスクリプトの例です:
@c COMMON

@example
(import (scheme base) (scheme write))
(display "Hello, world!\n")
@end example

@c EN
If you're already familiar with Gauche scripts, keep in mind that
R7RS program doesn't treat @code{main} procedure specially; it
just evaluates toplevel forms from top to bottom.  So the following
script doesn't output anything:
@c JP
Gaucheスクリプトを見慣れている人は、R7RSプログラムが@code{main}手続きを
特別扱いしないことに気をつけてください。R7RSプログラムは、トップレベルフォームを
順に評価してゆくだけです。したがって次のスクリプトは何も表示しません:
@c COMMON

@example
(import (scheme base) (scheme write))
(define (main args)
  (display "Hello, world!\n")
  0)
@end example

@c EN
To access the command-line arguments in R7RS scripts, use
@code{command-line} in @code{(scheme process-context)} library
(@pxref{R7RS process context}, also @pxref{Command-line arguments}).
@c JP
R7RSスクリプトからコマンドライン引数を利用するには、
@code{(scheme process-context)}ライブラリの@code{command-line}を使います
(@ref{R7RS process context} および @ref{Command-line arguments}参照)。
@c COMMON

@c EN
@subheading Using R7RS REPL
@c JP
@subheading R7RS REPLを使う
@c COMMON

@c EN
When @code{gosh} is invoked with @code{-r7} option and no script file is
given, it enters an R7RS REPL mode.  For the convenience, the following
modules (``libraries'', in R7RS term) are pre-loaded.
@c JP
@code{gosh}が@code{-r7}オプションつきで起動され、スクリプトファイルが
与えられていなかった場合は、R7RS REPLモードになります。
使いやすいように、以下のモジュール (R7RS用語では「ライブラリ」)は
自動的にロードされます。
@c COMMON

@example
(scheme base) (scheme case-lambda) (scheme char)
(scheme complex) (scheme cxr) (scheme eval)
(scheme file) (scheme inexact) (scheme lazy)
(scheme load) (scheme process-context) (scheme read)
(scheme repl) (scheme time) (scheme write)
@end example

@c EN
Besides, the history variables @code{*1}, @code{*2}, @code{*3},
@code{*1+}, @code{*2+}, @code{*3+}, @code{*e} and @code{*history}
are available (@xref{Working in REPL}, for the details of history variables).
@c JP
さらに、ヒストリ変数@code{*1}、@code{*2}、@code{*3}、
@code{*1+}、@code{*2+}、@code{*3+}、@code{*e} および
@code{*history}も使えます (ヒストリ変数の詳細については@ref{Working in REPL}参照)。
@c COMMON

@c EN
You can know you're in R7RS REPL by looking at the prompt, where
@code{gosh} shows the current module (@code{r7rs.user}):
@c JP
R7RS REPLにいることはプロンプトを見ればわかります。
現在のモジュールが@code{r7rs.user}となっているからです。
@c COMMON

@example
gosh[r7rs.user]>
@end example

@c EN
To switch Gauche REPL from R7RS REPL, import @code{(gauche base)} and
select @code{user} module using @code{select-module}:
@c JP
R7RS REPLからGauche REPLにスイッチするには、@code{(gauche base)}を
インポートして@code{select-module}を使って@code{user}モジュールを選びます。
@c COMMON

@example
gosh[r7rs.user]> (import (gauche base))
#<undef>
gosh[r7rs.user]> (select-module user)
#<undef>
gosh>
@end example

@c EN
(You can @code{(select-module gauche)} but that's usually not what you
want to do---changing @code{gauche} module can have unwanted side effects.)
@c JP
(@code{(select-module gauche)}とする手もありますが、おすすめはしません。
@code{gauche}モジュールの中を変えると思いがけない副作用が生じるかもしれませんから。)
@c COMMON

@c EN
When you're working on R7RS code in file and load it into R7RS REPL
(for example, if you're using Emacs Scheme mode, C-c C-l does the job),
make sure the file is in proper shape as R7RS; that is, the file
must start with appropriate @code{import} declarations, or
the file contains @code{define-library} form(s).  If you load
file without those forms, it is loaded into Gauche's @code{user} module
no matter what your REPL's current module is,
and the definitions won't be visible from @code{r7rs.user} module
by default.
@c JP
R7RSコードをファイルに書きだし、R7RS REPLにそのファイルをロードしてインタラクティブに
開発を進めている場合 (例えばEmacsのSchemeモードなら、C-c C-lでファイルがロードできます)、
そのファイルがR7RSとして正しい形式になっていることを確認してください。
つまり、ファイルは@code{import}宣言で始まるか、@code{define-library}形式
から構成されるものでなければなりません。それ以外の、単にSchemeコードが並べて
書いてあるだけのファイルをロードした場合、
それはREPLでの現在のモジュールが何であるかにかかわらずGaucheの@code{user}モジュールに
読み込まれるので、@code{r7rs.user}モジュールからはデフォルトでは見えません。
@c COMMON

@c EN
@subheading Switching from Gauche REPL
@c JP
@subheading Gauche REPLからのスイッチ
@c COMMON

@c EN
By default, @code{gosh} enters Gauche REPL when no script file is given.
@xref{Working in REPL}, for detailed explanation of using REPL.
@c JP
デフォルトでは、@code{gosh}はスクリプトファイルが与えられなければGaucheのREPLに
入ります。REPLの説明は@ref{Working in REPL}を参照してください。
@c COMMON

@c EN
To switch Gauche REPL to R7RS REPL, simply use r7rs-style import;
@code{user#import} knows you want R7RS and make a switch.
@c JP
Gauche REPLからR7RS REPLにスイッチするには、
単にr7rsスタイルのimportを使うだけです。@code{user#import}は
あなたが欲しいのがR7RSであることを察知して環境を切り替えます。
@c COMMON

@example
gosh> (import (scheme base))
#<undef>
gosh[r7rs.user]>
@end example

@c EN
If you don't start @code{gosh} with @code{-r7} option, however,
only the libraries you given to @code{user#import} are loaded at
this moment.
@c JP
ただし、@code{gosh}を@code{-r7}オプションつきで起動していなければ、
この時点でロードされているのは@code{user#import}で指定したライブラリだけです。
@c COMMON

@c EN
If you want to switch the ``vanilla'' r7rs environment, that is, even
not loading @code{(scheme base)}, then you can use @code{r7rs}
module and directly select @code{r7rs.user}:
@c JP
もし、「すっぴん」のR7RS環境、つまり@code{(scheme base)}でさえロードされていない
環境へと切り替えたければ、@code{r7rs}モジュールをuseして
直接@code{r7rs.user}モジュールを選択します。
@c COMMON

@example
gosh> (use r7rs)
gosh> (select-module r7rs.user)
gosh[r7rs.user]>
@end example

@c EN
If you do this, the only
bindings visible initially are @code{import} and @code{define-library};
even @code{define} is undefined!
You have to manually do @code{(import (scheme base))} etc. to start
writing Scheme in this environment.
@c JP
こうして切り替えた場合、使えるフォームは@code{import}と@code{define-library}
だけです (@code{define}でさえ定義されていません!)
この環境でSchemeを書くには、まず @code{(import (scheme base))} 等として
束縛をインポートする必要があります。
@c COMMON


@node Three forms of import,  , Traveling between two worlds back and forth, R7RS integration
@subsection Three import forms
@c NODE 3つのimport形式

@c EN
For historical reasons, Gauche has three @code{import} forms; the original
Gauche's @code{import}, R7RS @code{import}, and the hybrid @code{import}.

Usually it is clear that the code is written in traditional Gauche
or in R7RS, and usage of @code{import} is typically idiomatic, so there's
not much confusion in practice.  Only when you talk about @code{import}
outside of code, you might need to specify which one you're talking.

The hybrid @code{import} is what we described @code{user#import} in
the previous section (@pxref{Traveling between two worlds back and forth}).
It understands both of Gauche's @code{import} and
R7RS @code{import}.
So what you really need to know is the first two.
@c JP
歴史的な事情から、Gaucheには@code{import}形式が3つあります。
もともとのGaucheの@code{import}、R7RSの@code{import}、
そしてハイブリッドの@code{import}です。

通常、コードを読み書きしている時は、それが伝統的なGaucheコードかR7RSコードかは
明確ですし、また@code{import}の使われ方はだいたい決まっているので、
現場で混乱が起きることはありません。ただ、コードの外で@code{import}について
話す場合は、どの@code{import}のことかをはっきりさせるのが良いでしょう。

ハイブリッドの@code{import}は前節で説明した@code{user#import}です
(@ref{Traveling between two worlds back and forth}参照)。
@code{user#import}は
Gaucheの@code{import}とR7RSの@code{import}の両方の文法を理解できるので、
実際に知る必要のあるのは最初の2つの形式です。
@c COMMON

@c EN
Gauche's module system design is inherited from STk, and we've been
used @code{import} for purely name-space level operation; that is,
it assumes the module you import from already exists in memory.
Loading a file that defines the module (if necessary) is
done by separate primitives, @code{require}.  In most cases one file
defines one module, and using that module means @code{require} it then
@code{import} it (it's so common that Gauche has a macro for it---@code{use}).
However, separating those two sometimes comes handy when you need
some nontrivial hacks.  @xref{Using modules}, for the details of
Gauche's @code{import}.
@c JP
Gaucheのモジュールシステム設計はSTkを継承していて、
@code{import}は純粋に名前空間の操作として使われています。
つまり、既にメモリ上に存在するモジュールをインポートするということです。
そのモジュールが定義されているファイルを、(必要なら)ロードするという
操作は別のプリミティブ@code{require}により実現されます。
典型的には、ひとつのファイルがひとつのモジュールを定義していて、
そのモジュールを使うにはまずファイルを@code{require}し、
次にモジュールを@code{import}するということになります
(これはGaucheでは頻繁に出てくるので、@code{use}というマクロが定義されているくらいです)。
ファイルのロードとモジュールのインポートが分かれていることは、
たまに変わったハックが必要とされる時に役に立ちます。
Gaucheの@code{import}については@ref{Using modules}を参照してください。
@c COMMON

@c EN
R7RS leaves out the relation between modules (libraries) and files
in order to give implementation freedom.  If necessary, its @code{import}
must load a file implicitly and transparently.  So R7RS's @code{import}
is semantically Gauche's @code{use}.
@c JP
R7RSは実装に選択の余地を与えるため、モジュール(ライブラリ)とファイルの関係は
敢えて規定していません。R7RSの@code{import}は、
必要ならば暗黙のうちに、透過的にファイルをロードすることが期待されています。
つまり、R7RSの@code{import}はGaucheの@code{use}と意味的に同じと考えられます。
@c COMMON

@c EN
The hybrid @code{import} only appears at the beginning of the Scheme
scripts.  It finds out whether the script is in the traditional Gauche
code or in the R7RS code.  @xref{Traveling between two worlds back and forth}, for the details.
@c JP
ハイブリッド@code{import}はSchemeスクリプトの最初にのみ現れて、
実行されるスクリプトが伝統的なGaucheコードであるかR7RSコードであるかを
判断します。詳細は@ref{Traveling between two worlds back and forth}を参照してください。
@c COMMON

@c EN
Now we'll explain R7RS @code{import}:
@c JP
ではR7RSの@code{import}を説明します:
@c COMMON


@defspec import import-spec @dots{}
[R7RS]
@c EN
Imports libraries specified by @var{import-spec}s.  What R7RS calls
libraries are what Gauche calls modules; they're the same thing.
@c JP
@var{import-spec}で指定されるライブラリをインポートします。
R7RSでいうライブラリは、Gaucheがモジュールと呼んできたものです。両者は同じものです。
@c COMMON

@c EN
R7RS libraries are named by a list of symbols or integers,
e.g. @code{(scheme base)} or @code{(srfi 1)}.
It is translated to Gauche's module name by joining the symbols
by periods; so, R7RS @code{(scheme base)} is Gauche's @code{scheme.base}.
Conversely, Gauche's @code{data.queue} is available as
@code{(data queue)} in R7RS.  To use those two libraries,
R7RS program needs this form at the beginning.
@c JP
R7RSライブラリの名前はシンボルか整数のリストで表されます。
例: @code{(scheme base)}、@code{(srfi 1)}。
この名前は、ピリオドを挟んでシンボル名をつなげることで、Gaucheのモジュール名へと
変換されます。つまり、R7RSの@code{(scheme base)}はGaucheからは@code{scheme.base}
モジュールとして扱えます。逆にGaucheの@code{data.queue}モジュールは
R7RSからは@code{(data queue)}ライブラリとして扱えます。
R7RSプログラムからこれら二つのライブラリを使うには、プログラムの最初に
次のように記します。
@c COMMON

@example
(import (scheme base)
        (data queue))
@end example

@c EN
It works just like Gauche's @code{use} forms; that is, if the named
module doesn't exist in the current process, it loads the file; then
the module's exported bindings become visible from the current module.
@c JP
これはGaucheで@code{use}フォームを使うのと同じです。つまり、もし
その名前を持つモジュールが現在のプロセス内に無ければまずファイルをロードし、
それからモジュールがexportしている束縛を現在のモジュールから見えるようにします。
@c COMMON

@example
(use scheme.base)
(use data.queue)
@end example

@c EN
(You may wonder what if R7RS library uses symbols with periods in them.
Frankly, we haven't decided yet.   It'll likely be that we use some
escaping mechanism; for the time being you'd want to stick with
alphanumeric characters and hyphens as possible.)
@c JP
(勘の良い読者は、R7RSのライブラリがピリオドを中に含むシンボルを名前に使っていたら
どうなるのか疑問に思ったことでしょう。正直なところ、まだどうするか決めていません。
多分、何らかのエスケープ機構を用意することになると思いますが、
今のところ、できる限りモジュール名にはアルファベット、数字、ハイフンだけを
使うようにしておいて下さい。)
@c COMMON

@c EN
Just like Gauche's @code{use}, you can select which symbols to be
imported (or not imported), rename specific symbols, or add
prefix to all imported symbols.  The formal syntax
of R7RS import syntax is as follows:
@c JP
R7RSの@code{import}フォームは、
Gaucheの@code{use}と同様、どのシンボルをimportするか/しないかを指定したり、
名前を変えてimportしたりプレフィクスを付加することができます。
R7RSの@code{import}の正式な構文は次の通りです。
@c COMMON

@smallexample
<import declaration> : (import <import-set> <import-set> ...)

<import-set> : <library-name>
  | (only <import-set> <identifier> <identifier> ...)
  | (except <import-set> <identifier> <identifier> ...)
  | (prefix <import-set> <identifier>)
  | (rename <import-set>
            (<identifier> <identifier>)
            (<identifier> <identifier>) ...)

<library-name> : (<identifier-or-base-10-integer>
                  <identifier-or-base-10-integer> ...)
@end smallexample
@end defspec

@node R7RS small language, R7RS large, R7RS integration, Library modules - R7RS standard libraries
@section R7RS small language
@c NODE R7RS small language

@menu
* R7RS library form::
* R7RS base library::           @code{scheme.base}
* R7RS case-lambda::            @code{scheme.case-lambda}
* R7RS char library::           @code{scheme.char}
* R7RS complex numbers::        @code{scheme.complex}
* R7RS cxr accessors::          @code{scheme.cxr}
* R7RS eval::                   @code{scheme.eval}
* R7RS file library::           @code{scheme.file}
* R7RS inexact numbers::        @code{scheme.inexact}
* R7RS lazy evaluation::        @code{scheme.lazy}
* R7RS load::                   @code{scheme.load}
* R7RS process context::        @code{scheme.process-context}
* R7RS read::                   @code{scheme.read}
* R7RS repl::                   @code{scheme.repl}
* R7RS time::                   @code{scheme.time}
* R7RS write::                  @code{scheme.write}
* R5RS compatibility::          @code{scheme.r5rs}
@end menu

@node R7RS library form, R7RS base library, R7RS small language, R7RS small language
@subsection R7RS library form
@c NODE R7RSライブラリ形式

@c EN
R7RS libraries are defined by @code{define-library} form.

In R7RS view, @code{define-library} form itself does not belong
to a Scheme code---it exists outside of the Scheme world.
It defines the boundary of
R7RS Scheme; inside @code{define-library} there is R7RS world,
but outside, it's not a business of R7RS.
For example, you can't generate
@code{define-library} by a macro, within R7RS specification.

In Gauche, we implement R7RS world inside Gauche world;
@code{define-library} itself is interpreted in the Gauche world.
In fact, @code{define-library} @emph{is} a Gauche macro.
However, if you're writing portable R7RS code, you should forget
how @code{define-library} is implemented, and do not put anything
outside of @code{define-library} form.
@c JP
R7RSのライブラリは@code{define-library}フォームで定義されます。

R7RSの観点では@code{define-library}フォーム自体はSchemeコードではありません。
それ自身はScheme世界の外にあります。@code{define-library}フォームが、
R7RS Schemeの境界となるのです。その内側はR7RSの世界であり、
その外側に関してR7RSは関知しません。例えば、R7RSの仕様の範囲内では、
@code{define-library}フォーム自体をマクロで生成する、ということはできません。

Gaucheでは、R7RSの世界をGaucheの世界の中に作っています。
@code{define-library}自体はGauche世界で解釈されます。実際、
@code{define-library}はGaucheのマクロとして実装されています。
けれどもR7RSのコードを書く際には、@code{define-library}がどう実装されているかは
気にする必要はありません。また、@code{define-library}の外側には
何も書かないようにしてください。
@c COMMON

@defmac define-library library-name library-decl @dots{}
[R7RS]
@c EN
Defines a library @var{library-name}, which is a list of
symbols or base-10 integer:
@c JP
@var{library-name}という名前を持つライブラリを定義します。
@var{library-name}はシンボルもしくは10進整数のリストです。
@c COMMON

@smallexample
<library-name> : (<identifier-or-base-10-integer>
                  <identifier-or-base-10-integer> ...)
@end smallexample

@c EN
Library declarations @var{library-decl}
can be export declarations, import declarations,
@code{begin}-list of Scheme code,
include forms, or @code{cond-expand} forms.
@c JP
ライブラリ宣言@var{library-decl}は、エクスポート宣言、
インポート宣言、@code{begin}に囲まれたSchemeコード、
インクルードフォーム、あるいは@code{cond-expand}フォームです。
@c COMMON

@smallexample
<library-decl> : (export <export-spec> @dots{})
               | <import declaration>
               | (begin <command-or-definition> @dots{})
               | (include <string> <string2> @dots{})
               | (include-ci <string> <string2> @dots{})
               | (include-library-declarations
                        <string> <string2> @dots{})
               | (cond-expand <cond-expand-clause>
                              <cond-expand-clause2> @dots{})
               | (cond-expand <cond-expand-clause>
                              <cond-expand-clause2> @dots{}
                              (else <library-decl> @dots{}))
@end smallexample

@c EN
The @code{export} declaration is the same Gauche's @code{export}
form; @pxref{Using modules}.
@c JP
@code{export}宣言はGaucheの@code{export}フォームと同じです。
@ref{Using modules}参照。
@c COMMON

@c EN
The @code{import} declaration is R7RS's @code{import} form,
described in @ref{Three forms of import}.
@c JP
@code{import}宣言はR7RSの@code{import}フォームで、
@ref{Three forms of import}で説明しています。
@c COMMON

@c EN
The @code{include} and @code{include-ci} declarations
are the same as Gauche's; @pxref{Inclusions}.
Note that Gauche allows any code to be included---the content of
the named file is simply wrapped with @code{begin} and
substituted with these forms---but in R7RS definition,
what you include must contain only Scheme code
(not one of the library declarations or @code{define-library} form).
@c JP
@code{include}と@code{include-ci}フォームはGaucheのそれと同じです。
@ref{Inclusions}参照。Gaucheはインクルードされるコードの中身については
感知せず、単にその中身を@code{begin}で囲んで元のフォームと
置き換えるだけです。けれどもR7RSでは、これらのフォームが読み込むファイルには
Schemeコードのみが許されます(例えば@code{define-library}フォームや
他のライブラリ宣言フォームはだめです)。
@c COMMON

@c EN
The @code{include-library-declarations} declaration works like @code{include},
but the content of the read file is interpreted
as library declarations instead of Scheme code.
@c JP
@code{include-library-declarations}宣言は@code{include}宣言と
同じように動作しますが、読み込まれるファイルの中身はSchemeコードではなく
ライブラリ宣言として解釈されます。
@c COMMON

@c EN
The @code{cond-expand} declaration is also the same as Gauche's;
@pxref{Feature conditional}.  When used directly below
@code{define-library}, it must expands to one of the
library declarations.
@c JP
@code{cond-expand}宣言もGaucheのそれと同じです。
@ref{Feature conditional}参照。
但し、@code{define-library}の直下で使われた場合は、
展開結果もライブラリ宣言になっている必要があります。
@c COMMON
@end defmac


@node R7RS base library, R7RS case-lambda, R7RS library form, R7RS small language
@subsection @code{scheme.base} - R7RS base library
@c NODE R7RS基本ライブラリ, @code{scheme.base} - R7RS基本ライブラリ

@deftp {Module} scheme.base
@mdindex scheme.base
@c EN
Exports bindings of R7RS @code{(scheme base)} library.  From R7RS programs,
those bindings are available by @code{(import (scheme base))}.
@c JP
R7RSの@code{(scheme base)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は@code{(import (scheme base))}とすることで
使えます。
@c COMMON
@end deftp

@c EN
@subheading Bindings common to Gauche's built-ins
@c JP
@subheading Gaucheの組み込み束縛と共通なもの
@c COMMON

@c EN
The following syntaxes and procedures are the same as Gauche's
builtins:
@c JP
以下の構文の手続きはGaucheの組み込みのものと同じです。
@c COMMON

@table @asis
@item Primitive expression types
@example
quote if include include-ci lambda
@end example
@item Derived expression types
@example
cond case and or when unless cond-expand let let* letrec letrec*
let-values let*-values begin do make-parameter parameterize
guard quasiquote unquote unquote-splicing case-lambda
@end example
@item Macros
@example
let-syntax letrec-syntax syntax-rules syntax-error define-syntax
@end example
@item Variable definitions
@example
define define-values
@end example
@item Record type definitions
@example
define-record-type
@end example
@item Equivalence predicates
@example
eqv? eq? equal?
@end example
@item Numbers
@example
number? complex? real? rational? integer? exact? exact-integer?
= < > <= >= zero? positive? negative? odd? even? max min + * - / abs
floor/ floor-quotient floor-remainder
truncate/ truncate-quotient truncate-remainder
quotient modulo remainder gcd lcm numerator denominator
floor ceiling truncate round rationalize square exact-integer-sqrt
expt inexact exact number->string string->number
@end example
@item Booleans
@example
not boolean? boolean=?
@end example
@item Pairs and lists
@example
pair? cons car cdr set-car! set-cdr! caar cadr cdar cddr null? list?
make-list list length append reverse list-tail list-ref list-set!
memq memv member assq assv assoc list-copy
@end example
@item Symbols
@example
symbol? symbol=? symbol->string string->symbol
@end example
@item Characters
@example
char? char=? char<? char>? char<=? char>=? char->integer integer->char
@end example
@item Strings
@example
string? make-string string string-length string-ref string-set!
string=? string<? string>? string<=? string>=? substring string-append
string->list list->string string-copy string-copy! string-fill!
string-map string-for-each
@end example
@item Vectors
@example
vector? make-vector vector vector-length vector-ref vector-set!
vector->list list->vector vector->string string->vector
vector-copy vector-copy! vector-append vector-fill!
@end example
@item Control features
@example
procedure? apply map call-with-current-continuation call/cc
values call-with-values dynamic-wind
@end example
@item Exception
@example
error
@end example
@item Environments and evaluation
@example
scheme-report-environment null-environment
@end example
@item Input and output
@example
input-port? output-port? port? current-input-port current-output-port
current-error-port close-port close-input-port close-output-port
open-input-string open-output-string get-output-string
read-char peek-char read-u8 peek-u8
read-line eof-object? eof-object char-ready? u8-ready?
newline write-char write-u8
@end example
@end table

@c EN
@subheading Bytevector utilities
@c JP
@subheading バイトベクタユーティリティ
@c COMMON

@c EN
R7RS's bytevectors are the same as Gauche's u8vectors.

The following procedures are the same as @code{gauche.uvector}'s
(@pxref{Bytevector compatibility}).
@c JP
R7RSのバイトベクタはGaucheのu8vectorと同じです。

以下の手続きは@code{gauche.uvector}のものと同じです。
(@ref{Bytevector compatibility}参照)。
@c COMMON

@example
bytevector         bytevector?       make-bytevector
bytevector-length  bytevector-u8-ref bytevector-u8-set!
bytevector-copy    bytevector-copy!  bytevector-append
read-bytevector    read-bytevector!  write-bytevector
@end example

@c EN
The following procedures are the same as @code{gauche.vport}'s
(@pxref{Virtual ports}).
@c JP
以下の手続きは@code{gauche.vport}のものと同じです。
(@ref{Virtual ports}参照)。
@c COMMON

@example
open-input-bytevector open-output-bytevector get-output-bytevector
@end example

@c EN
And the following procedures are the same as @code{gauche.unicode}'s
(@pxref{Unicode transfer encodings}).
@c JP
そして以下の手続きは@code{gauche.unicode}のものと同じです。
(@ref{Unicode transfer encodings}参照)。
@c COMMON

@example
utf8->string       string->utf8
@end example

@c EN
@subheading Control features
@c JP
@subheading 制御機能
@c COMMON

@defun with-exception-handler handler thunk
[R7RS base]
@c MOD scheme.base
@c EN
@var{handler} is evaluated in the dynamic environment of the call to
@var{handler}, except that the current exception handler is that in
place for the call to @code{with-exception-handler}.

If the exception is not continuable, it is reraised after evaluating
@var{handler} and handled by the exception handler in place for the
call to @code{with-exception-handler}.
@c JP
@var{handler}は、@var{handler}呼び出し時の動的環境で評価されます。
ただし、@var{handler}内における例外ハンドラは、
@code{with-exception-handler}呼び出し時の例外ハンドラになります。

例外が継続不可能な場合、@var{handler}の評価後にさらに例外が発生し、それは
@code{with-exception-handler}呼び出し時の例外ハンドラで処理されます。
@c COMMON

@c EN
This slightly differs from Gauche's built-in @code{with-exception-handler},
which calls @var{handler} without replacing the current exception handler.
@xref{Handling exceptions}, for the details.
@c JP
これはGaucheの組み込みの@code{with-exception-handler}と微妙に異なります。
組み込みの方は、現在の例外ハンドラを置き換えずに@var{handler}を呼び出します。
詳しくは@ref{Handling exceptions}を参照してください。
@c COMMON
@end defun

@defun raise obj
@defunx raise-continuable obj
[R7RS base]
@c MOD scheme.base
@c EN
Gauche's @code{raise} may return if @var{obj} isn't a
@code{<serious-condition>}.
Distinguishing continuable and noncontinuable exception throw by the
procedure has an issue when your exception handler wants to reraise
the condition (you don't know if the original condition is raised
by @code{raise} or @code{raise-continuable}!).  Yet R7RS adopted
that model, so we compel.

R7RS @code{raise} is a wrapper of Gauche's @code{raise},
which throws an error if Gauche's @code{raise} returns.

R7RS @code{raise-continuable} is currently just an alias of
Gauche's @code{raise}---as long as you don't pass
@code{<serious-condition>}, it may return.  It is not exactly
R7RS conformant---it won't return if you pass @code{<serious-condition>}
or object of one of its subclasses (e.g. @code{<error>}), but
it's weired to expect returning from raising @code{<error>}, isn't it?
@c JP
Gaucheの@code{raise}は、@var{obj}が@code{<serious-condition>}でなければ、
例外ハンドラから戻って来ることを許しています。
継続可能な例外報告と継続不可能な例外報告を手続きで区別するのは、
例外ハンドラが渡されたコンディションを再び投げる場合に問題となります
(元のコンディションが@code{raise}で投げられたのか@code{raise-continuable}で
投げられたのか知る術がない!)。
しかしR7RSではそのモデルを採用したため、何とか合わせようとしています。

R7RS版の@code{raise}はGaucheの@code{raise}のラッパーで、
Gaucheの@code{raise}から戻って来たらエラーを投げるようにしています。

R7RSの@code{raise-continuable}は今のところGaucheの@code{raise}の
別名になっています。@code{<serious-condition>}を渡さなければ、
戻ってくることが可能です。R7RS準拠でないのは、
@code{<serious-condition>}かそのサブクラスのオブジェクト(例えば@code{<error>})を
@code{raise-continuable}に渡した場合ですが、
@code{<error>}を投げて戻って来ることを期待するというのはちょっとおかしいですよね。
@c COMMON
@end defun

@defun error-object? exc
[R7RS base]
@c MOD scheme.base
@c EN
Defined as @code{(condition-has-type? exc <error>))}
@c JP
@code{(condition-has-type? exc <error>))}として定義されています。
@c COMMON
@end defun

@defun error-object-message exc
[R7RS base]
@c MOD scheme.base
@c EN
If @var{exc} is a @code{<message-condition>},
returns its @code{message-prefix} slot;
otherwise, returns an empty string.
@c JP
@var{exc}が@code{<message-condition>}であれば
@code{message-prefix}の内容を、持っていなければ空文字列を返します。
@c COMMON
@end defun

@defun error-object-irritants exc
[R7RS base]
@c MOD scheme.base
@c EN
If @var{exc} is a @code{<message-condition>},
returns its @code{message-args} slot;
otherwise, returns an empty string.
@c JP
@var{exc}が@code{<message-condition>}であれば
@code{message-args}の内容を、持っていなければ空文字列を返します。
@c COMMON
@end defun

@defun read-error? exc
[R7RS base]
@c MOD scheme.base
@c EN
Defined as @code{(condition-has-type? e <read-error>))}.
@c JP
@code{(condition-has-type? e <read-error>))}として定義されています。
@c COMMON
@end defun

@defun file-error? exc
[R7RS base]
@c MOD scheme.base
@c EN
At this moment, Gauche doesn't have distinct @code{<file-error>} condition,
but most file errors are thrown as one of @code{<system-error>}s.
This procedure checks error code of @code{<system-error>} and
returns @code{#t} if the error is likely to be related to the filesystem.
@c JP
今のところ、Gaucheは独立した@code{<file-error>}コンディションを持っていませんが、
ファイルエラーのほとんどは@code{<system-error>}として投げられます。
この手続きは@code{<system-error>}のエラーコードを調べ、ファイルに起因するエラー
の場合に@code{#t}を返すようにしています。
@c COMMON
@end defun

@c EN
@subheading Input and output
@c JP
@subheading 入出力
@c COMMON

@defun textual-port? port
@defunx binary-port? port
[R7RS base]
@c MOD scheme.base
@c EN
Gauche's port can handle both, so these are equivalent to @code{port?}.
@c JP
Gaucheのポートはどちらも扱えるので、これらの手続きは@code{port?}と等価です。
@c COMMON
@end defun

@defun input-port-open? iport
@defunx output-port-open? oport
[R7RS base]
@c MOD scheme.base
@c EN
Checks whether @var{iport}/@var{oport} is an input/output port @emph{and}
it is not closed.
@c JP
@var{iport}/@var{oport}がそれぞれ入力/出力ポートであり、かつクローズされていなければ
@code{#t}を返します。
@c COMMON
@end defun


@defun flush-output-port :optional oport
[R7RS base]
@c MOD scheme.base
@c EN
An alias to @code{flush}.
@c JP
@code{flush}の別名です。
@c COMMON
@end defun

@defun features
[R7RS base]
@c MOD scheme.base
@c EN
Returns a list of symbols of supported feature identifiers,
recognized by @code{cond-expand} (@pxref{Feature conditional}).
@c JP
サポートされている@code{feature-identifier}のリストを返します。
@code{feature-identifier}については、@code{cond-expand}を参照してください
(@ref{Feature conditional}参照)。
@c COMMON
@end defun


@node R7RS case-lambda, R7RS char library, R7RS base library, R7RS small language
@subsection @code{scheme.case-lambda} - R7RS case-lambda
@c NODE R7RS case-lambda, @code{scheme.case-lambda} - R7RS case-lambda

@deftp {Module} scheme.case-lambda
@mdindex scheme.case-lambda
@c EN
Exports bindings of R7RS @code{(scheme case-lambda)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme case-lambda))}.

The only binding exported from this module is @code{case-lambda},
and it is the same as Gauche's built-in @code{case-lambda};
@pxref{Making procedures} for the details.
@c JP
R7RSの@code{(scheme case-lambda)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme case-lambda))}とすることで使えます。

このモジュールからエクスポートされるのは@code{case-lambda}だけで、
Gauche組み込みの@code{case-lambda}そのものです。
詳しくは@ref{Making procedures}を参照してください。
@c COMMON
@end deftp


@node R7RS char library, R7RS complex numbers, R7RS case-lambda, R7RS small language
@subsection @code{scheme.char} - R7RS char library
@c NODE R7RS文字ライブラリ, @code{scheme.char} - R7RS文字ライブラリ

@deftp {Module} scheme.char
@mdindex scheme.char
@c EN
Exports bindings of R7RS @code{(scheme char)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme char))}.
@c JP
R7RSの@code{(scheme char)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme char))}とすることで使えます。
@c COMMON
@end deftp

@c EN
The following procedures are the same as Gauche's builtin procedures;
@pxref{Characters}.
@c JP
以下の手続きはGaucheの組み込みのものと同じです。@ref{Characters}参照。
@c COMMON

@example
char-alphabetic? char-ci<=? char-ci<?  char-ci=? char-ci>=? char-ci>?
char-downcase char-foldcase char-lower-case? char-numeric?
char-upcase char-upper-case?  char-whitespace?
@end example

@c EN
The following procedures are the same as the ones provided
in @code{gauche.unicode} module (@pxref{Full string case conversion}).
They use full case folding by Unicode standard (e.g. taking into
account of German eszett).
@c JP
以下の手続きは@code{gauche.unicode}で提供されているものと同じです
(@ref{Full string case conversion}参照)。Unicodeで定義されている
フルセットの大文字小文字変換を使います(例えばドイツ語のエスツェットが考慮されます)。
@c COMMON

@example
string-ci<=? string-ci<?  string-ci=? string-ci>=?  string-ci>?
string-downcase string-foldcase string-upcase
@end example

@defun digit-value c
[R7RS char]
@c MOD scheme.char
@c EN
If @var{c} is a character with @code{Nd} general category---that is,
if it represents a decimal digit---this procedure returns the value
the character represents.  Otherwise it returns @code{#f}.
@c JP
@var{c}が@code{Nd}カテゴリの文字、つまり十進数の数字を表す文字であれば、
その文字が表す値を返します。それ以外の場合は@code{#f}を返します。
@c COMMON

@example
(digit-value #\3) @result{} 3

(digit-value #\z) @result{} #f
@end example

@c EN
Note that Unicode defines about two dozen sets of digit characters.
@c JP
Unicodeには20種類以上の数字が定義されています。
@c COMMON

@example
(digit-value #\x11068) @result{} 2
@end example

@c EN
Gauche's built-in procedure @code{digit->integer} has more general
interface (@pxref{Characters}).
@c JP
Gauche組み込みの@code{digit->integer}はより汎用的なインタフェースを
持っています(@ref{Characters}参照)。
@c COMMON

@example
(digit-value c) @equiv{} (digit->integer c 10 #t)
@end example
@end defun

@node R7RS complex numbers, R7RS cxr accessors, R7RS char library, R7RS small language
@subsection @code{scheme.complex} - R7RS complex numbers
@c NODE R7RS複素数, @code{scheme.complex} - R7RS複素数

@deftp {Module} scheme.complex
@mdindex scheme.complex
@c EN
Exports bindings of R7RS @code{(scheme complex)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme complex))}.
@c JP
R7RSの@code{(scheme complex)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme complex))}とすることで使えます。
@c COMMON

@c EN
This module provides the following bindings, all of which are
Gauche built-in (@pxref{Numerical conversions}).
@c JP
このモジュールは以下の束縛を提供します。
全てGaucheの組み込みです(@ref{Numerical conversions}参照)。
@c COMMON

@example
angle imag-part magnitude make-polar make-rectangular real-part
@end example
@end deftp


@node R7RS cxr accessors, R7RS eval, R7RS complex numbers, R7RS small language
@subsection @code{scheme.cxr} - R7RS cxr accessors
@c NODE R7RS cxrアクセサ, @code{scheme.cxr} - R7RS cxrアクセサ

@deftp {Module} scheme.cxr
@mdindex scheme.cxr
@c EN
Exports bindings of R7RS @code{(scheme cxr)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme cxr))}.
@c JP
R7RSの@code{(scheme complex)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme complex))}とすることで使えます。
@c COMMON

@c EN
This module provides the following bindings, all of which are
Gauche built-in (@pxref{List accessors and modifiers}).
@c JP
このモジュールは以下の束縛を提供します。
全てGaucheの組み込みです(@ref{List accessors and modifiers}参照)。
@c COMMON

@example
caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar
caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar
cddadr cdddar cddddr
@end example
@end deftp

@node R7RS eval, R7RS file library, R7RS cxr accessors, R7RS small language
@subsection @code{scheme.eval} - R7RS eval
@c NODE R7RS eval, @code{scheme.eval} - R7RS eval

@deftp {Module} scheme.eval
@mdindex scheme.eval
@c EN
Exports bindings of R7RS @code{(scheme eval)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme eval))}.
@c JP
R7RSの@code{(scheme eval)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme eval))}とすることで使えます。
@c COMMON
@end deftp

@defun eval expr environment
[R7RS eval]
@c MOD scheme.eval
@c EN
This is the same as Gauche's built-in @code{eval} (@pxref{Eval and repl}).
@c JP
Gauche組み込みの@code{eval}と同じです (@ref{Eval and repl}参照)。
@c COMMON
@end defun

@defun environment import-list @dots{}
[R7RS eval]
@c MOD scheme.eval
@c EN
This is R7RS way to create an environment specifier suitable to pass
to @code{eval}.  In Gauche, an environment specifier is just a
module object.
@c JP
これはR7RSで@code{eval}に渡せる環境指定子を作る手段です。Gaucheでは、
環境指定子は単なるモジュールオブジェクトです。
@c COMMON

@c EN
The argument is the same as what @code{r7rs#import} takes.
This procedure creates an empty environment (as a fresh anonymous module;
see @code{make-module} in @ref{Module introspection}, for the details),
then imports the bindings as specified by @var{import-list}s.

The following example creates an environment that includes
@code{scheme.base} bindings plus @code{select-module} syntax from Gauche.
@c JP
引数は@code{r7rs#import}が取るものと同じです。
この手続きはまず空の環境(=無名のモジュールです。
詳しくは@ref{Module introspection}の@code{make-module}参照)を作り、
それから@var{import-list}に指定される束縛をインポートします。

以下の例は、@code{scheme.base}及びGauche組み込みの@code{select-module}を
インポートした環境を作ります。
@c COMMON

@example
(environment
 '(scheme base)
 '(only (gauche base) select-module))
 @result{} #<module #f>  ; an anonymous module
@end example
@end defun


@node R7RS file library, R7RS inexact numbers, R7RS eval, R7RS small language
@subsection @code{scheme.file} - R7RS file library
@c NODE R7RSファイルライブラリ, @code{scheme.file} - R7RSファイルライブラリ

@deftp {Module} scheme.file
@mdindex scheme.file
@c EN
Exports bindings of R7RS @code{(scheme file)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme file))}.
@c JP
R7RSの@code{(scheme file)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme file))}とすることで使えます。
@c COMMON
@end deftp

@c EN
The following bindings provided in this module are
Gauche built-in (@pxref{File ports}, and @ref{File stats}).
@c JP
次に挙げる束縛はGaucheの組み込みと同じです
(@ref{File ports}及び@ref{File stats}参照)。
@c COMMON

@example
call-with-input-file call-with-output-file
file-exists?
open-input-file open-output-file
with-input-from-file with-output-to-file
@end example

@c EN
The following binding is the same as one in @code{file.util}
(@pxref{File operations}).
@c JP
以下の束縛は@code{file.util}で提供されるものと同じです
(@ref{File operations}参照)。
@c COMMON

@example
delete-file
@end example

@defun open-binary-input-file filename
@defunx open-binary-output-file filename
[R7RS file]
@c MOD scheme.file
@c EN
In Gauche, ports are both textual and binary at the same time,
so these R7RS procedures
are just aliases of @code{open-input-file} and @code{open-output-file},
respectively.  @xref{File ports}.
@c JP
Gaucheでは、ポートは同時にテキストポートでもバイナリポートでもあるので、
これらのR7RS手続きは単に
@code{open-input-file}と@code{open-output-file}の別名になっています。
@ref{File ports}参照。
@c COMMON
@end defun

@node R7RS inexact numbers, R7RS lazy evaluation, R7RS file library, R7RS small language
@subsection @code{scheme.inexact} - R7RS inexact numbers
@c NODE R7RS不正確数, @code{scheme.inexact} - R7RS不正確数

@deftp {Module} scheme.inexact
@mdindex scheme.inexact
@c EN
Exports bindings of R7RS @code{(scheme inexact)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme inexact))}.
@c JP
R7RSの@code{(scheme inexact)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme inexact))}とすることで使えます。
@c COMMON

@c EN
This module provides the following bindings, all of which are
Gauche built-in (@pxref{Arithmetics}, and @ref{Numerical predicates}).
@c JP
このモジュールは以下の束縛を提供します。全てGaucheの組み込みです
(@ref{Arithmetics}及び@ref{Numerical predicates}参照)。
@c COMMON

@example
acos asin atan cos exp finite? infinite? log nan? sin sqrt tan
@end example
@end deftp

@node R7RS lazy evaluation, R7RS load, R7RS inexact numbers, R7RS small language
@subsection @code{scheme.lazy} - R7RS lazy evaluation
@c NODE R7RS遅延評価, @code{scheme.lazy} - R7RS遅延評価

@deftp {Module} scheme.lazy
@mdindex scheme.lazy
@c EN
Exports bindings of R7RS @code{(scheme lazy)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme lazy))}.
@c JP
R7RSの@code{(scheme inexact)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme inexact))}とすることで使えます。
@c COMMON
@end deftp

@c EN
The following bindings this module provides are Gauche built-ins
(@pxref{Delay force and lazy}).
@c JP
以下の束縛は、Gauche組み込みです
(@ref{Delay force and lazy}参照)。
@c COMMON

@example
delay force promise?
@end example

@defspec delay-force promise
[R7RS lazy]
@c MOD scheme.lazy
@c EN
This is the same as Gauche's built-in @code{lazy}.
@pxref{Delay force and lazy} for the discussion about when this
form should be used.
@c JP
これはGauche組み込みの@code{lazy}と同じです。
使い方については@ref{Delay force and lazy}の議論を参照してください。
@c COMMON
@end defspec

@defun make-promise obj
[R7RS lazy]
@c MOD scheme.lazy
@c EN
If @var{obj} is a promise, it is returned as is.  Otherwise,
A promise, which yields @var{obj} when forced, is returned.
Because this is a procedure, expression passed as @var{obj} is
eagerly evaluated, so this doesn't have effect on lazy evaluation,
but can be used to ensure you have a promise.
@c JP
@var{obj}がプロミスならそのまま返されます。そうでなければ、
forceされた時に@var{obj}が返されるようなプロミスが返されます。
これは手続きなので、@var{obj}は@code{make-promise}を呼び出す前に
評価されてしまいます。従って遅延評価には使えませんが、
確実にプロミスを得たい場合に使えます。
@c COMMON

@c EN
This procedure is important on implementations where
@code{force} only takes a promise, and portable code should
use this procedure to yield a value that can be passed to @code{force}.
@c JP
@code{force}がプロミスのみを取るような実装ではこの手続きは重要です。
ポータブルなコードは、@code{force}に渡すものがプロミスであることを
確実にしたい場所でこの手続きを使うようにしてください。
@c COMMON

@c EN
If you write Gauche-specific code, however, @code{force} can take
non-promise values, so you don't need this.
@c JP
Gaucheの@code{force}はプロミスでない値も取れるので、
Gauche専用のコードを書いている時はこの手続きは不要です。
@c COMMON
@end defun


@node R7RS load, R7RS process context, R7RS lazy evaluation, R7RS small language
@subsection @code{scheme.load} - R7RS load
@c NODE R7RS load, @code{scheme.load} - R7RS load

@deftp {Module} scheme.load
@mdindex scheme.load
@c EN
Exports bindings of R7RS @code{(scheme load)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme load))}.
@c JP
R7RSの@code{(scheme load)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme load))}とすることで使えます。
@c COMMON
@end deftp

@defun load file :optional env
[R7RS load]
@c MOD scheme.load
@c EN
R7RS @code{load} takes environment as an optional argument,
while Gauche @code{load} takes it as a keyword argument
(among other keyword arguments).  @xref{Loading Scheme file}.

In Gauche, @var{env} is just a module.  In portable code,
you can create a module with desired bindings with R7RS @code{environment}
procedure; @pxref{R7RS eval}.
@c JP
R7RSの@code{load}は省略可能引数として環境を取ります。
Gaucheの@code{load}では環境はキーワード引数で受け取られることに注意してください。
@ref{Loading Scheme file}参照。

また、Gaucheでは環境は単にモジュールで良いのですが、
ポータブルなコードではR7RSの@code{environment}手続きを使って
環境を作る必要があります。@ref{R7RS eval}参照。
@c COMMON
@end defun


@node R7RS process context, R7RS read, R7RS load, R7RS small language
@subsection @code{scheme.process-context} - R7RS process context
@c NODE R7RSプロセスコンテキスト, @code{scheme.process-context} - R7RSプロセスコンテキスト

@deftp {Module} scheme.process-context
@mdindex scheme.process-context
@c EN
Exports bindings of R7RS @code{(scheme process-context)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme process-context))}.
@c JP
R7RSの@code{(scheme process-context)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、エクスポートされた束縛は
@code{(import (scheme process-context))}とすることで使えます。
@c COMMON
@end deftp

@c EN
The following bindings are the same as Gauche built-ins
(@pxref{Command-line arguments}, and @ref{Program termination}):
@c JP
次の束縛はGauche組み込みのものと同じです
(@ref{Command-line arguments}、および@ref{Program termination}参照)：
@c COMMON

@example
command-line exit
@end example

@c EN
The following bindings are the same as SRFI-98
(@pxref{Accessing environment variables}):
@c JP
次の束縛はsrfi-98のものと同じです
(@ref{Accessing environment variables}参照)：
@c COMMON

@example
get-environment-variable get-environment-variables
@end example

@defun emergency-exit :optional (obj 0)
[R7RS process-context]
@c MOD scheme.process-context
@c EN
Terminate the program without running any clean-up procedures
(@var{after} thunks of @code{dynamic-wind}).    I/O buffers won't
be flushed.
Internally,
it calls the @code{_exit(2)} system call directly.
The optional argument is used for the process exit code.
When omitted, 0 is assumed.

This is almost the same
as Gauche's @code{sys-exit}, except that @code{sys-exit} requires
the exit code argument (@pxref{Program termination}).
@c JP
クリーンアップ手続きを飛ばしてプログラムを直ちに終了させます
(@code{dynamic-wind}によって設定された@var{after}サンクは実行されません)。
内部的には、@code{_exit(2)}システムコールを直接呼んでいます。
省略可能引数はプロセスの終了コードを指定します。省略された場合は0になります。

この手続きはGaucheの@code{sys-exit}とほぼ同じですが、
@code{sys-exit}の方は終了コード引数が必須です
(@ref{Program termination}参照)。
@c COMMON
@end defun

@node R7RS read, R7RS repl, R7RS process context, R7RS small language
@subsection @code{scheme.read} - R7RS read
@c NODE R7RS read, @code{scheme.read} - R7RS read

@deftp {Module} scheme.read
@mdindex scheme.read
@c EN
Exports bindings of R7RS @code{(scheme read)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme read))}.

The only binding exported from this module is @code{read},
which is the same as Gauche's built-in.  @xref{Reading data}.
@c JP
R7RS @code{(scheme read)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、
@code{(import (scheme read))}とすることでこれらの名前が使えるようになります。

このモジュールからエクスポートされるのは@code{read}のみで、
これはGaucheでは組み込みになっています。@ref{Reading data}参照。
@c COMMON
@end deftp

@node R7RS repl, R7RS time, R7RS read, R7RS small language
@subsection @code{scheme.repl} - R7RS repl
@c NODE R7RS repl, @code{scheme.repl} - R7RS repl

@deftp {Module} scheme.repl
@mdindex scheme.repl
@c EN
Exports bindings of R7RS @code{(scheme repl)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme repl))}.

The only binding exported from this module is @code{interaction-environment},
which is the same as Gauche's built-in.  @xref{Eval and repl}.
@c JP
R7RS @code{(scheme repl)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、
@code{(import (scheme repl))}とすることでこれらの名前が使えるようになります。

このモジュールからエクスポートされるのは@code{interaction-environment}のみで、
これはGaucheでは組み込みになっています。@ref{Eval and repl}参照。
@c COMMON
@end deftp


@node R7RS time, R7RS write, R7RS repl, R7RS small language
@subsection @code{scheme.time} - R7RS time
@c NODE R7RS time, @code{scheme.time} - R7RS time

@deftp {Module} scheme.time
@mdindex scheme.time
@c EN
Exports bindings of R7RS @code{(scheme time)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme time))}.
@c JP
R7RS @code{(scheme time)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、
@code{(import (scheme time))}とすることでこれらの名前が使えるようになります。
@c COMMON
@end deftp

@defun current-second
[R7RS time]
@c MOD scheme.time
@c EN
Returns a real number represents the number of seconds since
the midnight of Jan. 1, 1970 TAI (which is 23:59:52, Dec 31, 1969 UTC, that
is, -8 seconds before Unix Epoch.)  Number of leap seconds were
inserted since then, and as of 2014, UTC is 35 seconds behind TAI.  That means
the number returned is 27 seconds larger than the unix time,
which is returned from @code{sys-time} or @code{sys-gettimeofday}.
@c JP
国際原子時(TAI)の1970年1月1日0時から現在までの経過秒数を実数で返します。
(これは、Unix Epochの8秒前、国際標準時(UTC)で1969年12月31日23:59:52に相当します)。
この起点以来、閏秒がしばしば挿入されてきて、2014年現在、UTCはTAIより35秒遅れています。
すなわち、この手続きが返す秒数は、@code{sys-time}や@code{sys-gettimeofday}が
返すUnix timeより27秒大きい値です。
@c COMMON

@c EN
The reason that R7RS adopts TAI is that it is monotonic and suitable
to take difference of two timepoints.  The unix time returned by
@code{sys-time} and @code{sys-gettimeofday} are defined in terms of
UTC date and time, so if the interval spans across leap seconds,
it won't reflect the actual number of seconds in the interval.
(The precise definition is given in section 4.15 of
IEEE Std 1003.1, 2013 Edition, a.k.a Single Unix Specification 4.)
@c JP
R7RSがTAIを採用したのは、それが狭義単調増加であり、二つの時刻の差をとるのに
適しているからです。@code{sys-time}や@code{sys-gettimeofday}は
UTCの日付と時間に基づいているので、二つの時刻が閏秒を挟んでいた場合、
差は経過秒数を表しません。
(Unix Timeの正確な定義については、
IEEE Std 1003.1, 2013年版の4.15節、いわゆるSingle Unix Specification 4を参照)。
@c COMMON

@c EN
However, since we don't know yet when the next leap second happen,
the current implementation just uses a fixed amount of offset
from the unix time.
@c JP
ただ、次にいつ閏秒が来るかはわからないので、現在の実装では単純に
Unix Timeから固定オフセットを引いています。
@c COMMON

@c EN
Just be aware the difference, or you'll be surprised if you
pass the return value of @code{current-second} to the UTC time
formatter such as @code{sys-strftime}, or compare it with
the file timestamps which uses the unix time.  You can convert
between TAI and UTC using srfi-19 (@pxref{SRFI-19 Date}).
@c JP
この差異があることは頭の隅に留めておいてください。
でないと、@code{current-second}の戻り値を
@code{sys-strftime}などUTC時刻のフォーマッタに渡したり、
Unix Timeで表されたタイムスタンプと比較した時にびっくりするかもしれません。
TAIとUTCはsrfi-19で変換できます (@ref{SRFI-19 Date})。
@c COMMON
@end defun

@defun current-jiffy
[R7RS time]
@c MOD scheme.time
@c EN
Returns an exact integer measuring a real (wallclock) time elapsed
since some point in the past, which does not change while a
process is running.  The time unit is a @code{jiffies-per-second}-th
second.

The absolute value of current jiffies doesn't matter, but
the difference can be used to measure the time interval.
@c JP
過去のどこかの時点を基準とする、実経過時間を正確な整数で返します。
基準時点はプロセスの起動ごとに変わるかもしれません。
1単位は1秒の@code{jiffies-per-second}分の1です。

「現在のjiffy値」の絶対値に意味はありません。差を取って経過時間を測るのに使います。
@c COMMON
@end defun

@defun jiffies-per-second
[R7RS time]
@c MOD scheme.time
@c EN
Returns a constant to tell how many time units used in @code{current-jiffy}
consists of a second.  In the current Gauche implementation,
this is 10^9 on 64bit architectures
(that is, nanosecond resolution) and 10^4 on 32bit architectures
(100 microseconds resolution).

The resolution for 32bit architectures
is unfortunately rather coarse, but if we make it finer
the current jiffy value easily becomes bignums, taking time
to allocate and operate, beating the purpose of benchmarking.
With the current choice, we have 53,867 seconds since process start
before we spill into bignum on 32bit architecture.
On 64bit architectures we have enough bits
not to worry about bignums, with nanosecond resolution.

If you want to do more finer benchmarks on 32bit machines,
you need to roll your own with @code{sys-clock-gettime-monotonic} or
@code{sys-gettimeofday}.
@c JP
@code{current-jiffy}が返す時間単位が、1秒あたりいくつあるかを示す定数を返します。
現在のGaucheの実装では、64ビットアークテクチャで10^9 (ナノ秒単位)、
32ビットアーキテクチャで10^4 (100マイクロ秒単位)です。

32ビットアーキテクチャでの分解能がかなり粗いですが、
jiffy値がbignumにオーバーフローするのを防ぐ方を優先しました。
bignumになるとアロケーションが頻繁に起きるのでベンチマークに干渉してしまいます。
現在の数値では、32ビットアーキテクチャだとプロセス開始後53,867杪でbignumになります。
64ビットアーキテクチャではナノ秒単位で測ってもbignumになることを
現実的に心配する必要はありません。

32ビットアーキテクチャでより精度の高いベンチマークを取りたい場合は、
@code{sys-clock-gettime-monotonic}や@code{sys-gettimeofday}を使ってください。
@c COMMON
@end defun


@node R7RS write, R5RS compatibility, R7RS time, R7RS small language
@subsection @code{scheme.write} - R7RS write
@c NODE R7RS write, @code{scheme.write} - R7RS write

@deftp {Module} scheme.write
@mdindex scheme.write
@c EN
Exports bindings of R7RS @code{(scheme write)} library.
From R7RS programs,
those bindings are available by @code{(import (scheme write))}.

This module provides the following bindings, all of which are
Gauche built-in (@pxref{Object output}).
@c JP
R7RS @code{(scheme write)}ライブラリの束縛をエクスポートします。
R7RSプログラムからは、
@code{(import (scheme write))}とすることでこれらの名前が使えるようになります。

このモジュールからは以下の束縛がエクスポートされます。
いずれもGauche組み込みです (@ref{Object output}参照)。
@c COMMON

@example
display write write-shared write-simple
@end example
@end deftp

@node R5RS compatibility,  , R7RS write, R7RS small language
@subsection @code{scheme.r5rs} - R5RS compatibility
@c NODE R5RS compatibility, @code{scheme.r5rs} - R5RS互換性

@deftp {Module} scheme.r5rs
@mdindex scheme.r5rs
@c EN
This module is to provide R5RS environment in R7RS programs.
The following bindings are exported.  Note that @code{lambda}
is @code{scheme#lambda}, without the support of
extended formals (@code{:optional} etc.)
@xref{Making procedures}, for the details of extended formals.
@c JP
このモジュールは、R7RSプログラム内でR5RS環境を実現します。
次に挙げる束縛がエクスポートされます。
ここでの@code{lambda}は@code{scheme#lambda}で、
Gaucheの拡張機能 (@code{:optional}など) は認識されないことに注意してください。
拡張された引数リストについては@ref{Making procedures}参照。
@c COMMON

@example
* + - / < <= = > >= abs acos and angle append apply asin assoc assq
assv atan begin boolean? caaaar caaadr caaar caadar caaddr caadr
caar cadaar cadadr cadar caddar cadddr caddr cadr
call-with-current-continuation call-with-input-file
call-with-output-file call-with-values car case cdaaar cdaadr cdaar
cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr
cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<?
char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case?
char-numeric? char-ready? char-upcase char-upper-case? char-whitespace?
char<=? char<? char=? char>=? char>? char? close-input-port
close-output-port complex? cond cons cos current-input-port
current-output-port define define-syntax delay denominator display
do dynamic-wind eof-object? eq? equal? eqv? eval even? exact->inexact
exact? exp expt floor for-each force gcd if imag-part inexact->exact
inexact? input-port? integer->char integer? interaction-environment
lambda lcm length let let* let-syntax letrec letrec-syntax list
list->string list->vector list-ref list-tail list? load log magnitude
make-polar make-rectangular make-string make-vector map max member
memq memv min modulo negative? newline not null-environment null?
number->string number? numerator odd? open-input-file open-output-file
or output-port? pair? peek-char positive? procedure? quasiquote quote
quotient rational? rationalize read read-char real-part real? remainder
reverse round scheme-report-environment set! set-car! set-cdr! sin
sqrt string string->list string->number string->symbol string-append
string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>?
string-copy string-fill! string-length string-ref string-set!
string<=? string<? string=? string>=? string>? string? substring
symbol->string symbol? tan truncate values vector vector->list
vector-fill! vector-length vector-ref vector-set! vector?
with-input-from-file with-output-to-file write write-char zero?
@end example
@end deftp

@node R7RS large,  , R7RS small language, Library modules - R7RS standard libraries
@section R7RS large
@c NODE R7RS large

@c EN
R7RS large is still under development, and we're gradually
adding support of the libraries that has been passed.
@c JP
R7RS largeはまだ策定途上ですが、既に決定したライブラリについては
徐々にGaucheに追加してゆきます。
@c COMMON

@c EN
Currently R7RS-large has two editions (Red and Tangerine),
and Gauche supports them.
@c JP
現在、R7RS-largeには2つのエディション (RedとTangerine) が
制定されており、Gaucheでもこれらをサポートしています。
@c COMMON

@menu
* R7RS lists::                  @code{scheme.list}
* R7RS vectors::                @code{scheme.vector}
* R7RS uniform vectors::        @code{scheme.vector.@@}
* R7RS sort::                   @code{scheme.sort}
* R7RS sets::                   @code{scheme.set}
* R7RS character sets::         @code{scheme.charset}
* R7RS hash tables::            @code{scheme.hash-table}
* R7RS immutable lists::        @code{scheme.ilist}
* R7RS random-access lists::    @code{scheme.rlist}
* R7RS immutable deques::       @code{scheme.ideque}
* R7RS immutable texts::        @code{scheme.text}
* R7RS generators::             @code{scheme.generator}
* R7RS lazy sequences::         @code{scheme.lseq}
* R7RS stream::                 @code{scheme.stream}
* R7RS boxes::                  @code{scheme.box}
* R7RS list queues::            @code{scheme.list-queue}
* R7RS ephemerons::             @code{scheme.ephemeron}
* R7RS comparators::            @code{scheme.comparator}
* R7RS regular expressions::    @code{scheme.regex}
* R7RS mappings::               @code{scheme.mapping}
* R7RS integer division::       @code{scheme.division}
* R7RS bitwise operations::     @code{scheme.bitwise}
* R7RS fixnum::                 @code{scheme.fixnum}
* R7RS flonum::                 @code{scheme.flonum}
* R7RS bytevectors::            @code{scheme.bytevector}
* R7RS combinator formatting::  @code{scheme.show}
@end menu

@node R7RS lists, R7RS vectors, R7RS large, R7RS large
@subsection @code{scheme.list} - R7RS lists
@c NODE R7RSリスト, @code{scheme.list} - R7RSリスト

@deftp {Module} scheme.list
@mdindex scheme.list
@c EN
This module is a rich collection of list manipulation procedures,
and same as @code{srfi-1}.

Note that Gauche supports quite a few @code{scheme.list}
procedures as built-in.
The following procedures can be used
without loading @code{scheme.list} module.  For the manual entries of
these procedures, @ref{Pairs and lists}.
@c JP
このモジュールは、豊富なリスト操作手続きのコレクションです (srfi-1と同じです)。

Gaucheは@code{scheme.list}の手続きの多くを組み込みで提供しています。
以下に挙げる手続きは@code{scheme.list}モジュールをロードしなくても使えます。
これらの手続きの説明は、@ref{Pairs and lists}を参照してください。
@c COMMON

@example
null-list? cons* last member
take drop take-right drop-right take! drop-right!
delete delete! delete-duplicates delete-duplicates!
assoc alist-copy alist-delete alist-delete!
any every filter filter! fold fold-right find find-tail
split-at split-at! iota
@end example
@end deftp

@subsubheading List constructors

@defun xcons cd ca
[R7RS list]
@c MOD scheme.list
@c EN
Equivalent to @code{(cons ca cd)}.  Useful to pass to
higher-order procedures.
@c JP
@code{(cons ca cd)} と同等です。高階手続きへ渡すのに便利です。
@c COMMON
@end defun

@defun list-tabulate n init-proc
[R7RS list]
@c MOD scheme.list
@c EN
Constructs an @var{n}-element list, in which
each element is generated by @code{(@var{init-proc} @i{i})}.
@c JP
@var{n}個の要素をもつリストを構築し、それぞれの要素を
@code{(@var{init-proc} @i{i})} で生成します。
@c COMMON
@example
(list-tabulate 4 values) @result{} (0 1 2 3)
@end example
@end defun

@defun circular-list elt1 elt2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Constructs a circular list of the elements.
@c JP
指定した要素をもつ循環リストを構築します。
@c COMMON
@example
(circular-list 'z 'q) @result{} (z q z q z q @dots{})
@end example
@end defun

@subsubheading List predicates

@defun not-pair? x
[R7RS list]
@c MOD scheme.list
@c EN
Same as @code{(lambda (x) (not (pair? x)))}.

SRFI-1 says: Provided as a procedure as it can be useful as
the termination condition for list-processing procedures that wish to
handle all finite lists, both proper and dotted.
@c JP
@code{(lambda (x) (not (pair? x)))}と同じです。

SRFI-1 では、「真性リストおよびドットリストの両方で、すべての有限リストを
扱う手続き用の終端条件として便利なように用意した」とあります。
@c COMMON
@end defun

@defun list= elt= list @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Determines list equality by comparing every n-th element
of given lists by the procedure @var{elt=}.

It is an error to apply @code{list=} to anything except proper lists.

The equality procedure must be consistent with @code{eq?}, i.e.
@c JP
@var{elt=} を用いて、n番目の要素をそれぞれ比較することで、
与えられたリストの同値性を決定します。

@code{list=} を真性リスト以外に適用するとエラーになります。

同値性判定の手続きは @code{eq?} と整合性がなければなりません。すなわち
@c COMMON

@example
(eq? x y) @result{} (elt= x y).
@end example
@end defun

@subsubheading List selectors

@defun  first pair
@defunx second pair
@defunx third pair
@defunx fourth pair
@defunx fifth pair
@defunx sixth pair
@defunx seventh pair
@defunx eighth pair
@defunx ninth pair
@defunx tenth pair
[R7RS list]
@c MOD scheme.list
@c EN
Returns n-th element of the (maybe improper) list.
@c JP
リスト(非真性でも可)のn番目の要素を返します。
@c COMMON
@end defun

@defun car+cdr pair
[R7RS list]
@c MOD scheme.list
@c EN
Returns two values, @code{(car pair)} and @code{(cdr pair)}.
@c JP
@code{(car pair)} および @code{(cdr pair)} の二つの値を返します。
@c COMMON
@end defun

@subsubheading List miscellaneous routines

@defun zip clist1 clist2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Equivalent to @code{(map list clist1 clist2 @dots{})}.
If @code{zip} is passed @var{n} lists, it returns a list as long as
the shortest of these lists, each element of which is an @var{n}-element list
comprised of the corresponding elements from the parameter lists.
@c JP
@code{(map list clist1 clist2 @dots{})} と同等です。
@var{n} 本のリストが @code{zip} に渡された場合には、そのなかで一番短いものと
同じ長さのリストを返します。返されたリストは、要素が @var{n} 要素のリストで、
そのそれぞれが、引数として渡ってリストの対応する要素になっています。
@c COMMON

@example
(zip '(one two three)
     '(1 2 3)
     '(odd even odd even odd even odd even))
     @result{} ((one 1 odd) (two 2 even) (three 3 odd))

(zip '(1 2 3)) @result{} ((1) (2) (3))
@end example

@c EN
At least one of the argument lists must be finite:
@c JP
引数のリストのうち、少くともひとつは有限のリストでなければなりません。
@c COMMON

@example
(zip '(3 1 4 1) (circular-list #f #t))
     @result{} ((3 #f) (1 #t) (4 #f) (1 #t))
@end example
@end defun

@defun unzip1 list
@defunx unzip2 list
@defunx unzip3 list
@defunx unzip4 list
@defunx unzip5 list
[R7RS list]
@c MOD scheme.list
@c EN
@code{unzip1} takes a list of lists, where every list must
contain at least one element, and returns a list containing the
initial element of each such list.
@code{unzip2} takes a list of lists, where every list
must contain at least two elements, and returns two values:
a list of the first elements, and a list of the second
elements. @code{unzip3} does the same for the first
three elements of the lists, and so on.
@c JP
@code{unzip1} はリストのリストを引数としてとります。それぞれの
リストは少くとも一つの要素を含むものでなくてはなりません。結果として
それぞれのリストの最初の要素のリストを返します。
@code{unzip2} はリストのリストを引数としてとります。それぞれのリストは
少くとも二つの要素を含むものでなくてはなりません。結果として二つの値を
返します。最初の要素のリストと二番目の要素のリストです。@code{unzip3} は
3番目までの要素について同様です。以下も同様です。
@c COMMON

@example
(unzip2 '((1 one) (2 two) (3 three))) @result{}
   (1 2 3) @r{and}
   (one two three)
@end example
@end defun

@subsubheading List fold, unfold & map

@defun pair-fold kons knil clist1 clist2 @dots{}
@defunx pair-fold-right kons knil clist1 clist2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Like @code{fold} and @code{fold-right}, but the procedure @var{kons}
gets each @code{cdr} of the given @var{clist}s, instead of @code{car}.
@c JP
@code{fold} および @code{fold-right} と同様ですが、@var{kons} 手続き
は与えられた @var{clist} の @code{car} ではなく、@code{cdr} をとります。
@c COMMON

@example
(pair-fold cons '() '(a b c d e))
  @result{} ((e) (d e) (c d e) (b c d e) (a b c d e))

(pair-fold-right cons '() '(a b c d e))
  @result{} ((a b c d e) (b c d e) (c d e) (d e) (e))
@end example
@end defun

@defun unfold p f g seed :optional tail-gen
[R7RS list]
@c MOD scheme.list
@c EN
Fundamental recursive list constructor.
Defined by the following recursion.
@c JP
基本リスト再帰構築子です。
以下のように再帰的に定義されています。
@c COMMON

@example
(unfold p f g seed tail-gen) @equiv{}
   (if (p seed)
       (tail-gen seed)
       (cons (f seed)
             (unfold p f g (g seed))))
@end example

@c EN
That is, @var{p} determines where to stop, @var{g} is used to generate
successive seed value from the current seed value, and @var{f} is used
to map each seed value to a list element.
@c JP
ここでは、@var{p} は終了位置の判定、@var{g} は現在の「種」から次の「種」
を生成するのに用い、@var{f} はそれぞれの「種」をリストの要素に変換する
のに用いられます。
@c COMMON

@example
(unfold (pa$ = 53) integer->char (pa$ + 1) 48)
  @result{} (#\0 #\1 #\2 #\3 #\4)
@end example
@end defun

@defun unfold-right p f g seed :optional tail
[R7RS list]
@c MOD scheme.list
@c EN
Fundamental iterative list constructor.
Defined by the following recursion.
@c JP
基本リスト反復構築子です。
以下のように再帰的に定義されています。
@c COMMON

@example
(unfold-right p f g seed tail) @equiv{}
  (let lp ((seed seed) (lis tail))
    (if (p seed)
        lis
        (lp (g seed) (cons (f seed) lis))))
@end example

@example
(unfold-right (pa$ = 53) integer->char (pa$ + 1) 48)
 @result{} (#\4 #\3 #\2 #\1 #\0)
@end example
@end defun

@defun map! f clist1 clist2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
The procedure @var{f} is applied to each element of @var{clist1} and
corresponding elements of @var{clist2}s, and the result is collected
to a list.  Cells in @var{clist1} is reused to construct the result list.
@c JP
手続き @var{f} は @var{clist1} の各要素と @var{clist2} の対応する要素
に適用され、結果はひとつのリストになります。@var{clist1} のセルは
結果のリストを構築するのに再利用されます。
@c COMMON
@end defun

@defun map-in-order f clist1 clist2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
A variant of @code{map}, but it guarantees to apply @var{f}
on each elements of arguments in a left-to-right order.
Since Gauche's @code{map} implementation follows the same order,
this function is just a synonym of @code{map}.
@c JP
@code{map} の変形バージョンですが、@var{f} の適用順序が、引数として
与えられたリストの要素の左から右への順であることを保証します。
Gauche では @code{map} の実装はこの順になっているので、@code{map} と
同意です。
@c COMMON
@end defun

@defun pair-for-each f clist1 clist2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Like @code{for-each}, but the procedure @var{f} is applied on
@var{clist}s themselves first, then each @code{cdr}s of them, and so on.
@c JP
@code{for-each} と似ていますが、手続き @var{f} はまず @var{clist}自体に
適用され、次ににそれらの@code{cdr} に適用され、となります。
@c COMMON

@example
(pair-for-each write '(a b c))
 @result{} @r{prints} (a b c)(b c)(c)
@end example
@end defun

@subsubheading List partitioning

@defun partition pred list
@defunx partition! pred list
[R7RS list]
@c MOD scheme.list
@c EN
@code{filter} and @code{remove} simultaneously, i.e.
returns two lists, the first is the result of filtering elements of
@var{list} by @var{pred}, and the second is the result of
removing elements of @var{list} by @var{pred}.
@c JP
@code{filter} と @code{remove} を同時に行い、
2つのリストを返します。一つ目は @var{pred} により @var{list} の要素をフィルタリング
した結果で、二つ目は @var{pred} により @var{list} の要素を削除した結果です。
@c COMMON
@example
(partition odd? '(3 1 4 5 9 2 6))
  @result{} (3 1 5 9) (4 2 6)
@end example
@c EN
@code{partition!} is the linear-update variant.  It may destructively
modifies @var{list} to produce the result.
@c JP
@code{partition!} はその場で更新されるバージョンです。結果を生成するために
@var{list} を破壊的に更新するかもしれません。
@c COMMON
@end defun

@subsubheading List searching

@defun take-while pred clist
@defunx take-while! pred list
[R7RS list]
@c MOD scheme.list
@c EN
Returns the longest initial prefix of @var{clist} whose elements all
satisfy @var{pred}.
@c JP
@var{clist} の最初から、@var{pred} を満足する限りの最長部分要素を返します。
@c COMMON
@end defun

@defun drop-while pred clist
[R7RS list]
@c MOD scheme.list
@c EN
Drops the longest initial prefix of @var{clist} whose elements all
satisfy @var{pred}, and returns the rest.
@c JP
@var{clist} の最初から、@var{pred} を満足する限りの最長部分要素を削除し、
残りを返します。
@c COMMON
@end defun

@defun span pred clist
@defunx span! pred list
@defunx break pred clist
@defunx break! pred list
[R7RS list]
@c MOD scheme.list
@c EN
@code{span} is equivalent to
@code{(values (take-while pred clist) (drop-while pred clist))}.
@code{break} inverts the sense of @var{pred}.
@c JP
@code{span} は @code{(values (take-while pred clist) (drop-while pred clist))}
と等価です。@code{break} は @var{pred} の意味を反転します。
@c COMMON
@end defun

@defun list-index pred clist1 clist2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns the index of the leftmost element that satisfies @var{pred}.
If no element satisfies @var{pred}, @code{#f} is returned.
@c JP
@var{pred} を満足する最も左の要素のインデックスを返します。
@var{pred}を満たす要素が無い場合は@code{#f}を返します。
@c COMMON
@end defun

@subsubheading Association lists

@defun alist-cons key datum alist
[R7RS list]
@c MOD scheme.list
@c EN
Returns @code{(cons (cons @var{key} @var{datum}) @var{alist})}.
This is an alias of the Gauche builtin procedure @code{acons}.
@c JP
@code{(cons (cons @var{key} @var{datum}) @var{alist})} を返します。
これは、Gauche の組み込み手続き @code{acons} の別名です。
@c COMMON
@end defun

@subsubheading Lists as sets

@c EN
These procedures use a list as a set, that is,
the elements in a list matter, but their order doesn't.

All procedures in this category takes a comparison procedure
@var{elt=}, as the first argument, which is used to determine
two elements in the given sets are the same.

Since lists require linear time to search, those procedures aren't
suitable to deal with large sets.  @xref{R7RS sets}, if you
know your sets will contain more than a dozen items or so.

See also @ref{Combination library}, which
concerns combinations of elements in the set.
@c JP
これらの手続きはリストを集合としてあつかいます。すなわち、どのような
要素があるかは重要ですが、その順序は重要ではありません。

この範疇にあるすべての手続きは、比較手続き @var{elt=} を最初の引数として
とります。この比較手続きは与えられた二つの集合の要素が等しいかどうかを
判定します。

リストは検索に線形時間を必要とするため、ここに挙げた手続きは
大きな集合を扱うには向いていません。もし対象となる集合が
二桁以上の要素を持つことが分かっているなら、@ref{R7RS sets}を
参照してください。

集合の要素の組み合せについては @ref{Combination library}
も参照してください。
@c COMMON

@defun lset<= elt= list1 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns @code{#t} iff all elements in @var{list1} are also included
in @var{list2}, and so on.
If no lists are given, or a single list is given,
@code{#t} is returned.
@c JP
@var{list1} のすべての要素が @var{list2} (以降の集合)に含まれている
ときに限り @code{#t} を返します。リストが与えられなかった場合
および一つだけしか与えられなかった場合には、@code{#t} を返します。
@c COMMON
@end defun

@defun lset= elt= list1 list2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns @code{#t} if all elements in @var{list1} are in @var{list2},
and all elements in @var{list2} are in @var{list1}, and so on.
@c JP
@var{list1} のすべての要素が @var{list2} に含まれており、かつ、
@var{list2} のすべての要素が @var{list1} に含まれていれば、@code{#t}
を返します。
@c COMMON

@example
(lset= eq? '(b e a) '(a e b) '(e e b a)) @result{} #t
@end example
@end defun

@defun lset-adjoin elt= list elt @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Adds @var{elt} @dots{} to the set @var{list}, if each one is not
already a member of @var{list}.  (The order doesn't matter).
@c JP
@var{elt} @dots{} を集合 @var{list} にまだなければ、追加します。
(順序はとくに決っていません。)
@c COMMON

@example
(lset-adjoin eq? '(a b c) 'a 'e) @result{} '(e a b c)
@end example
@end defun

@defun lset-union elt= list1 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns the union of the sets @var{list1} @dots{}.
@c JP
@var{list1} @dots{} の和集合を返します。
@c COMMON
@end defun

@defun lset-intersection elt= list1 list2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns a set of elements that are in every @var{list}s.
@c JP
すべての @var{list} に含まれる要素の集合を返します。
@c COMMON
@end defun

@defun lset-difference elt= list1 list2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns a set of elements that are in @var{list1} but not
in @var{list2}.  In n-ary case, binary difference operation is
simply folded.
@c JP
@var{list1} には含まれていて、@var{list2} には含まれていない要素の集合を
返します。引数が n 個与えられた場合には、差分をとる二項演算が
畳み込まれます。
@c COMMON
@end defun

@defun lset-xor elt= list1 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns the exclusive-or of given sets; that is, the returned
set consists of the elements that are in either @var{list1} or @var{list2},
but not in both.   In n-ary case, binary xor operation is simply folded.
@c JP
与えられた集合の排他的論理和を返します。すなわち、@var{list1} および
@var{list2} のどちらか一方にのみ属する要素からなる集合を返します。
引数が n 個の場合には、xor の二項演算が畳み込まれます。
@c COMMON
@end defun

@defun lset-diff+intersection elt= list1 list2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Returns two sets, a difference and an intersection of given sets.
@c JP
与えられた集合の差集合と積集合のふたつの集合を返します。
@c COMMON
@end defun

@defun lset-union! elt= list @dots{}
@defunx lset-intersection! elt= list1 list2 @dots{}
@defunx lset-difference! elt= list1 list2 @dots{}
@defunx lset-xor! elt= list1 @dots{}
@defunx lset-diff+intersection! elt= list1 list2 @dots{}
[R7RS list]
@c MOD scheme.list
@c EN
Linear update variant of the corresponding procedures.
The cells in the first list argument may be reused to construct the result.
@c JP
それぞれ対応する手続きのその場で更新するバージョンです。
最初の引数のリストのセルが結果を構築するのに再利用されるかもしれません。
@c COMMON
@end defun

@node R7RS vectors, R7RS uniform vectors, R7RS lists, R7RS large
@subsection @code{scheme.vector} - R7RS vectors
@c NODE R7RSベクタ, @code{scheme.vector} - R7RSベクタ

@deftp {Module} scheme.vector
@mdindex scheme.vector
@c EN
This module adds rich set of vector operations to the built-in / R7RS
vector procedures.
@c JP
このモジュールは豊富なベクタ操作を提供します。
@c COMMON

@c EN
The following procedures are built-in.
@xref{Vectors}, for the description.  We only explain
the procedures that are not built-in.
@c JP
以下の手続きはGaucheでは組み込みになっています。説明は@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 vector->string       string->vector
vector-map           vector-map!          vector-for-each
@end example

@c EN
This module is @code{srfi-133}, which supersedes @code{srfi-43}
(@pxref{Vector library (Legacy)}).
Note that the interface of following procedures in @code{srfi-43}
are changed for the consistency:
@c JP
このモジュールは@code{srfi-133}として制定され、
@code{srfi-43}(@ref{Vector library (Legacy)})を置き換えるものです。
@code{srfi-43}の手続きのうち、以下のものは一貫性からインタフェースが
変更されていることに注意してください。
@c COMMON

@example
vector-map           vector-map!          vector-for-each
vector-fold          vector-fold-right    vector-count
@end example

@c EN
Some of the functionalities
of @code{srfi-43} version is supported by built-in procedures
(e.g. Built-in @code{vector-map-with-index} is the same as
@code{srfi-43}'s @code{vector-map}).  So there's little point
for new code to use @code{srfi-43}.
@c JP
@code{srfi-43}から削られた機能の一部は、
Gaucheの組み込み手続きでサポートされています
(例えば@code{srfi-43}の@code{vector-map}は組み込みの@code{vector-map-with-index}と
同じです)。新しいコードで@code{srfi-43}を使う必要はほとんどないでしょう。
@c COMMON
@end deftp

@c EN
@subheading Vector constructors
@c JP
@subheading ベクタ構成子
@c COMMON

@defun vector-unfold f length seed @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Creates a vector of length @var{length}, filling elements
left to right by calling @var{f} repeatedly.

The procedure @var{f} must take as many arguments as
one plus number of seed values, and must return the same number
of values.  The first argument is the index.  The first return
value is used for the element of the result vector, and the
rest of return values are passed to the next call of @var{f}.
@c JP
長さ@var{length}のベクタを作って返します。要素は左から右に、
@var{f}を繰り返し呼ぶことで計算されます。

手続き@var{f}は、@var{seed}の数よりひとつ多い引数を取り、同数の値を返さなければなりません。
引数の最初に渡されるのはインデックスです。戻り値の最初の値がそのインデックスの要素の初期値に
使われ、残りの戻り値が次のシード値となります。
@c COMMON

@example
(vector-unfold (^[i] (* i i)) 5)
 @result{} #(0 1 4 9 16)

(vector-unfold (^[i x] (values (cons i x) (* x 2))) 8 1)
 @result{} #((0 . 1) (1 . 2) (2 . 4) (3 . 8)
    (4 . 16) (5 . 32) (6 . 64) (7 . 128))
@end example

@c EN
Note: This protocol is different from the list @code{unfold}
and most of other @code{*-unfold} constructors (@pxref{R7RS lists}).  
For fixed-length strcuctures like vectors,
it makes more sense to know the final length beforehand, rather than
checking the termination condition for each iteration.
@c JP
註: このプロトコルは、リストの@code{unfold}コンストラクタや、それに倣った
多くの@code{*-unfold}コンストラクタと異なることに注意してください。
ベクタのような固定長構造体では、終端条件を繰り返しの度に検査するより、
最初から長さが分かっている方が意味があります。
@c COMMON
@end defun

@defun vector-unfold-right f length seed @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Creates a vector of length @var{length}, filling elements
right to left by calling @var{f} repeatedly.
@c JP
長さ@var{length}のベクタを作って返します。要素は右から左に、
@var{f}を繰り返し呼ぶことで計算されます。
@c COMMON

@c EN
The procedure @var{f} must take as many arguments as
one plus number of seed values, and must return the same number
of values.  The first argument is the index.  The first return
value is used for the element of the result vector, and the
rest of return values are passed to the next call of @var{f}.
@c JP
手続き@var{f}は、@var{seed}の数よりひとつ多い引数を取り、同数の値を返さなければなりません。
引数の最初に渡されるのはインデックスです。戻り値の最初の値がそのインデックスの要素の初期値に
使われ、残りの戻り値が次のシード値となります。
@c COMMON

@example
(vector-unfold-right (^[i] (* i i)) 5)
 @result{} #(0 1 4 9 16)

(vector-unfold-right (^[i x] (values (cons i x) (* x 2))) 8 1)
 @result{} #((0 . 128) (1 . 64) (2 . 32) (3 . 16)
    (4 . 8) (5 . 4) (6 . 2) (7 . 1))
@end example
@end defun

@defun vector-reverse-copy vec :optional start end
[R7RS vector]
@c MOD scheme.vector
@c EN
Copies the vector @var{vec} with reversing its elements.
Optional @var{start} and @var{end} arguments can limit
the range of the input.
@c JP
ベクタ@var{vec}を要素を逆順にしてコピーします。
省略可能引数@var{start}と@var{end}は元のベクタから取り出す範囲を限定します。
@c COMMON

@example
(vector-reverse-copy '#(a b c d e) 1 4)
 @result{} #(d c b)
@end example
@end defun

@defun vector-concatenate list-of-vectors
[R7RS vector]
@c MOD scheme.vector
@c EN
Same as @code{(apply vector-append list-of-vectors)}.
@c JP
@code{(apply vector-append list-of-vectors)}と同じです。
@c COMMON
@end defun

@defun vector-append-subvectors spec @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
The number of arguments must be multiple of 3.  The argument list
must be in the following format, where each @var{vecN} is
a vector, and @code{startN} and @code{endN} are nonnegative exact integers:
@c JP
引数の数は3の倍数でなければなりません。
引数リストは次の形式をとります。ここで、@var{vecN}はベクタ、
@var{startN}と@var{endN}は非負の正確な整数です。
@c COMMON

@example
vec1 start1 end1 vec2 start2 end2 @dots{}
@end example

@c EN
This procedure creates a new vector by concatenating subvectors
specified by each triplet.  That is, it works as if it's the following
code, except it avoids copying each subvector:
@c JP
この手続きは、それぞれの3つ組で指定される部分ベクタをつなぎ合わせたベクタを
作って返します。つまり、以下のコードと同様の動作をしますが、
各部分ベクタのコピーは避けられます。
@c COMMON

@example
(vector-append (vector-copy vec1 start1 end1)
               (vector-copy vec2 start2 end2)
               @dots{})
@end example

@c EN
Here's an example:
@c JP
例を示します:
@c COMMON

@example
(vector-append-subvectors '#(a b c d e) 0 3
                          '#(f g h i j) 2 5)
  @result{} #(a b c h i j)
@end example
@end defun


@c EN
@subheading Vector predicates
@c JP
@subheading ベクタ上の述語
@c COMMON

@defun vector-empty? vec
[R7RS vector]
@c MOD scheme.vector
@c EN
Returns @code{#t} if @var{vec}'s length is zero, and
@code{#f} if @var{vec}'s length is more than zero.
Signals an error if @var{vec} is not a vector.
@c JP
ベクター@var{vec}の長さが0なら@code{#t}を、1以上なら@code{#f}を返します。
@var{vec}がベクタでなければエラーが投げられます。
@c COMMON
@end defun

@defun vector= elt= vec @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Compares @var{vec}s element-wise, using given predicate @var{elt=}.
Returns @code{#t} iff lengths of all the vectors are the same,
and every corresponding elements are equal by @var{elt=}.

@var{Elt=} is always called with two arguments and must
return @code{#t} iff two are the same.

When zero or one vector is passed, @var{elt=} won't be called
and @var{vector=} always returns @code{#t}.
@c JP
@var{vec} @dots{}を要素ごとに比較してゆきます。要素間の比較には@var{elt=}が使われます。
全てのベクタ引数が同じ長さで、対応する要素が@var{elt=}によって等しかった場合に、@code{#t}
が返されます。

@var{elt=}は常に二つの引数を取り、
等しければ@code{#t}を、そうでなければ@code{#f}を返します。

ゼロ個か1個のベクタが渡された場合は、@var{elt=}は全く呼ばれず、
@code{vector=}は常に@code{#t}を返します。
@c COMMON
@end defun

@c EN
@subheading Vector iteration
@c JP
@subheading ベクタ上の繰り返し
@c COMMON

@defun vector-fold kons knil vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
@var{Kons} is a procedure that takes @var{n}+1 arguments, where
@var{n} is the number of given vectors.  For each element of the
given vectors, @var{kons} is called as
@code{(@var{kons} @var{seed} @var{e_1i} @var{e_2i} @dots{})},
where and @var{e_ni} is the @var{i}-th element
of the vector @var{n}.  If the lengths of the vectors differ,
iteration stops when the shortest vector is exhausted.
@c JP
@var{kons}は与えられたベクタ引数@var{vec1} @var{vec2} @dots{}
の数よりひとつ多い引数を取る手続きです。
各ベクタの@var{i}番目の要素@var{e_1i} @var{e_2i} @dots{})に
対して、@var{kons}が
@code{(@var{kons} @var{seed} @var{e_1i} @var{e_2i} @dots{})}
のように順次呼ばれます。ベクタの長さが異なっていた場合、最も短いベクタが尽きたところで
繰り返しは停止します。
@c COMMON

@c EN
The initial value of @var{seed} is @var{knil}, and the return value
from @var{kons} is used as the next seed value.  The last return value
of @var{kons} is returned from @code{vector-fold}.
@c JP
@var{seed}の初期値は@var{knil}で、@var{kons}の戻り値が次の@var{seed}として
使われます。最後の@var{kons}の戻り値が@code{vector-fold}の戻り値となります。
@c COMMON

@c EN
The iteration is strictly left to right.
@c JP
繰り返しはベクタの左から右へと進みます。
@c COMMON

@c EN
Note that the seed value precedes elements, which is opposite to
@code{fold} (@pxref{Mapping over collection}).  It's an unfortunate
historical glitch; @code{vector-fold-left} would be more consistent
name.
@c JP
@var{seed}引数が要素の前に来ることに注意してください。これは
@code{fold} (@ref{Mapping over collection}参照)とは逆です。
歴史的に生じた不幸なすれちがいです。
@code{vector-fold-left}であれば一貫性があったでしょう。
@c COMMON

@example
(vector-fold (^[a b] (cons b a)) '() '#(a b c d))
  @result{} (d c b a)
@end example
@end defun

@defun vector-fold-right kons knil vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Like @code{vector-fold}, but elements in the @var{vec1} @var{vec2} @dots{}
are visited from right to left.

If the lengths of the vectors differ, this procedure only looks up to
the number of elements of the shortest vector and ignores any excessive
elements.  See the second example below.
@c JP
@code{vector-fold}と似ていますが、@var{vec1} @var{vec2} @dots{}の各要素は
右から左へと読まれます。

ベクタの長さが異なる場合は、最も短いベクタの要素数までを見て、残りは無視します。
下の2番目の例を見てください。
@c COMMON

@c EN
Unlike @code{fold-right} (@pxref{Mapping over sequences}),
the procedure @var{kons} takes the seed value in the
first argument.
@c JP
@code{fold-right} (@ref{Mapping over sequences}参照)とは異なり、
@var{kons}はシード値を最初の引数として受け取ります。
@c COMMON

@example
(vector-fold-right (^[a b] (cons b a)) '() '#(a b c d))
  @result{} (a b c d)

(vector-fold-right (^[s x y] (cons (list x y) s)) '()
                   '#(a b c) '#(1 2 3 4))
  @result{} ((a 1) (b 2) (c 3))                   
@end example
@end defun

@defun vector-count pred vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
Applies @var{pred} on each elements in argument vectors (if N vectors
are given, @var{pred} takes N arguments, the first being
@var{i}-th element of @var{vec1}, the second being @var{i}-th element
of @var{vec2}, etc.)  Then returns the number of times
@var{pred} returned true value.   The order @var{pred} applied
to each element is unspecified.

@example
(vector-count odd? '#(0 1 2 3 4)
  @result{} 2

(vector-count < '#(7 3 9 1 5) '#(6 8 2 3 8 8))
  @result{} 3
@end example
@end defun

@defun vector-cumulate f seed vec
[R7RS vector]
@c MOD scheme.vector
Returns a fresh vector with the same size of @var{vec}, with
the elements calculated as follows:

The first element of result vector is a result of procedure @var{f}
called with @var{seed} and the first element of @var{vec}.

The @var{i}-th element of result vector is a result of procedure @var{f}
called with @var{i-1}-th element of result vector and @var{i}-th element
of @var{vec}.

@example
(vector-cumulate string-append "z" '#("a" "b" "c"))
  @result{} #("za" "zab" "zabc")
@end example
@end defun


@c EN
@subheading Vector searching
@c JP
@subheading ベクタ上の検索
@c COMMON

@defun vector-index pred vec1 vec2 @dots{}
@defunx vector-index-right pred vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
Returns the index of the first or the last elements in @var{vec1}
@var{vec2} @dots{} that satisfy @var{pred}, respectively.
Returns @code{#f} if no elements satisfy @var{pred}.
In @code{vector-index}, comparison ends at the end of the shortest vector.
For @code{vector-index-right}, all the vectors must have the same length.
@end defun

@defun vector-skip pred vec1 vec2 @dots{}
@defunx vector-skip-right pred vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
Like @code{vector-index} and @code{vector-index-right}, except that
the result of @var{pred} is negated.  That is, returns the index
of the first or the last elements that don't satisfy @var{pred}.
@end defun

@defun vector-binary-search vec value cmp :optional start end
[R7RS+]
@c MOD scheme.vector
@c EN
Look for @var{value} in a sorted vector @var{vec}, and returns its
index if it is found, or @code{#f} if it is not found.

Comparison of @var{value} and an element in @var{vec} is
done by a procedure @var{cmp}, which takes two arguments,
and should return a negative integer if the first argument is less than the
second, 0 if they are the same, and a positive integer if the first
is greater than the second.

Elements in @var{vec} must be ordered from smaller to greater
w.r.t. @var{cmp}.  Using that fact, this procedure performs
binary search instead of linear search.

The optional arguments @var{start} and @var{end} are an
extension to SRFI-133, and can be used to limit the range of the
search in @var{start}-th element (inclusive) to
@var{end}-th element (exclusive).
@c JP
ソートされたベクタ@var{vec}中から値@var{value}を探し、
見つかればそのインデックスを、見つからなければ@code{#f}を返します。

@var{vec}の要素と@var{value}の比較は手続き@var{cmp}で行われます。
@var{cmp}は二つの引数を取り、最初の引数の方が小さければ負の整数を、
等しければ0を、最初の引数の方が大きければ正の整数を買えす手続きです。

@var{vec}の要素は@var{cmp}による比較に従い小さい方から順にソート済みで
なければなりません。この手続きはその仮定のもとに、二分探索を行います。

省略可能な@var{start}と@var{end}引数は、Gauche独自の拡張です。指定された場合、
@var{start}番目の要素(含む)から@var{end}番目の要素(含まない)までが探索の対象となります。
@c COMMON
@end defun

@defun vector-any pred vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Applies @var{pred} on each corresponding elements
of @var{vec1} @var{vec2} @dots{} left to right, and
as soon as @var{pred} returns non-@code{#f} value,
the procedure stops iteration and returns the value.

If no elements that satisfy @var{pred} are found, it returns @code{#f}.

Vectors can have different lengths.  Iteration stops at the end
of the shortest.
@c JP
@var{vec1} @var{vec2} @dots{}の各ベクタの先頭から順に、
ひとつづつ対応する要素を取って、それに@var{pred}を適用してゆきます。
@var{pred}が真の値を返したら、直ちにその値を返します。

@var{pred}を満たす要素が見つからなければ、@code{#f}が返されます。

ベクタの長さは異なっていても構いません。最も短いベクタの要素を使い切ったところで
探索は打ちきられます。
@c COMMON
@end defun

@defun vector-every pred vec1 vec2 @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Applies @var{pred} on each corresponding elements
of @var{vec1} @var{vec2} @dots{} left to right.
If all the elements (when the lengths of vectors differ, the
first N elements where N is the length of the shortest) satisfy
@var{pred}, returns the last result of @var{pred}.
If any of the elements don't satisfy @var{pred},
it returns @code{#f} immediately without looking further.
@c JP
@var{vec1} @var{vec2} @dots{}の各ベクタの先頭から順に、
ひとつづつ対応する要素を取って、それに@var{pred}を適用します。
全ての要素が@var{pred}を満たした場合(ベクタの長さが異なる場合は、
最も短いベクタを使い切った時点)で、最後の@var{pred}の結果を返します。
途中で@var{pred}が@code{#f}を返した場合は、その先は見ずに直ちに@code{#f}を返します。
@c COMMON

@example
(vector-every < '#(1 2 3 4 5) '#(2 3 4 4 5)
  @result{} #f

(vector-every (^[x y] (and (real? x) (real? y) (- x y)))
              '#(1 2 3)
              '#(2 4 6))
  @result{} -3
@end example
@end defun

@defun vector-partition pred vec
[R7RS vector]
@c MOD scheme.vector
@c EN
Allocates a fresh vector of the same size as @var{vec},
then fill it with elements in @var{vec} that satisfy @var{pred},
followed by elements that don't satisfy @var{pred}.

Returns two values, the newly created vector and
an exact integer of the index of the first element that doesn't satisfy
@var{pred} in the returned vector.
@c JP
@var{vec}と同じ大きさのベクタを新たにアロケートし、
まず@var{vec}中の@var{pred}を満たす要素を順に詰めてゆき、
その後を@var{pred}を満たさない要素で埋めます。

新たに作られたベクタと、その中で@var{pred}を満たさない最初の要素を指す
インデックスの二つの値を返します。
@c COMMON

@example
(vector-partition odd? '#(1 2 3 4 5 6 7 8))
  @result{} #(1 3 5 7 2 4 6 8) @r{and} 4
@end example
@end defun

@c EN
@subheading Vector mutators
@c JP
@subheading ベクタの変更子
@c COMMON

@defun vector-swap! vec i j
[R7RS vector]
@c MOD scheme.vector
@c EN
Swaps vector @var{vec}'s @var{i}-th and @var{j}-th elements.
Returns unspecified value.
@c JP
@var{vec}の@var{i}番目の要素と@var{j}番目の要素を交換します。
戻り値はunspecifiedです。
@c COMMON

@example
(rlet1 v (vector 'a 'b 'c 'd 'e)
  (vector-swap! v 0 2))
  @result{} #(c b a d e)
@end example
@end defun

@defun vector-reverse! vec :optional start end
[R7RS vector]
@c MOD scheme.vector
@c EN
Reverse the elements of @var{vec}.  Returns an undefined value.
Optional @var{start} and @var{end} arguments can limit
the range of operation.
@c JP
@code{vec}の要素を逆順に並べ替えます。戻り値は未定義です。
省略可能引数@var{start}と@var{end}は影響が及ぶ範囲を限定します。
@c COMMON

@example
(rlet1 v (vector 'a 'b 'c 'd 'e)
  (vector-reverse! v 0 4))
  @result{} #(d c b a e)
@end example
@end defun

@defun vector-reverse-copy! target tstart source :optional sstart send
[R7RS vector]
@c MOD scheme.vector
@c EN
Like @code{vector-copy!}, but reverses the order of elements from @var{start}.
@c JP
@code{vector-copy!}と似ていますが、指定範囲を逆順にコピーします。
@c COMMON

@example
(rlet1 v (vector 'a 'b 'c 'd 'e)
  (vector-reverse-copy! v 2 '#(1 2)))
  @result{} #(a b 2 1 e)
@end example

@c EN
It is ok to pass the same vector to @var{target} and @var{source};
it always works even if the regions of source and destination are
overlapping.
@c JP
@var{target}と@var{source}に同じベクタを指定しても構いません。
コピー範囲が重なっていても問題なく動作します。
@c COMMON

@example
(rlet1 v (vector 'a 'b 'c 'd 'e)
  (vector-reverse-copy! v 1 v 1))
  @result{} #(a e d c b)
@end example
@end defun

@defun vector-unfold! f rvec start end seeds @dots{}
@defunx vector-unfold-right! f rvec start end seeds @dots{}
[R7RS vector]
@c MOD scheme.vector
@c EN
Fill @var{rvec} starting from index @var{start} (inclusive) and
ending at index @var{end} (exclusive), with the elements
calculated by @var{f}.

The procedure @var{f} takes the number of seed values @var{seeds} @dots{}
plus one arguments.  The first argument is the current index,
followed by seed values.  The same number of values
as the arguments must be returned from @var{f}; the first return value
is used to fill the current element of @var{rvec}, and the rest of the values
are used as the next seed values.

The result vector is filled from left to right by @code{vector-unfold!},
and right to left by @code{vector-unfold-right!}.
The return value is unspecified.
@c JP
@var{rvec}の、@var{start}から@var{end}の直前までの範囲を@var{f}が算出する
新たな要素で埋めます。

@var{f}は、@var{seeds} @dots{}の数よりひとつ多い引数を取ります。
最初の引数は現在のインデックスで、それにシード値が続きます。
@var{f}は引数と同数の値を返します。最初の戻り値が@var{rvec}を埋めるのに使われ、
残りの戻り値は新たなシード値として次の@var{f}の呼び出しに使われます。

結果のベクタは、@code{vector-unfold!}では左から右へ、
@code{vector-unfold-right!}では右から左へと埋められます。
戻り値はunspecifiedです。
@c COMMON

@example
(let1 rvec (vector 'a 'b 'c 'd 'e 'f)
  (vector-unfold! (^[i] (+ i 1)) rvec 1 4)
  rvec)
 @result{} #(a 2 3 4 e f)

(let1 rvec (vector 'a 'b 'c 'd 'e 'f)
  (vector-unfold-right! (^[i] (+ i 1)) rvec 1 4)
  rvec)
 @result{} #(a 2 3 4 e f)

(let1 rvec (vector 'a 'b 'c 'd 'e 'f)
  (vector-unfold! (^[i x] (values x (* x 2))) rvec 1 5 10)
  rvec)
 @result{} #(a 10 20 40 80 f)

(let1 rvec (vector 'a 'b 'c 'd 'e 'f)
  (vector-unfold! (^[i x] (values x (* x 2))) rvec 1 5 10)
  rvec)
 @result{} #(a 80 40 20 10 f)
@end example
@end defun

@c EN
@subheading Vector conversion
@c JP
@subheading ベクタの変換
@c COMMON

@defun reverse-vector->list vec :optional start end
[R7RS vector]
@c MOD scheme.vector
@c EN
Same as @code{(reverse (vector->list vec start end))}, but more efficient.
@c JP
@code{(reverse (vector->list vec start end))}と同じですが、より効率的です。
@c COMMON
@end defun

@node R7RS uniform vectors, R7RS sort, R7RS vectors, R7RS large
@subsection @code{scheme.vector.@@} - R7RS uniform vectors
@c NODE R7RSユニフォームベクタ, @code{scheme.vector.@@} - R7RSユニフォームベクタ

@deftp {Module} scheme.vector.@@
@mdindex scheme.vector.base
@mdindex scheme.vector.u8
@mdindex scheme.vector.s8
@mdindex scheme.vector.u16
@mdindex scheme.vector.s16
@mdindex scheme.vector.u32
@mdindex scheme.vector.s32
@mdindex scheme.vector.u64
@mdindex scheme.vector.s64
@mdindex scheme.vector.f32
@mdindex scheme.vector.f64
@mdindex scheme.vector.c64
@mdindex scheme.vector.c128
@c EN
@code{@@} is actually one of @code{u8}, @code{s8}, @code{u16}, @code{s16},
@code{u32}, @code{s32}, @code{u64}, @code{s64}, @code{f32},
@code{f64}, @code{c64} or @code{c128}.
(Gauche's @code{gauche.uvector} module also provides @code{f16}
and @code{c32} vectors.)
@c JP
@code{@@}は次のいずれかに置き換えて読んでください：
@code{u8}, @code{s8}, @code{u16}, @code{s16},
@code{u32}, @code{s32}, @code{u64}, @code{s64}, @code{f32},
@code{f64}, @code{c64}, @code{c128}。
(Gaucheの@code{gauche.uvector}モジュールはさらに@code{f16}と@code{c32}を
提供します)。
@c COMMON

@c EN
These modules provides vectors that can hold specific range of numeric
values.  In Gauche we use @emph{packed} representation, meaning
numbers are tightly stored in consecutive memory region.
@c JP
これらのモジュールは限られた範囲の数値だけを格納するベクタを提供します。
Gaucheでは、数値は連続したメモリ領域に@emph{詰められて}格納されます。
@c COMMON

@c EN
Additionally, @code{scheme.vector.base} module exports basic procedures,
@code{make-@@vector}, @code{@@vector}, @code{@@vector?}, @code{@@vector-length},
@code{@@vector-ref}, @code{@@vector-set!},
@code{@@vector->list}, @code{list->@@vector}, @code{@@?},
for @code{@@} being over all element types.
@c JP
また、@code{scheme.vector.base}モジュールは全ての要素型についての
基本手続き、つまり次の手続きの@code{@@}を全ての基本型で置換した手続きをまとめて
エクスポートしています：
@code{make-@@vector}、@code{@@vector}、@code{@@vector?}
@code{@@vector-length}、@code{@@vector-ref}、@code{@@vector-set!}、
@code{@@vector->list}、@code{list->@@vector}、@code{@@?}
@c COMMON

@c EN
The @code{gauche.uvector} module is a superset of these modules, and
all procedures are described there.  @xref{Uniform vectors} for the
details.
@c JP
@code{gauche.uvector}モジュールはこれらのモジュールのスーパーセットで、
このモジュールの全ての手続きはそちらで説明されています。
@ref{Uniform vectors}を参照してください。
@c COMMON
@end deftp

@node R7RS sort, R7RS sets, R7RS uniform vectors, R7RS large
@subsection @code{scheme.sort} - R7RS sort
@c NODE R7RSソート, @code{scheme.sort} - R7RSソート

@deftp {Module} scheme.sort
@mdindex scheme.sort
@c EN
Provides utilities to sort, and to work on sorted lists/vectors.
This module is the same as @code{srfi-132}.
@c JP
ソートおよびソート済みのリストやベクタに関する手続きを提供します。
このモジュールは@code{srfi-132}と同じです。
@c COMMON

@c EN
Gauche has built-in sort and merge procedures (@pxref{Sorting and merging}).
This module has a bit different API.  Notably, the ordering predicate
comes first than the sequence to be sorted, and the procedures
dealing with vectors uniformly support start/end arguments
@c JP
Gaucheは組み込みでソートとマージの手続きを用意していますが
(@ref{Sorting and merging}参照)、
このモジュールはAPIがちょっと異なります。特に、順序を決める述語が
ソートすべきシーケンスより先に来ます。また、ベクタを扱う手続きは一様に
start/end引数をサポートします。
@c COMMON

@c EN
This module also provide useful procedures working on sorted or
partially sorted sequences.
@c JP
このモジュールはまた、(部分的に)ソートされた列に対する便利な手続きをいくつか
定義しています。
@c COMMON
@end deftp

@defun list-sort elt< lis
@defunx list-sort! elt< lis
@defunx list-stable-sort elt< lis
@defunx list-stable-sort! elt< lis
[R7RS sort]
@c MOD scheme.sort
@c EN
Sort elements in a list @var{lis} according to the ordering
predicate @var{elt<}, which takes two elements from @var{lis}
and returns true iff the first argument is strictly less
than the second argument.

Returns a sorted list.
The procedures with bang are linear update version.  They are
allowed, but not required, to reuse
@var{lis}.  The ``stable'' variation guarantees stable sort.

These are basically the same as Gauche's built-in
@code{sort}, @code{sort!}, @code{stable-sort} and @code{stable-sort!},
except the Gauche's version works on any sequences and takes
arguments differently. (@xref{Sorting and merging}.)
@c JP
リスト@var{lis}の要素を比較述語@var{elt<}を使ってソートします。
@var{elt<}は@var{lis}からの二要素を引数に取り、最初の引数が厳密に
二番目の引数より小さい場合に限り@code{#t}を返します。

ソートされたリストが返されます。@code{!}つきの手続きは線形更新版で、
@var{lis}を破壊的に再利用することが許されています (再利用しないかもしれません。
したがって呼び出し側は常に戻り値を使う必要があります)。 ``stable'' がついている
ものは安定ソートを行います。

これらは基本的にはGaucheの組み込み手続き
@code{sort}、@code{sort!}、@code{stable-sort}、@code{stable-slot!}と
同じです。ただ、Gaucheのは引数の順序と、任意のシーケンスを取れるところが異なります
(@ref{Sorting and merging}参照)。
@c COMMON
@end defun


@defun list-sorted? elt< lis
[R7RS sort]
@c MOD scheme.sort
@c EN
Returns true iff the list @var{list} is sorted according to the
ordering predicate @var{elt<}.

See also @code{sorted?} in @ref{Sorting and merging}.
@c JP
リスト@var{list}が、順序述語@var{elt<}での比較において既にソート済みであれば
真を、そうでなければ偽を返します。

@ref{Sorting and merging}の@code{sorted?}も参照。
@c COMMON
@end defun


@defun list-merge elt< lis1 lis2
@defunx list-merge! elt< lis1 lis2
[R7RS sort]
@c MOD scheme.sort
@c EN
Given two sorted lists @var{lis1} and @var{lis2}, returns
a new sorted list according to the ordering predicate @var{elt<}.

Note that @code{list-merge!} works in-place, that is, all the pairs
in @var{lis1} and @var{lis2} are reused.

See also @code{merge} and @var{merge!} in @ref{Sorting and merging}.
@c JP
ソート済みの二つのリスト@var{lis1}と@var{lis2}を合わせて、
ソート済みのひとつのリストにして返します。要素は順序述語@var{elt<}で比較されます。

@code{list-merge!}は、結果のリストを得るために@var{lis1}と@var{lis2}の
メモリを破壊的に再利用します。

@ref{Sorting and merging}の@code{merge}および@code{merge!}も参照。
@c COMMON
@end defun

@defun vector-sort elt< vec :optional start end
@defunx vector-stable-sort elt< vec :optional start end
[R7RS sort]
@c MOD scheme.sort
Sort elements in a vector @var{vec} according to the ordering
predicate @var{elt<}, which takes two elements from @var{vec}
and returns true iff the first argument is strictly less
than the second argument.  Returns a fresh sorted vector.
The ``stable'' variation guarantees stable sort.

When the optional @var{start} and/or @var{end} arguments are given,
only the portion from @var{start} (inclusive) and
@var{end} (exclusive) of @var{vec} are looked at.
The result vector's length is @code{@var{end} - @var{start})}.
When @var{end} is omitted, the length of @var{vec} is assumed.

See also @code{sort} and @code{stable-sort} in @ref{Sorting and merging}.
@end defun

@defun vector-sort! elt< vec :optional start end
@defunx vector-stable-sort! elt< vec :optional start end
[R7RS sort]
@c MOD scheme.sort
Sort elements ``in-place'' in a vector @var{vec} according to the ordering
predicate @var{elt<}, which takes two elements from @var{vec}
and returns true iff the first argument is strictly less
than the second argument.  Upon successful return,
@var{vec}'s elements are sorted.  Returns unspecified value; the
caller must rely on the side effect.

When the optional @var{start} and/or @var{end} arguments are given,
only the portion from @var{start} (inclusive) and
@var{end} (exclusive) of @var{vec} are sorted; other elements
will remain intact.
When @var{end} is omitted, the length of @var{vec} is assumed.

See also @code{sort!} and @code{stable-sort!} in @ref{Sorting and merging}.
@end defun

@defun vector-sorted? elt< vec :optional start end
[R7RS sort]
@c MOD scheme.sort
Returns true iff @var{vec} between @var{start} (inclusive)
and @var{end} (exclusive) is sorted according to the ordering
predicate @var{elt<}.  If @var{start} and/or @var{end} is/are omitted,
0 and the length of @var{vec} are assumed, respectively.

See also @code{sorted?} in @ref{Sorting and merging}.
@end defun


@defun vector-merge elt< vec1 vec2 :optional start1 end1 start2 end2
@defunx vector-merge! elt< rvec vec1 vec2 :optional rstart start1 end1 start2 end2
[R7RS sort]
@c MOD scheme.sort
Merge two sorted vectors @var{vec1} and @var{vec2}
into one vector, according to the
ordering predicate @var{elt<}.

The optional argument @var{start1} and @var{end1} restricts @var{vec1}'s
portion to be looked at, and @var{start2} and @var{end2}
restricts @var{vec2}'s portion to be looked at.

The functional version @var{vector-merge} allocates a fresh vector
to hold the result, and returns it.

The side-effecting version @var{vector-merge!} uses @var{rvec}.
to hold the result. The procedure doesn't return a meaningful value.
The optional @var{rstart} argument specifies
the index of @var{rvec} from which the result is filled; the default
is 0.
@end defun

@defun list-delete-neighbor-dups elt= lis
@defunx list-delete-neighbor-dups! elt= lis
@defunx vector-delete-neighbor-dups elt= vec :optional start end
@defunx vector-delete-neighbor-dups! elt= vec :optional start end
[R7RS sort]
@c MOD scheme.sort
From the given list @var{lis} or vector @var{vec},
these procedures delete adjacent duplicate elements.  Equivalence
is checked by @var{elt=} procedure.

@example
(list-delete-neighbor-dups eq? '(m i s s i s s i p p i))
  @result{} (m i s i s i p i)
@end example

The non-destructive versions @code{list-delete-neighbor-dups} and
@code{vector-delete-neighbor-dups} returns a freshly allocated
list and vector, respectively.

The destructive @code{list-delete-neighbor-dups!} works in-place,
reusing pairs of @var{lis}.  No allocation will be done.

The destructive @code{vector-delete-neighbor-dups!} has a bit different
interface.  It updates @var{vec} in-place, but since we can't change
the length of the vector, it gathers the result from the beginning of
the @var{vec}, then returns the next index @var{newend}
of @var{vec}---that is,
after calling this procedure, @code{[@var{start}, @var{newend})}
holds the result.
The elements between @code{[@var{newend}, @var{end})} will remain intact.

The optional @var{start} and @var{end} arguments limits the region
of @var{vec} to be looked at.

@example
(vector-delete-neighbor-dups eq? '#(a a a b b c c d d e e f f) 3 10)
  @result{} #(b c d e)

(let1 v '#(a a a b b c c d d e e f f)
  (cons (vector-delete-neighbor-dups! eq? v 3 10) v))
  @result{} (7 . #(a a a b c d e d d e e f f))
@end example

Note: The @code{gauche.sequence} module provides neighbor duplicate
deletion on generic sequences.  Those procedures are implemented by
the generic versions as shown below.  @xref{Other operations over sequences},
for the details.
@table @code
@item list-delete-neighbor-dups
@code{delete-neighbor-dups}
@item list-delete-neighbor-dups!
@code{delete-neighbor-dups-squeeze!}
@item vector-delete-neighbor-dups
@code{delete-neighbor-dups}
@item vector-delete-neighbor-dups!
@code{delete-neighbor-dups!}
@end table
@end defun

@defun vector-select! elt< vec k :optional start end
[R7RS sort]
@c MOD scheme.sort
Select @var{k}-th smallest element in @var{vec} according to the
ordering predicate @var{elt<}.  @var{K} is zero based, i.e. 0 means
the smallest.  The optional @var{start} and @var{end} arguments
limits the range of @var{vec} to be looked at, and defaulted to
0 and the length of @var{vec}, respectively.
@var{K} must satisfy @code{@var{start} <= @var{k} < @var{end}}.

This procedure runs in O(n) time, and requires no extra stroage.
This procedure may partially modify @var{vec}.
@end defun

@defun vector-separate! elt< vec k :optional start end
[R7RS sort]
@c MOD scheme.sort
Find @var{k}-th smallerst element in @var{vec} (pivot) between
between @var{start} and @var{end}, according to the ordering
predicate @var{elt<}, then rearrange elements
between @var{start} and @var{end} so that
elements smaller than the pivot comes between @code{@var{start}} and
@code{@var{start} + @var{k}}, and the rest of the elements come
afterwards.  When omitted, @var{start} is 0 and @var{end} is
the length of the @var{vec}.

This can be used as a building block for in-place divide-and-conquer
algorithms.  Runs in O(n) time.
@end defun

@defun vector-find-median elt< vec knil :optional mean
@defunx vector-find-median! elt< vec knil :optional mean
[R7RS sort]
@c MOD scheme.sort
Find median value of elements in @var{vec}, when ordered by
the ordering predicate @var{elt<}.  Non-destructive version
@code{vector-find-median} runs in O(n) time.  The destructive
version @code{vector-find-median!} is specified to leave
@var{vec} sorted, so it runs in O(n log n).

@enumerate
@item
If @var{vec} is empty, @var{knil} is returned.  This is the only case
@var{knil} is used.
@item
If @var{vec} has odd number of elements, the element falls in the exactly
the midpoint when ordered, is returned.
@item
If @var{vec} has even number of elements, the two elements closest to
the midpoint is chosen and passed to the procedure @var{mean}, and
its result is returned.  The default of @var{mean} is an arithmetic
mean of numbers.
@end enumerate

@example
(vector-find-median < #() 0)
  @result{} 0

(vector-find-median < #(78 61 19 38 51) 0)
  @result{} 51

(vector-find-median < #(78 61 19 38 51 52) 0)
  @result{} 103/2
@end example
@end defun

@node R7RS sets, R7RS character sets, R7RS sort, R7RS large
@subsection @code{scheme.set} - R7RS sets
@c NODE R7RSセット, @code{scheme.set} - R7RSセット

@deftp {Module} scheme.set
@mdindex scheme.set
@c EN
Sets and bags are unordered collection of Scheme values.
A set doesn't count duplicates; if you add an item
which is already in a set, you still have one item of the kind.
A bag counts duplicates; if you add an item which
is already in a bag, you have two items of the kind.
@c JP
セットとバッグは、Scheme値の順序づけのないコレクションです。
セットは重複を考慮しません。既にセット中にある要素をさらに追加しても、
その要素は依然として一つだけセット中にあると認識されます。
一方、バッグは重複を数えます。既にバッグ中にひとつだけある要素と同じものを
追加すると、バッグ中のその要素は二つと数えられます。
@c COMMON

@c EN
To check whether the items are ``the same'', sets and bags
takes a comparator at construction time.  The comparator
doesn't need to have an ordering predicate (we don't need
to order the elements) but has to have a hash function.
@xref{Basic comparators}, for the details of comparators.
@c JP
要素が「同じ」であるかどうかの判定のため、セットとバッグは構築時に
比較器を取ります。比較器は順序手続きを持っていなくても構いません
(要素の順序づけは必要ありません)が、ハッシュ手続きは持っている必要があります。
比較器について詳しくは@ref{Basic comparators}を参照してください。
@c COMMON

@c EN
This module is originally specified as @code{srfi-113}, and then
incorporated to R7RS large.
@c JP
このモジュールは当初@code{srfi-113}として定義され、のちにR7RS largeに
採用されました。
@c COMMON

@c EN
As a Gauche's extension, sets and bags implement collection protocol
(@pxref{Collection framework}, for the details), and generic collection
operations can be applied.
@c JP
Gauche独自拡張として、セットやバッグはコレクションプロトコルを実装しており、
汎用のコレクション操作が適用できます
(@ref{Collection framework}参照)。
@c COMMON

@example
(coerce-to <list> (set eq-comparator 'a 'b 'a 'b))
  @result{} (a b)      ; @r{order may differ}

(coerce-to <list> (bag eq-comparator 'a 'b 'a 'b))
  @result{} (a a b b)  ; @r{order may differ}
@end example
@end deftp

@subheading Constructors

@defun set comparator elt @dots{}
@defunx bag comparator elt @dots{}
[R7RS set]
@c MOD scheme.set
Creates a new set and bag from given elements @var{elt} @dots{}.
Given @var{comparator} will be used to compare equality of elements.

@example
(set->list (set eq-comparator 'a 'b 'a 'b))
  @result{} (a b)

(bag->list (bag eq-comparator 'a 'b 'a 'b))
  @result{} (a a b b)
@end example
@end defun

@defun set-unfold stop? mapper successor seed comparator
@defunx bag-unfold stop? mapper successor seed comparator
[R7RS set]
@c MOD scheme.set
Procedurally creates a set or a bag.  The first three
arguments, @var{stop?},  @var{mapper} and @var{successor},
are all procedures that takes one argument, the current seed value.
It may be easier to know their types:

@example
seed      :: Seed
stop?     :: Seed -> Boolean
mapper    :: Seed -> ElementType
successor :: Seed -> Seed
@end example

The @code{stop?} procedure takes the current seed value and
returns a boolean value - if it is true, iteration stops.

The @code{mapper} procedure takes the current seed value
and returns an item, which is to be included in the resulting set or bag.

The @code{successor} procedure takes the current seed value
and returns the next seed value.

And the @code{seed} argument gives the initial seed value.

@example
(set->list (set-unfold (^s (= s 75))
                       integer->char
                       (^s (+ s 1))
                       65
                       eqv-comparator))
 @result{} (#\D #\H #\A #\E #\I #\J #\B #\F #\C #\G)
@end example
@end defun

@subheading Predicates

@defun set-contains? set obj
@defunx bag-contains? bag obj
[R7RS set]
@c MOD scheme.set
Check if @var{obj} is in the set or the bag.
@end defun

@defun set-empty? set
@defunx bag-empty? bag
[R7RS set]
@c MOD scheme.set
Returns @code{#t} iff the given set or bag is empty.
@end defun

@defun set-disjoint? set1 set2
@defunx bag-disjoint? bag1 bag2
[R7RS set]
@c MOD scheme.set
Returns @code{#t} iff the given arguments (sets or bags) don't have
common items.  Both arguments must have the same comparator---otherwise
an error is signaled.
@end defun

@subheading Accessors

@defun set-member set obj default
@defunx bag-member bag obj default
[R7RS set]
@c MOD scheme.set
Returns an element in the given set or bag which is equal to @var{obj}
in terms of the set's or the bag's comparator.  If no such element is
found, @var{default} will be returned.

Note that the returned object doesn't need to be ``the same''
as @var{obj} in a usual sense.  See the following example:

@example
(let s (set string-ci-comparator "abc" def")
  (set-member s "ABC" #f))
  @result{} "abc"
@end example
@end defun

@defun set-element-comparator set
@defunx bag-element-comparator bag
[R7RS set]
@c MOD scheme.set
Returns the comparator used to compare the elements for the set or the bag.
@end defun

@subheading Updaters

@defun set-adjoin set elt @dots{}
@defunx bag-adjoin bag elt @dots{}
[R7RS set]
@c MOD scheme.set
Returns a newly created set or bag that contains all the elements
in the original set/bag, plus given elements.  The new set/bag's
comparator is the same as the original set/bag's one.
@end defun

@defun set-replace set elt
@defunx bag-replace bag elt
[R7RS set]
@c MOD scheme.set
Returns a newly created set/bag with the same comparator with
the original set/bag, and the same elements, except that the elements
equal to @var{elt} (in terms of set/bag's comparator) is replaced
by @var{elt}.  If the original set/bag doesn't contain an element
equal to @var{elt}, the original one is returned.

@example
(let ((s (set string-ci-comparator "ABC" "def")))
  (set->list (set-replace s "abc")))
  @result{} ("abc" "def")
@end example
@end defun

@defun set-delete set elt @dots{}
@defunx bag-delete bag elt @dots{}
[R7RS set]
@c MOD scheme.set
Returns a newly created set or bag that has the same comparator
and the same elements in the original set/bag, except that the
item which is equal to @var{elt}.
@end defun

@defun set-delete-all set elt-list
@defunx bag-delete-all bag elt-list
[R7RS set]
@c MOD scheme.set
Returns a newly created set or bag with the same comparator of
the original set/bag, with the elements of the original set/bag
except the ones listed in @var{elt-list}.
@end defun


@defun set-adjoin! set elt @dots{}
@defunx bag-adjoin! bag elt @dots{}
@defunx set-replace! set elt
@defunx bag-replace! bag elt
@defunx set-delete! set elt @dots{}
@defunx bag-delete! bag elt @dots{}
@defunx set-delete-all! set elt-list
@defunx bag-delete-all! bag elt-list
[R7RS set]
@c MOD scheme.set
These are the linear update versions of their counterparts.
It works just like the ones without @code{!}, except that
the original set/bag @emph{may} be reused to produce the result,
instead of new one being allocated.

Note that it's not guaranteed that the original
set/bag is modified, so you should use the return value of them,
instead of relying on the side effects.
@end defun

@defun set-search! set elt failure success
@defunx bag-search! bag elt failure success
[R7RS set]
@c MOD scheme.set
Lookup-and-modify procedures.  The @var{failure} and @var{success}
arguments are procedures.

First, they search @var{elt} in the given set/bag.
If an item that matches @var{elt} is found, the @var{success} procedure
is called with three arguments, as follows:
@example
(success item update remove)
@end example
The @var{update} argument is a procedure that takes two arguments,
as @code{(update new-item retval)}.  It replaces the matching @var{item} in the
set/bag with @var{new-item}, and returns @var{retval}.
The @var{remove} argument is a procedure that takes one argument,
as @code{(remove retval)}.  It removes the matching @var{item} in
the set/bag, and returns @var{retval}.

If an item that matches @var{elt} is not found, the @var{failure} procedure
is called with two arguments, as follows:
@example
(failure insert ignore)
@end example
The @var{insert} argument is a procedure that takes one argument,
as @code{(insert retval)}.  It inserts @var{elt} into the set/bag, and
returns @var{retval}.
The @var{ignore} argument is a procedure that takes one argument,
as @code{(ignore retval)}.  It just returns @var{retval}.

The return values of @code{set-search!} and @code{bag-search!} is
the modified set/bag (which may or may not be @code{eq?} to the passed one),
and the value returned by @var{success} or @var{failure} procedures.

Note that @var{retval} isn't used in this process; it is just to provide
one of the return values of @code{set-search!}/@code{bag-search!}, for
the procedures passed to @var{success} or @var{failure} are expected
to be tail-called.

If there are more than one item that matches @var{elt} in a bag,
@code{bag-search!} only invokes @var{success} for the first item
it finds.  You can recurse into @code{bag-search!} in the @var{failure}
procedure to visit all matching items.  It is guaranteed that @var{success}
and @var{failure} procedures are tail-called.
@end defun

@subheading The whole set

@defun set-size set
@defunx bag-size bag
[R7RS set]
@c MOD scheme.set
Returns the number of items in the set/bag.
@end defun

@defun set-find pred set failure
@defunx bag-find pred bag failure
[R7RS set]
@c MOD scheme.set
Apply @var{pred} on each item in the set/bag, and returns the
first item on which @var{pred} returns true.  Since sets and bags
are unordered, if there are more than one items that satisfy @var{pred},
you won't know which one will be returned.

If there're no items that satisfy @var{pred}, a thunk @code{failure}
is called and its result is returned.
@end defun

@defun set-count pred set
@defunx bag-count pred bag
[R7RS set]
@c MOD scheme.set
Returns the number of items that satisfy @var{pred} in the set/bag.
@end defun

@defun set-any? pred set
@defunx bag-any? pred bag
[R7RS set]
@c MOD scheme.set
Returns true iff any item in the set/bag satisfy @var{pred}.
@end defun

@defun set-every? pred set
@defunx bag-every? pred bag
[R7RS set]
@c MOD scheme.set
Returns true iff every item in the set/bag satisfy @var{pred}.
@end defun

@subheading Mapping and folding

@defun set-map comparator proc set
@defunx bag-map comparator proc bag
[R7RS set]
@c MOD scheme.set
Create and return a new set/bag with the comparator @var{comparator},
whose items are calculated by applying @var{proc} to each element
in the original set/bag.
@end defun

@defun set-for-each proc set
@defunx bag-for-each proc bag
[R7RS set]
@c MOD scheme.set
Apply @var{proc} to each element in the set/bag.   The result of @var{proc}
is ignored.  Return value is undefined.
@end defun

@defun set-fold proc seed set
@defunx bag-fold proc seed bag
[R7RS set]
@c MOD scheme.set
For each item in the set/bag, call @var{proc} with two arguments, an item
and a seed value.  What @var{proc} returns becomes the next seed value.
The @var{seed} argument gives the initial seed value, and the last return
value of @var{proc} will be the result of @code{set-fold}/@code{bag-fold}.

@example
(bag-fold + 0 (bag eqv-comparator 1 1 2 2 3 3 4 4))
  @result{} 20
@end example
@end defun

@defun set-filter pred set
@defunx bag-filter pred bag
[R7RS set]
@c MOD scheme.set
Returns a newly created set/bag with the same comparator of the original
set/bag, and its content consists of items from the original set/bag
that satisfy @var{pred}.

@example
(set->list (set-filter odd? (set eqv-comparator 1 2 3 4 5)))
  @result{} (1 3 5)
@end example
@end defun

@defun set-remove pred set
@defunx bag-remove pred bag
[R7RS set]
@c MOD scheme.set
Returns a newly created set/bag with the same comparator of the original
set/bag, and its content consists of items from the original set/bag
that does not satisfy @var{pred}.

@example
(set->list (set-remove odd? (set eqv-comparator 1 2 3 4 5)))
  @result{} (2 4)
@end example
@end defun

@defun set-partition pred set
@defunx bag-partition pred bag
[R7RS set]
@c MOD scheme.set
Returns two sets or bags, both have the same comparator of the original
set or bag.  The first one consists of the items from the original set/bag
that satisfy @var{pred}, and the second one consists of the items that don't.

@example
(receive (in out) (set-remove odd? (set eqv-comparator 1 2 3 4 5))
  (values (set->list in)
          (set->list out)))
  @result{} (1 3 5) @r{and} (2 4)
@end example
@end defun

@defun set-filter! pred set
@defunx bag-filter! pred bag
@defunx set-remove! pred set
@defunx bag-remove! pred bag
@defunx set-partition! pred set
@defunx bag-partition! pred bag
[R7RS set]
@c MOD scheme.set
Linear update versions of their counterparts (the procedures without @code{!}).
They work like their respective counterpart, but they are allowed (but not
required) to reuse the original set/bag to produce the result(s).

Note that it is not guaranteed that the original set/bag is modified, so
you have to use the return value(s) instead of relying on the side effects.
@end defun

@subheading Copying and conversion

@defun set-copy set
@defunx bag-copy bag
[R7RS set]
@c MOD scheme.set
Returns a copy of the set/bag.
@end defun

@defun set->list set
@defunx bag->list bag
[R7RS set]
@c MOD scheme.set
Returns a list of all items in the set/bag.
Since sets and bags are unordered, there's no guarantee on the
order of items.
@end defun

@defun list->set comparator elt-list
@defunx list->bag comparator elt-list
[R7RS set]
@c MOD scheme.set
Creates a set or a bag with the given comparator, and
the list of element.  Functionally equivalent to the followings:

@example
(apply set comparator elt-list)
(apply bag comparator elt-list)
@end example
@end defun

@defun list->set! set elt-list
@defunx list->bag! bag elt-list
[R7RS set]
@c MOD scheme.set
Add items in @var{elt-list} to the existing set/bag, and returns
the updated set/bag.  The original set/bag is also modified.
Functionally equivalent to the followings:

@example
(apply set-adjoin! set elt-list)
(apply bag-adjoin! bag elt-list)
@end example
@end defun

@defun bag->set bag
@defunx set->bag set
[R7RS set]
@c MOD scheme.set
Conversions between a bag and a set.  Returns a newly created bag or set,
respectively.

If @var{bag} has duplicated items, @code{bag->set} coerces them to one
item.
@end defun

@defun set->bag! bag set
[R7RS set]
@c MOD scheme.set
Adds all items in @var{set} to @var{bag}, and returns @var{bag}.
Both @var{bag} and @var{set} must have the same comparator.
@end defun


@defun bag->alist bag
[R7RS set]
@c MOD scheme.set
Returns a list of @code{(item . count)}, where @var{item} is
an item in @var{bag}, and @var{count} is the number of that item
in the bag.
@end defun

@defun alist->bag comparator alist
[R7RS set]
@c MOD scheme.set
Creates a new bag with @var{comparator}, and fills it according to
@var{alist}, which must be a list of @code{(item . count)}.

If there's duplicate items in @var{alist}, only fist one counts.
@end defun

@subheading Subsets

@defun set=? set1 set2 @dots{}
@defunx bag=? bag1 bag2 @dots{}
[R7RS set]
@c MOD scheme.set
Returns true iff all sets/bags have exactly same items.

The comparators of the argument sets/bags are not checked, but assumed
to be the same, in terms of the equality of items.
@end defun

@defun set<? set1 set2 @dots{}
@defunx bag<? bag1 bag2 @dots{}
@defunx set>? set1 set2 @dots{}
@defunx bag>? bag1 bag2 @dots{}
@defunx set<=? set1 set2 @dots{}
@defunx bag<=? bag1 bag2 @dots{}
@defunx set>=? set1 set2 @dots{}
@defunx bag>=? bag1 bag2 @dots{}
[R7RS set]
@c MOD scheme.set
Returns true iff each preceding set/bag is a proper subset of,
a proper superset of, a subset of, or a superset of the following
set/bags, respectively.

Again, the comparators of the argument sets/bags are not checked, but assumed
to be the same, in terms of the equality of items.
@end defun

@subheading Set theory operations

@defun set-union set1 set2 @dots{}
@defunx bag-union bag1 bag2 @dots{}
[R7RS set]
@c MOD scheme.set
Returns a newly allocated set or bag which is a union of all
the sets/bags.
@end defun

@defun set-intersection set1 set2 @dots{}
@defunx bag-intersection bag1 bag2 @dots{}
[R7RS set]
@c MOD scheme.set
Returns a newly allocated set or bag which is an intersection of
all the sets/bags.
@end defun

@defun set-difference set1 set2 @dots{}
@defunx bag-difference bag1 bag2 @dots{}
[R7RS set]
@c MOD scheme.set
Returns a newly created set or bag that contains items in @var{set1}/@var{bag1}
except those are also in @var{set2}/@var{bag2} @dots{}.

@example
(sort (set->list (set-difference (set eqv-comparator 1 2 3 4 5 6 7)
                                 (set eqv-comparator 3 5 7 9 11 13)
                                 (set eqv-comparator 4 8 16 32))))
  @result{} (1 2 6)
@end example
@end defun

@defun set-xor set1 set2
@defunx bag-xor bag1 bag2
[R7RS set]
@c MOD scheme.set
Returns a newly created set or bag that consists of items
that are either in @var{set1}/@var{bag1} or @var{set2}/@var{bag2},
but not in both.

@example
(sort (set->list (set-xor (set eqv-comparator 2 3 5 7 11 13 17)
                          (set eqv-comparator 3 5 7 9 11 13 15))))
  @result{} (2 9 15 17)
@end example
@end defun

@defun set-union! set1 set2 @dots{}
@defunx bag-union! bag1 bag2 @dots{}
@defunx set-intersection! set1 set2 @dots{}
@defunx bag-intersection! bag1 bag2 @dots{}
@defunx set-difference! set1 set2 @dots{}
@defunx bag-difference! bag1 bag2 @dots{}
@defunx set-xor! set1 set2
@defunx bag-xor! bag1 bag2
[R7RS set]
@c MOD scheme.set
Linear update versions of their corresponding procedures.
Those procedures works like their @code{!}-less counterparts,
except that they are allowed to, but not required to, reuse
@var{set1}/@var{bag1} to produce the result.

The caller should always use the returned set/bag instead of
relying on the side effects.
@end defun

@subheading Bag-specific procedures

@defun bag-sum bag1 bag2 @dots{}
@defunx bag-sum! bag1 bag2 @dots{}
[R7RS set]
@c MOD scheme.set
Returns a bag that gathers all the items in given bags, counting
duplicates.  The functional version @code{bag-sum} always
creates new bag to return.
The linear update version @code{bag-sum!} is allowed to,
but not required to, modify @var{bag1} to produce the result.

@example
(sort (bag->list (bag-sum (bag eqv-comparator 1 1 2 4 5 5 6)
                          (bag eqv-comparator 3 3 5 9))))
  @result{} (1 1 2 3 3 4 5 5 5 6 9)
@end example

Note the difference from @code{bag-union}:

@example
(sort (bag->list (bag-union (bag eqv-comparator 1 1 2 4 5 5 6)
                            (bag eqv-comparator 3 3 5 9))))
  @result{} (1 1 2 3 3 4 5 5 6 9)
@end example
@end defun

@defun bag-product n bag
@defunx bag-product! n bag
[R7RS set]
@c MOD scheme.set
Returns a bag that contains every item as @var{n}-times
many as the original bag.  A fresh bag is created and returned
by @code{bag-product}, while @code{bag-product!} may reuse
@var{bag} to produce the result.

@example
(sort (bag->list (bag-product 2 (bag eq-comparator 'a 'b 'r 'a))))
  @result{} (a a a a b b r r)
@end example
@end defun

@defun bag-unique-size bag
[R7RS set]
@c MOD scheme.set
Returns the number of unique elements in @var{bag}.

@example
(bag-unique-size (bag eqv-comparator 1 1 2 2 3 3 4))
 @result{} 4
@end example
@end defun

@defun bag-element-count bag elt
[R7RS set]
@c MOD scheme.set
Returns the number of specified element @var{elt} in @var{bag}.

@example
(bag-element-count (bag eqv-comparator 1 1 2 2 2 3 3) 2)
 @result{} 3
@end example
@end defun

@defun bag-for-each-unique proc bag
[R7RS set]
@c MOD scheme.set
For each unique item in @var{bag}, calls @code{proc} with two arguments:
The item, and the count of the item in the bag.
@end defun

@defun bag-fold-unique proc seed bag
[R7RS set]
@c MOD scheme.set
For each unique item in @var{bag}, calls @var{proc} with three arguments:
The item, the count of the item, and the previous seed value.
The @var{seed} argument provides the initial seed value; the result
of @var{proc} is used for the next seed value, and the last
result of @code{proc} is returned from @code{bag-fold-unique}.

@example
(sort (bag-fold-unique acons '()
        (bag equal-comparator "a" "a" "b" "b" "b" "c" "d"))
      string<? car)
 @result{} (("a" . 2) ("b" . 3) ("c" . 1) ("d" . 1))
@end example
@end defun

@defun bag-increment! bag elt count
@defunx bag-decrement! bag elt count
[R7RS set]
@c MOD scheme.set
Linear update @var{bag} to increase or decrease the count of @var{elt} in it
by @var{count}, which must be an exact integer.  Note that the
element count won't get below zero; if a bag has two @code{a}'s, and
you call @code{(bag-decrement! bag 'a 100)}, you get a bag
with zero @code{a}'s.
@end defun

@subheading Comparators

@defvr {Comparator} set-comparator
@defvrx {Comparator} bag-comparator
[R7RS comparator]
@c MOD scheme.set
Comparators to be used to compare sets or bags.  They don't provide
comparison procedure, for you cannot define a total order among sets or bags.
They do provide hash functions.
@end defvr


@node R7RS character sets, R7RS hash tables, R7RS sets, R7RS large
@subsection @code{scheme.charset} - R7RS character sets
@c NODE R7RS文字集合, @code{scheme.charset} - R7RS文字集合

@deftp {Module} scheme.charset
@mdindex scheme.charset
@c EN
Implements character set library, originally defined as SRFI-14.
Note that the following
character-set procedures and pre-defined charsets are Gauche's build-in.
@xref{Character sets}.
@c JP
文字集合ライブラリを実装します。元はSRFI-14で定義されたものです。
以下の文字集合手続きと定義済み文字集合はGauche組み込みになっているので、
@ref{Character sets}を参照してください。
@c COMMON

@example
char-set             char-set?            char-set-contains?
char-set-copy        char-set-complement  char-set-complement!

char-set:lower-case  char-set:upper-case  char-set:title-case
char-set:letter      char-set:digit       char-set:letter+digit
char-set:graphic     char-set:printing    char-set:whitespace
char-set:iso-control char-set:punctuation char-set:symbol
char-set:hex-digit   char-set:blank       char-set:ascii
char-set:empty       char-set:full
@end example

@c EN
In Gauche,
the @code{<char-set>} class inherits @code{<collection>} and implements
the collection protocol, so that the generic operations defined in
@code{gauche.collection} can also be used (@pxref{Collection framework}).
@c JP
Gaucheでは@code{<char-set>}クラスは@code{<collection>}を継承し、
コレクションプロトコルを実装しているので、@code{gauche.collection}モジュールで
提供される操作も使えます (@ref{Collection framework}参照)。
@c COMMON
@end deftp

@menu
* Character-set constructors::
* Character-set comparison::
* Character-set iteration::
* Character-set query::
* Character-set algebra::
@end menu

@node Character-set constructors, Character-set comparison, R7RS character sets, R7RS character sets
@subsubsection Character-set constructors
@c NODE 文字集合の構築子

@defun list->char-set char-list :optional base-cs
@defunx list->char-set! char-list base-cs
[R7RS comparator]
@c MOD scheme.charset
@c EN
Constructs a character set from a list of characters @var{char-list}.
If @var{base-cs} is given, it must be a character set, and the characters
in it are added to the result character set.
@code{List->char-set!} is allowed, but not required, to reuse @var{base-cs}
to store the result.
@c JP
与えられた文字のリスト@var{char-list}から文字集合を構築して返します。
文字集合@var{base-cs}が与えられていた場合、返される文字集合は
その文字集合に@var{char-list}中の文字を追加したものとなります。
@code{list->char-set!}は、結果を格納するために@var{base-cs}を
変更するかもしれません。
@c COMMON
@end defun

@defun string->char-set s :optional base-cs
@defunx string->char-set! s base-cs
[R7RS charset]
@c MOD scheme.charset
@c EN
Like @code{list->char-set} and @code{list->char-set!},
but take a list of characters from a string @var{s}.
@c JP
追加する文字をリストでなく文字列@var{s}で与えることを除けば
@code{list->char-set}、@code{list->char-set!}と同じです。
@c COMMON
@end defun

@defun char-set-filter pred char-set :optional base-cs
@defunx char-set-filter! pred char-set base-cs
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character set containing every character @var{c} in
@var{char-set} such that @code{(@var{pred} @var{c})} returns true.
If a character set @var{base-cs} is given, its content is added to
the result.  The linear update version @code{char-set-filter!}
is allowed, but not required, to modify @var{base-cs} to store the result.
@c JP
@var{char-set}内の文字のうち、@code{(@var{pred} @var{c})} が真の値を
返すような@var{c}からなる文字集合を作成して返します。
文字集合@var{base-cs}が与えられた場合は、その内容が結果に追加されます。
@code{char-set-filter!}は、結果を格納するために@var{base-cs}を変更するかも
しれません。
@c COMMON
@end defun

@defun ucs-range->char-set lower upper :optional error? base-cs
@defunx ucs-range->char-set! lower upper error? base-cs
[R7RS charset]
@c MOD scheme.charset
@c EN
Creates a character set containing every character whose ISO/IEC 10646
UCS-4 code lies in the half-open range [@var{lower},@var{upper}).

If the range contains unassigned codepoint, they are silently ignored.

If the range contains a valid codepoint which isn't supported in Gauche,
it is ignored when @var{error?} is false (default),
or an error is raised when @var{error?} has a true value.
If you compile Gauche with utf-8 native encoding (default), all valid
Unicode codepoints are supported.  If Gauche is compiled with other native
encoding, some codepoints are not supported.

If a character set @var{base-cs} is given, its content is added to
the result.  The linear update version @code{ucs-range->char-set!}
is allowed, but not required, to modify @var{base-cs} to store the result.
@c JP
@var{lower}以上、@var{upper}未満のUnicodeコードポイントを持つ文字を服務
文字集合を作って返します。

指定された範囲内に文字を割り当てられていないコードポイントがあった場合、
それは単に無視されます。

指定された範囲内にある有効なコードポイントをGaucheがサポートしていない場合、
@var{error?}が偽なら(デフォルト)それは単に無視され、真の値ならエラーが投げられます。
デフォルトではGaucheはutf-8内部エンコーディングでコンパイルされていて、
有効な全てのUnicodeコードポイントが扱えます。しかし、Gaucheをそれ以外の内部エンコーディング
でコンパイルした場合は、サポートされないコードポイントがあります。

文字集合@var{base-cs}が与えられた場合、その内容が結果の文字集合に追加されます。
@code{ucs-range->char-set!}は、結果を格納するために@var{base-cs}を
再利用するかもしれません。
@c COMMON
@end defun

@defun integer-range->char-set lower upper :optional error? base-cs
@defunx integer-range->char-set! lower upper error? base-cs
@c MOD scheme.charset
@c EN
These are Gauche-specific procedures and not in @code{scheme.charset}.
When Gauche is compiled with utf-8 native encoding (default), they are
the same as @code{ucs-range->char-set} and @code{ucs-range->char-set!},
respectively.
If Gauche is compiled with other native encoding, these interprets
the given range in its native encoding.

Meaning of @var{error?} and @var{base-cs} are the same as
@code{ucs-char->char-set}.
@c JP
これらはGauche特有で、@code{scheme.charset}の仕様には含まれていません。
Gaucheがutf-8内部エンコーディングでコンパイルされていた場合(デフォルト)、これらは
それぞれ@code{ucs-range->charset}および@code{ucs->range-char-set!}と同じです。
Gaucheがそれ以外の内部エンコーディングでコンパイルされていた場合は、
範囲指定がそのエンコーディングでの文字コードで解釈されません。

@var{error?}および@var{base-cs}引数の意味は@code{ucs-char->char-set}と同じです。
@c COMMON
@end defun

@defun ->char-set x
[R7RS charset]
@c MOD scheme.charset
@c EN
A convenience function to coerce various kinds of objects to a char-set.
The argument @var{x} can be a collection of characters,
a char-set, or a character.  If the argument is a char-set,
it is returned as-is.  If the argument is a character,
a char-set with that single character is returned.
@c JP
様々な種類のオブジェクトを文字集合に変換する関数です。@var{x}に
文字のコレクション、文字集合、あるいは文字を渡すことができます。
引数が文字集合の場合はそれがそのまま返されます。
引数が文字の場合は、その文字のみを含む文字集合が返されます。
@c COMMON

@c EN
Note: R7RS @code{(scheme charset)}'s
@code{->char-set} only accepts a string, a char-set
or a character as an argument.  Gauche extends it so that it can
accept any collection of characters.
@c JP
註: R7RS @code{(scheme charset)}の@code{->char-set}
は文字列、文字集合、文字のいずれかのみを
引数に取ります。Gaucheでは文字の任意のコレクションを取るように拡張しました。
@c COMMON
@end defun

@node Character-set comparison, Character-set iteration, Character-set constructors, R7RS character sets
@subsubsection Character-set comparison
@c NODE 文字集合の比較

@defun char-set= char-set1 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns @code{#t} iff all the character sets have exactly the
same members.
@c JP
与えられた文字集合が全て同じ要素を持っている場合に限り@code{#t}を返します。
@c COMMON

@example
(char-set=)  @result{} #t
(char-set= (char-set)) @result{} #t
(char-set= (string->char-set "cba")
           (list->char-set #\a #\b #\c))
  @result{} #t
@end example

@end defun

@defun char-set<= char-set1 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns @code{#t} iff every char-set argument is a subset of
the following char-sets.  If no arguments are given, @code{#t} is returned.
@c JP
各char-set引数がそれ以降のchar-setの部分集合になっている場合に限り@code{#t}を返します。
引数が無い場合は@code{#t}を返します。
@c COMMON
@end defun

@defun char-set-hash char-set :optional bound
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a non-negative exact integer as a hash value of @var{char-set}.
If optional @var{bound} argument is given, it must be a positive integer
that limits the range of the hash value, which will fall between
0 to @code{(- bound 1)}, inclusive.
@c JP
@var{char-set}のハッシュ値を非負の正確な整数で返します。@var{bound}が与えられた場合、
それは正の正確な整数でなければならず、戻り値は0から@code{(- bound 1)}まで(両端含む)の
値を取ります。
@c COMMON
@end defun

@node Character-set iteration, Character-set query, Character-set comparison, R7RS character sets
@subsubsection Character-set iteration
@c NODE 文字集合のイテレーション

@defun char-set-cursor char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns an object that can point to a first character within @var{char-set}
(here, `first' merely means the beginning of iteration; the order of
iteration is implementation-dependent and you can't assume a specific
order).
The caller must treat the return value as an opaque object; it can only
be used to pass as the @var{cursor} argument of @code{char-set-ref},
@code{char-set-cursor-next} and @code{end-of-char-set?}.
@c JP
@var{char-set}中の最初の文字を指すオブジェクトを返します。
(ここでの「最初」は文字集合を順にたどってゆく際の最初ということです。
文字集合をたどる順は実装依存で、特定の順序を当てにしないようにしてください。)
返されたオブジェクトは、そのまま@code{char-set-ref}、
@code{char-set-cursor-next}、@code{end-of-char-set?}の@var{cursor}引数に
渡す以外に使ってはいけません。
@c COMMON
@end defun

@defun char-set-ref char-set cursor
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character in @var{char-set} pointed by @var{cursor}.

The @var{cursor} argument must be an object returned from
@code{char-set-cursor} or @code{char-set-cursor-next} with @var{char-set}.
The behavior is undefined if @var{cursor} is not a cursor
created from @var{char-set}.
@c JP
@var{char-set}中の、@var{cursor}に指された文字を返します。

@var{cursor}は@code{char-set-cursor}か@code{char-set-cursor-next}によって
@var{char-set}から作られたオブジェクトでなければなりません。
@var{cursor}が@var{char-set}から作られたものでない場合の動作は未定義です。
@c COMMON
@end defun

@defun char-set-cursor-next char-set cursor
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a new cursor for the next character pointed by @var{cursor}
within @var{char-set}.

The @var{cursor} argument must be an object returned from
@code{char-set-cursor} or @code{char-set-cursor-next} with @var{char-set}.
The behavior is undefined if @var{cursor} is not a cursor
created from @var{char-set}.
@c JP
@var{char-set}中の、@var{cursor}が指している文字の次の文字を指す新たなカーソルを返します。

@var{cursor}は@code{char-set-cursor}か@code{char-set-cursor-next}によって
@var{char-set}から作られたオブジェクトでなければなりません。
@var{cursor}が@var{char-set}から作られたものでない場合の動作は未定義です。
@c COMMON
@end defun

@defun end-of-char-set? cursor
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns @code{#t} iff @var{cursor} points to the end of the charset.
@c JP
@var{cursor}が文字集合の終端を指していたら@code{#t}を、そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@defun char-set-fold kons knil char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
Iterate over all characters in @var{char-set}, calling the procedure @var{kons}
with a character and the seed value.  The return value of @var{kons} becomes
the next seed value, while @var{knil} gives the first seed value.
Returns the last seed value.  The order of traversal isn't specified.
@c JP
@var{char-set}中の全ての文字について、手続き@var{kons}を、文字とシード値を引数にして
呼び出します。@var{knil}が最初のシード値を与え、@var{kons}の戻り値が次のシード値となります。
最後のシード値が@code{char-set-fold}の戻り値となります。
文字を取り出す順番は規定されていません。
@c COMMON
@end defun

@defun char-set-unfold pred fun gen seed :optional base-char-set
@defunx char-set-unfold! pred fun gen seed base-char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
Build a character set by calling @var{fun} on the seed value repeatedly.
For each iteration, first @var{pred} is applied to the current seed value.
If it returns true, a character set that gathers characters generated so far
is returned.  Otherwise, @var{fun} is called on the seed value,
which must return a character.  Then @var{gen} is called on the seed value
to obtain the next seed value.

If @var{base-char-set} is given, a union of it and the generated characters
is returned.
The linear-update version @code{char-set-unfold!} may modify @var{base-char-set}
to create the result.
@c JP
@var{fun}をシード値に適用して得られる文字から文字集合を作って返します。
繰り返しの度に、まず@var{pred}が現在のシード値に対して呼ばれ、それが真の値を返したら
繰り返しは終了で、それまで作られた文字を集めた集合が戻り値となります。
そうでなければ@var{fun}がシード値を引数として呼ばれ、文字を返します。
次に@var{gen}がシード値を引数として呼ばれ、次のシード値を作ります。

@var{base-char-set}が与えられた場合は、それと生成された文字との和集合が返されます。
線形更新バージョンである@code{char-set-unfold!}は、@var{base-char-set}を破壊的に
再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-for-each proc char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
Applies @var{proc} on each character in @var{char-set}.  The return value
of @var{proc} is discarded.  Returns undefined value.
@c JP
@var{proc}を@var{char-set}中のそれぞれの文字に適用します。
@var{proc}の戻り値は捨てられます。この手続きの戻り値は規定されません。
@c COMMON
@end defun

@defun char-set-map proc char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
Applies @var{proc} on each character in @var{char-set}, which must
return a character.  Returns a new charset consists of the characters
returned from @var{proc}.
@c JP
@var{proc}を@var{char-set}中のそれぞれの文字に適用します。
@var{proc}の戻り値は文字でなければなりません。@var{proc}の戻り値の文字を集めた
新たな文字集合を返します。
@c COMMON
@end defun

@node Character-set query, Character-set algebra, Character-set iteration, R7RS character sets
@subsubsection Character-set query
@c NODE 文字集合への問い合わせ

@defun char-set-every pred char-set
@defunx char-set-any pred char-set
@defunx char-set-count pred char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
These procedures apply @var{pred} to each character in @var{char-set}.

@code{char-set-every} returns @code{#f} as soon as @var{pred} returns
@code{#f}.  Otherwise, it returns the result of the last application of
@var{pred}.

@code{char-set-any} returns as soon as @var{pred} returns a true value,
and the return value is the one @var{pred} returns.
If @var{pred} returns @code{#f} for all characters, @code{#f} is returned.

@code{char-set-count} returns the number of times
@var{pred} returns a true value.

Note that @var{char-set} can be huge (e.g. a complement of small char-set),
which can make these procedures take very long.
@c JP
これらの手続きは、@var{pred}を@var{char-set}に含まれる各文字に適用します。

@code{char-set-every}は@var{pred}が@code{#f}を返したら直ちに@code{#f}を返します。
@var{pred}が最後まで@code{#f}を返さなかった場合は、最後の@var{pred}の返り値が
@code{char-set-every}の返り値となります。

@code{char-set-any}は@var{pred}が真の値を返した場合に直ちにその値を返します。
@var{pred}が最後まで@code{#f}を返した場合には@code{#f}を返します。

@code{char-set-count}は@var{pred}が真の値を返した回数を返します。

@var{char-set}は非常に大きくなる可能性があり (例えばごく小さな文字集合の補集合)、
その場合、これらの手続きは非常に長くかかり得ることに注意してください。
@c COMMON
@end defun

@defun char-set->list char-set
@defunx char-set->string char-set
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a list of each character, or a string consisting of
each character, in @var{char-set}, respectively.
Be careful to apply this on a large char set.
@c JP
@var{char-set}に含まれる文字をリストあるいは文字列にして返します。
大きな文字集合に適用する場合は注意してください。
@c COMMON
@end defun


@node Character-set algebra,  , Character-set query, R7RS character sets
@subsubsection Character-set algebra
@c NODE 文字集合に適用できる代数的関数

@defun char-set-adjoin char-set char1 @dots{}
@defunx char-set-adjoin! char-set char1 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character set that adds @var{char1} @dots{} to
@var{char-set}.

The linear update version @code{char-set-adjoin!} may modify
@var{char-set}.
@c JP
@var{char-set}に@var{char1} @dots{}を加えた文字集合を返します。

線形更新版の@code{char-set-adjon!}は@var{char-set}引数を破壊的に再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-delete char-set char1 @dots{}
@defunx char-set-delete! char-set char1 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character set that removes @var{char1} @dots{} from @var{char-set}.
It is noop if @var{char-set} doesn't have @var{char1} @dots{}.

The linear update version @code{char-set-delete!} may modify
@var{char-set}.
@c JP
@var{char-set}から@var{char1} @dots{}を除いた文字集合を返します。
@var{char1} @dots{}が@var{char-set}に含まれている必要はありません。

線形更新版の@code{char-set-delete!}は@var{char-set}引数を破壊的に再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-union char-set @dots{}
@defunx char-set-union! char-set1 char-set2 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character set of all characters in any one of
@var{char-set} @dots{}.
Without arguments, returns an empty charset.

The linear update version @code{char-set-union!} may modify
@var{char-set1}.
@c JP
@var{char-set} @dots{}内の少なくともひとつに含まれる文字の文字集合を返します。
引数が無ければ空の文字集合を返します。

線形更新版の@code{char-set-union!}は@var{char-set1}引数を破壊的に再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-intersection char-set @dots{}
@defunx char-set-intersection! char-set1 char-set2 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character set of every character that
is in all of @var{char-set} @dots{}.
Without arguments, returns @code{char-set:full}.

The linear update version @code{char-set-intersection!} may modify
@var{char-set1}.
@c JP
@var{char-set} @dots{}の全てに共通して含まれる文字の文字集合を返します。
引数が無ければ@code{char-set:full}を返します。

線形更新版の@code{char-set-intersection!}は@var{char-set1}引数を破壊的に再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-difference char-set1 char-set2 @dots{}
@defunx char-set-difference! char-set1 char-set2 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns a character set of every character that is in @var{char-set1}
but not in any of @var{char-set2} @dots{}.

The linear update version @code{char-set-difference!} may modify
@var{char-set1}.
@c JP
@var{char-set1}に含まれ、しかし@code{char-set2} @dots{}のどれにも含まれない文字の文字集合を返します。

線形更新版の@code{char-set-difference!}は@var{char-set1}引数を破壊的に再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-xor char-set @dots{}
@defunx char-set-xor! char-set1 char-set2 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
With zero arguments, returns an empty charset.
With one argument, it is returned as is.
With two arguments, returns a character set of every character that
is in either one of two sets, but not in both.
With more than two arguments, it returns
@code{(char-set-xor (char-set-xor set1 set2) set3 @dots{})}.

The linear update version @code{char-set-xor!} may modify
@var{char-set1}.
@c JP
引数がない場合は空の文字集合を、引数が一つの場合はそれをそのまま返します。
引数が二つの場合、そのどちらか一方に含まれるが両方には含まれない文字の文字集合を返します。
引数が三つ以上の場合は@code{(char-set-xor (char-set-xor set1 set2) set3 @dots{})}を
返します。

線形更新版の@code{char-set-xor!}は@var{char-set1}引数を破壊的に再利用するかもしれません。
@c COMMON
@end defun

@defun char-set-diff+intersection char-set1 char-set2 @dots{}
@defunx char-set-diff+intersection! char-set1 char-set2 char-set3 @dots{}
[R7RS charset]
@c MOD scheme.charset
@c EN
Returns two values, the result of
@code{(char-set-difference char-set1 char-set2 @dots{}} and the result of
@code{(char-set-intersection char-set1 char-set2 @dots{}}.
@c JP
@code{(char-set-difference char-set1 char-set2 @dots{}}の結果と
@code{(char-set-intersection char-set1 char-set2 @dots{}}の結果の
二つの値を返します。
@c COMMON
@end defun


@node R7RS hash tables, R7RS immutable lists, R7RS character sets, R7RS large
@subsection @code{scheme.hash-table} - R7RS hash tables
@c NODE R7RSハッシュテーブル, @code{scheme.hash-table} - R7RSハッシュテーブル

@deftp {Module} scheme.hash-table
@mdindex scheme.hash-table
@c EN
This module provides hash table library, originally defined as @code{srfi-125}.

Hash table provided with this module is the same as Gauche's built-in
hash table.  However, srfi-125 introduces procedures that conflict
with Gauche's original procedures, so Gauche provides those procedures
built-in but under aliases.
@xref{Hashtables}, for the built-in hash table procedures.

With this module, procedures are provided as defined in R7RS.  Use this
module when you're writing portable code.
@c JP
このモジュールは、元々@code{srfi-125}で定義されていたハッシュテーブルのライブラリです。

このモジュールで提供されるハッシュテーブルはGaucheの組み込みハッシュテーブルそのものです。
ただ、srfi-125はいくつか、Gaucheの元々持っていた手続きと名前が衝突する手続きを
定義しています。Gaucheはそれらの手続きに関しては異なる名前で組み込み手続きを
用意しています。組み込みのハッシュテーブル手続きについては
@ref{Hashtables}を参照してください。

このモジュールを使うと、手続きはR7RSで定義されたとおりの動作になります。
ポータブルなコードを書く際にこのモジュールを使うと良いでしょう。
@c COMMON

@c EN
Srfi-125 also defines compatibility procedures with srfi-69, although saying
they're deprecated.  Those deprecated procedures are supported in this
module, too.
@c JP
srfi-125はまた、srfi-69で定義されたいくつかの手続きを、非推奨ながら
互換性のためにサポートしています。これらの非推奨手続きも
このモジュールで提供されます。
@c COMMON

@c EN
The following procedures are the same as Gauche's built-in.
@c JP
以下の手続きはGaucheの組み込みと同じです。
@c COMMON
@example
hash-table?         hash-table-contains? hash-table-exists?  
hash-table-empty?   hash-table=?         hash-table-mutable? 
hash-table-ref      hash-table-ref/default
hash-table-set!     hash-table-update!/default
hash-table-clear!   hash-table-size   hash-table-keys
hash-table-values   hash-table-copy   hash-table-empty-copy
hash-table->alist   hash-table-union! hash-table-intersection!
hash-table-difference!                hash-table-xor!
@end example

@c EN
@xref{Hashtables}, for the description of those procedures.
@c JP
これらの手続きの説明は@ref{Hashtables}を参照してください。
@c COMMON

@c EN
The following procedures are also provided as Gauche's built-in,
but with @code{-r7} suffix.
@c JP
以下の手続きは、Gaucheの組み込みでは@code{-r7}サフィックスをつけた名前で
提供されています。
@c COMMON
@example
hash-table         hash-table-delete! hash-table-intern!
hash-table-update! hash-table-pop!    hash-table-find
hash-table-count   hash-table-map     hash-table-for-each
hash-table-map!    hash-table-map->list
hash-table-prune!
@end example
@end deftp

@defun make-hash-table comparator arg @dots{}
@defunx make-hash-table equal-proc hash-proc arg @dots{}
[R7RS hash-table]
@c MOD scheme.hash-table
@c EN
This enhances built-in @code{make-hash-table} with the second form,
that takes two procedures instead of one comparator, as srfi-69.

In the srfi-69 form, @var{equal-proc} is a procedure taking two keys
to see if they are the same, and @var{hash-proc} is a procedure taking
a key to calculate its hash value (nonnegative fixnum).
The compatibility form is deprecated and should be avoided in the new code.

The optional @var{arg} @var{dots} are implementation-dependent,
and specify various properties of the created hash table.
They are ignored in Gauche.
@c JP
この手続きは、組み込みの@code{make-hash-table}を拡張して二番目の形式を許したものです。
二番目の形式は比較器のかわりに二つの手続きをとるもので、srfi-69互換です。

srfi-69互換形式では、@var{equal-proc}はふたつのキーを取りそれが等しいかどうかを
返す述語、@var{hash-proc}は一つのキーを取りそのハッシュ値を非負の正確な整数で
返す手続きです。
この互換係式は非推奨で、新たなコードでは使うべきではありません。

省略可能な@var{arg} @var{dots}引数は実装依存で、作られるハッシュテーブルの
様々な特性を指定するものです。Gaucheでは無視されます。
@c COMMON
@end defun

@defun hash-table cmpr key value @dots{}
[R7RS hash-table]
@c MOD scheme.hash-table
@c EN
This is the same as built-in @code{hash-table-r7} (@pxref{Hashtables}).

Construct a new hash table with key-comparator @var{cmpr}.  It is
populated by @var{key} @var{value} @dots{}, which is a list with
keys and values appear alternatively.  It is an error if the length
of key-value list is not even.

Note that srfi-125 defines this procedure to return an immutable
hash table if the implementation supports one.  Gauche doesn't provide
immutable hash tables (we do have immutable map
instead, @pxref{Immutable map}), but when you're writing a portable
program, be careful not to modify the table returned by this procedure.
@c JP
これは組み込みの@code{hash-table-r7}と同じです(@ref{Hashtables}参照)。

キーの比較とハッシュに比較器@var{cmpr}を使う新たなハッシュテーブルを作って返します。
また、ハッシュテーブルの内容は@var{key} @var{value} @dots{}によって初期化されます。
ここで引数はキーと値が交互に並んだものです。@var{key} @var{value} @dots{}部分の
長さが偶数でなければエラーが投げられます。

srfi-125では、この手続きは(実装がサポートしていれば)変更不可なハッシュテーブルを
返すと規定されています。Gaucheは変更不可なハッシュテーブルを持っていないので、
変更可能なハッシュテーブルが返りますが、ポータブルなコードを書く際には
返されたテーブルを変更しないようにしてください。
なお、Gaucheも変更不可なマップは持っています (@ref{Immutable map}参照)。
@c COMMON
@end defun

@defun alist->hash-table alist cmpr arg @dots{}
@defunx alist->hash-table alist equal-proc hash-proc cmpr arg @dots{}
[R7RS hash-table]
@c MOD scheme.hash-table
@c EN
This enhances built-in @code{alist->hash-table} with the second form,
that takes two procedures instead of one comparator, as srfi-69.

In the srfi-69 form, @var{equal-proc} is a procedure taking two keys
to see if they are the same, and @var{hash-proc} is a procedure taking
a key to calculate its hash value (nonnegative fixnum).
The compatibility form is deprecated and should be avoided in the new code.

The optional @var{arg} @var{dots} are implementation-dependent,
and specify various properties of the created hash table.
They are ignored in Gauche.
@c JP
この手続きは、組み込みの@code{alist->hash-table}を拡張して二番目の形式を許したものです。
二番目の形式は比較器のかわりに二つの手続きをとるもので、srfi-69互換です。

srfi-69互換形式では、@var{equal-proc}はふたつのキーを取りそれが等しいかどうかを
返す述語、@var{hash-proc}は一つのキーを取りそのハッシュ値を非負の正確な整数で
返す手続きです。
この互換係式は非推奨で、新たなコードでは使うべきではありません。

省略可能な@var{arg} @var{dots}引数は実装依存で、作られるハッシュテーブルの
様々な特性を指定するものです。Gaucheでは無視されます。
@c COMMON
@end defun

@defun hash-table-unfold p f g seed comparator :optional arg @dots{}
[R7RS hash-table]
@c MOD scheme.hash-table
@c EN
Same as Gauche's built-in @code{hash-table-unfold}, except that this
allows optional arguments, which are ignored.  They are
implementation-specific parameters to tune the created hash tables.
@xref{Hashtables}, for the detailed description.
@c JP
省略可能な@var{arg} @dots{}を許すことを除いて、
Gauche組み込みの@code{hash-table-unfold}と同じです。
@var{arg} @dots{}は作られるテーブルのパラメータを与える実装依存な引数で、
Gaucheでは今のところ無視されます。
詳しくは@ref{Hashtables}を参照してください。
@c COMMON
@end defun


@defun hash-table-delete! ht key @dots{}
[R7RS hash-table]
@c MOD scheme.hash-table
@c EN
This is the same as built-in @code{hash-table-delete!-r7}.

Deletes entries associated with the given @var{key}s from the
table @var{ht}.  It is ok if @var{ht} doesn't have @var{key}.
Returns the number of entries that are actually deleted.

It differs from built-in @code{hash-table-delete!} in two points:
The built-in one can take exactly one @var{key}, and returns
a boolean indicating if the entry is actually deleted.
@c JP
これは組み込みの@code{hash-table-delete!-r7}と同じです。

ハッシュテーブル@var{ht}から、@var{key} @dots{}を持つエントリを削除します。
@var{ht}が@var{key}を持っていなくてもエラーにはなりません。
実際に削除されたエントリの数を返します。

組み込みの@code{hash-table-delete!}と違うのは次の2点です。
組み込みはkeyをひとつしか取らず、そえが実際に削除されたかどうかをブール値で返します。
@c COMMON
@end defun

@defun hash-table-intern! ht key failure
[R7RS hash-table]
@c MOD scheme.hash-table
@c EN
This is the same as built-in @code{hash-table-intern!-r7}.

Search @var{key} in @var{ht}.  If it is found, returns the associated
value.  If it is not found, call @var{failure} without artuments,
and insert a new entry associating @var{key} and the value
@var{failure} returns, and returns that new value.
@c JP
これは組み込みの@code{hash-table-intern!-r7}と同じです。

ハッシュテーブル@var{ht}からキー@var{key}を持つエントリを探し、
見つかった場合はその値を返します。見つからなかった場合は、手続き@var{failure}を
引数無しで呼び出し、その返り値を@var{key}に結びついた新たなエントリとして
@var{ht}に追加し、また@code{hash-table-intern!}の返り値とします。
@c COMMON
@end defun

@defun hash-table-update! ht key updater :optional failure success
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-update!-r7}.
It takes different optional arguments from built-in @code{hash-table-update!}.

@var{Updater} is a procedure that takes one argument,
@var{failure} is a thunk, and @var{success} is a procedure
that takes one argument.

Works the same as follows, except maybe more efficiently.
@example
(hash-table-set! ht key (updater (hash-table-ref ht key failure success)))
@end example
@end defun

@defun hash-table-pop! ht
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-pop!-r7}.
It is a completely different procedure as built-in @code{hash-table-pop!}.

Removes an arbitrary entry in the hash table @var{ht}, and
returns the removed entry's key and value as two values.

If @var{ht} is empty, an error is signalled.
@end defun

@defun hash-table-find proc ht failure
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-find-r7}.
It takes different arguments from built-in @code{hash-table-find}.

Calls @var{proc} with a key and a value of each entry in @var{ht},
until @var{proc} returns non-false value.  If @var{proc} returns
non-false value, @code{hash-table-find} immediately returns it.
If @var{proc} returns @code{#f} for all entries, calls a thunk
@var{failure} and returns its result.
@end defun

@defun hash-table-count ht
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-count-r7}.

Calls @var{proc} with a key and a value of each entry in @var{ht},
and returns the number of times when @var{proc} returned true.
@end defun

@defun hash-table-map proc cmpr ht
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-map-r7}.
This is different from built-in @code{hash-table-map}.

Creates a fresh hashtable with a key comparator @var{cmpr}, then
populate it by inserting the key and the result of applying @var{proc}
on the value of each entry in @var{ht}.
@end defun

@defun hash-table-map! proc ht
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-map!-r7}.

Calls @var{proc} on the value of each entry in @var{ht}, and update
the entry with the result of @var{proc}.
@end defun

@defun hash-table-map->list proc ht
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-map->list-r7},
and same as built-in @code{hash-table-map} (not the @code{scheme.hash-table}'s
@code{hash-table-map}) except the order of the arguments.

Apply @var{proc} on a key and a value of each entry in @var{ht},
in arbitrary order, and returns a list of results.
@end defun

@defun hash-table-for-each proc ht
@defunx hash-table-for-each ht proc
[R7RS hash-table]
@c MOD scheme.hash-table
Apply @var{proc} on a key and a value of each entry in @var{ht}.  The
result of @var{proc} is discarded.  Returns an unspecified value.

This procedure allows arguments in both order for the compatibility---
the first way is the @code{scheme.hash-table} recommended one,
which is the same as built-in @code{hash-table-for-each-r7},
and the latter way is compatible with srfi-69, which is
the same as built-in @code{hash-table-for-each}.

It is unfortunate that this compatibility thing is extremely confusing;
especially in Gauche, you can make anything applicable, so the distinction
between procedures and other objects is blurred.

We recommend that you stick to one way or another within a module; if
your module uses built-in interface, use @code{(hash-table-for-each ht proc)}.
If your module imports @code{scheme.hash-table},
use @code{(hash-table-for-each proc ht)}.
@end defun

@defun hash-table-fold proc seed ht
@defunx hash-table-fold ht proc seed
[R7RS hash-table]
@c MOD scheme.hash-table
The @var{proc} argument takes three arguments, a key, a value, and
the current seed value.  The procedure applies @var{proc} for
each entry in @var{ht}, using @var{seed} as the first seed value,
and using the previous result of @var{proc} as the subsequent seed value.
Returns the result of the last call of @var{seed}.

This procedure allows arguments in both order for the compatibility---
the first way is the @code{scheme.hash-table} recommended one,
which is the same as built-in @code{hash-table-fold-r7},
and the latter way is compatible with srfi-69, which is
the same as built-in @code{hash-table-fold}.

It is unfortunate that this compatibility thing is extremely confusing.
We recommend that you stick to one way or another within a module; if
your module uses built-in interface, use the second interface.
If your module imports @code{scheme.hash-table},
use the first interface.
@end defun

@defun hash-table-prune! proc ht
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as built-in @code{hash-table-prune!-r7}.

Apply @var{proc} on a key and a value of each entry in @var{ht},
and deletes the entry if @var{proc} returns a true value.
This procedure returns an unspecified value.
@end defun

@defun hash-table-merge! ht1 ht2
[R7RS hash-table]
@c MOD scheme.hash-table
This is the same as @code{hash-table-union!}, and provided just
for the compatibility with srfi-69.  Deprecated.
@end defun

@defun hash obj :optional ignore
@defunx string-hash obj :optional ignore
@defunx string-ci-hash obj :optional ignore
@defunx hash-by-identity obj :optional ignore
[R7RS hash-table]
@c MOD scheme.hash-table
Provided for the compatibility with srfi-69, and are deprecated.

The first three are the same as built-in @code{default-hash},
@code{string-hash}, and @code{string-ci-hash}, except that
these accept an optional second argument, which is ignored.
Note that @code{hash-by-identity} is also defined as the same
as @code{default-hash} except the ignored optional second argument,
per srfi-125, although the name suggests that it would work as if
@code{eq-hash}.

Do not use these procedures in the new code; you can use comparators
instead (@code{default-comparator}, @code{string-comparator},
@code{string-ci-comparator} and @code{eq-comparator},
@pxref{Predefined comparators}).   If you do need hash function,
you should still avoid @code{hash} and @code{hash-by-identity},
and use @code{default-hash} and @code{eq-hash} instead.
@end defun

@defun hash-table-equivalence-function ht
@defunx hash-table-hash-function ht
[R7RS hash-table]
@c MOD scheme.hash-table
Provided for the compatibility with srfi-69, and are deprecated.

Returns the equivalence function and hash function of a hash table @var{ht}.

For the introspection, we recommend to use
built-in @code{hash-table-comparator}.  (Unfortunately, it is not
included in @code{scheme.hash-table}, though.)
@end defun


@node R7RS immutable lists, R7RS random-access lists, R7RS hash tables, R7RS large
@subsection @code{scheme.ilist} - R7RS immutable lists
@c NODE R7RS変更不可リスト, @code{scheme.ilist} - R7RS変更不可リスト

@deftp {Module} scheme.ilist
@mdindex scheme.ilist
@findex proper-ilist?
@findex ilist?
@findex dotted-ilist?
@findex not-ipair?
@findex null-ilist?
@findex ilist=
@findex icar
@findex icdr
@findex icaar
@findex icadr
@findex icdar
@findex icddr
@findex icaaar
@findex icaadr
@findex icadar
@findex icaddr
@findex icdaar
@findex icdadr
@findex icddar
@findex icdddr
@findex icaaaar
@findex icaaadr
@findex icaadar
@findex icaaddr
@findex icadaar
@findex icadadr
@findex icaddar
@findex icadddr
@findex icdaaar
@findex icdaadr
@findex icdadar
@findex icdaddr
@findex icddaar
@findex icddadr
@findex icdddar
@findex icddddr
@findex icar+icdr
@findex ilist-ref
@findex ifirst
@findex isecond
@findex ithird
@findex ifourth
@findex ififth
@findex isixth
@findex iseventh
@findex ieighth
@findex ininth
@findex itenth
@findex idrop
@findex ilist-tail
@findex itake-right
@findex ilast
@findex last-ipair
@findex ilength
@findex icount
@findex ifor-each
@findex ifold
@findex ipair-fold
@findex ireduce
@findex ifold-right
@findex ipair-fold-right
@findex ireduce-right
@findex ipair-for-each
@findex imember
@findex imemv
@findex imemq
@findex ifind-tail
@findex iany
@findex ievery
@findex ilist-index
@findex idrop-while
@findex iassoc
@findex iassq
@findex iassv
@findex iapply
@findex make-ilist-comparator
@findex make-improper-ilist-comparator
@findex make-icar-comparator
@findex make-icdr-comparator
This module provides a set of procedures that handles immutable pairs
and lists.

The standard allows an implementation to have mutable pairs and immutable
pairs separately, so it defines immutable version of most @code{scheme.list}
procedures.   In Gauche, mutable pairs and immutable pairs are both
abstract ``pairs'', and all procedures that accesses pairs (without modifying
them) works seamlessly on both kind.

Consequently, the following procedures are just aliases of their
non-immutable versions (just remove @code{i} prefix from them).
Note that these procedures and variables in Gauche do not reject if the input is
mutable pairs/lists, but such usage may not be portable.

@example
proper-ilist?     ilist?            dotted-ilist?     not-ipair?
null-ilist?       ilist=
icar              icdr              icaar             icadr
icdar             icddr             icaaar            icaadr
icadar            icaddr            icdaar            icdadr
icddar            icdddr            icaaaar           icaaadr
icaadar           icaaddr           icadaar           icadadr
icaddar           icadddr           icdaaar           icdaadr
icdadar           icdaddr           icddaar           icddadr
icdddar           icddddr           icar+icdr         ilist-ref
ifirst            isecond           ithird            ifourth
ififth            isixth            iseventh          ieighth
ininth            itenth
idrop             ilist-tail        itake-right
ilast             last-ipair        ilength           icount
ifor-each         ifold             ipair-fold        ireduce
ifold-right       ipair-fold-right  ireduce-right     ipair-for-each
imember           imemv             imemq             ifind-tail
iany              ievery            ilist-index       idrop-while
iassoc            iassq             iassv             iapply
make-ilist-comparator               make-improper-ilist-comparator
make-icar-comparator                make-icdr-comparator
@end example
@end deftp

@node R7RS random-access lists, R7RS immutable deques, R7RS immutable lists, R7RS large
@subsection @code{scheme.rlist} - R7RS random-access lists
@c NODE R7RSランダムアクセスリスト, @code{scheme.rlist} - R7RSランダムアクセスリスト

@deftp {Module} scheme.rlist
@mdindex scheme.rlist
This module provides an alternative datatype for pairs and lists,
which are immutable and allows O(log n) random access, while
maintaining O(1) @code{car} and @code{cdr} operations.
This is originally defined as @code{srfi-101}.  We call this datatype
@emph{rlist} in the following explanation.

The srfi allows a Scheme implementation to adopt rlist
as the built-in pairs and lists, so the procedure names are
duplicated from the Scheme primitives.  If you use this module,
you might want to import with prefix
(e.g. @code{(use scheme.rlist :prefix rlist:)}).

In Gauche, we implement rlist on top of skew-list
(@pxref{Skew binary random-access lists}).  The main difference
is that skew-list only allows proper lists, while rlist allows
improper lists (the @code{cdr} of the last pair can be an arbitrary
objects).

However, having improper lists makes things a lot complicated.  If you just
need a list with fast random access, you want to use skew-list.
Use rlist only if you need to deal with improper lists.

The following procedures behave just like the built-in counterparts,
except they take/return rlists instead of ordinary pairs and lists.
(NB: @code{list-ref} and @code{list-tail} here doesn't take the optional
fallback argument, for they are Gauche's extension).

@example
pair?     cons       car        cdr
caar      cadr       cdar       cddr
caaar     caadr      cadar      caddr
cdaar     cdadr      cddar      cdddr
caaaar    caaadr     caadar     caaddr
cadaar    cadadr     caddar     cadddr
cdaaar    cdaadr     cdadar     cdaddr
cddaar    cddadr     cdddar     cddddr
null?     list?      list       make-list
length    append     reverse    list-tail
list-ref  map        for-each
@end example

This module also exports a syntax @code{quote}, which denotes
the literal rlist.  @code{(quote (a (b c)))} becomes a literal
rlist consists of elements @code{a}, and an rlist consists
of @code{b} and @code{c}.

Note that if you import @code{scheme.rlist} without suffix,
the shorthand notation @code{'(a (b c))} refers to @code{scheme.rlist#quote},
instead of built-in @code{quote}.
@end deftp

@defun list-set rlist k obj
Returns a new rlist which is the same as @var{rlist} except
that its @var{k}-th element is replaced with @var{obj}.
This is O(log n) operation where n is the length of @var{rlist}.
@end defun

@defun list-ref/update rlist k proc
Returns two values, the result of @code{(list-ref rlist k)}
and the result of @code{(list-set rlist k (proc (list-ref rlist k)))},
but may be more efficient.
@end defun

@defun random-access-list->linear-access-list rlist
Convert a proper rlist to an ordinary list.  An error is
thrown when @var{rlist} is not proper.
The conversion is only done in the ``spine'' of @var{rlist}; that is,
if @var{rlist} is nested, only the outermost @var{rlist} is converted.
@end defun

@defun linear-access-list->linear-access-list list
Convert a proper ordinary list to an rlist.
An error is thrown when @var{list} is not proper.
The conversion is only done in the ``spine'' of @var{list}; that is,
if @var{list} is nested, only the outermost @var{list} is converted.
@end defun


@node R7RS immutable deques, R7RS immutable texts, R7RS random-access lists, R7RS large
@subsection @code{scheme.ideque} - R7RS immutable deques
@c NODE R7RS変更不可な両端キュー, @code{scheme.ideque} - R7RS変更不可な両端キュー

@deftp {Module} scheme.ideque
@mdindex scheme.ideque
This module provides a functional double-ended queue
(deque, pronounced as ``deck''),
with amortized O(1) access of queue operations on either end.

It also serves as a convenient bidirectional list structures
in a sense that operations from the end of the list is just as
efficient as the ones from the front.

Note: If you don't need immutability and wants space-efficient
deque, you can also use @code{data.ring-buffer} as a deque
(@pxref{Ring buffer}).

This module was originally defined as @code{srfi-134}, then
became a part of R7RS large.

Gauche's @code{data.ideque} is a superset of this module.
@xref{Immutable deques}.
@end deftp

@defun ideque element @dots{}
[R7RS ideque]
@c MOD scheme.ideque
Returns an ideque with the given elements.
@end defun

@defun ideque-unfold p f g seed
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-unfold-right p f g seed
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-tabulate size init
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque? idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-empty? idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-add-front idq x
@defunx ideque-add-back idq x
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-front idq
@defunx ideque-back idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-remove-front idq
@defunx ideque-remove-back idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-reverse idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque= idq idq2 @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-ref idq n
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-take idq n
@defunx ideque-take-right idq n
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-drop idq n
@defunx ideque-drop-right idq n
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-split-at idq n
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-length idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-append idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-zip idq idq2 @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-map proc idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-filter-map proc idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-for-each proc idq @dots{}
@defunx ideque-for-each-right proc idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-fold proc knil idq @dots{}
@defunx ideque-fold-right proc knil idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-append-map proc idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-filter pred idq
@defunx ideque-remove pred idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-partition pred idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-find pred idq :optional failure
@defunx ideque-find-right pred idq :optional failure
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-take-while pred idq
@defunx ideque-take-while-right pred idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-drop-while pred idq
@defunx ideque-drop-while-right pred idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-span pred idq
@defunx ideque-break pred idq
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque-any pred idq @dots{}
@defunx ideque-every pred idq @dots{}
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque->list idq
@defunx list->ideque list
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@defun ideque->generator idq
@defunx generator->ideque gen
[R7RS ideque]
@c MOD scheme.ideque
@end defun

@node R7RS immutable texts, R7RS generators, R7RS immutable deques, R7RS large
@subsection @code{scheme.text} - R7RS immutable texts
@c NODE R7RS変更不可なテキスト, @code{scheme.text} - R7RS変更不可なテキスト

@deftp {Module} scheme.text
@mdindex scheme.text
This module provides @emph{text} type, an immutable string
with O(1) random access.  This is originally defined in srfi-135.

In Gauche, a string with index access generally takes O(n); however,
if the string is ASCII-only or you precalculate string indexes,
index access becomes O(1) (@pxref{String indexing}).
So, a text in Gauche is just an immutable indexed string.  It satisfies
@code{string?}, too.

Note that, in Gauche, text is not disjoint from string, so @emph{textual}
type is just a string type, and many @code{textual-*} procedures are
just aliases to the corresponding @code{string-*} procedures.
Use this module if you need portability.
@end deftp

@defun text? obj
[R7RS text]
@c MOD scheme.text
Returns @code{#t} iff @var{obj} is a text, which is an immutable
indexed string in Gauche.  Note that a text type is not disjoint
from a string in Gauche.
@end defun

@defun textual? obj
[R7RS text]
@c MOD scheme.text
Returns @code{#t} iff @var{obj} is either a text or a string.
In Gauche, this is just an alias of @code{string?}.
@end defun

@defun textual-null? obj
[R7RS text]
@c MOD scheme.text
Returns @code{#t} iff @var{obj} is an empty string/text.  In Gauche
this is just an alias of @code{string-null?}.
@end defun

@defun textual-every pred textual :optional start end
@defunx textual-any pred textual :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun make-text len char
[R7RS text]
@c MOD scheme.text
In Gauche it is same as @code{make-string}, except that the returned
string is immutable and indexed, and you can't omit @var{char}.
@end defun

@defun text char @dots{}
[R7RS text]
@c MOD scheme.text
Like @code{string}, but returned string is immutable and indexed.
@end defun

@defun text-tabulate proc len
[R7RS text]
@c MOD scheme.text
Like @code{string-tabulate}, but returned string is immutable and indexed
(@pxref{String constructors}).
@end defun

@defun text-unfold p f g seed :optional base make-final
@defunx text-unfold-right p f g seed :optional base make-final
[R7RS text]
@c MOD scheme.text
Like @code{string-unfold} and @code{string-unfold-right},
but returned string is immutable and indexed
(@pxref{String constructors}).  The mapper procedure @var{f} may return
a string instead of a character.
@end defun

@defun text-length text
[R7RS text]
@c MOD scheme.text
@end defun

@defun text-ref text index
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-length textual
@defunx textual-ref textual index
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual->text textual
[R7RS text]
@c MOD scheme.text
Takes a string, and returns an immutable, indexed string of the same
content.  If @var{textual} is already a such string, it is returned as is.
@end defun

@defun textual->string textual :optional start end
@defunx textual->vector textual :optional start end
@defunx textual->list textual :optional start end
[R7RS text]
@c MOD scheme.text
Converts a textual to a fresh mutable string,
a vector and a list, respectively.
These are aliases of @code{string-copy}, @code{string->vector}
and @code{string->list} in Gauche.
@end defun

@defun string->text string :optional start end
@defunx vector->text char-vector :optional start end
@defunx list->text char-list :optional start end
[R7RS text]
@c MOD scheme.text
Convert a string, a vector of characters, and a list of characters
to an immutable indexed string.
If an immutable indexed string is given to @code{string->text} without
start/end arguments, the input is returned as is.
@end defun

@defun reverse-list->text char-list
[R7RS text]
@c MOD scheme.text
Same as @code{(list->text (reverse char-list))} but maybe more efficient.
@end defun

@defun textual->utf8 textual :optional start end
[R7RS text]
@c MOD scheme.text
Returns a bytevector that contains utf8 encoding of the input
textual.  In Gauche, it is the same as @code{string->utf8}
(@pxref{Unicode transfer encodings}).
@end defun

@defun textual->utf16 textual :optional start end
[R7RS text]
@c MOD scheme.text
Returns a bytevector that contains utf16 encoding of the input
textual, with BOM attached, and in the native byteorder.
In Gauche, it is the same as
@code{(string->utf16 textual (native-endian) #t [start end])}
(@pxref{Unicode transfer encodings}).
@end defun

@defun textual->utf16be textual :optional start end
@defunx textual->utf16le textual :optional start end
[R7RS text]
@c MOD scheme.text
Returns a bytevector that contains utf16be and utf16le encoding of the input
textual.  No BOM is attached.
In Gauche, they are the same as
@code{(string->utf16 textual 'big-endian #f [start end])} and
@code{(string->utf16 textual 'little-endian #t [start end])}
(@pxref{Unicode transfer encodings}).
@end defun

@defun utf8->text bytevector :optional start end
[R7RS text]
@c MOD scheme.text
Converts a utf8 octet sequence stored in @var{bytevector} to a text.
If the octet sequence begins with BOM sequence, it is interpreted
as a character U+FEFF.  Optional @var{start}/@var{end} arguments
limits the input range of @var{bytevector}.

If the input contains an invalid utf-8 sequence, and Gauche's native
encoding is utf-8, it is replaced by a unicode replacement character
U+FFFD.  (NB: Srfi-135 says it is an error.)
@end defun

@defun utf16->text bytevector :optional start end
@defunx utf16be->text bytevector :optional start end
@defunx utf16le->text bytevector :optional start end
[R7RS text]
Converts a utf16 octet sequence stored in @var{bytevector} to a text.
For @code{utf16->text}, the sequence may begin with BOM,
in which case it determines the endianness.
Otherwise, platform's native endianness is assumed.
Fro @code{utf16be->text} and @code{utf16le->text}, the input is
assumed to be in UTF16BE/UTF16LE respectively; if it begins with BOM
it is treated as a character U+FEFF.

Optional @var{start}/@var{end} arguments
limits the input range of @var{bytevector}.

If the length of input (@var{end} - @var{start}, if the range is limited)
isn't even, an error is thrown.

If the input contains an invalid utf-16 sequence (unpaired surrogates),
it is replaced by a unicode replacement character U+FFFD.
(NB: Srfi-135 says it is an error.)
@c MOD scheme.text
@end defun

@defun subtext text start end
@defunx subtextual textual start end
[R7RS text]
@c MOD scheme.text
Returns a text between @var{start}-th (inclusive) and @var{end}-th (exclusive)
characters in the input.
@end defun

@defun textual-copy textual :optional start end
[R7RS text]
@c MOD scheme.text
Returns a copy of @var{textual}, optionally limited between
@var{start}/@var{end}.

Srfi-135 specifies that even the input is a text, the returned one
must be freshly allocated.  In Gauche, string body is immutable anyway,
so it isn't a big deal.
@end defun

@defun textual-take textual nchars
@defunx textual-drop textual nchars
@defunx textual-take-right textual nchars
@defunx textual-drop-right textual nchars
@defunx textual-pad textual len :optional char start end
@defunx textual-pad-right textual len :optional char start end
@defunx textual-trim textual :optional pred start end
@defunx textual-trim-right textual :optional pred start end
@defunx textual-trim-both textual :optional pred start end
[R7RS text]
@c MOD scheme.text
In Gauche, these are the same as corresponding string operations
(@code{string-take}, @code{string-drop}, @code{string-take-right},
@code{string-drop-right}, @code{string-pad}, @code{string-pad-right},
@code{string-trim}, @code{string-tirm-right}, and @code{string-trim-both}),
except that the returned string is always immutable and indexed.
@xref{SRFI-13 String selection}, for these string procedures.
@end defun

@defun textual-replace textual1 textual2 start1 end1 :optional start2 end2
[R7RS text]
@c MOD scheme.text
In Gauche, this is same as @code{string-replace},
except that the returned string is always immutable and indexed.
@xref{SRFI-13 Other string operations}, for the details.
@end defun

@defun textual=? textual1 textual2 textual3 @dots{}
@defunx textual<? textual1 textual2 textual3 @dots{}
@defunx textual>? textual1 textual2 textual3 @dots{}
@defunx textual<=? textual1 textual2 textual3 @dots{}
@defunx textual>=? textual1 textual2 textual3 @dots{}
[R7RS text]
@c MOD scheme.text
In Gauche, these are just aliases of built-in
@code{string=?}, @code{string<?}, @code{string>?},
@code{string<=?} and @code{string>?}, respectively.
@xref{String comparison}, for the details.
@end defun

@defun textual-ci=? textual1 textual2 textual3 @dots{}
@defunx textual-ci<? textual1 textual2 textual3 @dots{}
@defunx textual-ci>? textual1 textual2 textual3 @dots{}
@defunx textual-ci<=? textual1 textual2 textual3 @dots{}
@defunx textual-ci>=? textual1 textual2 textual3 @dots{}
[R7RS text]
@c MOD scheme.text
In Gauche, these are just aliases of @emph{the unicode version} of
@code{string-ci=?}, @code{string-ci<?}, @code{string-ci>?},
@code{string-ci<=?} and @code{string-ci>?}, respectively.
@xref{Full string case conversion}, for the details.
@end defun

@defun textual-prefix-length textual1 textual2 :optional start1 end1 start2 end2
@defunx textual-suffix-length textual1 textual2 :optional start1 end1 start2 end2
@defunx textual-prefix? textual1 textual2 :optional start1 end1 start2 end2
@defunx textual-suffix? textual1 textual2 :optional start1 end1 start2 end2
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-index textual pred :optional start end
@defunx textual-index-right textual pred :optional start end
@defunx textual-skip textual pred :optional start end
@defunx textual-skip-right textual pred :optional start end
@defunx textual-contains textual1 textual2 :optional start1 end1 start2 end2
@defunx textual-contains-right textual1 textual2 :optional start1 end1 start2 end2
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-upcase textual
@defunx textual-downcase textual
@defunx textual-foldcase textual
@defunx textual-titlecase textual
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-append textual @dots{}
@defunx textual-concatenate textual-list
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-concatenate-reversse args :optional final-textual end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-join textual-list :optional delimiter grammar
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-fold kons knil textual :optional start end
@defunx textual-fold-right kons knil textual :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-map proc textural1 textural2 @dots{}
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-for-each proc textual1 textual2 @dots{}
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-map-index proc textual :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-for-each-index proc textual :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-count textual pred :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-filter pred textual :optional start end
@defunx textual-remove pred textual :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-replicate textual from to :optional start end
[R7RS text]
@c MOD scheme.text
@end defun

@defun textual-split textual delimiter :optional grammar limit start end
[R7RS text]
@c MOD scheme.text
Like @code{string-split}, except that the returned strings are all
immutable and indexed.  @xref{String utilities}, for the details.
@end defun


@node R7RS generators, R7RS lazy sequences, R7RS immutable texts, R7RS large
@subsection @code{scheme.generator} - R7RS generators
@c NODE R7RSジェネレータ, @code{scheme.generator} - R7RSジェネレータ

@deftp {Module} scheme.generator
@mdindex scheme.generator
@c EN
This module provides generators and accumulators.
They were first defined in srfi-121,
then enhanced in srfi-158, and finally
incorporated R7RS large as @code{(scheme generator)}.
@c JP
このモジュールは、ジェネレータとアキュムレータを提供します。
これらは最初にsrfi-121で定義され、srfi-158で拡張された後、
@code{(scheme generator)}としてR7RS largeに取り込まれました。
@c COMMON

@c EN
A generator is a thunk to generate a sequence of values, potentially
terminated by EOF.  Procedures to deal with generators are
provided by @code{gauche.generator}, which is a superset of srfi-121.
@xref{Generators}, for the details.
@c JP
ジェネレータは引数と取らない手続きで、呼ばれる度に値を次々に返し、
EOFを以って終端を示すものです。ジェネレータを扱う手続きは
srfi-121のスーパーセットである@code{gauche.generator}で提供されています。
詳しくは@ref{Generators}を参照してください。
@c COMMON

@c EN
An accumulator is an opposite of generators.
They are procedures
that work as consumers.  An accumulator takes one argument.
When non-eof value is given, the value is stored, and when EOF
is given, the accumulated value is returned.
How the values are accumulated depends on the accumulator.
@c JP
アキュムレータはジェネレータの反対で、値を消費する手続きと考えられます。
アキュムレータは一つの引数を取ります。EOF以外の値が与えられた場合は、
それが内部に何らかの形で蓄えられ、EOFが与えられた場合、
蓄えられた値が返されます。
どのように値が蓄えられるかは各アキュムレータに依存します。
@c COMMON

@c EN
Once EOF is given, the accumulator is ``finalized''.  Subsequent
EOF makes it return the same accumulated value.  It is undefined
if other values are passed after EOF is passed.
@c JP
一度EOFが与えられると、アキュムレータは終了状態になります。
その後何度EOFが与えられても同じ蓄積結果を返します。
終了状態になったアキュムレータにEOF以外の値を与えた場合の動作は未定義です。
@c COMMON

@c EN
The accumulator can be used to parameterize procedures that yield
aggregate objects.  Consider the following procedure, which
takes items from two generators and accumulate them alternatively.
(Note that @code{glet*} is Gauche's procedure but not in srfi-158).
@c JP
アキュムレータは、複合的なオブジェクトを生成する手続きで、
実際に生成される値の型をパラメタライズするのに使えます。
次の手続きを見てみましょう。これは二つのジェネレータから交互に値を取り、
それを蓄積して返す手続きです。
(@code{glet*}はGaucheの手続きですがsrfi-158には含まれていません。)
@c COMMON

@example
(define (intertwine acc gen1 gen2)
  (let loop ()
    (glet* ([a (gen1)]
            [b (gen2)])
      (acc a)
      (acc b)
      (loop)))
  (acc (eof-object)))
@end example

@c EN
The procedure can return various type of collections, without
knowing the actual type---the passed accumulator determines it.
@c JP
この手続きは具体的に返される値が何かは関知しません。
それは引数に与えられたアキュムレータにより決定されます。
@c COMMON

@example
(intertwine (list-accumulator) (giota 5) (giota 5 100))
  @result{} (0 100 1 101 2 102 3 103 4 104)
(intertwine (vector-accumulator) (giota 5) (giota 5 100))
  @result{} #(0 100 1 101 2 102 3 103 4 104)
(intertwine (bytevector-accumulator) (giota 5) (giota 5 100))
  @result{} #u8(0 100 1 101 2 102 3 103 4 104)
@end example

@c EN
Note: In Gauche, you can also use classes to parameterize returned
container types (e.g. @code{map-to}),
for many collection classes support @emph{builder protocol}.
@xref{Collection framework}, for the details.
Accumulator has the flexibility that you can provide more than one
ways to construct return value on the same type (e.g. forward and reverse
list).
@c JP
註: Gaucheでは、クラスを使うことで戻り値となるコンテナの型をパラメタライズできます
(例: @code{map-to})。これは多くのコレクションクラスが@emph{builderプロトコル}を
サポートしているからです。詳しくは@ref{Collection framework}を見てください。
アキュムレータの利点は、同じ型の戻り値についても、異なる値の蓄積方法
(例えばリストを順に蓄積するか逆順に蓄積するか、等)を提供できることです。
@c COMMON
@end deftp

@c EN
The following generator procedures are explained in
@code{gauche.generator} section (@pxref{Generators}):
@c JP
以下のジェネレータ手続きは、@code{gauche.generator}のセクションで
解説してあります(@ref{Generators}参照)。
@c COMMON

@itemize
@item @ref{Generator constructors}:
@example
generator                circular-generator       make-iota-generator
make-range-generator     make-coroutine-generator
make-unfold-generator    make-for-each-generator
list->generator
vector->generator        reverse-vector->generator
string->generator        bytevector->generator
@end example
@item @ref{Generator operations}:
@example
gcons*                   gappend                  gflatten
ggroup                   gmerge                   gmap
gcombine                 gfilter                  gremove
gstate-filter            ggroup
gtake                    gdrop                    gtake-while
gdrop-while              gdelete                  gdelete-neighbor-dups
gindex                   gselect
@end example
@item @ref{Generator consumers}:
@example
generator->list         generator->reverse-list   generator-map->list
generator->vector       generator->vector!        generator->string
generator-count         generator-any             generator-every
generator-unfold
@end example
@item @ref{Folding generated values}:
@example
generator-fold          generator-for-each        generator-find
@end example
@end itemize

@c EN
The following are accumulator procedures:
@c JP
以下はアキュムレータ手続きです。
@c COMMON

@defun make-accumulator kons knil finalizer
[R7RS generator]
@c MOD scheme.generator
@c EN
Creates and returns an accumulator with a state,
whose initial value is @var{knil}.
When non-EOF value @var{v} is passed to the accumulator,
@var{kons} is called as @code{(kons v state)}, and its result
becomes the new state value.  When EOF value is passed,
@code{(finalizer state)} is called and its result becomes
the result of accumulator.
@c JP
内部状態をひとつ持つアキュムレータを作って返します。
状態は@var{khil}で初期化されます。
EOFでない値@var{v}がアキュムレータに与えられる度に、手続き@var{kons}が
@code{(kons v state)}と呼ばれ、その戻り値が新たな状態となります。
EOFがアキュムレータに渡されると、@code{(finalizer state)}が呼ばれ、
その結果がアキュムレータの戻り値となります。
@c COMMON
@end defun

@defun list-accumulator
@defunx reverse-list-accumulator
[R7RS generator]
@c MOD scheme.generator
@c EN
Creates and returns accumulators that return accumulated value
as a list, in the accumulated order (@code{list-accumulator})
or the reverse order (@code{reverse-list-accumulator}).
@c JP
蓄積された値をリストとして返すアキュムレータを作って返します。
@code{list-accumulator}ではリストは与えられた順に、
@code{reverse-list-accumulator}では逆順になります。
@c COMMON
@end defun

@defun vector-accumulator
@defunx reverse-vector-accumulator
@defunx bytevector-accumulator
[R7RS generator]
@c MOD scheme.generator
@c EN
Returns accumulators that return accumulated value
as a fresh vector or bytevector (u8vector),
in the accumulated order (@code{vector-accumulator},
@code{bytevector-accumulator})
or the reverse order (@code{reverse-vector-accumulator}).
There's no @code{reverse-bytevector-accumulator}.
@c JP
蓄積された値をベクタあるいはバイトベクタ(u8vector)として返すアキュムレータを
作って返します。@code{vector-accumulator}と
@code{bytevector-accumulator}では値は先頭から順に、
@code{reverse-vector-accumulator}ではベクタの最後から逆順に詰められます。
@code{reverse-bytevector-accumulator}はありません。
@c COMMON
@end defun

@defun vector-accumulator! vec at
@defunx bytevector-accumulator! bvec at
[R7RS generator]
@c MOD scheme.generator
@c EN
The @var{vec} or @var{bvec} argument is a mutable vector or
bytevector (u8vector), and is used as a buffer.

Returns an accumulator that stores the accumulated values in the
buffer, starting from the index @var{at}.
It is an error if the accumulator gets more values after
the buffer reaches at the end.

Once EOF is passed to the accumulator, @var{vec} or @var{bvec}
is returned, respectively.
@c JP
@var{vec}と@var{bvec}はそれぞれ変更可能なベクタとバイトベクタ(u8vector)です。
この引数はバッファとして使われます。

与えられた値を、バッファのインデックス@var{at}から順に格納してゆくアキュムレータを
作って返します。バッファの最後を越えて値を格納しようとした場合はエラーになります。

EOFが与えられたら、@var{vec}または@var{bvec}をそのまま返します。
@c COMMON
@end defun

@defun string-accumulator
[R7RS generator]
@c MOD scheme.generator
@c EN
Returns an accumulator that accepts characters and accumulates
them to a string.
@c JP
文字を受け取り、それを蓄積して最後に文字列として返すアキュムレータを生成して返します。
@c COMMON
@end defun

@defun sum-accumulator
@defunx product-accumulator
@defunx count-accumulator
[R7RS generator]
@c MOD scheme.generator
@c EN
Returns accumulators that yield a scalar value.

The accumulator created by @code{sum-accumulator} and
@code{product-accumulator} accepts numbers,
and keep adding or multiplying it with the accumulated value
(the default value is 0 and 1, respectively).

The accumulator created by @code{count-accumulator} accepts any
objects and just counting it.
@c JP
スカラー値を生成するアキュムレータを作って返します。

@code{sum-accumulator}と@code{product-accumulator}で作られた
アキュムレータはそれぞれ、
数値を受け取り、それを蓄積された値に加算または乗算してゆきます。
値の初期値はそれぞれ0と1です。

@code{count-accumulator}で作られたアキュムレータは
任意のオブジェクトを受け取ります。
EOFを受け取ったらそれまで受け取ったオブジェクトの数を返します。
@c COMMON
@end defun


@node R7RS lazy sequences, R7RS stream, R7RS generators, R7RS large
@subsection @code{scheme.lseq} - R7RS lazy sequences
@c NODE R7RS遅延シーケンス, @code{scheme.lseq} - R7RS遅延シーケンス


@deftp {Module} scheme.lseq
@mdindex scheme.lseq
This module provides lightweight lazy sequence (lseq), conceptually represented
by a pair of element and generator.  When the rest of sequence is
taken, the generator is evaluated and yields another pair of element and
generator, and so on.  The overhead is one allocation of a pair per
element.  It is much lighter than streams (@pxref{Stream library}),
which requires to create a thunk for every element.

Gauche already has built-in support for such lazy sequences;
we go further to make it behave like ordinary pairs---that is, if you
take cdr of a lazy pair, we automatically forces the generator so
it is indistinguishable from an ordinary pair, modulo side effects.
@xref{Lazy sequences}.

Srfi-127, the original srfi for this module,
is a bit ambiguous whether its lazy sequence @emph{must} be
implemented with a pair whose cdr is a generator procedure, or
it refers to the pair+generator as a conceptual model.  Considering
of the purpose of lazy sequence, the concrete implementation shouldn't
matter; that is, the user of lazy sequence should not count on the fact
that the lseq is an improper list terminated by a generator procedure.
Instead, an lseq should be treated as an opaque object that can be
passed to @code{scheme.lseq} procedures.

With that premise, we implement this module as just a thin wrapper of
Gauche's native lazy sequence.  It is upper-compatible,
except that the code that assumes the internal structure could break.
Notably, the constructor @code{generator->lseq} is the same as
Gauche's built-in, which returns Gauche's lseq, undistinguishable
to the ordinary list.

@example
(procedure? (generator->lseq (generator 1)))
  ;; => #t, in srfi-127 reference implementation,
  ;;    #f, in our implementation.
@end example
@end deftp

@defun lseq? x
[R7RS lseq]
@c MOD scheme.lseq
Returns true iff @var{x} is an object that can be passed to
lseq procedures.  In Gauche, it returns @code{#t} if @var{x} is
a pair or an empty list, since a lazy pair is indistinguishable
from a pair.
@end defun

@defun lseq=? elt=? lseq1 lseq2
[R7RS lseq]
@c MOD scheme.lseq
Compare two lseqs element-wise using @code{elt=?} and returns @code{#t}
iff two lseqs are equal.
@end defun

@defun lseq-car lseq
@defunx lseq-first lseq
[R7RS lseq]
@c MOD scheme.lseq
Returns the first item of @var{lseq}.  If @var{lseq} is empty, an error
is raised.  In Gauche, these are just aliases of @code{car}.
@end defun

@defun lseq-cdr lseq
@defunx lseq-rest lseq
[R7RS lseq]
@c MOD scheme.lseq
Returns the rest of @var{lseq}.  If @var{lseq} is empty, an error
is raised.  In Gauche, these are just aliases of @code{cdr}.
@end defun

@defun lseq-take lseq k
@defunx lseq-drop lseq k
[R7RS lseq]
@c MOD scheme.lseq
Returns an lseq that has first @code{k} items,
or an lseq that skips first @code{k} items, respectively.

An error is signaled when the resulting lseq of @code{lseq-take}
reached at the end of sequence before @code{k} items are taken.
It is different from Gauche's @code{ltake}, which simply returns @code{()}
in such case.

On the other hand,  @code{lseq-drop} is the same as @code{drop}
in Gauche; it just drops @var{k} items from the head of input
sequence, regardless of whether it is an ordinary list or lseq.
@end defun

@defun lseq-realize lseq
[R7RS lseq]
@c MOD scheme.lseq
Realizes all the elements in @var{lseq}, resulting an ordinary list.
@end defun

@defun lseq->generator lseq
[R7RS lseq]
@c MOD scheme.lseq
Creates a generator from @var{lseq}.  In Gauche, this is same
as @code{list->generator}.
@end defun

@defun lseq-length lseq
[R7RS lseq]
@c MOD scheme.lseq
Returns the length of @var{lseq}.  All the elements in @var{lseq} are
realized as the side effect.  In Gauche, this is same as @code{length}.
@end defun

@defun lseq-append lseq lseq2 @dots{}
[R7RS lseq]
@c MOD scheme.lseq
Append one or more @var{lseq}s lazily.  This is the same as @code{lappend}
in Gauche.
@end defun

@defun lseq-zip lseq lseq2 @dots{}
[R7RS lseq]
@c MOD scheme.lseq
Returns a lazy sequence in which the first element is a list of
first elements of @code{lseq}s, and so on.
@end defun

@defun lseq-map proc lseq lseq2 @dots{}
[R7RS lseq]
@c MOD scheme.lseq
Lazy map.  The same as Gauche's @code{lmap}.  Returns a lazy sequence.
@end defun

@defun lseq-for-each proc lseq lseq2 @dots{}
[R7RS lseq]
@c MOD scheme.lseq
This one consumes all the input lseqs, applying @var{proc} on
each corresponding elements of the input sequences for the side
effects.  In Gauche, it is the same as @code{for-each}, for
Gauche doesn't distinguish lseqs and ordinary lists.
@end defun

@defun lseq-filter pred lseq
@defunx lseq-remove pred lseq
[R7RS lseq]
@c MOD scheme.lseq
Returns an lseq that contains elements from the input
@var{lseq} that satisfy or don't satisfy @var{pred}, respectively.
@code{Lseq-filter} is the same as Gauche's @code{lfilter}.
@end defun

@defun lseq-take-while pred lseq
@defunx lseq-drop-while pred lseq
[R7RS lseq]
@c MOD scheme.lseq
These are the same as Gauche's @code{ltake-while} and @code{drop-while}
(the latter doesn't have @code{l}-prefix, since it just drops items
from the head of the input sequence, regardless of whether it is
an ordinary list or an lseq.
@end defun

@defun lseq-find pred lseq
@defunx lseq-find-tail pred lseq
@defunx lseq-any pred lseq
@defunx lseq-every pred lseq
@defunx lseq-index pred lseq
@defunx lseq-member pred lseq :optional eq
@defunx lseq-memq pred lseq
@defunx lseq-memv pred lseq
[R7RS lseq]
@c MOD scheme.lseq
In Gauche, these are the same as the corresponding list functions,
@code{find}, @code{find-tail}, @code{any}, @code{every},
@code{list-index}, @code{member}, @code{memq} and @code{memv}, respectively,
for all of those functions won't look at input more than necessary
so @var{lseq}s work just as well as ordinary lists.
@end defun

@node R7RS stream, R7RS boxes, R7RS lazy sequences, R7RS large
@subsection @code{scheme.stream} - R7RS stream
@c NODE R7RSストリーム, @code{scheme.stream} - R7RSストリーム

@deftp {Module} scheme.stream
@mdindex scheme.stream
This module provides utilities for lazily evaluated streams.
It is more heavyweight than lazy sequences (@pxref{Lazy sequences}),
but it strictly implements ``as lazy as possible'' semantics---elements
are never evaluated until it is actually accessed.

The following procedures are provided in Gauche's @code{util.stream} module;
@pxref{Stream library} for their description:

@example
stream-null         stream-cons       stream?          stream-null?
stream-pair?        stream-car        stream-cdr       stream-lambda

define-stream       list->stream      port->stream
stream->list        stream-append     stream-concat    stream-constant
stream-drop-while   stream-filter     stream-fold
stream-for-each     stream-from       stream-iterate   stream-length
stream-let          stream-map        stream-match     stream-of
stream-range        stream-ref        stream-reverse   stream-scan
stream-take-while   stream-unfold     stream-unfolds   stream-zip
@end example

The following macro and procedures have different interface from
Gauche's @code{util.stream} module:

@example
stream              stream-take      stream-drop
@end example
@end deftp

@defmac stream expr @dots{}
[R7RS stream]
@c MOD scheme.stream
Returns a new stream whose elements are the result of @var{expr} @dots{}.
Arguments won't be evaluated until required.

This differs from srfi-40 and @code{util.stream}'s @code{stream},
which is a procedure so arguments are evaluated
(@pxref{Stream constructors}, for the details).
@end defmac


@defun stream-take n stream
@defunx stream-drop n stream
[R7RS stream]
@c MOD scheme.stream
Returns a stream that contains first @var{n} elements from @var{stream},
or elements without first @var{n} elements from it, respectively.
If @var{stream} has less than @var{n} elements, @code{stream-take}
returns a copy of the entire @var{stream}, while @code{stream-drop}
returns a null stream.

Note that the argument order doesn't follow the Scheme tradition,
which takes the main object (@var{stream} in this case) first, then
the count.  Procedures with the same name is provided in @code{util.stream}
with the different argument order.
@end defun

@node R7RS boxes, R7RS list queues, R7RS stream, R7RS large
@subsection @code{scheme.box} - R7RS boxes
@c NODE R7RSボックス, @code{scheme.box} - R7RSボックス

@deftp {Module} scheme.box
@mdindex scheme.box
Gauche supports boxes built-in (@pxref{Boxes}), so this module
is merely a facade that exports the following identifiers:

@example
box    box?    unbox    set-box!
@end example
@end deftp

@node R7RS list queues, R7RS ephemerons, R7RS boxes, R7RS large
@subsection @code{scheme.list-queue} - R7RS list queues
@c NODE R7RSリストキュー, @code{scheme.list-queue} - R7RSリストキュー

@deftp {Module} scheme.list-queue
@mdindex scheme.list-queue
@c EN
A library of simple queue based on lists.
Gauche has a queue support in @code{data.queue} module, which also
includes MT-safe queue (@pxref{Queue}).  This library is implemented
on top of @code{data.queue}'s @code{<queue>} object and mainly provided
for portable code.
@c JP
リストを元にしたキューのライブラリです。
Gaucheは@code{data.queue}モジュールでキューをサポートしています
(スレッドセーフなキューも含まれています。詳しくは@ref{Queue}を参照。)
このモジュールは、主としてポータブルなコードのために、
@code{data.queue}の@code{<queue>}の上に実装されています。
@c COMMON

@c EN
The list-queue is just an instance of @code{<queue>}, so you can
pass a queue created by @code{make-queue} to @code{scheme.list-queue}
API and
a list-queue created by @code{make-list-queue} to Gauche's queue API.
@c JP
このモジュールでいうリストキューは@code{<queue>}のインスタンスそのものなので、
@code{make-queue}で作ったキューを@code{scheme.list-queue}のAPIに渡したり、
@code{make-list-queue}で作ったキューをGaucheのキューAPIに渡すこともできます。
@c COMMON

@c EN
Note: Some API of this library requires to return internal pairs the queue
uses, for the efficiency.
The pair's car/cdr will be mutated by subsequent queue operation,
and also any mutation done on the pair would cause inconsistency
in the original queue.
@c JP
註: このライブラリのAPIには、性能のために、
キューが使う内部のペアをそのまま返すことを要求されている
ものがあります。これらの内部ペアはキューの操作によって破壊的に変更される可能性があります。
ユーザ側でも変更した場合、その後のキューの動作は保証されません。
@c COMMON
@end deftp

@defun make-list-queue lis :optional last
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Creates and returns a list-queue whose initial content is @var{lis}.
In Gauche, a list queue is just an instance of @code{<queue>} (@pxref{Queue}).

The cells in @var{lis} are owned by the queue; the caller shouldn't mutate
it afterwards, nor assume its structure remains the same.

The optional @var{last} argument must be the last pair of @var{lis}.
If it is passed, @code{make-list-queue} will skip scanning @var{lis}
and just hold a reference to @var{last} as the tail of the queue.
@c JP
リスト@var{lis}の内容を初期値として持つリストキューを作って返します。
Gaucheでは、リストキューは@code{<queue>}のインスタンスです(@ref{Queue}参照)。

@var{lis}の実体は作成されたキューの所有物となります。
呼び出し側は、この関数を呼んだ後で@var{lis}を変更してはいけません。
また、作成されたキューの操作によって@var{lis}の内容は変更されるでしょう。

省略可能な@var{last}引数は、もし与えられる場合は、@var{lis}の最後のペアで
なければなりません。この引数が渡された場合、@code{make-list-queue}は自分で
リストの末尾のペアを見つけるかわりに、呼び出し側を信頼して@var{last}を最後の
ペアとして保持します。
@c COMMON
@end defun

@defun list-queue elt @dots{}
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Creates and returns a list-queue whose initial content is @var{elt} @dots{}.
In Gauche, a list queue is just an instance of @code{<queue>} (@pxref{Queue}).
@c JP
@var{elt} @dots{}を初期内容とするリストキューを作成して返します。
Gaucheでは、リストキューは@code{<queue>}のインスタンスです(@ref{Queue}参照)。
@c COMMON
@end defun

@defun list-queue-copy queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns a copy of a list-queue @var{queue}.
@c JP
リストキュー@var{queue}のコピーを返します。
@c COMMON
@end defun

@defun list-queue-unfold p f g seed :optional queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Prepend @var{queue} with the items generated by
@code{(unfold p f g seed)} and returns the updated queue.
@xref{R7RS lists}, for @code{unfold}.
If @var{queue} is omitted, a fresh queue is created.
@c JP
リストキュー@var{queue}の前に、@code{(unfold p f g seed)}で生成される
要素を付け足して、@var{queue}を返します。
@code{unfold}については@ref{R7RS lists}を参照してください。
@var{queue}が省略された場合は新たに作成したキューを使います。
@c COMMON

@example
(list-queue-unfold (pa$ = 5) ; p
                   (pa$ * 2) ; f
                   (pa$ + 1) ; g
                   0         ; seed
                   (list-queue 'x 'y 'z))
 @result{} @r{a queue containing (0 2 4 6 8 x y z)}
@end example
@end defun

@defun list-queue-unfold-right p f g seed :optional queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Append @var{queue} with the items generated by
@code{(unfold-right p f g seed)} and returns the updated queue.
@xref{R7RS lists}, for @code{unfold-right}.
If @var{queue} is omitted, a fresh queue is created.
@c JP
@var{queue}の後ろに、@code{(unfold-right p f g seed)}で生成される
要素を付け足して、@var{queue}を返します。
@code{unfold-right}については@ref{R7RS lists}を参照してください。
@var{queue}が省略された場合は
新たに作成したキューを使います。
@c COMMON

@example
(list-queue-unfold-right (pa$ = 5) ; p
                         (pa$ * 2) ; f
                         (pa$ + 1) ; g
                         0         ; seed
                         (list-queue 'x 'y 'z))
 @result{} @r{a queue containing (x y z 8 6 4 2 0)}
@end example
@end defun

@defun list-queue? obj
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns true iff @var{queue} is a list-queue.
In Gauche, it is the same as @code{queue?} in the @code{data.queue} module.
@c JP
@var{queue}がリストキューなら@code{#t}を、そうでなければ@code{#f}を返します。
Gaucheでは@code{data.queue}モジュールの@code{queue?}と同じです。
@c COMMON
@end defun

@defun list-queue-empty? queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns true iff @var{queue} is empty.
Same as @code{queue-empty?} of @code{data.queue}.
@c JP
@var{queue}が空なら@code{#t}を、そうでなければ@code{#f}を返します。
@code{data.queue}の@code{queue-empty?}と同じです。
@c COMMON
@end defun

@defun list-queue-front queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns the front element of the @var{queue}.
An error is thrown if @var{queue} is empty.
Same as @code{queue-front} of @code{data.queue}.
@c JP
@var{queue}の先頭の要素を返します。@var{queue}が空の場合はエラーを報告します。
@code{data.queue}の@code{queue-front}と同じです。
@c COMMON
@end defun

@defun list-queue-back queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns the rear element of the @var{queue}.
An error is thrown if @var{queue} is empty.
Same as @code{queue-rear} of @code{data.queue}.
@c JP
@var{queue}の末尾の要素を返します。@var{queue}が空の場合はエラーを報告します。
@code{data.queue}の@code{queue-rear}と同じです。
@c COMMON
@end defun

@defun list-queue-list queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns the internal list of @var{queue}.
Note that the list would be modified by subsequent operations of @var{queue},
and any modification on the list would make @var{queue} inconsistent.
The primary purpose of this procedure is to implement other
queue-related operations with small overhead.

If you merely need a cheap access the content of the queue,
consider @code{list-queue-remove-all!}.
That returns the list of elements of the queue without copying, and
simultaneously reset the queue to empty, so it's safe.
@c JP
@var{queue}が内部的に保持している要素のリストを返します。
返されたリストは、@var{queue}が操作されれば破壊的に変更される可能性があり、
また返されたリストを破壊的に変更した場合は@var{queue}の一貫性が失われます。
この手続きの主な目的は、他のキュー操作を効率よく実装することです。

単にキューの中身にオーバーヘッド無くアクセスしたい場合は、
@code{list-queue-remove-all!}が使えないかどうか検討してください。
そちらはキューの中身のリストを直接返すと同時にキュー自体を空にするので、安全です。
@c COMMON
@end defun

@defun list-queue-fist-last queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns two values, the first and last pair of @var{queue}.
If the queue is empty, two empty lists are returned.

This also returns the internal pair of the queue, so
any subsequent operations of @var{queue} would change the contents
of the pairs, and any modification on the pairs would make @var{queue}
inconsistent.
The purpose of this procedure is to implement other
queue-related operations with small overhead.  This procedure should
not be used in general.
@c JP
@var{queue}の内部で要素を保持しているリストの先頭と末尾のペアを返します。
キューが空の場合は、二つの空リストを返します。

この手続きも、@code{list-queue-list}と同じく、内部のリストを直接返すため、
返されたリストは、@var{queue}が操作されれば破壊的に変更される可能性があり、
また返されたリストを破壊的に変更した場合は@var{queue}の一貫性が失われます。
この手続きの主な目的は、他のキュー操作を効率よく実装することであり、
一般的な用途に使うべきではありません。
@c COMMON
@end defun

@defun list-queue-add-front! queue elt
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Add @var{elt} to the front of @var{queue}.
Same as @code{(queue-push! queue elt)} of @code{data.queue}.
@c JP
@var{elt}を@var{queue}の先頭に追加します。
@code{data.queue}の@code{(queue-push! queue elt)}と同じです。
@c COMMON
@end defun

@defun list-queue-add-back! queue elt
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Add @var{elt} to the back of @var{queue}.
Same as @code{(enqueue! queue elt)} of @code{data.queue}.
@c JP
@var{elt}を@var{queue}の末尾に追加します。
@code{data.queue}の@code{(enqueue! queue elt)}と同じです。
@c COMMON
@end defun

@defun list-queue-remove-front! queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Remove an element from the front of @var{queue} and returns
the removed element.  Throws an error if @var{queue} is empty.
Same as @code{dequeue!} of @code{data.queue}.
@c JP
@var{queue}の先頭から要素をひとつ取り除き、その取り除かれた要素を返します。
@var{queue}が空ならエラーを報告します。
@code{data.queue}の@code{(dequeue! queue elt)}と同じです。
@c COMMON
@end defun

@defun list-queue-remove-back! queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Remove an element from the back of @var{queue} and returns the
removed element.  Throws an error if @var{queue} is empty.
This isn't guaranteed to be efficient; it is O(n)
operation where n is the number of elements.
In general, if you need this operation frequently, you should
consider double-ended queue.  (@xref{Immutable deques}, and also
@pxref{Ring buffer}.)
@c JP
@var{queue}の末尾から要素をひとつ取り除き、その取り除かれた要素を返します。
@var{queue}が空ならエラーを報告します。
この手続きは、キューの持つ要素数nに対してO(n)の時間がかかります。
もしこの操作を頻繁に必要とするなら、デック(deque, 両端キュー)を使うことを
検討すべきでしょう。(@ref{Immutable deques}および
@ref{Ring buffer}参照。)
@c COMMON
@end defun

@defun list-queue-remove-all! queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Remove all the elements from @var{queue} and returns them as a list.
The list isn't copied---this is O(1) operation.  This should be preferred
over @code{list-queue-list}, for it's safer.
In Gauche, this is the same as @code{dequeue-all!} in @code{data.queue}.
@c JP
@var{queue}を空にして、入っていた全ての要素をリストで返します。
リストはコピーされません。つまりO(1)の操作です。
可能なら、@code{list-queue-list}よりはこちらを使う方が安全です。
Gaucheでは、これは@code{data.queue}の@code{deque-all!}と同じです。
@c COMMON
@end defun

@defun list-queue-set-list! queue lis :optional last
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Modify @var{queue} to have the elements in @var{lis} as its element.
The original content of @var{queue} is discarded.  If the optional
@var{last} argument is provided, it must be the last pair of @var{lis},
and the procedure uses that instead of scanning @var{lis}, to achieve
O(1) operation.

After calling this, @var{lis} is owned by @var{queue} and it may
be mutated.  The caller shouldn't change, or rely on @var{lis} afterwards.
@c JP
@var{queue}を変更して、@var{lis}の内容がキューの内容になるようにします。
@var{queue}の元の内容は捨てられます。省略可能な@var{last}引数が渡される場合、
それは@var{lis}の最後のペアでなければなりません。手続きは呼び出し元を信頼して、
@var{lis}をスキャンせずに@var{last}を最後のペアと考えることで
O(1)操作を実現しています。

この手続きを呼び出した後では、@var{lis}は@var{queue}に所有され、破壊的変更を
受けます。この後で@var{lis}の内容をあてにしたり変更したりしてはいけません。
@c COMMON
@end defun

@defun list-queue-append queue @dots{}
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns a fresh list-queue whose contents are concatenation of
@var{queue}s.  The contents of arguments are intact.
This is O(n) operation where n is the total number of elements.
@c JP
与えられた@var{queue}を全部つないだ要素を持つリストキューを
新たに作成して返します。引数のキューは変更されません。
これは要素の総数nについてO(n)の操作となります。
@c COMMON
@end defun

@defun list-queue-append! queue @dots{}
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns a list-queue whose contents are concatenation of
@var{queue}s.  During the operation, the contents of @var{queue}s
may be mutated, and they shouldn't be used any longer.  (In Gauche,
to avoid accident, we actually empty all the @var{queue}s.)
It is also noted that the result doesn't need to be @code{eq?} to
any of the arguments.
This is O(m) operation where m is the total number of queues
(as opposed to the number of elements).
@c JP
与えられた@var{queue}の要素を全てつないだものを要素とするリストキューを
返します。操作によって、@var{queue}の内容は破壊されることがあり、
以降それらのキューを使ってはなりません
(Gaucheでは、事故を避けるために、全ての@var{queue}を空にしています)。
結果として返されるキューが、引数のどれとも@code{eq?}になる必要はない、
ということに注意してください。
これはキューの総数mに対してO(m)の操作です(要素の総数ではなく)。
@c COMMON
@end defun

@defun list-queue-concatenate queues
[R7RS list-queue]
@c MOD scheme.list-queue
@code{(apply list-queue-append queues)}.
@end defun

@defun list-queue-map proc queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Returns a fresh list-queue whose elements are obtained by
applying @var{proc} on every elements in @var{queue}.
@c JP
@var{proc}を@var{queue}の各要素に適用して得られた結果を要素とする
新たなリストキューを返します。
@c COMMON
@end defun

@defun list-queue-map! proc queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Replaces every element in @var{queue} by the result of
application of @var{proc} on the element.
@c JP
@var{queue}の各要素を、それに@var{proc}を適用して得られた結果に
置き替えます。
@c COMMON
@end defun

@defun list-queue-for-each proc queue
[R7RS list-queue]
@c MOD scheme.list-queue
@c EN
Applies @var{proc} on every element of @var{queue}.
The results are discarded.
@c JP
@var{proc}を@var{queue}の各要素に適用します。結果は捨てられます。
@c COMMON
@end defun

@node R7RS ephemerons, R7RS comparators, R7RS list queues, R7RS large
@subsection @code{scheme.ephemeron} - R7RS ephemeron
@c NODE R7RS Ephemeron, @code{scheme.ephemeron} - R7RS Ephemeron

@deftp {Module} scheme.ephemeron
@mdindex scheme.ephemeron
@c EN
This module defined @emph{ephemerons}, a weak reference
structure to hold key-value association.  This is originally
defined as srfi-142.
@c JP
このモジュールは@emph{ephemeron}と呼ばれる、
キーとそれに関連づけられたデータについて弱参照を保持する構造を提供します。
元々はsrfi-142で定義されました。
@c COMMON

@c EN
Gauche supports weak pointers in the form of weak vectors
(@pxref{Weak vectors}), but it is known that a simple weak
pointer (a single pointer that doesn't prevent the pointed
object from being collected) isn't enough to implement
weak key-value association such as mappings.
@c JP
Gaucheはweak vectorとして弱参照を提供しています
(@ref{Weak vectors}参照)が、単なるweak pointer (それに指されている
オブジェクトの回収を許す) だけでは、mappingのようなキーと値を関連付ける
データ構造で弱参照を実現するには不十分なことが知られています。
@c COMMON

@c EN
An ephemeron is a record that points to a key and an associated
datum, with the following characteristics:
@c JP
ephemeronはキーとデータへの参照を保持するレコードで、以下の性質を持ちます。
@c COMMON

@enumerate
@item
@c EN
Reference to the key is weak; it doesn't prevent the key from
being collected if there's no strong reference to the key,
@emph{except from the datum associated by the ephemeron}.
@c JP
キーへの参照はweakです。もし、キーへの強参照が、
@emph{ephemeronを通じて対応しているデータからのものを除いて}
存在しない場合、キーは回収されます。
@c COMMON

@item
@c EN
Reference to the datum is also a kind of weak; it doesn't prevent the datum
from being collected if there's no strong reference to the datum,
@emph{and there's no strong reference to the associated key}.
Note that the datum is retained as long as the key is retained,
even there's no strong reference to the datum itself.
@c JP
データへの参照もある意味weakです。
データへの強参照が存在せず、@emph{かつ対応するキーへの強参照が無い場合}、
データは回収されます。
データへの強参照が無くても、キーが生きていればデータは保持されるという点がポイントです。
@c COMMON
@end enumerate

@c EN
Implementing the proper ephemeron requires deep integration with
the GC.  At this moment, Gauche's ephemeron is implemented separately
from GC, and has the following limitations:
@c JP
ephemeronを完全に実装するには、GCとの統合が必要になります。
今のところ、GaucheのephemeronはGCとは独立に実装されており、
以下の制限があります:
@c COMMON

@itemize @bullet
@item
@c EN
If the datum has a strong reference to the associated key, the
key won't be collected even if there's no other strong reference to it.
@c JP
データからキーへの強参照があると、キーは回収されません。
@c COMMON

@item
@c EN
After the key is collected and there's no strong reference to
the datum, @code{ephemeron-broken?} needs to be called in order
to trigger the collection of the datum.
@c JP
キーが回収され、データへの強参照が無い状態になってから、データが回収されるには
@code{ephemeron-broken?}が呼ばれる必要があります。
@c COMMON
@end itemize

@c EN
Since the timing of collection isn't specified in the spec,
Gauche's implementation still conforms srfi-142, but in practice
you need to be aware of these limitations.  Eventually we want
to support full ephemeron integrated with GC.
@c JP
いつ回収されるかについての規定は仕様にないので、Gaucheの現在の実装もsrfi-142の
仕様は満たしているのですが、実際に使うにあたっては上記の制限を意識する必要があるでしょう。
将来的にはGCと統合されたephemeronをサポートしたいと思っています。
@c COMMON

@c EN
Once the key and/or the datum is collected (we call such ephemeron
``broken''), referencing them returns a bogus value.  The proper
way to use an ephemeron @var{e} is the following pattern:
@c JP
キーあるいはデータが回収された後は (この状態のephemeronを ``broken'' と呼びます)、
キーやデータを取り出そうとしても意味のある値は得られません。
ephemeron @var{e}を使う正しい手順は次のパターンです:
@c COMMON

@example
(let ([k (ephemeron-key e)]
      [d (ephemeron-datum e)])
  (if (ephemeron-broken? e)
    (... k and d are invalid ...)
    (... k and d are valid ...)))
@end example

@c EN
You should take values, then check if the ephemeron isn't broken yet.
If you call @code{ephemeron-broken?} first, there's a chance
that the ephemeron is broken between the check and the time
you reference it.
@c JP
つまり、値を取り出した後でephemeronがbrokenかどうかを調べます。
先に@code{ephemeron-broken?}を呼んでしまうと、その呼び出しから
値を取り出すまでの間にGCが走ってキーやデータが回収されてしまう可能性があります。
@c COMMON
@end deftp

@defun make-ephemeron key datum
[R7RS ephemeron]
@c MOD scheme.ephemeron
@c EN
Create a new ephemeron associating the @var{key} to the @var{datum}.
@c JP
@var{key}を@var{datum}に関連づけるephemeronを作って返します。
@c COMMON
@end defun

@defun ephemeron? obj
[R7RS ephemeron]
@c MOD scheme.ephemeron
@c EN
Returns @code{#t} iff @var{obj} is an ephemeron.
@c JP
@var{obj}がephemeronであれば@code{#t}を、そうでなければ@var{#f}を返します。
@c COMMON
@end defun


@defun ephemeron-key ephemeron
@defunx ephemeron-datum ephemeron
[R7RS ephemeron]
@c MOD scheme.ephemeron
@c EN
Returns the key and the datum of @var{ephemeron}, respectively.
If the ephemeron is already broken, there's no guarantee
on what is returned. Thus you should always call @code{ephemeron-broken?}
@emph{after} calling these procedure to ensure the values are
meaningful.  See the @code{scheme.ephemeron} entry for the details.
@c JP
それぞれ、@var{ephemeron}のキーとデータを返します。
ephemeronが既にbrokenだと、何が返されるかはわかりません。
なので常に、これらの手続きで値を取り出した@emph{後で} @code{ephemeron-broken?}
を呼んで値が有効かどうかチェックする必要があります。
詳しくは上の@code{scheme.ephemeron}のエントリを参照してください。
@c COMMON
@end defun

@defun ephemeron-broken? ephemeron
[R7RS ephemeron]
@c MOD scheme.ephemeron
@c EN
Returns @code{#t} iff @var{ephemeron} has been broken, that is,
its key and/or datum may be collected and cannot be reliably retrieved.
See the @code{scheme.ephemeron} entry for the details.
@c JP
@var{ephemeron}がbrokenであれば@code{#t}を、そうでなければ@code{#f}を返します。
brokenであるとは、キーや値が既に回収されてしまって取り出せないことを意味します。
詳しくは@code{scheme.ephemeron}のエントリを参照してください。
@c COMMON
@end defun

@defun reference-barrier key
[R7RS ephemeron]
@c MOD scheme.ephemeron
@c EN
This procedure does nothing by itself,
but guarantees @var{key} is strongly reference
until returning from this procedure.
@c JP
この手続きはそれ自体は何もしませんが、
この手続きが戻るまで@var{key}への参照が保持されることを保証します。
@c COMMON
@end defun


@node R7RS comparators, R7RS regular expressions, R7RS ephemerons, R7RS large
@subsection @code{scheme.comparator} - R7RS comparators
@c NODE R7RS比較器, @code{scheme.comparator} - R7RS比較器

@deftp {Module} scheme.comparator
@mdindex scheme.comparator
This module defines comparators and related procedures.
Originally called @code{srfi-128}.

Gauche supports comparators fully compatible to
@code{scheme.comparator} built-in.
@xref{Basic comparators}, for the following procedures
defined in this module.

@example
comparator? comparator-ordered? comparator-hashable?
make-comparator make-pair-comparator
make-list-comparator make-vector-comparator
make-eq-comparator make-eqv-comparator make-equal-comparator

boolean-hash char-hash char-ci-hash string-hash
string-ci-hash symbol-hash number-hash
hash-bound hash-salt

make-default-comparator default-hash
comparator-register-default!

comparator-type-test-predicate comparator-equality-predicate
comparator-ordering-predicate comparator-hash-function
comparator-test-type comparator-check-type comparator-hash

=? <? >? <=? >=? comparator-if<=>
@end example
@end deftp

@c ----------------------------------------------------------------------
@node R7RS regular expressions, R7RS mappings, R7RS comparators, R7RS large
@subsection @code{scheme.regex} - R7RS regular expressions
@c NODE R7RS正規表現, @code{scheme.regex} - R7RS正規表現

@deftp {Module} scheme.regex
@mdindex scheme.regex
@c COMMON
This module provides operations on Scheme Regular Expressions (SRE).
Originally defined as srfi-115.

@end deftp

@subheading Scheme regular expression syntax

@subsubheading Syntax summary

SRE is just an S-expression with the structure summarized below.

With the exception of @code{or}, any syntax that takes multiple
@code{<sre>} processes them in a sequence. In other words @code{(foo
<sre> ...)} is equivalent to @code{(foo (seq <sre> ...))}.

Note: SRE uses the symbol @code{|} for alteration, but the vertical bar
character is used for symbol escape in Gauche (and R7RS), so you have to
write such symbol as @code{|\||}.  We recommend to use @code{or} instead.

@smallexample
    <sre> ::=
     | <string>                    ; A literal string match.
     | <cset-sre>                  ; A character set match.
     | (* <sre> ...)               ; 0 or more matches.
     | (zero-or-more <sre> ...)
     | (+ <sre> ...)               ; 1 or more matches.
     | (one-or-more <sre> ...)
     | (? <sre> ...)               ; 0 or 1 matches.
     | (optional <sre> ...)
     | (= <n> <sre> ...)           ; <n> matches.
     | (exactly <n> <sre> ...)
     | (>= <n> <sre> ...)          ; <n> or more matches.
     | (at-least <n> <sre> ...)
     | (** <n> <m> <sre> ...)      ; <n> to <m> matches.
     | (repeated <n> <m> <sre> ...)

     | (|\||  <sre> ...)           ; Alternation.
     | (or <sre> ...)

     | (:   <sre> ...)             ; Sequence.
     | (seq <sre> ...)
     | ($ <sre> ...)               ; Numbered submatch.
     | (submatch <sre> ...)
     | (-> <name> <sre> ...)               ;  Named submatch.  <name> is
     | (submatch-named <name> <sre> ...)   ;  a symbol.

     | (w/case   <sre> ...)        ; Introduce a case-sensitive context.
     | (w/nocase <sre> ...)        ; Introduce a case-insensitive context.

     | (w/unicode   <sre> ...)     ; Introduce a unicode context.
     | (w/ascii <sre> ...)         ; Introduce an ascii context.

     | (w/nocapture <sre> ...)     ; Ignore all enclosed submatches.

     | bos                         ; Beginning of string.
     | eos                         ; End of string.

     | bol                         ; Beginning of line.
     | eol                         ; End of line.

     | bow                         ; Beginning of word.
     | eow                         ; End of word.
     | nwb                         ; A non-word boundary.
     | (word <sre> ...)            ; An SRE wrapped in word boundaries.
     | (word+ <cset-sre> ...)      ; A single word restricted to a cset.
     | word                        ; A single word.

     | (?? <sre> ...)              ; A non-greedy pattern, 0 or 1 match.
     | (non-greedy-optional <sre> ...)
     | (*? <sre> ...)              ; Non-greedy 0 or more matches.
     | (non-greedy-zero-or-more <sre> ...)
     | (**? <m> <n> <sre> ...)     ; Non-greedy <m> to <n> matches.
     | (non-greedy-repeated <sre> ...)
     | (atomic <sre> ...)          ; Atomic clustering.

     | (look-ahead <sre> ...)      ; Zero-width look-ahead assertion.
     | (look-behind <sre> ...)     ; Zero-width look-behind assertion.
     | (neg-look-ahead <sre> ...)  ; Zero-width negative look-ahead assertion.
     | (neg-look-behind <sre> ...) ; Zero-width negative look-behind assertion.

     | (backref <n-or-name>)       ; Match a previous submatch.
     @c These are extensions
     @c | (if-look-ahead <test-sre> <then-sre> [<else-sre>])      ; Conditional pattern
     @c | (if-neg-look-ahead <test-sre> <then-sre> [<else-sre>])  ; Conditional pattern
     @c | (if-look-behind <test-sre> <then-sre> [<else-sre>])     ; Conditional pattern
     @c | (if-neg-look-behind <test-sre> <then-sre> [<else-sre>]) ; Conditional pattern
     @c | (if-backref <backref> <then-sre> [<else-sre>])          ; Conditional pattern
@end smallexample

The grammar for @code{cset-sre} is as follows.

@smallexample
    <cset-sre> ::=
     | <char>                      ; literal char
     | "<char>"                    ; string of one char
     | <char-set>                  ; embedded SRFI 14 char set
     | (<string>)                  ; literal char set
     | (char-set <string>)
     | (/ <range-spec> ...)        ; ranges
     | (char-range <range-spec> ...)
     | (or <cset-sre> ...)         ; union
     | (|\|| <cset-sre> ...)
     | (and <cset-sre> ...)        ; intersection
     | (& <cset-sre> ...)
     | (- <cset-sre> ...)          ; difference
     | (- <difference> ...)
     | (~ <cset-sre> ...)          ; complement of union
     | (complement <cset-sre> ...)
     | (w/case <cset-sre>)         ; case and unicode toggling
     | (w/nocase <cset-sre>)
     | (w/ascii <cset-sre>)
     | (w/unicode <cset-sre>)
     | any | nonl | ascii | lower-case | lower
     | upper-case | upper | title-case | title
     | alphabetic | alpha | alphanumeric | alphanum | alnum
     | numeric | num | punctuation | punct | symbol
     | graphic | graph | whitespace | white | space
     | printing | print | control | cntrl | hex-digit | xdigit

    <range-spec> ::= <string> | <char>
@end smallexample

@subsubheading Basic patterns

@table @code
@item <string>

A literal string.

@example
(regexp-search "needle" "hayneedlehay")
 @result{} #<regexp-match>
(regexp-search "needle" "haynEEdlehay")
 @result{} #f
@end example

@item (seq <sre> ...)
@itemx (: <sre> ...)

A sequence of patterns that should be matched in the same order. This
is the same as RE syntax @code{(?:@i{re}@dots{})}

@example
(regexp-search '(: "one" space "two" space "three") "one two three")
 @result{} #<regexp-match>
@end example

@item (or <sre> ...)
@itemx (|\|| <sre> ...)

Matches one of the given patterns. This is the same as
RE syntax @code{@i{pattern1}|@i{pattern2}|@dots{}}

@example
(regexp-search '(or "eeney" "meeney" "miney") "meeney")
 @result{} #<regexp-match>
(regexp-search '(or "eeney" "meeney" "miney") "moe")
 @result{} #f
@end example

@item (w/nocase <sre> ...)

Changes to match the given patterns case-insensitively. Sub-patterns
can still be made sensitive with @code{w/case}. This is the same as
RE syntax @code{(?i:@i{re}@dots{})}

@example
(regexp-search "needle" "haynEEdlehay") @result{} #f
(regexp-search '(w/nocase "needle") "haynEEdlehay")
  @result{}  #<regexp-match>

(regexp-search '(~ ("Aab")) "B") @result{} #<regexp-match>
(regexp-search '(~ ("Aab")) "b") @result{} #f
(regexp-search '(w/nocase (~ ("Aab"))) "B") @result{} #f
(regexp-search '(w/nocase (~ ("Aab"))) "b") @result{} #f
(regexp-search '(~ (w/nocase ("Aab"))) "B") @result{} #f
(regexp-search '(~ (w/nocase ("Aab"))) "b") @result{} #f
@end example

@item (w/case <sre> ...)

Changes to match the given patterns case-sensitively. Sub-patterns can
still be made case-insensitive. This is the same as RE syntax
@code{(?-i:@i{re}@dots{})}. This is the default.

@example
(regexp-search '(w/nocase "SMALL" (w/case "BIG")) "smallBIGsmall")
 @result{} #<regexp-match>
(regexp-search '(w/nocase (~ (w/case ("Aab")))) "b") @result{} #f
@end example

@item (w/ascii <sre> ...)

Limits the character sets and other predefined patterns to ASCII. This
affects patterns or character sets like @code{any}, @code{alpha},
@code{(word)}@dots{}

@example
(regexp-search '(w/ascii bos (* alpha) eos) "English")
 @result{} #<regexp-match>
(regexp-search '(w/ascii bos (* alpha) eos) "Ελληνική") @result{} #f
@end example

@item (w/unicode <sre> ...)

Changes the character sets and other predefined patterns back to
Unicode if @code{w/ascii} has been used in the outer scope. This is
the default.

@example
(regexp-search '(w/unicode bos (* alpha) eos) "English")
 @result{} #<regexp-match>
(regexp-search '(w/unicode bos (* alpha) eos) "Ελληνική")
 @result{} #<regexp-match>
@end example

@item (w/nocapture <sre> ...)

Disables capturing for all @code{submatch} and @code{submatch-named}
inside.

@example
(let ((number '($ (+ digit))))
  (cdr
   (regexp-match->list
    (regexp-search `(: ,number "-" ,number "-" ,number)
                   "555-867-5309")))  ; @result{} '("555" "867" "5309")
  (cdr
   (regexp-match->list
    (regexp-search `(: ,number "-" (w/nocapture ,number) "-" ,number)
                   "555-867-5309"))))   @result{} '("555" "5309")
@end example
@end table

@subsubheading Repeating patterns
@table @code
@item (optional <sre> ...)
@itemx (? <sre> ...)

Matches the pattern(s) one or zero times.

@example
(regexp-search '(: "match" (? "es") "!") "matches!")
 @result{} #<regexp-match>
(regexp-search '(: "match" (? "es") "!") "match!")
 @result{} #<regexp-match>
(regexp-search '(: "match" (? "es") "!") "matche!")
 @result{} #f
@end example

@item (zero-or-more <sre> ...)
@itemx (* <sre> ...)

Matches the pattern(s) zero or more times.

@example
(regexp-search '(: "<" (* (~ #\>)) ">") "<html>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (* (~ #\>)) ">") "<>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (* (~ #\>)) ">") "<html")
 @result{} #f
@end example

@item (one-or-more <sre> ...)
@itemx (+ <sre> ...)

Matches the pattern(s) at least once.

@example
(regexp-search '(: "<" (+ (~ #\>)) ">") "<html>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (+ (~ #\>)) ">") "<a>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (+ (~ #\>)) ">") "<>")
 @result{} #f
@end example

@item (at-least n <sre> ...)
@itemx (>= n <sre> ...)

Matches the pattern(s) at least @code{n} times.

@example
(regexp-search '(: "<" (>= 3 (~ #\>)) ">") "<table>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (>= 3 (~ #\>)) ">") "<pre>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (>= 3 (~ #\>)) ">") "<tr>")
 @result{} #f
@end example

@item (exactly n <sre> ...)
@itemx (= n <sre> ...)

Matches the pattern(s) exactly @code{n} times.

@example
(regexp-search '(: "<" (= 4 (~ #\>)) ">") "<html>")
 @result{} #<regexp-match>
(regexp-search '(: "<" (= 4 (~ #\>)) ">") "<table>")
 @result{} #f
@end example

@item (repeated from to <sre> ...)
@itemx (** from to <sre> ...)

Matches the pattern(s) at least @code{from} times and up to @code{to}
times.

@example
(regexp-search '(: (= 3 (** 1 3 numeric) ".") (** 1 3 numeric))
               "192.168.1.10")
 @result{} #<regexp-match>
(regexp-search '(: (= 3 (** 1 3 numeric) ".") (** 1 3 numeric))
               "192.0168.1.10")
 @result{} #f
@end example
@end table

@subsubheading Submatch Patterns
@table @code
@item (submatch <sre> ...)
@itemx ($ <sre> ...)

Captures the matched string. Each capture is numbered increasing from
one (capture zero is the entire matched string). For nested captures,
the numbering scheme is depth-first walk.

@item (submatch-named <name> <sre> ...)
@itemx (-> <name> <sre> ...)

Captures the matched string and assigns a name to it in addition to a
number. This is the equivalent of @code{(?<@i{name}>@i{re}@dots{})}

@item (backref <n-or-name>)

Matches a previously matched submatch. This is the same as
RE syntax @code{\@i{n}} or @code{\k<@i{name}>}.

@c @item (if-backref <n> <then-sre> [<else-sre>])

@c Conditional matching. If the @code{<n>}-th capturing group has a
@c match, @code{<then-sre>} pattern is tried; otherwise @code{<else-sre>}
@c pattern is tried when provided.

@c This is Gauche extension and is the same as RE syntax
@c @code{(?(@i{n})@i{then})} or @code{(?(@i{n})@i{then}|@i{else})}.

@end table

@subsubheading Character Sets

@table @code
@item <char>

A character set contains a single character.

@example
(regexp-matches '(* #\-) "---") @result{} #<regexp-match>
(regexp-matches '(* #\-) "-_-") @result{} #f
@end example

@item "<char>"

A character set contains a single character. This is technically
ambiguous with SRE matching a literal string. However the end result
of both syntaxes is the same.

@item <char-set>

A SRFI-14 character set.

Note that while currently there is no portable written representation
of SRFI 14 character sets, you can use Gauche reader syntax
@code{#[char-set-spec]}, @pxref{Character sets}.

@example
(regexp-partition `(+ ,char-set:vowels) "vowels")
 @result{} ("v" "o" "w" "e" "ls")
@end example

@item (char-set <string>)
@itemx (<string>)

A character set contains the characters in the given string. This is
the same as @code{`(char-set ,(string->char-set <string>))}.

@example
(regexp-matches '(* ("aeiou")) "oui") @result{} #<regexp-match>
(regexp-matches '(* ("aeiou")) "ouais") @result{} #f
(regexp-matches '(* ("e\x0301")) "e\x0301") @result{} #<regexp-match>
(regexp-matches '("e\x0301") "e\x0301") @result{} #f
(regexp-matches '("e\x0301") "e") @result{} #<regexp-match>
(regexp-matches '("e\x0301") "\x0301") @result{} #<regexp-match>
(regexp-matches '("e\x0301") "\x00E9") @result{} #f
@end example

@item (char-range <range-spec> ...)
@itemx (/ <range-spec> ...)

A character set contains the characters within
@code{<range-set>}. This is the same as RE syntax @code{[]}.

@example
(regexp-matches '(* (/ "AZ09")) "R2D2") @result{} #<regexp-match>
(regexp-matches '(* (/ "AZ09")) "C-3PO") @result{} #f
@end example

@item (or <cset-sre> ...)
@itemx (|\|| <cset-sre> ...)

A shorthand for @code{`(char-set ,(char-set-union <cset-sre>...))}.

@item (complement <cset-sre> ...)
@itemx (~ <cset-sre> ...)

A shorthand for @code{`(char-set ,(char-set-complement <cset-sre>...))}.

@item (difference <cset-sre> ...)
@itemx (- <cset-sre> ...)

A shorthand for @code{`(char-set ,(char-set-difference <cset-sre>...))}.

@example
(regexp-matches '(* (- (/ "az") ("aeiou"))) "xyzzy")
 @result{} #<regexp-match>
(regexp-matches '(* (- (/ "az") ("aeiou"))) "vowels")
 @result{} #f
@end example

@item (and <cset-sre> ...)
@itemx (& <cset-sre> ...)

A shorthand for @code{`(char-set ,(char-set-intersection <cset-sre>...))}.

@example
(regexp-matches '(* (& (/ "az") (~ ("aeiou")))) "xyzzy")
 @result{} #<regexp-match>
(regexp-matches '(* (& (/ "az") (~ ("aeiou")))) "vowels")
 @result{} #f
@end example

@item (w/case <cset-sre>)
@itemx (w/nocase <cset-sre>)
@itemx (w/ascii <cset-sre>)
@itemx (w/unicode <cset-sre>)

This is similar to the SRE equivalent, listed to indicate that they
can also be applied on character sets.

@end table

@subsubheading Named Character Sets

Note that if @code{w/ascii} is in effect, these character sets will
return the ASCII subset. Otherwise they return full Unicode ones.

@table @code
@item any

Matches any character. This is the @code{.} in regular expression.

@item nonl

Matches any character other than @code{#\return} or @code{#\newline}.

@item ascii

A shorthand for @code{`(char-set ,char-set:ascii)}.

@item lower-case
@itemx lower

A shorthand for @code{`(char-set ,char-set:lower-case)}.

@item upper-case
@itemx upper

A shorthand for @code{`(char-set ,char-set:upper-case)}.

@item title-case
@itemx title

A shorthand for @code{`(char-set ,char-set:title-case)}.

@item alphabetic
@itemx alpha

A shorthand for @code{`(char-set ,char-set:letter)}.

@item numeric
@itemx num

A shorthand for @code{`(char-set ,char-set:digit)}.

@item alphanumeric
@itemx alphanum
@itemx alnum

A shorthand for @code{`(char-set ,char-set:letter+digit)}.

@item punctuation
@itemx punct

A shorthand for @code{`(char-set ,char-set:punctuation)}.

@item symbol

A shorthand for @code{`(char-set ,char-set:symbol)}.

@item graphic
@itemx graph

A shorthand for @code{`(char-set ,char-set:graphic)}.

@example
(or alphanumeric punctuation symbol)
@end example


@item whitespace
@itemx white
@itemx space

A shorthand for @code{`(char-set ,char-set:whitespace)}.

@item printing
@itemx print

A shorthand for @code{`(char-set ,char-set:printing)}.

@item control
@itemx cntrl

A character set contains ASCII characters with from 0 to 31.

@item hex-digit
@itemx xdigit

A shorthand for @code{`(char-set ,char-set:hex-digit)}.

@end table

@subsubheading Boundary Assertions

@table @code
@item bos
@itemx eos

Matches the beginning of the string. If start/end parameters are
specified, matches the start or end of the substring as specified.

@item bol
@itemx eol

Matches the beginning or end of a line (or the string). For single
line matching, this is the same as @code{bos} and @code{eos}. A line
is interpreted the same way with @code{read-line}.

@item bow
@itemx eow

Matches the beginning or the end of a word.

@example
  (regexp-search '(: bow "foo") "foo") @result{} #<regexp-match>
  (regexp-search '(: bow "foo") "<foo>>") @result{} #<regexp-match>
  (regexp-search '(: bow "foo") "snafoo") @result{} #f
  (regexp-search '(: "foo" eow) "foo") @result{} #<regexp-match>
  (regexp-search '(: "foo" eow) "foo!") @result{} #<regexp-match>
  (regexp-search '(: "foo" eow) "foobar") @result{} #f
@end example


@item nwb

A shorthand for @code{(neg-look-ahead (or bow eow))}.

@item (word <sre> ...)

Matches the word boundary around the given SRE:

@example
(: bow <sre> ... eow)
@end example


@item (word+ <cset-sre> ...)

Matches a single word composed of characters of the given characters
sets:

@example
(word (+ (and (or alphanumeric "_") (or cset-sre ...))))
@end example


@item word

A shorthand for @code{(word+ any)}.

@end table

@subsubheading Non-Greedy Patterns

@table @code

@item (non-greedy-optional <sre> ...)
@itemx (?? <sre> ...)

The non-greedy equivalent of @code{(optional <sre>...)}. This is the
same as RE syntax @code{@i{re}??}

@item (non-greedy-zero-or-more< <sre> ...)
@itemx (*? <sre> ...)

The non-greedy equivalent of @code{(zero-or-more <sre>...)}. This is
the same as RE syntax @code{@i{re}*?}

@item (non-greedy-repeated <m> <n> <sre> ...)
@itemx (**? <m> <n> <sre> ...)

The non-greedy equivalent of @code{(repeated <sre>...)}. This is the
same as RE syntax @code{@i{re}@{@i{n},@i{m}@}?}

@item (atomic <sre> ...)

Atomic clustering. Once @code{<sre> ...} matches, the match is fixed;
even if the following pattern fails, the engine won't backtrack to try
the alternative match in @code{<sre> ...}. This is Gauche extension
and is the same as RE syntax @code{(?>@i{pattern})}

@end table

@subsubheading Look Around Patterns

@table @code
@item (look-ahead <sre> ...)

Zero-width look-ahead assertion. Asserts the sequence matches from the
current position, without advancing the position. This is the same as
RE syntax @code{(?=@i{pattern})}

@example
(regexp-matches '(: "regular" (look-ahead " expression") " expression")
                "regular expression")
 @result{} #<regexp-match>
(regexp-matches '(: "regular" (look-ahead " ") "expression")
                "regular expression")
 @result{} #f
@end example


@item (look-behind <sre> ...)

Zero-width look-behind assertion. Asserts the sequence matches behind
the current position, without advancing the position. It is an error
if the sequence does not have a fixed length. This is the same as RE
syntax @code{(?<=@i{pattern})}

@item (neg-look-ahead <sre> ...)

Zero-width negative look-ahead assertion. This is the same as
RE syntax @code{(?!@i{pattern})}

@item (neg-look-behind <sre> ...)

Zero-width negative look-behind assertion. This is the same as RE
syntax @code{(?<!@i{pattern})}

@c @item (if-look-ahead <test-sre> <then-sre> [<else-sre>])
@c @itemx (if-neg-look-ahead <test-sre> <then-sre> [<else-sre>])
@c @itemx (if-look-behind <test-sre> <then-sre> [<else-sre>])
@c @itemx (if-neg-look-behind <test-sre> <then-sre> [<else-sre>])

@c Conditional matching. If @code{<test-sre>} counts true,
@c @code{<then-sre>} pattern is tried; otherwise @code{<else-sre>}
@c pattern is tried when provided.

@c This is Gauche extension and the same as @code{(?(?=..)...)},
@c @code{(?(?!..)...)}, @code{(?(?<=..)...)}, @code{(?(?<!..)...)}
@c respectively.

@end table

@subheading Using regular expressions

@defun regexp @var{re}
[R7RS regex]
@c MOD scheme.regex
Compiles the given Scheme Regular Expression into a @code{<regexp>}
object. If @var{re} is already a regexp object, the object is
returned as-is.

@end defun

@defmac rx @var{sre} @dots{}
[R7RS regex]
@c MOD scheme.regex
A macro shorthand for @code{(regexp `(: @var{sre} ...))}.
@end defmac

@defun regexp->sre @var{re}
[R7RS regex]
@c MOD scheme.regex
Returns the SRE corresponding to the given given regexp object. Note
that if the regexp object is not created from an SRE, it may contain
features that cannot be expressed in SRE and cause an error.
@end defun

@defun char-set->sre @var{char-set}
[R7RS regex]
@c MOD scheme.regex
Returns the SRE of the given character set. Currently this is not
optimized. If you convert @code{any} to SRE for example, you may get
an SRE listing every single character.
@end defun

@defun valid-sre? @var{obj}
[R7RS regex]
@c MOD scheme.regex
Returns true iff @var{obj} can be safely passed to regexp.
@end defun

@defun regexp? @var{obj}
[R7RS regex]
@c MOD scheme.regex
Returns true iff @var{obj} is a regexp.
@end defun

@defun regexp-matches @var{re} @var{str} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Returns an @code{<regexp-match>} object if re successfully matches the
entire string @var{str} or optionally from @var{start} (inclusive) to
@var{end} (exclusive), or @code{#f} is the match fails.

For convenience, @var{end} accepts @code{#f} and interprets it as the
end of the string.

The regexp-match object will contain information needed to extract any
submatches.
@end defun

@defun regexp-matches? @var{re} @var{str} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Similar to @code{regexp-matches} but returns @code{#t} instead of a
@code{<regexp-match>} object.
@end defun

@defun regexp-search @var{re} @var{str} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Similar to @code{regexp-matches} except that @var{re} only has to
match a substring in @var{str} instead.
@end defun


@defun regexp-fold @var{re} @var{kons} @var{knil} @var{str} [@var{finish} [@var{start} [@var{end}]]]
[R7RS regex]
@c MOD scheme.regex
Calls the procedure @var{kons} for every match found in @var{str} with
following four arguments:

@itemize
@item
The position of the end of the last matched string.
@item
The @code{<regexp-match>} object.
@item
The argument @var{str}.
@item
The result of the last @var{kons} call or @var{knil} if this is the
first call.
@end itemize

If @var{finish} is given, it is called after all matches with the same
parameters as calling @var{kons} except that @code{#f} is passed
instead of @code{<regexp-match>} and the result is returned. Otherwise
the result of the last @var{kons} call is returned.

@example
   (regexp-fold 'word
                (lambda (i m str acc)
                  (let ((s (regexp-match-submatch m 0)))
                   (cond ((assoc s acc)
                          => (lambda (x) (set-cdr! x (+ 1 (cdr x))) acc))
                         (else `((,s . 1) ,@@acc)))))
                '()
                "to be or not to be")
   @result{} '(("not" . 1) ("or" . 1) ("be" . 2) ("to" . 2))
@end example
@end defun


@defun regexp-extract @var{re} @var{str} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Returns a list of matched string or an empty list if no matches.

@example
   (regexp-extract '(+ numeric) "192.168.0.1")
   @result{} ("192" "168" "0" "1")
@end example
@end defun

@defun regexp-split @var{re} @var{str} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Returns a list of not matched substrings. This can be seen as the
opposite of @code{regexp-extract} where the matched strings are
removed instead of returned.

@example
   (regexp-split '(+ space) " fee fi  fo\tfum\n")
   @result{} ("fee" "fi" "fo" "fum")
   (regexp-split '(",;") "a,,b,")
   @result{} ("a" "" "b" "")
   (regexp-split '(* numeric) "abc123def456ghi789")
   @result{} ("abc" "def" "ghi" "")
@end example
@end defun

@defun regexp-partition @var{re} @var{str} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Returns a list of all matched and not matched substrings. In other
words it's the combination of @code{regexp-extract} and
@code{regexp-split} where the boundary of matched strings are used to
split the original string.

@example
   (regexp-partition '(+ (or space punct)) "")
   @result{} ("")
   (regexp-partition '(+ (or space punct)) "Hello, world!\n")
   @result{} ("Hello" ", " "world" "!\n")
   (regexp-partition '(+ (or space punct)) "¿Dónde Estás?")
   @result{} ("" "¿" "Dónde" " " "Estás" "?")
   (regexp-partition '(* numeric) "abc123def456ghi789")
   @result{} ("abc" "123" "def" "456" "ghi" "789")
@end example
@end defun

@defun regexp-replace @var{re} @var{str} @var{subst} [@var{start} [@var{end} [@var{count}]]]
[R7RS regex]
@c MOD scheme.regex
Returns a new string where the first matched substring is replaced
with @var{subst}. If @var{count} is specified, the @var{count}-th
match will be replaced instead of the first one.

@var{subst} can be either a string (the replacement), an integer or a
symbol to refer to the capture group that will be used as the
replacement, or a list of those.

The special symbols @code{pre} and @code{post} use the substring to
the left or right of the match as replacement, respectively.

@var{subst} could also be a procedure, which is
called with the given match object and the result will be used as the
replacement.

The optional parameters @var{start} and @var{end} essentially
transform the substitution into this

@example
   (regexp-replace re (substring str start end) subst)
@end example

except that @var{end} can take @code{#f} which is the same as
@code{(string-length str)}.

@example
   (regexp-replace '(+ space) "one two three" "_")
   @result{} "one_two three"
   (regexp-replace '(+ space) "one two three" "_" 1 10)
   @result{} "ne_two th"
   (regexp-replace '(+ space) "one two three" "_" 0 #f 0)
   @result{} "one_two three"
   (regexp-replace '(+ space) "one two three" "_" 0 #f 1)
   @result{} "one two_three"
   (regexp-replace '(+ space) "one two three" "_" 0 #f 2)
   @result{} "one two three"
@end example

Note that Gauche also has a builtin procedure of the same name, but
works slightly differently, @pxref{Using regular expressions}.
@end defun


@defun regexp-replace-all @var{re} @var{str} @var{subst} [@var{start} [@var{end}]]
[R7RS regex]
@c MOD scheme.regex
Returns a new string where all matches in @var{str} are replaced with
@var{subst}. @var{subst} can also take a string, a number, a symbol or
a procedure similar to @code{regexp-replace}.

@example
(regexp-replace-all '(+ space) "one two three" "_")
   @result{} "one_two_three"
@end example

Note that Gauche also has a builtin procedure of the same name, but
works slightly differently, @pxref{Using regular expressions}.
@end defun


@defun regexp-match? @var{obj}
[R7RS regex]
@c MOD scheme.regex
Returns true iff @var{obj} is a @code{<regexp-match>} object.

@example
(regexp-match? (regexp-matches "x" "x"))  @result{} #t
(regexp-match? (regexp-matches "x" "y"))  @result{} #f
@end example
@end defun


@defun regexp-match-count @var{regexp-match}
[R7RS regex]
@c MOD scheme.regex
Returns the number of matches in @var{match} except the implicit zero
full match. This is just an alias of @code{rxmatch-num-matches} minus
one.

@example
(regexp-match-count (regexp-matches "x" "x"))  @result{} 0
(regexp-match-count (regexp-matches '($ "x") "x"))  @result{} 1
@end example
@end defun

@defun regexp-match-submatch @var{regexp-match} @var{field}
[R7RS regex]
@c MOD scheme.regex
This is an alias of @code{rxmatch-substring}

@example
   (regexp-match-submatch (regexp-search 'word "**foo**") 0)  @result{} "foo"
   (regexp-match-submatch
    (regexp-search '(: "*" ($ word) "*") "**foo**") 0)  @result{} "*foo*"
   (regexp-match-submatch
    (regexp-search '(: "*" ($ word) "*") "**foo**") 1)  @result{} "foo"
@end example
@end defun

@defun regexp-match-submatch-start @var{regexp-match} @var{field}
[R7RS regex]
@c MOD scheme.regex
This is an alias of @code{regexp-match-submatch-start}.

@example
   (regexp-match-submatch-start
    (regexp-search 'word "**foo**") 0)  @result{} 2
   (regexp-match-submatch-start
    (regexp-search '(: "*" ($ word) "*") "**foo**") 0)  @result{} 1
   (regexp-match-submatch-start
    (regexp-search '(: "*" ($ word) "*") "**foo**") 1)  @result{} 2
@end example
@end defun

@defun regexp-match-submatch-end @var{regexp-match} @var{field}
[R7RS regex]
@c MOD scheme.regex
This is an alias of @code{regexp-match-submatch-end}.

@example
   (regexp-match-submatch-end
    (regexp-search 'word "**foo**") 0)  @result{} 5
   (regexp-match-submatch-end
    (regexp-search '(: "*" ($ word) "*") "**foo**") 0)  @result{} 6
   (regexp-match-submatch-end
    (regexp-search '(: "*" ($ word) "*") "**foo**") 1)  @result{} 5
@end example
@end defun

@defun regexp-match->list @var{regexp-match}
[R7RS regex]
@c MOD scheme.regex
This is an alias of @code{rxmatch-substrings}

@example
   (regexp-match->list
    (regexp-search '(: ($ word) (+ (or space punct)) ($ word)) "cats & dogs"))
    @result{} '("cats & dogs" "cats" "dogs")
@end example
@end defun

@node R7RS mappings, R7RS integer division, R7RS regular expressions, R7RS large
@subsection @code{scheme.mapping} - R7RS mappings
@c NODE R7RSマップ, @code{scheme.mapping} - R7RSマップ

@deftp {Module} scheme.mapping
@deftpx {Module} scheme.mapping.hash
@mdindex scheme.mapping
@mdindex scheme.mapping.hash
This module defines immutable mappings from keys to values.
Originally called @code{srfi-146} and @code{srfi-146.hash}.

The @code{scheme.mapping} module provides @emph{mapping} objects,
where keys have total order.  The @code{scheme.mapping.hash} module
provides @code{hashmap} objects, where keys can be hashed.

Currently, Gauche uses built-in @code{<tree-map>} for the mapping object,
and built-in @code{<hash-table>} for the hashmap object.
The actual implementation
may be changed in future versions, so the user must not rely on the
underlying implementations.

The caller must treat mappings and hashmaps as immutable object.
The modules also provide ``linear update'' APIs, which is @emph{allowed}
to mutate the mappings passed to the arguments, under assumption
that the argument won't be used afterwards.  The linear update APIs
are marked with @code{!} at the end of the name.
@end deftp

@menu
* Mappings::
* Hashmaps::
@end menu


@node Mappings, Hashmaps, R7RS mappings, R7RS mappings
@subsubsection Mappings
@c NODE Mappings

@deftp {Class} <mapping>
@clindex mapping
@c MOD scheme.mapping
On Gauche, this is just an alias of @code{<tree-map>}.
@end deftp

@subsubheading Constructors

@defun mapping comparator key value @dots{}
[R7RS mapping]
@c MOD scheme.mapping
Creates a new mapping with the given @var{comparator},
whose initial content is
provided by @var{key} @var{value} @dots{}.

The @var{comparator} argument must be a comparator
(@pxref{Basic comparators}).

The @var{key} @var{value} @dots{} arguments must be
even length, alternating keys and values.

@example
(define m (mapping default-comparator 'a 1 'b 2))

(mapping-ref m 'a) @result{} 1
(mapping-ref m 'b) @result{} 2
@end example
@end defun

@defun mapping-unfold p f g seed comparator
[R7RS mapping]
@c MOD scheme.mapping
Creates a new mapping, whose content is populated by
three procedures, @var{p}, @var{f} and @var{g}, and
a seed value @var{seed}, as follows.

In each iteration, we have a current seed value, whose initial
value is @var{seed}.

First, @var{p}, a stop predicate, is applied to the current
seed value. If it returns true, we stop iteration and returns
the new mapping.

Next, @var{f} is applied to the current seed value.  It must
return two values.  The first one is for a key and the second
one for the value.  We add this pair to the mapping.

Then, @var{g} is applied to the current seed value.  The result
becomes the seed value of the next iteration.  And we iterate.

The following example creates a mapping that maps ASCII characters
to their character codes:

@example
(mapping-unfold (cut >= <> 128)
                (^c (values (integer->char c) c))
                (cut + <> 1)
                0
                default-comparator)
@end example
@end defun

@defun mapping/ordered comparator key value @dots{}
[R7RS mapping]
@c MOD scheme.mapping
Similar to @code{mapping}, but keys are given in the ascending order
w.r.t. the comparator.  An implementation may use more efficient algorithm
than @code{mapping}.  In Gauche, this is the same as @code{mapping}
at this moment.
@end defun

@defun mapping-unfold/ordered p f g seed comparator
[R7RS mapping]
@c MOD scheme.mapping
Similar to @code{mapping-unfold}, but keys are generated in the
ascending order
w.r.t. the comparator.  An implementation may use more efficient algorithm
than @code{mapping-unfold}.
In Gauche, this is the same as @code{mapping-unfold} at this moment.
@end defun

@subsubheading Predicates

@defun mapping? obj
[R7RS mapping]
@c MOD scheme.mapping
Returns @code{#t} iff @var{obj} is a mapping object.
@end defun

@defun mapping-empty? m
[R7RS mapping]
@c MOD scheme.mapping
@var{M} must be a mapping.
Returns @code{#t} if @var{m} is empty, @code{#f} otherwise.
In Gauche, this is same as @code{tree-map-empty?}
(@pxref{Treemaps}).
@end defun

@defun mapping-contains? m key
[R7RS mapping]
@c MOD scheme.mapping
@var{M} must be a mapping.
Returns @code{#t} if @var{m} has an entry with @var{key},
@code{#f} otherwise.
In Gauche, this is same as @code{tree-map-exists?}
(@pxref{Treemaps}).
@end defun

@defun mapping-disjoint? m1 m2
[R7RS mapping]
@c MOD scheme.mapping
Returns @code{#t} iff two mappings @var{m1} and @var{m2} have no keys
in common.  In other words, there's no such key K that
satisfy both @code{(mapping-contains? m1 K)} and
@code{(mapping-contains? m2 K)}.
@end defun

@subsubheading Accessors

@defun mapping-ref m key :optional failure success
[R7RS mapping]
@c MOD scheme.mapping
Get the value from a mapping @var{m} associated with @var{key},
and calls @var{success} on the value, and returns its result.
If @var{m} doesn't have @var{key}, @var{failure} is invoked with no
arguments and its result is returned.
Both @var{success} and @var{failure} is called in tail context.

When @var{failure} is omitted and @var{key} is not found, an error
is signaled.  When @var{success} is omitted, @code{identity} is
assumed.
@end defun

@defun mapping-ref/default m key default
[R7RS mapping]
@c MOD scheme.mapping
Returns the value associated to @var{key} from a mapping @var{m}.
If @var{m} doesn't have @var{key}, @var{default} is returned.
@end defun

@defun mapping-key-comparator m
[R7RS mapping]
@c MOD scheme.mapping
Returns a comparator used to compare keys in a mapping @var{m}.
@xref{Basic comparators}, for the details of comparators.
@end defun

@subsubheading Updaters

Note that the basic premise of mappings srfi is to treat mappings
as immutable.  Each updating operation comes with a purely functional
version (without bang) and a linear update version (with bang), but
the linear update version may not require to destructively modiy
the passed mapping; it's merely a hint that it may reuse the
argument for the efficiency.  You always need to use the returned
mapping as the result of update.  If you use linear update versions,
you shouldn't use the passed mapping afterwards, for there's no guarantee
how the state of the passed mapping is.

@defun mapping-adjoin m arg @dots{}
@defunx mapping-adjoin! m arg @dots{}
[R7RS mapping]
@c MOD scheme.mapping
The @var{arg} @dots{} are alternating between key and value.  Returns
a mapping that contains all the entries in @var{m} plus given
keys and values, with the same comparator as @var{m}.
Linear update version @code{mapping-adjoin!} may destructively modify
@var{m} to create the return value, while @code{mapping-adjoin}
creates a new mapping.

Arguments are processed in order.
If there's already an entry in @var{m} with the same key as given to
@var{arg}, the original entry remains.

@example
(mapping-adjoin (mapping default-comparator 'a 1 'b 2) 'c 3 'a 4 'c 5)
 @result{} @r{mapping with @t{a} @arrow{} 1, @t{b} @arrow{} 2, @t{c} @arrow{} 3}
@end example
@end defun

@defun mapping-set m arg @dots{}
@defunx mapping-set! m arg @dots{}
[R7RS mapping]
@c MOD scheme.mapping
The @var{arg} @dots{} are alternating between key and value.  Returns
a mapping that contains all the entries in @var{m} plus given
keys and values, with the same comparator as @var{m}.
Linear update version @code{mapping-set!} may destructively modify
@var{m} to create the return value, while @code{mapping-set}
creates a new mapping.

Arguments are processed in order.
If there's already an entry in @var{m} with the same key as given to
@var{arg}, the new key-value pair supersedes the old one.

@example
(mapping-set (mapping default-comparator 'a 1 'b 2) 'c 3 'a 4 'c 5)
 @result{} @r{mapping with @t{a} @arrow{} 4, @t{b} @arrow{} 2, @t{c} @arrow{} 5}
@end example
@end defun

@defun mapping-replace m key value
@defunx mapping-replace! m key value
[R7RS mapping]
@c MOD scheme.mapping
If the mapping @var{m} has an entry of @var{key}, return a mapping
with the value of the entry replaced for @var{value}.  If @var{m} doesn't
have an entry with @var{key}, @var{m} is returned unchanged.

Linear update version @code{mapping-replace!} may destructively modify
@var{m} to produce the return value, while @code{mapping-replace}
creates a new mapping.

@example
(mapping-replace (mapping default-comparator 'a 1 'b 2) 'a 3)
 @result{} @r{mapping with @t{a} @arrow{} 3, @t{b} @arrow{} 2}

(mapping-replace (mapping default-comparator 'a 1 'b 2) 'c 3)
 @result{} @r{mapping with @t{a} @arrow{} 1, @t{b} @arrow{} 2}
@end example
@end defun


@defun mapping-delete m key @dots{}
@defunx mapping-delete! m key @dots{}
[R7RS mapping]
@c MOD scheme.mapping
Returns a mapping that is the same as @var{m} except its entries with
any of the given @var{key} @dots{} being removed.  Keys that are
not in @var{m} are ignored.

Linear update version @code{mapping-delete!} may destructively modify
@var{m} to produce the return value, while @code{mapping-delete}
creates a new mapping.
@end defun

@defun mapping-delete-all m key-list
@defunx mapping-delete-all! m key-list
[R7RS mapping]
@c MOD scheme.mapping
Returns a mapping that is the same as @var{m} except its entries with
any of the given keys in @var{key-list} being removed.  Keys that are
not in @var{m} are ignored.

Linear update version @code{mapping-delete-all!} may destructively modify
@var{m} to produce the return value, while @code{mapping-delete-all}
creates a new mapping.
@end defun


@defun mapping-intern m key make-value
@defunx mapping-intern! m key make-value
[R7RS mapping]
@c MOD scheme.mapping
Looks up @var{key} in the mapping @var{m}, and returns two values,
@var{m} and the associated value.  If @var{m} does not contain an entry
with @var{key}, a thunk @var{make-value} is invoked, and creates a new
mapping that contains all entries in @var{m} plus a new entry with
@var{key} and the return value of @var{make-value}, then returns the
new mapping and the return value of @var{make-value}.

Linear update version @code{mapping-intern!} may destructively modify
@var{m} to produce the return value, while @code{mapping-intern}
creates a new mapping.

@example
(mapping-intern (mapping default-comparator 'a 1) 'b (^[] 2))
  @result{}
  @r{mapping with @t{a} @arrow{} 1, @t{b} @arrow{} 2}
  @r{and}
  2

(mapping-intern (mapping default-comparator 'a 1) 'a (^[] 2))
  @result{}
  @r{mapping with @t{a} @arrow{} 1}
  @r{and}
  1
@end example
@end defun

@defun mapping-update m key updater :optional failure success
@defunx mapping-update! m key updater :optional failure success
[R7RS mapping]
@c MOD scheme.mapping
Semantically equivalent to this:

@example
(mapping-set @var{m} @var{var}
  (@var{updater} (mapping-ref @var{m} @var{key} @var{failure} @var{success})))
@end example

The @var{failure} and @var{success} optional arguments are procedures
with zero and one arguments, respectively.  When omitted,
@var{failure} defaults to a thunk that raises an error,
and @var{success} defaults to @code{identity}.

First, @var{key} is looked up in @var{m}.  If an entry is found,
the associated value is passed to @var{success}; otherwise,
@var{failure} is called with no arguments.  Either way, let the returned
value be @var{v0}.

Then, @var{v0} is passed to @var{updater}.  Let its result be @var{v1}.

Finally, a mapping with the same entries as @var{m} except the value of
@var{key} is altered to @var{v1} is returned.

Linear update version @code{mapping-update!} may destructively modify
@var{m} to produce the return value, while @code{mapping-update}
creates a new mapping.

@example
(mapping-update (mapping default-comparator 'a 1)
                'a (pa$ + 1))
 @result{} @r{mapping with @t{a} @arrow{} 2}

(mapping-update (mapping default-comparator)
                'a (pa$ + 1) (^[] 0))
 @result{} @r{mapping with @t{a} @arrow{} 1}
@end example
@end defun

@defun mapping-update/default m key updater default
@defunx mapping-update!/default m key updater default
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-pop m :optional failure
@defunx mapping-pop! m :optional failure
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-search m k failure success
@defunx mapping-search! m k failure success
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading The whole mapping

@defun mapping-size m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-find pred m failure
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-count pred m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-any? pred m
@defunx mapping-every? pred m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-keys m
@defunx mapping-values m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-entries m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading Mapping and folding

@defun mapping-map proc comparator m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-map/monotone proc comparator m
@defunx mapping-map/monotone! proc comparator m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-for-each proc m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-fold kons knil m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-fold/reverse kons knil m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-map->list proc m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-filter pred m
@defunx mapping-filter! pred m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-remove pred m
@defunx mapping-remove! pred m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-partition pred m
@defunx mapping-partition! pred m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading Copying and conversion

@defun mapping-copy m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping->alist m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun alist->mapping comparator alist
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun alist->mapping! m alist
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun alist->mapping/ordered comparator alist
@defunx alist->mapping/ordered! m alist
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading Submappings

@defun mapping=? comparator m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping<? comparator m1 m2 @dots{}
@defunx mapping<=? comparator m1 m2 @dots{}
@defunx mapping>? comparator m1 m2 @dots{}
@defunx mapping>=? comparator m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading Set operations

@defun mapping-union m1 m2 @dots{}
@defunx mapping-union! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-intersection m1 m2 @dots{}
@defunx mapping-intersection! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-difference m1 m2 @dots{}
@defunx mapping-difference! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-xor m1 m2 @dots{}
@defunx mapping-xor! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading Mappings with ordered keys

@defun mapping-min-key m
@defunx mapping-max-key m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-min-value m
@defunx mapping-max-value m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-min-entry m
@defunx mapping-max-entry m
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-key-predecessor m obj failure
@defunx mapping-key-successor m obj failure
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-range= m obj
@defunx mapping-range< m obj
@defunx mapping-range<= m obj
@defunx mapping-range> m obj
@defunx mapping-range>= m obj
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-range=! m obj
@defunx mapping-range<! m obj
@defunx mapping-range<=! m obj
@defunx mapping-range>! m obj
@defunx mapping-range>=! m obj
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-split m obj
@defunx mapping-split! m obj
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defun mapping-catenate comparator m1 key value m2
@defunx mapping-catenate! m1 key value m2
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@subsubheading Comparators

@defun make-mapping-comparator comparator
[R7RS mapping]
@c MOD scheme.mapping
@end defun

@defvar mapping-comparator
[R7RS mapping]
@c MOD scheme.mapping
@end defvar


@node Hashmaps,  , Mappings, R7RS mappings
@subsubsection Hashmaps
@c NODE Hashmaps

@subsubheading Constructors

@defun hashmap comparator key value @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
Creates a new hashmap with the given @var{comparator},
whose initial content is
provided by @var{key} @var{value} @dots{}.

The @var{comparator} argument must be a comparator
(@pxref{Basic comparators}).

The @var{key} @var{value} @dots{} arguments must be
even length, alternating keys and values.

@example
(define m (hashmap default-comparator 'a 1 'b 2))

(hashmap-ref m 'a) @result{} 1
(hashmap-ref m 'b) @result{} 2
@end example
@end defun

@defun hashmap-unfold p f g seed comparator
[R7RS mapping]
@c MOD scheme.mapping.hash
Creates a new hashmap, whose content is populated by
three procedures, @var{p}, @var{f} and @var{g}, and
a seed value @var{seed}, as follows.

In each iteration, we have a current seed value, whose initial
value is @var{seed}.

First, @var{p}, a stop predicate, is applied to the current
seed value. If it returns true, we stop iteration and returns
the new hashmap.

Next, @var{f} is applied to the current seed value.  It must
return two values.  The first one is for a key and the second
one for the value.  We add this pair to the hashmap.

Then, @var{g} is applied to the current seed value.  The result
becomes the seed value of the next iteration.  And we iterate.

The following example creates a hashmap that maps ASCII characters
to their character codes:

@example
(hashmap-unfold (cut >= <> 128)
                (^c (values (integer->char c) c))
                (cut + <> 1)
                0
                default-comparator)
@end example
@end defun

@subsubheading Predicates

@defun hashmap? obj
[R7RS mapping]
@c MOD scheme.mapping.hash
Returns @code{#t} iff @var{obj} is a hashmap object.
@end defun

@defun hashmap-empty? m
[R7RS mapping]
@c MOD scheme.mapping.hash
@var{M} must be a hashmap.
Returns @code{#t} if @var{m} is empty, @code{#f} otherwise.
In Gauche, this is same as @code{tree-map-empty?}
(@pxref{Treemaps}).
@end defun

@defun hashmap-contains? m key
[R7RS mapping]
@c MOD scheme.mapping.hash
@var{M} must be a hashmap.
Returns @code{#t} if @var{m} has an entry with @var{key},
@code{#f} otherwise.
In Gauche, this is same as @code{tree-map-exists?}
(@pxref{Treemaps}).
@end defun

@defun hashmap-disjoint? m1 m2
[R7RS mapping]
@c MOD scheme.mapping.hash
Returns @code{#t} iff two hashmaps @var{m1} and @var{m2} have no keys
in common.  In other words, there's no such key K that
satisfy both @code{(hashmap-contains? m1 K)} and
@code{(hashmap-contains? m2 K)}.
@end defun

@subsubheading Accessors

@defun hashmap-ref m key :optional failure success
[R7RS mapping]
@c MOD scheme.mapping.hash
Get the value from a hashmap @var{m} associated with @var{key},
and calls @var{success} on the value, and returns its result.
If @var{m} doesn't have @var{key}, @var{failure} is invoked with no
arguments and its result is returned.
Both @var{success} and @var{failure} is called in tail context.

When @var{failure} is omitted and @var{key} is not found, an error
is signaled.  When @var{success} is omitted, @code{identity} is
assumed.
@end defun

@defun hashmap-ref/default m key default
[R7RS mapping]
@c MOD scheme.mapping.hash
Returns the value associated to @var{key} from a hashmap @var{m}.
If @var{m} doesn't have @var{key}, @var{default} is returned.
@end defun

@defun hashmap-key-comparator m
[R7RS mapping]
@c MOD scheme.mapping.hash
Returns a comparator used to compare keys in a hashmap @var{m}.
@xref{Basic comparators}, for the details of comparators.
@end defun

@subsubheading Updaters

Note that the basic premise of hashmaps srfi is to treat hashmaps
as immutable.  Each updating operation comes with a purely functional
version (without bang) and a linear update version (with bang), but
the linear update version may not require to destructively modiy
the passed hashmap; it's merely a hint that it may reuse the
argument for the efficiency.  You always need to use the returned
hashmap as the result of update.  If you use linear update versions,
you shouldn't use the passed hashmap afterwards, for there's no guarantee
how the state of the passed hashmap is.

@defun hashmap-adjoin m arg @dots{}
@defunx hashmap-adjoin! m arg @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-set m arg @dots{}
@defunx hashmap-set! m arg @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-replace m key value
@defunx hashmap-replace! m key value
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun


@defun hashmap-delete m key @dots{}
@defunx hashmap-delete! m key @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-delete-all m key-list
@defunx hashmap-delete-all! m key-list
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun


@defun hashmap-intern m key failure
@defunx hashmap-intern! m key failure
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-update m key updater :optional failure success
@defunx hashmap-update! m key updater :optional failure success
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-update/default m key updater default
@defunx hashmap-update!/default m key updater default
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-pop m :optional failure
@defunx hashmap-pop! m :optional failure
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-search m k failure success
@defunx hashmap-search! m k failure success
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@subsubheading The whole hashmap

@defun hashmap-size m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-find pred m failure
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-count pred m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-any? pred m
@defunx hashmap-every? pred m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-keys m
@defunx hashmap-values m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-entries m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@subsubheading Mapping and folding

@defun hashmap-map proc comparator m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-for-each proc m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-fold kons knil m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-map->list proc m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-filter pred m
@defunx hashmap-filter! pred m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-remove pred m
@defunx hashmap-remove! pred m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-partition pred m
@defunx hashmap-partition! pred m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@subsubheading Copying and conversion

@defun hashmap-copy m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap->alist m
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun alist->hashmap comparator alist
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun alist->hashmap! m alist
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@subsubheading Subhashmaps

@defun hashmap=? comparator m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap<? comparator m1 m2 @dots{}
@defunx hashmap<=? comparator m1 m2 @dots{}
@defunx hashmap>? comparator m1 m2 @dots{}
@defunx hashmap>=? comparator m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@subsubheading Set operations

@defun hashmap-union m1 m2 @dots{}
@defunx hashmap-union! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-intersection m1 m2 @dots{}
@defunx hashmap-intersection! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-difference m1 m2 @dots{}
@defunx hashmap-difference! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defun hashmap-xor m1 m2 @dots{}
@defunx hashmap-xor! m1 m2 @dots{}
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@subsubheading Comparators

@defun make-hashmap-comparator comparator
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defun

@defvar hashmap-comparator
[R7RS mapping]
@c MOD scheme.mapping.hash
@end defvar

@c ----------------------------------------------------------------------
@node R7RS integer division, R7RS bitwise operations, R7RS mappings, R7RS large
@subsection @code{scheme.division} - R7RS integer division
@c NODE R7RS整数除算, @code{scheme.division} - R7RS整数除算

@deftp {Module} scheme.division
@mdindex scheme.division
@c EN
This module provides a comprehensive set of integer division operators.

Quotient and remainder in integer divisions can be defined in multiple
ways, when you consider the choice of sign of the result with regard to
the operands.  Gauche has builtin procedures in several flavors:
R5RS @code{quotient}, @code{remainder} and @code{modulo},
R6RS @code{div}, @code{mod}, @code{div0} and @code{mod0},
and R7RS @code{floor-quotient}, @code{floor-remainder}, @code{floor/},
@code{truncate-quotient}, @code{truncate-remainder}, @code{truncate/}.

This module complements R7RS procedures, by adding @code{ceiling},
@code{round}, @code{euclidean} and @code{balanced} variants.

The following procedures are in scheme.division but built-in in Gauche
(@pxref{Arithmetics}).
@c JP
このモジュールは、様々な整数除算操作を包括的に提供します。

整数除算の商と剰余には、除数と被除数の符号の考慮によって、
いくつかの定義が考えられます。
Gaucheはそのうちいくつかの定義を組み込みで提供しています：
R5RSの@code{quotient}、@code{remainder}、@code{modulo}、
R6RSの@code{div}、@code{mod}、@code{div0}、@code{mod0}、
そしてR7RSの
@code{floor-quotient}、@code{floor-remainder}、@code{floor/}、
@code{truncate-quotient}、@code{truncate-remainder}、@code{truncate/}、です。

このモジュールは、R7RSの手続きにさらに
@code{ceiling}、
@code{round}、@code{euclidean}、@code{balanced}のバリエーションを加えます。

scheme.divisionの以下の手続きについては組み込みになっているので、
@ref{Arithmetics}を参照してください。
@c COMMON
@example
floor-quotient     floor-remainder    floor/
truncate-quotient  truncate-remainder truncate/
@end example
@end deftp

@defun ceiling-quotient n d
@defunx ceiling-remainder n d
@defunx ceiling/ n d
[R7RS division]
@c MOD scheme.division
@example
ceiling-quotient = ceiling(n / d)
ceiling-remainder = n - d * ceiling-quotient
ceiling/ = values(ceiling-quotient, ceiling-remainder)
@end example
@end defun

@defun round-quotient n d
@defunx round-remainder n d
@defunx round/ n d
[R7RS division]
@c MOD scheme.division
@example
round-quotient = round(n/d)
round-remainder = n - d * round-quotient
round/ = values(round-quotient, round-remainder)
@end example
@end defun

@defun euclidean-quotient n d
@defunx euclidean-remainder n d
@defunx euclidean/ n d
[R7RS division]
@c MOD scheme.division
@example
euclidean-quotient = floor(n / d)   if d > 0
                     ceiling(n / d) if d < 0
euclidean-remainder = n - d * euclidean-quotient
euclidean/ = values(euclidean-quotient, euclidean-remainder)
@end example
@c EN
The Eclidean variant satisfies a property @code{0 <= remainder < abs(d)}.
These are the same as R6RS's @code{div}, @code{mod}, and @code{div-and-mod},
except that they accept non-integers (@pxref{Arithmetics})
@c JP
Eclideanバリエーションは、@code{0 <= remainder < abs(d)}という関係を常に満たします。
この定義はR6RSの@code{div}、@code{mod}および@code{div-and-mod}と同じです。
但し、R6RS版は非整数を引数に取ることもできます(@ref{Arithmetics}参照)。
@c COMMON
@end defun

@defun balanced-quotient n d
@defunx balanced-remainder n d
@defunx balanced/ n d
[R7RS division]
@c MOD scheme.division
@example
balanced-quotient = roundup(n / d)
balanced-remainder = n - d * balanced-quotient
balanced/ = values(balanced-quotient, balanced-remainder)
@c EN
  where roundup(x) rounds towards zero if |x| - floor(|x|) < 0.5,
                   and away from zero  if |x| - floor(|x|) >= 0.5,
@c JP
  ここでroundup(x)は、|x| - floor(|x|) < 0.5 ならゼロの方向に、
                       |x| - floor(|x|) >= 0.5 ならゼロと逆方向丸めます
@c COMMON
@end example
@c EN
The balanced variant satisfies a property
@code{-abs(d/2) <= remainder < abs(d/2)}.
These are the same as R6RS's @code{div0}, @code{mod0}, and
@code{div0-and-mod0}, except that they accept non-integers
(@pxref{Arithmetics}).
@c JP
Balancedバージョンは@code{-abs(d/2) <= remainder < abs(d/2)}という
関係を常に満たします。これはR6RSの
@code{div0}、@code{mod0}および@code{div0-and-mod0}と同じです。
但し、R6RS版は非整数を引数に取ることもできます(@ref{Arithmetics}参照)。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node R7RS bitwise operations, R7RS fixnum, R7RS integer division, R7RS large
@subsection @code{scheme.bitwise} - R7RS bitwise operations
@c NODE R7RSビット演算, @code{scheme.bitwise} - R7RSビット演算

@deftp {Module} scheme.bitwise
@mdindex scheme.bitwise
@c EN
This module provides comprehensive bitwise operations.
Originally it was srfi-151.
It is mostly a superset of srfi-60, with some change of names for the consistency
and the compatibility (@pxref{Integers as bits}).  We keep srfi-60 for
legacy code, while recommend this module to be used in the new code.

The following procedures are Gauche built-in.
@xref{Basic bitwise operations}, for the description.
@c JP
このモジュールは包括的なビット演算手続きを提供します。
元はsrfi-151で、
ほぼsrfi-60のスーパーセットですが、いくつかの手続きは一貫性と互換性のために
名前が変わりました(srfi-60については@ref{Integers as bits}参照)。
srfi-60も以前のコードとの互換性のため残されますが、新たに書くコードは
このモジュールを使うことを推奨します。

以下の手続きはGauche組み込みになっています。
説明は@ref{Basic bitwise operations}を参照してください。
@c COMMON

@example
integer-length    copy-bit          bit-field
@end example
@end deftp

@c EN
@subheading Basic operations
@c JP
@subheading 基本演算
@c COMMON

@defun bitwise-not n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns the bitwise complement of @var{n}.
Same as builtin @code{lognot} (@pxref{Basic bitwise operations}).
@c JP
@var{n}の各ビットを反転したものを返します。
組み込みの@code{lognot}と同じです。(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun bitwise-and n @dots{}
@defunx bitwise-ior n @dots{}
@defunx bitwise-xor n @dots{}
@defunx bitwise-eqv  n @dots{}
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
When no arguments are given, these procedures returns @code{-1}, @code{0},
@code{0} and @code{-1}, respectively.  With one arguments, they return the
argument as is.  With two arguments, they return bitwise and, ior, xor,
and eqv (complement of xor).  With three or more arguments, they apply
binary operations associaively, that is,
@c JP
引数が与えられない場合、これらはそれぞれ@code{-1}、@code{0}、@code{0}、@code{-1}を
返します。引数がひとつの場合はそれをそのまま返します。
引数が二つの場合は、それらのビット毎のand、ior、xor、及びeqv (xorの論理反転) を
取ったものを返します。3引数以上は、2引数の計算から導かれます。
@c COMMON

@example
(bitwise-xor a b c)
 @equiv{} (bitwise-xor a (bitwise-xor b c))
 @equiv{} (bitwise-xor (bitwise-xor a b) c)
@end example

@c EN
Be careful that multi-argument @code{bitwise-eqv} does not produce
bit 1 everywhere that all the argument's bit agree.
@c JP
この定義では、3引数以上の@code{bitwise-eqv}は
「すべての引数の該当ビットが同じである時に1」とはならないことに注意してください。
@c COMMON

@c EN
The first three procedures are the same as built-in
@code{logand}, @code{logior} and @code{logxor}, respectively
(@pxref{Basic bitwise operations}).
@c JP
最初の3つの手続きはそれぞれ組み込みの
@code{logand}、@code{logior}、@code{logxor}と同じです
(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun bitwise-nand n0 n1
@defunx bitwise-nor n0 n1
@defunx bitwise-andc1 n0 n1
@defunx bitwise-andc2 n0 n1
@defunx bitwise-orc1 n0 n1
@defunx bitwise-orc2 n0 n1
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
These operations are not associative.
@c JP
これらの手続きは2引数固定です。
@c COMMON

@example
nand n0 n1   @equiv{}  (NOT (AND n0 n1))
nor n0 n1    @equiv{}  (NOT (OR n0 n1))
andc1 n0 n1  @equiv{}  (AND (NOT n0) n1)
andc2 n0 n1  @equiv{}  (AND n0 (NOT n1))
orc1 n0 n1   @equiv{}  (OR (NOT n0) n1)
orc2 n0 n1   @equiv{}  (OR n0 (NOT n1))
@end example
@end defun

@c EN
@subheading Integer operations
@c JP
@subheading 整数演算
@c COMMON

@defun arithmetic-shift n count
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Shift @var{n} for @var{count} bits to left; if @var{count} is negative,
it shifts @var{n} to right for @var{-count} bits.

Same as builtin @code{ash} (@pxref{Basic bitwise operations}).
@c JP
整数@var{n}を@var{count}ビット左シフトします。@var{count}が負ならば、
@code{n}は@var{-count}ビット右にシフトされることになります。

これは組み込みの@code{ash}と同じです(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun bit-count n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
If @var{n} is positive, returns the number of @code{1}'s in @var{n}.
If @var{n} is negative, returns the number of @code{0}'s in @var{n}.

Same as builtin @code{logcount} (@pxref{Basic bitwise operations}).
@c JP
@var{n}が正の場合は@var{n}中の@code{1}であるビットの数を、
@var{n}が負の場合は@var{n}中の@code{0}であるビットの数を返します。

組み込みの@code{logcount}と同じです(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun bitwise-if mask n0 n1
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns integer, whose @var{n}-th bit is taken as follows:
If the @var{n}-th bit of @var{mask} is 1, the @var{n}-th bit of @var{n0};
otherwise, the @var{n}-th bit of @var{n1}.
@c JP
整数を返します。戻り値の@var{n}番目のビットは、@var{mask}の@var{n}番目のビットが
1であれば@var{n0}の@code{n}番目のビット、0であれば@var{n1}の@code{n}番目のビット
になります。
@c COMMON

@example
(bitwise-if #b10101100 #b00110101 #b11001010)
 @result{} #b01100110
@end example
@end defun

@c EN
@subheading Single-bit operations
@c JP
@subheading 単一ビットの操作
@c COMMON

@defun bit-set? index n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns @code{#t} or @code{#f} if @var{index}-th bit (counted from LSB)
of @var{n} is @code{1} or @code{0}, respectively.

Same as built-in @code{logbit?} (@pxref{Basic bitwise operations}).
@c JP
@var{n}のLSBから数えて@var{index}番目(0ベース)のビットが@code{1}であれば
@code{#t}を、@code{0}であれば@code{#f}を返します。

組み込みの@code{logbit?}と同じです(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun bit-swap index1 index2 n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns an integer with @var{index1}-th bit and @var{index2}-th bit are
swapped.  Index is counted from LSB.
@c JP
@var{n}の@var{index1}番目のビットと@var{index2}番目のビットを入れ替えた整数を
返します。インデックスは0ベースでLSBから数えます。
@c COMMON
@end defun

@defun any-bit-set? mask n
@defunx every-bit-set? mask n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns @code{#t} iff any/all bits set in @var{mask} are also set in @var{n}.

@code{any-bit-set?} is the same as built-in @code{logtest},
except @code{logtest} accepts one or more arguments
(@pxref{Basic bitwise operations}).
@c JP
@var{n}中で、@var{mask}でビットの立っている箇所のビットのいずれか(@code{any-bit-set?})
あるいはすべて(@code{every-bit-set?})が@code{1}であれば@code{#t}を返し、
それ以外では@code{#f}を返します。

@code{any-bit-set?}は組み込みの@code{logtest}とほぼ同じですが、
@code{logtest}は可変長引数です
(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun first-set-bit n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns the number of factors of two of integer @var{n}; that is,
returns a maximum @code{k} such that @code{(expt 2 k)} divides
@var{n} without a remainder.
It is the same as the index of the least significant @code{1} in @var{n},
hence the alias @code{first-set-bit}.
@c JP
@var{n}を割り切る@code{(expt 2 k)}のうち最大のkを返します。別の言い方をすれば、
@var{n}のビット列のうち一番右にある@code{1}のインデックスを返します。
@code{first-set-bit}の名前はそこからきています。
@c COMMON

@example
(first-set-bit 0) @result{} -1   ; @r{edge case}
(first-set-bit 1) @result{} 0
(first-set-bit 2) @result{} 1
(first-set-bit 15) @result{} 0
(first-set-bit 16) @result{} 4
@end example

@c EN
This is equivalent to Gauche's built-in @code{twos-exponent-factor}
(@pxref{Basic bitwise operations}).
@c JP
これはGauche組み込みの@code{twos-exponent-factor}と同じです
(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@c EN
@subheading Bit field operations
@c JP
@subheading ビットフィールド操作
@c COMMON

@defun bit-field-any? n start end
@defunx bit-field-every? n start end
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns @code{#t} iff any/all bits of @var{n} from @var{start} (inclusive)
to @var{end} (exclusive) are set.
@c JP
@var{n}中の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までの
ビットフィールドのうち、一つでもビットが立っていた場合(@code{bit-field-any?})、
あるいは全てのビットが立っていた場合(@code{bit-field-every?})に@code{#t}を、
それ以外に@code{#f}を返します。
@c COMMON
@end defun

@defun bit-field-clear n start end
@defunx bit-field-set n start end
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns @var{n} with the bits from @var{start} (inclusive)
to @var{end} (exclusive) are set to all @code{0}'s/@code{1}'s.
@c JP
@var{n}中の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までの
ビットを全て@code{0}あるいは@code{1}にした整数値を返します。
@c COMMON
@end defun

@defun bit-field-replace dst src start end
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns @var{dst} with the bitfield from @var{start} to @var{end}
are replaced with the least-significant (@var{end}-@var{start}) bits
of @var{src.}
@c JP
@var{dst}中の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までの
ビットフィールドを、@var{src}中の下位(@var{end}-@var{start})ビットで置き換えた
値を返します。
@c COMMON

@example
(bit-field-replace #b101010 #b010 1 4) @result{} #b100100
@end example

@c EN
Same as built-in @code{copy-bit-field} (@pxref{Basic bitwise operations}).
@c JP
組み込みの@code{copy-bit-field}と同じです(@ref{Basic bitwise operations}参照)。
@c COMMON
@end defun

@defun bit-field-replace-same dst src start end
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns @var{dst} with the bitfield from @var{start} to @var{end}
are replaced with the @code{src}'s bitfield from @var{start} to @var{end}.
@c JP
@var{dst}中の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までの
ビットフィールドを、
@var{src}中の同じ位置にあるビットフィールドに置き換えた値を返します。
@c COMMON

@example
(bit-field-replace-same #b111111 #b100100 1 4) @result{} #b110101
@end example
@end defun

@defun bit-field-rotate n count start end
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Rotate the region of @var{n} between @var{start}-th bit (inclusive) and
@var{end}-th bit (exclusive) by @var{count} bits to the left.
If @var{count} is negative, it rotates to the right by @var{-count}
bits.
@c JP
@var{n}中の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までの
ビットフィールドを、@var{count}ビットだけ左にローテートした値を返します。
@var{count}が負の場合は@var{-count}ビットだけ右にローテートします。
@c COMMON

@example
(bit-field-rotate #b110100100010000 -1 5 9)
 @result{} 26768 ;#b110100010010000

(bit-field-rotate #b110100100010000 1 5 9)
 @result{} 26672 ;#b110100000110000
@end example
@end defun

@defun bit-field-reverse n start end
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Reverse the order of bits of @var{n} between @var{start}-th bit
(inclusive) and @var{end}-th bit (exclusive).
@c JP
@var{n}中の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までの
ビットフィールドを逆順にしたものを返します。
@c COMMON

@example
(bit-field-reverse #b10100111 0 8)
 @result{} 229 ; #b11100101
@end example
@end defun

@c EN
@subheading Bits conversion
@c JP
@subheading ビット変換
@c COMMON

@defun bits->list n :optional len
@defunx bits->vector n :optional len
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns a list/vector of booleans of length @var{len},
corresponding to each bit in non-negative integer @var{n}, LSB-first.
When @var{len} is omitted, @code{(integer-length n)} is used.
@c JP
非負整数@var{n}を、長さ@var{len}の真偽値からなるリストまたはベクタにして返します。
ビットはLSBから順に取り出されます。@var{len}が省略された場合は
@code{(integer-length n)}が使われます。
@c COMMON

@example
(bits->vector #b101101110)
  @result{} #(#f #t #t #t #f #t #t #f #t)
@end example

@c EN
Note: Srfi-60 has a similar @code{integer->list}, but the order of
bits is reversed.
@c JP
註: srfi-60には@code{integer->list}という似た手続きがありますが、
ビットの順番が逆です。
@c COMMON
@end defun

@defun list->bits bool-list
@defunx vector->bits bool-vector
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns an exact integer formed from boolean values in given list/vector,
LSB first.  The result will never be negative.
@c JP
真偽値のリストまたはベクタを受け取り、
LSBから対応するビットを詰めた正確な整数を返します。
返り値は負になることはありません。
@c COMMON

@example
(list->bits '(#f #t #t #t #f #t #t #f #t))
 @result{} #b101101110
@end example

@c EN
Note: Srfi-60 has a similar @code{list->integer}, but the order of
bits is reversed.
@c JP
註: srfi-60には@code{list->integer}という似た手続きがありますが、
ビットの順番が逆です。
@c COMMON
@end defun

@defun bits bool @dots{}
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns the integer coded by @var{bool}s, LSB first.
The result will never be negative.
@c JP
真偽値@var{bool}の列をLSBから順にビットとして詰めた整数を返します。
返り値は負になることはありません。
@c COMMON

@example
(bits #f #t #t #t #f #t #t #f #t)
 @result{} #b101101110
@end example

@c EN
Note: Srfi-60 has a similar @code{booleans->integer}, but the order of
bits is reversed.
@c JP
註: srfi-60には@code{booleans->integer}という似た手続きがありますが、
ビットの順番が逆です。
@c COMMON
@end defun

@c EN
@subheading Fold, unfold and generate
@c JP
@subheading Foldとunfoldとgenerate
@c COMMON

@defun bitwise-fold kons knil n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Traverse bits in integer @var{n} from LSB to the @code{(integer-length n)} bit,
applying @code{kons} on the bit as boolean
and the seed value, whose initial value
is given by @var{knil}.  Returns the last result of @var{kons}.
@c JP
整数@var{n}のビットを、LSBから@code{(integer-length n)}ビット分、順に調べ、
各ビットを真偽値とみなした値とシード値に@var{kons}を適用してゆきます。
@var{kons}の戻り値が次のシード値となり、最後の@var{kons}の結果が返されます。
@c COMMON

@example
(bitwise-fold cons '() #b10110111)
 @result{} (#t #f #t #t #f #t #t #t)
@end example
@end defun

@defun bitwise-for-each proc n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Applies @var{proc} to the bit as boolean in @var{n}, from LSB to
the @code{(integer-length n)} bit.  The result is discarded.
@c JP
整数@var{n}の各ビットを真偽値とみなした値に対して、
LSBから順に@code{(integer-length n)}ビット分、@var{proc}を適用してゆきます。
@var{proc}の結果は捨てられます。
@c COMMON
@end defun

@defun bitwise-unfold p f g seed
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Generates a non-negative integer bit by bit, from LSB to MSB.
The @var{seed} gives the initial state value.
For each iteration, @var{p} is applied to the current state value,
and if it returns a true value, the iteration ends and @code{bitwise-unfold}
returns the accumulated bits as an integer.
Otherwise, @var{f} is applied to the current state value, and
its result, coerced to a boolean value, determines the bit value.
Then @var{g} is applied to the current state value to produce
the next state value of the next iteration.
@c JP
非負整数をLSBから順に1ビットづつ生成します。
@var{seed}は状態の値の初期値を与えます。
各繰り返しにおいて、@var{p}が現在の状態の値に適用され、
その結果が真ならば繰り返しは終了し@code{bitwise-unfold}は蓄積されたビットを整数として
返します。
そうでなければ、@var{f}が現在の状態の値に適用され、
その結果が真の値なら対応するビットが1に、偽なら0になります。
次いで@var{g}が現在の状態の値に適用され、その結果が次の繰り返しにおける状態の値となります。
@c COMMON

@c EN
The following expression produces a bitfield of width 100, where n-th bit
indicates whether n is prime or not:
@c JP
次の式は、nビット目が、nが素数なら1になっているような100ビット長の整数を返します。
@c COMMON

@example
(use math.prime)
(bitwise-unfold (cut = 100 <>)
                small-prime?
                (cut + 1 <>)
                0)
@end example
@end defun

@defun make-bitwise-generator n
[R7RS bitwise]
@c MOD scheme.bitwise
@c EN
Returns a generator that generates boolean values
corresponding to the bits in @var{n}, LSB-first.  The returned generator
is infinite.

This is similar to @code{bits->generator} in @code{gauche.generator},
except that the generator created by it stops at the integer
length of @var{n} (@pxref{Generators}).
@c JP
整数nの各ビットをLSBから順に真偽値として生成するようなジェネレータを作って返します。
返されるジェネレータは無限です。

これは@code{gauche.integer}の@code{bits->generator}と似ていますが、
@code{bits->generator}が作るジェネレータの方は@var{n}の@code{integer-length}で止まります。
詳しくは@ref{Generators}を参照してください。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node R7RS fixnum, R7RS flonum, R7RS bitwise operations, R7RS large
@subsection @code{scheme.fixnum} - R7RS fixnums
@c NODE R7RS fixnum, @code{scheme.fixnum} - R7RS fixnum

@deftp {Module} scheme.fixnum
@mdindex scheme.finxum
@c EN
This module provides a set of fixnum-specific operations.
Originally defined as srfi-143.

A fixnum is a small exact integer that can be handled very efficiently.
In Gauche, fixnum is 62bit wide on 64bit platforms, and
30bit wide on 32bit platforms.
@c JP
このモジュールはfixnumに特化した操作を提供します。
srfi-143として制定されました。

fixnumは絶対値が小さめの正確な整数で、極めて効率的に処理できます。
Gaucheのfixnumは、64ビット環境では62ビット、32ビット環境では30ビットの幅を持ちます。
@c COMMON

@c EN
Note that these procedures are defined only to work on fixnums,
but it is not enforced.  If you pass non-fixnum arguments, or
the result falls out of range of fixnums, what happens is up to
the implementation.  Consider these procedures as the way to
tell your intentions to the compiler for potential optimizations.
@c JP
このモジュールの手続きはfixnumの範囲でしか動作を定義されていませんが、
それを強制するのではないことに注意してください。fixnumでない引数を
渡したり、結果がfixnumの範囲外になった場合に何が起きるかは
処理系依存とされています。これらの手続きは、プログラマがその意図を
コンパイラに伝えて最適化を期待するためのものと考えると良いでしょう。
@c COMMON

@c EN
In the current Gauche architecture,
generic numeric operators are just as efficient,
so most procedures provided in this module are aliases to corresponding
operators.   However, we might employ some optimizations in future
versions.
@c JP
現在のGaucheのアーキテクチャでは一般的な数値計算が効率よく実行できるようになっているので、
これらの手続きは対応する手続きの単なる別名になっています。
将来は、fixnum特有の最適化を導入するかもしれません。
@c COMMON

@c EN
The procedure @code{fixnum?} is built-in, and
not explained here.  @xref{Numerical predicates}.
@c JP
手続き@code{fixnum?}は組み込みなのでここでは説明しません。
@ref{Numerical predicates}を参照してください。
@c COMMON
@end deftp

@defvar fx-width
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
A variable bound to an exact positive integer @var{w}, where @var{w}
is the greatest number such that exact integers between
@code{2^(w-1) - 1} and @code{-2^(w-1)} are all fixnums.
This value is the same as the built-in procedure @code{fixnum-width}
returns (@pxref{Arithmetics}).

In Gauche, it is usually @code{30} for 32bit platforms, and @code{62} for
64bit platforms.
@c JP
@code{2^(w-1) - 1}から@code{-2^(w-1)}までの正確な整数が全てfixnumであるような
最大の正整数@code{w}に束縛された変数です。
組み込み手続き@code{fixnum-width}が返す値と同じです。
(@ref{Arithmetics}参照)。

Gaucheでは、これは通常32ビット環境で@code{30}、64ビット環境で@code{62}です。
@c COMMON
@end defvar

@defvar fx-greatest
@defvarx fx-least
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
Variables bound to the greatest fixnum and the least fixnum.
They are the same as the built-in procedures
@code{greatest-fixnum} and @code{least-fixnum} return, respectively
(@pxref{Arithmetics}).

The following table shows the typical values on Gauche:
@c JP
最大および最小のfixnumに束縛された変数です。これらの値は
組み込み手続き@code{greatest-fixnum}および@code{least-fixnum}が
返すものと同じです(@ref{Arithmetics}参照)。

次の表はGaucheでの典型的な値を示します。
@c COMMON

@multitable {Platform} {2,305,843,009,213,693,951} {-2,305,843,009,213,693,951}
@headitem Platform @tab @code{fx-greatest} @tab @code{fx-least}
@item 32bit @tab 536,870,911 @tab -536,870,912
@item 64bit @tab 2,305,843,009,213,693,951 @tab -2,305,843,009,213,693,952
@end multitable
@end defvar

@defun fx=? i @dots{}
@defunx fx<? i @dots{}
@defunx fx<=? i @dots{}
@defunx fx>? i @dots{}
@defunx fx>=? i @dots{}
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to built-in @code{=}, @code{<}, @code{<=},
@code{>} and @code{>=}, except that you should use these only for fixnums.
@c JP
これらは、fixnumのみに適用しなければならないことを除き、組み込みの
@code{=}、@code{<}、@code{<=}、@code{>}、@code{>=}と同じです。
@c COMMON
@end defun

@defun fxzero? i
@defunx fxpositive? i
@defunx fxnegative? i
@defunx fxodd? i
@defunx fxeven? i
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to built-in @code{zero?}, @code{positive?},
@code{negative?}, @code{odd?} and @code{even?},
except that you should use these only for fixnums.
@c JP
これらは、fixnumのみに適用しなければならないことを除き、組み込みの
@code{zero?}、@code{positive?}、@code{negative?}、@code{odd?}、@code{even?}と同じです。
@c COMMON
@end defun

@defun fxmax i j @dots{}
@defunx fxmin i j @dots{}
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to built-in @code{max} and  @code{min},
except that you should use these only for fixnums.
@c JP
これらは、fixnumのみに適用しなければならないことを除き、組み込みの
@code{max}および@code{min}と同じです。
@c COMMON
@end defun

@defun fx+ i j
@defunx fx- i j
@defunx fx* i j
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to built-in @code{+}, @code{-}
and  @code{*},
except that these take exactly two arguments, and
you should use these only for fixnums and
when the result fits within fixnum range.
@c JP
これらは、常に2つの引数を取ること、
fixnumのみに適用しなければならないこと、
そして結果がfixnumの範囲に収まる場合だけに使わなければならないことを除き、
組み込みの@code{+}、@code{-}、@code{*}と同じです。
@c COMMON
@end defun

@defun fxneg i
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
This is equivalent to single-argument @code{-},
except that you should use this only for fixnums and
when the result fits within fixnum range.
@c JP
これは、fixnumのみに適用しなければならないこと、
そして結果がfixnumの範囲に収まる場合だけに使わなければならないことを除き、
組み込みの単項@code{-}と同じです。
@c COMMON
@end defun

@defun fxquotient i j
@defunx fxremainder i j
@defunx fxabs i
@defunx fxsquare i
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to built-in @code{quotient}, @code{remainder},
@code{abs} and @code{square},
except that you should use these only for fixnums and
when the result fits within fixnum range.
@c JP
これらは、fixnumのみに適用しなければならないこと、
そして結果がfixnumの範囲に収まる場合だけに使わなければならないことを除き、
組み込みの@code{quotient}、@code{remainder}、@code{abs}、@code{square}と
同じです。
@c COMMON
@end defun

@defun fxsqrt i
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
This is equivalent to @code{exact-integer-sqrt} (not @code{sqrt}),
except that you should use it only for fixnums.
@xref{Arithmetics}.
@c JP
これらは、fixnumのみに適用しなければならないことを除き、
@code{exact-integer-sqrt}と同じです。@code{sqrt}ではありません。
@ref{Arithmetics}参照。
@c COMMON
@end defun

@defun fx+/carry i j k
@defunx fx-/carry i j k
@defunx fx*/carry i j k
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These calculates @code{(+ i j k)}, @code{(- i j k)} and @code{(+ (* i j) k)},
respectively, then split the result to the remainder value @code{R}
in the fixnum range, and spilled value @code{Q}, and return those values.
That is,
@code{(+ (* Q (expt 2 fx-width)) R)} is the result of above calculations.
Both @code{Q} and @code{R} fits in the fixnum range, and
@code{- 2^(w-1) <= R < 2^(w-1)}, where @code{w} is @code{fx-width}.
@c JP
これらはそれぞれ、まず
@code{(+ i j k)}、@code{(- i j k)}、@code{(+ (* i j) k)}を計算し、
その結果をfixnumの範囲内に収まる剰余@code{R}と、溢れ@code{Q}に分割して
2つの値として返します。
すなわち、@code{(+ (* Q (expt 2 fx-width)) R)}が上記計算と一致します。
@code{Q}と@code{R}は常にfixnumの範囲内であり、また@code{R}は
@code{- 2^(w-1) <= R < 2^(w-1)}を満たします。ただし@code{w}は
@code{fx-width}です。
@c COMMON

@example
(fx*/carry 1845917459 19475917581 4735374)
 @result{} -942551854601421179 @r{and} 8

(+ (* 8 (expt 2 fx-width)) -942551854601421179)
 @result{} 35950936292817682053

(+ (* 1845917459 19475917581) 4735374)
 @result{} 35950936292817682053
@end example

@c EN
These are primitives to implement extended-precision
integer arithmetic on top of fixnum operations.  In Gauche, however,
you can just use built-in bignums.  We provide these for the compatibility.
@c JP
これらは拡張精度整数演算をfixnum手続き上に効率よく実装するためのプリミティブです。
ただ、Gaucheでは必要ならbignumを使えば良いので、これらは単に互換性のために提供しています。
@c COMMON
@end defun

@defun fxnot i
@defunx fxand i @dots{}
@defunx fxior i @dots{}
@defunx fxxor i @dots{}
@defunx fxarithmetic-shift i count
@defunx fxlength i
@defunx fxbit-count i
@defunx fxcopy-bit index i boolean
@defunx fxbit-set? index i
@defunx fxbit-field i start end
@defunx fxfirst-set-bit i
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to @code{lognot}, @code{logand},
@code{logior}, @code{logxor}, @code{ash}, @code{integer-length},
@code{logcount},
@code{copy-bit}, @code{logbit?}, @code{bit-field},
and @code{twos-exponent-factor} respectively,
except that you should use these only for fixnums.
@xref{Basic bitwise operations}.
@c JP
これらはfixnumのみに適用しなければならないことを除き、
組み込みの@code{lognot}、 @code{logand}、
@code{logior}、 @code{logxor}、 @code{ash}、 @code{integer-length}、
@code{logcount}、
@code{copy-bit}、 @code{logbit?}、 @code{bit-field}、
@code{twos-exponent-factor}とそれぞれ同じです。
詳しくは@ref{Basic bitwise operations}参照。
@c COMMON
@end defun

@defun fxif mask i j
@defunx fxbit-field-rotate i start end
@defunx fxbit-field-rotate i start end
[R7RS fixnum]
@c MOD scheme.fixnum
@c EN
These are equivalent to srfi-60's
@code{bitwise-if}, @code{rotate-bit-field} and
@code{reverse-bit-field},
except that you should use these only for fixnums.
@xref{Integers as bits}.
@c JP
これらはfixnumのみに適用しなければならないことを除き、
srfi-60の@code{bitwise-if}、@code{rotate-bit-field}、
@code{reverse-bit-field}と同じです。
@ref{Integers as bits}参照。
@c COMMON
@end defun


@c ----------------------------------------------------------------------
@node R7RS flonum, R7RS bytevectors, R7RS fixnum, R7RS large
@subsection @code{scheme.flonum} - R7RS flonum
@c NODE R7RS flonum, @code{scheme.flonum} - R7RS flonum

@deftp {Module} scheme.flonum
@mdindex scheme.flonum
@c EN
This module provides a set of flonum-specific operations.
Originally defined as srfi-144.

In Gauche, a flonum is IEEE 754 double-precision floating point numbers.
@c JP
このモジュールはflonumに特化した操作を提供します。
srfi-144として制定されました。

Gaucheでは、flonumはIEEE754倍精度浮動小数点数です。
@c COMMON

@c EN
Note that these procedures are defined only to work on flonums,
but it is not enforced.  If you pass non-flonum arguments,
the result is undefined.
Consider these procedures as the way to
tell your intentions to the compiler for potential optimizations.
@c JP
このモジュールの手続きはflonumの範囲でしか動作を定義されていませんが、
それを強制するのではないことに注意してください。flonumでない引数を
渡した場合の動作は未定義です。これらの手続きは、プログラマがその意図を
コンパイラに伝えて最適化を期待するためのものと考えると良いでしょう。
@c COMMON

@c EN
In the current Gauche architecture,
generic numeric operators are just as efficient,
so most procedures provided in this module are aliases to corresponding
operators.   However, we might employ some optimizations in future
versions.
@c JP
現在のGaucheのアーキテクチャでは一般的な数値計算が効率よく実行できるようになっているので、
これらの手続きは対応する手続きの単なる別名になっています。
将来は、flonum特有の最適化を導入するかもしれません。
@c COMMON

@c EN
The procedure @code{flonum?} is built-in, and
not explained here.  @xref{Numerical predicates}.
@c JP
手続き@code{flonum?}は組み込みなのでここでは説明しません。
@ref{Numerical predicates}を参照してください。
@c COMMON
@end deftp

@c EN
@subheading Constants
@c JP
@subheading 定数
@c COMMON

We also have a few constants in @code{math.const} module
(@pxref{Mathematic constants}).

@defvr {Constant} fl-e
[R7RS flonum]
@c MOD scheme.flonum
e.
@end defvr

@defvr {Constant} fl-1/e
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ e)}.
@end defvr


@defvr {Constant} fl-e-2
[R7RS flonum]
@c MOD scheme.flonum
@code{(square e)}.
@end defvr

@defvr {Constant} fl-e-pi/4
[R7RS flonum]
@c MOD scheme.flonum
@code{(expt e (/ pi 4))}.
@end defvr

@defvr {Constant} fl-log2-e
[R7RS flonum]
@c MOD scheme.flonum
@code{(log2 e)}.  (Same as @code{(/ (log 2))}).
@end defvr

@defvr {Constant} fl-log10-e
[R7RS flonum]
@c MOD scheme.flonum
@code{(log10 e)}.  (Same as @code{(/ (log 10))}).
@end defvr

@defvr {Constant} fl-log-2
[R7RS flonum]
@c MOD scheme.flonum
@code{(log 2)}.
@end defvr

@defvr {Constant} fl-1/log-2
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ (log 2))}.  (Same as @code{(log2 e)}).
@end defvr

@defvr {Constant} fl-log-3
[R7RS flonum]
@c MOD scheme.flonum
@code{(log 3)}.
@end defvr

@defvr {Constant} fl-log-pi
[R7RS flonum]
@c MOD scheme.flonum
@code{(log pi)}.
@end defvr

@defvr {Constant} fl-log-10
[R7RS flonum]
@c MOD scheme.flonum
@code{(log 10)}.
@end defvr

@defvr {Constant} fl-1/log-10
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ (log 10))}.  (Same as @code{(log10 e)}).
@end defvr

@defvr {Constant} fl-pi
[R7RS flonum]
@c MOD scheme.flonum
@code{pi}.
@end defvr

@defvr {Constant} fl-1/pi
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ pi)}.
@end defvr

@defvr {Constant} fl-2pi
[R7RS flonum]
@c MOD scheme.flonum
@code{(* 2 pi)}.
@end defvr

@defvr {Constant} fl-pi/2
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ pi 2)}.
@end defvr

@defvr {Constant} fl-pi/4
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ pi 4)}.
@end defvr

@defvr {Constant} fl-pi-squared
[R7RS flonum]
@c MOD scheme.flonum
@code{(square pi)}.
@end defvr

@defvr {Constant} fl-degree
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ pi 180)}.
@end defvr

@defvr {Constant} fl-2/pi
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ 2 pi)}.
@end defvr

@defvr {Constant} fl-2/sqrt-pi
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ 2 (sqrt pi))}.
@end defvr

@defvr {Constant} fl-sqrt-2
@code{(sqrt 2)}.
@end defvr

@defvr {Constant} fl-sqrt-3
[R7RS flonum]
@c MOD scheme.flonum
@code{(sqrt 3)}.
@end defvr

@defvr {Constant} fl-sqrt-5
[R7RS flonum]
@c MOD scheme.flonum
@code{(sqrt 5)}.
@end defvr

@defvr {Constant} fl-sqrt-10
[R7RS flonum]
@c MOD scheme.flonum
@code{(sqrt 10)}.
@end defvr

@defvr {Constant} fl-1/sqrt-2
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ (sqrt 2))}.
@end defvr

@defvr {Constant} fl-cbrt-2
[R7RS flonum]
@c MOD scheme.flonum
@code{(expt 2 1/3)}.
@end defvr

@defvr {Constant} fl-cbrt-3
[R7RS flonum]
@c MOD scheme.flonum
@code{(expt 3 1/3)}.
@end defvr

@defvr {Constant} fl-4thrt-2
[R7RS flonum]
@c MOD scheme.flonum
@code{(expt 2 1/4)}.
@end defvr

@defvr {Constant} fl-phi
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ (+ 1 (sqrt 5)) 2)}.
@end defvr

@defvr {Constant} fl-log-phi
[R7RS flonum]
@c MOD scheme.flonum
@code{(log fl-phi)}.
@end defvr

@defvr {Constant} fl-1/log-phi
[R7RS flonum]
@c MOD scheme.flonum
@code{(/ (log fl-phi))}.
@end defvr

@defvr {Constant} fl-euler
[R7RS flonum]
@c MOD scheme.flonum
Euler's constant.
@end defvr

@defvr {Constant} fl-e-euler
[R7RS flonum]
@c MOD scheme.flonum
@code{(exp fl-euler)}
@end defvr

@defvr {Constant} fl-sin-1
[R7RS flonum]
@c MOD scheme.flonum
@code{(sin 1)}
@end defvr

@defvr {Constant} fl-cos-1
[R7RS flonum]
@c MOD scheme.flonum
@code{(cos 1)}
@end defvr

@defvr {Constant} fl-gamma-1/2
[R7RS flonum]
@c MOD scheme.flonum
@code{(gamma 1/2)}
@end defvr

@defvr {Constant} fl-gamma-1/3
[R7RS flonum]
@c MOD scheme.flonum
@code{(gamma 1/3)}
@end defvr

@defvr {Constant} fl-gamma-2/3
[R7RS flonum]
@c MOD scheme.flonum
@code{(gamma 2/3)}
@end defvr

@defvr {Constant} fl-gamma-1/3
[R7RS flonum]
@c MOD scheme.flonum
@code{(gamma 1/3)}
@end defvr

@defvr {Constant} fl-greatest
@defvrx {Constant} fl-least
[R7RS flonum]
@c MOD scheme.flonum
Bound to the largest/smallest positive finite flonum.

The latter is the same as @code{(flonum-min-denormalized)} in Gauche
(@pxref{Numerical comparison}).
@end defvr

@defvr {Constant} fl-epsilon
[R7RS flonum]
@c MOD scheme.flonum
@c EN
The same as @code{(flonum-epsilon)} in Gauche
(@pxref{Numerical comparison}).
@c JP
Gaucheの@code{(flonum-epsilon)}と同じです。
(@ref{Numerical comparison}参照)。
@c COMMON
@end defvr

@defvr {Constant} fl-fast-fl+*
[R7RS flonum]
@c MOD scheme.flonum
@c EN
If this is @code{#t}, @code{(fl+* x y z)} executes as fast as,
or faster than, @code{(fl+ (fl* x y) z)}.  If not, @code{#f}.
@c JP
これが@code{#t}を返した場合、@code{(fl+* x y z)}は
@code{(fl+ (fl* x y) z)}と同等の速度、もしくはより速く実行されます。
@c COMMON
@end defvr

@defvr {Constant} fl-integer-exponent-zero
@defvrx {Constant} fl-integer-exponent-nan
[R7RS flonum]
@c MOD scheme.flonum
@c EN
These are exact integer values returned in special occasion
from @code{flinteger-exponent}.  The values themselves don't mean
much; they're to be compared with the result of @code{flinteger-exponent}.

If its argument is 0, @code{flinteger-exponent} returns
@code{fl-integer-exponent-zero}.  If its argument is @code{+nan.0},
@code{flinteger-exponent} returns @code{fl-integer-exponent-nan}.
@c JP
これらは、@code{flinteger-exponent}が特別な場合に返し得る正確な整数値です。
値そのものに意味はなく、@code{flinteger-exponent}の結果と比較するために使われます。

@code{flinteger-exponent}は引数が0の時@code{fl-integer-exponent-zero}を、
引数が@code{+nan.0}の時@code{fl-integer-exponent-nan}を返します。
@c COMMON
@end defvr

@c EN
@subheading Constructors
@c JP
@subheading コンストラクタ
@c COMMON

@defun flonum number
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns a flonum that's equal to or (if there's no equivalent flnoum)
the closest to @var{number}.

If @var{number} is not a real number,
@code{+nan.0} is returned.  (Note: srfi-144 recommends it, but
a conformant implementation may signal an error in such case.
Portable code shouldn't rely on this behavior.)
@c JP
@var{number}と等しいflonum、もしくは等しい値がflonumで表現可能でなければもっとも近い
flonumを返します。

@var{number}が実数でなければ@code{+nan.0}が返されます
(これはsrfi-144で推奨されている動作ですが、処理系によってはエラーを投げても良いことに
なっているので、ポータブルなコードを書くときは注意してください。)
@c COMMON
@end defun

@defun fladjacent x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns a flonum adjacent to @var{x} in the direction of @var{y}.
If @var{x} = @var{y}, @var{x} is returned.
@c JP
flonum @var{x}から@var{y}の方向に1最小単位だけ進めたflonumを返します。
@var{x} = @var{y}なら、@var{x}そのものが返されます。
@c COMMON

@example
(fladjacent 1.0 2.0) @result{} 1.0000000000000002
(fladjacent 1.0 0.0) @result{} 0.9999999999999999
@end example
@end defun

@defun flcopysign x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns a flonum whose absolute value is @code{(abs x)} and whose
sign is the sign of @var{y}.
@c JP
絶対値が@code{(abs x)}と同じで、符号が@var{y}と同じであるようなflonumを返します。
@c COMMON
@end defun


@defun make-flonum x n
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns a flonum @code{(* @var{x} (expt 2 @var{n}))}.  It is the same
as @code{ldexp} (@pxref{Numerical conversions}).
@c JP
@code{(* @var{x} (expt 2 @var{n}))}なるflonumを返します。
Gaucheの@code{ldexp}と同じです (@ref{Numerical conversions}参照)。
@c COMMON
@end defun

@c EN
@subheading Accessors
@c JP
@subheading アクセサ
@c COMMON

@defun flinteger-fraction x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns two flnoums, the integral part of @var{x} and the fractional
part of @var{x}.  Same as @code{modf} (@pxref{Numerical conversions}).

If @var{x} is @code{+inf.0}, @code{+inf.0} and @code{0.0} is returned.
If @var{x} is @code{-inf.0}, @code{-inf.0} and @code{-0.0} is returned.
If @var{x} is @code{+nan.0}, @code{+nan.0} and @code{+nan.0} is returned.
(These corner cases are not explicit in srfi-144, but follows
the POSIX specification of @code{modf}.)
@c JP
flonum @var{x}の整数部と小数部をそれぞれflonumとして返します。
Gaucheの@code{modf}と同じです (@ref{Numerical conversions}参照)。

@var{x}が@code{+inf.0}なら、@code{+inf.0}と@code{0.0}が、
@var{x}が@code{-inf.0}なら、@code{-inf.0}と@code{-0.0}が、
そして@var{x}が@code{+nan.0}なら、@code{+nan.0}と@code{+nan.0}が返されます。
(この動作はsrfi-144では指定されていません。GaucheはPOSIXの@code{modf}の動作に
準じています)。
@c COMMON

@example
(flinteger-fraction fl-pi)
 @result{} 3.0 @r{and} 0.14159265358979312
@end example
@end defun

@defun flexponent x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns the exponent part of @var{x} as a flnoum.  If @var{x} is
a non-zero finite value, the result is an integer.

If @var{x} is zero, @code{-inf.0} is returned.
If @var{x} is @var{+inf.0} or @code{-inf.0}, @code{+inf.0} is returned.
@c JP
flonum @var{x}の指数部をflonumとして返します。@var{x}がゼロでない有限値なら、
結果は整数です。

@var{x}がゼロなら、@code{-inf.0}が、
@var{x}が無限大なら、@code{+inf.0}が返されます。
@c COMMON

@example
(flexponent 1.0)    @result{} 0.0
(flexponent 1024.0) @result{} 10.0
(flexponent 0.01)   @result{} -7.0
(flexponent fl-least) @result{} -1074.0
@end example
@end defun

@defun flinteger-exponent x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns the same as @code{flexponent} but as an exact integer.

If @var{x} is zero, the value of @code{fl-integer-exponent-zero} is
returned.
If @var{x} is @var{+inf.0} or @code{-inf.0}, a large
implementation-dependent exact integer (usually it's so large that
@code{(ldexp 1 (flinteger-exponent +inf.0))} becomes @code{+inf.0})
is returned.
If @var{x} is @code{+nan.0}, the value of
@code{fl-integer-exponent-nan} is returned.
@c JP
@code{flexponent}と同様に@var{x}の指数部を返しますが、こちらは正確な整数を返します。

@var{x}がゼロの場合、定数@code{fl-integer-exponent-zero}が返されます。
@var{x}が無限大の場合、非常に大きな正確な整数
(@code{(ldexp 1 (flinteger-exponent +inf.0))}が@code{+inf.0}になるような
値)が返されます。
@var{x}が@code{+nan.0}の場合、定数@code{fl-integer-exponent-nan}が返されます。
@c COMMON
@end defun

@defun flnormalized-fraction-exponent x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns two values, a normalized mantissa of @var{x} with the same sign
as @var{x} as a flonum, and an exact integer exponent of @var{x}.  If it returns
a value @var{y} and @var{n}, @code{x = (* y (expt 2 n))} and
@code{x = (ldexp y n)}.
This is the same as @code{frexp}
(@pxref{Numerical conversions}).
@c JP
flonum @var{x}の正規化された仮数部 (符号は@var{x}と同じ)をflonumで、
および@var{x}の指数部を正確な整数で2つの返り値として返します。
それらを@var{y}と@var{n}とすれば、@code{x = (* y (expt 2 n))}であり、
@code{x = (ldexp y n)}となります。
この手続きはGaucheの@code{frexp}と同じです(@ref{Numerical conversions}参照)。
@c COMMON

@c EN
If @var{x} is non-zero finite value, the first value
falls between 0.5 (inclusive) and 1.0 (exclusive).
The corner cases are not explicit in srfi-144, but Gauche follows
@code{frexp}: If @var{x} is (minus) zero, it returns
(minus) zero and 0; if @var{x} is infinity, it returns
infinity (of the same sign) and 0; if @var{x} is @code{+nan.0},
it returns @code{+nan.0} and 0.
@c JP
@var{x}がゼロでない有限の値ならば、
最初の返り値は0.5以上で1.0より小さな値になります。
コーナーケースについてはsrfi-144では規程されていませんが、Gaucheは
@code{frexp}の仕様に沿って、次のようにしています。
@var{x}が@code{0.0}(か@code{-0.0})なら、結果は@code{0.0}(か@code{-0.0})と@code{0}。
@var{x}が無限大なら、同じ符号の無限大と@code{0}。
@var{x}が@code{+nan.0}なら、@code{+nan.0}と@code{0}。
@c COMMON

@example
(flnormalized-fraction-exponent 12345.6789)
  @result{} 0.7535204406738282 @r{and} 14
(make-flonum 0.7535204406738282 14)
  @result{} 12345.6789
@end example
@end defun

@defun flsign-bit x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns 0 if @var{x} is positive or @var{0.0},
and 1 if it is negative (including @code{-0.0}).
@code{(flsign-bit +nan.0)} is implementation-dependent.

There's also @code{flsgn}, if you need sign instead of a bit value.
@c JP
@var{x}が正もしくは@code{0.0}なら@code{0}を、
負もしくは@code{-0.0}なら@code{1}を返します。
@code{(flsign-bit +nan.0)}は実装依存です。

ビット値でなく符号が欲しい場合、@code{flsgn}も使えます。
@c COMMON
@end defun

@c EN
@subheading Predicates
@c JP
@subheading 述語
@c COMMON

@c EN
(Note: @code{flonum?} is built-in; @pxref{Numerical predicates}).
@c JP
(註: @code{flonum?}は組み込みです。@ref{Numerical predicates}参照)。
@c COMMON

@defun fl=? x y z @dots{}
@defunx fl<? x y z @dots{}
@defunx fl>? x y z @dots{}
@defunx fl<=? x y z @dots{}
@defunx fl>=? x y z @dots{}
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum specific version of numerical comparison predicates
@code{=}, @code{<}, @code{>}, @code{<=} and @code{>=}, respectively.

Currently these are just an alias of the generic numerical comparison
predicates; hence they don't reject when you pass non-flonum
arguments, but doing so is not portable.  These are to give
compilers hints that you are passing flonums so that it can optimize.

Note that @code{-0.0} and @code{0.0} are the same in terms of
these predicates, e.g. @code{(fl<? -0.0 0.0)} is @code{#f}.

If a @code{+nan.0} is passed to any of the arguments, these predicates returns
@code{#f}.
@c JP
flonum専用の比較関数です。それぞれ
@code{=}、@code{<}、@code{>}、@code{<=}、@code{>=}に対応します。

今のところGaucheではこれらは単に汎用の比較関数の別名となっています。
なのでflonum以外の数値が渡されても動作しますが、そうすることはポータブルではありません。
これらの関数の意図は、将来的にコンパイラに型についてのヒントを与え
最適化を可能にすることです。

@code{-0.0}と@code{0.0}は数値比較においては等しいものと扱われることに
注意してください。@code{(fl<? -0.0 0.0)}は@code{#f}になります。

引数に@code{+nan.0}がひとつでもあれば、結果は常に@code{#f}となります。
@c COMMON
@end defun

@defun flunordered? x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{#t} iff at least one of @var{x} or @var{y} is
a @code{+nan.0}.
@c JP
@var{x}と@var{y}の少なくとも一方が@code{+nan.0}であれば@code{#t}を、
そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@defun flinteger? x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{#t} if @var{x} is an integral flonum,
@code{#f} otherwise.
@c JP
@var{x}が整数のflonumであれば@code{#t}を、
そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@defun flzero? x
@defunx flpositive? x
@defunx flnevative? x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{zero?}, @code{positive?} and @code{negative?}.
Note that @code{(flnegative? -0.0)} is @code{#f}.
You need @code{flsign-bit} or @code{flsgn} to
distinguish negative zero from zero.
@c JP
flonum専用の@code{zero?}、@code{positive?}、@code{negative?}です。
@code{(flnegative? -0.0)}は@code{#f}であることに注意してください。
負のゼロを普通のゼロと見分けるには@code{flsign-bit}や@code{flsgn}を使います。
@c COMMON
@end defun

@defun flodd? x
@defunx fleven? x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{odd?} and @code{even?}.  An error is thrown
if @var{x} is not an integer.
@c JP
flonum専用の@code{odd?}と@code{even?}です。
@var{x}が整数でなければエラーが投げられます。
@c COMMON
@end defun

@defun flfinite? x
@defunx flinfinite? x
@defunx flnan? x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{finite?}, @code{infinite?} and
@code{nan?} (@pxref{Numerical predicates}).
@c JP
それぞれflonum専用の@code{finite?}、@code{infinite?}、
@code{nan?}です (@ref{Numerical predicates}参照)。
@c COMMON
@end defun

@defun flnormalized? x
@defunx fldenormalized? x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{#t} iff @var{x} is a normalized/denormalized flonum,
respectively.
@c JP
それぞれ、@var{x}が正規化浮動小数点数、非正規化浮動小数点数の場合に
@code{#t}を返し、そうでなければ@code{#f}を返します。
@c COMMON
@end defun

@c EN
@subheading Arithmetic
@c JP
@subheading 演算
@c COMMON

@defun flmax x @dots{}
@defunx flmin x @dots{}
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{min} and @code{max}, except that
these can take no arguments, in which case @code{-inf.0}
and @code{+inf.0} are returned, respectively.

Note that we don't check whether the arguments are flonums or not,
but passing non-flonums are not portable.
@c JP
flonum専用の@code{min}と@code{max}です。汎用の@code{min}、@code{max}と
異なり、引数がゼロ個でもエラーにならず、それぞれ@code{-inf.0}と
@code{+inf.0}が返されます。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun fl+ x @dots{}
@defunx fl* x @dots{}
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{+.} and @code{*.}
(@pxref{Arithmetics}).

Note that we don't check whether the arguments are flonums or not,
but passing non-flonums is not portable.
@c JP
flonum専用の@code{+.}と@code{-.}です (@ref{Arithmetics}参照)。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun fl+* x y z
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(+ (* x y) z)}, but (potentially) faster, and more accurately.
It calls C99 @code{fma} function internally.  ``More accurately'' means
that calculation is done in a single step, with rounding once at the end.

Note: As of release of 0.9.8, MinGW implementation of @code{fma} seems
to produce slightly off value occasionally, as if it is calculated
with the two steps (rounding after multiplication).
@c JP
@code{(+ (* x y) z)}の値を返しますが、
プラットフォームによってはより速く正確な結果を返します。
Gaucheは内部的にはC99の@code{fma}を呼んでいます。
「より正確」というのは、乗算と加算が一度に行われ、丸めが最後に1回だけ起きることを
指します。

註: 0.9.8リリース時点で、MinGWの@code{fma}実装は
乗算と加算それぞれに丸めが入るようになっているので、
しばしばわずかにずれた結果を返します。
@c COMMON
@end defun

@defun fl- x y @dots{}
@defunx fl- x y @dots{}
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{-.} and @code{/.}
(@pxref{Arithmetics}).

Note that we don't check whether the arguments are flonums or not,
but passing non-flonums is not portable.
@c JP
flonum専用の@code{-.}と@code{/.}です (@ref{Arithmetics}参照)。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun flabs x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{abs}
(@pxref{Arithmetics}).

Note that we don't check whether the argument is a flonum or not,
but passing non-flonum is not portable.
@c JP
flonum専用の@code{abs}です (@ref{Arithmetics}参照)。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun flabsdiff x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(abs (- x y))}.

Note that we don't check whether the arguments are flonums or not,
but passing non-flonum is not portable.
@c JP
@code{(abs (- x y))}を返します。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun flposdiff
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(max (- x y) 0)}.

Note that we don't check whether the arguments are flonums or not,
but passing non-flonum is not portable.
@c JP
@code{(max (- x y) 0)}を返します。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun flsgn x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{1.0} if @var{x}'s sign bit is 0 (zero or positive),
@code{-1.0} if it's 1 (negative).  Same as @code{(flcopysign 1.0 x)},
or @code{(if (zero? (flsign-bit x)) 1.0 -1.0)}.
Note that @code{(flsgn 0.0)} is @code{1.0}, while
@code{(flsgn -0.0)} is @code{-1.0}.  The result of
passing @code{+nan.0} is implementation-dependent, reflecting
the sign bit of underlying representation; it returns either @code{1.0} or
@code{-1.0} but you can't count on which.

To extract the sign bit, instead of obtaining a signed flonum,
you can use @code{flsign-bit}.
@c JP
@var{x}の符号ビットが0 (ゼロまたは正)なら@code{1.0}を、
1 (負および負のゼロ)の場合は@code{-1.0}を返します。
@code{(flcopysign 1.0 x)}や@code{(if (zero? (flsign-bit x)) 1.0 -1.0)}
と考えることもできます。
@code{(flsgn 0.0)}の結果は@code{1.0}、
@code{(flsng -0.0)}の結果は@code{-1.0}です。
@code{+nan.0}を渡した場合の結果は実装上NaNの符号ビットがどうなっているかに
よるので、結果は@code{1.0}か@code{-1.0}かのいずれかになりますが、
どちらになるかはっきりしたことは言えません。

符号つきflonumではなく符号ビットそのものを取り出すには@code{flsign-bit}が使えます。
@c COMMON
@end defun

@defun flnumerator x
@defunx fldenominator x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{numerator} and @code{denominator}
(@pxref{Arithmetics}).

For infinity and zero, denominator is 1.0.

Note that we don't check whether the arguments are flonums or not,
but passing non-flonum is not portable.
@c JP
flonum専用の@code{numerator}と@code{denominator}です
(@ref{Arithmetics}参照)。

無限大とゼロのdenominatorは@code{1.0}になります。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@defun flfloor x
@defunx flceiling x
@defunx flround x
@defunx fltruncate x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{floor}, @code{ceiling},
@code{round} and @code{truncate}
(@pxref{Arithmetics}).

Note that we don't check whether the arguments are flonums or not,
but passing non-flonum is not portable.
@c JP
flonum専用の@code{floor}、@code{ceiling}、@code{round}、@code{truncate}です
(@ref{Arithmetics}参照)。

引数がflonumかどうかはチェックしていませんが、flonum以外の引数を渡すことは
ポータブルではありません。
@c COMMON
@end defun

@c EN
@subheading Exponents and logarithms
@c JP
@subheading 指数対数関数
@c COMMON

@defun flexp x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{exp} (@pxref{Arithmetics}).
Returns @code{(expt fl-e x)}.
@c JP
flonum専用の@code{exp}です (@ref{Arithmetics}参照)。
@code{(expt fl-e x)}を返します。
@c COMMON
@end defun

@defun flexp2 x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(expt 2 x)}
@c JP
@code{(expt 2 x)}を返します。
@c COMMON
@end defun

@defun flexp-1 x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(- 1 (expt fl-e x))}, but is much more accurate
when @var{x} is small.  We call C's @code{expm1} internally.
@c JP
@code{(- 1 (expt fl-e x))}を返しますが、@var{x}が小さい場合はより正確です。
内部的にはCの@code{expm1}を呼んでいます。
@c COMMON
@end defun

@defun flsquare x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(*. x x)}
@c JP
@code{(*. x x)}を返します。
@c COMMON
@end defun

@defun flsqrt x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{sqrt}.
@c JP
flonum専用の@code{sqrt}です。
@c COMMON
@end defun

@defun flcbrt x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns cubic root of a flonum @var{x}.
@c JP
flonum @var{x}の3乗根を返します。
@c COMMON
@end defun

@defun flhypot x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Calculates @code{(sqrt (* x x) (* y y))}, with avoiding
overflow or underflow during the intermediate steps.
@c JP
@code{(sqrt (* x x) (* y y))}を計算しますが、
中間結果でオーバーフローやアンダーフローが起きないように配慮されています。
@c COMMON
@end defun

@defun flexpt x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{expt} (@pxref{Arithmetics}).
@c JP
flonum専用の@code{expt}です(@ref{Arithmetics}参照)。
@c COMMON
@end defun

@defun fllog x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{log} (@pxref{Arithmetics}).
@c JP
flonum専用の@code{log}です(@ref{Arithmetics}参照)。
@c COMMON
@end defun

@defun fllog1+ x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(log (+ x 1))}, but is more accurate than @code{log}
when @var{x} is near zero.
@c JP
@code{(log (+ x 1))}を返しますが、@var{x}がゼロに近い場合により正確です。
@c COMMON
@end defun

@defun fllog2 x
@defunx fllog10 x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns base-2 and base-10 logarithm of a flonum @var{x}, respectively.
@c JP
flonum @var{x}の2および10を底とする対数を返します。
@c COMMON
@end defun

@defun make-fllog-base x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns a procedure that calculates base-@var{x} logarithm.
An error is signalled if @var{x} isn't a real number greater than 1.0.
@c JP
@var{x}を底とする対数を計算する手続きを返します。@var{x}が1.0より大きい実数でない
場合はエラーが投げられます。
@c COMMON

@example
(define log5 (make-fllog-base 5.0))

(log5 25.0) @result{} 5.0
@end example
@end defun

@c EN
@subheading Trigonometric functions
@c JP
@subheading 三角関数
@c COMMON

@defun flsin x
@defunx flcos x
@defunx fltan x
@defunx flasin x
@defunx flacos x
@defunx flatan x
@defunx flatan y x
@defunx flsinh x
@defunx flcosh x
@defunx fltanh x
@defunx flasinh x
@defunx flacosh x
@defunx flatanh x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Flonum-specific version of @code{sin}, @code{cos}, @code{tan},
@code{asin}, @code{acos}, @code{sinh}, @code{cosh}, @code{tanh},
@code{asinh}, @code{acosh}, and @code{atanh}, respectively
(@pxref{Arithmetics}).
@c JP
それぞれ、flonum専用の
@code{sin}, @code{cos}, @code{tan},
@code{asin}, @code{acos}, @code{sinh}, @code{cosh}, @code{tanh},
@code{asinh}, @code{acosh}, @code{atanh}です
(@ref{Arithmetics}参照)。
@c COMMON

@c EN
Note that @code{flatan} can take one or two arguments; if two arguments
are passed, it calculates @code{(atan (/ y x)}.
@c JP
@code{flatan}は1つまたは2つの引数を取ります。@code{(flatan y x)}は
@code{(flatan (/ y x))}を計算します (が、より正確です)。
@c COMMON
@end defun

@c EN
@subheading Integer division
@c JP
@subheading 整数除算
@c COMMON

@defun flquotient x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(fltruncate (fl/ x y))}.

The result is always integer flonum, but @var{x} and @var{y} doesn't
need to be integers.
@c JP
@code{(fltruncate (fl/ x y))} を返します。

結果は常に整数のflonumになります。引数@var{x}、@var{y}は整数である必要はありません。
@c COMMON

@example
(flquotient 14.0 4.0)  @result{} 3.0
(flquotient -14.0 4.0) @result{} -3.0
(flquotient 14.0 2.5)  @result{} 5.0
(flquotient -14.2 2.8) @result{} -5.0
@end example
@end defun

@defun flremainder x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns @code{(- x (* y (flquotient x y)))}.
@c JP
@code{(- x (* y (flquotient x y)))}を返します。
@c COMMON

@example
(flquotient 14.0 4.0)  @result{} 2.0
(flquotient -14.0 4.0) @result{} -2.0
(flquotient 14.0 2.5)  @result{} 1.5
(flquotient -14.2 2.8) @result{} -0.1999999999999993 ; inexact calculation
@end example
@end defun

@defun flremquo x y
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns two values:
@c JP
二つの値を返します:
@c COMMON
@itemize @bullet
@item
@c EN
Remainder of @var{x} divided by @var{y}.
(Same as @code{(flremainder x y)}, but we calculate it in different
routines so the result may differ in a few ulp.
@c JP
@var{x}を@var{y}で割った余り。
(@code{(flremainder x y)}と同じですが、異なる計算方法を使うので
最後のビットで差が出るかもしれません)。
@c COMMON
@item
@c EN
Integer quotient of @var{x} divided by @var{y}, modulo 2^@var{n} (@var{n} >= 3), as
an exact integer.  Its sign is the same as @var{x}/@var{y}.
@c JP
2^@var{n} (@var{n} >= 3) を法とする、@var{x}割る@var{y}の商。
正確な整数で、@var{x}/@var{y}と同じ符号を持ちます。
@c COMMON
@end itemize

@c EN
This corresponds to C99's @code{remquo}.
@c JP
これはC99の@code{remquo}に相当します。
@c COMMON

@c EN
This function is useful to reduce the input for the periodic functions
with symmetries.
@c JP
周期関数の入力を対称性を使って絞る時に便利です。
@c COMMON
@end defun


@c EN
@subheading Special functions
@c JP
@subheading 特殊関数
@c COMMON

@defun flgamma x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Computes the value of gamma function for a flonum @var{x}.
When @var{x} is integer, it is the same as the factorial of @var{x}-1.

This is same as Gauche's built-in @code{gamma} (@pxref{Arithmetics}).
@c JP
flonum @var{x}のガンマ関数を計算します。
@var{x}が整数の時は、@var{x}-1の階乗と一致します。

これはGauche組み込みの@code{gamma}と同じです (@ref{Arithmetics}参照)。
@c COMMON
@end defun

@defun flloggamma x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns two values, @code{(log (abs (flgamma x)))} and the sign of
@code{(flgamma x)} as 1.0 if it is positive and -1.0 if it is negative.
@c JP
@code{(log (abs (flgamma x)))}の値および、@code{(flgamma x)}の符号
(正の場合は1.0、負の場合は-1.0)の二つの値を返します。
@c COMMON

@c EN
The first value is calculated by Gauche's built-in @code{lgamma}
(@pxref{Arithmetics}).  It's more accurate than using @code{gamma} then
calling @code{log}.  The second value is @code{+nan.0} when
@var{x} is @code{-inf.0} or @code{+nan.0}.
@c JP
最初の値はGauche組み込みの@code{lgamma}で計算されます (@ref{Arithmetics}参照)。
これは@code{gamma}を計算して@code{log}を取るより正確です。
なお、@var{x}が@code{-inf.0}か@code{+nan.0}の場合、二番目の値は@code{+nan.0}になります。
@c COMMON
@end defun

@defun flfirst-bessel n x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns the @var{n}-th order Bessel function of the first kind.
@c JP
@var{n}階の第1種ベッセル関数の値を返します。
@c COMMON
@end defun

@defun flsecond-bessel n x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns the @var{n}-th order Bessel function of the second kind.
@c JP
@var{n}階の第2種ベッセル関数の値を返します。
@c COMMON
@end defun

@defun flerf x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns the error function erf(@var{x}).
@c JP
誤差関数erfです。
@c COMMON
@end defun

@defun flerfc x
[R7RS flonum]
@c MOD scheme.flonum
@c EN
Returns the complementary error function, 1 - erf(@var{x}).
@c JP
1 - erf(@var{x}) を計算します。
@c COMMON
@end defun

@c ----------------------------------------------------------------------
@node R7RS bytevectors, R7RS combinator formatting, R7RS flonum, R7RS large
@subsection @code{scheme.bytevector} - R7RS bytevectors
@c NODE R7RS bytevectors, @code{scheme.bytevector} - R7RS bytevector

@deftp {Module} scheme.bytevector
@mdindex scheme.bytevector
@c EN
This module is taken from R6RS (@code{(rnrs bytevectors)} (note
that R7RS uses singular form).

The bytevector in this module is u8vector in Gauche.
@c JP
このモジュールはR6RSの@code{(rnrs bytevectors)}からの輸入です
(R7RSのライブラリ名は単数形であることに注意)。

Gaucheでは「バイトベクタ」はu8vectorです。
@c COMMON

@c EN
The following procedures are the same as in @code{gauche.uvector}.
@xref{Bytevector compatibility}, for the explanations.
@c JP
以下の手続きは@code{gauche.uvector}のものと同じです。
詳しくは@ref{Bytevector compatibility}を参照してください。
@c COMMON

@example
bytevector?        make-bytevector     bytevector-length
bytevector=?       bytevector-fill!    bytevector-copy
bytevector-u8-ref  bytevector-u8-set!  bytevector-s8-ref
bytevector-s8-set! bytevector->u8-list u8-list->bytevector
@end example

@c EN
The following procedures are the same as in @code{gauche.unicode}.
@xref{Unicode utilities}, for the explanations.
@c JP
以下の手続きは@code{gauche.unicode}のものと同じです。
詳しくは@ref{Unicode utilities}を参照してください。
@c COMMON

@example
string->utf8       string->utf16       string->utf32
utf8->string       utf16->string       utf32->string
@end example

@c EN
This module exports @code{bytevector-copy!}, which takes arguments
in different order from
R7RS base's (and @code{gauche.uvector}'s) @code{bytevector-copy!}.
It is the same as @code{bytevector-copy!-r6} in @code{gauche.uvector}
(@pxref{Bytevector compatibility}).
@c JP
このモジュールは@code{bytevector-copy!}をexportしていますが、
R7RS baseおよび@code{gauche.unicode}に含まれる同名の手続きと引数の順序が異なります。
@code{gauche.uvector}で@code{bytevector-copy!-r6}として定義されているものと
同じになります(@ref{Bytevector compatibility}参照)。
@c COMMON
@end deftp

@defmac endianness symbol
[R7RS bytevector]
@c EN
If @var{symbol} is a valid endianness symbol, returns it.  Otherwise,
raise an error at macro-expansion time.   Useful to catch an error early,
and explicitly indicates you mean endianness.

Valid symbols are listed in @ref{Endianness}.  Only @code{big} and
@code{little} are portable.
@c JP
@var{symbol}がエンディアンを示すシンボルであればそれをそのまま返し、
そうでなければマクロ展開時にエラーを投げます。
エラーを早期に検出するのに役立ちます。
また、シンボルがエンディアンを示すという意図を明確にできます。

有効なシンボルは@ref{Endianness}を参照してください。
@code{big}と@code{little}だけがポータブルです。
@c COMMON
@end defmac

@defun native-endianness
[R7RS bytevector]
@c EN
Returns a symbol representing the native endianness.
Same as Gauche's built-in @code{native-endian} (@pxref{Endianness}).
@c JP
システムのネイティブなエンディアンを示すシンボルを返します。
Gauche組み込みの@code{native-endian}と同じです(@ref{Endianness}参照)。
@c COMMON
@end defun


@defun bytevector-uint-ref bv pos endian size
@defunx bytevector-sint-ref bv pos endian size
[R7RS bytevector]
@c EN
Read @var{size} octets from u8vector @var{bv}, starting from @var{pos}-th
octet, as an unsigned or signed integer, respectively.
Similar to @code{binary.io}'s @code{get-uint} and @code{get-sint},
with different argument order.
@c JP
u8vector @var{bv}の、@var{pos}番めのオクテットから@var{size}オクテットを、
それぞれ符号なしと符号あり整数として読み取ります。
@code{binary.io}モジュールの@code{get-uint}と@code{get-sint}に似ていますが、
引数の順序は異なります。
@c COMMON

@c EN
They accept all valid endianness symbols in Gauche, but
the portable code should only use @code{big} and @code{little} for
@var{endian} argument.
@c JP
@var{endian}にはエンディアンを示すシンボルを渡します。
@code{bit}と@code{little}のみがポータブルに使えます。
@c COMMON
@end defun

@defun bytevector-uint-set! bv pos val endian size
@defunx bytevector-sint-set! bv pos val endian size
[R7RS bytevector]
@c EN
Store an unsigned or signed integer @var{val} into an u8vector
@var{bv} starting from @var{pos}-th octet, for @var{size} octets,
respectively.
Similar to @code{binary.io}'s @code{put-uint!} and @code{put-sint!},
with different argument order.
@c JP
それぞれ、符号なし、および符号つき整数@var{val}をu8vector @var{bv}の
@var{pos}番目のオクテットから@var{size}オクテットにわたって格納します。
@code{binary.io}の@code{put-uint!}および@code{put-sint!}と
引数の順序以外は同じです。
@c COMMON

@c EN
They accept all valid endianness symbols in Gauche, but
the portable code should only use @code{big} and @var{little} for
@var{endian} argument.
@c JP
@var{endian}引数には、Gaucheが許すエンディアンを示すシンボルなら何でも渡せますが、
ポータブルなコードで使えるのは@code{big}と@var{little}だけです。
@c COMMON
@end defun

@defun bytevector->uint-list bv endian size
@defunx bytevector->sint-list bv endian size
[R7RS bytevector]
@c EN
Convert the u8vector @var{bv} to a list of unsigned or signed integer,
each of which is represented by @var{size}-octets.
The length of @var{bv} must be a multiple of @var{size}; otherwise
an error is signaled.
@c JP
u8vector @var{bv}から@var{size}オクテットづつ取り出し、それをそれぞれ符号なし、
および符号つき整数と解釈して、その整数のリストを返します。
@var{bv}の長さが@var{size}の整数倍でなければエラーが投げられます。
@c COMMON

@c EN
They accept all valid endianness symbols in Gauche, but
the portable code should only use @code{big} and @var{little} for
@var{endian} argument.
@c JP
@var{endian}引数には、Gaucheが許すエンディアンを示すシンボルなら何でも渡せますが、
ポータブルなコードで使えるのは@code{big}と@var{little}だけです。
@c COMMON
@end defun

@defun uint-list->bytevector lis endian size
@defunx sint-list->bytevector lis endian size
[R7RS bytevector]
@c EN
@var{Lis} must be a list of unsigned or signed integers, respectively.
Creates a u8vector of length @code{(* size (length lis))}, and
stores each integer into the u8vector using @var{size} octets,
and returns the u8vector.
@c JP
@var{lis}はそれぞれ符号なしまたは符号つき整数のリストでなければなりません。
@code{(* size (length lis))}のu8vectorが作られて、
先頭から@var{size}オクテットごとに、リストの整数が詰められてゆきます。
そしてそのu8vectorが返されます。
@c COMMON

@c EN
They accept all valid endianness symbols in Gauche, but
the portable code should only use @code{big} and @var{little} for
@var{endian} argument.
@c JP
@var{endian}引数には、Gaucheが許すエンディアンを示すシンボルなら何でも渡せますが、
ポータブルなコードで使えるのは@code{big}と@var{little}だけです。
@c COMMON
@end defun

@defun bytevector-u16-ref bv k endian
@defunx bytevector-s16-ref bv k endian
@defunx bytevector-u32-ref bv k endian
@defunx bytevector-s32-ref bv k endian
@defunx bytevector-u64-ref bv k endian
@defunx bytevector-s64-ref bv k endian
@defunx bytevector-ieee-single-ref bv k endian
@defunx bytevector-ieee-double-ref bv k endian
[R7RS bytevector]
Retrieve a numerical value from a u8vector @var{bv} starting at
index @var{k}, using @var{endian}.  These are the same as
@code{get-u16}, @dots{} in @code{binary.io}, except that
all arguments are mandatory.  (Note that
@code{ieee-single} and @code{ieee-double} corresponds to @code{f32} and
@code{f64}).  @xref{Binary I/O}), for the details.

They accept all valid endianness symbols in Gauche, but
the portable code should only use @code{big} and @var{little} for
@var{endian} argument.
@end defun

@defun bytevector-u16-native-ref bv k
@defunx bytevector-s16-native-ref bv k
@defunx bytevector-u32-native-ref bv k
@defunx bytevector-s32-native-ref bv k
@defunx bytevector-u64-native-ref bv k
@defunx bytevector-s64-native-ref bv k
@defunx bytevector-ieee-single-native-ref bv k
@defunx bytevector-ieee-double-native-ref bv k
[R7RS bytevector]
Like @code{bytevector-u16-ref} etc., but uses native endianness.
@end defun

@defun bytevector-u16-set! bv k val endian
@defunx bytevector-s16-set! bv k val endian
@defunx bytevector-u32-set! bv k val endian
@defunx bytevector-s32-set! bv k val endian
@defunx bytevector-u64-set! bv k val endian
@defunx bytevector-s64-set! bv k val endian
@defunx bytevector-ieee-single-set! bv k val endian
@defunx bytevector-ieee-double-set! bv k val endian
[R7RS bytevector]
Store a numerical value into a u8vector @var{bv} starting at
index @var{k}, using @var{endian}.  These are the same as
@code{put-u16!}, @dots{} in @code{binary.io}, except that
all arguments are mandatory.  (Note that
@code{ieee-single} and @code{ieee-double} corresponds to @code{f32} and
@code{f64}).  @xref{Binary I/O}), for the details.

They accept all valid endianness symbols in Gauche, but
the portable code should only use @code{big} and @var{little} for
@var{endian} argument.
@end defun

@defun bytevector-u16-native-set! bv k val
@defunx bytevector-s16-native-set! bv k val
@defunx bytevector-u32-native-set! bv k val
@defunx bytevector-s32-native-set! bv k val
@defunx bytevector-u64-native-set! bv k val
@defunx bytevector-s64-native-set! bv k val
@defunx bytevector-ieee-single-native-set! bv k val
@defunx bytevector-ieee-double-native-set! bv k val
[R7RS bytevector]
Like @code{bytevector-u16-set!} etc., but uses native endianness.
@end defun

@node R7RS combinator formatting,  , R7RS bytevectors, R7RS large
@subsection @code{scheme.show} - R7RS combinator formatting
@c NODE R7RS combinator formatting, @code{scheme.show} - R7RS combinator formatting

@subsubheading Module structure
@deftp {Module} scheme.show
@mdindex scheme.show
Exports bindings of R7RS @code{(scheme show)} library.
From R7RS programs, those bindings are available by
@code{(import (scheme show))}.

scheme.show is a combination of submodules scheme.show.base,
scheme.show.color, scheme.show.columnar and scheme.show.unicode.
@end deftp

@deftp {Module} scheme.show.base
Exports bindings of R7RS @code{(scheme show base)} library.
From R7RS programs, those bindings are available by
@code{(import (scheme show base))}.

This contains most combinator formatting procedures.
@end deftp

@deftp {Module} scheme.show.color
Exports bindings of R7RS @code{(scheme show color)} library.
From R7RS programs, those bindings are available by
@code{(import (scheme show color))}.

This contains formatters to color text using ANSI escape codes.
@end deftp

@deftp {Module} scheme.show.columnar
Exports bindings of R7RS @code{(scheme show columnar)} library.
From R7RS programs, those bindings are available by
@code{(import (scheme show columnar))}.

This contains formatters to help format in columns.
@end deftp

@deftp {Module} scheme.show.unicode
Exports bindings of R7RS @code{(scheme show unicode)} library.
From R7RS programs, those bindings are available by
@code{(import (scheme show unicode))}.
@end deftp

@subsubheading Usage

Combinator formatting provides a functionality similar to
@code{format} from SRFI-28. But instead of writing a template string,
you can use S-expressions, which are called ``formatters''. It's also
extensible.

The two main concepts in combinator formatting are formatters and
states. Formatters are procedures that specify how or what you want to
output. Formatters can be composed to produce complex format. Normal
types are also accepted where a procedure takes a formatter, they are
formatted with @code{displayed}.

Format states let us customize control formatting, for example how
many precision digits, what character for padding @dots{}. Format
states can be changed locally with @code{with} or @code{with!}.

The entry point to combinator formatting is @code{show}, which takes a
sequence of formatters and outputs to a port or returns a string.

@defun show @var{output-dest} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
This is the main entry for combinator formatting. All formatters are
processed to produce a string to @var{output-dest} if it's a port. If
@var{output-dest} is @code{#f}, the output string is returned.
@code{show} return value is otherwise undefined. Non-formatters are
also accepted and will be wrapped in @code{displayed} formatter.

@example
(show #f "π = " (with ((precision 2)) (acos -1)) nl)
@result{} "π = 3.14\n"
@end example
@end defun

@subsubheading Formatting Objects

@defun displayed @var{obj}
[R7RS show base]
@c MOD scheme.show.base
The formatter that formats the object @var{obj} the
same as @code{display}. This is the default formatter when you pass an
object to @code{show}.
@end defun

@defun written @var{obj}
[R7RS show base]
@c MOD scheme.show.base
The formatter that formats the object @var{obj} the same as
@code{write}. Formatting settings @code{numeric} and @code{precision}
are respected for relevant number types as long as the result can
still be passed to @code{read}.
@end defun

@defun written-simply @var{obj}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{written} but does not handle shared structures.
@end defun

@defun pretty @var{obj}
[R7RS show base]
@c MOD scheme.show.base
Pretty prints an object.
@end defun

@defun pretty-simply @var{obj}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{pretty} but does not handle shared structures.
@end defun

@defun escaped @var{str} [@var{quote-ch} @var{esc-ch} @var{renamer}]
[R7RS show base]
@c MOD scheme.show.base
Prints a string, adding @var{esc-ch} (@code{#\\} by default) in front
of all @var{quote-ch} (@code{#\"} by default).

If @var{esc-ch} is @code{#f}, escape all @var{quote-ch} by doubling
it.

If @var{renamer} is specified, it's a procedure that takes one
character and returns another character or @code{#f}. It serves two
purposes: to allow quoting more than one character and to replace them
with something else. If the procedure returns @code{#f}, the character
in question is not escaped. Otherwise the character is escaped and
replaced with a new one.

@var{esc-ch} could also be a string, but this is Gauche specific behavior.

@example
(show #t (escaped "hello \"world\"")) @result{} hello \"world\"
(show #t (escaped "hello \"world\"" #\l)) @result{} he\l\lo "world"
(show #t (escaped "hello \"world\"" #\l #\x)) @result{} hexlxlo "worxld"
(show #t (escaped "hello \"world\""
                  #\e #f
                  (lambda (x) (if (char=? x #\o) #\O #f))))
@result{} heelleO "weOrld"
@end example
@end defun

@defun maybe-escaped @var{str} @var{pred} [@var{quote-ch} @var{esc-ch} @var{renamer}]
[R7RS show base]
@c MOD scheme.show.base
Determines if @var{str} needs to be escaped or not. If true, the
string is wrapped with @var{quote-ch}. The original string is escaped
with @code{escaped}.

The string needs to be escaped if any @var{quote-ch} or @var{esc-ch}
is present, or any character that makes @var{pred} return @code{#t}.

@example
(show #t (maybe-escaped "helloworld" char-whitespace?)) @result{} helloworld
(show #t (maybe-escaped "hello world" char-whitespace?)) @result{} "hello world"
(show #t (maybe-escaped "hello \"world\"" char-whitespace? #\")) @result{} "hello \"world\""
@end example

@end defun

@subsubheading Formatting Numbers

@defun numeric @var{num} [@var{radix} @var{precision} @var{sign-rule} @var{comma-rule} @var{comma-sep} @var{decimal-sep}]
[R7RS show base]
@c MOD scheme.show.base
Formats a number. The default values are from state variables below.

@example
(show #f (numeric 1000)) @result{} "1000"
(show #f (numeric 1000 8)) @result{} "1750"
(show #f (numeric 1000 8 2)) @result{} "1750.00"
(show #f (numeric 1000 8 2 #t)) @result{} "+1750.00"
(show #f (numeric -1000 8 2 (cons "(" ")"))) @result{} "(1750.00)"
(show #f (numeric 1000 8 2 #t 2)) @result{} "+17,50.00"
(show #f (numeric 1000 8 2 #t 2 #\')) @result{} "+17'50.00"
(show #f (numeric 1000 8 2 #t 2 #\' #\:)) @result{} "+17'50:00"
@end example

@end defun

@defun numeric/comma @var{num} [@var{radix} @var{precision} @var{sign-rule}]
[R7RS show base]
@c MOD scheme.show.base
Formats a number with default @var{comma-rule} 3. See @code{numeric}
for details.
@example
(show #f (numeric/comma 1000)) @result{} "1,000"
(show #f (with ((comma-sep #\.)) (numeric/comma 1000))) @result{} "1.000"
@end example

@end defun

@defun numeric/si @var{num} [@var{base} @var{separator}]
[R7RS show base]
@c MOD scheme.show.base
Formats a numeric with SI suffix. The default base is 1024 and uses
suffix names like Ki, Mi, Gi@dots{}. Other bases (e.g. 1000) use
suffixes k, M, G@dots{}. If @var{separator} is specified, it's
inserted between the number and suffix.

@example
(show #f (numeric/si 1024)) @result{} "1Ki"
(show #f (numeric/si 200000 1000)) @result{} "200k"
(show #f (numeric/si 1024 1024 #\/)) @result{} "1/Ki"
@end example

@end defun

@defun numeric/fitted @var{width} @var{n} [@var{arg} @dots{}]
[R7RS show base]
@c MOD scheme.show.base
Like @code{numeric} but if the result does not fit in @var{width}
characters with current precision, outputs a string of hashes instead
of the truncated and incorrect number.

@example
(show #f (with ((precision 2)) (numeric/fitted 4 1.25))) @result{} "1.25"
(show #f (with ((precision 2)) (numeric/fitted 4 12.345))) @result{} "#.##"
@end example

@end defun

@subsubheading Formatting Space

@defvar nl
Outputs a newline.

@example
(show #f nl) @result{} "\n"
@end example
@end defvar

@defvar fl
Short for ``fresh line'', make sures the following output is at the
beginning of the line.

@example
(show #f fl) @result{} ""
(show #f "aaa" fl) @result{} "aaa\n"
@end example
@end defvar

@defvar nothing
Outputs nothing. This is useful in combinators as default no-op in
conditionals.
@end defvar

@defun space-to @var{column}
[R7RS show base]
@c MOD scheme.show.base
Appends @var{pad-char} to reach the given @var{column}.

@example
(show #f "abcdef" (space-to 3) "a") @result{} "   a"
(show #f "abcdef" (space-to 3) "a") @result{} "abcdefa"
@end example
@end defun

@defun tab-to [@var{tab-width}]
[R7RS show base]
@c MOD scheme.show.base
Outputs @var{pad-char} to reach the next tab stop.
@end defun

@subsubheading Concatenation

@defun each @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
@end defun

@defun each-in-list @var{list-of-fmts}
[R7RS show base]
@c MOD scheme.show.base
@end defun

@defun joined @var{mapper} @var{list} [@var{sep}]
[R7RS show base]
@c MOD scheme.show.base
Formats each element in @var{list} with @var{mapper} and inserts
@var{sep} in between. @var{sep} by default is an empty string, but it
could be any string or formatter.

@example
(show #f (joined displayed (list "a" "b") " ")) @result{} "a b"
(show #f (joined displayed (list "a" "b") nl)) @result{} "a\nb"
@end example
@end defun

@defun joined/prefix @var{mapper} @var{list} [@var{sep}]
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{joined} except the separator is inserted before
every element.

@example
(show #f (joined/prefix displayed '(usr local bin) "/")) @result{} "/usr/local/bin"
@end example
@end defun

@defun joined/suffix @var{mapper} @var{list} [@var{sep}]
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{joined} except the separator is inserted after every
element.

@example
(show #f (joined/suffix displayed '(1 2 3) nl)) @result{} "1\n2\n3\n"
@end example
@end defun

@defun joined/last @var{mapper} @var{last-mapper} @var{list} [@var{sep}]
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{joined} but @var{last-mapper} is used on the last
element of @var{list} instead.

@example
(show #f (joined/last displayed
                      (lambda (last) (each "and " last))
                      '(lions tigers bears)
                      ", "))
@result{} "lions, tigers, and bears"
@end example
@end defun

@defun joined/dot @var{mapper} @var{dot-mapper} @var{list} [@var{sep}]
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{joined} but if @var{list} is a dotted list, then
formats the dotted value with @var{dot-mapper} instead.
@end defun

@defun joined/range @var{mapper} @var{start} [@var{end} @var{sep}]
[R7RS show base]
@c MOD scheme.show.base
@end defun

@subsubheading Padding and Trimming

@defun padded @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Pads the output of @var{fmt}@dots{} on the left side with
@var{pad-char} if it's shorter than @var{width} characters.

@example
(show #f (padded 10 "abc")) @result{} "       abc"
(show #f (with ((pad-char #\-)) (padded 10 "abc"))) @result{} "-------abc"
@end example
@end defun

@defun padded/right @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{padded} but except padding is on the right side instead.
@end defun

@defun padded/both @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{padded} but except padding is on both sides, keeping
the @var{fmt} output at the center.
@end defun

@defun trimmed @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Trims the output of @var{fmt}@dots{} on the left so that the length is
@var{width} characters or less. If @var{ellipsis} state variable is
defined, it will be put on the left to denote trimming.

@example
(show #f (trimmed 5 "hello world")) @result{} "world"
(show #f (with ((ellipsis "..")) (trimmed 5 "hello world"))) @result{} "..rld"
@end example
@end defun

@defun trimmed/right @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{trimmed} but the trimming is on the right.
@end defun

@defun trimmed/both @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{trimmed} but the trimming is on both sides, keeping
the center of the output.
@end defun

@defun trimmed/lazy @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
A variant of @code{trimmed} which generates each @code{fmt} in left to
right order, and truncates and terminates immediately if more than
@code{width} characters are generated. Thus this is safe to use with
an infinite amount of output, e.g. from @code{written-simply} on an
infinite list.
@end defun

@defun fitted width @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
A combination of @code{padded} and @code{trimmed}, ensures the output
width is exactly @var{width}, truncating if it goes over and padding
if it goes under.
@end defun

@defun fitted/right @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
A combination of @code{padded/right} and @code{trimmed/right}, ensures
the output width is exactly @var{width}, truncating if it goes over
and padding if it goes under.
@end defun

@defun fitted/both @var{width} @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
A combination of @code{padded/both} and @code{trimmed/both}, ensures
the output width is exactly @var{width}, truncating if it goes over
and padding if it goes under.
@end defun

@subsubheading Columnar Formatting

@defun columnar @var{column} @dots{}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun tabular @var{column} @dots{}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun wrapped @var{fmt} @dots{}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun wrapped/list @var{list-of-strings}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun wrapped/char @var{fmt} @dots{}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun justified @var{format} @dots{}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun from-file @var{pathname}
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@defun line-numbers [@var{start}]
[R7RS show columnar]
@c MOD scheme.show.columnar
@end defun

@subsubheading Colors

@defun as-red @var{fmt} @dots{}
@defunx as-blue @var{fmt} @dots{}
@defunx as-green @var{fmt} @dots{}
@defunx as-cyan @var{fmt} @dots{}
@defunx as-yellow @var{fmt} @dots{}
@defunx as-magenta @var{fmt} @dots{}
@defunx as-white @var{fmt} @dots{}
@defunx as-black @var{fmt} @dots{}
@defunx as-bold @var{fmt} @dots{}
@defunx as-underline @var{fmt} @dots{}
[R7RS show color]
@c MOD scheme.show.color
Outputs the ANSI escape code to make all @var{fmt}@dots{} a given
color or style.
@end defun

@subsubheading Unicode

@defun as-unicode @var{fmt} @dots{}
[R7RS show unicode]
@c MOD scheme.show.unicode
@end defun

@defun unicode-terminal-width @var{str}
[R7RS show unicode]
@c MOD scheme.show.unicode
@end defun

@subsubheading Higher Order Formatters and State

@defun fn ((@var{id} @var{state-var}) @dots{}) @var{expr} @dots{} @var{fmt}
[R7RS show base]
@c MOD scheme.show.base
This is short for ``function'' and the analog to @code{lambda}. It
returns a formatter which on application evaluates each @var{expr} and
@var{fmt} in left-to-right order, in a lexical environment extended
with each identifier id bound to the current value of the state
variable named by the symbol @var{state-var}. The result of the
@var{fmt} is then applied as a formatter.

As a convenience, any @code{(id state-var)} list may be abbreviated as
simply @code{id}, indicating @var{id} is bound to the state variable
of the same (symbol) name.
@end defun

@defun with ((@var{state-var} @var{value}) @dots{}) @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
This is the analog of @code{let}. It temporarily binds specified state
variables with new values for @var{fmt} @dots{}.
@end defun

@defun with! (@var{state-var} @var{value}) @var{fmt} @dots{}
[R7RS show base]
@c MOD scheme.show.base
Similar to @code{with} but the value updates persist even after
@code{with!}.
@end defun

@defun forked @var{fmt1} @var{fmt2}
[R7RS show base]
@c MOD scheme.show.base
Calls @var{fmt1} on (a conceptual copy of) the current state, then
@var{fmt2} on the same original state as though @var{fmt1} had not
been called (i.e. any potential state mutation by @var{fmt1} does not
affect @var{fmt2}).
@end defun

@defun call-with-output @var{formatter} @var{mapper}
[R7RS show base]
@c MOD scheme.show.base
A utility, calls formatter on a copy of the current state (as with
@code{forked}), accumulating the results into a string. Then calls the
formatter resulting from @code{(mapper result-string)} on the original
state.
@end defun

@subsubheading Standard State Variables

@defvar port
The current port output is written into, could be overriden to capture
intermediate output.
@end defvar

@defvar row
The current row of the output.
@end defvar

@defvar col
The current column of the output.
@end defvar

@defvar width
The current line width, used for wrapping, pretty printing and
columnar formatting.
@end defvar

@defvar output
The underlying standard formatter for writing a single string.

The default value outputs the string while tracking the current row
and col. This can be overridden both to capture intermediate output
and perform transformations on strings before outputting, but should
generally wrap the existing output to preserve expected behavior.
@end defvar

@defvar writer
The mapper for automatic formatting of non-string/char values in
top-level show, each and other formatters. Default value is
implementation-defined.
@end defvar

@defvar string-width
A function of a single string. It returns the length in columns of
that string, used by the default output.
@end defvar

@defvar pad-char
The character used for by padding formatters, @code{#\space} by default
@end defvar

@defvar ellipsis
The string used when truncating as described in @code{trimmed}.
@end defvar

@defvar radix
The radix for numeric output, 10 by default. Valid values are from 2
to 36.
@end defvar

@defvar precision
The number of digits written after the decimal point for numeric
output. The value is rounded if the numeric value written out requires
more digits than requested precision. See the SRFI for exact rounding
behavior.
@end defvar

@defvar sign-rule
If @code{#t}, always output the plus sign @code{+} for positive
numbers. If @var{sign-rule} is a par of two strings, negative numbers
are printed with the strings wrapped around (and no preceding negative
sign @code{-}).
@end defvar

@defvar comma-rule
The number of digits between commans, specified by @var{comma-sep}.
@end defvar

@defvar comma-sep
The character used as comma for numeric formatting, @code{#\,} by
default.
@end defvar

@defvar decimal-sep
The character to use for decimals in numeric formatting. The default
depends on @var{comma-sep}, if it's @code{#\.}, then the decimal
separator is @code{#\,}, otherwise it's @code{#\.}
@end defvar

@defvar decimal-align
@end defvar

@defvar word-separator?
@end defvar


@c Local variables:
@c mode: texinfo
@c coding: utf-8
@c end:
