@node Core library, Object system, Macros, Top @chapter Core library @c NODE 組み込みライブラリ @c ---------------------------------------------------------------------- @menu * Types and classes:: * Equality and comparison:: * Numbers:: * Booleans:: * Undefined values:: * Pairs and lists:: * Symbols:: * Keywords:: * Characters:: * Character sets:: * Strings:: * Regular expressions:: * Vector family:: * Dictionaries:: * Procedures and continuations:: * Parameters and dynamic states:: * Boxes:: * Lazy evaluation:: * Exceptions:: * Eval and repl:: * Input and output:: * Loading Programs:: * Sorting and merging:: * System interface:: * Development helper API:: @end menu @node Types and classes, Equality and comparison, Core library, Core library @section Types and classes @c NODE 型とクラス @c EN Scheme is a dynamically and strongly typed language. That is, every value @emph{knows} its type at run-time, and the type determines what kind of operations can be applied on the value. @c JP Schemeは動的な強い型付けの言語です。つまり、全ての値は 実行時に自分の型を知っていて、その型が値に適用できる操作を決定します。 @c COMMON @c EN The Scheme standard is pretty simple on types; basically, an object being a type means the type predicate returns true on the object, and that's all. Gauche adopts a bit more elaborated system---types are first-class objects and you can query various information. @c JP Scheme標準は、型についてはとても単純です。基本的に、オブジェクトがある型であるというのは、 そのオブジェクトに対して型述語が真を返す、それだけです。 Gaucheはもう少し込み入ったシステムを採用していて、型も第一級のオブジェクトになり 様々な情報を問い合わせることができます。 @c COMMON @c EN In Gauche, types are conventionally named with brackets @code{<} and @code{>}, e.g. @code{}. It's nothing syntactically special with these brackets; they're valid characters to consist of variable names. @c JP Gaucheでは慣習的に、型は@code{}のように @code{<}と@code{>}で囲まれた名前を持ちます。 この@code{<}や@code{>}は文法的には何ら特別な意味を持ちません。 普通に変数名として使える文字です。 @c COMMON @menu * Prescriptive and descriptive types:: * Generic type predicates:: * Predefined classes:: * Type expressions and type constructors:: * Native types:: @end menu @node Prescriptive and descriptive types, Generic type predicates, Types and classes, Types and classes @subsection Prescriptive and descriptive types @c NODE 規範的な型と記述的な型 @c EN Types are used in two ways. A type can be seen as a template of the actual values (instances)---that is, a type @emph{prescribes} the structure of, and possible operations on, its instances. In Gauche, such prescriptive types are represented by @emph{classes}. Every value in Gauche belongs to a class, which can be queried with the @code{class-of} procedure. You can also define your own class with @code{define-class} or @code{define-record-type} (@pxref{Object system}, and @pxref{Record types}). @c JP 型には2つの使われ方があります。まず、型は実際の値(インスタンス)のテンプレートと 見ることができます。つまり、型がインスタンスの構造と、それに適用できる操作を あらかじめ決めている(prescribe)ということです。 Gaucheでは、このような規範的(prescriptive)な型は、@emph{クラス}で表現されます。 Gauche内での値は全て何かのクラスに属していて、 @code{class-of}手続きでそのクラスを取れます。また、ユーザは独自のクラスを @code{define-class}や@code{define-record-type}で定義することもできます (@ref{Object system}および@ref{Record types}参照)。 @c COMMON @c EN A type can also be seen as a constraint of a given expression---that is, a type @emph{describes} what characteristics a certain expression must have. Gauche has entities to represent such descriptive types separate from classes. Descriptive types are created with @emph{type constructors} (@pxref{Type expressions and type constructors}). We also have a set of predefined descriptive types to communicate to C libraries (@pxref{Native types}. @c JP 型はまた、与えられた式についての制約と見ることもできます。 つまり、型がその式が持つべき特定の性質を記述する(describe)ということです。 Gaucheでは、クラスとは別に、そういった記述的(descriptive)な型を表現するエンティティを 用意しています。記述的な型は型コンストラクタで作ることができます (@ref{Type expressions and type constructors}参照)。 また、Cライブラリとやりとりするための記述的な型も用意されています (@ref{Native types}参照)。 @c COMMON @c EN A value is an instance of a class. For example, @code{1} is an instance of @code{}, and @code{"xyz"} is an instance of @code{}. This presctiptive type relationship is checked with @code{is-a?} procedure: @code{(is-a? 1 )} and @code{(is-a? "xyz" )} both returns @code{#t}. @c JP 値は、特定のクラスのインスタンスです。 例えば@code{1}は@code{}のインスタンスであり、 @code{"xyz"}は@code{}のインスタンスです。 このprescriptiveな型の関係は、手続き@code{is-a?}で検査できます。 @code{(is-a? 1 )}、@code{(is-a? "xyz" )}は どちらも@code{#t}を返します。 @c COMMON @c EN On the other hand, you may have a procedure that takes either a number or a string as an argument. ``A number or a string'' is a type constraint, and can be expressed as a descriptive type, @code{( )}. Descriptive type relationship is checked with @code{of-type?} procedure: @code{(of-type? 1 ( ))} and @code{(of-type? "xyz" ( ))} both returns @code{#t}. More conveniently, @code{(assume-type arg ( ))} would raise an error if @var{arg} doesn't satisfy the given type constraint. @c JP 一方、例えば手続きが数値か文字列を引数に取る、といったケースもあります。 「数値か文字列」というのは型に関する制約であり、descriptiveな型 @code{( )}として表現できます。 descriptiveな型の関係は手続き@code{of-type?}で検査できます。 @code{(of-type? 1 ( ))}、 @code{(of-type? "xyz" ( ))}はどちらも@code{#t}を返します。 また、@code{(assume-type arg ( ))}は @var{arg}が与えられた型の制約を満たさなければエラーを投げます。 @c COMMON @node Generic type predicates, Predefined classes, Prescriptive and descriptive types, Types and classes @subsection Generic type predicates @c NODE 汎用型述語 @c EN A ``type predicate'' is a predicate that tells if an object is of a specific type; e.g. @code{number?} tells you if the argument is a number. Since types are first-class in Gauche, we have predicates that can tell an object is of a @emph{given} type, as well as predicates to ask the relationship between types. @c JP 「型述語」は、与えられたオブジェクトが特定の型を持つかどうかを判定する述語です。 例えば@code{number?}は引数が数値かどうかを返します。 Gaucheでは型がファーストクラスなので、もう一歩進めて、 オブジェクトが@emph{与えられた}型を持つかどうかを判定する述語や、 型同士の関係を調べる述語が提供されています。 @c COMMON @defun is-a? obj class @c EN This is a prescriptive types predicate. Returns true iff @var{obj} is an instance of @var{class} or an instance of descendants of @var{class}. @c JP これは規範的な型に関する述語です。 @var{obj}が@var{class}のインスタンスであるか、@var{class}のサブクラスの インスタンスである場合に、真を返します。 @c COMMON @example (is-a? 3 ) @result{} #t (is-a? 3 ) @result{} #t (is-a? 5+3i ) @result{} #f @end example @c EN Note: If @var{obj}'s class has been redefined, @code{is-a?} also triggers instance update. See @ref{Class redefinition} for the details. @c JP 註:@var{obj}のクラスが再定義されていた場合、@code{is-a?}はインスタンスアップデートを トリガします。@ref{Class redefinition}を参照してください。 @c COMMON @end defun @defun of-type? obj type @c EN This is a descriptie type predicate. Returns true iff @var{obj} satisfies the constraints described by @var{type}, which can be either a class (in that case, this is the same as @code{is-a?}), or a descriptive type (@pxref{Type expressions and type constructors} below). @c JP これは記述的な型を調べる述語です。 @var{obj}が@var{type}で記述される制約を満たすなら@code{#t}を、そうでなければ@code{#f}を 返します。@var{type}はクラスか(その場合は@code{is-a?}と同じです)、 記述型 (@pxref{Type expressions and type constructors}参照) です。 @c COMMON @example (of-type? 1 ( )) @result{} #t (of-type? "a" ( )) @result{} #t (of-type? 'a ( )) @result{} #f @end example @end defun @defun subtype? sub super @c EN Returns @code{#t} if a type @var{sub} is a subtype of a type @var{super} (includes the case that @var{sub} is @var{super}). Otherwise, returns @code{#f}. @c JP 型@var{sub}が型@var{super}のサブタイプであれば(@var{sub}と@var{super}が 同じである場合も含め)@code{#t}を、そうでなければ@code{#f}を返します。 @c COMMON @c EN In general, if @var{sub} is a subtype of @var{super}, an object that satisfies the constraints of @var{sub} also satisfies the constraints of @var{super}, so you can use the object where objects of type @var{super} are expected. In other words, @var{sub} is more restrictive than @var{super}. If both @var{sub} and @var{super} are classes, @var{sub} being a subtype of @var{super} means @var{sub} is a subclass of @var{super}. @c JP 一般的に、@var{sub}が@var{super}のサブタイプであれば、 @var{sub}の制約を満たすオブジェクトは@var{super}が期待されている箇所で使うことが できます。言い換えれば、@var{sub}の制約の方が@var{super}よりきついということです。 @var{sub}と@var{super}のどちらもがクラスの場合、@var{sub}が@var{super}の サブタイプであるということは、@var{sub}が@var{super}のサブクラスであるということです。 @c COMMON @example (subtype? ) @result{} #t (subtype? ( )) @result{} #t (subtype? ( ) ( )) @result{} #t @end example @c EN Note that we're not rigorous on this ``substitution principle'', for we don't aim at guaranteeing type safety through static analysis. For example, ``list of integers'' can be used in place of a generic list most of the time, and @code{(subtype? ( ) )} is @code{#t}. However, if list is mutated, you can't replace generic list with a list of integers---because mutators may try to set non-integer in the list. That kind of cases needs to be handled separately, not on relying solely on @code{subtype?}. @c JP この「置換原則」は常に厳密に成り立つわけではないことに注意してください。 例えば「整数のリスト」は大抵の場合、ジェネリックなリストが期待されているところに 使えて、従って@code{(subtype? ( ) )}も@code{#t}を 返します。しかし、渡されたリストが変更される場合は、ジェネリックなリストを 整数のリストで置き換え可能とは限りません。コードはリストに整数でないものをセットしようとする かもしれないからです。こういったケースは@code{subtype?}に頼るのではなく 個別に対応する必要があります。 @c COMMON @end defun @defun type? obj @c EN Returns @code{#t} if @var{obj} is a type (either a class or a descriptive type), @code{#f} otherwise. You can pass objects that returns @code{#t} for this predicate to the second argument of @code{of-type?}, and the first or second argument of @code{subtype?}. @c JP @var{obj}が型(クラスまたは記述型)であれば@code{#t}を、 そうでなければ@code{#f}を返します。 この述語が真を返すオブジェクトは、@code{of-type?}の第二引数、 もしくは@code{subtype?}の引数に渡せます。 @c COMMON @end defun @defun subclass? sub super @c EN Both arguments must be classes. Returns @code{#t} iff @var{sub} is a subclass of @var{super}. A class is regarded as a subclass of itself. @c JP 引数はどちらもクラスでなければなりません。 @var{sub}が@var{super}のサブクラスであれば@code{#t}を、そうでなければ@code{#f}を 返します。クラスはそれ自身のサブクラスとみなされます。 @c COMMON @end defun @node Predefined classes, Type expressions and type constructors, Generic type predicates, Types and classes @subsection Predefined classes @c NODE 定義済みクラス @c EN We'll introduce classes for each built-in type as we go through this chapter. Here are a few basic classes to start with: @c JP 組み込みの型に対応するクラスについては、この章の中で順に紹介してゆきます。 まずは次のいくつかのクラスから始めましょう。 @c COMMON @deftp {Builtin Class} @clindex top @c EN This class represents the supertype of all the types in Gauche. That is, for any class @code{X}, @code{(subtype? X )} is @code{#t}, and for any object @code{x}, @code{(is-a? x )} is @code{#t}. @c JP 全ての型のスーパータイプを表現するクラスです。 つまり、どんなクラス@code{X}に対しても@code{(subtype? X )}は@code{#t}であり、 どんなオブジェクト@code{x}に対しても@code{(is-a? x )}は@code{#t}です。 @c COMMON @end deftp @deftp {Builtin Class} @clindex bottom @c EN This class represents the subtype of all the types in Gauche. For any class @code{X}, @code{(subtype? X)} is @code{#t}, and for any object @code{x}, @code{(is-a? x )} is @code{#f}. @c JP 全ての型のサブタイプを表現するクラスです。 どんなクラス@code{X}に対しても@code{(subtype? X)}は@code{#t}であり、 どんなオブジェクト@code{x}に対しても@code{(is-a? x )}は@code{#f}です。 @c COMMON @c EN There's no instance of @code{}. @c JP @code{}型のインスタンスは存在しません。 @c COMMON @c EN Note: Although @code{} is subtype of other types, the class precedence list (CPL) of @code{} only contains @code{} and @code{}. It's because it isn't always possible to calculate a linear list of all the types. Even if it is possible, it would be expensive to check and update the CPL of @code{} every time a new class is defined or an existing class is redefined. Procedures @code{subtype?} and @code{is-a?} treat @code{} specially. One of use case of @code{} is @code{applicable?} procedure. @xref{Procedure class and applicability}. @c JP 註: @code{}は全ての型のサブタイプですが、そのクラス順位リスト (class precedence list, CPL)には@code{}と@code{} 以外のクラスは含まれていません。全ての型を線形に並べることは常に可能である とは限らず、まだそうであったとしても新たなクラスの定義や既存のクラスの 再定義のたびに@code{}のCPLを検査してアップデートすることは 高くつくでしょう。@code{subtype?}や@code{is-a?}といった手続きは @code{}を特別扱いしています。 @code{}の使いどころのひとつは、@code{applicable?}手続きです。 @ref{Procedure class and applicability}を参照のこと。 @c COMMON @end deftp @deftp {Builtin Class} @clindex object @c EN This class represents a supertype of all user-defined classes. @c JP このクラスは、ユーザ定義されたクラスのスーパータイプを表現するクラスです。 @c COMMON @end deftp @defun class-of obj @c EN Returns a class metaobject of @var{obj}. @c JP @var{obj}のクラスを返します。 @c COMMON @example (class-of 3) @result{} #> (class-of "foo") @result{} #> (class-of ) @result{} #> @end example @c EN Note: In Gauche, you can redefine existing user-defined classes. If the new definition has different configuration of the instance, @code{class-of} on existing instance triggers instance updates; @pxref{Class redefinition} for the details. Using @code{current-class-of} suppresses instance updates (@pxref{Accessing instance}). @c JP 註: Gaucheでは、ユーザ定義クラスを再定義することができます。 新たな定義でインスタンスの構造が変更された場合、以前のクラスから作られた インスタンスに@code{class-of}を適用すると、インスタンスが新しいクラスに 適合するようにアップデートされます。詳しくは@ref{Class redefinition}を参照して ください。インスタンスアップデートを避けるには@code{current-class-of}を 使います(@ref{Accessing instance}参照)。 @c COMMON @end defun @node Type expressions and type constructors, Native types, Predefined classes, Types and classes @subsection Type expressions and type constructors @c NODE 型の式と型コンストラクタ @c EN Types are first-class objects manipulatable at runtime in Gauche, but they must be known at compile-time in order to do optimizations or static analysis. In certain places, Gauche requires the the value of type-yielding expressions to be statically computable. We call such expressions @emph{type expressions}. @c JP 型はGaucheでは実行時に扱える第一級のオブジェクトですが、 静的解析のためにはコンパイル時に型がわかる必要があります。 なので、いくつかの場所では、型を生成する式の値が静的に計算可能であることが要求されます。 そのような式を「型の式 (type expression)」と呼びます。 @c COMMON @c EN A type expression is either a global variable reference that are constantly bound to a type, or a call of type constructor: @c JP 型の式は、型に静的に束縛されたグローバル変数か、型コンストラクタの呼び出しです: @c COMMON @example : | : ( ...) : | | -> | * @end example @c EN All built-in classes, such as @code{}, are statically bound (in precise terms, they are ``inlinable'' binding). If you try to alter it, a warning is issued, and the further bahvior will be undefined. In future, we'll make it an error to alter the binding of global variables bount to types. Classes defined with @code{define-class} and @code{define-record-type} are also bound as inlinable. @c JP @code{}のような全ての組み込みクラスは静的に束縛されています (正確には、「インライン可能な」束縛になっています)。 そのような束縛を変更しようとすると警告が出され、それ以降の動作は保証されません。 将来的には、型に静的に束縛された変数を変更するのはエラーにするつもりです。 @code{define-class}や@code{define-record-type}で定義されるクラスも、 インライン可能な束縛になります。 @c COMMON @c EN Type constructors are special classes whose instances are descriptive types. Type constructors can be invoked as if they are a procedure, but above is recognized by the compiler and the derived type is computed at compile-time. So, at runtime you only see the resulting derived type instance. @c JP 型コンストラクタはそれ自身がクラスで、 そのインスタンスが記述的な型オブジェクトになるものです。 型コンストラクタは構文的には手続き呼び出しのように使えますが、 上のはコンパイラによって認識され、 コンパイル時に計算されて型オブジェクトになります。 なので、ランタイムには結果の型オブジェクトしか見えません。 @c COMMON @c EN For example, @code{} is a type constructor that creates ``maybe''-like type, e.g. ``an integer or @code{#f}''. (Do not confuse this with Maybe type defined in SRFI-189, @pxref{Maybe and Either optional container types}). A type expression @code{( )} yields such type (printed as @code{#>}): @c JP 例えば、@code{}は''maybe''のようなオプショナルな型を作る型コンストラクタです。 @code{( )}は「@code{}か@code{#f}」を意味します (SRFI-189 (@ref{Maybe and Either optional container types}参照) の Maybe型と混同しないようにしてください)。 この型オブジェクトは @code{#>} と表示されます。 @c COMMON @example ( ) @result{} #> @end example @c EN It looks like a procedure call, but it s computed at compile time: @c JP 型コンストラクタの呼び出しは手続き呼び出しのように見えますが、コンパイル時に計算されます。 @c COMMON @example gosh> (disasm (^[] ( ))) CLOSURE # === main_code (name=#f, cc=0x7f5cd76ab540, codevec=...): signatureInfo: ((#f)) 0 CONST-RET #> @end example @deftp {Type Constructor} type @clindex ? @c EN @var{Type} must be a type expression. This creates a maybe-like type, that is, the object is either of @var{type} or @code{#f}. Usually, @code{#f} indicates that the value is invalid (e.g. the return value of @code{assoc}). @c JP @var{type}は型の式でなければなりません。 この型の式はmaybe型に似た型を作ります。オブジェクトは型@var{type}を持つか@code{#f}です。 @code{#f}は通常、それが無効な値であることを示します (例: @code{assoc}の戻り値)。 @c COMMON @c EN This type has ambiguity when @code{#f} can be a meaningful value, but traditionally been used a lot in Scheme, for it is lightweight. We also have a ``proper'' Maybe type in SRFI-189 (@pxref{Maybe and Either optional container types}) but that involves extra allocation to wrap the value. @c JP この型は、@code{#f}が意味を担う場合に曖昧性があるのですが、 軽量であるゆえにSchemeでは伝統的に多用されてきました。 「正しい」MaybeについてはSRFI-189 (@ref{Maybe and Either optional container types}参照) により提供されているのですが、値をラップするごとに新たなアロケーションを必要とします。 @c COMMON @c EN So, those who came from functional programming may find this isn't a right abstraction, but it has its place in the Scheme world. @c JP 関数型言語から来た人には、これは正しい抽象化には見えないかもしれませんが、 Scheme界の中ではそれなりに実用的な型です。 @c COMMON @end deftp @deftp {Type Constructor} type @dots{} @clindex / @c EN @var{Type} @dots{} must be type expressions. This creates a @emph{sum type} of @var{type} @dots{}. For example, @code{( )} is a type that is either a string or a symbol. @c JP @var{type} @dots{} はそれぞれ型の式でなければなりません。 この型コンストラクタは、@var{type} @dots{} の直和型を作ります。 例えば@code{( )}は文字列かシンボルであるような型を表します。 @c COMMON @end deftp @deftp {Type Constructor} type @dots{} @clindex Tuple @c EN @var{Type} @dots{} must be type expressions, except that the last argument that may be an identifier @code{*}. This creates a @emph{product type} of @var{type} @dots{}. @c JP @var{type} @dots{}はそれぞれ型の式でなければなりません。 ただ、最後の要素にはシンボル@code{*}も許されます。 この型コンストラクタは、@var{type} @dots{} の直積型を作ります。 @c COMMON @c EN Actually, this type is looser than the product types in typical statically-typed languages. Our tuple is a subtype of list, with types of each positional element are restricted with @var{type} @dots{}. For example, @code{( )} is a list of two elements, the first one being an integer and the second being a string. @c JP 実のところ、これは静的型付け言語の直積型よりも緩い型です。 Gaucheではタプルはリストのサブタイプで、リストの各位置の要素が 対応する@var{type}で制約されているものです。 例えば@code{( )}は2要素のリストで、 最初が整数、次が文字列であるようなものを表します。 @c COMMON @example (of-type? '(3 "abc") ( )) @result{} #t @end example @c EN If you need a more strict and disjoint product type, you can just create a class or a record. @c JP より厳密な、他の型とは別であるような直積型が必要なら、クラスやレコードを作ってください。 @c COMMON @c EN If the last argument is @code{*}, the resulting type allows extra elements after the typed elements. @c JP 最後の要素が@code{*}である場合、結果の型は、 型が指定された要素のあとに任意個の要素を許します。 @c COMMON @example (of-type? '(3 "abc" 1 2) ( *)) @result{} #t @end example @end deftp @deftp {Type Constructor} <^> type @dots{} @code{->} type @dots{} @clindex ^ @c EN Each @var{type} must be type expressions, except that the one right before @code{->} and the last one may be an identifier @code{*}. This creates a procedure type, with the constraints in arguments and return types. The @var{type} @dots{} before @code{->} are the argument types, and the ones after @code{->} are the result types. @c JP @var{type} @dots{} はそれぞれ型の式でなければなりません。ただし、 @code{->} の直前、および最後の@var{type}は識別子@code{*}も許されます。 この型コンストラクタは引数および戻り値の型を制約する手続き型を作ります。 @code{->} の前の@var{type} @dots{} は引数の型を、 @code{->} の後のは戻り値の型を指定します。 @c COMMON @c EN The @code{*} in the last of argument type list and/or result type list indicates extra elements are allowed. @c JP 引数の型リストの最後に@code{*}がある場合は省略可能な追加の引数を、 戻り値の型リストの最後に@code{*}がある場合は追加の戻り値があることを示します。 @c COMMON @c EN In vanilla Scheme, all procedures belong to just one type, that responds true to @code{procedure?}. It is simple and flexible, but sometimes the resolution is too coarse to do reasoning on the program. @c JP 素のSchemeでは、全ての手続きは(@code{procedure?}が真を返すという意味で) ひとつの型に属しています。これは簡単で柔軟ですが、 プログラムの解析をしたい場合には粗すぎる分類です。 @c COMMON @c EN In Gauche, we can attach more detailed type information in procedures. In the current version, some built-in procedures already have such type information, that can be retrieved with @code{procedure-type}: @c JP Gaucheでは手続きオブジェクトがより詳しい型情報を持てます。 現在のバージョンでは、組み込み手続きの一部に既に詳しい型情報が付加されていて、 @code{procedure-type}によって取り出すことができます。 @c COMMON @example (procedure-type cons) @result{} #<^ -> > @end example @c EN Not all procedures have such information, though. Do not expect the rigorousness of statically typed languages. @c JP ただ、全ての手続きにこの情報が付加されているわけではありません。 静的型付け言語のような厳密さを期待しないでください。 @c COMMON @c EN At this moment, Scheme-defined procedures treats all argument types as @code{}. We'll provide a way to attach type info in future. @c JP 今のところ、Schemeで定義された手続きは全ての引数や戻り値を@code{}型として 扱います。いずれより詳しい型情報を指定できるようにする予定です。 @c COMMON @end deftp @deftp {Type Constructor} type :optional min-length max-length @deftpx {Type Constructor} type :optional min-length max-length @clindex List @clindex Vector @c EN @var{Type} must be a type expression. These create a list or a vector type whose elements are of @var{type}, respectively. For example, @code{( )} is a list of strings. @c JP @var{type}は型の式でなければなりません。 各要素が@var{type}であるようなリストもしくはベクタの型を作ります。 例えば@code{( )}は文字列のリストです。 @c COMMON @c EN The optional arguments must be a literal real numbers that limit the minimum and maximum (inclusive) length of the list or the vector. When omitted, @var{min-length} is zero and @var{max-length} is @code{inf.0}. @c JP 省略可能引数はどちらも実数でなければならず、 それぞれリストやベクタの長さの最小値と最大値(両端含む)を指定します。 省略された場合、@var{min-length}は0、@var{max-length}は無限大です。 @c COMMON @c EN Note: @code{subtype?} uses covariant subtyping, that is, @code{(subtype? ( ) )} is @code{#t}. @c JP 註: @code{subtype?}は共変関係を見ます。つまり、 @code{(subtype? ( ) )}は@code{#t}です。 @c COMMON @end deftp @deftp {Type Constructor} constant @dots{} @clindex Assortment @c EN @var{Constants} must be an expression that evaluates to a symbol, a boolean or a number, at the compile time. This type expression creates a type whose instances are limited to the given constant values. @c JP @var{constants}はコンパイル時にシンボル、真偽値、あるいは数値に評価される式でなければなりません。 この型の式は、与えられた定数のみをインスタンスとみなす記述型を作ります。 @c COMMON @example (define (p obj) (of-type? obj ( 'one 'two 'three))) (p 'one) @result{} #t (p 'three) @result{} #t (p 'four) @result{} #f @end example @c EN Mere membership test can be realized simply with a list or a set, but the construction of assortment type is done in compile-time, and potentially creates opportunities for optimizations or compile-time checks. For example, you can proclaim the argument is only allowed with certain set of symbols: @c JP 単なるメンバシップの検査ならリストやセットでもできますが、 assortment型の生成はコンパイル時に行われ、 最適化やコンパイル時検査の機会を増やします。 例えば、引数が特定のシンボルのいずれかしか取らないことを、次のような形で 宣言しておくことができるでしょう。 @c COMMON @example (define (p obj) (assume-type obj ( 'one 'two 'three)) ...) @end example @c EN Currently, it is only used by a runtime check. However, in futuer version of Gauche, the compiler knows the argument @var{obj} must be one of these symbols, and may use that information for static analysis. @c JP 現在のところこれは実行時チェックに使われるだけですが、 将来のGaucheではコンパイラが、引数はこれらのシンボルしか許されないという情報を 静的解析に利用するかもしれません。 @c COMMON @end deftp @node Native types, , Type expressions and type constructors, Types and classes @subsection Native types @c NODE ネイティブタイプ @c EN Native types are a set of predefined descriptive types that bridge Scheme types and C types. They can be used to access binary blobs passed from a foreign functions, for example. They'll also be used for FFI. @c JP ネイティブタイプは、Schemeの型とCの型の橋渡しをするためにあらかじめ定義されている型です。 外部の関数から渡されたバイナリデータの中身にアクセスする時などに使えます。 将来的にはFFIにも使う予定です。 @c COMMON @c EN An example of native types is @code{}, which corresponds to C's @code{int16_t}. You can use @code{} to check if a Scheme object can be treated as that type: @c JP ネイティブタイプの一例は@code{}です。これはCの@code{int16_t}に相当します。 例えばCの@code{int16_t}としてSchemeオブジェクトを渡せるかどうかを 次のとおり検査できます。 @c COMMON @example (of-type? 357 ) @result{} #t (of-type? 50000 ) @result{} #f @end example @c EN Or obtain size and alignment info on the running platform: @c JP また、実行中のプラットフォームにおけるその型のデータの大きさやアラインメントを知ることもできます。 @c COMMON @example gosh> (describe ) #> is an instance of class slots: name : super : #> c-type-name: "int16_t" size : 2 alignment : 2 @end example @deftp {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @deftpx {Native type} @clindex fixnum @clindex int @clindex int8 @clindex int16 @clindex int32 @clindex int64 @clindex short @clindex long @clindex uint @clindex uint8 @clindex uint16 @clindex uint32 @clindex uint64 @clindex ushort @clindex ulong @clindex float @clindex double @clindex size_t @clindex ssize_t @clindex ptrdiff_t @clindex off_t @clindex void @c EN Predefined native types. The correspondence of Scheme and C types are shown below: @c JP 定義済みのネイティブタイプです。 Cの型との関係は次の表のとおりです。 @c COMMON @example Native type Scheme C Notes ----------------------------------------------------------------- ScmSmallInt Integers within fixnum range int Integers representable in C int8_t int16_t int32_t int64_t short long uint Integers representable in C uint8_t uint16_t uint32_t uint64_t ushort ulong float Unboxed value casted to float double size_t System-dependent types ssize_t ptrdiff_t off_t - void (Used only as a return type. Scheme function returns #) @end example @end deftp @node Equality and comparison, Numbers, Types and classes, Core library @section Equality and comparison @c NODE 等価性と比較 @c EN Comparing two objects seems trivial, but if you look into deeper, there are lots of subtleties hidden in the corners. What should it mean if two procedures are equal to each other? How to order two complex numbers? It all depends on your purpose; there's no single generic answer. So Scheme (and Gauche) provides several options, as well as the way to make your own. @c JP ふたつのオブジェクトを比較するというのは簡単な話のように思えるかもしれません。 しかし詳しく見てゆくと、一筋縄ではいかない特別なケースが出てきます。 ふたつの手続きが等しいとはどういうことでしょうか。 複素数を何らかの基準で順番に並べるにはどうすばいいでしょう。 一般的な回答は無く、目的によるとしか言えません。 そこで、Schemeでは(Gaucheも)、いくつかの選択肢を用意しておき、 さらに必要ならばユーザが独自の定義を与えることもできるようにしています。 @c COMMON @menu * Equality:: * Comparison:: * Hashing:: * Basic comparators:: @end menu @node Equality, Comparison, Equality and comparison, Equality and comparison @subsection Equality @c NODE 等価 @c EN Scheme has three different general equality test predicates. Other than these, some types have their own comparison predicates. @c JP Schemeには等価性を判定する汎用的な述語が3つあります。 また、これらの他に、いくつかの型はその型同士で使える比較手続きを持っています。 @c COMMON @defun eq? obj1 obj2 [R7RS base] @c EN This is the fastest and finest predicate. Returns @code{#t} if @var{obj1} and @var{obj2} are identical objects---that is, if they represents the same object on memory or in a register. Notably, you can compare two symbols or two keywords with @code{eq?} to check if they are the same or not. You can think @code{eq?} as a pointer comparison for any heap-allocated objects. Booleans can be compared with @code{eq?}, but you can't compare characters and numbers reliably---objects with the same numerical value may or may not @code{eq?} to each other. If you identity comparison needs to include those objects, use @code{eqv?} below. @c JP 最も高速で、細かい区別ができる述語です。 @var{obj1}と@var{obj2}が同一(identical)のオブジェクト、 すなわち、メモリ上の同じオブジェクトを表している場合に@code{#t}を返します。 特に、二つのシンボルもしくは二つのキーワードが同一かどうかを比較するのに@code{eq?}が使えます。 ヒープアロケートされるオブジェクトに対しては、ポインタ比較と考えても良いでしょう。 真偽値も@code{eq?}で比較できますが、文字と数値はたとえ値が同じオブジェクトであっても 互いに@code{eq?}になるかどうかはわかりません。 同一性比較で文字や数値も扱う必要がある場合は、下の@code{eqv?}を使いましょう。 @c COMMON @example (eq? #t #t) @result{} #t (eq? #t #f) @result{} #f (eq? 'a 'a) @result{} #t (eq? 'a 'b) @result{} #f (eq? (list 'a) (list 'a)) @result{} #f (let ((x (list 'a))) (eq? x x)) @result{} #t @end example @end defun @defun eqv? obj1 obj2 [R7RS base] @c EN When @var{obj1} and @var{obj2} are both exact or both inexact numbers (except NaN or -0.0), @code{eqv?} returns @code{#t} iff @code{(= @var{obj1} @var{obj2})} is true. -0.0 is only @code{eqv?} to -0.0. @c JP @var{obj1}と@var{obj2}がともに正確な数値、もしくはともに (NaN、-0.0以外の)非正確な数値である場合、 @code{(= @var{obj1} @var{obj2})}が真であれば@code{#t}が、偽であれば@code{#f}が 返されます。 -0.0は-0.0とだけ@code{eqv?}です。 @c COMMON @c EN When @var{obj1} and @var{obj2} are both characters, @code{eqv?} returns @code{#t} iff @code{(char=? @var{obj1} @var{obj2})} is true. Otherwise, @code{eqv?} is the same as @code{eq?} on Gauche. @c JP @var{obj1}と@var{obj2}がともに文字である場合、 @code{(char=? @var{obj1} @var{obj2})}が真であれば@code{#t}が、偽であれば@code{#f}が 返されます。 それ以外の場合は、Gaucheでは@code{eqv?}は@code{eq?}と同じです。 @c COMMON @example (eqv? #\a #\a) @result{} #t (eqv? #\a #\b) @result{} #f (eqv? 1.0 1.0) @result{} #t (eqv? 1 1) @result{} #t (eqv? 1 1.0) @result{} #f (eqv? (list 'a) (list 'a)) @result{} #f (let ((x (list 'a))) (eqv? x x)) @result{} #t @end example @c EN Note that comparison of NaNs has some peculiarity. Any numeric comparison fails if there's at least one NaN in its argument. Therefore, @code{(= +nan.0 +nan.0)} is always @code{#f}. However, Gauche @emph{may} return @code{#t} for @code{(eq? +nan.0 +nan.0)} or @code{(eqv? +nan.0 +nan.0)}. @c JP NaNの比較には少々奇妙なところがあります。数値比較は、引数に一つでもNaNが 含まれていれば失敗します。したがって@code{(= +nan.0 +nan.0)}は常に@code{#f}と なります。けれども、@code{(eq? +nan.0 +nan.0)} や @code{(eqv? +nan.0 +nan.0)}は@code{#t}を返すことがあるかもしれません。 @c COMMON @end defun @defun equal? obj1 obj2 [R7RS+ base] @c EN If @var{obj1} and @var{obj2} are both aggregate types, @code{equal?} compares its elements recursively. Otherwise, @code{equal?} behaves the same as @code{eqv?}. If @var{obj1} and @var{obj2} are not @code{eqv?} to each other, not of builtin types, and the class of both objects are the same, @code{equal?} calls the generic function @code{object-equal?}. By defining the method, users can extend the behavior of @code{equal?} for user-defined classes. @c JP @var{obj1}と@var{obj2}がリストやベクタなどの複合型である場合、 @code{equal?}は再帰的に対応する要素同士を@code{equal?}で比較してゆきます。 そうでなければ、@code{equal?}は@code{eqv?}と同じようにふるまいます。 もし@code{obj1}と@var{obj2}が互いに@code{eqv?}でなく、 組み込み型でもなく、かつ両者のクラスが等しい場合、@code{equal?}は ジェネリックファンクション@code{object-equal?}を呼びます。 @code{object-equal?}にメソッドを定義することにより、 ユーザ定義のデータ型に対する@code{equal?}の振るまいを拡張することができます。 @c COMMON @example (equal? (list 1 2) (list 1 2)) @result{} #t (equal? "abc" "abc") @result{} #t (equal? 100 100) @result{} #t (equal? 100 100.0) @result{} #f @c EN ;; 0.0 and -0.0 is numerically equal (=), but eqv? distingushes them, so as equal?. @c JP ;; 0.0と-0.0は数値としては等しい(=)ですが、eqv?は区別し、したがってequal?も区別します。 @c COMMON (equal? 0.0 -0.0) @result{} #f @end example @c EN Note: This procedure correctly handles the case when both @var{obj1} and @var{obj2} have cycles through pairs and vectors, as required by R6RS and R7RS. However, if the cycle involves user-defined classes, @code{equal?} may fail to terminate. @c JP 註: この手続きは、@var{obj1}と@var{obj2}がともにペアやベクタを介した 循環構造を持っている場合もR6RSやR7RSに規定されるように値を返します。 ただし、循環構造がユーザ定義データ型を間に挟んでいる場合は 終了しない可能性があります。 @c COMMON @end defun @deffn {Generic Function} object-equal? obj1 obj2 @c EN This generic function is called when @code{equal?} is called on the objects it doesn't know about. You can define this method on your class so that @code{equal?} can check equivalence. This method is supposed to return @code{#t} if @var{obj1} is equal to @var{obj2}, @code{#f} otherwise. If you want to check equivalence of elements recursively, do not call @code{object-equal?} directly; call @code{equal?} on each element. @c JP @code{equal?}が未知のオブジェクトに対して呼ばれた場合、 このジェネリックファンクションが呼ばれます。自分で定義したクラスに対して このメソッドを定義することにより、@code{equal?}で等価判定が行えるように なります。メソッドは、@var{obj1}と@var{obj2}が等価ならば@code{#t}を、 そうでなければ@code{#f}を返さねばなりません。 オブジェクトの各要素に対して再帰的に等価判定を行いたい場合は、 @code{object-equal?}を直接呼ぶのではなく、@code{equal?}を各要素に対して 呼ぶようにして下さい。 @c COMMON @example (define-class () ((x :init-keyword :x) (y :init-keyword :y))) (define-method object-equal? ((a ) (b )) (and (equal? (slot-ref a 'x) (slot-ref b 'x)) (equal? (slot-ref a 'y) (slot-ref b 'y)))) (equal? (make :x 1 :y (list 'a 'b)) (make :x 1 :y (list 'a 'b))) @result{} #t (equal? (make :x 1 :y (make :x 3 :y 4)) (make :x 1 :y (make :x 3 :y 4))) @result{} #t @end example @end deffn @deffn {Method} object-equal? (obj1 ) (obj2 ) @c EN This method catches @code{equal?} between two objects of a user-defined class, in case the user doesn't define a specialized method for the class. When called, it scans the registered default comparators that can handle both @var{obj1} and @var{obj2}, and if it finds one, use the comparator's equality predicate to see if two arguments are equal to each other. When no matching comparators are found, it just returns @code{#f}. @xref{Predefined comparators}, about the default comparators: Look for the entries of @code{default-comparator} and @code{comparator-register-default!}. Note: If you define @code{object-equal?} with exactly the same specializers of this method, you'll replace it and that breaks @code{default-comparator} operation. Future versions of Gauche will prohibit such redefinition. For now, be careful not to redefine it accidentally. @c JP このメソッドは、ユーザ定義クラスの2つのインスタンスが@code{equal?}であるかを 調べる際に、そのクラスに特殊化したメソッドが無かった場合を捕まえるものです。 このメソッドが呼ばれると、まず登録されたデフォルト比較器の中に@var{obj1}と @var{obj2}を共に処理できるものがあるかどうかを調べ、 あればその比較器の等価述語を使って比較します。デフォルト比較器が引数を処理できなければ @code{#f}を返します。デフォルト比較器については @ref{Predefined comparators}を参照してください。特に @code{default-comparator}と@code{comparator-register-default!}の 項目を見てください。 註: もし、このメソッドと全く同じスペシャライザを 指定して@code{object-equal?}メソッドを定義すると、それはこのメソッドを 置き換えることになり、@code{default-comparator}の動作が壊れることになります。 将来のGaucheのバージョンではそのような再定義は禁止される予定です。 うっかりそういう再定義を行わないように気をつけてください。 @c COMMON @end deffn @c EN Sometimes you want to test if two aggregate structures are topologically equal, i.e., if one has a shared substructure, the other has a shared substructure in the same way. @code{Equal?} can't handle it; module @code{util.isomorph} provides a procedure @code{isomorphic?} which does the job (@pxref{Determine isomorphism}). @c JP しばしば、ふたつの複合型オブジェクトに関して、両者がトポロジー的に等しいこと、 すなわち一方が共有する部分構造を持っている場合にもう一方も同じように部分構造を 共有しているかどうかを調べたいことがあります。@code{equal?}はその目的には 使えません。モジュール@code{util.isomorph}の提供する@code{isomorphic?}が その目的に使えます。(@ref{Determine isomorphism}参照)。 @c COMMON @node Comparison, Hashing, Equality, Equality and comparison @subsection Comparison @c NODE 比較 @c EN Equality only concern about whether two objects are equivalent or not. However, sometimes we want to see the order among objects. Again, there's no single ``universal order''. It doesn't make mathematical sense to ask if one complex number is greater than another, but having some artificial order is useful when you want a consistent result of sorting a list of objects including numbers. @c JP 等価性はオブジェクトが等しいかどうかしか判断しませんが、しばしば オブジェクトの順序関係を調べたい場合もあります。 ここでも、唯一の「万能順序」があるわけではありません。例えばある複素数が 別の複素数より大きいか小さいかというのは数学的には意味をなしませんが、 数値を含むオブジェクトのリストをソートして一貫性のある結果を得たい場合は 何らかの適当な順序づけを決めておくことは役に立ちます。 @c COMMON @defun compare obj1 obj2 @c EN A general comparison procedure. Returns -1 if @var{obj1} is less than @var{obj2}, 0 if @var{obj1} is equal to @var{obj2}, and 1 if @var{obj1} is greater than @var{obj2}. @c JP 一般的な比較手続きです。@var{obj1}が@var{obj2}より小さければ-1を、 等しければ0を、大きければ1を返します。 @c COMMON @c EN If @var{obj1} and @var{obj2} are incomparable, an error is signalled. However, @code{compare} defines total order between most Scheme objects, so that you can use it on wide variety of objects. The definition is upper-compatible to the order defined in SRFI-114. @c JP @var{obj1}と@var{obj2}が比較できない場合はエラーとなりますが、 @code{compare}は多くのSchemeオブジェクト間に全順序を定義しているので、 様々なオブジェクトの比較に使うことができます。この全順序は、 SRFI-114で定義されているものの上位互換です。 @c COMMON @c EN Some built-in types are handled by this procedure reflecting ``natural'' order of comparison if any (e.g. real numbers are compared by numeric values, characters are compared by @code{char<} etc.) For convenience, it also defines superficial order between objects that doesn't have natural order; complex numbers are ordered first by their real part, then their imaginary part, for example. That is, @code{1+i} comes before @code{2-i}, which comes before @code{2}, which comes before @code{2+i}. @c JP 組み込みオブジェクトのうち、自然な順序が定義されているものはそれに従って順序づけられます (例えば実数はその数値の大小で、文字は@code{char<}等を使って比較されます)。 また便宜上、通常の意味で大小が定義されないオブジェクトについても ある程度表面的な順序が定義されます。例えば複素数は、まず実部の大小によって 順序づけられ、次に虚部の大小によって順序づけられます。 すなわち、@code{1+i}、@code{2-i}、@code{2}、@code{2+i}はこの順番に並びます。 @c COMMON @c EN Boolean false comes before boolean true. @c JP @code{#f}は@code{#t}より前に来ます。 @c COMMON @c EN Lists are ordered by dictionary order: Take the common prefix. If either one is @code{()} and the other is not, @code{()} comes first. If both tails are not empty, compare the heads of the tails. (This makes empty list the ``smallest'' of all lists). @c JP リストは辞書順で比較されます。すなわち、まず共通のプリフィクスを除きます。 一方が@code{()}でもう一方がそうでなければ、@code{()}である方が先にきます。 どちらの尾部も空でなければ、尾部の先頭要素同士を比べます。 (この定義により、空リストは全てのリストの「最小」のものになります)。 @c COMMON @c EN Vectors (including uniform vectors) are compared first by their lengths, and if they are the same, elements are compared from left to right. Note that it's different from lists and strings. @c JP (ユニフォームベクタを含む)ベクタは、まず長さで比較され、 長さが同じ場合は要素同士が左から比較されます。 リストや文字列とは異なることに注意。 @c COMMON @example (compare '(1 2 3) '(1 3)) @result{} -1 ; (1 2 3) is smaller (compare '#(1 2 3) '#(1 3)) @result{} 1 ; #(1 3) is smaller (compare "123" "13") @result{} -1 ; "123" is smaller @end example @c EN If two objects are of subclasses of @code{}, a generic function @code{object-compare} is called. @c JP 二つのオブジェクトがともに@code{}のサブクラスであれば、 ジェネリックファンクション@code{object-compare}が呼ばれます。 @c COMMON @c EN If two objects are of different types and at least one of them isn't @code{}, then they are ordered by their types. SRFI-114 defines the order of builtin types as follows: @c JP 二つのオブジェクトが異なる型で、少なくとも一方が@code{}でない時は、 両者の型により順序が決まります。SRFI-114は組み込み型について 次の順序を定めています。 @c COMMON @enumerate @item Empty list. @item Pairs. @item Booleans. @item Characters. @item Strings. @item Symbols. @item Numbers. @item Vectors. @item Uniform vectors (u8 < s8 < u16 < s16 < u32 < s32 < u64 < s64 < f16 < f32 < f64) @item @c EN All other objects. @c JP 他のオブジェクトすべて @c COMMON @end enumerate @end defun @deffn {Generic Function} object-compare obj1 obj2 @c EN Specializing this generic function extends @code{compare} procedure for user-defined classes. This method must return either @code{-1} (@var{obj1} precedes @var{obj2}), @code{0} (@var{obj1} equals to @var{obj2}), @code{1} (@var{obj1} succeeds @var{obj2}), or @code{#f} (@var{obj1} and @var{obj2} cannot be ordered). @c JP このジェネリックファンクションを特殊化することで @code{compare}手続きをユーザ定義クラスに対して動作するように拡張できます。 このメソッドは以下のいずれかの値を返さねばなりません。 @code{-1} (@var{obj1}は@var{obj2}より前)、 @code{0} (@var{obj1}と@var{obj2}は等しい)、 @code{1} (@var{obj1}は@var{obj2}より後)、 @code{#f} (@var{obj1}と@var{obj2}は順序づけできない)。 @c COMMON @end deffn @deffn {Method} object-compare (obj1 ) (obj2 ) @c EN This method catches @code{compare} between two objects of a user-defined class, in case the user doesn't define a specialized method for the class. When called, it scans the registered default comparators that can handle both @var{obj1} and @var{obj2}, and if it finds one, use the comparator's compare procedure to determine the order of @var{obj1} and @var{obj2}. When no matching comparators are found, it returns @code{#f}, meaning two objects can't be ordered. @xref{Predefined comparators}, about the default comparators: Look for the entries of @code{default-comparator} and @code{comparator-register-default!}. Note: If you define @code{object-compare} with exactly the same specializers of this method, you'll replace it and that breaks @code{default-comparator} operation. Future versions of Gauche will prohibit such redefinition. For now, be careful not to redefine it accidentally. @c JP このメソッドは、ユーザ定義クラスの2つのインスタンスを@code{compare}する 際に、そのクラスに特殊化したメソッドが無かった場合を捕まえるものです。 このメソッドが呼ばれると、まず登録されたデフォルト比較器の中に@var{obj1}と @var{obj2}を共に処理できるものがあるかどうかを調べ、 あればその比較器の比較手続きを使って両者の順序を判定します。 デフォルト比較器が引数を処理できなければ @code{#f}(「比較できない」)を返します。デフォルト比較器については @ref{Predefined comparators}を参照してください。特に @code{default-comparator}と@code{comparator-register-default!}の 項目を見てください。 註: もし、このメソッドと全く同じスペシャライザを 指定して@code{object-compare}メソッドを定義すると、それはこのメソッドを 置き換えることになり、@code{default-comparator}の動作が壊れることになります。 将来のGaucheのバージョンではそのような再定義は禁止される予定です。 うっかりそういう再定義を行わないように気をつけてください。 @c COMMON @end deffn @defun eq-compare obj1 obj2 @c EN Returns -1 (less than), 0 (equal to) or 1 (greater than) according to a certain total ordering of @var{obj1} and @var{obj2}. Both arguments can be any Scheme objects, and can be different type of objects. The following properties are guaranteed. @itemize @bullet @item @code{(eq-compare x y)} is 0 iff @code{(eq? x y)} is @code{#t}. @item The result is consistent within a single run of the process (but may differ between runs). @end itemize Other than these, no actual semantics are given to the ordering. This procedure is useful when you need to order arbitrary Scheme objects, but you don't care the actual order as far as it's consistent. @c JP とある全順序に従って@var{obj1}と@var{obj2}を比較し、前者が小さければ-1、 等しければ0、前者が大きければ1を返します。@var{obj1}と@var{obj2}は どんなSchemeオブジェクトでも良く、また型が違っていても構いません。 次の二つの性質が保証されます。 @itemize @bullet @item @code{(eq? x y)}が@code{#t}なら、そしてその時に限り、 @code{(eq-compare x y)}は0。 @item 結果は、一回のプロセスの実行中で一貫している (ただし、別のプロセスの実行では異なる結果を返すかもしれない)。 @end itemize これらの性質以外には、順序についていかなる意味もありません。 この手続きは、任意のSchemeオブジェクトをとにかく順序づけたい (一貫してさえいれば、実際の順序は何でも良い)、という場合に使います。 @c COMMON @end defun @node Hashing, Basic comparators, Comparison, Equality and comparison @subsection Hashing @c NODE ハッシュ @c EN Hash functions have close relationship with equality predicate, so we list them here. @c JP ハッシュ関数は等価判定述語と関係が深いので、ここで説明します。 @c COMMON @defun eq-hash obj @defunx eqv-hash obj @c EN These are hash functions suitable to be used with @code{eq?} and @code{eqv?}, respectively. The returned hash value is system- and process-dependent, and can't be carried over the boundary of the running process. Note: don't hash numbers by @code{eq-hash}. Two numbers are not guaranteed to be @code{eq?} even if they are numerically equal. @c JP この2つはそれぞれ@code{eq?}および @code{eqv?}と一緒に使うのに適した ハッシュ関数です。返り値のハッシュ値は、 システムおよびプロセスに依存する値です。動作しているプロセスの境界を 超えてもちまわることはできません。 注意: @code{eq-hash} をつかって、数をハッシュしてはいけません。 2つの数はたとえその値が等しくても @code{eq?} であることは保証されて いません。 @c COMMON @end defun @defun default-hash obj [R7RS+ comparator] @c EN This is a hash function suitable to be used with @code{equal?}. In R7RS, this is defined in @code{scheme.comparator} (originally in @code{srfi.128}). If @var{obj} is either a number, a boolean, a character, a symbol, a keyword, a string, a list, a vector or a uniform vector, internal hash function is used to calculate the hash value. If @var{obj} is other than that, a generic function @code{object-hash} is called to calculate the hash value (see below). The hash value also depends on @code{hash-salt}, which differs for every run of the process. @c JP @code{equal?}と一緒に使うのに適したハッシュ関数です。 R7RSでは、@code{scheme.comparator}ライブラリで定義されています (元は@code{srfi.128})。 @var{obj} が、数値、真理値、文字、シンボル、キーワード、文字列、リスト、 ベクタ、ユニフォームベクタのいずれかならば、そのハッシュ値を求めるのには内部ハッシュ関数を 使います。 @var{obj} が、それ以外であれば、 @code{hash} は総称関数 @code{object-hash} を呼んで、そのハッシュ値を計算します。 返されるハッシュ値は@code{hash-salt}の値にも依存します。@code{hash-salt} はプロセスが走る度に異なる値をとります。 @c COMMON @end defun @defun portable-hash obj salt @c EN Sometimes you need to calculate a hash value that's ``portable'', in a sense that the value won't change across multiple runs of the process, nor between different platforms. Such hash value can be used with storing objects externally to share among processes. This procedure calculates a hash value of @var{obj} with such characteristics; the hash value is the same for the same object and the same salt value. Here ``same object'' roughly means having the same external representation. Objects @code{equal?} to each other are same. If you write out an object with @code{write}, and read it back, they are also the same objects in this sense. This means objects without read/write invariance, such as ports, can't be handled with @code{portable-hash}. It is caller's responsibility that @var{obj} won't contain such objects. The @var{salt} argument is a nonnegative fixnum and gives variations in the hash function. You have to use the same salt to get consistent results. If @var{obj} is other than a number, a boolean, a character, a symbol, a keyword, a string, a list, a vector, or a uniform vector, this procedure calls a generic function @code{object-hash} is called to calculate the hash value (see below). @c JP 時に、「ポータブル」なハッシュ値が必要になることがあります。ここでポータブルとは、 プロセスを何度実行しても、また異なるプラットフォームで実行しても、同じオブジェクト に対して常に同じ値となることです。そのようなハッシュ値は、 プロセスの外に保存したり他のプロセスと共有するオブジェクトと一緒に使えます。 この手続きは@var{obj}についてその性質を持つハッシュ値を計算して返します。 つまり、同じオブジェクトと同じソルト値が渡されれば同じハッシュ値となる、ということです。 ここで、「同じオブジェクト」とは、だいたい外部表現が同じになるものと 考えて構いません。@code{equal?}であるもの同士は同じです。 また、オブジェクトを@code{write}で書き出して@code{read}で読み込んだものは 元のオブジェクトと同じになります。 このことから、read/write不変性をもたないオブジェクトは@code{portable-hash} では扱えません。@var{obj}がそのようなオブジェクトを含まないことは 呼び出し側で保証する必要があります。 @var{salt}は非負のfixnumで、ハッシュ関数に変化をつけます。一貫した結果を 得るには同じソルト値を使わなければなりません。 @var{obj}が数値、真理値、文字、シンボル、キーワード、文字列、リスト、 ベクタ、ユニフォームベクタのいずれでもない場合、ハッシュ値を計算するのに 総称関数 @code{object-hash}が呼ばれます。 @c COMMON @end defun @defun legacy-hash obj @c EN Up to 0.9.4, Gauche had a hash function called @code{hash} that was used in both @code{equal?}-hashtable @emph{and} for the portable hash function. It had a problem, though. @c JP バージョン0.9.4まで、Gaucheでは@code{hash}と呼ばれるハッシュ関数が @code{equal?}ハッシュテーブル用のハッシュ計算と ポータブルなハッシュ値の計算の両方を兼ねていました。 しかしそれには問題がありました。 @c COMMON @enumerate @item @c EN There was no way to salt the hash function, which makes the hashtables storing externally provided data vulnerable to collision attack. @c JP ハッシュ関数にソルトを与えることができなかったため、 外部からのデータによる衝突攻撃が可能だった @c COMMON @item @c EN The hash function behaves poorly, especially on flonums. @c JP ハッシュ関数自体があまり良くなかった(特に浮動小数点数) @c COMMON @item @c EN There are bugs in bignum and flonum hashing code that have produced different results on different architectures. @c JP 多倍長整数と浮動小数点数のハッシュ値計算で、 異なるアーキテクチャで異なる値を返してしまうバグがあった。 @c COMMON @end enumerate @c EN Since there are existing hash values calculated with the old hash function, we preserve the behavior of the original @code{hash} function as @code{legacy-hash}. Use this when you need to access old data. (The @code{hash} function also behaves as @code{legacy-hash} by default, but it has tweaks; see below.) @c JP 既に@code{hash}で計算されたハッシュ値を利用しているデータがあるため、 以前の@code{hash}で提供していたハッシュ関数を@code{legacy-hash}として 保存することにしました。古いデータにアクセスする場合に使ってください。 (@code{hash}関数自体もデフォルトでは @code{legacy-hash}と同様に振る舞いますが、ちょっとした仕掛けがあります。 下の説明を参照)。 @c COMMON @c EN The new code that needs portable hash value should use @code{portable-hash} instead. @c JP 新たに書くコードでポータブルなハッシュ値が必要なら @code{portable-hash}を使ってください。 @c COMMON @end defun @deffn {Generic Function} object-hash obj rec-hash @c EN By defining a method for this generic function, objects of user-defined types can have a hash value and can be used in a @code{equal?} hash table. The method has to return an exact non-negative integer, and must return the same value for two object which are @code{equal?}. Furthermore, the returned value must not rely on the platform or state of the process, if @var{obj} is a portable object (see @code{portable-hash} above for what is portable.) If the method needs to get hash value of @var{obj}'s elements, it has to call @var{rec-hash} on them. It guarantees that the proper hash function is called recursively. So you can count on @var{rec-hash} to calculate a portable hash value when @code{object-hash} itself is called from @code{portable-hash}. If @var{obj} has several elements, you can call @code{combine-hash-value} on the elements' hash values. @c JP この総称関数に対するメソッドを定義することにより、ユーザ定義された 型のオブジェクトはハッシュ値を持つことができ、@code{equal?}型のハッシュ テーブルで利用できるようになります。 メソッドは正確な非負整数を返さなければなりません。また、 互いに@code{equal?}であるオブジェクト同士に対しては同じハッシュ値を 返さなければなりません。 さらに、@var{obj}がポータブル(「ポータブル」の意味については 上の@code{portable-hash}の説明を参照)の場合には、 ハッシュ値は実行中のプラットフォームやプロセスの状態に依存してはなりません。 メソッドが @var{obj} の要素のハッシュ値を必要とする場合には、 それらに対して、@var{rec-hash}を呼び出してください。そうすれば 適切なハッシュ関数が再帰的に呼び出されます。例えば@code{object-hash}が @code{portable-hash}経由で呼び出されている場合、 @var{rec-hash}を呼べば同じソルト値でポータブルなハッシュ値が計算されます。 @var{obj}がいくつかの要素を持っている場合、各要素のハッシュ値を まとめるには@code{combine-hash-value}を呼びます。 @c COMMON @example (define-class () (x y)) ;; user-defined equality function (define-method object-equal? ((a ) (b )) (and (equal? (ref a 'x) (ref b 'x)) (= (abs (ref a 'y)) (abs (ref b 'y))))) ;; user-defined hash function (define-method object-hash ((a ) rec-hash) (combine-hash-value (rec-hash (ref a 'x)) (rec-hash (abs (ref a 'y))))) @end example @c EN Note: The base method of @code{object-hash} hashes any object to a single hash value (the actual value depends on @code{hash-salt} if @code{object-hash} is called from @code{default-hash}, and a fixed constant value otherwise. It's because object's equality semantics can be customized separately, and we can't compute a non-constant hash value without knowing the equality semantics. This behavior is the last ``safety net''; in general, you should define @code{object-hash} method on your class if the instances of your class can ever be hashed. @c JP 註: @code{object-hash}のベースメソッドは、どんな引数に対しても 単一の値を返します (具体的な値は、@code{object-hash}が @code{default-hash}から呼ばれた場合は@code{hash-salt}に依存します。 それ以外の場合は固定値です)。 これは、オブジェクトの等価性が自由に設定できるからで、 等価性を知らずに意味のあるハッシュ値を計算できないあらです。 この振る舞いは最後の安全ネットと考えるべきで、一般には自分で定義したクラスのインスタンスが ハッシュされる可能性があるなら、必ず@code{object-hash}メソッドを定義するように してください。 @c COMMON @end deffn @deffn {Method} object-hash (obj ) rec-hash @deffnx {Method} object-hash (obj ) @c EN These two methods are defined by the system and ensures the backward compatibility and the behavior of @code{default-comparator}. Be careful not to replace these methods by defining the exactly same specializers. In future versions of Gauche, attempts to replace these methods will raise an error. @c JP これら二つのメソッドはシステムで定義されており、 後方互換性および@code{default-comparator}の正しい振る舞いを保証しています。 全く同じスペシャライザを持つメソッドを定義することでこれらを置き換えてしまわないように 注意してください。将来のバージョンでは、これらのメソッドを置き換えるのは エラーになる予定です。 @c COMMON @end deffn @defun combine-hash-value ha hb @c EN Returns a hash value which is a combination of two hash values, @var{ha} and @var{hb}. The guaranteed invariance is that if @code{(= ha1 ha2)} and @code{(= hb1 hb2)} then @code{(= (combine-hash-value ha1 hb1) (combine-hash-value ha2 hb2))}. This is useful to write user-defined @code{object-hash} method. @c JP 二つのハッシュ値@var{ha}と@var{hb}を組み合わせたハッシュ値を返します。 次の性質が保証されます:@code{(= ha1 ha2)} かつ @code{(= hb1 hb2)} ならば @code{(= (combine-hash-value ha1 hb1) (combine-hash-value ha2 hb2))}。 これはユーザ定義の@code{object-hash}メソッドを書くのに便利です。 @c COMMON @end defun @defun hash obj @c EN This function is deprecated. Calculate a hash value of @var{obj} suitable for @code{equal?} hash. By default, it returns the same value as @code{legacy-hash}. However, if this is called from @code{default-hash} or @code{portable-hash} (via @code{object-hash} method), it recurses to the calling hash function. The behavior is to keep the legacy code work. Until 0.9.5, @code{hash} is the only hash function to be used for both portable hash and @code{equal?}-hash, and @code{object-hash} method takes single argument (an object to hash) and calls @code{hash} recursively whenever it needs to get a hash value of other objects pointed from the argument. As of 0.9.5 we have more than one hash functions that calls @code{object-hash}, so the method takes the hash function as the second argument to recurse. However, we can't just break the legacy code; so there's a default method defined in @code{object-hash} which is invoked when no two-arg method is defined for the given object, and dispatches to one-arg method. As far as the legacy @code{object-hash} code calls @code{hash}, it calls proper function. The new code shouldn't rely on this behavior, and must use the second argument of @code{object-hash} instead. @c JP この関数は非推奨となりました。 @code{equal?}ハッシュとして使える、@var{obj}のハッシュ値を返します。 デフォルトでは、この関数は@code{legacy-hash}と同じ値を返します。 しかし、この関数が@code{default-hash}か@code{portable-hash}から (@code{object-hash}を経由して)呼ばれた場合は、呼び出したハッシュ関数へと 再帰します。 この振る舞いは既存のコードを動かすためのものです。0.9.5より前は、 @code{hash}が、ポータブルなハッシュ値にも@code{equal?}ハッシュテーブルにも 使えるハッシュ値を計算する唯一の関数でした。@code{object-hash}メソッドは ハッシュ値を計算したいオブジェクトだけを引数に取り、もしそのオブジェクトが 指す他のオブジェクトのハッシュ値が欲しいなら、@code{hash}を再帰呼び出ししていました。 0.9.5から、@code{object-hash}はいくつかのハッシュ関数から呼び出されるようになり、 第2引数に再帰すべきハッシュ関数を取るようになりました。 けれども既存のコードを動かなくしてしまうわけにはいきません。そこで、 @code{object-hash}のデフォルトメソッド(2引数でマッチするメソッドが 無い場合に呼ばれるもの)が、1引数の@code{object-hash}を呼び出すように 定義されています。既存の@code{object-hash}が@code{hash}を呼び出していれば、 正しいハッシュ関数へと再帰するというわけです。 新たに書くコードはこの振る舞いに依存してはいけません。 2引数の@code{object-hash}メソッドを定義してください。 @c COMMON @end defun @defun boolean-hash bool @defunx char-hash char @defunx char-ci-hash char @defunx string-hash str @defunx string-ci-hash str @defunx symbol-hash sym @defunx number-hash num [R7RS comparator] @c EN These are hash functions for specific type of objects, defined in R7RS @code{scheme.comparator}. In Gauche, these procedures are just a wrapper of @code{default-hash} with type checks (and case folding when relevant). These are mainly provided to conform @code{scheme.comparator}; in your code you might just want to use @code{default-hash} (or @code{eq-hash}/@code{eqv-hash}, depending on the equality predicate). @c JP これらは、R7RSの@code{scheme.comparator}で定義された、 特定の型のオブジェクト専用のハッシュ関数です。 Gaucheでは、これらの関数は単に引数の型チェックをして(必要なら大文字小文字の 区別をなくした後)、組み込みの@code{default-hash}を呼び出しているだけです。 これらは@code{scheme.comparator}で定義されているために提供されていますが、 特にポータビリティが必要でなければ@code{default-hash} (あるいは、等価述語によっては@code{eq-hash}や @code{eqv-hash})を呼んでしまう方が簡単だし高速です。 @c COMMON @c EN The case-folding versions, @code{char-ci-hash} and @code{string-ci-hash}, calls @code{char-foldcase} and @code{string-foldcase} respectively, on the argument before passing it to @code{hash}. (@xref{Characters}, for @code{char-foldcase}. @xref{Full string case conversion}, for @code{string-foldcase}). @c JP 大文字小文字を区別しない、@code{char-ci-hash}および@code{string-ci-hash}は、 引数にそれぞれ@code{char-foldcase}と@code{string-foldcase}を適用してから @code{hash}に渡します。 (@code{char-foldcase}については@ref{Characters}を、 @code{string-foldcase}については@ref{Full string case conversion}を 参照してください。) @c COMMON @end defun @defun hash-bound @defunx hash-salt [R7RS comparator] @c EN Both evaluates to an exact nonnegative integers. In R7RS, these are defined in @code{scheme.comparator}. (Note: @code{scheme.comparator} defines these as macros, in order to allow implementations optimize runtime overhead. In Gauche we use procedures but the overhead is negligible.) User-defined hash functions can limit the range of the result between 0 and @code{(hash-bound)}, respectively, without worrying to lose quality of hash function. (User-defined hash functions don't need to honor @code{(hash-bound)} at all; hashtables takes modulo when necessary.) User-defined hash function can also take into account of the value @code{(hash-salt)} into hash calculation; the salt value may differ between runs of the Scheme processes, or even between hash table instances. It is to avoid collision attack. Built-in hash functions already takes the salt value into account, so if your hash function is combining the hash values of primitive types, you don't need to worry about salt values. @c JP どちらも、正確な非負整数へと展開されます。R7RSでは、 @code{scheme.comparator}ライブラリで定義されています。 (註: @code{scheme.comparator}はこれらをマクロと定義しています。処理系が ランタイムオーバヘッドを避けられるようにするためです。 Gaucheでは、呼び出しのオーバヘッドはそれほど問題にならないという 立場から、どちらも手続きにしています。) ユーザ定義のハッシュ関数は、 結果を0と@code{(hash-bound)}の間に限定してもハッシュの質を落とさないことが 保証されます。(ユーザ定義のハッシュ関数は@code{(hash-bound)}を気にする 必要はありません。ハッシュテーブルが必要な時にモジュロを取ります)。 ユーザ定義のハッシュ関数はまた、@code{(hash-salt)}を計算に組み入れることが できます。展開されるソルト値は、Schemeプロセスの実行ごとに異なる値を 取ったり、ハッシュテーブルごとに異なる値を取るかもしれません。 これは、コリジョン攻撃を回避するためのものです。 組み込みのハッシュ関数は既にソルト値を考慮しているので、 ユーザ定義ハッシュ関数がプリミティブ型のハッシュ値を組み合わせるだけの 場合は、ソルト値を気にする必要はありません。 @c COMMON @end defun @node Basic comparators, , Hashing, Equality and comparison @subsection Basic comparators @c NODE 基本的な比較器 @c EN Equality and comparison procedures are parameters in various data structures. A treemap needs to order its keys; a hashtable needs to see if the keys are the same or not, and it also need a hash function consistent with the equality predicate. @c JP 等価性判定と大小比較は色々なデータ構造のパラメータになっています。 treemapはキーの大小を比較します。ハッシュテーブルはキーが等しいかどうかを調べ、 またハッシュ関数と等価性判定に一貫性が無ければなりません。 @c COMMON @c EN If we want to work on generic data structures, we need to abstract those variations of comparison schemes. So here comes the comparator, a record that bundles closely-related comparison procedures together. @c JP ジェネリックなデータ構造を作りたければ、こういった比較についてのバリエーションを 抽象化する必要があります。そのために導入されたのが比較器(comparator)です。 これは、比較について関係の深いいくつかの手続きをまとめた構造体です。 @c COMMON @c EN There are two SRFIs that define comparators. The one that was originally called SRFI-128 has now become a part of R7RS large as @code{scheme.comparator}, and we recommend new code to use it. Gauche has all of @code{scheme.comparator} procedures built-in. The older, and rather complex one is SRFI-114; Gauche also supports it mainly for the backward compatibility. Importantly, Gauche's native @code{} object is compatible to both @code{scheme.comparator} and @code{srfi-114} comparators. @c JP 比較器を定義したSRFIは二つあります。SRFI-128と呼ばれていた規格は R7RS largeに取り込まれ、@code{scheme.comparator}になりました。 新しいコードではそちらを使うべきです。 Gaucheは@code{scheme.comparator}のAPIを全て組み込みで提供します。 古く、より複雑なのがSRFI-114で、Gaucheはそちらは主に後方互換性のために サポートしています。重要なのは、Gaucheの組み込みの@code{}オブジェクトは @code{scheme.comparator}の比較器としても SRFI-114の比較器としても使えるということです。 @c COMMON @menu * Comparator class and constructors:: * Comparator predicates and accessors:: * Predefined comparators:: * Combining comparators:: @end menu @node Comparator class and constructors, Comparator predicates and accessors, Basic comparators, Basic comparators @subsubsection Comparator class and constructors @c NODE 比較器クラスとコンストラクタ @deftp {Builtin Class} @c EN A comparator record that bundles the following procedures: @c JP 以下の手続きをひとまとめにするレコードです。 @c COMMON @c EN @table @emph @item Type test predicate Checks if an object can be compared with this comparator. @item Equality predicate See if given two objects are equal to each other; returns a boolean value. @item Ordering predicate Compare given two objects, and returns true iff the first one is strictly precedes the second one. That is, this is a less-than predicate. @item Comparison procedure Compare given two objects, and returns either -1 (the first one is less than the second), 0 (they are equal), or 1 (the first one is greater than the second). @item Hash function Returns a hash value of the given object. @end table @c JP @table @emph @item 型検査述語 オブジェクトがこの比較器によって扱えるかどうかを調べます。 @item 等価述語 二つのオブジェクトが等価かどうかを判定し、等価なら@code{#t}を、そうでなければ@code{#f} を返します。 @item 順序手続き 二つのオブジェクトの大小関係を判定し、 最初のオブジェクトが二つ目のオブジェクトより小さければ@code{#t}を、 そうでなければ@code{#f}を返します。 @item 比較手続き 二つのオブジェクトの大小関係を判定し、 最初のオブジェクトの方が小さければ-1を、 二つが等しければ0を、 最初のオブジェクトの方が大きければ1を返します。 @item ハッシュ関数 オブジェクトのハッシュ値を返します。 @end table @c COMMON @c EN @code{Scheme.comparator}'s comparators use the ordering predicate, while SRFI-114 comparators use the comparison procedure. Gauche's @code{} supports both by automatically generating the missing one; that is, if you create a comparator with @code{scheme.comparator} interface, by giving an ordering predicate, Gauche automatically fills the comparison procedure, and if you create one with SRFI-114 interface by giving a comparison procedure, Gauche generates the ordering predicate. @c JP @code{scheme.comparator}の比較器は順序手続きを使い、 SRFI-114の比較器は比較手続きを使います。 Gaucheの@code{}は両方をサポートするために、 自動的に欠けている手続きを補います。 つまり、順序手続きを与えて@code{scheme.comparator}のインタフェースで 比較器を作った場合、Gaucheは自動的に比較手続きを生成しますし、 比較手続きを与えてSRFI-114のインタフェースで比較器を作った場合は 順序手続きが自動生成されます。 @c COMMON @c EN A comparator may not have an ordering predicate / comparison procedure, and/or a hash function. You can check if the comparator can be used for ordering or hashing by @code{comparator-ordered?} and @code{comparator-hashable?}, respectively. @c JP 比較器は、順序/比較手続き、ハッシュ関数、あるいはその両方を欠いていることもあります。 比較器が順序づけやハッシュに使えるかどうかは、それぞれ @code{comparator-ordered?}と @code{comparator-hashable?}で調べることができます。 @c COMMON @c EN Some built-in data types such as hashtables (@pxref{Hashtables}) and treemaps (@pxref{Treemaps}), take a comparator in their constructors. The sort and merge procedures also accept comparators (@pxref{Sorting and merging}). @c JP Gauche組み込みのデータ型は、コンストラクタで比較器を取ることができます (例:ハッシュテーブル(@ref{Hashtables}参照)、 ツリーマップ(@ref{Treemaps}参照))。 また、ソートとマージの手続きも比較器を受け取ることができます (@ref{Sorting and merging}参照。 @c COMMON @end deftp @defun make-comparator type-test equal order hash :optional name [R7RS comparator] @c EN Creates a new comparator form the given @var{type-test}, @var{equal}, @var{order} and @var{hash} functions, and returns it. In R7RS, this is defined in @code{scheme.comparator} See the description of @code{} above for the role of those procedures. @c JP 与えられた@var{type-test}、@var{equal}、@var{order}、@var{hash}の 各関数をまとめて、新たな比較器を作って返します。 R7RSではこの関数は@code{scheme.comparator}で定義されています。 各関数の役割については上の@code{}の説明を参照してください。 @c COMMON @c EN Note: Both @code{scheme.comparator} and @code{srfi.114} defines @code{make-comparator}, but where @code{scheme.comparator} takes @var{order} argument, @code{srfi.114} takes @var{compare} argument. Since @code{scheme.comparator} is preferable, we adopt it for the built-in interface, and give a different name (@code{make-comparator/compare}) for SRFI-114 constructor. @c JP 註: @code{scheme.comparator}と@code{srfi.114}は両方とも @code{make-comparator}を定義していますが、 @code{scheme.comparator}が@var{order}手続きを取るところで @code{srfi.114}は@var{compare}手続きを取ります。 @code{scheme.comparator}の方が推奨されるので、 Gaucheでは組み込みの@code{make-comparator}を@code{scheme.comparator}に合わせ、 SRFI-114の方は@code{make-comparator/compare}という名前にしてあります。 @c COMMON @c EN Actually, some arguments can be non-procedures, to use predefined procedures, for the convenience. Even if non-procedure arguments are passed, the corresponding accessors (e.g. @code{comparator-type-test-procedure} for the @code{type-test} procedure) always return a procedure---either the given one or the predefined one. @c JP 各引数は、手続きでなく真偽値を取ることもできます。その場合、既に定義された 手続きが使えるので便利です。但し、引数に真偽値を渡した場合でも、 アクセサは補われた手続きの方を返します。 (例えば@code{type-test}引数に対応するアクセサは @code{comparator-type-test-procedure}ですが、これは常に手続きを返します。) @c COMMON @c EN The @var{type-test} argument must be either @code{#t} or a predicate taking one argument to test suitability of the object for comparing by the resulting comparator. If it is @code{#t}, a procedure that always return @code{#t} is used. @c JP @code{type-test}引数は、@code{#t}もしくは1引数の手続きでなければなりません。 手続きの場合、それは渡されたオブジェクトが比較器の他の手続きに渡せるかどうかを 判定する述語です。@code{#t}の場合、どんなオブジェクトに対しても@code{#t}を 返す手続きが補われます。 @c COMMON @c EN The @var{equal} argument must a predicate taking two arguments to test equality. @c JP @var{equal}引数は二つの引数を取りその等価性を判定する 述語でなければなりません。 @c COMMON @c EN the @var{order} argument must be either @code{#f} or a procedure taking two arguments and returning a boolean value. It must return @code{#t} iff the first argument strictly precedes the second one. If @code{#f} is passed, the comparator can not be used for ordering. @c JP @var{order}手続きは@code{#f}もしくは二つの引数を取り真偽値を返す手続きで なければなりません。手続きの場合、最初の引数が二番目の引数より厳密に手前に ある場合にのみ@code{#t}を返します。@code{#f}が渡された場合は、 作られる比較器は順序づけには使えません。 @c COMMON @c EN The @var{hash} argument must be either @code{#f}, or a procedure taking one argument and returning nonnegative exact integer. If @code{#f} is given, it indicates the comparator can't hash objects; the predefined procedure just throws an error. @c JP @var{hash}引数は@code{#f}か、一つの引数を取り非負の正確な整数をハッシュ値と して返す手続きでなければなりません。 @code{#f}が渡された場合は、この比較器ではハッシュ値を取れないことを意味します。 この場合、呼ばれたらエラーを投げる手続きが補われます。 @c COMMON @c EN The fifth, optional argument @var{name}, is Gauche's extension. It can be any object but usually a symbol; it is only used when printing the comparator, to help debugging. @c JP 最後の、省略可能な引数@var{name}はGaucheの拡張です。 どんなオブジェクトでも構いませんが、通常はシンボルが渡されます。 これは比較器を出力する時に使われるだけですが、デバッグには役に立ちます。 @c COMMON @end defun @defun make-comparator/compare type-test equal compare hash :optional name @c EN This is SRFI-114 comparator constructor. In SRFI-114, this is called @code{make-comparator}. Avoiding name conflict, we renamed it. If you @code{(use srfi.114)} you get the original name @code{make-comparator} (and the built-in @code{make-comparator} is shadowed). This is provided for the backward compatibility, and new code should use built-in @code{make-comparator} above. @c JP これはSRFI-114比較器のコンストラクタです。SRFI-114ではこれが @code{make-comparator}と呼ばれていますが、名前の衝突を避けるために別の名前を用意しました。 @code{(use srfi.114)}した場合は、SRFI-114のコンストラクタが元の名前 で使えるようになります(組み込みの@code{make-comparator}がシャドウされます。) これは後方互換性のために提供されています。 新たなコードは上に示した組み込みの@code{make-comparator}を使ってください。 @c COMMON @c EN It's mostly the same as @code{make-comparator} above, except the following: @c JP 以下の点を除き、上の@code{make-comparator}とほぼ同じです。 @c COMMON @itemize @item @c EN The third argument (@var{compare}) is a comparison procedure instead of an ordering predicate. It must be either @code{#f}, or a procedure taking two arguments and returning either -1, 0, or 1, depending on whether the first argument is less than, equal to, or greater than the second argument. If it is @code{#f}, it indicates the comparator can't order objects. @c JP 第3引数(@var{compare})には順序手続きのかわりに比較手続きを渡します。 この引数は@code{#f}か、二つの引数を取りそれらの大小関係を 判定する手続きでなければなりません。手続きの場合、引数の最初の方が小さいか、 両者が等しいか、最初の方が大きいか、に応じて-1, 0, 1をそれぞれ返さなければ なりません。@code{#f}の場合、対象とするオブジェクトの集合に全順序関係がつけられない ことを表します。 @c COMMON @item @c EN You can pass @code{#t} to the @var{equal} argument when you give a comparison procedure. In that case, equality is determined by calling the comparison procedure and see if the result is 0. @c JP 比較手続きを与えた場合、@var{equal}手続きに@code{#t}を渡すことができます。 その場合、等価性の判定は比較手続きが0を返すかどうかで行われます。 @c COMMON @end itemize @end defun @node Comparator predicates and accessors, Predefined comparators, Comparator class and constructors, Basic comparators @subsubsection Comparator predicates and accessors @c NODE 比較器にまつわる述語とアクセサ @defun comparator? obj [R7RS comparator] @c EN Returns true iff @var{obj} is a comparator. In R7RS, this is provided from @code{scheme.comparator}. @c JP @var{obj}が比較器である場合に@code{#t}を、そうでなければ@code{#f}を返します。 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。 @c COMMON @end defun @deffn {Method} object-equal? (a ) (b ) @c EN Comparing two comparators by @code{equal?} compares their contents, via this method. Even @var{a} and @var{b} are comparators created separately, they can be @code{equal?} if all of their slots are the same. This is Gauche's extension. The standard says nothing about equality of comparators, but it is sometimes useful if you can compare two. @c JP 二つの比較器が等価かどうかを@code{equal?}で調べた場合、 比較はこのメソッドを介して、各スロットが等価かどうかで判定されます。 比較器@var{a}と@var{b}が別々に作られたものであっても、各スロットの内容が 等価であれば@code{equal?}とみなされます。 これはGaucheの拡張です。標準は比較器同士の等価性については何も定義していません。 けれども、時には等価判定が便利なことがあります。 @c COMMON @example (equal? (make-comparator #t equal? #f hash 'foo) (make-comparator #t equal? #f hash 'foo)) @result{} #t @c EN ;; The following may be #t or #f, depending on how the anonymous ;; procedure is allocated. @c JP ;; 次の式は、無名手続きがどのようにアロケートされるかによって、#tにも#fにも ;; なり得る。 @c COMMON (equal? (make-comparator (^x x) eq? #f #f) (make-comparator (^x x) eq? #f #f)) @end example @end deffn @defun comparator-flavor cmpr @c EN Returns a symbol @code{ordering} if @var{cmpr} is created with @code{scheme.comparator} constructor, and returns @code{comparison} if @var{cmpr} is created with SRFI-114 constructor. Usually applications don't need to distinguish these two kinds of comparators, for either kind of comparators can behave just as another kind. This procedure is for some particular cases when one wants to optimize for the underlying comparator implementation. @c JP @var{cmpr}が@code{scheme.comparator}コンストラクタで作られた場合は シンボル@code{ordering}を、 SRFI-114コンストラクタで作られた場合はシンボル@code{comparison}を返します。 アプリケーションは通常両者を区別する必要はありません。一方の比較器は もう一方の比較器としても使うことができるからです。 比較器の実装に特化した最適化をしたい場合にのみ、区別が必要です。 @c COMMON @end defun @defun comparator-ordered? cmpr @defunx comparator-hashable? cmpr [R7RS comparator] @c EN Returns true iff a comparator @var{cmpr} can be used to order objects, or to hash them, respectively. In R7RS, this is provided from @code{scheme.comparator}. @c JP 比較器@var{cmpr}が、オブジェクトの順序づけあるいはハッシュに使える 場合にそれぞれ@code{#t}を返します。 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。 @c COMMON @end defun @defun comparator-type-test-procedure cmpr @defunx comparator-equality-predicate cmpr @defunx comparator-ordering-predicate cmpr @defunx comparator-hash-function cmpr [R7RS comparator] @c EN Returns type test procedure, equality predicate, ordering procedure and hash function of comparator @var{cmpr}, respectively. In R7RS, this is provided from @code{scheme.comparator}. These accessors always return procedures; if you give @code{#f} to the @var{order} or @var{hash} argument of the constructor, @code{comparator-ordering-predicate} and @code{comparator-hash-function} still return a procedure, which will just raise an error. @c JP 比較器の型検査述語、等価述語、順序手続きおよびハッシュ関数をそれぞれ返します。 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。 これらの手続きは常に手続きを返します。@code{make-comparator}で @var{order}や@var{hash}に@code{#f}を渡した場合でも、エラーを投げるだけの 手続きが返されます。 @c COMMON @end defun @defun comparator-comparison-procedure cmpr [SRFI-114] @c EN This is a SRFI-114 procedure, but sometimes handy with @code{scheme.comparator} comparators. Returns a procedure that takes two objects that satisfy the type predicates of @var{cmpr}. The procedure returns either -1, 0 or 1, depending on whether the first object is less than, equal to, or greater than the second. The comparator must be ordered, that is, it must have an ordering predicate (or a comparison procedure, if it is created by SRFI-114 constructor). @c JP これはSRFI-114の手続きですが、 @code{scheme.comparator}比較器でも時々便利なことがあります。 @var{cmpr}の型検査述語を満たす二つのオブジェクトを取り、-1、0、1のいずれかを 返す手続きを返します。二つのオブジェクトのうち最初の方が小さければ-1が、 等しければ0が、大きければ1が返されます。 比較器は大小比較可能でなけばなりません(順序手続きが渡されるか、 あるいはSRFI-114コンストラクタで比較手続きが渡されるか)。 @c COMMON @end defun @defun comparator-test-type cmpr obj @defunx comparator-check-type cmpr obj [R7RS comparator] @c EN Test whether @var{obj} can be handled by a comparator @var{cmpr}, by applying @var{cmpr}'s type test predicate. The former (@code{comparator-test-type}) returns a boolean values, while the latter (@code{comparator-check-type}) signals an error when @var{obj} can't be handled. In R7RS, this is provided from @code{scheme.comparator}. @c JP @var{obj}が比較器@var{cmpr}で扱えるオブジェクトかどうかを、 @var{cmpr}の型検査述語を適用して調べます。 @code{comparator-test-type}は結果の真偽値を返します。 @code{comparator-check-type}は@var{obj}が扱えないオブジェクトである場合に エラーを投げます。 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。 @c COMMON @end defun @defun =? cmpr obj obj2 obj3 @dots{} @defunx ? cmpr obj obj2 obj3 @dots{} @defunx >=? cmpr obj obj2 obj3 @dots{} [R7RS comparator] @c EN Compare objects using a comparator @var{cmpr}. All of @var{obj}, @var{obj2}, @var{obj3} @dots{} must satisfy the type predicate of @var{cmpr}. When more than two objects are given, the order of comparison is undefined. In order to use @code{?} and @code{>=?}, comparator must be ordered. In R7RS, this is provided from @code{scheme.comparator}. @c JP 比較器@var{cmpr}を使ってオブジェクトを比較します。 @var{obj}, @var{obj2}, @var{obj3} @dots{}は全て@code{cmpr}の 型検査述語を満たさなければなりません。 3つ以上のオブジェクトが渡された場合、比較の順番は規定されていません。 @code{?}、@code{>=?}を使うためには 比較器は順序比較可能でなければなりません。 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。 @c COMMON @end defun @defun comparator-hash cmpr obj [R7RS comparator] @c EN Returns a hash value of @var{obj} with the hash function of a comparator @var{cmpr}. The comparator must be hashable, and @var{obj} must satisfy comparator's type test predicate. In R7RS, this is provided from @code{scheme.comparator}. @c JP 比較器@var{cmpr}のハッシュ関数を使って@var{obj}のハッシュ値を計算して返します。 比較器はハッシュ計算可能でなければなりません。また、@var{obj}は 比較器の型検査述語を満たさなければなりません。 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。 @c COMMON @end defun @defun comparator-compare cmpr a b [SRFI-114] @c EN Order two objects @var{a} and @var{b} using @var{cmpr}, and returns either one of -1 (@var{a} is less than @var{b}), 0 (@var{a} equals to @var{b}), or 1 (@var{a} is greater than @var{b}). Objects must satisfy @var{cmpr}'s type test predicate. A simple comparison can be done by @code{} are defined for these generic functions, which catches the case when @code{default-comparator} is applied on object(s) of user-defined classes that don't have specialized methods defined for those generic functions. The catching method examines registered comparators to find one that can handle passed argument(s), and if it finds one, use it. @c JP 実際、Gaucheではこれらのジェネリックファンクションを使って、 登録されたデフォルト比較器を処理しています。これらのジェネリックファンクションには、 あらかじめ@code{}に特殊化されたメソッドが定義されており、 @code{default-comparator}がユーザ定義クラスのオブジェクトに使われ、 かつそのクラスに特殊化されたメソッドが定義されていない場合を捕まえます。 そして、登録された比較器から与えられた引数に適用可能なものを探し、 見つかればそれを使います。 @c COMMON @c EN You might frown at this procedure having a global side-effect. Well, @code{scheme.comparator} explicitly prohibits comparators registered by this procedure alters the behavior of the default comparator in the existing domain---it is only allowed to handle objects that aren't already handled by the system's original default comparator and other already registered comparators. So, the only effect of adding new comparator should make the default comparator work on objects that had been previously raised an error. @c JP この手続きがグローバルな副作用を持つことに顔をしかめる人もいるかもしれません。 @code{scheme.comparator}では、 デフォルトの比較器や登録された比較器が既にカバーしている定義域と 重複する定義域を持つ比較器を登録することを禁じています。 言い換えれば、@code{comparator-register-default!}で定義できるのは、 デフォルトの比較器や既に登録された比較器が処理できないオブジェクトを扱う 比較器だけです。従って、新たな比較器を登録することによる副作用は、 それまで@code{default-comparator}が扱えなかったオブジェクトを 扱えるようになるというだけで、既に扱えていたオブジェクトに対する @code{default-comparator}の動作が変わってしまうということはありません。 @c COMMON @c EN In reality, it is impossible to enforce the condition. If you register a comparator whose domain overlaps overlaps the domain the default comparator (and its extensions via Gauche's methods), the program becomes non-portable at that moment. In the current version, the comparators registered by @code{comparator-register-default!} has the lowest precedence on the dispatch mechanism, but you shouldn't count on that. @c JP 尤も、現実にその条件を強制することは不可能です。 もし、既にデフォルトの比較器の定義域(および、Gaucheのメソッドにより拡張された定義域) と重なるような定義域を持つ比較器を登録してしまったら、その時点でプログラムの 移植性は損なわれます。現在のバージョンでは、@code{comparator-register-default!} で登録された比較器は最も低い優先度を持ちますが、その動作をあてにすべきではありません。 @c COMMON @end defun @defvar eq-comparator @defvarx eqv-comparator @defvarx equal-comparator [SRFI-114] @c EN Built-in comparators that uses @code{eq?}, @code{eqv?} and @code{equal?} for the equality predicate, respectively. They accept any kind of Scheme objects. Each has corresponding hash functions (i.e. @code{eq-hash} for @code{eq-comparator}, @code{eqv-hash} for @code{eqv-comparator} and @code{default-hash} for @code{equal-comparator}). Only @code{eq-comparator} is ordered, using @code{eq-compare} to order the objects (@pxref{Comparison}, for @code{eq-compare}). @c JP それぞれ、等価述語に@code{eq?}、@code{eqv?}、@code{equal?}を使う 組み込みの比較器です。全てのSchemeオブジェクトを受け付けます。 対応するハッシュ関数(@code{eq-comparator}は@code{eq-hash}、 @code{eqv-comparator}は@code{eqv-hash}、@code{equal-comparator}は @code{hash})を備えています。 @code{eq-comparator}のみ、@code{eq-compare}を使った順序づけが可能です (@code{eq-compare}については@ref{Comparison}参照)。 @c COMMON @c EN Note that @code{eq-comparator} and @code{eqv-comparator} are not equivalent from what @code{make-eq-comparator} and @code{make-eqv-comparator} return, respectively. The latter two are defined in @code{scheme.comparator} and specified to use @code{default-hash} for the hash function. It is heavier than @code{eq-hash}/@code{eqv-hash}, and it can't be used for circular objects, nor for the mutable objects with which you want to hash them by identity. We provide @code{eq-comparator} and @code{eqv-comparator} in case you want to avoid limitations of @code{default-hash}. @c JP @code{eq-comparator}と@code{eqv-comparator}はそれぞれ、 @code{make-eq-comparator} and @code{make-eqv-comparator}が返す比較器とは 等価でないことに注意してください。後者の手続きは@code{scheme.comparator} で規定されていますが、 ハッシュ関数には@code{default-hash}を使うように指定されています。 @code{default-hash}は@code{eq-hash}や@code{eqv-hash}より重く、 ループのある構造は扱えず、また変更可能なオブジェクトの同一性のみに基づいてハッシュ値を 計算するのには使えません。 こういった@code{default-hash}の制限を避けたい場合のために @code{eq-comparator}と@code{eqv-comparator}を用意しました。 @c COMMON @end defvar @defvar boolean-comparator @defvarx char-comparator @defvarx char-ci-comparator @defvarx string-comparator @defvarx string-ci-comparator [SRFI-114] @c EN Compare booleans, characters, and strings, respectively. The @code{*-ci-*} variants uses case-insensitive comparison. All have appropriate hash functions, too. The string case-insensitive comparison uses Unicode full-string case conversion (@pxref{Full string case conversion}). @c JP それぞれ、真偽値、文字、文字列を比較する比較器です。 @code{*-ci-*}がついている手続きは大文字小文字の区別をしません。 全て、適切なハッシュ関数も備えています。 文字列の大文字小文字の区別をしない比較は、Unicodeのfull-string case conversion に従います (@ref{Full string case conversion}参照)。 @c COMMON @end defvar @defvar exact-integer-comparator @defvarx integer-comparator @defvarx rational-comparator @defvarx real-comparator @defvarx complex-comparator @defvarx number-comparator [SRFI-114] @c EN Compare exact integers, integers, rational numbers, real numbers, complex numbers and general numbers, respectively. In Gauche @code{number-comparator} is the same as @code{complex-comparator}. The equality are determined by @code{=}. For exact integer, integer, rational and real comparators, the order is the numerical order. Two complex numbers are compared first by their real components, and then their imaginary components only if the real components are the same. Note that those comparator rejects NaN. You need @code{make-inexact-real-comparator} in @code{srfi.114} module to compare NaNs with your own discretion. @xref{Comparators}, for the details. @c JP それぞれ、正確な整数、整数、有理数、実数、複素数、そして全ての数値を比較する比較器です。 Gaucheでは@code{number-comparator}は@code{complex-comparator}と同じです。 等価性は@code{=}により判定されます。 正確な整数、整数、有理数および実数の比較器では、比較手続きは数値の大小に基づいて 判定されます。複素数の比較においては、まず実部の大小が比べられ、実部が等しい場合に 虚部の大小が比べられます。 これらの比較器はNaNを扱いません。 NaNを扱いたい場合は、@code{srfi.114}モジュールの@code{make-inexact-real-comparator} 手続きを使って、NaNの比較方法を指定する必要があります。 詳しくは@ref{Comparators}を参照してください。 @c COMMON @end defvar @defvar pair-comparator @defvarx list-comparator @defvarx vector-comparator @defvarx uvector-comparator @defvarx bytevector-comparator [SRFI-114] @c EN The default comparators to compare pairs, lists, vectors, uniform vectors and bytevectors (which is synonym to @code{u8vector}). Their respective elements are compared with the default comparators. Note that lists are compared by dictionary order (@code{(1 2 3)} comes before @code{(1 3)}), while in vector-families shorter ones are ordered first ( @code{#(1 3)} comes before @code{#(1 2 3)}). @c JP ペア、リスト、ベクタ、ユニフォームベクタ、バイトベクタ(@code{u8vector}の別名)を それぞれ比較するための比較器です。 各データ型の要素についてはデフォルトの比較器(@code{default-comparator)}が 使われます。 リストは辞書順で比較されますが(例:@code{(1 2 3)}は@code{(1 3)}より前)、 ベクタの仲間はまず長さが短いものが先に来て、それから内容で比較されることに注意してください (@code{#(1 3)}は@code{#(1 2 3)}より前)。 @c COMMON @end defvar @defvar time-comparator @c EN A comparator to compare @code{