@node Core syntax, Macros, Programming in Gauche, Top @chapter Core syntax @c NODE 基本的な構文 @c ---------------------------------------------------------------------- @menu * Lexical structure:: * Literals:: * Making procedures:: * Assignments:: * Conditionals:: * Binding constructs:: * Grouping:: * Iteration:: * Quasiquotation:: * Definitions:: * Inclusions:: * Feature conditional:: * Modules:: @end menu @node Lexical structure, Literals, Core syntax, Core syntax @section Lexical structure @c NODE 字句構造 @c EN Gauche extends R7RS Scheme lexical parser in some ways. Besides, because of historical reasons, a few of the default lexical syntax may conflict R7RS specification. You can set a reader mode to make it R7RS compliant. @c JP GaucheはR7RS Schemeのパーザをいくつかの点で拡張しています。 また、歴史的経緯から、デフォルトの字句構文の中に、R7RSの仕様と相反するものが いくつかあります。リーダのモードを設定することで、 R7RS互換にすることもできます。 @c COMMON @table @emph @c EN @item Hash-bang directives Tokens beginning with @code{#!} may have special meanings to the reader. R7RS defines two of such directives---@code{#!fold-case} and @code{#!no-fold-case}, which switches whether symbols are read in case-folding or non-case-folding mode, respectively. @pxref{Hash-bang token} below, for all the directives Gauche has. @c JP @item hash-bang指示子 @code{#!}で始まるトークンはリーダに特別な影響を与えます。 R7RSではそういった指示子がふたつ定義されています。 シンボルのリード時に大文字小文字を無視するかしないかを 切り替える、@code{#!fold-case}と@code{#!no-fold-case}です。 Gaucheで使える指示子の一覧については、下の@ref{Hash-bang token}を参照してください。 @c COMMON @c EN @item Square brackets @lxindex [ Gauche adopts the R6RS syntax that regards @code{[]} the same as @code{()}. Both kind of parentheses are equivalent, but the kind of corresponding open and close parentheses must match. Some seasoned Lisper may frown on them, but it helps visually distinguish different roles of parentheses. A general convention is to use @code{[]} for groupings other than function and macro application. If such grouping nests, however, use @code{()} for outer groupings. Examples: @c JP @item 角括弧 @lxindex [ Gaucheは、R6RSの@code{[]}を@code{()}と同様に扱う構文規則を採用しています。 どちらの括弧も全く等価ですが、それぞれの開き括弧と閉じ括弧は対応していなければなりません。 括弧を混ぜることに眉をひそめる熟練のLisperもいますが、 括弧の種類を使い分けるのは、括弧の役割を視覚的に識別するのに役に立ちます。 一般的な慣習は、関数とマクロ呼び出し以外のグルーピングには@code{[]}を使う、 というものです。ただしそのようなグルーピングがネストする場合は、外側には@code{()}を 使います。例: @c COMMON @example (cond [(test1 x) (y z)] [(test2 x) (s t)] [else (u v)]) (let ([x (foo a b)] [y (bar c d)]) (baz x y)) @end example @c EN It is purely optional, so you don't need to use them if you don't like them. R7RS doesn't adopt this syntax and leaves @code{[]} for extensions, so it is safe to stick to @code{()} in portable R7RS programs. (If the reader is in @code{strict-r7} mode, an error is signalled when @code{[]} is used. @xref{Reader lexical mode}, for the details.) Scheme-specific modes of some editors (e.g. Quack on Emacs) allows you to type just @code{)} and inserts either @code{]} or @code{)} depending on which kind parenthesis it is closing. We recommend using such modes if you use this convention. @c JP この記法は、必ず従わなければいけないというものではありません。 R7RSではこの構文を採用せず、@code{[]}は言語拡張用に取ってあるので、 ポータブルなR7RSプログラムを書く場合は@code{()}だけを使うのが良いでしょう。 (リーダが@code{strict-r7}モードの時は、@code{[]}が使われていたら エラーが通知されます。詳しくは@ref{Reader lexical mode}参照。) エディタのSchemeモードの中には、@code{)}をタイプするとそれがどちらの 種類の括弧を閉じるかに応じて自動的に@code{]}か@code{)}を選んで挿入してくれる ものがあります (EmacsのQuackなど)。この記法を使うときは そういったモードを活用すると良いでしょう。 @c COMMON @c EN @item Symbol names Symbol names are case sensitive by default (@pxref{Case-sensitivity}). Symbol name can begin with digits, '@code{+}' or '@code{-}', as long as the entire token doesn't consist valid number syntax. Other weird characters can be included in a symbol name by surrounding it with '|', e.g. '@code{|this is a symbol|}'. @xref{Symbols}, for details. @c JP @item シンボル名 シンボル名はデフォルトで大文字小文字を区別します (@ref{Case-sensitivity}参照)。 数字や'@code{+}', '@code{-}' で始まるシンボル名も、 トークンが有効な数値リテラルを構成しない限り許されます。 また、他の変な文字も '|' でシンボルを囲むことによってシンボル名に含めることが できます (例:'@code{|this is a symbol|}')。 @ref{Symbols}も参照して下さい。 @c COMMON @c EN @item Numeric literals Either integral part or fraction part of inexact real numbers can be omitted if it is zero, i.e. @code{30.}, @code{.25}, @code{-.4} are read as real numbers. The number reader recognizes '@code{#}' as insignificant digits. Complex numbers can be written both in the rectangular format (e.g. @code{1+0.3i}) and in the polar format (e.g. @code{3.0@@1.57}). Inexact real numbers include the positive infinity, the negative infinity, and NaN, which are represented as @code{+inf.0}, @code{-inf.0} and @code{+nan.0}, respectively. (@code{-nan.0} is also read as NaN.) Gauche supports SRFI-169 (underscores in numbers) notation; you can insert a character @code{_} between digits in numeric literals to improve readability, e.g. @code{#b1100_1010_1111_1110}. A valid underscore must be surrounded by digits; @code{1_2_3} is ok, but @code{_123}, @code{123_}, and @code{12__3} are not. Gauche also adopts Common-Lisp style radix prefixed numeric literals, e.g. @code{#3r120} (@code{120} in base-3, 15 in decimal). Radix between 2 and 36 are recognized; alphabetic letters @code{a-zA-Z} are used beyond decimal. For the polar notation of complex numbers, Gauche allows the suffix @code{pi} to denote the phase by multiples of pi. The Scheme syntax use radians for the phase, but you can only approximate pi with the floating point numbers, so it can't represent round numbers except zero angle. @example gosh> 2@@3.141592653589793 -2.0+2.4492935982947064e-16i @end example With the @code{pi} suffix, you can get a round numbers. @example gosh> 2@@1pi -2.0 gosh> 2@@0.5pi 0.0+2.0i gosh> 2@@-0.5pi 0.0-2.0i @end example @c JP @item 数値リテラル 非正確な実数の整数部または小数部のいずれかが0の場合、それを省略することが できます。例:@code{30.}, @code{.25}, @code{-.4}。 数値のリーダは、パディングの'@code{#}'を認識します。 複素数表記は直交座標形 (例:@code{1+0.3i}) でも極座標形 (例:@code{3.0@@1.57}) でも 認識されます。 非正確な実数は、正の無限大、負の無限大、非数(NaN)を含み、 それらはそれぞれ@code{+inf.0}、@code{-inf.0}、および@code{+nan.0}と 表記されます。(@code{-nan.0}も非数(NaN)として読まれます)。 Gaucheはまた、SRFI-169 (数値中のアンダースコア)構文をサポートしています。 読みやすくするために、数値中に@code{_}を挿入することができます (例: @code{#b1100_1010_1111_1110})。 ただし、各アンダースコアは数字に囲まれていなければなりません。 @code{1_2_3}はokですが、@code{_123}、@code{123_}、@code{12__3}は 有効な数値リテラルではありません。 Gaucheはまた、Common Lisp風の基数を明示した数値リテラルも認識します。 例えば3進数の120は@code{#3r120}と書けます(10進数で15)。2進数から36進数まで 認識されます。10進数より上では@code{a-zA-Z}のアルファベットを使えます。 複素数の極座標記法において、Gaucheではサフィックス@code{pi}をつけることにより 偏角をπの係数で表すことができます。Schemeの構文では偏角はラジアンですが、 πは浮動小数点数では近似値でしか扱えないので、偏角ゼロ以外で切りの良い数値を 表現することができません。 @example gosh> 2@@3.141592653589793 -2.0+2.4492935982947064e-16i @end example @code{pi}サフィックスを使うと切りの良い数値が書けます。 @example gosh> 2@@1pi -2.0 gosh> 2@@0.5pi 0.0+2.0i gosh> 2@@-0.5pi 0.0-2.0i @end example @c COMMON @c EN @item Hex character escapes @lxindex \x You can denote a character using hexadecimal notation of the character code in some literals; specifically, character literals, charcter set literals, string literals, symbols, regular expression literals. R7RS adopted a hex escape notation @code{\xNNNN;} for strings and symbols surrounded by vertical bars, and @code{#\xNNNN} for characters. The number of digits is variable, and the character code is Unicode codepoint. Gauche had been using two types of escapes; @code{\u} and @code{\x}. In general, @code{u} is for Unicode codepoint, while @code{x} is for the character code in the internal encoding. Besides, except character literals, we used fixed number of digits, instead of using the terminator @code{;} as in R7RS. Since 0.9.4, we interpret @code{\x}-escape as R7RS whenever if it consists a valid R7RS hex-escape, and if not, try to interpret it as legacy Gauche hex-escape. Although rarely, there are cases that can interpreted both in R7RS syntax and legacy Gauche syntax, but yielding different characters. Reading legacy files with such literals in the current Gauche may cause unexpected behavior. You can switch the reader mode so that it becomes backward-compatible. @xref{Reader lexical mode}, for the details. @c JP @item 16進数文字エスケープ @lxindex \x いくつかのリテラル中では、文字をその文字コードの16進数表記で記入できます。 具体的には、文字、文字集合、文字列、シンボル、正規表現リテラルです。 R7RSは文字列および縦棒で囲まれたシンボル中では@code{\xNNNN;}、文字単独では @code{#\xNNNN}というエスケープ構文を採用しました。16進数の桁数は可変で、 文字コードはUnicodeコードポイントです。 Gaucheは歴史的に2種類のエスケープを使ってきました。 @code{\u}と@code{\x}です。 @code{u}はUnicodeコードポイントに、@code{x}は内部エンコーディングによる 文字コードに使っていました。また、文字リテラル以外では 16進数の桁数は固定で、したがってR7RSのような終端文字(@code{;})を必要としませんでした。 0.9.4からは、@code{\x}エスケープはそれが正しいR7RSの16進エスケープと解釈できる 限りはそう読まれます。R7RSの構文に合致しない場合は、以前のGaucheの構文とみなされます。 滅多にないことですが、R7RSとも以前のGauche構文ともみなすことができて、しかし解釈に違いが 生じるような場合というのが存在します。そのようなリテラルを含む昔のソースを 現在のGaucheで読むと、予想外の動作が起きるかもしれません。 その場合は、リーダのモードを以前との互換モードに変更できます。 詳細は@ref{Reader lexical mode}を参照してください。 @c COMMON @c EN @item Extended sharp syntax Many more special tokens begins with '@code{#}' are defined. See the table below. @c JP @item 拡張された#構文 '@code{#}' で始まる特殊構文がたくさん定義されています。 下の表を参照して下さい。 @c COMMON @end table @menu * Sharp syntax:: * Hash-bang token:: @end menu @node Sharp syntax, Hash-bang token, Lexical structure, Lexical structure @subsection Sharp syntax @c NODE #構文 @c EN The table below lists sharp-syntaxes. @c JP 以下の表はシャープ構文のリストです。 @c COMMON @multitable {aaaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} @item @code{#!} @c EN @tab [R6RS][R7RS][SRFI-22] It is either a beginning of an interpreter line (shebang) of a script, or a special token that affects the mode of the reader. See `hash-bang token' section below. @c JP @tab [R6RS][R7RS][SRFI-22] これは、スクリプトのインタプリタ指定行(shebang)の 開始を示すか、リーダのモードに影響を与える特別なトークンとして読まれます。 下の`hash-bang token'の節を参照してください。 @c COMMON @item @code{#"} @c EN @tab Introduces an interpolated string. @xref{String interpolation}. @c JP @tab 補間された文字列を先導します。@ref{String interpolation}参照。 @c COMMON @item @code{##}, @code{#$}, @code{#%}, @code{#&}, @code{#'} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#(} @c EN @tab [R7RS] Introduces a vector. @c JP @tab [R7RS] リテラルベクタ表記の開始です。 @c COMMON @item @code{#)} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#*} @c EN @tab Bitvector or an incomplete string. @xref{Strings}. @c JP @tab ビットベクタあるいは不完全な文字列。@ref{Strings}参照。 @c COMMON @item @code{#+} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#,} @c EN @tab [SRFI-10] Introduces reader constructor syntax. @c JP @tab [SRFI-10] リーダ構築子構文を開始します。 @c COMMON @item @code{#-}, @code{#.} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#/} @c EN @tab Introduces a literal regular expression. @xref{Regular expressions}. @c JP @tab リテラルの正規表現を先導します。@ref{Regular expressions}参照。 @c COMMON @item @code{#0} @dots{} @code{#9} @c EN @tab @code{#@var{n}#}, @code{#@var{n}=}: [SRFI-38] Shared substructure definition and reference.@* @code{#@var{n}R}, @code{#@var{n}r}: Radix prefixed numeric literals. @c JP @tab @code{#@var{n}#}, @code{#@var{n}=}: [SRFI-38] 共有サブストラクチャの定義と参照。@* @code{#@var{n}R}, @code{#@var{n}r}: 基数を明示した数値リテラル。 @c COMMON @item @code{#:} @c EN @tab Uninterned symbol. @xref{Symbols}. @c JP @tab インターンされていないシンボル。@ref{Symbols}参照。 @c COMMON @item @code{#;} @c EN @tab [SRFI-62] S-expression comment. Reads next one S-expression and discard it. @c JP @tab [SRFI-62] S式コメント。続くS式をひとつ読んで捨てます。 @c COMMON @item @code{#<} @c EN @tab Introduces an unreadable object. @c JP @tab 読み取り不可能オブジェクトを先導します。 @c COMMON @item @code{#=}, @code{#>} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#?} @c EN @tab Introduces debug macros. @xref{Debugging}. @c JP @tab デバッグマクロを先導します。@ref{Debugging}参照。 @c COMMON @item @code{#@@} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#a} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#b} @c EN @tab [R7RS] Binary number prefix. @c JP @tab [R7RS] 2進数接頭辞。 @c COMMON @item @code{#c} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#d} @c EN @tab [R7RS] Decimal number prefix. @c JP @tab [R7RS] 10進数接頭辞。 @c COMMON @item @code{#e} @c EN @tab [R7RS] Exact number prefix. @c JP @tab [R7RS] 正確数接頭辞。 @c COMMON @item @code{#f} @c EN @tab [R7RS] Boolean false, or introducing R7RS uniform vector. @xref{Uniform vectors}. R7RS defines both @code{#f} and @code{#false} as a boolean false value. @c JP @tab [R7RS] 真理値の偽、あるいは R7RS のユニフォームベクタを先導します。@ref{Uniform vectors}参照。 R7RSでは真理値の偽として@code{#f}と@code{#false}が使えます。 @c COMMON @item @code{#g}, @code{#h} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#i} @c EN @tab [R7RS] Inexact number prefix. @c JP @tab [R7RS] 非正確数接頭辞。 @c COMMON @item @code{#j}, @code{#k}, @code{#l}, @code{#m}, @code{#n} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#o} @c EN @tab [R7RS] Octal number prefix. @c JP @tab [R7RS] 8進数接頭辞。 @c COMMON @item @code{#p}, @code{#q}, @code{#r} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#s} @c EN @tab [R7RS vector.@@] introducing R7RS uniform vector. @xref{Uniform vectors}. @c JP @tab [R7RS vector.@@] R7RSのユニフォームベクタを先導します。@ref{Uniform vectors}参照。 @c COMMON @item @code{#t} @c EN @tab [R7RS] Boolean true. R7RS defines @code{#t} and @code{#true} as a boolean true value. @c JP @tab [R7RS] 真理値の真。R7RSでは真理値の真として@code{#t}と@code{#true}が使えます。 @c COMMON @item @code{#u} @c EN @tab [R7RS vector.@@] introducing R7RS uniform vector. @xref{Uniform vectors}. R7RS uses @code{#u8} prefix for bytevectors, which is compatible to @code{u8} uniform vectors. @c JP @tab [R7RS vector.@@] R7RS のユニフォームベクタを先導します。@ref{Uniform vectors}参照。 R7RSもバイトベクタに@code{#u8}のプリフィクスを使いますが、これは @code{u8}ユニフォームベクタと互換です。 @c COMMON @item @code{#v}, @code{#w} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#x} @c EN @tab [R7RS] Hexadecimal number prefix. @c JP @tab [R7RS] 16進数接頭辞 @c COMMON @item @code{#y}, @code{#z} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#[} @c EN @tab Introduces a literal character set. @xref{Character sets}. @c JP @tab リテラルの文字集合を先導します。@ref{Character sets}参照 @c COMMON @item @code{#\} @c EN @tab [R7RS] Introduces a literal character. @xref{Characters}. @c JP @tab [R7RS] リテラルの文字を先導します。@ref{Characters}参照。 @c COMMON @item @code{#]}, @code{#^}, @code{#_} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#`} @c EN @tab Legacy syntax for string interpolation, superseded by @code{#"}. @c JP @tab 文字列補間の古い構文です。新しいコードでは@code{#"}を使ってください。 @c COMMON @item @code{#@{} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @item @code{#|} @c EN @tab [SRFI-30] Introduces a block comment. Comment ends by matching '@code{|#}'. @c JP @tab [SRFI-30] ブロックコメントを先導します。コメントは対応する '@code{|#}' で終ります。 @c COMMON @item @code{#@}}, @code{#~} @c EN @tab Unused. @c JP @tab 未使用。 @c COMMON @end multitable @menu * Hash-bang token:: @end menu @node Hash-bang token, , Sharp syntax, Lexical structure @subsection Hash-bang token @c NODE Hash-bangトークン @lxindex #! @c EN A character sequence @code{#!} has two completely different semantics, depending on how and where it occurs. If a file begins with @code{#!/} or @code{#! } (hash, bang, and a space), then the reader assumes it is an interpreter line (shebang) of a script and ignores the rest of characters until the end of line. (Actually the source doesn't need to be a file. The reader checks whether it is the beginning of a port.) Other than the above case, @code{#!@var{identifier}} is read as a token with special meanings. This kind token can be a special directive for the reader, instead of read as a datum. By default, the following tokens are recognized. @c JP 文字シーケンス@code{#!}は、どこでどのように現れるかによって2つの全く異なる 意味を持ちます。 ファイルが@code{#!/}もしくは@code{#! } (ハッシュ、バング、空白) から始 まっている場合、読み込みルーチンはそれをスクリプトのインタプリタ指定行 (shebang) とみなし、最初の行末までを無視します。 (実際は、ソースはファイルでなくても構いません。リーダはポートの先頭かどうかで 判断します。) その場合以外では、@code{#!@var{identifier}}がひとつのトークンとして読ま れ、特別な意味を持ちます。この種のトークンはデータとして読まれるのでは なく、リーダに対して特別な指定を与えることもあります。 デフォルトでは、以下のトークンが認識されます。 @c COMMON @table @code @item #!fold-case @itemx #!no-fold-case @c EN Switches the reader's case sensitivity; @code{#!fold-case} makes the reader case insensitive, and @code{#!no-fold-case} makes it case sensitive. (Also see @ref{Case-sensitivity}). @c JP リーダが大文字小文字を区別するかどうかを切り替えます。 @code{#!fold-case}に出会うとリーダは大文字小 文字を区別しないモードになり、@code{#!no-fold-case}に出会うとその逆にな ります。(@ref{Case-sensitivity}も参照してください。) @c COMMON @item #!r6rs @c EN This token is introduced in R6RS and used to indicate the program strictly conforms R6RS. Gauche doesn't conform R6RS, but currently it just issues warning when it sees @code{#!r6rs} token, and it keeps reading on. @c JP このトークンはR6RSで導入され、プログラムがR6RSに準拠しているこ とを示します。GaucheはR6RSに準拠していませんが、今のところこのトー クンに出会っても警告を出すだけで読み込みは継続します。 @c COMMON @item #!r7rs @c EN Make the reader @code{strict-r7} mode, that complies R7RS. @xref{Reader lexical mode}, for the details. @c JP リーダをR7RSに準拠した@code{strict-r7}モードにします。 詳細は@ref{Reader lexical mode}を参照してください。 @c COMMON @c TODO: Describe concrete details @item #!gauche-legacy @c EN Make the reader @code{legacy} mode, that is compatible to Gauche 0.9.3 and before. @xref{Reader lexical mode}, for the details. @c JP リーダをGauche 0.9.3およびそれ以前のものと互換な@code{legacy}モードにします。 詳細は@ref{Reader lexical mode}を参照してください。 @c COMMON @end table @c ---------------------------------------------------------------------- @node Literals, Making procedures, Lexical structure, Core syntax @section Literals @c NODE リテラル @defspec quote datum [R7RS base] @c EN Evaluates to @var{datum}. @c JP @var{datum}それ自身を返します。 @c COMMON @example (quote x) @result{} x (quote (1 2 3)) @result{} (1 2 3) @end example @end defspec @deftp {Reader Syntax} @code{'@var{datum}} @lxindex ' [R7RS] @c EN Equivalent to @code{(quote datum)}. @c JP @code{(quote datum)}の略記です。 @c COMMON @example 'x @result{} x '(1 2 3) @result{} (1 2 3) @end example @end deftp @c EN @emph{Note:} Literals are immutable. You'll get an error if you try to change, for example, a quoted pair with @code{set-car!} or a literal string with @code{string-set!}. Mutability may be managed differently for each type, so some object may not raise an error even if it appears in a part of literals (it is often the case with user-defined class with read-time constructor, @pxref{Read-time constructor}. However, if you ever modify a literal data, it is not guaranteed that the program runs correctly. @c JP @emph{註:} リテラルは変更不可です。例えばクオートされたペアを@code{set-car!}に 渡したり、リテラル文字列を@code{string-set!}に渡すと、エラーが報告されるでしょう。 変更可能かどうかのチェックは型ごとに行われるので、時にはリテラルの一部であっても 変更でエラーにならないオブジェクトもあります (読み込み時コンストラクタを持つユーザ定義クラスはそうです。 @ref{読み込み時コンストラクタ}参照。) たとえエラーが発生しなくても、リテラルを変更しているプログラムの動作は 保証されません。 @c COMMON @c ---------------------------------------------------------------------- @node Making procedures, Assignments, Literals, Core syntax @section Making procedures @c NODE 手続きを作る @defspec lambda formals body @dots{} @defspecx ^ formals body @dots{} [R7RS+ base] @c EN Evaluates to a procedure. The environment in effect when this expression is evaluated is stored in the procedure. When the procedure is called, @var{body} is evaluated sequentially in the stored environment extended by the bindings of the formal arguments, and returns the value(s) of the last expression in the body. @c JP この式は評価されると手続きを生成します。この式が評価された時点の環境が手続き中に保持されます。 手続きが呼ばれると、記憶された環境に引数の束縛を追加した環境中で@var{body} が順に評価され、 最後の式の値が返されます。 @c COMMON @c EN @code{^} is a concise alias of @code{lambda}. It is Gauche's extension. @c JP @code{^}は@code{lambda}の短い別名です。これはGauche独自の拡張です。 @c COMMON @example (lambda (a b) (+ a b)) @c EN @result{} @r{procedure that adds two arguments} @c JP @result{} @r{二つの引数を加算する手続き} @c COMMON ((lambda (a b) (+ a b)) 1 2) @result{} 3 ((^(a b) (+ a b)) 1 2) @result{} 3 @end example @c EN Gauche also extends R7RS @code{lambda} to take extended syntax in @var{formals} to specify optional and keyword arguments easily. The same functionality can be written in pure R7RS, with parsing variable-length arguments explicitly, but the code tends to be longer and verbose. It is recommended to use extended syntax unless you're writing portable code. @c JP Gaucheはまた、@code{lambda}が取る@var{formals}の構文を拡張し、 省略可能引数やキーワード引数を簡単に指定できるようにしています。 同じ機能は純粋なR7RSでも、可変長引数を自力で解析することで実現可能ですが、 コードはより長く冗長になってしまいます。ポータブルなコードを書いているのでなければ 拡張構文を使った方が良いでしょう。 @c COMMON @c EN @var{Formals} should have one of the following forms: @c JP @var{Formals} は以下のいずれかの形でなければなりません。 @c COMMON @itemize @bullet @item @code{(@var{variable} @dots{})} : @c EN The procedure takes a fixed number of arguments. The actual arguments are bound to the corresponding variables. @c JP 手続きは決まった数の引数を取ります。 実引数がそれぞれ対応する@var{variable}に束縛されます。 @c COMMON @example ((lambda (a) a) 1) @result{} 1 ((lambda (a) a) 1 2) @result{} @i{error - wrong number of arguments} @end example @item @code{@var{variable}} : @c EN The procedure takes any number of arguments. The actual arguments are collected to form a new list and bound to the variable. @c JP 手続きは不定個の引数を取ります。 実引数は新しいリストに集められて、そのリストが@var{variable}に束縛されます。 @c COMMON @example ((lambda a a) 1 2 3) @result{} (1 2 3) @end example @item @code{(@var{variable_0} @dots{} @var{variable_N-1} . @var{variable_N})} : @c EN The procedure takes at least @var{N} arguments. The actual arguments up to @var{N} is bound to the corresponding variables. If more than @var{N} arguments are given, the rest arguments are collected to form a new list and bound to @var{variable_N}. @c JP 手続きは少なくとも@var{N}個の引数を取ります。@var{N}個までの実引数は対応する@var{variable} に束縛されます。@var{N}個を越えた実引数は新しいリストに集められて @var{variable_N}に束縛されます。 @c COMMON @example ((lambda (a b . c) (print "a=" a " b=" b " c=" c)) 1 2 3 4 5) @result{} @r{prints} a=1 b=2 c=(3 4 5) @end example @item @code{(@var{variable} @dots{} @var{extended-spec} @dots{})} : @c EN Extended argument specification. Zero or more variables that specifies required formal arguments, followed by an @emph{extended spec}, a list beginning with a keyword @code{:optional}, @code{:key} or @code{:rest}. The @var{extended-spec} part consists of the optional argument spec, the keyword argument spec and the rest argument spec. They can appear in any combinations. @c JP 拡張引数指定です。ゼロ個以上の必須引数を示す変数のリストの後に、 キーワード@code{:optional}、@code{:key}あるいは@code{:rest}で 始まる@var{extended-spec}が続きます。 @var{extended-spec}は省略可能引数指定、キーワード引数指定、残余引数指定の 任意の組み合わせにより構成されます。 @c COMMON @table @code @item :optional @var{optspec} @dots{} @c EN Specifies optional arguments. Each @var{optspec} can be either one of the following forms: @c JP 省略可能引数を指定します。各@var{optspec}は以下のいずれかの形式です。 @c COMMON @example @var{variable} (@var{variable} @var{init-expr}) @end example @c EN The @var{variable} names the formal argument, which is bound to the value of the actual argument if given, or the value of the expression @var{init-expr} otherwise. If @var{optspec} is just a variable, and the actual argument is not given to it, then @var{variable} will be bound to @code{#} (@pxref{Undefined values}). The expression @var{init-expr} is only evaluated if the actual argument for @var{variable} is not given. The scope in which @var{init-expr} is evaluated includes the preceding formal arguments. @c JP 仮引数@var{variable}は、対応する実引数が与えられればその値に、 与えられなければ@var{init-expr}を評価した値に束縛されます。 @var{optspec}が@code{@var{variable}}だけである場合は、 実引数が省略された時の仮引数の値は@code{#}になります (@ref{Undefined values}参照)。 @var{init-expr}は対応する実引数が与えられなかった場合にのみ評価されます。 @var{init-expr}の評価環境にはこの@var{optspec}に先立つ仮引数が含まれます。 @c COMMON @example ((lambda (a b :optional (c (+ a b))) (list a b c)) 1 2) @result{} (1 2 3) ((lambda (a b :optional (c (+ a b))) (list a b c)) 1 2 -1) @result{} (1 2 -1) ((lambda (a b :optional c) (list a b c)) 1 2) @result{} (1 2 #) ((lambda (:optional (a 0) (b (+ a 1))) (list a b)) ) @result{} (0 1) @end example @c EN The procedure signals an error if more actual arguments than the number of required and optional arguments are given, unless it also has @code{:key} or @code{:rest} argument spec. @c JP 必須引数と省略可能引数の総数よりも多い実引数が渡された場合、 その手続きが@code{:key}や@code{:rest}引数指定を持っていない限りは エラーが通知されます。 @c COMMON @example ((lambda (:optional a b) (list a b)) 1 2 3) @result{} @i{error - too many arguments} ((lambda (:optional a b :rest r) (list a b r)) 1 2 3) @result{} (1 2 (3)) @end example @item :key @var{keyspec} @dots{} [:allow-other-keys [@var{variable}]] @c EN Specifies keyword arguments. Each @var{keyspec} can be either one of the following forms. @c JP キーワード引数を指定します。各@var{keyspec}は以下の形式のいずれかです。 @c COMMON @example @var{variable} (@var{variable} @var{init-expr}) ((@var{keyword} @var{variable}) @var{init-expr}) @end example @c EN The @var{variable} names the formal argument, which is bound to the actual argument given with the keyword of the same name as @var{variable}. When the actual argument is not given, @var{init-expr} is evaluated and the result is bound to @var{variable} in the second and third form, or @code{#} is bound in the first form. @c JP 仮引数@var{variable}は、実引数に@var{variable}と同名のキーワードによる キーワード引数が与えられればその値に、そうでなければ@var{init-expr}を評価 した値に束縛されます。@var{init-expr}の無い最初の形式では、実引数が 与えられなければ@var{variable}は@code{#}に束縛されます。 @c COMMON @example (define f (lambda (a :key (b (+ a 1)) (c (+ b 1))) (list a b c))) (f 10) @result{} (10 11 12) (f 10 :b 4) @result{} (10 4 5) (f 10 :c 8) @result{} (10 11 8) (f 10 :c 1 :b 3) @result{} (10 3 1) @end example @c EN With the third form you can name the formal argument differently from the keyword to specify the argument. @c JP 三番目の形式では、仮引数の名前とは別に引数を与えるキーワードを指定できます。 @c COMMON @example ((lambda (:key ((:aa a) -1)) a) :aa 2) @result{} 2 @end example @c EN By default, the procedure with keyword argument spec raises an error if a keyword argument with an unrecognized keyword is given. Giving @code{:allow-other-keys} in the formals suppresses this behavior. If you give @var{variable} after @code{:allow-other-keys}, the list of unrecognized keywords and their arguments are bound to it. Again, see the example below will help to understand the behavior. @c JP デフォルトでは、キーワード引数指定をもつ手続きは、認識できないキーワード引数が 与えられた場合にエラーを通知します。仮引数リストに@code{:allow-other-keys}を指定することで、 この動作を抑制することができます。 @code{:allow-other-keys}に続いて@var{variable}を与えれば、 認識できなかったキーワード引数のリストが@var{variable}に束縛されます。 @c COMMON @example ((lambda (:key a) a) :a 1 :b 2) @result{} @i{error - unknown keyword :b} ((lambda (:key a :allow-other-keys) a) :a 1 :b 2) @result{} 1 ((lambda (:key a :allow-other-keys z) (list a z)) :a 1 :b 2) @result{} (1 (:b 2)) @end example @c EN When used with @code{:optional} argument spec, the keyword arguments are searched after all the optional arguments are bound. @c JP @code{:optional}引数指定と同時に使われた場合、キーワード引数はすべての 省略可能引数が束縛された後の実引数リストから探されます。 @c COMMON @example ((lambda (:optional a b :key c) (list a b c)) 1 2 :c 3) @result{} (1 2 3) ((lambda (:optional a b :key c) (list a b c)) :c 3) @result{} (:c 3 #) ((lambda (:optional a b :key c) (list a b c)) 1 :c 3) @result{} @i{error - keyword list not even} @end example @item :rest @var{variable} @c EN Specifies the rest argument. If specified without @code{:optional} argument spec, a list of remaining arguments after required arguments are taken is bound to @var{variable}. If specified with @code{:optional} argument spec, the actual arguments are first bound to required and all optional arguments, and the remaining arguments are bound to @var{variable}. @c JP 残余引数を指定します。@code{:optional}引数指定が無い場合は、 必須引数の束縛が済んだ後で残っている実引数のリストが@var{variable}に 束縛されます。@code{:optional}引数指定がある場合は、 必須引数とすべての省略可能引数の束縛が済んだ後で残っている実引数の リストが@var{variable}に束縛されます。 @c COMMON @example ((lambda (a b :rest z) (list a b z)) 1 2 3 4 5) @result{} (1 2 (3 4 5)) ((lambda (a b :optional c d :rest z) (list a b c d z)) 1 2 3 4 5) @result{} (1 2 3 4 (5)) ((lambda (a b :optional c d :rest z) (list a b c d z)) 1 2 3) @result{} (1 2 3 # ()) @end example @c EN When the rest argument spec is used with the keyword argument spec, both accesses the same list of actual argument---the remaining arguments after required and optional arguments are taken. @c JP 残余引数指定とキーワード引数指定の両方が与えられた場合、 両者はともに、必須引数と省略可能引数が処理された後の実引数リストを処理の対象とします。 @c COMMON @example ((lambda (:optional a :rest r :key k) (list a r k)) 1 :k 3) @result{} (1 (:k 3) 3) @end example @end table @c EN See also @code{let-optionals*}, @code{let-keywords} and @code{let-keywords*} macros in @ref{Optional argument parsing} for an alternative way to receive optional/keyword arguments within the spec of R7RS. @c JP R7RSの仕様範囲内で省略可能引数、キーワード引数を受け取るように 書くこともできます。@ref{Optional argument parsing}の @code{let-optionals*}、@code{let-keywords}、 @code{let-keywords*}を参照してください。 @c COMMON @end itemize @end defspec @defmac ^c body @dots{} @findex ^_ @findex ^a @findex ^b @findex ^d @findex ^e @findex ^f @findex ^g @findex ^h @findex ^i @findex ^j @findex ^k @findex ^l @findex ^m @findex ^n @findex ^o @findex ^p @findex ^q @findex ^r @findex ^s @findex ^t @findex ^u @findex ^v @findex ^w @findex ^x @findex ^y @findex ^z @c EN A shorthand notation of @code{(lambda (@var{c}) @var{body} @dots{})}. where @var{c} can be any character in @code{#[_a-z]}. @c JP @code{(lambda (@var{c}) @var{body} @dots{})}の短縮表記です。 @var{c}には@code{#[_a-z]}に含まれる任意の一文字が使えます。 @c COMMON @example (map (^x (* x x)) '(1 2 3 4 5)) @result{} (1 4 9 16 25) @end example @end defmac @defmac cut expr-or-slot expr-or-slot2 @dots{} @defmacx cute expr-or-slot expr-or-slot2 @dots{} [SRFI-26] @c EN Convenience macros to notate a procedure compactly. This form can be used to realize partial application, a.k.a sectioning or projection. @c JP 手続きを簡潔に書ける便利なマクロです。 いわゆる部分適用を実現するために使えます。 @c COMMON @c EN Each @var{expr-or-slot} must be either an expression or a symbol @code{<>}, indicating a 'slot'. The last @var{expr-or-slot} can be a symbol @code{<...>}, indicating a 'rest-slot'. @code{Cut} expands into a @code{lambda} form that takes as many arguments as the number of slots in the given form, and whose body is an expression @example (@var{expr-or-slot} @var{expr-or-slot2} @dots{}) @end example where each occurrence of @code{<>} is replaced to the corresponding argument. In case there is a rest-slot symbol, the resulting procedure is also of variable arity, and all the extra arguments are passed to the call of @var{expr-or-slot}. See the fourth example below. @c JP 各@var{expr-or-slot}は式またはシンボル@code{<>}でなければなりません。 最後の@var{expr-or-slot}はシンボル@code{<...>}であっても構いません。 @code{cut}は、そのフォーム中にある@code{<>}と同じ数の引数を取る @code{lambda}フォームに展開されます。そのフォームのボディには次の式が置かれます。 @example (@var{expr-or-slot} @var{expr-or-slot2} @dots{}) @end example 但し、各@code{<>}は対応する仮引数に置き換えられます。 もしシンボル@code{<...>}が与えられていた場合、展開された@code{lambda}フォームは 可変長引数を取る手続きとなり、作成される手続きに与えられたすべての引数が @var{expr-or-slot}を呼び出すのに使われます(下の4番目の例を参照のこと)。 @c COMMON @example (cut cons (+ a 1) <>) @equiv{} (lambda (x2) (cons (+ a 1) x2)) (cut list 1 <> 3 <> 5) @equiv{} (lambda (x2 x4) (list 1 x2 3 x4 5)) (cut list) @equiv{} (lambda () (list)) (cut list 1 <> 3 <...>) @equiv{} (lambda (x2 . xs) (apply list 1 x2 3 xs)) (cut <> a b) @equiv{} (lambda (f) (f a b)) ;; Usage (map (cut * 2 <>) '(1 2 3 4)) (for-each (cut write <> port) exprs) @end example @c EN @code{Cute} is a variation of @code{cut} that evaluates @var{expr-or-slot}s before creating the procedure. @c JP @code{cute}は@code{cut}とほぼ同じですが、@var{expr-or-slot}に与えられた フォームが手続きを作る前に評価される点が異なります。 @c COMMON @example (cute cons (+ a 1) <>) @equiv{} (let ((xa (+ a 1))) (lambda (x2) (cons xa x2))) @end example @c EN Gauche provides a couple of different ways to write partial applications concisely; see the @code{$} macro below, and also the @code{pa$} procedure (@pxref{Combinators}). @c JP Gaucheには他にも二つほど、部分適用を簡潔に書く方法があります。 下の@code{$}マクロ、及び組み込み手続き@code{pa$}です (@ref{Combinators}参照)。 @c COMMON @end defmac @defmac $ arg @dots{} @c EN A macro to chain applications, hinted from Haskell's @code{$} operator (although the meaning is different). Within the macro arguments @var{arg} @dots{}, @code{$} delimits the last argument. For example, the following code makes the last argument for the procedure @code{f} to be @code{(g c d @dots{})} @c JP 関数適用をチェインするマクロです。Haskellの@code{$}にヒントを得ました (意味は異なりますが)。 マクロ引数@var{arg} @dots{}中に@code{$}が出現すると、それが 関数の最後の引数の区切りとなります。例えば次のコードでは、 関数@code{f}の最後の引数が@code{(g c d @dots{})}となります。 @c COMMON @example ($ f a b $ g c d ...) @equiv{} (f a b (g c d ...)) @end example @c EN The @code{$} notation can be chained. @c JP @code{$}はチェインすることができます。 @c COMMON @example ($ f a b $ g c d $ h e f ...) @equiv{} (f a b (g c d (h e f ...))) @end example @c EN If @code{$*} appears in the argument list instead of @code{$}, it fills the rest of the arguments, instead of just the last argument. @c JP @code{$}のかわりに@code{$*}が現れた場合は、最後の引数ひとつだけでなく 「残りの引数全部」を示します。 @c COMMON @example ($ f a b $* g c d ...) @equiv{} (apply f a b (g c d ...)) ($ f a b $* g $ h $* hh ...) @equiv{} (apply f a b (g (apply h (hh ...)))) @end example @c EN Furthermore, if the argument list ends with @code{$} or @code{$*}, the whole expression becomes a procedure expecting the last argument(s). @c JP さらに、もし引数リストが@code{$}または@code{$*}で終わっていた場合は、 式全体が「残りの引数(リスト)」を受け取ることを期待する手続きとなります。 @c COMMON @example ($ f a b $ g c d $ h e f $) @equiv{} (lambda (arg) (f a b (g c d (h e f arg)))) @equiv{} (.$ (cut f a b <>) (cut g c d <>) (cut h e f <>)) ($ f a b $ g c d $ h e f $*) @equiv{} (lambda args (f a b (g c d (apply h e f args)))) @equiv{} (.$ (cut f a b <>) (cut g c d <>) (cut h e f <...>)) @end example @c EN The more functional the code becomes, the more you are tempted to write it as a chain of nested function calls. Scheme's syntax can get awkward in such code. Close parentheses tend to clutter at the end of expressions. Inner applications tends to pushed toward right columns with the standard indentation rules. Compare the following two code functionally equivalent to each other: @c JP 関数的にコードを書いていると、関数呼び出しが深くネストすることが多くなります。 しかしSchemeの構文はそのようなネストとあまり相性が良くありません。 閉じ括弧が式の最後にずらずらと積み重なりますし、また通常のインデントルールでは コードが右のカラムにどんどん伸びていってしまいます。次の同等な二つの式を比べてみてください。 @c COMMON @example (intersperse ":" (map transform-it (delete-duplicates (map cdr (group-sequence input))))) ($ intersperse ":" $ map transform-it $ delete-duplicates $ map cdr $ group-sequence input) @end example @c EN It is purely a matter of taste, and also this kind of syntax sugars can be easily abused. Use with care, but it may work well if used sparingly, like spices. @c JP これはあくまで好みの問題ですし、こういった構文糖衣は濫用されがちなので 気をつけてください。けれどもスパイスのように、控えめな隠し味として使うと、 しばしばとても有用です。 @c COMMON @c EN As a corner case, if neither @code{$} nor @code{$*} appear in the argument list, it just calls the function. It is useful when the function has long name and you don't want to indent arguments too further right. @c JP コーナーケースとして、引数リストに@code{$}も@code{$*}も現れなかった場合は、 単なる関数呼び出しになります。これだけでも、関数名が長くて引数をあまり右に 深くインデントしたくない場合には便利です。 @c COMMON @example ($ f a b c) @equiv{} (f a b c) @end example @end defmac @defmac case-lambda clause @dots{} [R7RS case-lambda] @c EN Each @var{clause} should have the form (@var{formals} @var{expr} @dots{}), where @var{formals} is a formal arguments list as for @code{lambda}. This expression evaluates to a procedure that accepts a variable number of arguments and is lexically scoped in the same manner as procedures resulting from @code{lambda} expressions. When the procedure is called with some arguments, then the first @var{clause} for which the arguments agree with @var{formals} is selected, where agreement is specified as for the @var{formals} of a @code{lambda} expression. The variables of @code{formals} are bound to the given arguments, and the @var{expr} @dots{} are evaluated within the environment. It is an error for the arguments not to agree with the @var{formals} of any @var{clause}. @c JP それぞれの @var{clause} は (@var{formals} @var{expr} @dots{}) という形式 でなければなりません。ここで、@var{formals} は @code{lambda} の仮引数 リストです。 この式は、評価されると可変数の引数をとり、@code{lambda} 式から結果として できる手続きと同じレキシカルスコープをもつ手続きになります。この手続きが いくつかの引数とともに呼ばれると、その引数が @var{formals} と一致する 最初の @var{clause} が選択されます。この引数の一致というのは、 @code{lambda} 式の @var{formals} に対応するものとして指定されるものです。 @code{formals} の変数は実引数に束縛され、 @var{expr} @dots{} がその 環境内で評価されます。 実際の引数がどの @var{clause} の @var{formals} にも一致しなければエラーです。 @c COMMON @example (define f (case-lambda [() 'zero] [(a) `(one ,a)] [(a b) `(two ,a ,b)])) (f) @result{} zero (f 1) @result{} (one 1) (f 1 2) @result{} (two 1 2) (f 1 2 3) @result{} @r{Error: wrong number of arguments to case lambda} (define g (case-lambda [() 'zero] [(a) `(one ,a)] [(a . b) `(more ,a ,@@b)])) (g) @result{} zero (g 1) @result{} (one 1) (g 1 2 3) @result{} (more 1 2 3) @end example @c EN Note that the clauses are examined sequentially to match the number of arguments, so in the following example @code{g2} never returns @code{(one ...)}. @c JP 各@var{clause}は順に引数の個数とマッチするかどうか調べられます。次の例では @code{g2}が@code{(one ...)}を返すことはありません。 @c COMMON @example (define g2 (case-lambda [() 'zero] [(a . b) `(more ,a ,@@b)] [(a) `(one ,a)])) (g2 1) @result{} (more 1) @end example @end defmac @c ---------------------------------------------------------------------- @node Assignments, Conditionals, Making procedures, Core syntax @section Assignments @c NODE 代入 @defspec set! symbol expression @defspecx set! (proc arg @dots{}) expression [R7RS+ base][SRFI-17] @c EN First, @var{expression} is evaluated. In the first form, the binding of @var{symbol} is modified so that next reference of @var{symbol} will return the result of @var{expression}. If @var{symbol} is not locally bound, the global variable named @var{symbol} must already exist, or an error is signaled. @c JP まず@var{expression}が評価されます。最初の形式では、@var{symbol}への束縛が @var{expression}の結果を指すように変更されます。 もし@var{symbol}がローカルに束縛されていない場合は、グローバルな変数@var{symbol}が 存在していなければなりません。そうでなければエラーが報告されます。 @c COMMON @c EN The second form is a ``generalized set!'' specified in SRFI-17. It is a syntactic sugar of the following form. @example ((setter @var{proc}) @var{arg} @dots{} @var{expression}) @end example Note the order of the arguments of the setter method differs from CommonLisp's @code{setf}. Some examples: @c JP 2番目の形式はSRFI-17に定義されている「一般化されたset!」です。 これは構文的な装飾であり、実際は以下のように解釈されます。 @example ((setter @var{proc}) @var{arg} @dots{} @var{expression}) @end example CommonLispの@code{setf}とは、setter手続きに渡される引数の順序が異なることに注意して下さい。 例: @c COMMON @example (define x 3) (set! x (list 1 2)) x @result{} (1 2) (set! (car x) 5) x @result{} (5 2) @end example @end defspec @defmac set!-values (var @dots{}) expr @defmacx set!-values (var @dots{} . varn) expr @defmacx set!-values var expr [SRFI-210] @c EN Sets values of multiple variables at once. @var{Expr} must yield as many values as @var{var} @dots{}. Each value is set to the corresponding @var{var}. @c JP 複数の変数を同時に更新します。@var{Expr}は与えられた変数と同じ 数だけの値を生成しなけばなりません。各値が対応する@var{var}に セットされます。 @c COMMON @example (define a 0) (define b 1) (define c 2) (set!-values (a b) (values 3 4)) a @result{} 3 b @result{} 4 (set!-values (a b) (values b a)) a @result{} 4 b @result{} 3 (set!-values (a b . c) (values 1 2 3 4)) a @result{} 1 b @result{} 2 c @result{} (3 4) @end example @c EN See also @code{define-values} (@ref{Definitions}). @c JP @code{define-values}も参照 (@ref{Definitions})。 @c COMMON @end defmac @defun setter proc [SRFI-17] @c EN Returns a setter procedure associated to the procedure @var{proc}. If no setter is associated to @var{proc}, its behavior is undefined. A setter procedure @var{g} of a procedure @var{f} is such that when used as @code{(g a b @dots{} v)}, the next evaluation of @code{(f a b @dots{})} returns @var{v}. To associate a setter procedure to another procedure, you can use the setter of @code{setter}, like this: @example (set! (setter @var{f}) @var{g}) @end example A procedure's setter can be ``locked'' to it. System default setters, like @code{set-car!} for @code{car}, is locked and can't be set by the above way. In order to lock a setter to a user defined procedure, use @code{getter-with-setter} below. If @var{proc} is not a procedure, a setter generic function of @code{object-apply} is returned; it allows the applicable object extension to work seamlessly with the generalized @code{set!}. @xref{Applicable objects}, for the details. @c JP 手続き@var{proc}のsetter手続きを返します。 @var{proc}がsetter手続きを持たない場合の動作は未定義です。 ある関数@var{f}のsetter手続き@var{g}とは、もし@code{(g a b @dots{} v)}のように 呼ばれた場合、次の@code{(f a b @dots{})}が@var{v}を返すようになる手続きのことです。 ある手続きにsetter手続きを関連付けるには、@code{setter}自身のsetter手続きを使うことが できます。 @example (set! (setter @var{f}) @var{g}) @end example 特定の手続きにsetter手続きを「ロック」することができます。システム既定のsetter手続き、 例えば@code{car}に対する@code{set-car!}等はロックされていて、上記のような方法で 変更することは出来ません。ユーザ定義手続きにsetter手続きをロックするには下記の @code{getter-with-setter}を使います。 @var{proc}が手続きでない場合は、@code{object-apply}ジェネリックファンクションの setterが返されます。これにより、適用可能オブジェクトが一般化された@code{set!} でもうまく動作します。詳しくは@ref{Applicable objects}を参照して下さい。 @c COMMON @end defun @defun has-setter? proc @c EN Returns @code{#t} if a setter is associated to @var{proc}. @c JP @var{proc}がsetter手続きを持っている場合は@code{#t}を返します。 @c COMMON @end defun @defun getter-with-setter get set [SRFI-17] @c EN Takes two procedure @var{get} and @var{set}. Returns a new procedure which does the same thing as @var{get}, and its setter is locked to @var{set}. When an inlinable procedure has a locked setter, generalized @code{set!} may be inlined by the compiler. @xref{Definitions}, for inlinable procedure definition. @c JP 2つの手続き、@var{get}と@var{set}を取り、新しい手続きを返します。 新しい手続きは@var{get}と同じ動作をし、そのsetter手続きは@var{set}にロックされて います。 インライン化可能な手続きにsetterがロックされている場合、一般化された@code{set!}は コンパイラによってインライン展開される場合があります。 インライン化可能な手続きの定義については@ref{Definitions}を参照してください。 @c COMMON @end defun @c EN A few macros that adopts the same semantics of generalized @code{set!} are also provided. They are built on top of @code{set!}. @c JP Gaucheでは、一般化された@code{set!}と同じセマンティクスを持ついくつかのマクロが定義 されています。これらは@var{set!}を使った形に展開されます。 @c COMMON @defmac push! place item @c EN Conses @var{item} and the value of @var{place}, then sets the result to @var{place}. @var{place} is either a variable or a form @code{(@var{proc} @var{arg} @dots{})}, as the second argument of @code{set!}. The result of this form is undefined. @c JP @var{item}と@var{place}の値をコンスし、その結果を再び@var{place}にセットします。 @var{place}は@code{set!}と同様に、 変数か@code{(@var{proc} @var{arg} @dots{})}という形式でなければなりません。 このマクロの戻り値は未定義です。 @c COMMON @example (define x (list 2)) (push! x 3) x @result{} (3 2) (push! (cdr x) 4) x @result{} (3 4 2) @end example @c EN When @var{place} is a list, it roughly expands like the following. @c JP @var{place}がリストの場合、だいたいこんなふうに展開されます。 @c COMMON @example (push! (foo x y) item) @equiv{} (let ((tfoo foo) (tx x) (ty y)) ((setter tfoo) tx ty (cons item (tfoo tx ty)))) @end example @c EN Note: Common Lisp's @code{push} macro takes its argument reverse order. I adopted this order since it is consistent with other destructive operations. Perl's @code{push} function takes the same argument order, but it appends @var{item} at the end of the array (Perl's @code{unshift} is closer to @code{push!}). You can use a queue (@pxref{Queue}) if you need a behavior of Perl's @code{push}. @c JP 註:Common Lispの@code{push}マクロは引数を逆の順番で取ります。 @code{push!}は他の副作用を持つ形式との互換性を考えてこの順番としました。 Perlの@code{push}関数は@code{push!}マクロと同じ引数順ですが、 @var{item}はシーケンスの末尾に追加されます (Perlの@code{unshift}の方が @code{push!}の動作に近いです)。 Perlのpushオペレータの動作が必要ならQueueが使えます (@ref{Queue}参照)。 @c COMMON @end defmac @defmac push-unique! place item [equal] @c EN The value in @var{place} must be a list. If @var{item} isn't already in the value in @var{place}, @var{place} is updated with the cons of @var{item} and its previous value. If @var{item} is already in the value, nothing is done. The equivalence is checked with @var{equal} procedure. If omitted, @code{eqv?} is assumed. This is similar to Common Lisp's @code{pushnew}, but the argument order is flipped. See also @code{enqueue-unique!} and @code{queue-push-unique!} in @code{data.queue} (@ref{Queue}). @c JP @var{place}の値はリストでなければなりません。@var{item}がそのリスト中に なければ、@var{place}が@var{item}を先頭にコンスした値に更新されます。 @var{item}が既に@var{place}の値の中にあれば、何も起きません。 @var{item}が既にある値と等しいかどうかは@var{equal}手続きで比較されます。 省略された場合は@code{eqv?}が使われます。 Common Lispの@code{pushnew}に似ていますが、引数の順序が異なります。 @code{data.queue}の@code{enqueue-unique!}と@code{queue-push-unique!}も 参照してください(@ref{Queue})。 @c COMMON @example (define v (vector '("a"))) (push-unique! (vector-ref v 0) "b") v @result{} #(("b" "a")) (push-unique! (vector-ref v 0) "A" string-ci=?) v @result{} #(("b" "a")) (push-unique! (vector-ref v 0) "A") v @result{} #(("A" "b" "a")) @end example @end defmac @defmac pop! place @c EN Retrieves the value of @var{place}, sets its @code{cdr} back to @var{place} and returns its @code{car}. @c JP @var{place}の値を取り出し、その@code{cdr}を@var{place}にセットします。 元の値の@code{car}を返します。 @c COMMON @example (define x (list 1 2 3)) (pop! x) @result{} 1 x @result{} (2 3) (define x (vector (list 1 2 3))) x @result{} #((1 2 3)) (pop! (vector-ref x 0)) @result{} 1 x @result{} #((2 3)) @end example @c EN Note: This works the same as Common Lisp's @code{pop}. Perl's @code{pop} pops value from the end of the sequence; its @code{shift} does the same thing as @code{pop!}. @c JP 註:この動作はCommon Lispの@code{pop}と同じです。 Perlの@code{pop}はシーケンスの末尾から値を取ります。 Perlなら@code{shift}が@code{pop!}の動作に近いです。 @c COMMON @end defmac @defmac inc! place :optional delta @defmacx dec! place :optional delta @c EN Evaluates the value of @var{place}. It should be a number. Adds (@code{inc!}) or subtracts (@code{dec!}) @var{delta} to/from it, and then stores the result to @var{place}. The default value of @var{delta} is 1. This is like Common Lisp's @code{incf} and @code{decf}, except that you can't use the result of @code{inc!} and @code{dec!}. @c JP @var{place}の値を評価します。それは数値にならなければなりません。 その値に@var{delta}が加算(@code{inc!})もしくは減算(@code{dec!})され、 結果が@var{place}に格納されます。@var{delta}の既定値は1です。 Common Lispの@code{incf}と@code{decf}に似ていますが、 戻り値を使うことは出来ません。 @c COMMON @end defmac @defmac update! place proc @c EN Generalized form of @code{push!} etc. @var{Proc} must be a procedure which takes one argument and returns one value. The original value of @var{place} is passed to the @var{proc}, then its result is set to @var{place}. @c JP @code{push!}等のマクロの一般化された形式です。 @var{proc}は一つの引数を取り、一つの値を返す手続きでなければなりません。 @var{place}の値が@var{proc}に渡され、@var{proc}の結果が@var{place}に格納されます。 @c COMMON @example (define a (cons 2 3)) (update! (car a) (lambda (v) (* v 3))) a @result{} (6 . 3) (update! (cdr a) (cut - <> 3)) a @result{} (6 . 0) @end example @end defmac @defmac rotate! place0 place1 @dots{} placeN @c EN It is roughly equivalent to: @c JP 次のコードと概ね同じです: @c COMMON @example (let ((tmp0 place0) (tmp1 place1) ... (tmpN placeN)) (set! place0 tmp1) (set! place1 tmp2) : (set! placeN tmp0)) @end example @c EN However, if @code{place} is the form @code{(proc arg ...)}, then each @var{arg} is evaluated only once. @c JP 但し、@code{place}が@code{(proc arg ...)}の形であった場合、 各@var{arg}は1度しか評価されません。 @c COMMON @c EN It can be used to swap values of two locations: @c JP 二ヶ所の値を交換するのにも使えます: @c COMMON @example (let ((x (vector 1 2))) (rotate! (~ x 0) (~ x 1)) x) @result{} #(2 1) @end example @c EN This is similar to Common Lisp's @code{rotatef}. @c JP これはCommon Lispの@code{rotatef}に似ています。 @c COMMON @end defmac @c ---------------------------------------------------------------------- @node Conditionals, Binding constructs, Assignments, Core syntax @section Conditionals @c NODE 条件式 @defspec if test consequent alternative @defspecx if test consequent [R7RS base] @c EN @var{Test} is evaluated. If it yields a true value, @var{consequent} is evaluated. Otherwise, @var{alternative} is evaluated. If @var{alternative} is not provided, it results undefined value. @c JP まず@code{test}を評価し、それが真の値を返したら@var{consequent}を評価します。 そうでなければ@var{alternative}を評価します。もし@var{alternative}が与えられて いなければ未定義の値を返します。 @c COMMON @example (if (number? 3) 'yes 'no) @result{} yes (if (number? #f) 'yes 'no) @result{} no (let ((x '(1 . 2))) (if (pair? x) (values (car x) (cdr x)) (values #f #f))) @result{} 1 @r{and} 2 @end example @end defspec @defspec cond clause1 clause2 @dots{} [R7RS+ base][SRFI-61] @c EN Each @var{clause} must be the form @example (@var{test} @var{expr} @dots{}) (@var{test} => @var{expr}) (@var{test} @var{guard} => @var{expr}) (else @var{expr} @var{expr2} @dots{}) @end example The last form can appear only as the last clause. @code{cond} evaluates @var{test} of each clauses in order, until it yields a true value. Once it yields true, if the clause is the first form, the corresponding @var{expr}s are evaluated and the result(s) of last @var{expr} is(are) returned; if the clause is the second form, the @var{expr} is evaluated and it must yield a procedure that takes one argument. Then the result of @var{test} is passed to it, and the result(s) it returns will be returned. The third form is specified in SRFI-61. In this form, @var{test} can yield arbitrary number of values. The result(s) of @var{test} is(are) passed to @var{guard}; if it returns a true value, @var{expr} is applied with an equivalent argument list, and its result(s) is(are) returned. If @var{guard} returns @code{#f}, the evaluation proceeds to the next clause. If no test yields true, and the last clause is not the fourth form (else clause), an undefined value is returned. If the last clause is else clause and all tests are failed, @var{expr}s in the else clause are evaluated, and its last @var{expr}'s result(s) is(are) returned. @c JP 各@var{clause}節は次のいずれかの形式でなければなりません。 @example (@var{test} @var{expr} @dots{}) (@var{test} => @var{expr}) (@var{test} @var{guard} => @var{expr}) (else @var{expr} @var{expr2} @dots{}) @end example 最後の形式は最後の節のみに許されます。 最初の節から順に@var{test}が評価され、それが真の値を返すまで次の節の@var{test}が 評価されます。@var{test}が真の値を返したら、それが最初の形式であれば その節の@var{expr}が順に評価され、最後の評価値が戻り値となります。 それが2番目の形式であれば、@var{expr}がまず評価されます。 @var{expr}は引数をひとつ取る手続きを返さねばなりません。 続いて、@var{test}の結果がその手続きに渡され、その手続きの戻り値が@code{cond}形式の 評価値となります。 3番目の形式はSRFI-61で定義されています。この形式では、@var{test}は 任意の数の値に評価されることができます。それらの値がまず @var{guard}に渡され、もし@var{guard}が真の値を返したら、同じ引数が@var{expr}に 適用されて、その戻り値が@code{cond}形式の評価値となります。 @var{guard}が@code{#f}を返した場合は次の節へと評価が進みます。 @var{guard}と@var{expr} は、@var{test}が返すのと同数の引数を取れなければいけません。 もし全てのテストが偽の値を返し、最後の節が4番目の形式(else節)でなければ、未定義の値が返されます。 最後の節が@code{else}節で、他の全てのテストが失敗した場合、@code{else}節の@var{expr} が順に評価され、その最後の値が@code{cond}形式の値となります。 @c COMMON @example (cond ((> 3 2) 'greater) ((< 3 2) 'less)) @result{} greater (cond ((> 3 3) 'greater) ((< 3 3) 'less) (else 'equal)) @result{} equal (cond ((assv 'b '((a 1) (b 2))) => cadr) (else #f)) @result{} 2 @end example @end defspec @defspec case key-expr clause1 clause2 @dots{} [R7RS+ base][SRFI-87] @c EN @var{Key-expr} may be any expression that yields one value. Each @var{clause} should have the form @example ((@var{datum} ...) @var{expr} @var{expr2} @dots{}) ((@var{datum} ...) => @var{proc}) @end example where each @var{datum} is an external representation of some object. All the @var{datum}s must be distinct. The last @var{clause} may be an ``else clause,'' which has the form @example (else @var{expr} @var{expr2} @dots{}) (else => @var{proc}) @end example First, @var{key-expr} is evaluated and its result is compared against each @var{datum}. If the result of evaluating @var{key-expr} is equivalent (using @code{eqv?}, @pxref{Equality}) to a @var{datum}, then the expressions in the corresponding clause are evaluated sequentially, and the result(s) of the last expression in the @var{clause} is(are) returned from the case expression. The forms containing @code{=>} are specified in SRFI-87. In these forms, the result of @var{key-expr} is passed to @var{proc}, and its result(s) is(are) returned from the case expression. If the result of evaluating @var{key-expr} is different from every @var{datum}, then if there is an else clause its expressions are evaluated and the result(s) of the last is(are) the result(s) of the case expression; otherwise the result of the case expression is undefined. @c JP @var{key-expr}は1つの値を生成する任意の式です。 @var{clause}は以下の形式でなければなりません。 @example ((@var{datum} ...) @var{expr} @var{expr2} @dots{}) ((@var{datum} ...) => @var{proc}) @end example ここで、各@var{datum}はSchemeオブジェクトの外部表現であり、全ての@var{datum}は 異なっていなければなりません。最後の@var{clause}には次の形式を持つelse節が許されます。 @example (else @var{expr} @var{expr2} @dots{}) (else => @var{proc}) @end example まず@var{key-expr}が評価され、その結果がそれぞれの@var{datum}と比較されます。 @var{key-expr}の値と@code{eqv?}(@ref{Equality}参照)を使って一致する@var{datum} が見つかれば、対応する@var{expr}が順に評価され、その最後の値が@code{case}の 値となります。@code{=>}を含む節はSRFI-87で定義されています。これらの節では、 @var{key-expr}の結果が@var{proc}に渡され、その結果が@code{case}の値となります。 もし一致する@var{datum}が見つからない場合、else節が与えられていれば その@var{expr}が順に評価され、最後の値が返されます。else節がなければ@code{case}節 の値は未定義です。 @c COMMON @example (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite)) @result{} composite (case (car '(c d)) ((a) 'a) ((b) 'b)) @result{} @r{undefined} (case (car '(c d)) ((a e i o u) 'vowel) ((w y) 'semivowel) (else 'consonant)) @result{} consonant (case 6 ((2 4 6 8) => (cut + <> 1)) (else => (cut - <> 1))) @result{} 7 (case 5 ((2 4 6 8) => (cut + <> 1)) (else => (cut - <> 1))) @result{} 4 @end example @end defspec @defmac ecase key-expr clause1 clause2 @dots{} @c EN This works exactly like @code{case}, except when there's no @code{else} clause and the value of @var{key-expr} expression doesn't match any of @var{datum}s provided in @var{clause}s. While @code{case} form returns undefined value for such case, @code{ecase} raises an error. It is taken from Common Lisp. It's a convenient form when you want to detect unexpected value getting passed just in case. @c JP このフォームはほぼ@code{case}と同等ですが、@code{else}節が与えられず、 @var{key-expr}の値が@var{clause}中のどの@var{datum}とも一致しなかった場合の 動作だけが異なります。@code{case}ではそのような場合は未定義値が返されますが、 @code{ecase}はエラーを報告します。 このマクロはCommon Lispから採られました。想定外の値が渡されることを 念のために検出したい、という場合に便利です。 @c COMMON @smallexample (ecase 5 ((1) 'a) ((2 3) 'b) ((4) 'c)) @result{} ERROR: ecase test fell through: got 5, expecting one of (1 2 3 4) @end smallexample @end defmac @defmac typecase key-expr clause1 clause2 @dots{} @c EN This is taken from Common Lisp. @var{Key-expr} is a Scheme expression yielding one value. Each @var{clause} must have either one of the following forms. The @code{else} clause can only appear as the last clause, if any. @c JP これはCommon Lispから採られました。 @var{key-expr}はひとつの値を生成するScheme式です。 各@var{clause}は次のいずれかの形式でなければなりません。 @code{else}節は、現れるなら最後の@var{clause}でなければなりません。 @c COMMON @example (@var{type-expr} @var{expr} @dots{}) (else @var{expr1} @var{expr2} @dots{}) @end example @c EN Each @var{type-expr} must be a type expression (@pxref{Types and classes}). @c JP 各@var{type-expr}は型の式でなければなりません (@ref{Types and classes}参照)。 @c COMMON @c EN This macro first evaluates @var{key-expr}, then tests if its value is of the type @var{type-expr}, in turn. If the type constraint is satisfied, the @var{expr} @dots{} in the clause is evaluated and the last result(s) becomes the value of @code{typecase}. Type constrant is checked with @code{of-type?} (@pxref{Generic type predicates}). If none of the type constrait is satisfied, @var{expr}s in the @code{else} clause is evaluated if any, or an undefined value results. @c JP このマクロはまず@var{key-expr}を評価し、次にその値が型@var{type-expr}であるかどうかを 順番に検査してゆきます。もし型の制約が満たされたら、その節にある@var{expr} @dots{} が評価され、その最後の値が@code{typecase}の値となります。 型の制約は@code{of-type?}で検査されます (@ref{Generic type predicates}参照)。 どの節の型でもなかった場合、@code{else}節があればその中の式が順に評価されて最後の値が @code{typecase}の値となり、@code{else}節がなければ未定義値が返されます。 @c COMMON @example (typecase key-expr ( 'a) (( ) 'b)) @equiv{} (let ((tmp key-expr)) (cond ((of-type? tmp ) 'a) ((of-type? tmp ( )) 'b))) @end example @end defmac @defmac etypecase key-expr clause1 clause2 @dots{} @c EN Like @code{typecase}, but if the value of @var{key-expr} satisfies no @var{type-expr} and there's no @code{else} clause, an error is signaled. If there's an @code{else} clause, it is the same as @code{typecase}. @c JP @code{typecase}と似ていますが、@var{key-expr}の結果が どの@var{type-expr}の型でもなく、また@code{else}節がなかった場合、 エラーが投げられます。@code{else}節がある場合は @code{typecase}と同じです。 @c COMMON @example (etypecase (sqrt -2) ( 'int) ( 'real)) @result{} *** ERROR: etypecase fell through: expecting one of types in ( ), but got 0.0+1.4142135623730951i @end example @end defmac @defspec and test @dots{} [R7RS base] @c EN The @var{test} expressions are evaluated from left to right, and the value of the first expression that evaluates to a false value is returned. Any remaining expressions are not evaluated. If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then @code{#t} is returned. @c JP @var{test}式が順に評価されます。最初に偽の値を返したところで評価が止まり、 偽の値が返されます。残りの式は評価されません。 もし全ての式が真の値を返した場合は、最後の式の値が返されます。 式が与えれない場合は@code{#t}が返されます。 @c COMMON @example (and (= 2 2) (> 2 1)) @result{} #t (and (= 2 2) (< 2 1)) @result{} #f (and 1 2 'c '(f g)) @result{} (f g) (and) @result{} #t @end example @end defspec @defspec or test @dots{} [R7RS base] @c EN The @var{test} expressions are evaluated from left to right, and the value of the first expression that evaluates to a true value is returned. Any remaining expressions are not evaluated. If all expressions evaluate to false values, the value of the last expression is returned. If there are no expressions then @code{#f} is returned. @c JP @var{test}式が順に評価されます。最初に真の値を返したところで評価が止まり、 その値が返されます。残りの式は評価されません。 もし全ての式が偽の値を返した場合は、偽の値が返されます。 式が与えれない場合は@code{#f}が返されます。 @c COMMON @example (or (= 2 2) (> 2 1)) @result{} #t (or (= 2 2) (< 2 1)) @result{} #t (or #f #f #f) @result{} #f (or (memq 'b '(a b c)) (/ 3 0)) @result{} (b c) @end example @end defspec @defspec when test expr1 expr2 @dots{} @defspecx unless test expr1 expr2 @dots{} [R7RS base] @c EN Evaluates @var{test}. If it yields true value (or false in case of @code{unless}), @var{expr1} and @var{expr2} @dots{} are evaluated sequentially, and the result(s) of the last evaluation is(are) returned. Otherwise, undefined value is returned. @c JP まず@var{test}が評価されます。それが真の値(@code{unless}の場合は偽の値)を返した場合、 引続き@var{expr1}および@var{expr2} @dots{}が順に評価され、最後の評価値が返されます。 そうでなければ、未定義の値が返されます。 @c COMMON @end defspec @defmac assume test-expr [message obj @dots{}] [SRFI-145] @c EN Evaluates @var{text-expr} and returns its value. Also, this form declares the programmer's intent that the code following this path always satisfy @var{test-expr}. Currently, Gauche always signals an error if @var{text-expr} evaluates to @code{#f}. @c JP @var{test-expr}を評価してその値を返します。 また、このフォームに続くコードパスにおいて、@var{test-expr}が常に満たされている、 というプログラマの意図を宣言します。 Gaucheでは今のところ、@var{text-expr}が偽となった場合は常にエラーが投げられます。 @c COMMON @example (define (rsqrt x) (assume (and (real? x) (>= x 0))) (sqrt x)) gosh> (rsqrt -1) *** ERROR: Invalid assumption: (and (real? x) (>= x 0)) @end example @c EN If optional arguments @var{message} @var{obj} @dots{} are passed, they are given to the @code{error} procedure when @var{test-expr} yields false. @c JP 省略可能な引数 @var{message} @var{obj} @dots{} が与えられた場合、 それらは@var{test-expr}が偽を返した際に@code{error}の引数に使われます。 @c COMMON @example (define (rsqrt x) (assume (and (real? x) (>= x 0)) "Argument must be nonnegative real number, but got:" x) (sqrt x)) gosh> (rsqrt -1) *** ERROR: Argument must be nonnegative real number, but got: -1 @end example @c EN Note: This form is advisory---it isn't guaranteed for an error to be signaled when @var{test-expr} fails. For example, we may add an optimization option that omits testing in speed-optimized code in future. We may also enhance the compiler to generate better code using the given information---for example, in the above @code{real-sqrt} code, the compiler could theoretically deduce that @code{(sqrt x)} only needs to work as real functions, so it would be able to generate specialized code. Use this form to inform the compiler and the reader your intention. @c JP 註: このフォームは勧告として機能します。 @var{test-expr}が失敗してもエラーが投げられるとは限りません。例えば、 将来、最適化オプションをつけて、 速度最適化レベルが高い時はテストを省略するようになるかもしれません。 また一方で、この情報を利用してコンパイラがより良いコードを出すように拡張される 可能性もあります。例えば上の@code{real-sqrt}の例では、コンパイラは理論的には @code{(sqrt x)}が実関数として動作すれば良いということを演繹できるため、 実数に特化したコードを生成できる可能性があります。 このフォームを、コードの書き手の意図をコンパイラやコードの読み手に知らせるために 用いると良いでしょう。 @c COMMON @end defmac @defmac assume-type expr type [message obj @dots{}] @c EN Evaluates @var{expr}, and Checks if the value has type @var{type}. If not, raises an error. The result of @var{expr} is returned. @c JP @var{expr}を評価し、その値が型@var{type}かどうかチェックします。 型が合わなければエラーを投げます。@var{expr}の値が返されます。 @c COMMON @c EN As @var{type}, you can specify a Gauche class or a descriptive type. The value is of type if it satisfies @code{(of-type? value type)} (@pxref{Types and classes}). @c JP @var{type}にはGaucheのクラスか記述的な型を指定できます。 値がその型かどうかは@code{(of-type? value type)}で判定されます (@ref{Types and classes}参照)。 @c COMMON @c EN If optional arguments @var{message} @var{obj} @dots{} are passed, they are given to the @code{error} procedure when @var{test-expr} yields false. @c JP 省略可能な引数 @var{message} @var{obj} @dots{} が与えられた場合、 それらは@var{test-expr}が偽を返した際に@code{error}の引数に使われます。 @c COMMON @example (define (strlen s) (assume-type s ) (string-length s)) gosh> (strlen 4) *** ERROR: s is supposed to be of type #>, but got 4 (define (strlen s) (assume-type s "Argument s must be a string, but got:" s) (string-length s)) gosh> (strlen 4) *** ERROR: Argument s must be a string, but got: 4 @end example @c EN The type assumption may be used by the compiler future compilers for optimizations. In order for the compiler to use the type constraint information, @var{type} must be an expression statically computable at compile-time. That is, it must be either a class or a type constructor expression, or a constant binding to them. @c JP このフォームによる情報は、将来のコンパイラで最適化に使われるかもしれません。 コンパイラが型制約の情報を利用するためには、@var{type}が静的に型へと計算可能でなければ なりません。すなわち、クラスか、型コンストラクタか、それらへのconstantな束縛です。 @c COMMON @c EN Note: Like @code{assume}, this form is advisory; it is not guaranteed that the check is performed, nor @var{expr} is evaluated. @c JP 註: @code{assume}と同様、このフォームも勧告として機能します。 チェックがなされるか、@var{expr}が評価されるかどうかは保証されません。 @c COMMON @end defmac @node Binding constructs, Grouping, Conditionals, Core syntax @section Binding constructs @c NODE 変数束縛 @defspec let ((var expr) @dots{}) body @dots{} @defspecx let* ((var expr) @dots{}) body @dots{} @defspecx letrec ((var expr) @dots{}) body @dots{} @defspecx letrec* ((var expr) @dots{}) body @dots{} [R7RS base] @c EN Creates a local scope where @var{var} @dots{} are bound to the value of @var{expr} @dots{}, then evaluates @var{body} @dots{}. @var{Var}s must be symbols, and there shouldn't be duplicates. The value(s) of the last expression of @var{body} @dots{} becomes the value(s) of this form. @c JP 各変数@var{var}が@var{expr}の値に束縛されているローカルな環境を作成し、 その中で@var{body} @dots{}を評価します。@var{var}はシンボルでなければ ならず、重複があってはなりません。@var{body} @dots{}の最後の式の値が このフォームの値となります。 @c COMMON @c EN The four forms differ in terms of the scope and the order @var{expr}s are evaluated. @code{Let} evaluates @var{expr}s before (outside of) @code{let} form. The order of evaluation of @var{expr}s is undefined, and the compiler may reorder those @var{expr}s freely for optimization. @code{Let*} evaluates @var{expr}s, in the order they appears, and each @var{expr} is evaluated in the scope where @var{var}s before it are bound. @code{Letrec} evaluates @var{expr}s, in an undefined order, in the environment where @var{var}s are already bound (to an undefined value, initially). @code{letrec} is necessary to define mutually recursive local procedures. Finally, @code{letrec*} uses the same scope rule as @code{letrec}, and it evaluates @var{expr} in the order of appearance. @c JP これらの4つのフォームの違いは、@var{expr}が評価される時点のスコープと順序にあります。 @code{let}は@var{expr}を@var{let}フォームに入る前の環境において評価します。 各@var{expr}の評価される順序は不定で、コンパイラは最適化のために自由に順序を 変更することがあります。 一方、@code{let*}は@var{expr}を現れた順に、 それ以前の@var{var}が束縛された環境において評価してゆきます。 @code{letrec}は全ての@var{var}が仮想的に不定の値に束縛された環境において 各@var{expr}を(順不同で)評価します。 @code{letrec}は相互再帰的なローカル関数を定義する場合に必要です。 最後に、@code{letrec*}は@code{letrec}と同じスコープ規則を使い、 さらに@var{expr}を現れる順に評価するものです。 @c COMMON @example (define x 'top-x) (let ((x 3) (y x)) (cons x y)) @result{} (3 . top-x) (let* ((x 3) (y x)) (cons x y)) @result{} (3 . 3) (let ((cons (lambda (a b) (+ a b))) (list (lambda (a b) (cons a (cons b 0))))) (list 1 2)) @result{} (1 2 . 0) (letrec ((cons (lambda (a b) (+ a b))) (list (lambda (a b) (cons a (cons b 0))))) (list 1 2)) @result{} 3 @end example @c EN You need to use @code{letrec*} if evaluation of one @var{expr} requires the value of @var{var} that appears before the @var{expr}. In the following example, calculating the value of @var{a} and @var{b} requires the value of @var{cube}, so you need @code{letrec*}. (Note the difference from the above example, where @emph{calculating} the value of @var{list} doesn't need to take the value of @var{cons} bound in the same @code{letrec}. The value of @var{cons} isn't required until @var{list} is actually applied.) @c JP ひとつの@var{expr}を評価するために、それまでに現れた@var{var}の値を参照する 必要がある時は、@code{letrec*}を使わなければなりません。 下の例では、@var{a}と@var{b}の値を計算するために@var{cube}の値を 使っているので、@code{letrec*}にする必要があります。 (上の例との違いに注意してください。上の例では、@var{list}の値を@emph{計算する} 時には、同時に束縛されている@var{cons}の値は必要とされません。@var{cons}の値が 必要になるのは@var{list}が実際に適用される時です。) @c COMMON @example (letrec* ((cube (lambda (x) (* x x x))) (a (+ (cube 1) (cube 12))) (b (+ (cube 9) (cube 10)))) (= a b)) @result{} #t @end example @c EN This example happens to work with @code{letrec} in the current Gauche, but it is not guaranteed to keep working in future. You just should not rely on evaluation order when you use @code{letrec}. In retrospect, it would be a lot simpler if we only had @code{letrec*}. Unfortunately @code{letrec} preceded for long time in Scheme history and it's hard to remove that. Besides, @code{letrec} does have more opportunities to optimize than @code{letrec*}. @c JP この例は現在のGaucheでは@code{letrec}を使ってもたまたま動作しますが、 将来にわたって動作し続けることは保証されません。 @code{letrec}を使うなら評価順に依存しないように、プログラマが気をつけないといけません。 振り返ってみれば、@code{letrec*}だけが提供されてた方が単純だったでしょう。 生憎、Schemeの歴史の中では@code{letrec}の方がずっと前からあったので、いまさら 取り除くこともできないのです。また、@code{letrec*}に出来ない最適化が @code{letrec}だと可能になることもあります。 @c COMMON @end defspec @defmac let1 var expr body @dots{} @c EN A convenient macro when you have only one variable. Expanded as follows. @c JP 変数が一つしか無い場合の便利なマクロです。次のように展開されます。 @c COMMON @example (let ((@var{var} @var{expr})) @var{body} @dots{}) @end example @end defmac @defmac if-let1 var expr then @defmacx if-let1 var expr then else @c EN This macro simplifies the following idiom: @c JP このマクロは次のようなイディオムを簡素化します。 @c COMMON @example (let1 @var{var} @var{expr} (if @var{var} @var{then} @var{else})) @end example @end defmac @defmac rlet1 var expr body @dots{} @c EN This macro simplifies the following idiom: @c JP このマクロは次のようなイディオムを簡素化します。 @c COMMON @example (let1 @var{var} @var{expr} @var{body} @dots{} @var{var}) @end example @end defmac @defmac and-let* (binding @dots{}) body @dots{} [SRFI-2] @c EN In short, it works like @code{let*}, but returns @code{#f} immediately whenever the expression in @var{binding}s evaluates to @code{#f}. @c JP 簡単に言うと、このフォームは@code{let*}のように動作しますが、 @var{bindings}中の式が@code{#f}に評価されたらそこで評価を打ち切り @code{#f}を返します。 @c COMMON @c EN Each @var{binding} should be one of the following form: @c JP 各@var{binding}は以下のいずれかの形式でなければなりません。 @c COMMON @table @code @item (@var{variable} @var{expression}) @c EN The @var{expression} is evaluated; if it yields true value, the value is bound to @var{variable}, then proceed to the next binding. If no more bindings, evaluates @var{body} @dots{}. If @var{expression} yields @code{#f}, stops evaluation and returns @code{#f} from @code{and-let*}. @c JP @var{expression}が評価されます。それが真の値を返したら、その値が@var{variable} に束縛され、次の@var{binding}へと進みます。もう@var{binding}が無ければ @var{body} @dots{}が評価されます。もし@var{expression}が@code{#f}を返したら、 評価を打ち切り、@code{and-let*}から@code{#f}を返します。 @c COMMON @item (@var{expression}x) @c EN In this form, @var{variable} is omitted. @var{Expression} is evaluated and the result is used just to determine whether we continue or stop further evaluation. @c JP この形式では@var{variable}が省略されています。@var{Expression}が評価され、 その結果は評価を続行するか打ち切るかを判断するためにのみ使われます。 @c COMMON @item @var{bound-variable} @c EN In this form, @var{bound-variable} should be an identifier denoting a bound variable. If its value is not @code{#f}, we continue the evaluation of the clauses. @c JP この形式では@var{bound-variable}は束縛変数を示す識別子でなければなりません。 その変数の値が偽でなければ評価を続行します。 @c COMMON @end table @c EN Let's see some examples. The following code searches @var{key} from an assoc-list @var{alist} and returns its value if found. @c JP いくつか例を挙げます。次のコードは連想リスト@var{alist}から@var{key}を 探し、見つかったらその値を返します。 @c COMMON @example (and-let* ((entry (assoc key alist))) (cdr entry)) @end example @c EN If @var{arg} is a string representation of an exact integer, returns its value; otherwise, returns 0: @c JP もし@var{arg}が正確な整数の文字列表現だった場合は@var{num}を返し、そうでなければ 0を返します: @c COMMON @example (or (and-let* ((num (string->number arg)) ( (exact? num) ) ( (integer? num) )) num) 0) @end example @c EN The following is a hypothetical code that searches a certain server port number from a few possibilities (environment variable, configuration file, ...) @c JP 以下のコードはとあるサーバーのポート番号をいくつかの可能性 (環境変数、設定ファイル…)の中から探す仮想的なコードです。 @c COMMON @example (or (and-let* ((val (sys-getenv "SERVER_PORT"))) (string->number val)) (and-let* ((portfile (expand-path "~/.server_port")) ( (file-exists? portfile) ) (val (call-with-input-string portfile port->string))) (string->number val)) 8080) ; default @end example @end defmac @defmac and-let1 var test exp1 exp2 @dots{} @c EN Evaluates @var{test}, and if it isn't @code{#f}, binds @var{var} to it and evaluates @var{exp1} @var{exp2} @dots{}. Returns the result(s) of the last expression. If @var{test} evaluates to @code{#f}, returns @code{#f}. This can be easily written by @code{and-let*} or @code{if-let1} as follows. However, we've written this idiom so many times that it deserves another macro. @c JP @var{test}を評価し、それが@code{#f}でなければ@var{var}をその値に束縛して @var{exp1} @var{exp2} @dots{}を評価します。戻り値は最後の式の値です。 @var{test}が@code{#f}だった場合は単に@code{#f}を返します。 これは@code{and-let*}や@code{if-let1}を使って次のとおり書くこともできます。 しかし、このパターンを書くことがあまりに多いため、専用のマクロを用意する価値が あると判断しました。 @c COMMON @example (and-let1 var test exp1 exp2 @dots{}) @equiv{} (and-let* ([var test]) exp1 exp2 @dots{}) @equiv{} (if-let1 var test (begin exp1 exp2 @dots{}) #f) @end example @end defmac @defmac fluid-let ((var val) @dots{}) body @dots{} @c EN A macro that emulates dynamic scoped variables. @var{Var}s must be variables bound in the scope including @code{fluid-let} form. @var{Val}s are expressions. @code{Fluid-let} first evaluates @var{val}s, then evaluates @var{body} @dots{}, with binding @var{var}s to the corresponding values during the dynamic scope of @var{body} @dots{}. Note that, in multithreaded environment, the change of the value of @var{var}s are visible from all the threads. This form is provided mainly for the porting convenience. Use parameter objects instead (@pxref{Parameters}) for thread-local dynamic state. @c JP 動的スコープの変数をエミュレートするマクロです。 @var{var}は@code{fluid-let}フォームを含むスコープで定義されている 変数でなければなりません。@var{val}は式です。 @code{fluid-let}はまず@var{val}を評価し、 @var{val}を@var{var}に動的スコープで束縛して@var{body} @dots{} を評価します。 マルチスレッド環境下では、@var{var}の値の変化は全てのスレッドから見えます。 このフォームは主として他の処理系のコードを移植する際の利便性のために 追加されました。スレッドローカルな動的状態を実現するには、 パラメータオブジェクト(@ref{Parameters}参照)を 使って下さい。 @c COMMON @example (define x 0) (define (print-x) (print x)) (fluid-let ((x 1)) (print-x)) @result{} ;; prints 1 @end example @end defmac @defspec receive formals expression body @dots{} [SRFI-8] @c EN This is the way to receive multiple values. @var{Formals} can be a (maybe-improper) list of symbols. @var{Expression} is evaluated, and the returned value(s) are bound to @var{formals} like the binding of lambda formals, then @var{body} @dots{} are evaluated. @c JP この構文により、多値を受け取ることができます。 @var{formals}はシンボルのリストです。不完全なリストであっても構いません。 @var{expression}が評価され、返された値がlambda形式の引数の束縛と 同じようにして@var{formals}内の変数と束縛され、その環境下で@var{body} @dots{}が 評価されます。 @c COMMON @example (define (divrem n m) (values (quotient n m) (remainder n m))) (receive (q r) (divrem 13 4) (list q r)) @result{} (3 1) (receive all (divrem 13 4) all) @result{} (3 1) (receive (q . rest) (divrem 13 4) (list q rest)) @result{} (3 (1)) @end example @c EN See also @code{call-with-values} in @ref{Multiple values} which is the procedural equivalent of @code{receive}. You can use @code{define-values} (@pxref{Definitions}) to bind multiple values to variables simultaneously. Also @code{let-values} and @code{let*-values} below provides @code{let}-like syntax with multiple values. @c JP なお、@ref{Multiple values}の@code{call-with-values}は @code{receive}と等価な手続き的インタフェースです。 多値を複数の変数に同時に束縛するには、@code{define-values} (@ref{Definitions}参照) が使えます。 また、下の@code{let-values}と @code{let*-values}は@code{let}のような形式で多値を扱うことができます。 @c COMMON @end defspec @defmac let-values ((vars expr) @dots{}) body @dots{} [R7RS base] @c EN @var{vars} are a list of variables. @var{expr} is evaluated, and its first return value is bound to the first variable in @var{vars}, its second return value to the second variable, and so on, then @var{body} is evaluated. The scope of @var{expr}s are the outside of @code{let-values} form, like @code{let}. @c JP @var{vars} は変数のリストです。@var{expr} は評価され、最初の返り値は、 @var{vars} の最初の変数に束縛されます。二番目の返り値は、@var{vars} の 二番目の変数に束縛され、以下同様です。そのあと、@var{body} が評価されます。 @var{expr} のスコープは @code{let} と同様に、@code{let-values} の 外側になります。 @c COMMON @example (let-values (((a b) (values 1 2)) ((c d) (values 3 4))) (list a b c d)) @result{} (1 2 3 4) (let ((a 1) (b 2) (c 3) (d 4)) (let-values (((a b) (values c d)) ((c d) (values a b))) (list a b c d))) @result{} (3 4 1 2) @end example @c EN @var{vars} can be a dotted list or a single symbol, like the lambda parameters. @c JP @var{vars} lambda パラメータと同様に、ドット付リストでも、 単一のシンボルでもかまいません。 @c COMMON @example (let-values (((x . y) (values 1 2 3 4))) y) @result{} (2 3 4) (let-values ((x (values 1 2 3 4))) x) @result{} (1 2 3 4) @end example @c EN If the number of values returned by @var{expr} doesn't match what @var{vars} expects, an error is signaled. @c JP @var{expr} によって返された値の数と @var{vars} が期待する数とが一致しない 場合にはエラーになります。 @c COMMON @end defmac @defmac let*-values ((vars expr) @dots{}) body @dots{} [R7RS base] @c EN Same as @code{let-values}, but each @var{expr}'s scope includes the preceding @var{vars}. @c JP @code{let-values}と同じですが、各 @var{expr} のスコープが先行する @var{vars} を含みます。 @c COMMON @example (let ((a 1) (b 2) (c 3) (d 4)) (let*-values (((a b) (values c d)) ((c d) (values a b))) (list a b c d))) @result{} (3 4 3 4) @end example @end defmac @defmac rec var expr @defmacx rec (name . vars) expr @dots{} [SRFI-31] @c EN A macro to evaluate an expression with recursive reference. In the first form, evaluates expr while @var{var} in @var{expr} is bound to the result of @var{expr}. The second form is equivalent to the followings. @c JP 再帰的な参照のある式の評価を行うマクロです。 最初の形式は、@var{var}が@var{expr}の結果に束縛される状態で@var{expr}を 評価します。 2番目の形式は以下の形式と等価です。 @c COMMON @example (rec @var{name} (lambda @var{vars} @var{expr} @dots{})) @end example @c EN Some examples: @c JP 例: @c COMMON @example ;; constant infinite stream (rec s (cons 1 (delay s))) ;; factorial function (rec (f n) (if (zero? n) 1 (* n (f (- n 1))))) @end example @end defmac @node Grouping, Iteration, Binding constructs, Core syntax @section Grouping @c NODE 式をまとめる @defspec begin form @dots{} [R7RS base] @c EN Evaluates @var{form}s sequentially, and returns the last result(s). @c JP @var{form}を順に評価し、最後の値を返します。 @c COMMON @c EN @code{Begin} doesn't introduce new scope like @code{let}, that is, you can't place "internal define" at the beginning of @var{form}s generally. Semantically @code{begin} behaves as if @var{form}s are spliced into the surrounding context. For example, toplevel expression like the following is the same as two toplevel definitions: @c JP @code{Begin}は@code{let}のように新たなスコープを作成するわけではありません。 すなわち、一般的には@var{form} @dots{}の先頭に「内部のdefine (internal define)」を 置くことはできません。意味的には、@code{begin}はまるで@var{form} @dots{}が @code{begin}を囲むコンテクスト中に展開されているかのように振舞います。 例えば、トップレベルに次のような式があった場合、それは2つのトップレベルのdefineと 同等です。 @c COMMON @example (begin (define x 1) (define y 2)) @end example @c EN Here's a trickier example: @c JP よりトリッキーな例: @c COMMON @example (let () (begin (define x 2) (begin (define y 3) )) (+ x y)) @equiv{} (let () (define x 2) (define y 3) (+ x y)) @end example @end defspec @defmac begin0 exp0 exp1 @dots{} @c EN Evaluates @var{exp0}, @var{exp1}, @dots{}, then returns the result(s) of @var{exp0}. The name is taken from MzScheme. This is called @code{prog1} in CommonLisp. Unlike @code{begin}, this @emph{does} creates a new scope, for the @code{begin0} form is expanded as follows. @c JP @var{exp0}, @var{exp1}, @dots{} を評価し、@var{exp0}の結果を返します。 この名前はMzSchemeから取られました。これはCommonLispで @code{prog1}と呼ばれているものです。 @code{begin}と違って、これは新たなスコープを構成します。 @code{begin0}フォームは次のように展開されるからです。 @c COMMON @example (receive tmp @var{exp0} @var{exp1} @dots{} (apply values tmp)) @end example @end defmac @defmac independently exp @dots{} [SRFI-236] @c EN Evaluates @var{exp} @dots{} in an unspecified order, and returns an undefined result. This form is defined in SRFI-236. You can use @code{begin} to group multiple expressions, but @code{begin} also specifies the order of evaluation even when it's unnecessary. Using @code{independently}, you can express the intention to the readers that the order does not matter, and also gives the compiler more opportunities for optimization. As the order doesn't matter, SRFI-236 does not specify the return value of this form. Gauche returns @code{#}, but the caller shoudn't rely on it. @c JP @var{exp} @dots{}を順序を問わずに評価し、未定義値を返します。 このフォームはSRFI-236で定義されました。 複数の式を評価するのには@code{begin}が使えますが、 @code{begin}は順序も指定してしまいます。 @code{independently}は、コードを読む人に順序が関係ないことを伝え、 またコンパイラにより多くの最適化の機会を与えます。 式がどういう順で評価されるかわからないので、SRFI-236では結果の値は指定されていません。 Gaucheは@code{#}を返しますが、返り値に依存するコードは書くべきではありません。 @c COMMON @end defmac @node Iteration, Quasiquotation, Grouping, Core syntax @section Iteration @c NODE 繰り返し @defspec do ((variable init [step]) @dots{}) (test expr @dots{}) body @dots{} [R7RS base] @c EN @enumerate @item Evaluates @var{init} @dots{} and binds @var{variable} @dots{} to each result. The following steps are evaluated under the environment where @var{variables} are bound. @item Evaluate @var{test}. If it yields true, evaluates @var{expr} @dots{} and returns the result(s) of last @var{expr}. @item Otherwise, evaluates @var{body} @dots{} for side effects. @item Then evaluates @var{step} @dots{} and binds each result to a fresh @var{variable} @dots{}, and repeat from the step 2. @end enumerate The following example loops 10 times while accumulating each value of @var{i} to @var{j} and returns it. @c JP @enumerate @item @var{init} @dots{}を評価し、@var{variable} @dots{}をそれぞれの結果へと 束縛します。以降のステップは@var{variable} @dots{}が束縛された環境で評価されます。 @item @var{test}を評価します。真の値が得られたら、 @var{expr} @dots{}を順に評価し、最後の@var{expr}の結果を返り値とします。 @item そうでなければ、@var{body} @dots{}を(副作用のために)評価します。 @item それから@var{step} @dots{}を評価し、それぞれの結果へ 新たな@var{variable} @dots{}を束縛し、ステップ2から繰り返します。 @end enumerate 次の例はループを10回繰り返し、その間@var{i}の値を@var{j}へと 累積して最後に返すコードです。 @c COMMON @example (do ((i 0 (+ i 1)) (j 0 (+ i j))) ((= i 10) j) (print j)) @c EN @result{} 45 ; @r{also prints intermediate values of j} @c JP @result{} 45 ; @r{また、jの中間結果が途中で出力される} @c COMMON @end example @c EN If @var{step} is omitted, the previous value of @var{variable} is carried over. When there's no @var{expr}, the non-false value returned by @var{test} becomes the value of the @code{do} expression. @c JP @var{step}が省略された場合は、@var{variable}の元の値がそのまま持ち越されます。 @var{expr}が一つも無い場合は、@var{test}が真の値を返した時点でその値がそのまま @code{do}式の値となります。 @c COMMON @c EN Since @code{do} syntax uses many parentheses, some prefer using square brackets as well as parentheses to visually distinguish the groupings. A common way is to group each variable binding, and the test clause, by square brackets. @c JP @code{do}構文は括弧を多用するので、角括弧を併用してまとまりを視覚的に 強調するのを好む人もいます。よくある書き方は、それぞれの変数の束縛と、 テスト節全体に角括弧を使うという書き方です。 @c COMMON @example (do ([i 0 (+ i 1)] [j 0 (+ i j)]) [(= i 10) j] (print j)) @end example @c EN Note: Unlike Common Lisp (and ``for loops'' in many languages), @var{variable} is freshly bound for each iteration. The following example loops 5 times and creates a list of closures, each of which closes the variable @var{i}. When you call each closures, you can see that each of them closes different @var{i} at the time of the iteration they were created. @c JP 註:Common Lisp (や、多くの言語の``forループ'') とは違って、 繰り返しの度に新しい@var{variable}が束縛されます。 次の例では5回ループして、それぞれ@var{i}を閉じ込むクロージャのリストを 作っています。各クロージャを呼び出せば、それぞれが自身が作られた時の@var{i}を 閉じ込んでいることがわかります。 @c COMMON @example (define closures (do ([i 0 (+ i 1)] [c '() (cons (^[] i) c)]) [(= i 5) (reverse c)] )) ((car closures)) @result{} 0 ((cadr closures)) @result{} 1 @end example @end defspec @defspec let name ((var init) @dots{}) body @dots{} [R7RS base] @c EN This variation of @code{let} is called ``named let''. It creates the following procedure and binds it to @var{name}, then calls it with @var{init} @dots{}. @c JP 「名前付きlet」と呼ばれる@code{let}式のバリエーションです。 この構文は、次の手続きを作り、それを@var{name}に束縛して、 @var{init} @dots{}を引数として呼び出します。 @c COMMON @example (lambda (var @dots{}) body @dots{}) @end example @c EN This syntax itself isn't necessarily related to iteration. However, the whole point of named let is that the above lambda expression is within the scope of @var{name}---that is, you can call @var{name} recursively within @var{body}. Hence this is used very often to write a loop by recursion (thus, often the procedure is named @var{loop}, as in the following example.) @c JP この構文自体は繰り返しとは直接に関係ありませんが、 名前付きletのポイントは、上のlambda式が@var{name}のスコープ内で作られることです。 すなわち、@var{body}から@var{name}を再帰的に呼ぶことができます。したがって この構文は再帰によるループを書くのに非常に良く使われます (そのため、次の例のように作られる手続きを@var{loop}と名付けることが良く行われます)。 @c COMMON @example (let loop ([x 0] [y '()]) (if (= x 10) y (loop (+ x 1) (cons x y)))) @result{} (9 8 7 6 5 4 3 2 1 0) @end example @c EN Of course you don't need to loop with a named let; you can call @var{name} in non-tail position, pass @var{name} to other higher-order procedure, etc. Named let exists since it captures a very common pattern of local recursive procedures. Some Schemers even prefer named let to @code{do}, for the better flexibility. @c JP もちろん名前付きletは必ずループに使わなければならないということはありません。 @var{name}を非末尾再帰呼び出ししても良いですし、他の高階関数に渡しても構いません。 名前付きletがあるのは、ローカルな再帰関数を定義する際の共通するパターンをうまく とらえているためです。@code{do}よりも名前付きletを好んで使うSchemerもいます。 名前付きletの方が柔軟性が高いからです。 @c COMMON @c EN The following rewrite rule precisely explains the named let semantics. The tricky use of @code{letrec} in the expansion is to make @var{proc} visible from @var{body} @dots{} but not from @var{init} @dots{}. @c JP 以下の書き換え規則が、名前付きletのセマンティクスを正確に説明します。 @code{letrec}の使い方がちょっとひねってあるのは、@var{body}は@var{proc}の スコープに含まれるけれど@var{init}はそうではない、ということを表現するためです。 @c COMMON @example (let proc ((var init) @dots{}) body @dots{}) @equiv{} ((letrec ((proc (lambda (var @dots{}) body @dots{}))) proc) init @dots{}) @end example @end defspec @defmac dotimes ([variable] num-expr [result]) body @dots{} @defmacx dolist ([variable] list-expr [result]) body @dots{} @c EN Convenience loop syntaxes, imported from Common Lisp. They are not very Scheme-y, in a sense that these rely on some side-effects in @var{body} @dots{}. Nevertheless these capture some common pattern in day-to-day scripting. @c JP Common Lispから輸入された、簡易なループ構文です。 これらは、@var{body} @dots{}における副作用を前提としているという点で あまりSchemeっぽくありませんが、 日常のスクリプティングでよく出てくるパターンを手軽に書けます。 @c COMMON @c EN You can use @code{dotimes} to repeat @var{body} @dots{} for a number of times given by @var{num-expr}, and @code{dolist} to repeat @var{body} @dots{} while traversing a list given by @var{list-expr}. While @var{body} @dots{} is evaluated, @var{variable} is bound to the current iteration count (in @code{dotimes}), or the current element in the list (in @code{dolist}). @c JP @code{dotimes}は、@var{num-expr}で与えられる回数@var{body} @dots{}を繰り返すのに、 @code{dolist}は、@var{list-expr}で与えられるリストの各要素に対して @var{body} @dots{}を繰り返すのに使えます。@var{body} @dots{}の実行中、 @var{variable}はそれまで繰り返した回数(@code{dotimes}の場合)もしくは 現在のリスト要素(@code{dolist}の場合)に束縛されます。 @c COMMON @example (dotimes (n 5) (write n)) @result{} @r{writes "01234"} (dolist (v '(a b c d e)) (write v)) @result{} @r{writes "abcde"} @end example @c EN If you don't need to refer to @var{variable}, you can omit it. For example, the following example prints @code{year!} 10 times: @c JP @var{variable}を使う必要がなければ省略することができます。 次の例は@code{year!}を10回出力します。 @c COMMON @example (dotimes (10) (print "yeah!")) @end example @c EN If the third element (@var{result}) is given in @code{dotimes} or @code{dolist}, it is evaluated after all repetition is done, and its result becomes the result of @code{dotimes}/@code{dolist}. While @var{result} is evaluated, @var{variable} is bound to the number of repetitions (in @code{dotimes}) or @code{()} (in @code{dolist}). It is supported because Common Lisp has it. @c JP 3番めの要素@var{result}が@code{dotimes}や@code{dolist}に与えられた場合、 その式はすべての繰り返しが終わった後で評価され、 その結果が@code{dotimes}/@code{dolist}の値となります。 @var{result}は、@var{variable}が繰り返しの総回数(@code{dotimes}の場合) もしくは@code{()}(@code{dolist}の場合)に束縛された環境で評価されます。 これはCommon Lispに倣っています。 @c COMMON @c EN Note that a fresh @var{variable} is bound for each iteration, as opposed to Common Lisp where @var{variable} is mutated. So if you create a closure closing @var{variable}, it won't be overwritten by the subsequent iteration. @c JP Common Lispと違い、新たな@var{variable}が繰り返しの度に束縛されます (Common Lispでは、一つの@var{variable}が繰り返しごとに変更を受けます)。 したがって、@var{variable}を綴じ込むクロージャを作った場合でも、 繰り返しの進行で@var{variable}が上書きされることはありません。 @c COMMON @c EN If you need more than simple iteration, you can use @code{do} form, named @code{let}, or @ref{Eager comprehensions}, which provides rich way to iterate. @c JP 単純な繰り返し以上のことがしたいなら、@code{do}フォーム、名前付き@code{let}、あるいは @ref{Eager comprehensions}も参照してください。 より複雑な繰り返しを記述できます。 @c COMMON @end defmac @c @defmac do-plist ((kvar vvar) plist-expr [default]) body @dots{} @c @c EN @c A @emph{plist} is a list alternating key and values. This macro @c provides a convenient way to loop over a plist. @c @example @c ;; example of a plist, associating a => 1 and b => 2. @c (a 1 b 2) @c @end example @c @c JP @c @emph{plist}とは、キーと値が交互に現れるリストです。 @c このマクロはplistに対する繰り返しを簡単にするものです。 @c @example @c ;; plistの例。a => 1、 b => 2 という関係を示す。 @c (a 1 b 2) @c @end example @c @c COMMON @c @c EN @c The @var{plist-expr} form must evaluate to a plist. @c It evaluates @code{body} @dots{} while binding @c @var{kvar} and @var{vvar} to each key and value. @c @c JP @c @var{plist-expr}はplistを返す式です。 @c @var{kvar}と@var{vvar}にそれぞれキーと値に束縛された環境で @c @code{body} @dots{}が評価されます。 @c @c COMMON @c @example @c (doplist ((k v) '(a 1 b 2 c 3)) (print k " => " v)) @c @result{} @r{prints:} @c a => 1 @c b => 2 @c c => 3 @c @end example @c @c EN @c By default, an error is signalled if @var{plist-expr} isn't even @c (we only detect the error when we reach to the end of the list). @c If you give @var{default} argument, however, it is used as the missing @c value for the last key. @c @c JP @c デフォルトでは、@var{plist-expr}の生成するリストの要素が偶数個でなければ @c エラーが報告されます(エラーはリストを最後までループした段階で検出されます)。 @c しかし、@var{default}引数が与えられていれば、要素が奇数個の場合は@var{default}の @c 値が最後のキーに対応する値として使われます。 @c @c COMMON @c @example @c (doplist ((k v) '(a 1 b 2 c)) (print k " => " v)) @c @result{} @r{Error, after printing} a => 1 @r{and} b => 2 @c (doplist ((k v) '(a 1 b 2 c) #f) (print k " => " v)) @c @result{} @r{prints:} @c a => 1 @c b => 2 @c c => #f @c @end example @c @end defmac @defmac while expr body @dots{} @defmacx while expr @code{=>} var body @dots{} @defmacx while expr guard @code{=>} var body @dots{} @c EN @var{Var} is an identifier and @var{guard} is a procedure that takes one argument. @c JP @var{var}は識別子で@var{guard}は一つの引数をとる手続きです。 @c COMMON @c EN In the first form, @var{expr} is evaluated, and if it yields a true value, @var{body} @dots{} are evaluated. It is repeated while @var{expr} yields true value. @c JP 最初の形式ではまず@var{expr}が評価され、もしそれが真値を返したら @var{body} @dots{} が評価されます。そして@var{expr}が真値を返す 限り繰り返されます。 @c COMMON @c EN In the second form, @var{var} is bound to a result of @var{expr} in the scope of @var{body} @dots{}. @c JP 2番目の形式では、@var{body} @dots{} で有効な変数@var{var}を 作成し、@var{expr}の結果に束縛します。 @c COMMON @c EN In the third form, the value @var{expr} yields are passed to @var{guard}, and the execution of @var{body} @dots{} is repeated while @var{guard} returns a true value. @var{var} is bound to the result of @var{expr}. @c JP 最後の形式では、@var{expr} の返り値が @var{guard} に渡されこの 結果が真値である限り @var{body} @dots{} が繰り返されます。 変数 @var{var} は @var{expr} の結果に束縛されます。 @c COMMON @c EN The return value of @code{while} form itself isn't specified. @c JP @code{while} 自体の返り値は不定です。 @c COMMON @example (let ((a '(0 1 2 3 4))) (while (pair? a) (write (pop! a)))) @result{} @r{prints "01234"} (let ((a '(0 1 2 3 #f 5 6))) (while (pop! a) integer? => var (write var))) @result{} @r{prints "0123"} @end example @end defmac @defmac until expr body @dots{} @defmacx until expr guard @code{=>} var body @dots{} @c EN Like @code{while}, but the condition is reversed. That is, the first form repeats evaluation of @var{expr} and @var{body} @dots{} until @var{expr} yields true. In the second form, the result of @var{expr} is passed to @var{guard}, and the execution is repeated until it returns true. @var{Var} is bound to the result of @var{expr}. @c JP @code{while} の条件を逆にしたものです。 つまり、 最初の形式では@var{expr}が真値を返すまで @var{body} @dots{} を 繰り返します。2番目の形式では@var{expr}の結果が@var{guard} に渡され それが真値を返すまで繰り返します。 @var{Var}は@var{expr}返り値に 束縛されます。 @c COMMON @c EN (The second form without @var{guard} isn't useful in @code{until}, since @var{var} would always be bound to @code{#f}). @c JP (@var{guard} を省いた2番目の形式では@var{var}は常に@code{#f}へ 束縛されるため、あまり意味がありません。) @c COMMON @c EN The return value of @code{until} form itself isn't specified. @c JP @code{until}自体の返り値は不定です。 @c COMMON @example (let ((a '(0 1 2 3 4))) (until (null? a) (write (pop! a)))) @result{} @r{prints "01234"} (until (read-char) eof-object? => ch (write-char ch)) @result{} @r{reads from stdin and writes char until EOF is read} @end example @end defmac @c ---------------------------------------------------------------------- @node Quasiquotation, Definitions, Iteration, Core syntax @section Quasiquotation @c NODE 準クオート, 準クオート(Quasiquote) @defspec quasiquote template [R7RS base] @c EN Quasiquotation is a convenient way to build a structure that has some fixed parts and some variable parts. See the explanation below. @c JP 準クォートは固定部分と変数部分の両方を持つような構造を構成するのに便利 です。詳細は以下の説明を参照してください。 @c COMMON @end defspec @deftp {Reader Syntax} @code{`@var{template}} @lxindex ` [R7RS] @c EN The syntax @code{`x} is read as @code{(quasiquote x)}. @c JP @code{`x}は@code{(quasiquote x)}として読み込まれます。 @c COMMON @end deftp @defspec unquote datum @dots{} @defspecx unquote-splicing datum @dots{} [R7RS base] @c EN These syntaxes have meaning only when they appear in the @var{template} of quasiquoted form. R5RS says nothing about these syntaxes appear outside of quasiquote. Gauche signals an error in such case, for it usually indicates you forget quasiquote somewhere. @c JP これらの構文は準クォートされた@var{template}内にあるときにだけ意味を持ち ます。R5RSではこれらの構文が準クォートの外側で現われたときの意味に ついては何も言及していません。Gaucheではそのような場合にはエラーを通知します。 そのような@code{unquote}や@code{unquote-splicing}が現れるのは、 通常どこかで準クォートを忘れているからです。 @c COMMON @c EN R5RS only allows @code{unquote} and @code{unquote-splicing} to take a single argument; it is undefined if you have @code{(unquote)} or @code{(unquote x y)} inside quasiquoted form. R6RS allows zero or multi-arguments, and Gauche follows that. @c JP R5RSは@code{unquote}と@code{unquote-splicing}に一つだけ引数を取ることを 許しています。@code{(unquote)}や@code{(unquote x y)}のようなフォームが 準クオートの中に現れた場合の動作は定義されていません。 R6RSではこれらの場合も定義されており、Gaucheもそれに倣っています。 @c COMMON @end defspec @deftp {Reader Syntax} @code{,@var{datum}} @deftpx {Reader Syntax} @code{,@@@var{datum}} @lxindex , @lxindex ,@@ [R7RS] @c EN The syntaxes @code{,x} and @code{,@@x} are read as @code{(unquote x)} and @code{(unquote-splicing x)}, respectively. @c JP @code{,x}および@code{,@@x}は、それぞれ@code{(unquote x)}および @code{(unquote-splicing x)}として読み込まれます。 @c COMMON @end deftp @c EN @subheading Quasiquote basics @c JP @subheading 準クォートの基本 @c COMMON @c EN Suppose you want to create a list @code{(foo bar @var{x} @var{y})}, where @code{foo} and @code{bar} are symbols, and @var{x} and @var{y} are the value determined at runtime. (For the sake of explanation, let's assume we have variables @var{x} and @var{y} that provides those values.) One way to do that is to call the function @code{list} explicitly. @c JP @code{(foo bar @var{x} @var{y})}のようなリストを構成したいとしましょう。 ここでは@code{foo}および@code{bar}はシンボルで、@var{x}および@var{y}は 実行時に定まる値とします。(説明のために、変数@var{x}および@var{y}がそ れらの値を持っているものとします。) ひとつの方法は@code{list}関数を明 示的に呼ぶことです。 @c COMMON @example (let ((x 0) (y 1)) (list 'foo 'bar x y)) @result{} (foo bar 0 1) @end example @c EN You can do the same thing with quasiquote, like this: @c JP 同じことを準クォートを使うと以下のようになります。 @c COMMON @example (let ((x 0) (y 1)) `(foo bar ,x ,y)) @result{} (foo bar 0 1) @end example @c EN The difference between the two notations is that the explicit version quotes the parts that you want to insert literally into the result, while the quasiquote version @emph{unquotes} the parts that you don't want to quote. @c JP ふたつの記法の違いは、前者では結果に書いたとおりを入れ込みたいところで クォートを使い、後者ではクォートしたくないところに@emph{unquotes}を使 うことです。 @c COMMON @c EN The quasiquote version gets simpler and more readable when you have lots of static parts with scattered variable parts in your structure. @c JP ほとんどが固定部分でその中に変数部分が散在するような場合には準クォート を使った方が単純で読みやすくなります。 @c COMMON @c EN That's why quasiquote is frequently used with legacy macros, which are basically a procedure that create program fragments from variable parts provided as macro arguments. See the simple-minded @code{my-if} macro that expands to @code{cond} form: @c JP そういうわけで、旧来のマクロでは準クォートが頻繁につかわれていました。 旧来のマクロは基本的にマクロの引数として与えられた変数部分からプログラ ム断片を生成する手続だからです。簡単な@code{my-if}マクロの定義とそれが @code{cond}に展開されるようすを見てみましょう。 @c COMMON @example (define-macro (my-if test then else) `(cond (,test ,then) (else ,else))) (macroexpand '(my-if (< n 0) n (- n))) @result{} (cond ((< n 0) n) (else (- n))) @end example @c EN Note the two @code{else}s in the macro definition; one isn't unquoted, thus appears literally in the output, while another is unquoted and the corresponding macro argument is inserted in its place. @c JP マクロ定義内の2つの@code{else}に注目してください。ひとつはアンクォート されていませんので、出力にはそのまま現われます。もうひとつの方はといえ ば、こちらはアンクォートされていますので、その場所にマクロの引数が入り ます。 @c COMMON @c EN Of course you can use quasiquotes unrelated to macros. It is a general way to construct structures. Some even prefer using quasiquote to explicit construction even most of the structure is variable, for quasiquoted form can be more concise. Gauche also tries to minimize runtime allocation for quasiquoted forms, so it may potentially be more efficient; see "How static are quasiquoted forms?" below. @c JP もちろんマクロとは関係のないところでも準クォートは使えます。準クォート は構造のあるデータを構築する汎用的な方法です。ほとんどが変数部分である ような構造でも準クォートを好んで使うプログラマもいます。準クォートを使っ た方が簡潔に書けるからです。さらにGaucheでは準クォート形式に対する実行 時アロケーションができるだけ少くなるようにしていますので、準クォートを 使った方が効率がいいはずです。この点については後述の「準クォートはどの くらい静的か」を見てください。 @c COMMON @c EN @subheading Splicing @c JP @subheading スプライシング @c COMMON @c EN When @code{(unquote-splicing @var{expr})} appears in a quasiquoted form, @var{expr} must evaluate to a list, which is @emph{spliced} into the surrounding context. It's easier to see examples: @c JP @code{(unquote-splicing @var{expr})}が準クォート形式の中で使われていれ ば、@var{expr}は評価されてリストになるものでなければならず、それをとり まくコンテキストで継ぎ合わされます。例を見ると簡単にわかります。 @c COMMON @example (let ((x '(1 2 3))) `(a ,@@x b)) @result{} (a 1 2 3 b) (let ((x '(1 2 3))) `(a ,x b)) @result{} (a (1 2 3) b) (let ((x '(1 2 3))) `#(a ,@@x b)) @result{} #(a 1 2 3 b) @end example @c EN Compare the unquote version and unquote-splicing version. Splicing also works within a vector. @c JP アンクォート版とアンクォートスプライシング版を比べてください。スプライ シングはベクタに対しても機能します。 @c COMMON @c EN @subheading Multi-argument unquotes @c JP @subheading 複数の引数を取るunquote @c COMMON @c EN If @code{unquote} or @code{unquote-splicing} takes multiple arguments, they are interpreted as if each of its arguments are unquoted or unquote-spliced. @c JP @code{unquote}や@code{unquote-splicing}が複数の引数を取る場合は、 あたかも各引数がそれぞれ@code{unquote}または@code{unquote-splicing}されている かのように解釈されます。 @c COMMON @smallexample ;; This is the same result as `(,(+ 1 2) ,(+ 2 3) ,(+ 3 4)) `((unquote (+ 1 2) (+ 2 3) (+ 3 4))) @result{} (3 5 7) ;; This is the same result as ;; `(,@@(list 1 2) ,@@(list 2 3) ,@@(list 3 4)) `((unquote-splicing (list 1 2) (list 2 3) (list 3 4))) @result{} (1 2 2 3 3 4) ;; Edge cases `((unquote)) @result{} () `((unquote-splicing)) @result{} () @end smallexample @c EN It is an error for zero or multiple argument @code{unquote}/@code{unquote-splicing} forms appear which you cannot splice multiple forms into. @c JP 複数のフォームをスプライスできない位置に現れた ゼロ個もしくは複数の引数を取る@code{unquote}/@code{unquote-splicing}フォームは エラーとなります。 @c COMMON @smallexample ;; Multiple arguments unquotes are error in non-splicing context `(unquote 1 2) @result{} @r{error} `(unquote-splicing 1 2) @result{} @r{error} @end smallexample @c EN Note that the abbreviated notations @code{,x} and @code{,@@x} are only for single-argument forms. You have to write @code{unquote} or @code{unquote-splicing} explicitly for zero or multiple argument forms; thus you don't usually need to use them. These forms are supported mainly to make the nested unquoting forms such as @code{,,@@} and @code{,@@,@@}---R5RS cannot handle the case the inner unquote-splicing form expands into zero or multiple forms. @c JP 省略記法の@code{,x}と@code{,@@x}は単一引数のフォームとしてしか使えないので、 ゼロ個もしくは複数の引数を取る場合は @code{unquote}や@code{unquote-splicing}を陽に表記しなければなりません。 わざわざそんなコーディングをする必要はまず無いでしょう。 この機能は、ネストしたアンクオートしているフォーム、 @code{,,@@}や@code{,@@,@@}をサポートするためにあります。 R5RSの仕様では、これらのフォームで、内側のunquote-splicingがゼロ個もしくは複数個の フォームへと展開された場合を処理できません。 @c COMMON @c EN @subheading How static are quasiquoted forms? @c JP @subheading 準クォートはどのくらい静的か @c COMMON @c EN When quasiquoted form contains variable parts, what happens at runtime is just the same as when an explicit form is used: @code{`(,x ,y)} is evaluated exactly like @code{(list x y)}. However, Gauche tries to minimize runtime allocation when a quasiquoted form has static parts. @c JP 準クォート形式が変数部分を含む場合、実行時には、明示的な形式が使われた ときと同じことがおこります。@code{`(,x ,y)}は@code{(list x y)}のように 評価されます。しかし、Gaucheでは準クォート形式が固定部分を持つ場合には 実行時アロケーションができるだけ少くなるようにします。 @c COMMON @c EN First of all, if there's no variable parts in quasiquoted form, like @code{`(a b c)}, the entire form is allocated statically. If there is a static tail in the structure, it is also allocated statically; e.g. @code{`((,x a b) (,y c d))} works like @code{(list (cons x '(a b)) (cons y '(c d)))}. @c JP まず、@code{`(a b c)}のように準クォート形式に変数部分がない場合、全体 は静的にアロケートされます。構造の末尾が固定部分の場合にも静的にアロケー トされます。たとえば、@code{`((,x a b) (,y c d))}は@code{(list (cons x '(a b)) (cons y '(c d)))}のように機能します。 @c COMMON @c EN Furthermore, when an unquoted expression is a constant expression, Gauche embeds it into the static form. If you've defined a constant like @code{(define-constant x 3)}, then the form @code{`(,x ,(+ x 1))} is compiled as the constant @code{'(3 4)}. (See @ref{Definitions}, for the explanation of @code{define-constant} form.) @c JP さらにアンクォート式が定数式の場合,Gaucheはそれを準クォートの固定部分 に埋め込みます。たとえば、@code{(define-constant x 3)}のように定義した としましょう。この場合@code{`(,x ,(+ x 1))}は定数@code{'(3 4)}のように コンパイルされます。(@code{define-constant}形式については、 @ref{Definitions}を参照してください。) @c COMMON @c EN In general it is hard to say which part of quasiquoted form is compiled as a static datum and which part is not, so you shouldn't write a code that assumes some parts of the structure returned from quasiquote are freshly allocated. In other words, you better avoid mutating such structures. @c JP 一般的には、準クォート形式のどの部分が固定データとしてコンパイルされど の部分がされないのかを特定することは困難です。それゆえ、準クォートの返 す構造の一部が新規にアロケートされていることを前提としたコードを書いて はいけません。いいかえると、そのような構造を変更するのは避けるべきです。 @c COMMON @c ---------------------------------------------------------------------- @node Definitions, Inclusions, Quasiquotation, Core syntax @section Definitions @c NODE 定義 @defspec define variable expression @defspecx define (variable . formals) body @dots{} @defspecx define variable [R7RS+ base] @c EN This form has different meanings in the toplevel (without no local bindings) or inside a local scope. On toplevel, it defines a global binding to a symbol @var{variable}. In the first form, it globally binds a symbol @var{variable} to the value of @var{expression}, in the current module. @c JP この形式はトップレベル (ローカルな束縛が無い状態) とローカルスコープがある状態とで 別の意味を持ちます。 トップレベルでは、この形式は変数@var{variable}に対するグローバルな束縛を定義します。 最初の形式では、@var{expression}が評価され、その結果が変数@var{variable}の値となります。 @c COMMON @example (define x (+ 1 2)) x @result{} 3 (define y (lambda (a) (* a 2))) (y 8) @result{} 16 @end example @c EN If @var{variable} is already bound @emph{in the same module}, the subsequent definitions work just like assignments. @c JP @var{variable}が@emph{同じモジュールの中で}既に束縛されていた場合、 二度目以降の定義は代入と同じです。 @c COMMON @example (define x 3) (define (value-of-x) x) (value-of-x x) @result{} 3 (define x 4) (value-of-x x) @result{} 4 @end example @c EN If @var{variable} is not bound in the current module, but has an imported bindings, things get interesting but complicated. @xref{Into the Scheme-Verse}, for the details. @c JP @var{variable}が現在のモジュールでは束縛されていないけれど、 他のモジュールからインポートされた束縛があった場合、話はちょっとややこしく (おもしろく)なります。詳しくは @ref{Into the Scheme-Verse}で論じます。 @c COMMON @c EN The second form is a syntactic sugar of defining a procedure. It is equivalent to the following form. @c JP 2番目の形式は手続きを定義するための構文的な修飾で、以下の形式と同じです。 @c COMMON @example (define (@var{name} . @var{args}) @var{body} @dots{}) @equiv{} (define @var{name} (lambda @var{args} @var{body} @dots{})) @end example @c EN The third form is a shorthand of @code{(define variable (undefined))}. It is introduced in R6RS (but not a part of R7RS). You can use that form to indicate the initial value doesn't matter. @c JP 3番目の形式は@code{(define variable (undefined))}の略記です。 これはR6RSで導入されました(ただし、R7RSには入っていません)。 初期値が重要でないことを示したい場合に使えます。 @c COMMON @c EN If the form appears inside a local scope (internal define), this introduce a local binding of the variable. @c JP このフォームがローカルスコープの中に現われた場合、ローカル変数の束縛となります。 (内部define)。 @c COMMON @c EN Internal defines can appear in the beginning of body of @code{lambda} or other forms that introduces local bindings. They are equivalent to a @code{letrec*} form, as shown below. @c JP 内部defineは@code{lambda}やその他のローカル束縛を作る構文の、本体部分の先頭に置けます。 これらは、下に示すように@code{letrec*}フォームと等価です。 @c COMMON @example (lambda (a b) (define (cube x) (* x x x)) (define (square x) (* x x)) (+ (cube a) (square b))) @equiv{} (lambda (a b) (letrec* ([cube (lambda (x) (* x x x))] [square (lambda (x) (* x x))]) (+ (cube a) (square b)))) @end example @c EN Since internal defines are essentially a @code{letrec*} form, you can write mutually recursive local functions, and you can use preceding bindings introduced in the same scope to calculate the value to be defined. However, you can't use a binding that is introduced after an internal define form to calculate its value; if you do so, Gauche may not report an error immediately, but you may get strange errors later on. @c JP 内部defineは実質的に@code{letrec*}フォームなので、 相互再帰する内部関数を書けますし、また同じスコープで先に導入された定義を 使って定義される値を計算することもできます。しかし、 内部defineフォームの後に定義される値を使うことはできません。 そういったプログラムを書いてもGaucheは直ちにエラーを報告しませんが、 あとでおかしな結果が出ることがあります。 @c COMMON @example (lambda (a) (define x (* a 2)) @c EN (define y (+ x 1)) ; ok to use x to calculate y @c JP (define y (+ x 1)) ; yの値を計算するのにxを使ってよい @c COMMON (* a y)) (lambda (a) @c EN ;; You can refer to even? in odd?, since the value of even? ;; isn't used at the time odd? is defined; it is only used ;; when odd? is called. @c JP ;; odd?の中からeven?を参照するのはok。odd?が定義される時点ではeven? ;; の値は使われず、odd?が呼ばれた時に初めて使われるから。 @c COMMON (define (odd? x) (or (= x 1) (not (even? (- x 1))))) (define (even? x) (or (= x 0) (not (odd? (- x 1))))) (odd? a)) (lambda (a) @c EN ;; This is not ok, for defining y needs to use the value ;; of x. However, you may not get an error immediately. @c JP ;; これはダメ。yを定義する時点でxの値を使わないとならないので。 ;; ただし、すぐにはエラーとならないかもしれない。 @c COMMON (define y (+ x 1)) (define x (* a 2)) (* a y)) @end example @c EN Inside the body of binding constructs, internal defines must appear before any expression of the same level. The following code isn't allowed, for an expression @code{(print a)} precedes the @code{define} form. @c JP 束縛を作るフォームのボディー内で、内部defineは同じレベルにあるすべての式より前に 現れなければなりません。例えば次のコードは、@code{define}フォームの 前に式@code{(print a)}があるので不正です。 @c COMMON @example (lambda (a) (print a) (define (cube x) (* x x x)) ; error! (cube a)) @end example @c EN It is also invalid to put no expressions but internal defines inside the body of binding constructs, although Gauche don't report an error. @c JP 束縛を作るフォームのボディー中に、式を置かず内部defineだけを書いておくのも不正ですが、 Gaucheは特にエラーを出しません。 @c COMMON @c EN Note that @code{begin} (@pxref{Grouping}) doesn't introduce a new scope. @code{Define}s in the @code{begin} act as if @code{begin} and surrounding parenthesis are not there. Thus these two forms are equivalent. @c JP @code{begin}は新しいスコープを作らないことに注意してください(@ref{Grouping}参照)。 @code{begin}の中に現われる@code{define}は、あたかも@code{begin}とそれを囲む 括弧が無いかのように振舞います。すなわち、以下の2つの形式は等価です。 @c COMMON @example (let ((x 0)) (begin (define (foo y) (+ x y))) (foo 3)) @equiv{} (let ((x 0)) (define (foo y) (+ x y)) (foo 3)) @end example @end defspec @defmac define-values (var @dots{}) expr @defmacx define-values (var var1 @dots{} . var2) expr @defmacx define-values var expr [R7RS base][SRFI-244] @c EN @var{Expr} is evaluated, and each value of the result is bound to each @var{var}s. In the first form, it is an error unless @var{expr} yields the same number of values as @var{var}s. @c JP まず@var{expr}が評価され、続いて各値が@var{var}に順に束縛されます。 最初の形式では、@var{expr} @c COMMON @example (define-values (lo hi) (min&max 3 -1 15 2)) lo @result{} -1 hi @result{} 15 @end example @c EN In the second form, @var{expr} may yield as many values as @var{var} @var{var1} @dots{} or more; the excess values are made into a list and bound to @var{var2}. @c JP 二番目の形式では、@var{expr}は@var{var} @var{var1} @dots{}に対応する数か それ以上の値を生成しなければなりません。余った値はリストになって@var{var2}に 束縛されます。 @c COMMON @example (define-values (a b . c) (values 1 2 3 4)) a @result{} 1 b @result{} 2 c @result{} (3 4) @end example @c EN In the last form, all the values yielded by @var{expr} are gathered to a list and bound to @var{var}. @c JP 最後の形式では、@var{expr}の生成する全ての値がリストにまとめられ、@var{var}に 束縛されます。 @c COMMON @example (define-values qr (quotient&remainder 23 5)) qr @result{} (4 3) @end example @c EN You can use @code{define-values} wherever @code{define} is allowed; that is, you can mix @code{define-values} in internal defines. @c JP @code{define-values}は@code{define}が許されるところならどこでも使えます。 つまり、内部defineに@code{define-values}を混ぜて使えるということです。 @c COMMON @example (define (foo . args) (define-values (lo hi) (apply min&max args)) (define len (length args)) (list len lo hi)) (foo 1 4 9 3 0 7) @result{} (6 0 9) @end example @end defmac @defspec define-constant variable expression @defspecx define-constant (variable . formals) body @dots{} @c EN This form is only effective in toplevel. Like top-level @code{define}, it defines a top-level definition of @var{variable} with the value of @var{expression}, but additionally tells the compiler that (1) the binding won't change, and (2) the value of @var{expression} won't change from the one computed at the compile time. So the compiler can replace references of @var{variable} with the compile-time value of @var{expression}. An error is signaled when you use @code{set!} to change the value of @var{variable}. It is allowed to redefine @var{variable}, but a warning is printed. @c JP このフォームはトップレベルでしか使えません。 トップレベルの@code{define}と同様に、トップレベルで@var{variable}を @var{expression}の値に束縛しますが、さらに次の情報をコンパイラに伝えます: (1)その束縛は変わらない (2)@var{expression}の値はコンパイル時に計算したものと変わらない。 コンパイラは@var{variable}が参照されている箇所を コンパイル時に計算した@var{expression}の値で置き換えて構わないと考えて最適化を行います。 @var{variable}の値を@code{set!}で変更しようとするとエラーとなります。 @var{variable}を再定義することは許されますが、警告が表示されます。 @c COMMON @c EN The difference from @code{define-inline} below is that the value of @var{expression} is computed at the compile time and treated as a literal. Suppose you define @var{x} as follows: @c JP 下の@code{define-inline}との違いは、@var{expression}の値がコンパイル時に 計算され、リテラルとして扱われることです。 例えば@var{x}を次のとおり定義したとします: @c COMMON @example (define-constant x (vector 1 2 3)) @end example @c EN Then, the code @code{(list x)} is compiled to the same code as @code{(list '#(1 2 3))}. This distinction is especially important when you do AOT (ahead of time) compilation. @c JP すると、コード@code{(list x)}は@code{(list '#(1 2 3))}と同じコードにコンパイルされます。 この違いは特にAOT (ahead of time)コンパイルをする場合に重要です。 @c COMMON @c EN There's no ``internal @code{define-constant}'', since the compiler can figure out whether a local binding is mutated, and optimize code accordingly, without a help of declarations. @c JP ``内部@code{define-constant}'' にあたるものはありません。宣言が無くても コンパイラはどのローカル束縛が変更されないかを検出して最適化できるからです。 @c COMMON @end defspec @defspec define-inline variable expression @defspecx define-inline (variable . formals) body @dots{} @c EN The second form is a shorthand of @code{(define-inline variable (lambda formals body @dots{}))}. If this appears in the position of internal defines, it is the same as internal defines. If it appears in the toplevel, it defines an @emph{inlinable} binding. An inlinable binding promises the compiler that the binding won't change, but unlike constant bindings introduced by @code{define-constant}, the actual value of @var{expression} may be computed at runtime. Hence the compiler cannot simply replace the references of @var{variable} with the compile-time value of @var{expression}. However, if the compiler can determine that the value of @var{expression} is to be a procedure, it may inline the procedure where it is invoked. @c JP 2番目の形式は@code{(define-inline variable (lambda formals body @dots{}))}の略記です。 このフォームが内部defineの位置に現れた場合は、内部defineと全く同じです。 このフォームがトップレベルに現れた場合、それは@emph{インライン可能な}束縛をつくります。 インライン可能な束縛とは、コンパイラに対してその束縛が変化しないことを約束するものです。 ただし@code{define-constant}で導入される定数束縛と違って、@var{expression}の値が コンパイル時に計算可能とは限りません。 従って、コンパイラは@code{define-constant}で定義される束縛でやっている、 @code{variable}の参照を無条件で@var{expression}のコンパイル時値に置き換えることは できません。 しかし、コンパイラが@var{expression}の値が手続きになることを決定できれば、 その手続きが呼び出される箇所に手続きの中身をインライン展開することができます。 @c COMMON @c EN In the example below, the body of @code{dot3} is inlined where @code{dot3} is called. Furthermore, since the second argument of @code{dot3} is a constant vector, you can see @code{vector-ref} on it is computed at compile time (e.g. @code{CONST -1.0} etc.) @c JP 下の例では、@code{dot3}の本体が@code{dot3}を呼び出している箇所にインライン展開されています。 さらに、@code{dot3}の呼び出しの第2引数が定数ベクタのため、それに対する@code{vector-ref}が コンパイル時に計算されていることがわかります (@code{CONST -1.0}など)。 @c COMMON @example gosh> (define-inline (dot3 a b) (+ (* (vector-ref a 0) (vector-ref b 0)) (* (vector-ref a 1) (vector-ref b 1)) (* (vector-ref a 2) (vector-ref b 2)))) dot3 gosh> (disasm (^[] (dot3 x '#(-1.0 -2.0 -3.0)))) CLOSURE # === main_code (name=#f, code=0x28524e0, size=26, const=4 stack=6): signatureInfo: ((#f)) 0 GREF-PUSH #; x 2 LOCAL-ENV(1) ; (dot3 x (quote #(-1.0 -2.0 -3.0))) 3 LREF0 ; a 4 VEC-REFI(0) ; (vector-ref a 0) 5 PUSH 6 CONST -1.0 8 NUMMUL2 ; (* (vector-ref a 0) (vector-ref b 0)) 9 PUSH 10 LREF0 ; a 11 VEC-REFI(1) ; (vector-ref a 1) 12 PUSH 13 CONST -2.0 15 NUMMUL2 ; (* (vector-ref a 1) (vector-ref b 1)) 16 NUMADD2 ; (+ (* (vector-ref a 0) (vector-ref b 0)) 17 PUSH 18 LREF0 ; a 19 VEC-REFI(2) ; (vector-ref a 2) 20 PUSH 21 CONST -3.0 23 NUMMUL2 ; (* (vector-ref a 2) (vector-ref b 2)) 24 NUMADD2 ; (+ (* (vector-ref a 0) (vector-ref b 0)) 25 RET @end example @c EN As an extreme case, if both arguments are compile-time constant, @code{dot3} is completely computed at compile time: @c JP 最も極端なケースとして、両方の引数がコンパイル時定数であれば、 @code{dot3}の呼び出し自体がコンパイル時に計算されます。 @c COMMON @example gosh> (disasm (^[] (dot3 '#(1 2 3) '#(4 5 6)))) CLOSURE # === main_code (name=#f, code=0x2a2b8e0, size=2, const=0 stack=0): signatureInfo: ((#f)) 0 CONSTI(32) 1 RET @end example @c EN The same inlining behavior may be achieved by making @code{dot3} a macro, but if you use @code{define-inline}, @code{dot3} can be used as procedures when needed: @c JP インライン展開と同様の効果は@code{dot3}をマクロにすることでも得られますが、 @code{define-inline}を使っておくと@code{dot3}を通常の手続きとしても使うことができます。 @c COMMON @example (map dot3 list-of-vectors1 list-of-vectors2) @end example @c EN If @code{dot3} is a macro you can't pass it as a higher-order procedure. @c JP @code{dot3}がマクロだと、上のように関数引数として@code{map}に渡すことはできないでしょう。 @c COMMON @c EN The inline expansion pass is run top-to-bottom. Inlinable procedure must be defined before used in order to be inlined. @c JP インライン展開パスはソースの上から下へと進みます。インライン展開されるためには、 呼び出される前にそれが定義されていなければなりません。 @c COMMON @c EN If you redefine an inlinable binding, Gauche warns you, since the redefinition won't affect already inlined call sites. So it should be used with care---either use it internal to the module, or use it for procedures that won't change in future. Inlining is effective for performance-critical parts. If a procedure is called sparingly, there's no point to define it inlinable. @c JP インライン可能な束縛が再定義されるとGaucheは警告を出します。 その再定義は既にインライン展開された呼び出し箇所には影響を及ぼさないからです。 なのでこれは注意して使わなければなりません。モジュール内だけで使うか、 あるいは将来に渡って変わらなさそうな手続きに使うか。 インライン展開は性能に重大な影響を与える場所では効果的ですが、 滅多に使われない手続きをインライン可能に定義する意味はありません。 @c COMMON @end defspec @defspec define-in-module module variable expression @defspecx define-in-module module (variable . formals) body @dots{} @c EN This form must appear in the toplevel. It creates a global binding of @var{variable} in @var{module}, which must be either a symbol of the module name or a module object. If @var{module} is a symbol, the named module must exist. @var{Expression} is evaluated in the current module. The second form is merely a syntactic sugar of: @c JP この形式はトップレベルでしか使えません。 @var{variable}のグローバルな束縛を@var{module}中に作成します。 @var{module}はモジュール名を表すシンボルか、モジュールオブジェクトで なければなりません。@var{module}がシンボルの場合、その名前を持つ モジュールが既に存在している必要があります。 @var{expression}は現在のモジュール中で評価されます。 2番目の形式は次の形式の構文的修飾です。 @c COMMON @example (define-in-module module variable (lambda formals body @dots{})) @end example @end defspec @c EN Note: to find out if a symbol has definition (global binding) in the current module, you can use @code{module-binds?} (@pxref{Module introspection}). @c JP 註: シンボルが現在のモジュール中で定義されているか(グローバルな束縛を持つか) を調べるには、@code{module-binds?}が使えます (@ref{Module introspection}参照)。 @c COMMON @menu * Into the Scheme-Verse:: @end menu @node Into the Scheme-Verse, , Definitions, Definitions @subsection Into the Scheme-Verse @c NODE Scheme多世界へようこそ @c EN @subsubheading Multiple toplevels are multiple scopes @c JP @subsubheading 複数のトップレベルと複数のスコープ @c COMMON @c EN Once upon a time, the Scheme world was simple. We had one single global space we called the toplevel. Toplevel definitions can be understood as side-effects to this global space; if the name hasn't been exist there yet, create a new binding, otherwise, overwrite existing one. @c JP 昔、Schemeの世界は単純でした。トップレベルと呼ばれる単一のグローバルな空間があり、 トップレベル定義はその空間への副作用と考えることが出来ました。名前がそこに まだなければ新たに作り、既にあったなら書き換えます。 @c COMMON @c EN The problem was that it was hard to scale, thus many implementations introduced their own module systems. One of the main agenda of R6RS was to have a module system (which is called ``library'' in RnRS) consistent with the design of Scheme. Especially, since Scheme's hygienic macro system captures lexical scope, it is desirable that it interacts with the module system in the same way. @c JP ただ、その単純なモデルはスケールしなかったので、 実装ごとに色々なモジュールシステムが試されました。R6RSの重要な目標のひとつは、 Schemeの設計と一貫性のあるモジュールシステム (RnRSでは「ライブラリ」と呼ばれることになります) を決めることでした。 特に、Schemeの衛生的マクロシステムはレキシカルスコープを捕捉するものでしたから、 モジュールシステムもマクロから見て同じように扱えることが望まれました。 @c COMMON @c EN In modern Scheme, ``toplevel'' of each module creates its own lexical scope, and the definitions are understood in @code{letrec*} semantics. Hence, macro systems can consistently treat identifiers as a name associated with a scope. @c JP 現代のSchemeでは、「トップレベル」、あるいは各モジュールは自分のレキシカルスコープを 持っていて、そこでの定義は@code{letrec*}セマンティクスで理解できる、とされます。 つまり、マクロシステムは識別子を常に「スコープと関連付けられた名前」として扱えます。 @c COMMON @c EN Suppose you see these toplevel definitions: @c JP 次のようなトップレベル定義があるとします。 @c COMMON @example (define (odd? n) (if (zero? x) #f (even? (- n 1)))) (define (even? n) (if (zero? x) #t (odd? (- n 1)))) @end example @c EN The first appearance of @code{even?} in the first line is understood as the one defined in the second line. It becomes apparent when we compare it with internal defines: @c JP 最初の行に現れる@code{even?}は、次の行で定義される名前だとみなされます。 これは内部defineと比べてみるとはっきりするでしょう。 @c COMMON @example (let ((even? error)) (define (odd? n) (if (zero? x) #f (even? (- n 1)))) (define (even? n) (if (zero? x) #t (odd? (- n 1)))) ...) @end example @c EN The @code{even?} in the definition of @code{odd?} refers to the one defined in the next line, never to the one bound by @code{let}. @c JP @code{odd?}の定義中に現れる@code{even?}は、@code{let}が導入する束縛ではなく、 次の行で定義される@code{even?}を参照します。 @c COMMON @c EN So far, so good. @c JP ここまではいいですね。 @c COMMON @c EN Now, consider the following toplevel code: @c JP では、次のコードを考えてみてください。 @c COMMON @example ;; Invalid in RnRS, n >= 6 (import (scheme base) (scheme write)) (define orig-error error) (define (error . args) (write args) (newline) (apply orig-error args)) @end example @c EN The intention is to save the @emph{original} value of @code{error}, which is imported from @code{(scheme base)}, into a variable @code{orig-error}, then redefine @code{error} to add logging feature. This technique was popular in pre-R6RS Scheme. @c JP コードの意図は、@code{(scheme base)}からインポートされた @code{error}の@emph{元の}値を変数@code{orig-error}にセーブしておいて、 @code{error}を再定義してログを出す機能を仕込むというものです。 このテクニックはR6RSより前のSchemeではよく見られました。 @c COMMON @c EN However, with our new toplevel-as-a-scope Scheme, the @code{error} in @code{(define orig-error error)} @emph{must} refer to the one defined in the same scope, which is the new definition below; otherwise lexical scoping gets broken. The value of inner @code{error} hasn't been calculated when @code{orig-error}'s value is calculated, so the above form is an invalid program in terms of RnRS. @c JP でも、トップレベルはスコープであるとした最近のSchemeでは、 @code{(define orig-error error)}における@code{error}は 同じスコープで定義されるもの、つまりその下で定義される@code{error}を参照しなければ なりません。でないとレキシカルスコープの規則が崩れてしまいます。 とはいえ内側の@code{error}の値は@code{orig-error}の初期値を計算する時点では まだ計算されていないので、上のコードはRnRS的には無効なコードということになります。 @c COMMON @c EN In fact, to avoid confusion, R6RS prohibits defining a toplevel variable that conflicts with the imported name (in R7RS the behavior of such program is undefined). In the example above, the name @code{error} is imported from @code{(scheme base)} and also defined in the toplevel, hence it's a violation. @c JP 実際、混乱を避けるために、R6RSではインポートした名前とぶつかる名前をトップレベルで 定義することを禁止しています (R7RSでは未定義動作になっています)。 上の例では、@code{error}は@code{(scheme base)}から既にインポートされているので、 トップレベルで再定義するのは文法違反となります。 @c COMMON @c EN The modern way of such augumentation is to use renaming import: @c JP 既存の手続きに機能を付け加える、現代風のやり方は、インポート時にリネームすることです。 @c COMMON @example (import (except (scheme base) error) (rename (scheme base) (error r7rs:error)) (scheme write)) (define (error . args) (write args) (newline) (apply r7rs:error args)) @end example @c EN @subsubheading Gauche's take @c JP @subsubheading Gaucheの選択 @c COMMON @c EN Gauche's module system predates R6RS and R7RS, and it regards a module as a first-class entity and supports class-like inheritance. It is upper-compatible to R7RS libraries, but we take freedom in interpreting R7RS undefined behaviors. @c JP GaucheのモジュールシステムはR6RS/R7RS以前からありました。 モジュールは第一級のオブジェクトで、クラスのような継承関係も持てます。 R7RSのライブラリの上位互換ですが、R7RSの未定義動作の部分については 拡張解釈をしています。 @c COMMON @c EN First, you can define toplevel variables that conflict with imported or inherited bindings. The new definition simply shadows the old one. @c JP まず、インポートしたり継承している名前と同名のトップレベル変数を定義できます。 新たな定義は前の定義を単にシャドウします。 @c COMMON @c EN Second, if multiple toplevel forms are processed at once e.g. it is enclosed in @code{begin} or the file is read by @code{include}, we treat them in one scope. That is, if the above @code{orig-error} example is read by @code{include}, the first @code{error} refers to the to-be-defined @code{error} below. Since the value of @code{error} hasn't been calculated by the time it's used, you'll get the following error: @c JP 次に、複数のトップレベルフォームが@code{begin}に包まれたり @code{include}経由で読まれるなどした場合、それらはひとつのスコープにあるものとして 処理されます。上の@code{orig-error}の例が@code{include}で読まれたとすると、 最初の@code{error}はその下で定義されるはずの@code{error}を参照することになります。 そのスコープの@code{error}の値は、@code{orig-error}の初期値を計算する時点では 計算されていないので、次のエラーが投げられます: @c COMMON @example *** ERROR: uninitialized variable: error @end example @c EN Third, Gauche compiles and executes each individual toplevel forms (the forms that's not enclosed in other S-expressions). It is the same as REPL semantics. If each form of @code{orig-error} example appears individually on the toplevel, the @code{(define orig-error error)} line actually refers to the R7RS @code{error} and assign it to @code{orig-error}, since @emph{we don't know yet if @code{error} will be defined in the same scope}. @c JP 一方、Gaucheは他のS式で囲まれていないトップレベルフォームは、ひとつひとつ 逐次的に処理します。つまりREPLと同じセマンティクスです。 @code{orig-error}の例がそのまま読み込まれた場合、@code{(define orig-error error)} の@code{error}はR7RSの@code{error}を参照し、その値が@code{orig-error}に 束縛されます。なぜなら@code{(define orig-error error)}を見た時点では、 次に@code{error}が再定義されるかどうかはまだわからないからです。 @c COMMON @c EN The third rule is necessary to support REPL semantics, but note that the result would differ when the same file is @code{include}d. If you can, avoid writing such ambiguous code. @c JP 最後の動作はREPLをサポートするのに必要な動作ですが、 同じコードを@code{include}した場合に結果が変わってくることに気をつけてください。 こういった曖昧性のあるコードを書くのを避けることが一番です。 @c COMMON @c EN Note: The second behavior is clarified in release 0.9.9 for the better compatibility with R7RS. Before that, the behavior of such case is undefined, but some code might have expected that it works in REPL semantics (the third rule). @c JP 註:トップレベルフォームが@code{begin}で囲まれた場合の動作は、 R7RSとの互換性を高めるために、0.9.9で明確化されました。 それ以前のバージョンでは上の例の動作は未定義でしたが、 REPLセマンティクスで動くことを期待していたコードはあるかもしれません。 @c COMMON @c EN In order to support the transition, if you set an environment variable @code{GAUCHE_LEGACY_DEFINE}, Gauche treats definitions in the same way as 0.9.8 and before. Note that if you do that, you may see Gauche can't include some valid R7RS code that has multiple libraries in one file. @c JP 移行をスムースにするために、環境変数@code{GAUCHE_LEGACY_DEFINE}が定義されている 場合は、Gaucheはトップレベル定義の評価を0.9.8以前と同じにします。 その場合、複数のライブラリが1ファイルで定義されている R7RSとして有効なコードをincludeできない場合があります。 @c COMMON @c ---------------------------------------------------------------------- @node Inclusions, Feature conditional, Definitions, Core syntax @section Inclusions @c NODE インクルード @defspec include filename @dots{} @defspecx include-ci filename @dots{} [R7RS base] @c EN Reads @var{filename} @dots{} at compile-time, and insert their contents as if the forms are placed in the includer's source file, surrounded by @code{begin}. The @code{include} form reads files as is, while @code{include-ci} reads files in case-insensitive way, as if @code{#!fold-case} is specified in the beginning of the file (@pxref{Case-sensitivity}). @c JP @var{filename} @dots{}で指定されるファイルをコンパイル時に読み、 その内容が@code{begin}で囲まれてインクルードフォームの位置に替わりに 置かれているかのように解釈します。 @code{include}フォームはファイルの内容をそのまま読みますが、 @code{include-ci}フォームは、あたかもファイル先頭に@code{#!fold-case}が 指定されたかのように、シンボルの大文字小文字を区別しないモードで読みます (@ref{Case-sensitivity}参照)。 @c COMMON @c EN The coding magic comment in each file is honored while reading that file (@pxref{Multibyte scripts}). @c JP 読み込まれるファイルに文字エンコーディングを指定するコメントがあればそれは そのファイルを読んでいる間有効になります(@ref{Multibyte scripts}参照)。 @c COMMON @c EN If @var{filename} is absolute, the file is just searched. If it is relative, the file is first searched relative to the file containing the @code{include} form, then the directories in @code{*load-path*} are tried. @c JP @var{filename}が絶対パスならば、そのパスに正確に合致するファイルが探されます。 相対パスなら、まず@code{include}フォームが 置かれていたファイルからの相対で探され、見つからなければ @code{*load-path*}にあるディレクトリからの相対パスが順に試されます。 @c COMMON @c EN Example: Suppose a file @file{a.scm} contains the following code: @c JP 例: ファイル@file{a.scm}には次のコードが書かれているとします。 @c COMMON @example (define x 0) (define y 1) @end example @c EN You can include this file into another source, like this: @c JP このファイルを別ソースファイルからインクルードすることができます: @c COMMON @example (define (foo) (include "a.scm") (list x y)) @end example @c EN It works as if the source is written as follows: @c JP この場合、元のソースファイルはあたかも次のように書かれていたかのように解釈されます。 @c COMMON @example (define (foo) (begin (define x 0) (define y 1)) (list x y)) @end example @c EN (Note: In version 0.9.4, @code{include} behaved differently when pathname begins with either @code{./} or @code{../}---in which case the file is searched relative to the current working directory of the compiler. It is rather an artifact of @code{include} sharing file search routine with @code{load}. But unlike @code{load}, which is a run-time operation, using relative path to the current directory won't make much sense for @code{include}, so we changed the behavior in 0.9.5.) @c JP (註: バージョン0.9.4では、@code{include}は渡されたパス名が @code{./}か@code{../}で始まっていた場合は特別な動作をしていました。 コンパイラのカレントディレクトリからの相対でファイルを探していたのです。 これは意図した動作というより、@code{load}とファイル探索ルーチンを共有していた ために生じた仕様でした。しかし@code{load}が常に実行時の動作であるのに対し、 @code{include}でカレントディレクトリからの相対パスを考える意味はほとんどありません。 そこで0.9.5では仕様を変更しました。) @c COMMON @end defspec @c EN Gauche has other means to incorporate source code from another files. Here's the comparison. @c JP Gaucheには、他のファイルからソースを読んでくる方法がいくつかあります。 以下にインクルードとの比較を説明します。 @c COMMON @table @asis @c EN @item @code{require} (@code{use} and @code{extend} calls @code{require} internally) @c JP @item @code{require} (@code{use}と@code{extend}も内部で@code{require}を呼んでいます) @c COMMON @itemize @item @c EN Both @code{require} and @code{include} work at compile-time. @c JP @code{require}も@code{include}もコンパイル時に解釈されます。 @c COMMON @item @c EN @code{Require} works only in toplevel context, while @code{include} can be anywhere. @c JP @code{require}はトップレベルでのみ動作します。 それに対し、@code{include}はどこにでも置けます。 @c COMMON @item @c EN @code{Require} reads the file only once (second and later @code{require} on the same file becomes no-op), while @code{include} reads the file every place it appears. @c JP @code{require}は ファイルを一度だけ読みます(つまり、2度め以降の同じファイルに対する@code{require}は 単なる無動作(no-op)になります)。これに対し、@code{include}は現れる場所ごとに ファイルを読み込みます。 @c COMMON @item @c EN The file is searched from @code{*load-path*}. The location of the file @code{require} form appears doesn't matter. (You can add directories relative to the requiring file using the @code{:relative} flag in @code{add-load-path}, though). @c JP ファイルは@code{*load-path*}から探され、@code{require}フォームが 使われたファイルの位置は関係ありません (但し、@code{add-load-path}の @code{:relative}フラグを使うことで、 @code{require}フォームを使っているファイルの位置をロードパスに加えることはできます。) @c COMMON @item @c EN Even if the current module is changed by @code{select-module} inside the required file, it is only effective while the required file is read. On the other hand, @code{include} inserts any S-expressions in the included file to the place @code{include} appears, so the effect of @code{select-module} persists after @code{include} form (Note: Encoding magic comment and @code{#!fold-case}/@code{#!no-fold-case} are dealt with by the reader, so those effect is contained in the file even with @code{include}). @c JP @code{require}されたファイル中でカレントモジュールが @code{select-module}で変更されたとしても、その有効範囲はそのファイル内に留まります。 一方@code{include}は、@code{include}フォームが出現した場所にS式が 挿入されたように解釈されるので、@code{select-module}の効果は それが挿入された箇所から@code{include}しているファイルの最後までということになります。 (文字エンコーディング指定コメントおよび、@code{#!fold-case}/@code{#!no-fold-case} による大文字小文字指定はリーダによって処理されるので、 効果は@code{include}されるファイルの中に留まります。) @c COMMON @item @c EN It is forbidden to the file loaded by @code{require} to insert a toplevel binding without specifying a module. In other words, the file you require should generally use @code{define-module}, @code{select-module} or @code{define-library}. @xref{Require and provide}, for further discussion. On the other hand, @code{include} has no such restrictions. @c JP @code{require}からロードするファイルが、モジュールを指定せずにトップレベル 束縛を挿入することは禁じられています。別の言い方をすれば、 @code{require}するファイルは一般的に@code{define-module}や@code{select-module}、 あるいは@code{define-library}を使う必要があるということです。 詳しい議論は@ref{Require and provide}を参照してください。 一方で、@code{include}にはそういった制限はありません。 @c COMMON @end itemize @item @code{load} @itemize @item @c EN Works at runtime, while @code{include} works at compile-time. @c JP @code{include}がコンパイル時に解釈されるのに対し、こちらは実行時に解釈されます。 @c COMMON @item @c EN Works only in toplevel context, while @code{include} can be anywhere. @c JP トップレベルでのみ動作します。それに対し、@code{include}はどこにでも置けます。 @c COMMON @item @c EN The file is searched from @code{*load-path*}, except when the file begins with @code{./} or @code{../}, in which case it is first tried relative to the current directory before being searched from @code{*load-path*}. @c JP ファイルは@code{*load-path*}から探されます。 但しファイルが@code{./}か@code{../}で始まっていた場合は、 まずカレントディレクトリ相対で探され、それから@code{*load-path*}が探されます。 @c COMMON @item @c EN As the case with @code{require}, change of the current module won't persist after @code{load}. @c JP @code{require}と同様、ロードされるファイル中でカレントモジュールを変えても、 その効果は@code{load}終了時までです。 @c COMMON @end itemize @end table @c EN Usually, @code{require} (or @code{use} and @code{extend}) are better way to incorporate sources in other files. The @code{include} form is mainly for the tricks that can't be achieved with @code{require}. For example, you have a third-party R5RS code and you want to wrap it with Gauche module system. Using @code{include}, you place the following small source file along the third-party code, and you can load the code with @code{(use third-party-module)} without changing the original code at all. @c JP 通常、他のファイルに書かれたソースファイルを取り込むのに適した方法は @code{require} (もしくは@code{use}や@code{extend}) です。 @code{include}フォームは、@code{require}では実現が難しいトリックのために使います。 例えば、第三者がR5RS向けに書いたコードを、Gaucheのモジュールシステムでラップしたい場合、 @code{include}を使う 次のような内容の小さなファイルをそのコードのファイルと同じディレクトリに置いておけば、 第三者のコードを一切変えることなく、@code{(use third-party-module)} で コードをロードできます。 @c COMMON @example (define-module third-party-module (export proc ...) (include "third-party-source.scm")) @end example @c ---------------------------------------------------------------------- @node Feature conditional, Modules, Inclusions, Core syntax @section Feature conditional @c NODE 機能条件式 @c EN @subheading The @code{cond-expand} macro @c JP @subheading @code{cond-expand}マクロ @c COMMON @c EN Sometimes you need to have a different piece of code depending on available features provided by the implementation and/or platform. For example, you may want to switch behavior depending on whether networking is available, or to embed an implementation specific procedures in otherwise-portable code. @c JP しばしば、実装やプラットフォームがどういった機能を提供しているかに 応じてコードを切り替えたいことがあります。例えば、ネットワークが使えるか どうかで振る舞いを変えるとか、ほぼポータブルなコードの一部だけに 特定の実装に依存するコードを入れたいとかいう場合です。 @c COMMON @c EN In C, you use preprocessor directives such as @code{#ifdef}. In Common Lisp, you use reader macro @code{#+} and @code{#-}. In Scheme, you have @code{cond-expand}: @c JP C言語なら、@code{#ifdef}のようなプリプロセッサディレクティブを、 Common Lispなら、@code{#+}と@code{#-}のようなリーダマクロを使うところです。 Schemeでは、こういう時には@code{cond-expand}を使います。 @c COMMON @defmac cond-expand (feature-requirement command-or-definition @dots{}) @dots{} [R7RS base] @c EN This macro expands to @var{command-or-definition} @dots{} if @var{feature-requirement} is supported by the current platform. @var{feature-requirement} must be in the following syntax: @c JP プラットフォームが@var{feature-requirement}に示される機能をサポートしていれば、 このマクロは@var{command-or-definition} @dots{} へと展開されます。 @var{feature-requirement} は以下のような構文でなければなりません。 @c COMMON @example @var{feature-requirement} : @var{feature-identifier} | (and @var{feature-requirement} @dots{}) | (or @var{feature-requirement} @dots{}) | (not @var{feature-requirement}) | (library @var{library-name}) @end example @c EN The macro tests each @var{feature-requirement} in order, and if one is satisfied, the macro itself expands to the corresponding @var{command-or-definition} @dots{}. @c JP このマクロは @var{feature-requirement} を順にテストし、そのひとつが 満たされたら、対応する @var{command-or-definition} @dots{} に展開されます。 @c COMMON @c EN The last clause may have @code{else} in the position of @var{feature-requirement}, to make the clause expanded if none of the previous feature requirement is fulfilled. @c JP 最後の節の@var{feature-requirement}の部分にはシンボル@code{else}を 置くこともできます。他の節の@var{feature-requirement}が満たされなかった場合に その節が展開されます。 @c COMMON @c EN If there's neither a satisfying clause nor @code{else} clause, @code{cond-expand} form throws an error. It is to detect the case early that the platform doesn't have required features. If the feature you're testing is optional, that is, your program works without the feature as well, add empty @code{else} clause as follows. @c JP 条件を満たす節も@code{else}節も無かった場合、@code{cond-expand}は エラーを通知します。この仕様は、 必要な機能を欠いている実行環境を早めに検出するためです。 もしチェックする機能がオプショナル、つまりそれが無くてもプログラムの実行自体は 可能であるというものであるなら、最後に空の@code{else}節を忘れないようにしてください。 @c COMMON @example (cond-expand [feature expr] ; some optional feature [else]) @end example @c EN @var{feature-identifier} is a symbol that indicates a feature. If such a feature is supported in the current platform, it satisfies the @var{feature-requirement}. You can do boolean combination of @var{feature-requirement}s to compose more complex conditions. @c JP @var{feature-identifier} は機能を示すシンボルです。その機能が現在のプラットフォームで サポートされているなら、それは、@var{feature-requirement} を満たします。 より複雑な条件を構成するために、@var{feature-requirement} のブール代数による 組み合わせを用いることが出来ます。 @c COMMON @c EN The form @code{(library @var{library-name})} is added in R7RS, and it is fulfilled when the named library is available. For the @var{library-name}, you can use both R7RS library name (e.g. @code{(srfi 13)}) and traditional Gauche module name (e.g. @code{srfi.13}). @c JP @code{(library @var{library-name})}という形式はR7RSで追加されたもので、 指定されるライブラリが使える場合に条件が満たされます。 @var{library-name}は、R7RS形式 (例: @code{(srfi 13)}) も伝統的なGaucheのモジュール名 (例: @code{srfi.13}) も使えます。 @c COMMON @c EN Here's a typical example: Suppose you want to have implementation-specific part for Gauche, Chicken Scheme and ChibiScheme. Most modern Scheme implementations defines a feature-identifier to identify itself. You can write the conditional part as follows: @c JP 例えば、Gauche、Chicken Scheme、ChibiSchemeに依存するコードを 入れたいとしましょう。現代の多くのScheme実装は、自分自身を示す feature-identifierを定義しているので、条件付きのコードは次のとおり書けます。 @c COMMON @example (cond-expand [gauche (gauche-specific-code)] [(or chicken chibi) (chicken-chibi-specific-code)] [else (fallback-code)] ) @end example @c EN It is important that the conditions of @code{cond-expand} is purely examined at the macro-expansion time, and unfulfilled clauses are discarded. Thus, for example, you can include macro calls or language extensions that may not be recognized on some implementations. You can also conditionally define global bindings. @c JP @code{cond-expand}の条件はマクロ展開時に全て処理され、 不採用だった節のコードは捨てられる、という事実は重要です。 このおかげで、例えば実装によって認識されないマクロ呼び出しや言語拡張を @var{command-or-definition}に含めることができます。 また、グローバルな束縛を条件によって定義したりしなかったりすることができます。 @c COMMON @c EN Compare that to @code{cond}, which examines conditions at runtime. If you include unsupported macro call in one of the conditions, it may raise an error at macro expansion time, even if that clause will never be executed on the platform. Also, it is not possible to conditionally define global bindings using @code{cond}. @c JP これを@code{cond}と比較してみましょう。@code{cond}は条件を実行時に調べます。 もし条件節の中に、あるプラットフォームではサポートされないマクロ呼び出しを 書いた場合、たとえその節が現実には決して実行されないものであるとしても、 マクロ展開時にエラーになってしまうかもしれません。 また、@code{cond}を使って条件的にグローバルな束縛を定義することはできません。 @c COMMON @c EN There's a caveat, though. Suppose you want to save the result of macro expansion, and run the expanded result later on other platforms. The result code is based on the features of the platform the macro expansion takes place, which may not agree with the features of the platform the code will run. (This issue always arises in cross-compiling situation in general.) @c Gauche has @emph{ahead-of-time compilation} feature, which is only @c used internally now, but will eventually be made for public use. @c JP ただし、マクロ展開した結果をどうにかして保存しておいて、 別のプラットフォームでそれを走らせる、ということをする場合は注意が必要です。 条件選択はマクロ展開をするプラットフォームの機能に応じて行われ、 それはコードを実行するプラットフォームの機能とは一致しないかもしれません (これはもちろん、クロスコンパイルで常に問題となることです。) @c COMMON @c EN NB: When @code{cond-expand} was defined as SRFI-0, there was no standard way to name Scheme libraries. So SRFI-0 suggested to use @code{srfi-N} as feature identifier to check the support of a specific srfi. @b{We deprecate this usage}. It should be replaced with @code{(library srfi.N)}. @xref{Testing availability of SRFIs}, for the details. As of 0.9.13, a warning is issued when @code{srfi-N} feature identifier is used in @code{cond-expand} if the environment variable @code{GAUCHE_WARN_SRFI_FEATURE_ID} is set. In future versions the warning will be default; we recommend to set this environment variable to detect code to update. @c JP 註: @code{cond-expand}がSRFI-0として定義された時には、 Schemeライブラリの命名法の標準が決まっていませんでした。 SRFI-0のドキュメントでは@code{srfi-N}という形式の機能識別子で特定のsrfiが サポートされているかどうかを検査するように推奨されていました。 @b{この使い方は現在は非推奨です}。@code{(library srfi.N)}で検査するように 変更してください。詳しくは@ref{Testing availability of SRFIs}参照。 0.9.13時点では、環境変数@code{GAUCHE_WARN_SRFI_FEATURE_ID}が セットされている場合に限り、機能識別子@code{srfi-N}が使われた時に 警告が出されます。将来はデフォルトで警告を出すようにするので、 いまのうちにこの環境変数をセットして古いコードを見つけて書き換えておくと良いでしょう。 @c COMMON @c EN See below for the list of feature identifiers defined in Gauche. @c JP Gaucheで使えるfeature identifier一覧は下を見てください。 @c COMMON @end defmac @c EN @subheading Gauche-specific feature identifiers @c JP @subheading Gauche特有のfeature identifier @c COMMON @table @code @item gauche @itemx gauche-X.X.X @c EN Indicates you're running on Gauche. It is useful to put Gauche-specific code in a portable program. @code{X.X.X} is the gauche's version (e.g. @code{gauche-0.9.4}), in case you want to have code for specific Gauche version. (Such feature identifier is suggested by R7RS; but it might not be useful if we don't have means to compare versions. Something to consider in future versions.) @c JP プログラムをGaucheで実行していることを示します。ポータブルなプログラムの中に Gauche特有のコードを埋め込むのに便利です。 @code{X.X.X}はGaucheのバージョンで(例: @code{gauche-0.9.4})、 特定のGaucheのバージョンのみに依存したコードを入れるのに使えます。 (処理系のバージョンつきの機能識別子はR7RSで示唆されているものですが、 バージョンを比較する機能がないとあまり有用ではないでしょう。 将来はそのような機能が追加されるかもしれません。) @c COMMON @item gauche.os.windows @itemx gauche.os.cygwin @c EN Defined on Windows-native platform and Cygwin/Windows platform, respectively. If neither is defined you can assume it's a unix variant. (Cygwin is supposedly unix variant, but corners are different enough to deserve it's own feature identifier.) @c JP それぞれ、WindowネイティブプラットフォームとCygwin/Windowsプラットフォームを 示します。どちらも定義されていなければ、Unix系と考えて構いません。 (CygwinもUnix系と言えなくはありませんが、他のUnix系に比べて 色々違いがあるので、機能識別子を用意してあります。) @c COMMON @item gauche.ces.utf8 @c EN This indicates Gauche's internal encoding is @code{utf-8}. Before 1.0, Gauche can be compiled with internal encodings other than @code{utf-8}, and the corresponding feature identifiers are defined so that the program can switch its behavior according to it. Now this is the only possible choice. This is kept for the backward compatibility. @c JP Gaucheの内部エンコーディングが@code{utf-8}であることを示します。 1.0以前には、Gaucheはutf-8以外のいくつかの内部エンコーディングで コンパイルすることが可能で、それに合わせた機能識別子が定義され、 プログラムが内部エンコーディングに応じて振る舞いを変えられるようになっていました。 今はこれが唯一のエンコーディングです。過去のコードを変更なしで走らせられるように 定義されています。 @c COMMON @item gauche.net.tls @itemx gauche.net.tls.axtls @itemx gauche.net.tls.mbedtls @c EN Defined if the runtime supports TLS in networking. The two sub feature identifiers, @code{gauche.net.tls.axtls} and @code{gauche.net.tls.mbedtls}, are defined if each subsystem @code{axTLS} and @code{mbedTLS} is supported, respectively. @c JP TLS/SSLサポートがあれば定義されます。サブ機能識別子@code{gauche.net.tls.axtls}と @code{gauche.net.tls.mbedtls}は、それぞれサブシステム@code{axTLS} と@code{mbedTLS}がサポートされていれば定義されます。 @c COMMON @item gauche.net.ipv6 @c EN Defined if the runtime supports IPv6. Note that this only indicates Gauche has been built with IPv6 support; the OS may not allow IPv6 features, in that case you'll get system error when you try to use IPv6. @c JP IPv6サポートが組み込まれていれば定義されます。 ただし、これがGaucheがIPv6サポート込みでビルドされたことを示すだけです。 OSがIPv6サポートをオフにしている場合、IPv6機能を使おうとするとシステムエラーが 投げられます。 @c COMMON @item gauche.sys.threads @itemx gauche.sys.pthreads @itemx gauche.sys.wthreads @c EN If the runtime supports multithreading, @code{gauche.sys.threads} is defined (@pxref{Threads}). Multithreading is based on either POSIX pthreads or Windows threads. The former defines @code{gauche.sys.pthreads}, and the latter defines @code{gauche.sys.wthreads}. @c JP マルチスレッドがサポートされていれば@code{gauche.sys.threads}が定義されます (@ref{Threads}参照)。また、マルチスレッドは内部ではプラットフォームによって POSIXスレッドかWindowsスレッドを利用しますが、前者の場合は @code{gauche.sys.pthreads}が、後者では@code{gauche.sys.wthreads}が 併せて定義されます。 @c COMMON @item gauche.sys.sigwait @itemx gauche.sys.setenv @itemx gauche.sys.unsetenv @itemx gauche.sys.clearenv @itemx gauche.sys.getloadavg @itemx gauche.sys.getrlimit @itemx gauche.sys.lchown @itemx gauche.sys.getpgid @itemx gauche.sys.nanosleep @itemx gauche.sys.crypt @itemx gauche.sys.symlink @itemx gauche.sys.readlink @itemx gauche.sys.select @itemx gauche.sys.fcntl @itemx gauche.sys.syslog @itemx gauche.sys.setlogmask @itemx gauche.sys.openpty @itemx gauche.sys.forkpty @c EN Those are defined based on the availability of these system features of the platform. @c JP これらシステムの機能が使えるのなら対応する機能識別子が定義されます。 @c COMMON @end table @c EN @subheading R7RS feature identifiers @c JP @subheading R7RSで定義されたfeature identifiers @c COMMON @table @code @item r7rs @c EN Indicates the implementation complies r7rs. @c JP 実装がr7rs準拠であることを示します。 @c COMMON @item exact-closed @c EN Exact arithmetic operations are closed; that is, dividing an exact number by a non-zero exact number always yields an exact number. @c JP 数値計算が正確な値について閉じている、つまり、正確な数を ゼロ以外の正確な数で割った結果が常に正確な数になることを示します。 @c COMMON @item ieee-float @c EN Using IEEE floating-point number internally. @c JP 内部的にIEEE浮動小数点数を使っていることを示します。 @c COMMON @item full-unicode @c EN Full unicode support. @c JP Unicodeの全ての範囲をサポートしていることを示します。 @c COMMON @item ratios @c EN Rational number support @c JP 有理数のサポートがあることを示します。 @c COMMON @item posix @itemx windows @c EN Either one is defined, according to the platform. @c JP プラットフォームによってどちらかが定義されます。 @c COMMON @item big-endian @itemx little-endian @c EN Either one is defined, according to the platform. @c JP プラットフォームによってどちらかが定義されます。 @c COMMON @end table @c ---------------------------------------------------------------------- @node Modules, , Feature conditional, Core syntax @section Modules @c NODE モジュール @c EN This section describes the semantics of Gauche modules and its API. See also @ref{Writing Gauche modules}, for the conventions Gauche is using for its modules. @c JP この章では、GaucheのモジュールのセマンティクスとAPIを述べます。 Gaucheで使われているモジュールの書法については@ref{Writing Gauche modules}も 併せて参照して下さい。 @c COMMON @c EN For R7RS programs, they are called ``libraries'' and have different syntax than Gauche modules. @xref{R7RS library form}, for the details. @c JP R7RSプログラムでは、モジュールに相当するものは「ライブラリ」と呼ばれ、 Gaucheとは異なる構文で定義します。詳しくは@ref{R7RS library form}を参照してください。 @c COMMON @menu * Module semantics:: * Modules and libraries:: * Defining and selecting modules:: * Using modules:: * Module inheritance:: * Module introspection:: * Predefined modules:: @end menu @node Module semantics, Modules and libraries, Modules, Modules @subsection Module semantics @c NODE モジュールのセマンティクス @c EN Module is an object that maps symbols onto @emph{bindings}, and affects the resolution of global variable reference. @c JP モジュールは、シンボルを束縛へとマップするオブジェクトで、 グローバル変数の解決に影響を与えます。 @c COMMON @c EN Unlike CommonLisp's packages, which map names to symbols, in Gauche symbols are @code{eq?} in principle if two have the same name (except uninterned symbols; @pxref{Symbols}). However, Gauche's symbol doesn't have a 'value' slot in it. From a given symbol, a module finds its binding that keeps a value. Different modules can associate different bindings to the same symbol, that yield different values. @c JP CommonLispのパッケージは名前からシンボルへのマッピングを行いますが、 Gaucheでは同じ名前を持つシンボルは原則として@code{eq?}です (例外はインターンされていないシンボルです。@ref{Symbols}参照)。 しかし、Gaucheのシンボルは「値」のスロットを持っていません。 モジュールによってシンボルに対応する束縛が見付けられ、値はそこに 格納されています。 モジュールが違えば同じシンボルは別々の束縛へとマップされ、違う値を 返します。 @c COMMON @example @c EN ;; Makes two modules A and B, and defines a global variable 'x' in them @c JP ;; 二つのモジュールAとBを作成し、グローバル変数'x'をその中で定義 @c COMMON (define-module A (define x 3)) (define-module B (define x 4)) ;; # ---[module A]--> # (with-module A x) @result{} 3 ;; # ---[module B]--> # (with-module B x) @result{} 4 @end example @c EN A module can @emph{export} a part or all of its bindings for other module to use. A module can @emph{import} other modules, and their exported bindings become visible to the module. A module can import any number of modules. @c JP モジュールは、自身が持つ一部または全ての束縛を他のモジュールからも 使えるように@emph{export}することができます。あるモジュールXが他の モジュールYを@emph{import}すると、 モジュールYでexportされている束縛が元のモジュールXから見えるようになります。 モジュールはいくつでも他のモジュールをimportすることができます。 @c COMMON @example (define-module A (export pi) (define pi 3.1416)) (define-module B (export e) (define e 2.71828)) (define-module C (import A B)) (select-module C) (* pi e) @result{} 8.539748448 @end example @c EN A module can also be @emph{inherited}, that is, you can extend the existing module by inheriting it and adding new bindings and exports. From the new module, all ancestor's bindings (including non-exported bindings) are visible. (A new module inherits the @code{gauche} module by default, which is why the built-in procedures and syntax of @code{gauche} are available in the new module). From outside, the new module looks like having all exported bindings of the original module plus the newly defined and exported bindings. @c JP また、モジュールは継承することもできます。 既存のモジュールを継承したモジュールに新しい束縛を足してexportすることにより、 既存のモジュールを拡張することができます。新しいモジュールの内部からは、 継承元のモジュールの束縛が(exportされていないものも含め)全て見えます。 (新しく作られるモジュールはデフォルトで@code{gauche}モジュールを継承しています。 新しいモジュールから@code{gauche}の組込み手続き等が使えるのはそのためです)。 外からは、新しいモジュールには元のモジュールの全てのexportされた束縛と 新たに追加されexportされた束縛が見えます。 @c COMMON @example ;; Module A defines and exports deg->rad. ;; A binding of pi is not exported. (define-module A (export deg->rad) (define pi 3.1416) ;; not exported (define (deg->rad deg) (* deg (/ pi 180)))) ;; Module Aprime defines and exports rad->deg. ;; The binding of pi is visible from inside Aprime. (define-module Aprime (extend A) (export rad->deg) (define (rad->deg rad) (* rad (/ 180 pi)))) ;; Module C imports Aprime. (define-module C (import Aprime) ;; Here, both deg->rad and rad->deg are visible, ;; but pi is not visible. ) @end example @c EN At any moment of the compilation, there is one "current module" available, and the global variable reference is looked for from the module. If there is a visible binding of the variable, the variable reference is compiled to the access of the binding. If the compiler can't find a visible binding, it marks the variable reference with the current module, and delays the resolution of binding at the time the variable is actually used. That is, when the variable is referenced at run time, the binding is again looked for from the marked module (@emph{not} the current module at the run time) and if found, the variable reference code is replaced for the the code to access the binding. If the variable reference is not found even at run time, an 'undefined variable' error is signaled. @c JP コンパイル中のどの時点でも、「カレントモジュール」が一意に決定され、 グローバル変数の束縛はそのカレントモジュールを起点に探されます。 その変数の束縛が見付かれば、変数参照の式はその束縛へアクセスするコードとして コンパイルされます。もしコンパイラが束縛を見付けられなかった場合、 変数参照の式はカレントモジュールでマークされ、束縛の解決はランタイムへと 先送りされます。すなわち、ランタイムにその変数が使われる時点で 再びマークされていたモジュールから束縛の探索が行われます (ランタイムでのカレントモジュールからでは無いことに注意)。 束縛が見付かれば、束縛へアクセスするコードがコンパイルされたコード列に 挿入されます。見付からなければ'undefined variable'エラーが報告されます。 @c COMMON @c EN Once the appropriate binding is found for the global variable, the access to the binding is hard-wired in the compiled code and the global variable resolution will never take place again. @c JP グローバル変数に対して適切な束縛がひとたび発見されれば、 その束縛へのアクセスはコンパイルされたコードに埋め込まれ、 その変数の束縛の探索は二度と行われません。 @c COMMON @c EN The definition special form such as @code{define} and @code{define-syntax} inserts the binding to the current module. Thus it may shadow the binding of imported or inherited modules. @c JP @code{define}や@code{define-syntax}等の定義を行う特殊形式は カレントモジュールに束縛を挿入します。これは、importしたり継承したりしている モジュールの同名の束縛をシャドウします。 @c COMMON @c EN The resolution of binding of a global variable happens like this. First, the current module is searched. Then, each imported module is taken in the reverse order of import, and searched, including each module's ancestors. Note that import is not transitive; imported module list is not chased recursively. Finally, ancestors of the current module are searched in order. @c JP グローバル変数の束縛の解決は次の手順で行われます。 まずカレントモジュールが探されます。次に、importしているモジュールが importされた逆の順番に並べられ、それぞれについてその モジュールおよびそのモジュールの先祖(継承されているモジュール)が順に探されます。 importは遷移的ではありません;importされたモジュールがimportしているモジュール… というふうに再帰的に辿ることはしません。 最後に、カレントモジュールの先祖が順に探されます。 @c COMMON @c EN This order is important when more than one modules defines the same name and your module imports both. Assuming your module don't define that name, if you first import a module @code{A} then a module @code{B}, you'll see @code{B}'s binding. If you import @code{A}, then @code{B}, then @code{A} again, the last import takes precedence; that is, you'll see @code{A}'s binding. @c JP この順序は、複数のモジュールで同じ名前が定義され、あなたのモジュールが その両方をインポートしている場合に重要になります。 その名前があなたのモジュールで 定義されていないとして、もしモジュール@code{A}がまずimportされ、 次に@code{B}がimportされている場合、あなたのコードは@code{B}の 束縛を見ることになります。 @code{A}をimportして@code{B}をimportした後に再び@code{A}をimport した場合、後のimportの方が効力を持ちます。すなわち、@code{A}の束縛が 見えることになります。 @c COMMON @c EN If two modules you want to use exports bindings of the same name and you want to access both, you can add prefix to either one (or both). @xref{Using modules}, for the details. @c JP もし、二つのモジュールが同名の束縛をエクスポートしており、 その両方にアクセスしたければ、一方もしくは両方の名前にプレフィクスを つけることができます。詳しくは@ref{Using modules}を参照してください。 @c COMMON @node Modules and libraries, Defining and selecting modules, Module semantics, Modules @subsection Modules and libraries @c NODE モジュールとライブラリ @c EN Modules are run-time data structure; you can procedurally create modules with arbitrary names at run-time. @c JP モジュールは実行時データ構造です。実行時に任意の名前のモジュールを 手続き的に作成することができます。 @c EN However, most libraries use modules to create their own namespace, so that they can control which bindings to be visible from library users. (This ``library'' is a general term, broader than R7RS ``library''). @c JP しかしほとんどのライブラリは、固有の名前空間を生成するために モジュールを用います。これにより、どの束縛をライブラリ使用者に 見せるかを制御できます。(ここでの「ライブラリ」は、R7RSのライブラリだけでなく より広い意味で使っています。) @c EN Usually a library is provided in the form of one or more Scheme source file(s), so it is convenient to have a convention to map module names to file names, and vice versa; then, you can load a library file and import its module by one action with @code{use} macro, for example. @c JP 通常ライブラリは1つ以上のSchemeソースファイル形式で提供されます。 したがって、ファイル名をモジュール名に対応づける(またはその逆の) 規約にしておけば便利です。そうすれば、たとえば、ライブラリーファイルを ロードしたり、@code{use} マクロを使ってモジュールを一動作で、 インポートしたりできます。 @c EN For the time being, Gauche uses a simple rules for this mapping: Module names are organized hierarchically, using period `@code{.}' for separator, e.g. @code{gauche.mop.validator}. If such a module is requested and doesn't exist in the current running environment, Gauche maps the module name to a pathname by replacing periods to directory separator, i.e. @code{gauche/mop/validator}, and look for @code{gauche/mop/validator.scm} in the load paths. @c JP 当分の間、Gauche はこの対応づけのための単純なルールを使用します。すなわち、 モジュール名は、例えば @code{gauche.mop.validator} のように `@code{.}' (ピリオド)記号で階層的に区切って構成されます。このようなモジュールが 要求されても、現在の実行時環境に存在しない場合には、Gauche は ピリオド記号をディレクトリ区切りに変換して @code{gauche/mop/validator} のようにモジュール名からパス名に変換します。その後、 @code{gauche/mop/validator.scm} をロードパスから探します。 @c EN Note that this is just a default behavior. Theoretically, one Scheme source file may contain multiple modules, or one module implementation may span to multiple files. In future, there may be some hook to customize this mapping for special cases. So, when you are writing routines that deal with modules and library files, do not apply the above default rule blindly. Gauche provides two procedures, @code{module-name->path} and @code{path->module-name}, to do mapping for you (see @ref{Module introspection}, for details). @c JP これが単にデフォルトの振る舞いであることに注意してください。 理論上、1つのSchemeソース・ファイルは多数のモジュールを含むことがあります。 あるいは、1つのモジュール実装は多数のファイルにまたがることもありえます。 将来、特別なケースのために、この対応付けをカスタマイズするフックを 用意するかもしれません。したがって、モジュールおよびライブラリーファイルを 扱うルーチンを書く場合には、上記のデフォルトルールを盲目的に適用しないで ください。Gaucheは @code{module-name->path} と @code{path->module-name} という 2つの対応づけ手続き(詳細に関しては、@ref{Module introspection}参照) を用意しています。 @c COMMON @node Defining and selecting modules, Using modules, Modules and libraries, Modules @subsection Defining and selecting modules @c NODE モジュールの定義と選択 @defspec define-module name body @dots{} @c EN @var{Name} must be a symbol. If a module named @var{name} does not exist, create one. Then evaluates @var{body} sequentially in the module. @c JP @var{name}はシンボルでなければなりません。 名前@var{name}を持つモジュールが存在しなければまず作成します。 それから、@var{body} @dots{} をモジュール@var{name}中で評価します。 @c COMMON @end defspec @defspec select-module name @c EN Makes a module named @var{name} as the current module. It is an error if no module named @var{name} exists. If @code{select-module} is used in the Scheme file, its effect is limited inside the file, i.e. even if you load/require a file that uses @code{select-module} internally, the current module of requirer is not affected. @c JP 名前@var{name}を持つモジュールをカレントモジュールとします。 その名前を持つモジュールが無ければエラーとなります。 @code{select-module}がSchemeファイルの中で用いられた場合、 その効果はそのファイルの終了までに限られます。@code{select-module}を中で呼んでいる ファイルをloadやrequireしても、呼んだ側のカレントモジュールは影響を受けません。 @c COMMON @end defspec @defspec with-module name body @dots{} @c EN Evaluates @var{body} sequentially in the module named @var{name}. Returns the last result(s). If no module named @var{name}, an error is signaled. @c JP 名前@var{name}を持つモジュールをカレントモジュールとした状態で@var{body} @dots{} を順に評価し、最後の結果を返します。該当するモジュールが存在しなければエラーとなります。 @c COMMON @end defspec @defspec current-module @c EN Evaluates to the current module in the compile context. Note that this is a special form, not a function. Module in Gauche is statically determined at compile time. @c JP コンパイル時点でのカレントモジュールに評価されます。 これは手続きではなく特殊形式です。 Gaucheではモジュールはコンパイル時に静的に決定されます。 @c COMMON @example (define-module foo (export get-current-module) (define (get-current-module) (module-name (current-module)))) (define-module bar (import foo) (get-current-module)) @result{} foo @r{; not bar} @end example @end defspec @node Using modules, Module inheritance, Defining and selecting modules, Modules @subsection Using modules @c NODE モジュールの使用 @defspec export spec @dots{} [R7RS base] @c EN Makes bindings specified by each @var{spec} available to modules that imports the current module. Each @var{spec} can be either one of the following forms, where @var{name} and @var{exported-name} are symbols. @table @code @item @var{name} The binding with @var{name} is exported. @item (rename @var{name} @var{exported-name}) The binding with @var{name} is exported under an alias @var{exported-name}. @end table @c JP カレントモジュールから、@var{spec}で指定される束縛をexportします。 exportされた束縛は、カレントモジュールをimportしたモジュール中で見えるようになります。 各@var{spec}は次のどちらかの形式でなければなりません。@var{name}と@var{export-name} はシンボルです。 @table @code @item @var{name} 名前@var{name}を持つ束縛がexportされます。 @item (rename @var{name} @var{exported-name}) 名前@var{name}を持つ束縛が、@var{exported-name}という別名でexportされます。 @end table @c COMMON @c EN Note: In Gauche, @code{export} is just a special form you can put in the middle of the program, whereas R7RS defines @code{export} as a library declaration, that can only appear immediately below @code{define-library} form. @xref{R7RS library form}, for the details. @c JP 註: Gaucheの@code{export}は単なるスペシャルフォームで プログラムの途中に書くこともできますが、 R7RSの@code{export}はライブラリ宣言の一部で @code{define-library}フォームの直下にしか書けません。 詳しくは@ref{R7RS library form}を参照してください。 @c COMMON @end defspec @defspec export-all @c EN Makes all bindings in the current module available to modules that imports it. @c JP カレントモジュール中の全ての束縛をexportします。 @c COMMON @end defspec @defspec import import-spec @dots{} @c EN Makes all or some exported bindings in the module specified by @var{import-spec} available in the current module. The syntax of @var{import-spec} is as follows. @c JP @var{import-spec}で指定されるモジュールがexportしている 束縛のすべてもしくはいくつかを、カレントモジュール中で使えるようにします。 @var{import-spec}は以下の形式です。 @c COMMON @example : | ( ...) : :only ( ...) | :except ( ...) | :rename (( ) ...) | :prefix : @end example @c EN The module named by @var{module-name} should exist when the compiler sees this special form. @c JP @var{module-name}で指定される名前のモジュールは このフォームがコンパイルされる時点までに存在していなければなりません。 @c COMMON @c EN Imports are not transitive. The modules that @var{module-name}s are importing are not automatically imported to the current module. This keeps modules' modularity; a library module can import whatever modules it needs without worrying about polluting the namespace of the user of the module. @c JP モジュールのimportは遷移的ではありません。 つまり@code{module-name}で指定されたモジュールがその内部でimport しているモジュールは自動的にカレントモジュールにはimportされてません。 モジュールの独立性を保つための設計です。この性質により、 ライブラリモジュールの作者はいくら他のモジュールを importしようとも利用者の名前空間を不意に汚染してしまう心配はありません。 (利用者からはそのモジュールでexportしている名前しか見えないからです。) @c COMMON @c EN @var{import-option} can be used to change how the bindings are imported. With @code{:only}, only the bindings with the names listed in @code{ @dots{}} are imported. With @code{:except}, the exported bindings except the ones with the listed names are imported. With @code{:rename}, the binding of each name in the first of two-symbol list is renamed to the second of it. With @code{:prefix}, the exported bindings are visible with the names that are prefixed by the symbol to the original names. Without import options, all the exported bindings are imported without a prefix. @c JP @var{import-option}は束縛がどのようにインポートされるかを制御します。 @code{:only}がある場合、@code{ @dots{}}に挙げられた名前を 持つ束縛のみがインポートされます。@code{:except}がある場合は逆に、 エクスポートされている束縛のうち挙げられた名前を持つもの以外が インポートされます。@code{:rename}は各2要素のリストの最初の名前 を持つ束縛が2番目の名前へとリネームされます。 @code{:prefix}があると、元の名前の前に 指定されるシンボルが付加された名前で束縛が見えるようになります。 @var{import-option}が指定されなければ、@var{module-name}のすべての エクスポートされた束縛がプレフィクス無しでインポートされます。 @c COMMON @example (define-module M (export x y) (define x 1) (define y 2) (define z 3)) (import M) x @result{} 1 @c EN z @result{} @r{error. z is not exported from M} @c JP z @result{} @r{エラー。 zはMからエクスポートされなていない} @c COMMON (import (M :only (y))) @c EN x @result{} @r{error. x is not in :only list.} @c JP x @result{} @r{エラー。xは:onlyリストに含まれない。} @c COMMON (import (M :except (y))) @c EN y @result{} @r{error. y is excluded by :except.} @c JP y @result{} @r{エラー。yは:exceptにより除外されている。} @c COMMON (import (M :prefix M:)) x @result{} @r{error} M:x @result{} 1 M:y @result{} 2 @end example @c EN If more than one import option are given, it is processed as the order of appearance. That is, if @code{:prefix} comes first, then @code{:only} or @code{:except} has to list the name with prefix. @c JP 一つ以上のインポートオプションが与えられた場合、 それは出現順に処理されます。すなわち、@code{:prefix}が 最初に現れた場合、その後に来る@code{:only}や@code{:except} はプレフィックスつきの名前を使って指定しなければなりません。 @c COMMON @c EN Note: R7RS has @code{import} form, which has slightly different syntax and semantics. @xref{Three forms of import}, for the details. @c JP 註: R7RSにも@code{import}フォームがありますが、若干構文と意味が異なります。 @ref{Three forms of import}を参照してください。 @c COMMON @end defspec @defmac use name :key only except rename prefix @c EN A convenience macro that combines module imports and on-demand file loading. Basically, @code{(use foo)} is equivalent to the following two forms: @example (require "foo") (import foo) @end example That is, it loads the library file named ``@code{foo}'' (if not yet loaded) which defines a module named @code{foo} in it, and then import the module @code{foo} into the current module. @c JP モジュールのインポートと必要に応じてファイルのロードを合わせて行う、 便利なマクロです。基本的に、@code{(use foo)} は以下のふたつのフォームと 等価です。 @example (require "foo") (import foo) @end example すなわち、まず名前``@code{foo}''を持つライブラリファイルが(まだロードされて いなければ)ロードされ、その中で定義されているモジュール@code{foo}をカレントモジュールに インポートします。 @c COMMON @c EN The keyword argument @var{only}, @var{except}, and @var{prefix} are passed to @code{import} as the import options. @c JP キーワード引数@var{only}, @var{except}, @var{prefix}は @code{import}にインポートオプションとして渡されます。 @c COMMON @example (use srfi.1 :only (iota) :prefix srfi-1:) (srfi-1:iota 3) @result{} (0 1 2) @end example @c EN Although the files and modules are orthogonal concept, it is practically convenient to separate files by modules. Gauche doesn't force you to do so, and you can always use @code{require} and @code{import} separately. However, all modules provided with Gauche are arranged so that they can be used by @code{use} macro. @c JP ファイルのロードとモジュールとは直交する概念ですが、 実用的にはモジュール毎にファイルを分割するのが便利です。 必ずしもそうする必要は無く、@code{require} と @code{import} を別々に 使っても構いません。が、Gaucheに附属してくるライブラリはすべて、 @code{use} マクロで使えるように書かれています。 @c COMMON @c EN If a module is too big to fit in one file, you can split them into several subfiles and one main file. The main file defines the module, and either loads, requires, or autoloads subfiles. @c JP もしモジュールが一つのファイルに収めるには大きすぎる場合、一つのメインファイルと いくつかのサブファイルに分けることも出来ます。メインファイルの中でモジュールを 定義し、サブファイルをまとめてロードするか、オートロードを設定します。 @c COMMON @c EN Actually, the file pathname of the given module name is obtained by the procedure @code{module-name->path} below. The default rule is to replace periods `@code{.}' in the @var{name} for `@code{/}'; for example, @code{(use foo.bar.baz)} is expanded to: @example (require "foo/bar/baz") (import foo.bar.baz) @end example This is not very Scheme-ish way, but nevertheless convenient. In future, there may be some mechanism to customize this mapping. @c JP 実際は、与えられたモジュール名からファイルのパス名を得るのに 手続き@code{module-name->path}が使われます。デフォルトの変換規則は、 モジュール名@var{name}中のピリオド`@code{.}'を`@code{/}'に置換 するというものです。例えば@code{(use foo.bar.baz)}は @example (require "foo/bar/baz") (import foo.bar.baz) @end example となります。これはあまりScheme風ではありませんが、便利ではあります。 将来、このマッピングルールをカスタマイズする機構が導入されるかもしれません。 @c COMMON @c EN The file to be @code{use}'d must have explicit module selection to have any toplevel definitions (usually via @code{define-module}/@code{select-module} pair or @code{define-library}). If you get an error saying ``Attempted to create a binding in a sealed module: module: #'', that's because the file lacks module selection. @xref{Require and provide}, for further discussion. @c JP @code{use}されるファイルがトップレベル定義を持つ場合、ファイル内でモジュールが 明示されてることが必要です (通常は@code{define-module}/@code{select-module} や@code{define-library}が使われます)。 もし、``Attempted to create a binding in a sealed module: module: #''というエラーが出たら、 @code{use}したファイルがモジュール指定を持っていないということです。 詳しくは@ref{Require and provide}を参照してください。 @c COMMON @end defmac @node Module inheritance, Module introspection, Using modules, Modules @subsection Module inheritance @c NODE モジュールの継承 @c EN The export-import mechanism doesn't work well in some cases, such as: @c JP export-importメカニズムは、次のような場合をうまく処理できません。 @c COMMON @itemize @bullet @c EN @item You want to create a module that is mostly the same as the existing one, but adding or altering some definitions. @c JP @item 既存のモジュールとほぼ同等の機能を持つが、若干定義を足したり変更したり したモジュールを作りたい。 @c COMMON @c EN @item You wrote a bunch of related modules that are often used together, and not want your users to repeat a bunch of 'use' forms every time they use your module. @c JP @item 相互に関連するいくつものモジュールを作成した。 ユーザがこれらのモジュールを使う時に毎回いくつも 'use' を並べないで済むように 一つにまとめたい。 @c COMMON @end itemize @c EN You can use module inheritance in these cases. @c JP このような場合にモジュールの継承が使えます。 @c COMMON @defmac extend module-name @dots{} @c EN Makes the current module inherit from named modules. The current inheritance information is altered by the inheritance information calculated from given modules. @c JP カレントモジュールが、@var{module-name} @dots{}に挙げられたモジュールを 継承するようにします。それまでの継承の情報は捨てられ、@var{module-name} @dots{} から計算される継承情報が有効になります。 @c COMMON @c EN A new module inherits from @code{gauche} module when created. If you put @code{(extend scheme)} in that module, for example, the module resets to inherit directly from @code{scheme} module that has only bindings defined in R5RS, hence, after the extend form, you can't use 'import' or any other @code{gauche}-specific bindings in the module. @c JP 新たに作られるモジュールはデフォルトで@code{gauche}モジュールを継承しています。 例えばそのモジュールに@code{(extend scheme)}というフォームを入れた場合、 その時点でそのモジュールは@code{scheme}モジュール(R5RSで定義された束縛 のみを含む)を直接継承するようになります。したがって、そのフォームの後で 'import' やその他@code{gauche}特有の束縛はそのモジュール内では 使えなくなります。 @c COMMON @c EN If a named module is not defined yet, @code{extend} tries to load it, using the same convention @code{use} macro does. @c JP @var{module-name}に挙げられたモジュールがまだ存在しなかった場合、 @code{extend}は@code{use}と同じメカニズムを使ってファイルをロードすることを 試みます。 @c COMMON @c EN A module can inherit multiple modules, exactly the same way as a class can inherit from multiple classes. The resolution of order of inheritance needs to be explained a bit. @c JP モジュールは複数のモジュールを継承することができます。 丁度、クラスが複数のクラスを継承できるのと同じようにです。 多重継承の場合、次のようにしてモジュール間の優先順位が決められます。 @c COMMON @c EN Each module has a @emph{module precedence list}, which lists modules in the order of how they are searched. When the module inherits multiple modules, module precedence lists of inherited modules are merged into a single list, keeping the constraints that: (1) if a module A appears before module B in some module precedence list, A has to appear before B in the resulting module precedence list; and (2) if a module A appears before module B in @code{extend} form, A has to appear before B in the resulting module precedence list. If no precedence list can be constructed with these constraints, an error is signaled. @c JP 各モジュールは@emph{module precedence list}というモジュールのリストを 持っています。そこにリストされた順に束縛が探されます。 モジュールが複数のモジュールを多重継承した場合、継承される各モジュールの module precedence listを、次に挙げる制約を満たすようにマージ したものが新たなmodule precedence listとなります: (1) あるmodule precedence listでモジュールAがモジュールBより前に現れていたら、 結果のmodule precedence listでもAはBより前に現れる: (2) モジュールAがモジュールBより@code{extend}フォームで前に現れていたら、 結果のmodule precedence listでもAはBより前に現れる。 この条件を満たすようなmodule precedence listが構成できない場合はエラーとなります。 @c COMMON @end defmac @c EN For example, suppose you wrote a library in modules @code{mylib.base}, @code{mylib.util} and @code{mylib.system}. You can bundle those modules into one module by creating a module @code{mylib}, as follows: @c JP 例えばあなたがライブラリを3つのモジュール、 @code{mylib.base}、@code{mylib.util}、@code{mylib.system}に分けて 書いたとしましょう。次のように書けば、これらのモジュールを 一つの@code{mylib}モジュールに見せることができます。 @c COMMON @example (define-module mylib (extend mylib.system mylib.util mylib.base)) @end example @c EN The user of your module just says @code{(use mylib)} and all exported symbols from three submodules become available. @c JP このライブラリモジュールのユーザは @code{(use mylib)} とするだけで 全てのサブモジュールのexportされた束縛を利用することができるようになります。 @c COMMON @node Module introspection, Predefined modules, Module inheritance, Modules @subsection Module introspection @c NODE モジュールイントロスペクション @c EN This subsection lists procedures that operates on modules at run-time. With these procedures you can introspect the modules, create new modules procedurally, or check the existence of certain modules/libraries, for example. However, don't forget that modules are primarily compile-time structures. Tweaking modules at run-time is only for those who know what they are doing. @c JP この節では、実行時にモジュールを操作する手続きをリストします。 これらの手続きにより、例えばモジュールの内部を調べたり、手続き的に 新しいモジュールを作成したり、特定のモジュールやライブラリの存在を 調べたりすることができます。ただし、モジュールは第一にコンパイル時の 構造であることを忘れないでください。実行時にモジュールをいじくるのは、 十分にモジュールの構造を理解した上で行ってください。 @c COMMON @deftp {Builtin Class} @clindex module @c EN A module class. @c JP モジュールクラスです。 @c COMMON @end deftp @defun module? obj @c EN Returns true if @var{obj} is a module. @c JP @var{obj}がモジュールなら真の値を返します。 @c COMMON @end defun @defun find-module name @c EN Returns a module object whose name is a symbol @var{name}. If the named module doesn't exist, @code{#f} is returned. @c JP 名前がシンボル@var{name}であるようなモジュールを返します。 その名前をもつモジュールが存在しなければ、@code{#f}を返します。 @c COMMON @end defun @defun make-module name :key if-exists @c EN Creates and returns a module that has symbol @var{name}. If the named module already exists, the behavior is specified by @var{if-exists} keyword argument. If it is @code{:error} (default), an error is signaled. If it is @code{#f}, @code{#f} is returned. @c JP シンボルの名前@var{name}を持つモジュールを作成して返します。 その名前を持つモジュールが既に存在していた場合、その動作は @var{if-exists}キーワード引数で指定されます。 @var{if-exists}引数が@code{:error}である場合(デフォルト)、 エラーが報告されます。それが@code{#f}である場合は単に@code{#f}が返されます。 @c COMMON @c EN Note that creating modules on-the-fly isn't usually necessary for ordinal scripts, since executing already written program requires modules to be specified by name, i.e. syntax @code{define-module}, @code{import}, @code{extend}, @code{with-module} all take module names, not module objects. It is because module are inherently compile-time structures. However, there are some cases that dynamically created modules are useful, especially when the program itself is dynamically created. You can pass a module to @code{eval} to compile and evaluate such dynamically created programs in it (@pxref{Eval and repl}). @c JP モジュールを実行時に動的に生成することは、通常のスクリプトでは あまり必要とはされません。既に書かれたプログラムの解釈においては、 モジュールは名前で指定されている必要があるからです。 構文@code{define-module}、@code{import}、@code{extend}、@code{with-module} 等はモジュールそのものではなくモジュール名を取ります。 これは、モジュールが本質的にコンパイル時の構造であるためです。 しかし、動的に作られるモジュールが有用な場合もあります---プログラムそのものが、 動的に作られる場合です。@code{eval}にモジュールを渡して、 そのような動的に作られたプログラムがそのモジュールの中で コンパイルされ評価されるようにできます。 @c COMMON @c EN You can also pass @code{#f} to @var{name} to create @emph{anonymous} module. Anonymous modules can't be looked up by @code{find-module}, nor can be imported or inherited (since @code{import} and @code{extend} take module names, not modules). It is useful when you want to have a temporary, segregated namespace dynamically---for example, you can create an anonymous module to evaluate code fragments sent from other program, and discards the module when the connection is terminated. Anonymous modules are not registered in the system dictionary and are garbage collected when nobody keeps reference to it. @c JP また、@var{name}に@code{#f}を渡すことで無名のモジュールを作ることもできます。 無名のモジュールは@code{find-module}で探すことはできませんし、 他のモジュールから@code{import}することも@code{extend}されることも できません(@code{import}や@code{extend}はモジュール名を必要とするからです)。 無名のモジュールは、一時的に隔離された名前空間を動的に作りたい時に 便利です。例えばネットワークで接続されたプログラムから送られた式を その中で評価して、コネクションが終了したら名前空間ごと捨ててしまうという ような場合です。無名のモジュールはシステムの内部辞書に登録されないので、 モジュールへの参照が無くなればガベージコレクトされます。 @c COMMON @c EN R7RS provides another way to create a transient module with @code{environment} procedure. @pxref{R7RS eval} for the details. @c JP R7RSでは、@code{environment}手続きによって一時的なモジュールを 作ることもできます。@ref{R7RS eval}を参照してください。 @c COMMON @end defun @defun all-modules @c EN Returns a list of all named modules. Anonymous modules are not included. @c JP 現在存在する全ての名前付きモジュールのリストを返します。 無名のモジュールは含まれません。 @c COMMON @end defun @defun module-name module @defunx module-imports module @defunx module-exports module @defunx module-table module @c EN Accessors of a module object. Returns the name of the module (a symbol), list of imported modules, list of exported symbols, and a hash table that maps symbols to bindings, of the @var{module} are returned, respectively. @c JP モジュールオブジェクトのアクセスメソッドです。 @var{module}の名前(シンボル)、@var{module}がインポートしているモジュールのリスト、 エクスポートしているシンボルのリスト、そして シンボルから束縛へのマップを行うハッシュテーブルを返します。 @c COMMON @c EN It is an error to pass a non-module object. @c JP モジュールオブジェクト以外が渡された場合はエラーになります。 @c COMMON @c EN If you want to check if a specific symbol is exported from a module, use @code{module-exports?} below instead of taking all exported symbols with @code{module-exports} and search from it. It is much faster to use @code{module-exports?}. @c JP 特定のシンボルがモジュールからエキスポートされているかどうかを調べるには、 下に説明する@code{module-exports?}を使ってください。 @code{module-exports}で全エキスポートシンボルのリストを取ってそこから探すより ずっと速いです。 @c COMMON @end defun @defun module-parents module @defunx module-precedence-list module @c EN Returns the information of module inheritance. @code{Module-parents} returns the modules @var{module} directly inherits from. @code{Module-precedence-list} returns the module precedence list of @var{module} (@pxref{Module inheritance}). @c JP モジュールの継承に関する情報を返します。 @code{module-parents}は@var{module}が直接継承しているモジュールのリストを 返します。@code{module-precedence-list}は@var{module}のmodule precedence list (@ref{Module inheritance}参照) を返します。 @c COMMON @end defun @defun module-binds? module symbol @c EN Returns @code{#t} if @var{symbol}'s global binding is visible from inside @var{module}, @code{#f} otherwise. That is, if @code{(module-binds? 'M 'v)} returns @code{#t}, @code{v} can be used as a globally bound identifier (either a variable or a syntactic keyword) in the module @code{M}. @var{Module} must be a module object or a symbol name of an existing module. This deals with the view from inside @var{module}, so it isn't affected whether the named variable is exported from @var{module}, or if so, whether it is renamed on export. If you need to test a variable from the viewpoint external to @var{module}, see @code{module-exports?} below. Note: Lisp traditionally has @code{symbol-bound?} procedure to check whether a global variable is bound, but we feel the name focuses too much on symbols, whereas global bindings are managed by modules in Gauche. Previous versions of Gauche uses the name @code{global-variable-bound?} and it is still kept for the backward compatibility, but we decided on the current name to be clear that it is about modules, and it is not only about variables. @c JP @var{symbol}のグローバルな束縛が@var{module}内部から 可視であれば@code{#t}を、そうでなければ@code{#f}を返します。 つまり、@code{(module-binds? 'M 'v)}が@code{#t}を返したら、 @code{v}はグローバルに束縛された識別子として (変数もしくは構文キーワードとして) モジュール@code{M}の中で使えるということです。 @var{module}はモジュールオブジェクトか 既存のモジュール名を示すシンボルでなければなりません。 この手続きは@var{module}内部からの見え方を扱うので、 名前@var{symbol}が@var{module}からエクスポートされているか、 あるいはエクスポート時にリネームされているかには影響されません。 @var{module}外部からの視点で束縛の可視性を調べたい場合は、 下の@code{module-exports?}を使ってください。 註: Lispは伝統的に、グローバル変数の束縛を調べる手続きを@code{symbol-bound?} と呼んできました。しかし、Gaucheでは束縛はモジュールにより管理されるのに対し、 その名前はシンボルに焦点を当ててしまっています。 以前のGaucheでは@code{global-variable-bound?}という名前を使っていて、 それは互換性のために今でも残されていますが、この操作はモジュールに関するものであること、 また、変数だけでなく構文キーワードを含めた束縛に関するものであることを明確にするために、 現在の名前になりました。 @c COMMON @end defun @defun module-exports? module symbol @c EN Returns @code{#t} if the binding of @var{symbol} is visible from outside @var{module}, @code{#f} otherwise. That is, if @code{(module-exports? 'M 'v)} returns @code{#t}, @code{v} can be used as a globally bound identifier (either as a variable or a syntactic keyword) in the module that imports module @code{M}. @var{Module} must be a module object or a symbol name of an existing module. Unlike @code{module-binds?}, this checks the outside appearance of the binding. Suppose you have those modules: @c JP @var{symbol}の束縛が@var{module}の外部から可視であれば@code{#t}を、 そうでなければ@code{#f}を返します。 すなわち、@code{(module-exports? 'M 'v)}が@code{#t}を返したなら、 @code{M}をインポートすれば@code{v}がグローバル変数もしくは構文キーワードとして 使えるということです。 @var{module}はモジュールオブジェクトか 既存のモジュール名を示すシンボルでなければなりません。 @code{module-binds?}と違い、この手続きは束縛が外からどう見えるかを検査します。 次のようなモジュールがあるとしましょう。 @c COMMON @example (define-module M (export a (rename b bee)) (define a 1) (define b 2) (define c 3)) @end example @c EN @code{module-binds?} concerns how the binding are visible in @code{M}. So it returns @code{#t} for @code{a}, @code{b}, and @code{c}, but not for @code{bee}, as in the following example: @c JP @code{module-binds?}は@code{M}の中で束縛がどう見えるかを調べるので、 @code{a}、@code{b}、@code{c}については@code{#t}を返しますが、 @code{bee}については@code{#f}を返します。 @c COMMON @example (module-binds? 'M 'a) @result{} #t (module-binds? 'M 'b) @result{} #t (module-binds? 'M 'c) @result{} #t (module-binds? 'M 'bee) @result{} #f ; renamed export doesn't affect in M @end example @c EN @code{module-exports?} concerts how the bindings are visible outside of @code{M}. So it returns @code{#t} for @code{a} and @code{bee}, but not for @code{b} and @code{c}, as in the following example. @c JP @code{module-exports?}はモジュールを外から見た場合の束縛を調べるので、 @code{a}と@code{bee}について@code{#t}を返しますが、@code{b}と@code{c}には @code{#f}を返します。 @c COMMON @example (module-exports? 'M 'a) @result{} #t (module-exports? 'M 'b) @result{} #f ; because of renamed export (module-exports? 'M 'c) @result{} #f ; not exported (module-exports? 'M 'bee) @result{} #t ; external name @end example @end defun @defun module-binding-ref module symbol :optional default @c EN Returns a value globally bound to the @var{symbol} inside @var{module}. @var{Module} must be a module object or a symbol name of an existing module. If there's no visible global binding inside @var{module} for @var{symbol}, an error is signaled, unless the @var{default} argument is provided, in which case it is returned instead. @c JP モジュール@var{module}から可視の、シンボル@var{symbol}のグローバルな 束縛値を返します。@var{module}はモジュールオブジェクトか 既存のモジュール名を示すシンボルでなければなりません。 @var{symbol}に対するグローバルな束縛が@var{module}から見えない場合は、 @var{default}引数があたえられていればその値を返し、 無ければエラーを通知します。 @c COMMON @c EN This used to be called as @code{global-variable-ref}, but we changed the name to be clear that it is module's operation, and the binding can be not only variables but also syntactic keywords. You can still use the old name but it is deprecated. @c JP これは以前は@code{global-variable-ref}と呼ばれていましたが、 モジュールの操作であること、また束縛は変数とは限らず構文キーワードでも良いことを 明確にするために名前を変えました。古い名前も使えますが非推奨です。 @c COMMON @end defun @defun global-variable-bound? module symbol @defunx global-variable-ref module symbol :optional default @c DEPRECATED @c EN Old name for @code{module-binds?} and @code{module-binding-ref}, respectively. Use new names for the new code. @c JP それぞれ、@code{module-binds?}と@code{module-binding-ref}の古い名前です。 新規コードでは新しい名前を使ってください。 @c COMMON @end defun @defun module-name->path symbol @c EN Converts a module name @var{symbol} to a fragment of pathname string (which you use for @code{require} and @code{provide}). @c JP モジュール名@var{symbol}を、パス名の一部(@code{require}や@code{provide}が 使うような)へと変換します。 @c COMMON @end defun @defun path->module-name string @c EN Reverse function of @code{module-name->path}. @c JP @code{module-name->path}の逆関数です。 @c COMMON @end defun @c EN If you want to find out specific libraries and/or modules are installed in the system and available from the program, see @ref{Operations on libraries}. @c JP 特定のライブラリやモジュールがシステムにインストールされて使える状態にあるか 調べたりする場合は、@ref{Operations on libraries}を参照して下さい。 @c COMMON @node Predefined modules, , Module introspection, Modules @subsection Predefined modules @c NODE 組み込みモジュール @c EN Several modules are predefined in Gauche. @c JP Gauche起動時にいくつかのモジュールがあらかじめ定義されています。 @c COMMON @deftp {Builtin Module} null @mdindex null @c EN This module corresponds to the null environment referred in R5RS. This module contains only syntactic bindings of R5RS syntax. @c JP このモジュールはR5RSで述べられている"null environment"に相当します。 R5RSの構文要素への束縛だけを含んだモジュールです。 @c COMMON @end deftp @deftp {Builtin Module} scheme @mdindex scheme @c EN This module contains all the binding of @code{null} module, and the binding of procedures defined in R5RS. @c JP このモジュールは@code{null}モジュール内の束縛全てに加えて、 R5RSで定義されている全ての手続きの束縛を含みます。 @c COMMON @end deftp @c EN Note that if you change the current module to @code{null} or @code{scheme} by @code{select-module}, there will be no way to switch back to other modules, since module-related syntaxes and procedures are not visible from @code{null} and @code{scheme} modules. @c JP @code{select-module}によって一度@code{null}や@code{scheme}モジュールに 入ると、そこから他のモジュールに移ることはできなくなることに注意してください。 これらのモジュールからは、あらゆるモジュール操作構文が不可視だからです。 @c COMMON @deftp {Builtin Module} gauche @mdindex gauche @c EN This module contains all the bindings of @code{scheme} module, plus Gauche specific built-in procedures. @c JP このモジュールは@code{scheme}モジュール内の全ての束縛に加え、 Gaucheの組込み手続きや構文が含まれています。 @c COMMON @end deftp @deftp {Builtin Module} user @mdindex user @c EN This module is the default module the user code is compiled. all the bindings of @code{gauche} module is imported. @c JP このモジュールはユーザコードがコンパイルされる既定のモジュールです。 @code{gauche}モジュール内の全ての束縛がインポートされています。 @c COMMON @end deftp @deftp {Builtin Module} gauche.keyword @deftpx {Builtin Module} keyword @mdindex gauche.keyword @mdindex keyword @c EN When Gauche is running with @code{GAUCHE_KEYWORD_IS_SYMBOL} mode (default) keywords (symbols beginning with @code{:}) is automatically bound to itself in these modules. (@pxref{Keywords}, for the details.) The @code{keyword} module doesn't export those bindings, while @code{gauche.keyword} does. The former is intended to be used internally; the programmer need to know the latter. If you use the default module inheritance, you don't need to use this module, since the @code{keyword} module is included in the inheritance chain. If you don't inherit @code{gauche} module, however, importing the @code{gauche.keyword} module gives you access to the keywords without quotes. For example, R7RS programs and libraries would require either @code{(import (gauche keyword))} or @code{(import (gauche base))} (the latter inherits @code{gauche.keyword}), or you have to quote all keywords. @c JP Gaucheがデフォルトの@code{GAUCHE_KEYWORD_IS_SYMBOL}モードで実行されている時は、 キーワード (@code{:}で始まるシンボル) が自動的にこれらのモジュールの中で 自分自身に束縛されます。(詳しくは@ref{Keywords}を参照してください。) @code{keyword}モジュールはキーワードの自己束縛をエクスポートせず、 @code{gauche.keyword}モジュールはエクスポートします。前者は主に 内部的に使うためのもので、プログラマが知る必要があるのは後者です。 デフォルトのモジュール継承を使っている場合、キーワードモジュールは 継承チェインの中に含まれているので、このモジュールを陽に使用する必要はありません。 @code{gauche}を継承しないモジュールを書いていて、キーワードをクオートせずに 使いたい場合にこのモジュールをインポートしてください。 例えばR7RSプログラムやライブラリは、@code{(import (gauche keyword))} もしくは@code{(import (gauche base))} (後者は@code{gauche.keyword}を 継承しています)しない限り、キーワードにクオートが必要です。 @c COMMON @c EN The following R7RS program imports @code{gauche.base}; it makes gauche built-in identifiers, @emph{and} all self-bound keywords, available: @c JP 次のR7RSプログラムは@code{gauche.base}をimportすることで、 Gaucheの組み込みの識別子とともに自己束縛されたキーワードが使えるようになります。 @c COMMON @example ;; R7RS program (import (scheme base) (gauche base)) ; import gauche builtins and keywords ;; You can use :directory without quote, for it is bound to itself. (sys-exec "ls" '("ls" "-l") :directory "/") @end example @c EN If you use more sophisticated import tricks, however, keep in mind that keywords are just imported symbols by default. The following code imports Gauche builtin identifiers with prefix @code{gauche/}. That causes keywords, imported via inheritance, also get the same prefix; if you don't want to bother adding prefix to all keywords or quote them, import @code{gauche.keyword} separately. @c JP ただ、もうちょっと凝ったインポートをする場合、 デフォルトではキーワードも 単なるインポートされるシンボルにすぎないということを覚えておいてください。 例えば次のコードではGaucheの組み込み識別子を@code{gauche/}というプレフィクス つきでインポートしています。この場合、@code{gauche.base}の継承経由で インポートされているキーワードもプレフィクスがつけられることになります。 キーワードをいちいちプレフィクスつき、もしくはクオートつきで書きたくなければ、 @code{gauche.keyword}を別にインポートしましょう。 @c COMMON @example ;; R7RS program (import (scheme base) (prefix (gauche base) gauche/) ; use gauche builtin with gauche/ prefix (gauche keyword)) ; imports keywords ;; Without importing gauche.keyword, ;; you need to write ':directory (gauche/sys-exec "ls" '("ls" "-l") :directory "/") @end example @end deftp @deftp {Builtin Module} gauche.require-base @c EN This is a module when @code{use} or @code{require} load the file. This is not meant to be @code{use}d directly; just to prevent library files lacking module switching from causing unexpected side effects. @xref{Using modules}, for more details. @c JP このモジュールは@code{use}や@code{require}がファイルを読み込む際に 設定するモジュールです。@code{use}するものではなく、 モジュール指定を欠いたライブラリファイルが予期せぬ副作用を起こすことを 防ぐためのものです。詳しくは@ref{Using modules} を参照してください。 @c COMMON @end deftp @c Local variables: @c mode: texinfo @c coding: utf-8 @c end: