Debian Codegraph @

doc/corelib.texi

raw
1 @node Core library, Object system, Macros, Top
2 @chapter Core library
3 @c NODE 組み込みライブラリ
4
5 @c ----------------------------------------------------------------------
6 @menu
7 * Types and classes::
8 * Equality and comparison::
9 * Numbers::
10 * Booleans::
11 * Undefined values::
12 * Pairs and lists::
13 * Symbols::
14 * Keywords::
15 * Characters::
16 * Character sets::
17 * Strings::
18 * Regular expressions::
19 * Vector family::
20 * Dictionaries::
21 * Procedures and continuations::
22 * Parameters and dynamic states::
23 * Boxes::
24 * Lazy evaluation::
25 * Exceptions::
26 * Eval and repl::
27 * Input and output::
28 * Loading Programs::
29 * Sorting and merging::
30 * System interface::
31 * Development helper API::
32 @end menu
33
34 @node Types and classes, Equality and comparison, Core library, Core library
35 @section Types and classes
36 @c NODE 型とクラス
37
38 @c EN
39 Scheme is a dynamically and strongly typed language. That is,
40 every value @emph{knows} its type at run-time, and the type
41 determines what kind of operations can be applied on the value.
42 @c JP
43 Schemeは動的な強い型付けの言語です。つまり、全ての値は
44 実行時に自分の型を知っていて、その型が値に適用できる操作を決定します。
45 @c COMMON
46
47 @c EN
48 The Scheme standard is pretty simple on types; basically,
49 an object being a type means the type predicate returns true on the object,
50 and that's all. Gauche adopts a bit more elaborated system---types are
51 first-class objects and you can query various information.
52 @c JP
53 Scheme標準は、型についてはとても単純です。基本的に、オブジェクトがある型であるというのは、
54 そのオブジェクトに対して型述語が真を返す、それだけです。
55 Gaucheはもう少し込み入ったシステムを採用していて、型も第一級のオブジェクトになり
56 様々な情報を問い合わせることができます。
57 @c COMMON
58
59 @c EN
60 In Gauche, types are conventionally
61 named with brackets @code{<} and @code{>}, e.g. @code{<string>}.
62 It's nothing syntactically special with these brackets; they're valid
63 characters to consist of variable names.
64 @c JP
65 Gaucheでは慣習的に、型は@code{<string>}のように
66 @code{<}と@code{>}で囲まれた名前を持ちます。
67 この@code{<}や@code{>}は文法的には何ら特別な意味を持ちません。
68 普通に変数名として使える文字です。
69 @c COMMON
70
71 @menu
72 * Prescriptive and descriptive types::
73 * Generic type predicates::
74 * Predefined classes::
75 * Type expressions and type constructors::
76 * Native types::
77 @end menu
78
79 @node Prescriptive and descriptive types, Generic type predicates, Types and classes, Types and classes
80 @subsection Prescriptive and descriptive types
81 @c NODE 規範的な型と記述的な型
82
83 @c EN
84 Types are used in two ways. A type can be seen as a template of
85 the actual values (instances)---that is, a type @emph{prescribes}
86 the structure of, and possible operations on, its instances.
87 In Gauche, such prescriptive types are represented by @emph{classes}.
88 Every value in Gauche belongs to a class, which can be queried with the
89 @code{class-of} procedure. You can also define your own class with
90 @code{define-class} or @code{define-record-type}
91 (@pxref{Object system}, and @pxref{Record types}).
92 @c JP
93 型には2つの使われ方があります。まず、型は実際の値(インスタンス)のテンプレートと
94 見ることができます。つまり、型がインスタンスの構造と、それに適用できる操作を
95 あらかじめ決めている(prescribe)ということです。
96 Gaucheでは、このような規範的(prescriptive)な型は、@emph{クラス}で表現されます。
97 Gauche内での値は全て何かのクラスに属していて、
98 @code{class-of}手続きでそのクラスを取れます。また、ユーザは独自のクラスを
99 @code{define-class}や@code{define-record-type}で定義することもできます
100 (@ref{Object system}および@ref{Record types}参照)。
101 @c COMMON
102
103 @c EN
104 A type can also be seen as a constraint of a given
105 expression---that is, a type @emph{describes} what characteristics
106 a certain expression must have. Gauche has entities
107 to represent such descriptive types separate from classes.
108 Descriptive types are created with @emph{type constructors}
109 (@pxref{Type expressions and type constructors}).
110 We also have a set of predefined descriptive types to communicate
111 to C libraries (@pxref{Native types}.
112 @c JP
113 型はまた、与えられた式についての制約と見ることもできます。
114 つまり、型がその式が持つべき特定の性質を記述する(describe)ということです。
115 Gaucheでは、クラスとは別に、そういった記述的(descriptive)な型を表現するエンティティを
116 用意しています。記述的な型は型コンストラクタで作ることができます
117 (@ref{Type expressions and type constructors}参照)。
118 また、Cライブラリとやりとりするための記述的な型も用意されています
119 (@ref{Native types}参照)。
120 @c COMMON
121
122 @c EN
123 A value is an instance of a class. For example,
124 @code{1} is an instance of @code{<integer>}, and @code{"xyz"}
125 is an instance of @code{<string>}. This presctiptive type relationship
126 is checked with @code{is-a?} procedure: @code{(is-a? 1 <integer>)} and
127 @code{(is-a? "xyz" <string>)} both returns @code{#t}.
128 @c JP
129 値は、特定のクラスのインスタンスです。
130 例えば@code{1}は@code{<integer>}のインスタンスであり、
131 @code{"xyz"}は@code{<string>}のインスタンスです。
132 このprescriptiveな型の関係は、手続き@code{is-a?}で検査できます。
133 @code{(is-a? 1 <integer>)}、@code{(is-a? "xyz" <string>)}は
134 どちらも@code{#t}を返します。
135 @c COMMON
136
137 @c EN
138 On the other hand, you may have a procedure that takes either a number
139 or a string as an argument. ``A number or a string'' is a type constraint,
140 and can be expressed as a descriptive type, @code{(</> <number> <string>)}.
141 Descriptive type relationship is checked with @code{of-type?} procedure:
142 @code{(of-type? 1 (</> <number> <string>))} and
143 @code{(of-type? "xyz" (</> <number> <string>))} both returns @code{#t}.
144 More conveniently, @code{(assume-type arg (</> <number> <string>))}
145 would raise an error if @var{arg} doesn't satisfy the given type constraint.
146 @c JP
147 一方、例えば手続きが数値か文字列を引数に取る、といったケースもあります。
148 「数値か文字列」というのは型に関する制約であり、descriptiveな型
149 @code{(</> <number> <string>)}として表現できます。
150 descriptiveな型の関係は手続き@code{of-type?}で検査できます。
151 @code{(of-type? 1 (</> <number> <string>))}、
152 @code{(of-type? "xyz" (</> <number> <string>))}はどちらも@code{#t}を返します。
153 また、@code{(assume-type arg (</> <number> <string>))}は
154 @var{arg}が与えられた型の制約を満たさなければエラーを投げます。
155 @c COMMON
156
157 @node Generic type predicates, Predefined classes, Prescriptive and descriptive types, Types and classes
158 @subsection Generic type predicates
159 @c NODE 汎用型述語
160
161 @c EN
162 A ``type predicate'' is a predicate that tells if an object is of a specific
163 type; e.g. @code{number?} tells you if the argument is a number.
164 Since types are first-class in Gauche, we have predicates that can tell
165 an object is of a @emph{given} type, as well as predicates to ask
166 the relationship between types.
167 @c JP
168 「型述語」は、与えられたオブジェクトが特定の型を持つかどうかを判定する述語です。
169 例えば@code{number?}は引数が数値かどうかを返します。
170 Gaucheでは型がファーストクラスなので、もう一歩進めて、
171 オブジェクトが@emph{与えられた}型を持つかどうかを判定する述語や、
172 型同士の関係を調べる述語が提供されています。
173 @c COMMON
174
175 @defun is-a? obj class
176 @c EN
177 This is a prescriptive types predicate.
178 Returns true iff @var{obj} is an instance of @var{class} or an instance
179 of descendants of @var{class}.
180 @c JP
181 これは規範的な型に関する述語です。
182 @var{obj}が@var{class}のインスタンスであるか、@var{class}のサブクラスの
183 インスタンスである場合に、真を返します。
184 @c COMMON
185
186 @example
187 (is-a? 3 <integer>) @result{} #t
188 (is-a? 3 <real>) @result{} #t
189 (is-a? 5+3i <real>) @result{} #f
190 @end example
191
192 @c EN
193 Note: If @var{obj}'s class has been redefined, @code{is-a?} also
194 triggers instance update.
195 See @ref{Class redefinition} for the details.
196 @c JP
197 註:@var{obj}のクラスが再定義されていた場合、@code{is-a?}はインスタンスアップデートを
198 トリガします。@ref{Class redefinition}を参照してください。
199 @c COMMON
200 @end defun
201
202 @defun of-type? obj type
203 @c EN
204 This is a descriptie type predicate.
205 Returns true iff @var{obj} satisfies the constraints described by @var{type},
206 which can be either a class (in that case, this is the same as @code{is-a?}),
207 or a descriptive type (@pxref{Type expressions and type constructors} below).
208 @c JP
209 これは記述的な型を調べる述語です。
210 @var{obj}が@var{type}で記述される制約を満たすなら@code{#t}を、そうでなければ@code{#f}を
211 返します。@var{type}はクラスか(その場合は@code{is-a?}と同じです)、
212 記述型 (@pxref{Type expressions and type constructors}参照) です。
213 @c COMMON
214
215 @example
216 (of-type? 1 (</> <number> <string>)) @result{} #t
217 (of-type? "a" (</> <number> <string>)) @result{} #t
218 (of-type? 'a (</> <number> <string>)) @result{} #f
219 @end example
220 @end defun
221
222 @defun subtype? sub super
223 @c EN
224 Returns @code{#t} if a type @var{sub} is a subtype of a type @var{super}
225 (includes the case that @var{sub} is @var{super}).
226 Otherwise, returns @code{#f}.
227 @c JP
228 型@var{sub}が型@var{super}のサブタイプであれば(@var{sub}と@var{super}が
229 同じである場合も含め)@code{#t}を、そうでなければ@code{#f}を返します。
230 @c COMMON
231
232 @c EN
233 In general, if @var{sub} is a subtype of @var{super}, an object that satisfies
234 the constraints of @var{sub} also satisfies the constraints of @var{super},
235 so you can use the object where objects of type @var{super} are expected.
236 In other words, @var{sub} is more restrictive than @var{super}.
237 If both @var{sub} and @var{super} are classes, @var{sub} being a subtype
238 of @var{super} means @var{sub} is a subclass of @var{super}.
239 @c JP
240 一般的に、@var{sub}が@var{super}のサブタイプであれば、
241 @var{sub}の制約を満たすオブジェクトは@var{super}が期待されている箇所で使うことが
242 できます。言い換えれば、@var{sub}の制約の方が@var{super}よりきついということです。
243 @var{sub}と@var{super}のどちらもがクラスの場合、@var{sub}が@var{super}の
244 サブタイプであるということは、@var{sub}が@var{super}のサブクラスであるということです。
245 @c COMMON
246
247 @example
248 (subtype? <integer> <real>) @result{} #t
249 (subtype? <char> (</> <char> <string>)) @result{} #t
250 (subtype? (</> <integer> <string>) (</> <number> <string>)) @result{} #t
251 @end example
252
253 @c EN
254 Note that we're not rigorous on this ``substitution principle'',
255 for we don't aim at guaranteeing type safety through static analysis.
256 For example, ``list of integers'' can be used in place of a generic list
257 most of the time, and @code{(subtype? (<List> <integer>) <list>)} is
258 @code{#t}. However, if list is mutated, you can't replace
259 generic list with a list of integers---because mutators may try to
260 set non-integer in the list. That kind of cases needs to be handled
261 separately, not on relying solely on @code{subtype?}.
262 @c JP
263 この「置換原則」は常に厳密に成り立つわけではないことに注意してください。
264 例えば「整数のリスト」は大抵の場合、ジェネリックなリストが期待されているところに
265 使えて、従って@code{(subtype? (<List> <integer>) <list>)}も@code{#t}を
266 返します。しかし、渡されたリストが変更される場合は、ジェネリックなリストを
267 整数のリストで置き換え可能とは限りません。コードはリストに整数でないものをセットしようとする
268 かもしれないからです。こういったケースは@code{subtype?}に頼るのではなく
269 個別に対応する必要があります。
270 @c COMMON
271 @end defun
272
273 @defun type? obj
274 @c EN
275 Returns @code{#t} if @var{obj} is a type (either a class or a descriptive
276 type), @code{#f} otherwise.
277
278 You can pass objects that returns @code{#t} for this predicate
279 to the second argument of @code{of-type?}, and the first or second argument
280 of @code{subtype?}.
281 @c JP
282 @var{obj}が型(クラスまたは記述型)であれば@code{#t}を、
283 そうでなければ@code{#f}を返します。
284
285 この述語が真を返すオブジェクトは、@code{of-type?}の第二引数、
286 もしくは@code{subtype?}の引数に渡せます。
287 @c COMMON
288 @end defun
289
290
291 @defun subclass? sub super
292 @c EN
293 Both arguments must be classes. Returns @code{#t} iff @var{sub} is
294 a subclass of @var{super}. A class is regarded as a subclass of
295 itself.
296 @c JP
297 引数はどちらもクラスでなければなりません。
298 @var{sub}が@var{super}のサブクラスであれば@code{#t}を、そうでなければ@code{#f}を
299 返します。クラスはそれ自身のサブクラスとみなされます。
300 @c COMMON
301 @end defun
302
303
304 @node Predefined classes, Type expressions and type constructors, Generic type predicates, Types and classes
305 @subsection Predefined classes
306 @c NODE 定義済みクラス
307
308 @c EN
309 We'll introduce classes for each built-in type as we go through
310 this chapter. Here are a few basic classes to start with:
311 @c JP
312 組み込みの型に対応するクラスについては、この章の中で順に紹介してゆきます。
313 まずは次のいくつかのクラスから始めましょう。
314 @c COMMON
315
316 @deftp {Builtin Class} <top>
317 @clindex top
318 @c EN
319 This class represents the supertype of all the types in Gauche.
320 That is, for any class @code{X}, @code{(subtype? X <top>)} is @code{#t},
321 and for any object @code{x}, @code{(is-a? x <top>)} is @code{#t}.
322 @c JP
323 全ての型のスーパータイプを表現するクラスです。
324 つまり、どんなクラス@code{X}に対しても@code{(subtype? X <top>)}は@code{#t}であり、
325 どんなオブジェクト@code{x}に対しても@code{(is-a? x <top>)}は@code{#t}です。
326 @c COMMON
327 @end deftp
328
329 @deftp {Builtin Class} <bottom>
330 @clindex bottom
331 @c EN
332 This class represents the subtype of all the types in Gauche.
333 For any class @code{X}, @code{(subtype? <bottom> X)} is @code{#t},
334 and for any object @code{x}, @code{(is-a? x <bottom>)} is @code{#f}.
335 @c JP
336 全ての型のサブタイプを表現するクラスです。
337 どんなクラス@code{X}に対しても@code{(subtype? <bottom> X)}は@code{#t}であり、
338 どんなオブジェクト@code{x}に対しても@code{(is-a? x <bottom>)}は@code{#f}です。
339 @c COMMON
340
341 @c EN
342 There's no instance of @code{<bottom>}.
343 @c JP
344 @code{<bottom>}型のインスタンスは存在しません。
345 @c COMMON
346
347 @c EN
348 Note: Although @code{<bottom>} is subtype of other types,
349 the class precedence list (CPL) of @code{<bottom>} only contains
350 @code{<bottom>} and @code{<top>}. It's because it isn't
351 always possible to calculate a linear list of all the types.
352 Even if it is possible, it would be expensive to check and update the
353 CPL of @code{<bottom>} every time a new class is defined or
354 an existing class is redefined. Procedures @code{subtype?} and
355 @code{is-a?} treat @code{<bottom>} specially.
356
357 One of use case of @code{<bottom>} is @code{applicable?} procedure.
358 @xref{Procedure class and applicability}.
359 @c JP
360 註: @code{<bottom>}は全ての型のサブタイプですが、そのクラス順位リスト
361 (class precedence list, CPL)には@code{<bottom>}と@code{<top>}
362 以外のクラスは含まれていません。全ての型を線形に並べることは常に可能である
363 とは限らず、まだそうであったとしても新たなクラスの定義や既存のクラスの
364 再定義のたびに@code{<bottom>}のCPLを検査してアップデートすることは
365 高くつくでしょう。@code{subtype?}や@code{is-a?}といった手続きは
366 @code{<bottom>}を特別扱いしています。
367
368 @code{<bottom>}の使いどころのひとつは、@code{applicable?}手続きです。
369 @ref{Procedure class and applicability}を参照のこと。
370 @c COMMON
371 @end deftp
372
373 @deftp {Builtin Class} <object>
374 @clindex object
375 @c EN
376 This class represents a supertype of all user-defined classes.
377 @c JP
378 このクラスは、ユーザ定義されたクラスのスーパータイプを表現するクラスです。
379 @c COMMON
380 @end deftp
381
382 @defun class-of obj
383 @c EN
384 Returns a class metaobject of @var{obj}.
385 @c JP
386 @var{obj}のクラスを返します。
387 @c COMMON
388
389 @example
390 (class-of 3) @result{} #<class <integer>>
391 (class-of "foo") @result{} #<class <string>>
392 (class-of <integer>) @result{} #<class <class>>
393 @end example
394
395 @c EN
396 Note: In Gauche, you can redefine existing user-defined classes.
397 If the new definition has different configuration of the instance,
398 @code{class-of} on existing instance triggers instance updates;
399 @pxref{Class redefinition} for the details. Using
400 @code{current-class-of} suppresses instance updates
401 (@pxref{Accessing instance}).
402 @c JP
403 註: Gaucheでは、ユーザ定義クラスを再定義することができます。
404 新たな定義でインスタンスの構造が変更された場合、以前のクラスから作られた
405 インスタンスに@code{class-of}を適用すると、インスタンスが新しいクラスに
406 適合するようにアップデートされます。詳しくは@ref{Class redefinition}を参照して
407 ください。インスタンスアップデートを避けるには@code{current-class-of}を
408 使います(@ref{Accessing instance}参照)。
409 @c COMMON
410 @end defun
411
412 @node Type expressions and type constructors, Native types, Predefined classes, Types and classes
413 @subsection Type expressions and type constructors
414 @c NODE 型の式と型コンストラクタ
415
416 @c EN
417 Types are first-class objects manipulatable at runtime in Gauche,
418 but they must be known at compile-time
419 in order to do optimizations or static analysis. In certain places,
420 Gauche requires the the value of type-yielding expressions to be statically
421 computable. We call such expressions @emph{type expressions}.
422 @c JP
423 型はGaucheでは実行時に扱える第一級のオブジェクトですが、
424 静的解析のためにはコンパイル時に型がわかる必要があります。
425 なので、いくつかの場所では、型を生成する式の値が静的に計算可能であることが要求されます。
426 そのような式を「型の式 (type expression)」と呼びます。
427 @c COMMON
428
429 @c EN
430 A type expression is either a global variable reference that are
431 constantly bound to a type, or a call of type constructor:
432 @c JP
433 型の式は、型に静的に束縛されたグローバル変数か、型コンストラクタの呼び出しです:
434 @c COMMON
435
436 @example
437 <type-expression> : <global-variable-constantly-bound-to-a-type>
438 | <type-constructor-call>
439
440 <type-constructor-call> : (<type-constructor> <type-constructor-argument> ...)
441
442 <type-constructor-argument> : <type-expression>
443 | <integer-constant>
444 | ->
445 | *
446 @end example
447
448 @c EN
449 All built-in classes, such as @code{<integer>}, are statically bound
450 (in precise terms, they are ``inlinable'' binding). If you try to alter
451 it, a warning is issued, and the further bahvior will be undefined.
452 In future, we'll make it an error to alter the binding of
453 global variables bount to types. Classes defined with @code{define-class} and
454 @code{define-record-type} are also bound as inlinable.
455 @c JP
456 @code{<integer>}のような全ての組み込みクラスは静的に束縛されています
457 (正確には、「インライン可能な」束縛になっています)。
458 そのような束縛を変更しようとすると警告が出され、それ以降の動作は保証されません。
459 将来的には、型に静的に束縛された変数を変更するのはエラーにするつもりです。
460 @code{define-class}や@code{define-record-type}で定義されるクラスも、
461 インライン可能な束縛になります。
462 @c COMMON
463
464 @c EN
465 Type constructors are special classes whose instances are
466 descriptive types. Type constructors can be invoked as if they are
467 a procedure, but <type-constructor-call> above is recognized by
468 the compiler and the derived type is computed at compile-time.
469 So, at runtime you only see the resulting derived type instance.
470 @c JP
471 型コンストラクタはそれ自身がクラスで、
472 そのインスタンスが記述的な型オブジェクトになるものです。
473 型コンストラクタは構文的には手続き呼び出しのように使えますが、
474 上の<type-constructor-call>はコンパイラによって認識され、
475 コンパイル時に計算されて型オブジェクトになります。
476 なので、ランタイムには結果の型オブジェクトしか見えません。
477 @c COMMON
478
479 @c EN
480 For example, @code{<?>} is a type constructor that creates
481 ``maybe''-like type, e.g. ``an integer or @code{#f}''.
482 (Do not confuse this with Maybe type
483 defined in SRFI-189, @pxref{Maybe and Either optional container types}).
484 A type expression @code{(<?> <integer>)} yields such type
485 (printed as @code{#<? <integer>>}):
486 @c JP
487 例えば、@code{<?>}は''maybe''のようなオプショナルな型を作る型コンストラクタです。
488 @code{(<?> <integer>)}は「@code{<integer>}か@code{#f}」を意味します
489 (SRFI-189 (@ref{Maybe and Either optional container types}参照) の
490 Maybe型と混同しないようにしてください)。
491 この型オブジェクトは @code{#<? <integer>>} と表示されます。
492 @c COMMON
493
494 @example
495 (<?> <integer>) @result{} #<? <integer>>
496 @end example
497
498 @c EN
499 It looks like a procedure call, but it s computed at compile time:
500 @c JP
501 型コンストラクタの呼び出しは手続き呼び出しのように見えますが、コンパイル時に計算されます。
502 @c COMMON
503
504 @example
505 gosh> (disasm (^[] (<?> <integer>)))
506 CLOSURE #<closure (#f)>
507 === main_code (name=#f, cc=0x7f5cd76ab540, codevec=...):
508 signatureInfo: ((#f))
509 0 CONST-RET #<? <integer>>
510 @end example
511
512 @deftp {Type Constructor} <?> type
513 @clindex ?
514 @c EN
515 @var{Type} must be a type expression.
516 This creates a maybe-like type, that is, the object is either
517 of @var{type} or @code{#f}. Usually, @code{#f} indicates
518 that the value is invalid (e.g. the return value of @code{assoc}).
519 @c JP
520 @var{type}は型の式でなければなりません。
521 この型の式はmaybe型に似た型を作ります。オブジェクトは型@var{type}を持つか@code{#f}です。
522 @code{#f}は通常、それが無効な値であることを示します
523 (例: @code{assoc}の戻り値)。
524 @c COMMON
525
526 @c EN
527 This type has ambiguity when @code{#f} can be a meaningful value, but
528 traditionally been used a lot in Scheme, for it is lightweight.
529 We also have a ``proper'' Maybe type in SRFI-189
530 (@pxref{Maybe and Either optional container types}) but that involves
531 extra allocation to wrap the value.
532 @c JP
533 この型は、@code{#f}が意味を担う場合に曖昧性があるのですが、
534 軽量であるゆえにSchemeでは伝統的に多用されてきました。
535 「正しい」MaybeについてはSRFI-189 (@ref{Maybe and Either optional container types}参照)
536 により提供されているのですが、値をラップするごとに新たなアロケーションを必要とします。
537 @c COMMON
538
539 @c EN
540 So, those who came from functional programming may find this isn't
541 a right abstraction, but it has its place in the Scheme world.
542 @c JP
543 関数型言語から来た人には、これは正しい抽象化には見えないかもしれませんが、
544 Scheme界の中ではそれなりに実用的な型です。
545 @c COMMON
546 @end deftp
547
548 @deftp {Type Constructor} </> type @dots{}
549 @clindex /
550 @c EN
551 @var{Type} @dots{} must be type expressions.
552 This creates a @emph{sum type} of @var{type} @dots{}.
553 For example, @code{(</> <string> <symbol>)} is a type that is
554 either a string or a symbol.
555 @c JP
556 @var{type} @dots{} はそれぞれ型の式でなければなりません。
557 この型コンストラクタは、@var{type} @dots{} の直和型を作ります。
558 例えば@code{(</> <string> <symbol>)}は文字列かシンボルであるような型を表します。
559 @c COMMON
560 @end deftp
561
562 @deftp {Type Constructor} <Tuple> type @dots{}
563 @clindex Tuple
564 @c EN
565 @var{Type} @dots{} must be type expressions, except that the
566 last argument that may be an identifier @code{*}.
567 This creates a @emph{product type} of @var{type} @dots{}.
568 @c JP
569 @var{type} @dots{}はそれぞれ型の式でなければなりません。
570 ただ、最後の要素にはシンボル@code{*}も許されます。
571 この型コンストラクタは、@var{type} @dots{} の直積型を作ります。
572 @c COMMON
573
574 @c EN
575 Actually, this type is looser than the product types in typical
576 statically-typed languages. Our tuple is a subtype of list, with
577 types of each positional element are restricted with @var{type} @dots{}.
578 For example, @code{(<Tuple> <integer> <string>)} is a list of two
579 elements, the first one being an integer and the second being a string.
580 @c JP
581 実のところ、これは静的型付け言語の直積型よりも緩い型です。
582 Gaucheではタプルはリストのサブタイプで、リストの各位置の要素が
583 対応する@var{type}で制約されているものです。
584 例えば@code{(<Tuple> <integer> <string>)}は2要素のリストで、
585 最初が整数、次が文字列であるようなものを表します。
586 @c COMMON
587
588 @example
589 (of-type? '(3 "abc") (<Tuple> <integer> <string>)) @result{} #t
590 @end example
591
592 @c EN
593 If you need a more strict and disjoint product type, you can just create
594 a class or a record.
595 @c JP
596 より厳密な、他の型とは別であるような直積型が必要なら、クラスやレコードを作ってください。
597 @c COMMON
598
599 @c EN
600 If the last argument is @code{*}, the resulting type allows
601 extra elements after the typed elements.
602 @c JP
603 最後の要素が@code{*}である場合、結果の型は、
604 型が指定された要素のあとに任意個の要素を許します。
605 @c COMMON
606
607 @example
608 (of-type? '(3 "abc" 1 2) (<Tuple> <integer> <string> *)) @result{} #t
609 @end example
610 @end deftp
611
612 @deftp {Type Constructor} <^> type @dots{} @code{->} type @dots{}
613 @clindex ^
614 @c EN
615 Each @var{type} must be type expressions, except that the
616 one right before @code{->} and the last one may be an identifier @code{*}.
617
618 This creates a procedure type, with the constraints in
619 arguments and return types.
620 The @var{type} @dots{} before @code{->} are the argument types,
621 and the ones after @code{->} are the result types.
622 @c JP
623 @var{type} @dots{} はそれぞれ型の式でなければなりません。ただし、
624 @code{->} の直前、および最後の@var{type}は識別子@code{*}も許されます。
625
626 この型コンストラクタは引数および戻り値の型を制約する手続き型を作ります。
627 @code{->} の前の@var{type} @dots{} は引数の型を、
628 @code{->} の後のは戻り値の型を指定します。
629 @c COMMON
630
631 @c EN
632 The @code{*} in the last of argument type list and/or result type list
633 indicates extra elements are allowed.
634 @c JP
635 引数の型リストの最後に@code{*}がある場合は省略可能な追加の引数を、
636 戻り値の型リストの最後に@code{*}がある場合は追加の戻り値があることを示します。
637 @c COMMON
638
639 @c EN
640 In vanilla Scheme, all procedures belong to just one type, that responds
641 true to @code{procedure?}. It is simple and flexible, but sometimes the
642 resolution is too coarse to do reasoning on the program.
643 @c JP
644 素のSchemeでは、全ての手続きは(@code{procedure?}が真を返すという意味で)
645 ひとつの型に属しています。これは簡単で柔軟ですが、
646 プログラムの解析をしたい場合には粗すぎる分類です。
647 @c COMMON
648
649 @c EN
650 In Gauche, we can attach more detailed type information in procedures.
651 In the current version, some built-in procedures already have such
652 type information, that can be retrieved with @code{procedure-type}:
653 @c JP
654 Gaucheでは手続きオブジェクトがより詳しい型情報を持てます。
655 現在のバージョンでは、組み込み手続きの一部に既に詳しい型情報が付加されていて、
656 @code{procedure-type}によって取り出すことができます。
657 @c COMMON
658
659 @example
660 (procedure-type cons) @result{} #<^ <top> <top> -> <pair>>
661 @end example
662
663 @c EN
664 Not all procedures have such information, though. Do not expect the
665 rigorousness of statically typed languages.
666 @c JP
667 ただ、全ての手続きにこの情報が付加されているわけではありません。
668 静的型付け言語のような厳密さを期待しないでください。
669 @c COMMON
670
671 @c EN
672 At this moment, Scheme-defined procedures treats all argument types
673 as @code{<top>}. We'll provide a way to attach type info in future.
674 @c JP
675 今のところ、Schemeで定義された手続きは全ての引数や戻り値を@code{<top>}型として
676 扱います。いずれより詳しい型情報を指定できるようにする予定です。
677 @c COMMON
678 @end deftp
679
680 @deftp {Type Constructor} <List> type :optional min-length max-length
681 @deftpx {Type Constructor} <Vector> type :optional min-length max-length
682 @clindex List
683 @clindex Vector
684 @c EN
685 @var{Type} must be a type expression.
686
687 These create a list or a vector type whose elements are of @var{type},
688 respectively.
689 For example, @code{(<List> <string>)} is a list of strings.
690 @c JP
691 @var{type}は型の式でなければなりません。
692
693 各要素が@var{type}であるようなリストもしくはベクタの型を作ります。
694 例えば@code{(<List> <string>)}は文字列のリストです。
695 @c COMMON
696
697 @c EN
698 The optional arguments must be a literal real numbers that limit
699 the minimum and maximum (inclusive) length of the list or the vector.
700 When omitted, @var{min-length}
701 is zero and @var{max-length} is @code{inf.0}.
702 @c JP
703 省略可能引数はどちらも実数でなければならず、
704 それぞれリストやベクタの長さの最小値と最大値(両端含む)を指定します。
705 省略された場合、@var{min-length}は0、@var{max-length}は無限大です。
706 @c COMMON
707
708 @c EN
709 Note: @code{subtype?} uses covariant subtyping, that is,
710 @code{(subtype? (<List> <string>) <list>)} is @code{#t}.
711 @c JP
712 註: @code{subtype?}は共変関係を見ます。つまり、
713 @code{(subtype? (<List> <string>) <list>)}は@code{#t}です。
714 @c COMMON
715 @end deftp
716
717 @deftp {Type Constructor} <Assortment> constant @dots{}
718 @clindex Assortment
719 @c EN
720 @var{Constants} must be an expression that evaluates to a symbol,
721 a boolean or a number, at the compile time. This type expression
722 creates a type whose instances are limited to the given constant values.
723 @c JP
724 @var{constants}はコンパイル時にシンボル、真偽値、あるいは数値に評価される式でなければなりません。
725 この型の式は、与えられた定数のみをインスタンスとみなす記述型を作ります。
726 @c COMMON
727
728 @example
729 (define (p obj)
730 (of-type? obj (<Assortment> 'one 'two 'three)))
731
732 (p 'one) @result{} #t
733 (p 'three) @result{} #t
734 (p 'four) @result{} #f
735 @end example
736
737 @c EN
738 Mere membership test can be realized simply with a list or a set, but
739 the construction of assortment type is done in compile-time, and
740 potentially creates opportunities for optimizations or compile-time
741 checks. For example, you can proclaim the argument is only allowed
742 with certain set of symbols:
743 @c JP
744 単なるメンバシップの検査ならリストやセットでもできますが、
745 assortment型の生成はコンパイル時に行われ、
746 最適化やコンパイル時検査の機会を増やします。
747 例えば、引数が特定のシンボルのいずれかしか取らないことを、次のような形で
748 宣言しておくことができるでしょう。
749 @c COMMON
750
751 @example
752 (define (p obj)
753 (assume-type obj (<Assortment> 'one 'two 'three))
754 ...)
755 @end example
756
757 @c EN
758 Currently, it is only used by a runtime check. However, in futuer version
759 of Gauche, the compiler knows the argument @var{obj} must be one of these
760 symbols, and may use that information for static analysis.
761 @c JP
762 現在のところこれは実行時チェックに使われるだけですが、
763 将来のGaucheではコンパイラが、引数はこれらのシンボルしか許されないという情報を
764 静的解析に利用するかもしれません。
765 @c COMMON
766 @end deftp
767
768
769 @node Native types, , Type expressions and type constructors, Types and classes
770 @subsection Native types
771 @c NODE ネイティブタイプ
772
773 @c EN
774 Native types are a set of predefined descriptive types that bridge
775 Scheme types and C types. They can be used to access binary blobs
776 passed from a foreign functions, for example. They'll also be used
777 for FFI.
778 @c JP
779 ネイティブタイプは、Schemeの型とCの型の橋渡しをするためにあらかじめ定義されている型です。
780 外部の関数から渡されたバイナリデータの中身にアクセスする時などに使えます。
781 将来的にはFFIにも使う予定です。
782 @c COMMON
783
784 @c EN
785 An example of native types is @code{<int16>}, which corresponds to
786 C's @code{int16_t}. You can use @code{<int16>} to check if a Scheme
787 object can be treated as that type:
788 @c JP
789 ネイティブタイプの一例は@code{<int16>}です。これはCの@code{int16_t}に相当します。
790 例えばCの@code{int16_t}としてSchemeオブジェクトを渡せるかどうかを
791 次のとおり検査できます。
792 @c COMMON
793
794 @example
795 (of-type? 357 <int16>) @result{} #t
796 (of-type? 50000 <int16>) @result{} #f
797 @end example
798
799 @c EN
800 Or obtain size and alignment info on the running platform:
801 @c JP
802 また、実行中のプラットフォームにおけるその型のデータの大きさやアラインメントを知ることもできます。
803 @c COMMON
804
805 @example
806 gosh> (describe <int16>)
807 #<native-type <int16>> is an instance of class <native-type>
808 slots:
809 name : <int16>
810 super : #<class <integer>>
811 c-type-name: "int16_t"
812 size : 2
813 alignment : 2
814 @end example
815
816 @deftp {Native type} <fixnum>
817 @deftpx {Native type} <int>
818 @deftpx {Native type} <int8>
819 @deftpx {Native type} <int16>
820 @deftpx {Native type} <int32>
821 @deftpx {Native type} <int64>
822 @deftpx {Native type} <short>
823 @deftpx {Native type} <long>
824 @deftpx {Native type} <uint>
825 @deftpx {Native type} <uint8>
826 @deftpx {Native type} <uint16>
827 @deftpx {Native type} <uint32>
828 @deftpx {Native type} <uint64>
829 @deftpx {Native type} <ushort>
830 @deftpx {Native type} <ulong>
831 @deftpx {Native type} <float>
832 @deftpx {Native type} <double>
833 @deftpx {Native type} <size_t>
834 @deftpx {Native type} <ssize_t>
835 @deftpx {Native type} <ptrdiff_t>
836 @deftpx {Native type} <off_t>
837 @deftpx {Native type} <void>
838 @clindex fixnum
839 @clindex int
840 @clindex int8
841 @clindex int16
842 @clindex int32
843 @clindex int64
844 @clindex short
845 @clindex long
846 @clindex uint
847 @clindex uint8
848 @clindex uint16
849 @clindex uint32
850 @clindex uint64
851 @clindex ushort
852 @clindex ulong
853 @clindex float
854 @clindex double
855 @clindex size_t
856 @clindex ssize_t
857 @clindex ptrdiff_t
858 @clindex off_t
859 @clindex void
860 @c EN
861 Predefined native types. The correspondence of Scheme and C types
862 are shown below:
863 @c JP
864 定義済みのネイティブタイプです。
865 Cの型との関係は次の表のとおりです。
866 @c COMMON
867
868 @example
869 Native type Scheme C Notes
870 -----------------------------------------------------------------
871 <fixnum> <integer> ScmSmallInt Integers within fixnum range
872
873 <int> <integer> int Integers representable in C
874 <int8> <integer> int8_t
875 <int16> <integer> int16_t
876 <int32> <integer> int32_t
877 <int64> <integer> int64_t
878 <short> <integer> short
879 <long> <integer> long
880 <uint> <integer> uint Integers representable in C
881 <uint8> <integer> uint8_t
882 <uint16> <integer> uint16_t
883 <uint32> <integer> uint32_t
884 <uint6r> <integer> uint64_t
885 <ushort> <integer> ushort
886 <ulong> <integer> ulong
887 <float> <real> float Unboxed value casted to float
888 <double> <real> double
889
890 <size_t> <integer> size_t System-dependent types
891 <ssize_t> <integer> ssize_t
892 <ptrdiff_t> <integer> ptrdiff_t
893 <off_t> <integer> off_t
894
895 <void> - void (Used only as a return type.
896 Scheme function returns #<undef>)
897 @end example
898 @end deftp
899
900
901 @node Equality and comparison, Numbers, Types and classes, Core library
902 @section Equality and comparison
903 @c NODE 等価性と比較
904
905 @c EN
906 Comparing two objects seems trivial, but if you look into deeper,
907 there are lots of subtleties hidden in the corners. What should it
908 mean if two procedures are equal to each other? How to order two
909 complex numbers? It all depends on your purpose; there's no single
910 generic answer. So Scheme (and Gauche) provides several options,
911 as well as the way to make your own.
912 @c JP
913 ふたつのオブジェクトを比較するというのは簡単な話のように思えるかもしれません。
914 しかし詳しく見てゆくと、一筋縄ではいかない特別なケースが出てきます。
915 ふたつの手続きが等しいとはどういうことでしょうか。
916 複素数を何らかの基準で順番に並べるにはどうすばいいでしょう。
917 一般的な回答は無く、目的によるとしか言えません。
918 そこで、Schemeでは(Gaucheも)、いくつかの選択肢を用意しておき、
919 さらに必要ならばユーザが独自の定義を与えることもできるようにしています。
920 @c COMMON
921
922 @menu
923 * Equality::
924 * Comparison::
925 * Hashing::
926 * Basic comparators::
927 @end menu
928
929 @node Equality, Comparison, Equality and comparison, Equality and comparison
930 @subsection Equality
931 @c NODE 等価
932
933 @c EN
934 Scheme has three different general equality test predicates.
935 Other than these, some types have their own comparison predicates.
936 @c JP
937 Schemeには等価性を判定する汎用的な述語が3つあります。
938 また、これらの他に、いくつかの型はその型同士で使える比較手続きを持っています。
939 @c COMMON
940
941 @defun eq? obj1 obj2
942 [R7RS base]
943 @c EN
944 This is the fastest and finest predicate.
945 Returns @code{#t} if @var{obj1} and @var{obj2} are identical
946 objects---that is, if they represents the same object on memory
947 or in a register. Notably, you can compare two symbols or two keywords with
948 @code{eq?} to check if they are the same or not.
949 You can think @code{eq?} as a pointer comparison for
950 any heap-allocated objects.
951
952 Booleans can be compared with @code{eq?}, but you can't
953 compare characters and numbers reliably---objects with the same
954 numerical value may or may not @code{eq?} to each other.
955 If you identity comparison needs to include those objects,
956 use @code{eqv?} below.
957 @c JP
958 最も高速で、細かい区別ができる述語です。
959 @var{obj1}と@var{obj2}が同一(identical)のオブジェクト、
960 すなわち、メモリ上の同じオブジェクトを表している場合に@code{#t}を返します。
961 特に、二つのシンボルもしくは二つのキーワードが同一かどうかを比較するのに@code{eq?}が使えます。
962 ヒープアロケートされるオブジェクトに対しては、ポインタ比較と考えても良いでしょう。
963
964 真偽値も@code{eq?}で比較できますが、文字と数値はたとえ値が同じオブジェクトであっても
965 互いに@code{eq?}になるかどうかはわかりません。
966 同一性比較で文字や数値も扱う必要がある場合は、下の@code{eqv?}を使いましょう。
967 @c COMMON
968
969 @example
970 (eq? #t #t) @result{} #t
971 (eq? #t #f) @result{} #f
972 (eq? 'a 'a) @result{} #t
973 (eq? 'a 'b) @result{} #f
974 (eq? (list 'a) (list 'a)) @result{} #f
975 (let ((x (list 'a)))
976 (eq? x x)) @result{} #t
977 @end example
978 @end defun
979
980 @defun eqv? obj1 obj2
981 [R7RS base]
982 @c EN
983 When @var{obj1} and @var{obj2} are both exact or both inexact numbers
984 (except NaN or -0.0),
985 @code{eqv?} returns @code{#t} iff @code{(= @var{obj1} @var{obj2})} is true.
986 -0.0 is only @code{eqv?} to -0.0.
987 @c JP
988 @var{obj1}と@var{obj2}がともに正確な数値、もしくはともに
989 (NaN、-0.0以外の)非正確な数値である場合、
990 @code{(= @var{obj1} @var{obj2})}が真であれば@code{#t}が、偽であれば@code{#f}が
991 返されます。
992 -0.0は-0.0とだけ@code{eqv?}です。
993 @c COMMON
994
995 @c EN
996 When @var{obj1} and @var{obj2} are both characters,
997 @code{eqv?} returns @code{#t} iff @code{(char=? @var{obj1} @var{obj2})} is true.
998 Otherwise, @code{eqv?} is the same as @code{eq?} on Gauche.
999 @c JP
1000 @var{obj1}と@var{obj2}がともに文字である場合、
1001 @code{(char=? @var{obj1} @var{obj2})}が真であれば@code{#t}が、偽であれば@code{#f}が
1002 返されます。
1003 それ以外の場合は、Gaucheでは@code{eqv?}は@code{eq?}と同じです。
1004 @c COMMON
1005
1006 @example
1007 (eqv? #\a #\a) @result{} #t
1008 (eqv? #\a #\b) @result{} #f
1009 (eqv? 1.0 1.0) @result{} #t
1010 (eqv? 1 1) @result{} #t
1011 (eqv? 1 1.0) @result{} #f
1012 (eqv? (list 'a) (list 'a)) @result{} #f
1013 (let ((x (list 'a)))
1014 (eqv? x x)) @result{} #t
1015 @end example
1016
1017 @c EN
1018 Note that comparison of NaNs has some peculiarity.
1019 Any numeric comparison fails if there's at least one NaN in its argument.
1020 Therefore, @code{(= +nan.0 +nan.0)} is always @code{#f}. However,
1021 Gauche @emph{may} return @code{#t} for @code{(eq? +nan.0 +nan.0)}
1022 or @code{(eqv? +nan.0 +nan.0)}.
1023 @c JP
1024 NaNの比較には少々奇妙なところがあります。数値比較は、引数に一つでもNaNが
1025 含まれていれば失敗します。したがって@code{(= +nan.0 +nan.0)}は常に@code{#f}と
1026 なります。けれども、@code{(eq? +nan.0 +nan.0)} や
1027 @code{(eqv? +nan.0 +nan.0)}は@code{#t}を返すことがあるかもしれません。
1028 @c COMMON
1029 @end defun
1030
1031 @defun equal? obj1 obj2
1032 [R7RS+ base]
1033 @c EN
1034 If @var{obj1} and @var{obj2} are both aggregate types,
1035 @code{equal?} compares its elements recursively.
1036 Otherwise, @code{equal?} behaves the same as @code{eqv?}.
1037
1038 If @var{obj1} and @var{obj2} are not @code{eqv?} to each other,
1039 not of builtin types, and the class of both
1040 objects are the same, @code{equal?} calls the generic
1041 function @code{object-equal?}.
1042 By defining the method, users can extend the behavior of @code{equal?}
1043 for user-defined classes.
1044 @c JP
1045 @var{obj1}と@var{obj2}がリストやベクタなどの複合型である場合、
1046 @code{equal?}は再帰的に対応する要素同士を@code{equal?}で比較してゆきます。
1047 そうでなければ、@code{equal?}は@code{eqv?}と同じようにふるまいます。
1048
1049 もし@code{obj1}と@var{obj2}が互いに@code{eqv?}でなく、
1050 組み込み型でもなく、かつ両者のクラスが等しい場合、@code{equal?}は
1051 ジェネリックファンクション@code{object-equal?}を呼びます。
1052 @code{object-equal?}にメソッドを定義することにより、
1053 ユーザ定義のデータ型に対する@code{equal?}の振るまいを拡張することができます。
1054 @c COMMON
1055
1056 @example
1057 (equal? (list 1 2) (list 1 2)) @result{} #t
1058 (equal? "abc" "abc") @result{} #t
1059 (equal? 100 100) @result{} #t
1060 (equal? 100 100.0) @result{} #f
1061
1062 @c EN
1063 ;; 0.0 and -0.0 is numerically equal (=), but eqv? distingushes them, so as equal?.
1064 @c JP
1065 ;; 0.0と-0.0は数値としては等しい(=)ですが、eqv?は区別し、したがってequal?も区別します。
1066 @c COMMON
1067 (equal? 0.0 -0.0) @result{} #f
1068 @end example
1069
1070 @c EN
1071 Note: This procedure correctly handles the case when
1072 both @var{obj1} and @var{obj2} have cycles through pairs and vectors,
1073 as required by R6RS and R7RS. However, if the cycle involves
1074 user-defined classes, @code{equal?} may fail to terminate.
1075 @c JP
1076 註: この手続きは、@var{obj1}と@var{obj2}がともにペアやベクタを介した
1077 循環構造を持っている場合もR6RSやR7RSに規定されるように値を返します。
1078 ただし、循環構造がユーザ定義データ型を間に挟んでいる場合は
1079 終了しない可能性があります。
1080 @c COMMON
1081 @end defun
1082
1083 @deffn {Generic Function} object-equal? obj1 obj2
1084 @c EN
1085 This generic function is called when @code{equal?} is called on the objects
1086 it doesn't know about. You can define this method on your class
1087 so that @code{equal?} can check equivalence. This method is supposed
1088 to return @code{#t} if @var{obj1} is equal to @var{obj2}, @code{#f}
1089 otherwise. If you want to check equivalence of elements recursively,
1090 do not call @code{object-equal?} directly; call @code{equal?} on each element.
1091 @c JP
1092 @code{equal?}が未知のオブジェクトに対して呼ばれた場合、
1093 このジェネリックファンクションが呼ばれます。自分で定義したクラスに対して
1094 このメソッドを定義することにより、@code{equal?}で等価判定が行えるように
1095 なります。メソッドは、@var{obj1}と@var{obj2}が等価ならば@code{#t}を、
1096 そうでなければ@code{#f}を返さねばなりません。
1097 オブジェクトの各要素に対して再帰的に等価判定を行いたい場合は、
1098 @code{object-equal?}を直接呼ぶのではなく、@code{equal?}を各要素に対して
1099 呼ぶようにして下さい。
1100 @c COMMON
1101
1102 @example
1103 (define-class <foo> ()
1104 ((x :init-keyword :x)
1105 (y :init-keyword :y)))
1106
1107 (define-method object-equal? ((a <foo>) (b <foo>))
1108 (and (equal? (slot-ref a 'x) (slot-ref b 'x))
1109 (equal? (slot-ref a 'y) (slot-ref b 'y))))
1110
1111 (equal? (make <foo> :x 1 :y (list 'a 'b))
1112 (make <foo> :x 1 :y (list 'a 'b)))
1113 @result{} #t
1114
1115 (equal? (make <foo> :x 1 :y (make <foo> :x 3 :y 4))
1116 (make <foo> :x 1 :y (make <foo> :x 3 :y 4)))
1117 @result{} #t
1118 @end example
1119 @end deffn
1120
1121 @deffn {Method} object-equal? (obj1 <top>) (obj2 <top>)
1122 @c EN
1123 This method catches @code{equal?} between two objects of a user-defined
1124 class, in case the user doesn't define a specialized method for the class.
1125
1126 When called, it scans the registered default comparators that can handle
1127 both @var{obj1} and @var{obj2},
1128 and if it finds one, use the comparator's equality
1129 predicate to see if two arguments are equal to each other. When no
1130 matching comparators are found, it just returns @code{#f}.
1131 @xref{Predefined comparators}, about the default comparators:
1132 Look for the entries of
1133 @code{default-comparator} and @code{comparator-register-default!}.
1134
1135 Note: If you define @code{object-equal?} with exactly the same
1136 specializers of this method,
1137 you'll replace it and that breaks
1138 @code{default-comparator} operation. Future versions of Gauche
1139 will prohibit such redefinition. For now, be careful not to redefine
1140 it accidentally.
1141 @c JP
1142 このメソッドは、ユーザ定義クラスの2つのインスタンスが@code{equal?}であるかを
1143 調べる際に、そのクラスに特殊化したメソッドが無かった場合を捕まえるものです。
1144
1145 このメソッドが呼ばれると、まず登録されたデフォルト比較器の中に@var{obj1}と
1146 @var{obj2}を共に処理できるものがあるかどうかを調べ、
1147 あればその比較器の等価述語を使って比較します。デフォルト比較器が引数を処理できなければ
1148 @code{#f}を返します。デフォルト比較器については
1149 @ref{Predefined comparators}を参照してください。特に
1150 @code{default-comparator}と@code{comparator-register-default!}の
1151 項目を見てください。
1152
1153 註: もし、このメソッドと全く同じスペシャライザを
1154 指定して@code{object-equal?}メソッドを定義すると、それはこのメソッドを
1155 置き換えることになり、@code{default-comparator}の動作が壊れることになります。
1156 将来のGaucheのバージョンではそのような再定義は禁止される予定です。
1157 うっかりそういう再定義を行わないように気をつけてください。
1158 @c COMMON
1159 @end deffn
1160
1161 @c EN
1162 Sometimes you want to test if two aggregate structures
1163 are topologically equal, i.e., if one has a shared substructure,
1164 the other has a shared substructure in the same way.
1165 @code{Equal?} can't handle it; module @code{util.isomorph}
1166 provides a procedure @code{isomorphic?} which does the job
1167 (@pxref{Determine isomorphism}).
1168 @c JP
1169 しばしば、ふたつの複合型オブジェクトに関して、両者がトポロジー的に等しいこと、
1170 すなわち一方が共有する部分構造を持っている場合にもう一方も同じように部分構造を
1171 共有しているかどうかを調べたいことがあります。@code{equal?}はその目的には
1172 使えません。モジュール@code{util.isomorph}の提供する@code{isomorphic?}が
1173 その目的に使えます。(@ref{Determine isomorphism}参照)。
1174 @c COMMON
1175
1176 @node Comparison, Hashing, Equality, Equality and comparison
1177 @subsection Comparison
1178 @c NODE 比較
1179
1180 @c EN
1181 Equality only concern about whether two objects are equivalent or not.
1182 However, sometimes we want to see the order among objects. Again,
1183 there's no single ``universal order''. It doesn't make mathematical
1184 sense to ask if one complex number is greater than another, but
1185 having some artificial order is useful when you want a consistent
1186 result of sorting a list of objects including numbers.
1187 @c JP
1188 等価性はオブジェクトが等しいかどうかしか判断しませんが、しばしば
1189 オブジェクトの順序関係を調べたい場合もあります。
1190 ここでも、唯一の「万能順序」があるわけではありません。例えばある複素数が
1191 別の複素数より大きいか小さいかというのは数学的には意味をなしませんが、
1192 数値を含むオブジェクトのリストをソートして一貫性のある結果を得たい場合は
1193 何らかの適当な順序づけを決めておくことは役に立ちます。
1194 @c COMMON
1195
1196 @defun compare obj1 obj2
1197 @c EN
1198 A general comparison procedure. Returns -1 if @var{obj1} is less than
1199 @var{obj2}, 0 if @var{obj1} is equal to @var{obj2}, and 1 if @var{obj1}
1200 is greater than @var{obj2}.
1201 @c JP
1202 一般的な比較手続きです。@var{obj1}が@var{obj2}より小さければ-1を、
1203 等しければ0を、大きければ1を返します。
1204 @c COMMON
1205
1206 @c EN
1207 If @var{obj1} and @var{obj2} are incomparable, an error is signalled.
1208 However, @code{compare} defines total order between most Scheme objects,
1209 so that you can use it on wide variety of objects. The definition is
1210 upper-compatible to the order defined in SRFI-114.
1211 @c JP
1212 @var{obj1}と@var{obj2}が比較できない場合はエラーとなりますが、
1213 @code{compare}は多くのSchemeオブジェクト間に全順序を定義しているので、
1214 様々なオブジェクトの比較に使うことができます。この全順序は、
1215 SRFI-114で定義されているものの上位互換です。
1216 @c COMMON
1217
1218 @c EN
1219 Some built-in types are handled by this procedure reflecting
1220 ``natural'' order of comparison if any (e.g. real numbers are compared
1221 by numeric values, characters are compared by @code{char<} etc.)
1222 For convenience,
1223 it also defines superficial order between objects that doesn't have
1224 natural order; complex numbers are ordered first by their real part,
1225 then their imaginary part, for example. That is,
1226 @code{1+i} comes before @code{2-i},
1227 which comes before @code{2}, which comes before @code{2+i}.
1228 @c JP
1229 組み込みオブジェクトのうち、自然な順序が定義されているものはそれに従って順序づけられます
1230 (例えば実数はその数値の大小で、文字は@code{char<}等を使って比較されます)。
1231 また便宜上、通常の意味で大小が定義されないオブジェクトについても
1232 ある程度表面的な順序が定義されます。例えば複素数は、まず実部の大小によって
1233 順序づけられ、次に虚部の大小によって順序づけられます。
1234 すなわち、@code{1+i}、@code{2-i}、@code{2}、@code{2+i}はこの順番に並びます。
1235 @c COMMON
1236
1237 @c EN
1238 Boolean false comes before boolean true.
1239 @c JP
1240 @code{#f}は@code{#t}より前に来ます。
1241 @c COMMON
1242
1243 @c EN
1244 Lists are ordered by dictionary order: Take the common prefix.
1245 If either one is @code{()} and the other is not, @code{()} comes first.
1246 If both tails are not empty, compare the heads of the tails.
1247 (This makes empty list the ``smallest'' of all lists).
1248 @c JP
1249 リストは辞書順で比較されます。すなわち、まず共通のプリフィクスを除きます。
1250 一方が@code{()}でもう一方がそうでなければ、@code{()}である方が先にきます。
1251 どちらの尾部も空でなければ、尾部の先頭要素同士を比べます。
1252 (この定義により、空リストは全てのリストの「最小」のものになります)。
1253 @c COMMON
1254
1255 @c EN
1256 Vectors (including uniform vectors) are compared first by their
1257 lengths, and if they are the same, elements are compared from left to right.
1258 Note that it's different from lists and strings.
1259 @c JP
1260 (ユニフォームベクタを含む)ベクタは、まず長さで比較され、
1261 長さが同じ場合は要素同士が左から比較されます。
1262 リストや文字列とは異なることに注意。
1263 @c COMMON
1264
1265 @example
1266 (compare '(1 2 3) '(1 3))
1267 @result{} -1 ; (1 2 3) is smaller
1268 (compare '#(1 2 3) '#(1 3))
1269 @result{} 1 ; #(1 3) is smaller
1270 (compare "123" "13")
1271 @result{} -1 ; "123" is smaller
1272 @end example
1273
1274 @c EN
1275 If two objects are of subclasses of @code{<object>},
1276 a generic function @code{object-compare} is called.
1277 @c JP
1278 二つのオブジェクトがともに@code{<object>}のサブクラスであれば、
1279 ジェネリックファンクション@code{object-compare}が呼ばれます。
1280 @c COMMON
1281
1282 @c EN
1283 If two objects are of different types and at least one of them
1284 isn't @code{<object>}, then they are ordered by their types.
1285 SRFI-114 defines the order of builtin types as follows:
1286 @c JP
1287 二つのオブジェクトが異なる型で、少なくとも一方が@code{<object>}でない時は、
1288 両者の型により順序が決まります。SRFI-114は組み込み型について
1289 次の順序を定めています。
1290 @c COMMON
1291
1292 @enumerate
1293 @item
1294 Empty list.
1295 @item
1296 Pairs.
1297 @item
1298 Booleans.
1299 @item
1300 Characters.
1301 @item
1302 Strings.
1303 @item
1304 Symbols.
1305 @item
1306 Numbers.
1307 @item
1308 Vectors.
1309 @item
1310 Uniform vectors
1311 (u8 < s8 < u16 < s16 < u32 < s32 < u64 < s64 < f16 < f32 < f64)
1312 @item
1313 @c EN
1314 All other objects.
1315 @c JP
1316 他のオブジェクトすべて
1317 @c COMMON
1318 @end enumerate
1319 @end defun
1320
1321 @deffn {Generic Function} object-compare obj1 obj2
1322 @c EN
1323 Specializing this generic function extends @code{compare} procedure
1324 for user-defined classes.
1325
1326 This method must return either @code{-1} (@var{obj1} precedes @var{obj2}),
1327 @code{0} (@var{obj1} equals to @var{obj2}),
1328 @code{1} (@var{obj1} succeeds @var{obj2}),
1329 or @code{#f} (@var{obj1} and @var{obj2} cannot be ordered).
1330 @c JP
1331 このジェネリックファンクションを特殊化することで
1332 @code{compare}手続きをユーザ定義クラスに対して動作するように拡張できます。
1333
1334 このメソッドは以下のいずれかの値を返さねばなりません。
1335 @code{-1} (@var{obj1}は@var{obj2}より前)、
1336 @code{0} (@var{obj1}と@var{obj2}は等しい)、
1337 @code{1} (@var{obj1}は@var{obj2}より後)、
1338 @code{#f} (@var{obj1}と@var{obj2}は順序づけできない)。
1339 @c COMMON
1340 @end deffn
1341
1342 @deffn {Method} object-compare (obj1 <top>) (obj2 <top>)
1343 @c EN
1344 This method catches @code{compare} between two objects of a
1345 user-defined class, in case the user doesn't define a specialized
1346 method for the class.
1347
1348 When called, it scans the registered default comparators that can
1349 handle both @var{obj1} and @var{obj2},
1350 and if it finds one, use the comparator's compare procedure
1351 to determine the order of @var{obj1} and @var{obj2}.
1352 When no matching comparators are found, it returns @code{#f}, meaning
1353 two objects can't be ordered.
1354 @xref{Predefined comparators}, about the default comparators:
1355 Look for the entries of
1356 @code{default-comparator} and @code{comparator-register-default!}.
1357
1358 Note: If you define @code{object-compare} with exactly the same
1359 specializers of this method,
1360 you'll replace it and that breaks
1361 @code{default-comparator} operation. Future versions of Gauche
1362 will prohibit such redefinition. For now, be careful not to redefine
1363 it accidentally.
1364 @c JP
1365 このメソッドは、ユーザ定義クラスの2つのインスタンスを@code{compare}する
1366 際に、そのクラスに特殊化したメソッドが無かった場合を捕まえるものです。
1367
1368 このメソッドが呼ばれると、まず登録されたデフォルト比較器の中に@var{obj1}と
1369 @var{obj2}を共に処理できるものがあるかどうかを調べ、
1370 あればその比較器の比較手続きを使って両者の順序を判定します。
1371 デフォルト比較器が引数を処理できなければ
1372 @code{#f}(「比較できない」)を返します。デフォルト比較器については
1373 @ref{Predefined comparators}を参照してください。特に
1374 @code{default-comparator}と@code{comparator-register-default!}の
1375 項目を見てください。
1376
1377 註: もし、このメソッドと全く同じスペシャライザを
1378 指定して@code{object-compare}メソッドを定義すると、それはこのメソッドを
1379 置き換えることになり、@code{default-comparator}の動作が壊れることになります。
1380 将来のGaucheのバージョンではそのような再定義は禁止される予定です。
1381 うっかりそういう再定義を行わないように気をつけてください。
1382 @c COMMON
1383 @end deffn
1384
1385
1386 @defun eq-compare obj1 obj2
1387 @c EN
1388 Returns -1 (less than), 0 (equal to) or 1 (greater than)
1389 according to a certain total ordering of
1390 @var{obj1} and @var{obj2}. Both arguments can be any Scheme
1391 objects, and can be different type of objects.
1392 The following properties are guaranteed.
1393
1394 @itemize @bullet
1395 @item
1396 @code{(eq-compare x y)} is 0 iff @code{(eq? x y)} is @code{#t}.
1397 @item
1398 The result is consistent within a single run of the process
1399 (but may differ between runs).
1400 @end itemize
1401
1402 Other than these, no actual semantics are given to the ordering.
1403
1404 This procedure is useful when you need to order arbitrary Scheme
1405 objects, but you don't care the actual order as far as it's consistent.
1406 @c JP
1407 とある全順序に従って@var{obj1}と@var{obj2}を比較し、前者が小さければ-1、
1408 等しければ0、前者が大きければ1を返します。@var{obj1}と@var{obj2}は
1409 どんなSchemeオブジェクトでも良く、また型が違っていても構いません。
1410 次の二つの性質が保証されます。
1411
1412 @itemize @bullet
1413 @item
1414 @code{(eq? x y)}が@code{#t}なら、そしてその時に限り、
1415 @code{(eq-compare x y)}は0。
1416 @item
1417 結果は、一回のプロセスの実行中で一貫している
1418 (ただし、別のプロセスの実行では異なる結果を返すかもしれない)。
1419 @end itemize
1420
1421 これらの性質以外には、順序についていかなる意味もありません。
1422
1423 この手続きは、任意のSchemeオブジェクトをとにかく順序づけたい
1424 (一貫してさえいれば、実際の順序は何でも良い)、という場合に使います。
1425 @c COMMON
1426 @end defun
1427
1428 @node Hashing, Basic comparators, Comparison, Equality and comparison
1429 @subsection Hashing
1430 @c NODE ハッシュ
1431
1432 @c EN
1433 Hash functions have close relationship with equality predicate,
1434 so we list them here.
1435
1436 @c JP
1437 ハッシュ関数は等価判定述語と関係が深いので、ここで説明します。
1438 @c COMMON
1439
1440 @defun eq-hash obj
1441 @defunx eqv-hash obj
1442 @c EN
1443 These are hash functions suitable to be used
1444 with @code{eq?} and @code{eqv?}, respectively.
1445 The returned hash value is system- and process-dependent,
1446 and can't be carried over the boundary of the running process.
1447
1448 Note: don't hash numbers by @code{eq-hash}. Two numbers
1449 are not guaranteed to be @code{eq?} even if they are numerically equal.
1450 @c JP
1451 この2つはそれぞれ@code{eq?}および @code{eqv?}と一緒に使うのに適した
1452 ハッシュ関数です。返り値のハッシュ値は、
1453 システムおよびプロセスに依存する値です。動作しているプロセスの境界を
1454 超えてもちまわることはできません。
1455
1456 注意: @code{eq-hash} をつかって、数をハッシュしてはいけません。
1457 2つの数はたとえその値が等しくても @code{eq?} であることは保証されて
1458 いません。
1459 @c COMMON
1460 @end defun
1461
1462 @defun default-hash obj
1463 [R7RS+ comparator]
1464 @c EN
1465 This is a hash function suitable to be used with @code{equal?}.
1466 In R7RS, this is defined in @code{scheme.comparator} (originally
1467 in @code{srfi.128}).
1468
1469 If @var{obj} is either a number, a boolean, a character,
1470 a symbol, a keyword, a string, a list, a vector or a uniform vector,
1471 internal hash function is used to calculate the hash value.
1472 If @var{obj} is other than that,
1473 a generic function @code{object-hash} is called to calculate the hash value
1474 (see below).
1475
1476 The hash value also depends on @code{hash-salt}, which differs
1477 for every run of the process.
1478 @c JP
1479 @code{equal?}と一緒に使うのに適したハッシュ関数です。
1480 R7RSでは、@code{scheme.comparator}ライブラリで定義されています
1481 (元は@code{srfi.128})。
1482
1483 @var{obj} が、数値、真理値、文字、シンボル、キーワード、文字列、リスト、
1484 ベクタ、ユニフォームベクタのいずれかならば、そのハッシュ値を求めるのには内部ハッシュ関数を
1485 使います。
1486 @var{obj} が、それ以外であれば、 @code{hash} は総称関数 @code{object-hash}
1487 を呼んで、そのハッシュ値を計算します。
1488
1489 返されるハッシュ値は@code{hash-salt}の値にも依存します。@code{hash-salt}
1490 はプロセスが走る度に異なる値をとります。
1491 @c COMMON
1492 @end defun
1493
1494 @defun portable-hash obj salt
1495 @c EN
1496 Sometimes you need to calculate a hash value that's ``portable'',
1497 in a sense that the value won't change across multiple runs of
1498 the process, nor between different platforms. Such hash value can
1499 be used with storing objects externally to share among processes.
1500
1501 This procedure calculates a hash value of @var{obj} with such
1502 characteristics; the hash value is the same for the same
1503 object and the same salt value.
1504 Here ``same object'' roughly means having
1505 the same external representation. Objects @code{equal?} to each
1506 other are same. If you write out an object with @code{write},
1507 and read it back, they are also the same objects in this sense.
1508
1509 This means objects without read/write invariance, such as
1510 ports, can't be handled with @code{portable-hash}. It is caller's
1511 responsibility that @var{obj} won't contain such objects.
1512
1513 The @var{salt} argument is a nonnegative fixnum and gives variations
1514 in the hash function. You have to use the same salt to get consistent
1515 results.
1516
1517 If @var{obj} is other than a number, a boolean, a character,
1518 a symbol, a keyword, a string, a list, a vector, or a uniform vector,
1519 this procedure calls
1520 a generic function @code{object-hash} is called to calculate the hash value
1521 (see below).
1522 @c JP
1523 時に、「ポータブル」なハッシュ値が必要になることがあります。ここでポータブルとは、
1524 プロセスを何度実行しても、また異なるプラットフォームで実行しても、同じオブジェクト
1525 に対して常に同じ値となることです。そのようなハッシュ値は、
1526 プロセスの外に保存したり他のプロセスと共有するオブジェクトと一緒に使えます。
1527
1528 この手続きは@var{obj}についてその性質を持つハッシュ値を計算して返します。
1529 つまり、同じオブジェクトと同じソルト値が渡されれば同じハッシュ値となる、ということです。
1530 ここで、「同じオブジェクト」とは、だいたい外部表現が同じになるものと
1531 考えて構いません。@code{equal?}であるもの同士は同じです。
1532 また、オブジェクトを@code{write}で書き出して@code{read}で読み込んだものは
1533 元のオブジェクトと同じになります。
1534
1535 このことから、read/write不変性をもたないオブジェクトは@code{portable-hash}
1536 では扱えません。@var{obj}がそのようなオブジェクトを含まないことは
1537 呼び出し側で保証する必要があります。
1538
1539 @var{salt}は非負のfixnumで、ハッシュ関数に変化をつけます。一貫した結果を
1540 得るには同じソルト値を使わなければなりません。
1541
1542 @var{obj}が数値、真理値、文字、シンボル、キーワード、文字列、リスト、
1543 ベクタ、ユニフォームベクタのいずれでもない場合、ハッシュ値を計算するのに
1544 総称関数 @code{object-hash}が呼ばれます。
1545 @c COMMON
1546 @end defun
1547
1548 @defun legacy-hash obj
1549 @c EN
1550 Up to 0.9.4, Gauche had a hash function called @code{hash}
1551 that was used in both @code{equal?}-hashtable @emph{and}
1552 for the portable hash function. It had a problem, though.
1553 @c JP
1554 バージョン0.9.4まで、Gaucheでは@code{hash}と呼ばれるハッシュ関数が
1555 @code{equal?}ハッシュテーブル用のハッシュ計算と
1556 ポータブルなハッシュ値の計算の両方を兼ねていました。
1557 しかしそれには問題がありました。
1558 @c COMMON
1559
1560 @enumerate
1561 @item
1562 @c EN
1563 There was no way to salt the hash function, which makes the
1564 hashtables storing externally provided data vulnerable
1565 to collision attack.
1566 @c JP
1567 ハッシュ関数にソルトを与えることができなかったため、
1568 外部からのデータによる衝突攻撃が可能だった
1569 @c COMMON
1570 @item
1571 @c EN
1572 The hash function behaves poorly, especially on flonums.
1573 @c JP
1574 ハッシュ関数自体があまり良くなかった(特に浮動小数点数)
1575 @c COMMON
1576 @item
1577 @c EN
1578 There are bugs in bignum and flonum hashing code that
1579 have produced different results on different architectures.
1580 @c JP
1581 多倍長整数と浮動小数点数のハッシュ値計算で、
1582 異なるアーキテクチャで異なる値を返してしまうバグがあった。
1583 @c COMMON
1584 @end enumerate
1585
1586 @c EN
1587 Since there are existing hash values calculated with
1588 the old hash function, we preserve the behavior of the
1589 original @code{hash} function as @code{legacy-hash}.
1590 Use this when you need to access old data.
1591 (The @code{hash} function also behaves as @code{legacy-hash}
1592 by default, but it has tweaks; see below.)
1593 @c JP
1594 既に@code{hash}で計算されたハッシュ値を利用しているデータがあるため、
1595 以前の@code{hash}で提供していたハッシュ関数を@code{legacy-hash}として
1596 保存することにしました。古いデータにアクセスする場合に使ってください。
1597 (@code{hash}関数自体もデフォルトでは
1598 @code{legacy-hash}と同様に振る舞いますが、ちょっとした仕掛けがあります。
1599 下の説明を参照)。
1600 @c COMMON
1601
1602 @c EN
1603 The new code that needs portable hash value should use
1604 @code{portable-hash} instead.
1605 @c JP
1606 新たに書くコードでポータブルなハッシュ値が必要なら
1607 @code{portable-hash}を使ってください。
1608 @c COMMON
1609 @end defun
1610
1611 @deffn {Generic Function} object-hash obj rec-hash
1612 @c EN
1613 By defining a method for this generic function, objects of
1614 user-defined types can have a hash value and can be used
1615 in a @code{equal?} hash table.
1616
1617 The method has to return an exact non-negative integer,
1618 and must return the same value for two object which are @code{equal?}.
1619 Furthermore, the returned value must not rely on the platform
1620 or state of the process, if @var{obj} is a portable object
1621 (see @code{portable-hash} above for what is portable.)
1622
1623 If the method needs to get hash value of @var{obj}'s elements,
1624 it has to call @var{rec-hash} on them. It guarantees that
1625 the proper hash function is called recursively. So you can
1626 count on @var{rec-hash} to calculate a portable hash value
1627 when @code{object-hash} itself is called from @code{portable-hash}.
1628
1629 If @var{obj} has several elements,
1630 you can call @code{combine-hash-value} on the elements'
1631 hash values.
1632 @c JP
1633 この総称関数に対するメソッドを定義することにより、ユーザ定義された
1634 型のオブジェクトはハッシュ値を持つことができ、@code{equal?}型のハッシュ
1635 テーブルで利用できるようになります。
1636
1637 メソッドは正確な非負整数を返さなければなりません。また、
1638 互いに@code{equal?}であるオブジェクト同士に対しては同じハッシュ値を
1639 返さなければなりません。
1640 さらに、@var{obj}がポータブル(「ポータブル」の意味については
1641 上の@code{portable-hash}の説明を参照)の場合には、
1642 ハッシュ値は実行中のプラットフォームやプロセスの状態に依存してはなりません。
1643
1644 メソッドが @var{obj} の要素のハッシュ値を必要とする場合には、
1645 それらに対して、@var{rec-hash}を呼び出してください。そうすれば
1646 適切なハッシュ関数が再帰的に呼び出されます。例えば@code{object-hash}が
1647 @code{portable-hash}経由で呼び出されている場合、
1648 @var{rec-hash}を呼べば同じソルト値でポータブルなハッシュ値が計算されます。
1649
1650 @var{obj}がいくつかの要素を持っている場合、各要素のハッシュ値を
1651 まとめるには@code{combine-hash-value}を呼びます。
1652 @c COMMON
1653 @example
1654 (define-class <myclass> () (x y))
1655
1656 ;; user-defined equality function
1657 (define-method object-equal? ((a <myclass>) (b <myclass>))
1658 (and (equal? (ref a 'x) (ref b 'x))
1659 (= (abs (ref a 'y)) (abs (ref b 'y)))))
1660
1661 ;; user-defined hash function
1662 (define-method object-hash ((a <myclass>) rec-hash)
1663 (combine-hash-value (rec-hash (ref a 'x))
1664 (rec-hash (abs (ref a 'y)))))
1665 @end example
1666
1667 @c EN
1668 Note: The base method of @code{object-hash} hashes any object
1669 to a single hash value (the actual value depends on @code{hash-salt}
1670 if @code{object-hash} is called from @code{default-hash},
1671 and a fixed constant value otherwise.
1672 It's because object's equality semantics can be customized separately,
1673 and we can't compute a non-constant hash value without knowing the
1674 equality semantics.
1675
1676 This behavior is the last ``safety net''; in general, you should define
1677 @code{object-hash} method on your class if the instances of your class
1678 can ever be hashed.
1679 @c JP
1680 註: @code{object-hash}のベースメソッドは、どんな引数に対しても
1681 単一の値を返します (具体的な値は、@code{object-hash}が
1682 @code{default-hash}から呼ばれた場合は@code{hash-salt}に依存します。
1683 それ以外の場合は固定値です)。
1684 これは、オブジェクトの等価性が自由に設定できるからで、
1685 等価性を知らずに意味のあるハッシュ値を計算できないあらです。
1686
1687 この振る舞いは最後の安全ネットと考えるべきで、一般には自分で定義したクラスのインスタンスが
1688 ハッシュされる可能性があるなら、必ず@code{object-hash}メソッドを定義するように
1689 してください。
1690 @c COMMON
1691 @end deffn
1692
1693 @deffn {Method} object-hash (obj <top>) rec-hash
1694 @deffnx {Method} object-hash (obj <top>)
1695 @c EN
1696 These two methods are defined by the system and ensures the
1697 backward compatibility and the behavior of @code{default-comparator}.
1698 Be careful not to replace these methods by defining the exactly same
1699 specializers. In future versions of Gauche, attempts to replace
1700 these methods will raise an error.
1701 @c JP
1702 これら二つのメソッドはシステムで定義されており、
1703 後方互換性および@code{default-comparator}の正しい振る舞いを保証しています。
1704 全く同じスペシャライザを持つメソッドを定義することでこれらを置き換えてしまわないように
1705 注意してください。将来のバージョンでは、これらのメソッドを置き換えるのは
1706 エラーになる予定です。
1707 @c COMMON
1708 @end deffn
1709
1710 @defun combine-hash-value ha hb
1711 @c EN
1712 Returns a hash value which is a combination of two hash
1713 values, @var{ha} and @var{hb}. The guaranteed invariance
1714 is that if @code{(= ha1 ha2)} and @code{(= hb1 hb2)}
1715 then @code{(= (combine-hash-value ha1 hb1) (combine-hash-value ha2 hb2))}.
1716 This is useful to write user-defined @code{object-hash} method.
1717 @c JP
1718 二つのハッシュ値@var{ha}と@var{hb}を組み合わせたハッシュ値を返します。
1719 次の性質が保証されます:@code{(= ha1 ha2)} かつ @code{(= hb1 hb2)}
1720 ならば @code{(= (combine-hash-value ha1 hb1) (combine-hash-value ha2 hb2))}。
1721 これはユーザ定義の@code{object-hash}メソッドを書くのに便利です。
1722 @c COMMON
1723 @end defun
1724
1725 @defun hash obj
1726 @c EN
1727 This function is deprecated.
1728
1729 Calculate a hash value of @var{obj} suitable for @code{equal?} hash.
1730 By default, it returns the same value as @code{legacy-hash}. However,
1731 if this is called from @code{default-hash} or @code{portable-hash}
1732 (via @code{object-hash} method), it recurses to the calling hash
1733 function.
1734
1735 The behavior is to keep the legacy code work. Until 0.9.5,
1736 @code{hash} is the only hash function to be used for both portable
1737 hash and @code{equal?}-hash, and @code{object-hash} method takes single
1738 argument (an object to hash) and calls @code{hash} recursively whenever it
1739 needs to get a hash value of other objects pointed from the argument.
1740
1741 As of 0.9.5 we have more than one hash functions that calls
1742 @code{object-hash}, so the method takes the hash function as
1743 the second argument to recurse. However, we can't just break
1744 the legacy code; so there's a default method defined in
1745 @code{object-hash} which is invoked when no two-arg method
1746 is defined for the given object, and dispatches to one-arg method.
1747 As far as the legacy @code{object-hash}
1748 code calls @code{hash}, it calls proper function.
1749 The new code shouldn't rely on this behavior, and must use
1750 the second argument of @code{object-hash} instead.
1751 @c JP
1752 この関数は非推奨となりました。
1753
1754 @code{equal?}ハッシュとして使える、@var{obj}のハッシュ値を返します。
1755 デフォルトでは、この関数は@code{legacy-hash}と同じ値を返します。
1756 しかし、この関数が@code{default-hash}か@code{portable-hash}から
1757 (@code{object-hash}を経由して)呼ばれた場合は、呼び出したハッシュ関数へと
1758 再帰します。
1759
1760 この振る舞いは既存のコードを動かすためのものです。0.9.5より前は、
1761 @code{hash}が、ポータブルなハッシュ値にも@code{equal?}ハッシュテーブルにも
1762 使えるハッシュ値を計算する唯一の関数でした。@code{object-hash}メソッドは
1763 ハッシュ値を計算したいオブジェクトだけを引数に取り、もしそのオブジェクトが
1764 指す他のオブジェクトのハッシュ値が欲しいなら、@code{hash}を再帰呼び出ししていました。
1765
1766 0.9.5から、@code{object-hash}はいくつかのハッシュ関数から呼び出されるようになり、
1767 第2引数に再帰すべきハッシュ関数を取るようになりました。
1768 けれども既存のコードを動かなくしてしまうわけにはいきません。そこで、
1769 @code{object-hash}のデフォルトメソッド(2引数でマッチするメソッドが
1770 無い場合に呼ばれるもの)が、1引数の@code{object-hash}を呼び出すように
1771 定義されています。既存の@code{object-hash}が@code{hash}を呼び出していれば、
1772 正しいハッシュ関数へと再帰するというわけです。
1773 新たに書くコードはこの振る舞いに依存してはいけません。
1774 2引数の@code{object-hash}メソッドを定義してください。
1775 @c COMMON
1776 @end defun
1777
1778
1779 @defun boolean-hash bool
1780 @defunx char-hash char
1781 @defunx char-ci-hash char
1782 @defunx string-hash str
1783 @defunx string-ci-hash str
1784 @defunx symbol-hash sym
1785 @defunx number-hash num
1786 [R7RS comparator]
1787 @c EN
1788 These are hash functions for specific type of objects,
1789 defined in R7RS @code{scheme.comparator}.
1790 In Gauche, these procedures are just a wrapper of @code{default-hash}
1791 with type checks (and case folding when relevant). These are
1792 mainly provided to conform @code{scheme.comparator}; in your code you might
1793 just want to use @code{default-hash} (or @code{eq-hash}/@code{eqv-hash},
1794 depending on the equality predicate).
1795 @c JP
1796 これらは、R7RSの@code{scheme.comparator}で定義された、
1797 特定の型のオブジェクト専用のハッシュ関数です。
1798 Gaucheでは、これらの関数は単に引数の型チェックをして(必要なら大文字小文字の
1799 区別をなくした後)、組み込みの@code{default-hash}を呼び出しているだけです。
1800 これらは@code{scheme.comparator}で定義されているために提供されていますが、
1801 特にポータビリティが必要でなければ@code{default-hash}
1802 (あるいは、等価述語によっては@code{eq-hash}や
1803 @code{eqv-hash})を呼んでしまう方が簡単だし高速です。
1804 @c COMMON
1805
1806 @c EN
1807 The case-folding versions, @code{char-ci-hash} and
1808 @code{string-ci-hash}, calls @code{char-foldcase} and
1809 @code{string-foldcase} respectively, on the argument before
1810 passing it to @code{hash}.
1811 (@xref{Characters}, for @code{char-foldcase}.
1812 @xref{Full string case conversion}, for @code{string-foldcase}).
1813 @c JP
1814 大文字小文字を区別しない、@code{char-ci-hash}および@code{string-ci-hash}は、
1815 引数にそれぞれ@code{char-foldcase}と@code{string-foldcase}を適用してから
1816 @code{hash}に渡します。
1817 (@code{char-foldcase}については@ref{Characters}を、
1818 @code{string-foldcase}については@ref{Full string case conversion}を
1819 参照してください。)
1820 @c COMMON
1821 @end defun
1822
1823 @defun hash-bound
1824 @defunx hash-salt
1825 [R7RS comparator]
1826 @c EN
1827 Both evaluates to an exact nonnegative integers. In R7RS,
1828 these are defined in @code{scheme.comparator}.
1829
1830 (Note: @code{scheme.comparator}
1831 defines these as macros, in order to allow
1832 implementations optimize runtime overhead. In Gauche we use
1833 procedures but the overhead is negligible.)
1834
1835 User-defined hash functions can limit the range of the result between
1836 0 and @code{(hash-bound)}, respectively, without worrying to lose
1837 quality of hash function. (User-defined hash functions don't need
1838 to honor @code{(hash-bound)} at all; hashtables takes modulo when
1839 necessary.)
1840
1841 User-defined hash function can also take into account of the
1842 value @code{(hash-salt)} into hash calculation; the salt value may
1843 differ between runs of the Scheme processes, or even between
1844 hash table instances. It is to avoid collision attack.
1845 Built-in hash functions already takes the salt value into account,
1846 so if your hash function is combining the hash values of
1847 primitive types, you don't need to worry about salt values.
1848 @c JP
1849 どちらも、正確な非負整数へと展開されます。R7RSでは、
1850 @code{scheme.comparator}ライブラリで定義されています。
1851
1852 (註: @code{scheme.comparator}はこれらをマクロと定義しています。処理系が
1853 ランタイムオーバヘッドを避けられるようにするためです。
1854 Gaucheでは、呼び出しのオーバヘッドはそれほど問題にならないという
1855 立場から、どちらも手続きにしています。)
1856
1857 ユーザ定義のハッシュ関数は、
1858 結果を0と@code{(hash-bound)}の間に限定してもハッシュの質を落とさないことが
1859 保証されます。(ユーザ定義のハッシュ関数は@code{(hash-bound)}を気にする
1860 必要はありません。ハッシュテーブルが必要な時にモジュロを取ります)。
1861
1862 ユーザ定義のハッシュ関数はまた、@code{(hash-salt)}を計算に組み入れることが
1863 できます。展開されるソルト値は、Schemeプロセスの実行ごとに異なる値を
1864 取ったり、ハッシュテーブルごとに異なる値を取るかもしれません。
1865 これは、コリジョン攻撃を回避するためのものです。
1866 組み込みのハッシュ関数は既にソルト値を考慮しているので、
1867 ユーザ定義ハッシュ関数がプリミティブ型のハッシュ値を組み合わせるだけの
1868 場合は、ソルト値を気にする必要はありません。
1869 @c COMMON
1870 @end defun
1871
1872
1873 @node Basic comparators, , Hashing, Equality and comparison
1874 @subsection Basic comparators
1875 @c NODE 基本的な比較器
1876
1877 @c EN
1878 Equality and comparison procedures are parameters in various
1879 data structures. A treemap needs to order its keys;
1880 a hashtable needs to see if the keys are the same or not,
1881 and it also need a hash function consistent with the equality predicate.
1882 @c JP
1883 等価性判定と大小比較は色々なデータ構造のパラメータになっています。
1884 treemapはキーの大小を比較します。ハッシュテーブルはキーが等しいかどうかを調べ、
1885 またハッシュ関数と等価性判定に一貫性が無ければなりません。
1886 @c COMMON
1887
1888 @c EN
1889 If we want to work on generic data structures, we need to abstract those
1890 variations of comparison schemes. So here comes the comparator,
1891 a record that bundles closely-related comparison procedures together.
1892 @c JP
1893 ジェネリックなデータ構造を作りたければ、こういった比較についてのバリエーションを
1894 抽象化する必要があります。そのために導入されたのが比較器(comparator)です。
1895 これは、比較について関係の深いいくつかの手続きをまとめた構造体です。
1896 @c COMMON
1897
1898 @c EN
1899 There are two SRFIs that define comparators. The one that was originally
1900 called SRFI-128 has now become a part of R7RS large as
1901 @code{scheme.comparator}, and we recommend new code to use it.
1902 Gauche has all of @code{scheme.comparator}
1903 procedures built-in. The older, and rather complex one is SRFI-114;
1904 Gauche also supports it mainly for the backward compatibility.
1905 Importantly, Gauche's native @code{<comparator>} object is compatible
1906 to both @code{scheme.comparator} and @code{srfi-114}
1907 comparators.
1908 @c JP
1909 比較器を定義したSRFIは二つあります。SRFI-128と呼ばれていた規格は
1910 R7RS largeに取り込まれ、@code{scheme.comparator}になりました。
1911 新しいコードではそちらを使うべきです。
1912 Gaucheは@code{scheme.comparator}のAPIを全て組み込みで提供します。
1913 古く、より複雑なのがSRFI-114で、Gaucheはそちらは主に後方互換性のために
1914 サポートしています。重要なのは、Gaucheの組み込みの@code{<comparator>}オブジェクトは
1915 @code{scheme.comparator}の比較器としても
1916 SRFI-114の比較器としても使えるということです。
1917 @c COMMON
1918
1919 @menu
1920 * Comparator class and constructors::
1921 * Comparator predicates and accessors::
1922 * Predefined comparators::
1923 * Combining comparators::
1924 @end menu
1925
1926 @node Comparator class and constructors, Comparator predicates and accessors, Basic comparators, Basic comparators
1927 @subsubsection Comparator class and constructors
1928 @c NODE 比較器クラスとコンストラクタ
1929
1930 @deftp {Builtin Class} <comparator>
1931 @c EN
1932 A comparator record that bundles the following procedures:
1933 @c JP
1934 以下の手続きをひとまとめにするレコードです。
1935 @c COMMON
1936
1937 @c EN
1938 @table @emph
1939 @item Type test predicate
1940 Checks if an object can be compared with this comparator.
1941 @item Equality predicate
1942 See if given two objects
1943 are equal to each other; returns a boolean value.
1944 @item Ordering predicate
1945 Compare given two objects, and returns true iff the first one is
1946 strictly precedes the second one. That is, this is a less-than predicate.
1947 @item Comparison procedure
1948 Compare given two objects, and returns either -1 (the first one is less
1949 than the second), 0 (they are equal), or 1 (the first one is greater
1950 than the second).
1951 @item Hash function
1952 Returns a hash value of the given object.
1953 @end table
1954 @c JP
1955 @table @emph
1956 @item 型検査述語
1957 オブジェクトがこの比較器によって扱えるかどうかを調べます。
1958 @item 等価述語
1959 二つのオブジェクトが等価かどうかを判定し、等価なら@code{#t}を、そうでなければ@code{#f}
1960 を返します。
1961 @item 順序手続き
1962 二つのオブジェクトの大小関係を判定し、
1963 最初のオブジェクトが二つ目のオブジェクトより小さければ@code{#t}を、
1964 そうでなければ@code{#f}を返します。
1965 @item 比較手続き
1966 二つのオブジェクトの大小関係を判定し、
1967 最初のオブジェクトの方が小さければ-1を、
1968 二つが等しければ0を、
1969 最初のオブジェクトの方が大きければ1を返します。
1970 @item ハッシュ関数
1971 オブジェクトのハッシュ値を返します。
1972 @end table
1973 @c COMMON
1974
1975 @c EN
1976 @code{Scheme.comparator}'s
1977 comparators use the ordering predicate,
1978 while SRFI-114 comparators use the comparison procedure.
1979 Gauche's @code{<comparator>} supports both by automatically
1980 generating the missing one; that is, if you create a comparator
1981 with @code{scheme.comparator} interface, by giving an ordering predicate,
1982 Gauche automatically fills the comparison procedure, and
1983 if you create one with SRFI-114 interface by giving a comparison
1984 procedure, Gauche generates the ordering predicate.
1985 @c JP
1986 @code{scheme.comparator}の比較器は順序手続きを使い、
1987 SRFI-114の比較器は比較手続きを使います。
1988 Gaucheの@code{<comparator>}は両方をサポートするために、
1989 自動的に欠けている手続きを補います。
1990 つまり、順序手続きを与えて@code{scheme.comparator}のインタフェースで
1991 比較器を作った場合、Gaucheは自動的に比較手続きを生成しますし、
1992 比較手続きを与えてSRFI-114のインタフェースで比較器を作った場合は
1993 順序手続きが自動生成されます。
1994 @c COMMON
1995
1996 @c EN
1997 A comparator may not have an ordering predicate / comparison procedure,
1998 and/or a hash function. You can check if the comparator
1999 can be used for ordering or hashing by
2000 @code{comparator-ordered?} and
2001 @code{comparator-hashable?}, respectively.
2002 @c JP
2003 比較器は、順序/比較手続き、ハッシュ関数、あるいはその両方を欠いていることもあります。
2004 比較器が順序づけやハッシュに使えるかどうかは、それぞれ
2005 @code{comparator-ordered?}と
2006 @code{comparator-hashable?}で調べることができます。
2007 @c COMMON
2008
2009 @c EN
2010 Some built-in data types such as hashtables (@pxref{Hashtables})
2011 and treemaps (@pxref{Treemaps}), take a comparator in their constructors.
2012 The sort and merge procedures also accept comparators
2013 (@pxref{Sorting and merging}).
2014 @c JP
2015 Gauche組み込みのデータ型は、コンストラクタで比較器を取ることができます
2016 (例:ハッシュテーブル(@ref{Hashtables}参照)、
2017 ツリーマップ(@ref{Treemaps}参照))。
2018 また、ソートとマージの手続きも比較器を受け取ることができます
2019 (@ref{Sorting and merging}参照。
2020 @c COMMON
2021 @end deftp
2022
2023 @defun make-comparator type-test equal order hash :optional name
2024 [R7RS comparator]
2025 @c EN
2026 Creates a new comparator form the given @var{type-test},
2027 @var{equal}, @var{order} and @var{hash} functions, and returns it.
2028 In R7RS, this is defined in @code{scheme.comparator}
2029
2030 See the description of @code{<comparator>} above for the role of
2031 those procedures.
2032 @c JP
2033 与えられた@var{type-test}、@var{equal}、@var{order}、@var{hash}の
2034 各関数をまとめて、新たな比較器を作って返します。
2035 R7RSではこの関数は@code{scheme.comparator}で定義されています。
2036
2037 各関数の役割については上の@code{<comparator>}の説明を参照してください。
2038 @c COMMON
2039
2040 @c EN
2041 Note: Both @code{scheme.comparator}
2042 and @code{srfi.114} defines @code{make-comparator},
2043 but where @code{scheme.comparator} takes @var{order} argument,
2044 @code{srfi.114} takes @var{compare} argument.
2045 Since @code{scheme.comparator} is preferable, we adopt
2046 it for the built-in interface, and give a different name
2047 (@code{make-comparator/compare}) for SRFI-114 constructor.
2048 @c JP
2049 註: @code{scheme.comparator}と@code{srfi.114}は両方とも
2050 @code{make-comparator}を定義していますが、
2051 @code{scheme.comparator}が@var{order}手続きを取るところで
2052 @code{srfi.114}は@var{compare}手続きを取ります。
2053 @code{scheme.comparator}の方が推奨されるので、
2054 Gaucheでは組み込みの@code{make-comparator}を@code{scheme.comparator}に合わせ、
2055 SRFI-114の方は@code{make-comparator/compare}という名前にしてあります。
2056 @c COMMON
2057
2058 @c EN
2059 Actually, some arguments can be non-procedures, to use predefined
2060 procedures, for the convenience. Even if non-procedure arguments
2061 are passed, the corresponding accessors (e.g.
2062 @code{comparator-type-test-procedure} for the @code{type-test}
2063 procedure) always return a procedure---either the given one
2064 or the predefined one.
2065 @c JP
2066 各引数は、手続きでなく真偽値を取ることもできます。その場合、既に定義された
2067 手続きが使えるので便利です。但し、引数に真偽値を渡した場合でも、
2068 アクセサは補われた手続きの方を返します。
2069 (例えば@code{type-test}引数に対応するアクセサは
2070 @code{comparator-type-test-procedure}ですが、これは常に手続きを返します。)
2071 @c COMMON
2072
2073 @c EN
2074 The @var{type-test} argument must be either @code{#t} or
2075 a predicate taking one argument to test suitability of
2076 the object for comparing by the resulting comparator.
2077 If it is @code{#t},
2078 a procedure that always return @code{#t} is used.
2079 @c JP
2080 @code{type-test}引数は、@code{#t}もしくは1引数の手続きでなければなりません。
2081 手続きの場合、それは渡されたオブジェクトが比較器の他の手続きに渡せるかどうかを
2082 判定する述語です。@code{#t}の場合、どんなオブジェクトに対しても@code{#t}を
2083 返す手続きが補われます。
2084 @c COMMON
2085
2086 @c EN
2087 The @var{equal} argument must
2088 a predicate taking two arguments to test equality.
2089 @c JP
2090 @var{equal}引数は二つの引数を取りその等価性を判定する
2091 述語でなければなりません。
2092 @c COMMON
2093
2094 @c EN
2095 the @var{order} argument must be either @code{#f} or
2096 a procedure taking two arguments and returning a boolean value.
2097 It must return @code{#t} iff the first argument strictly precedes
2098 the second one. If @code{#f} is passed, the comparator can not be
2099 used for ordering.
2100 @c JP
2101 @var{order}手続きは@code{#f}もしくは二つの引数を取り真偽値を返す手続きで
2102 なければなりません。手続きの場合、最初の引数が二番目の引数より厳密に手前に
2103 ある場合にのみ@code{#t}を返します。@code{#f}が渡された場合は、
2104 作られる比較器は順序づけには使えません。
2105 @c COMMON
2106
2107 @c EN
2108 The @var{hash} argument must be either @code{#f}, or
2109 a procedure taking one argument and returning nonnegative exact
2110 integer. If @code{#f} is given, it indicates the comparator
2111 can't hash objects; the predefined procedure just throws an error.
2112 @c JP
2113 @var{hash}引数は@code{#f}か、一つの引数を取り非負の正確な整数をハッシュ値と
2114 して返す手続きでなければなりません。
2115 @code{#f}が渡された場合は、この比較器ではハッシュ値を取れないことを意味します。
2116 この場合、呼ばれたらエラーを投げる手続きが補われます。
2117 @c COMMON
2118
2119 @c EN
2120 The fifth, optional argument @var{name}, is Gauche's extension.
2121 It can be any object but usually a symbol; it is only used when
2122 printing the comparator, to help debugging.
2123 @c JP
2124 最後の、省略可能な引数@var{name}はGaucheの拡張です。
2125 どんなオブジェクトでも構いませんが、通常はシンボルが渡されます。
2126 これは比較器を出力する時に使われるだけですが、デバッグには役に立ちます。
2127 @c COMMON
2128 @end defun
2129
2130 @defun make-comparator/compare type-test equal compare hash :optional name
2131 @c EN
2132 This is SRFI-114 comparator constructor. In SRFI-114, this is called
2133 @code{make-comparator}. Avoiding name conflict, we renamed it.
2134 If you @code{(use srfi.114)} you get the original name @code{make-comparator}
2135 (and the built-in @code{make-comparator} is shadowed).
2136 This is provided for the backward
2137 compatibility, and new code should use built-in @code{make-comparator} above.
2138 @c JP
2139 これはSRFI-114比較器のコンストラクタです。SRFI-114ではこれが
2140 @code{make-comparator}と呼ばれていますが、名前の衝突を避けるために別の名前を用意しました。
2141 @code{(use srfi.114)}した場合は、SRFI-114のコンストラクタが元の名前
2142 で使えるようになります(組み込みの@code{make-comparator}がシャドウされます。)
2143 これは後方互換性のために提供されています。
2144 新たなコードは上に示した組み込みの@code{make-comparator}を使ってください。
2145 @c COMMON
2146
2147 @c EN
2148 It's mostly the same as @code{make-comparator} above, except
2149 the following:
2150 @c JP
2151 以下の点を除き、上の@code{make-comparator}とほぼ同じです。
2152 @c COMMON
2153
2154 @itemize
2155 @item
2156 @c EN
2157 The third argument (@var{compare}) is a comparison procedure
2158 instead of an ordering predicate.
2159 It must be either @code{#f}, or a procedure taking two arguments
2160 and returning either -1, 0, or 1, depending on whether the
2161 first argument is less than, equal to,
2162 or greater than the second argument.
2163 If it is @code{#f}, it indicates the comparator can't order objects.
2164 @c JP
2165 第3引数(@var{compare})には順序手続きのかわりに比較手続きを渡します。
2166 この引数は@code{#f}か、二つの引数を取りそれらの大小関係を
2167 判定する手続きでなければなりません。手続きの場合、引数の最初の方が小さいか、
2168 両者が等しいか、最初の方が大きいか、に応じて-1, 0, 1をそれぞれ返さなければ
2169 なりません。@code{#f}の場合、対象とするオブジェクトの集合に全順序関係がつけられない
2170 ことを表します。
2171 @c COMMON
2172 @item
2173 @c EN
2174 You can pass @code{#t} to the @var{equal} argument when you give
2175 a comparison procedure. In that case, equality is determined
2176 by calling the comparison procedure and see if the result is 0.
2177 @c JP
2178 比較手続きを与えた場合、@var{equal}手続きに@code{#t}を渡すことができます。
2179 その場合、等価性の判定は比較手続きが0を返すかどうかで行われます。
2180 @c COMMON
2181 @end itemize
2182 @end defun
2183
2184 @node Comparator predicates and accessors, Predefined comparators, Comparator class and constructors, Basic comparators
2185 @subsubsection Comparator predicates and accessors
2186 @c NODE 比較器にまつわる述語とアクセサ
2187
2188
2189 @defun comparator? obj
2190 [R7RS comparator]
2191 @c EN
2192 Returns true iff @var{obj} is a comparator.
2193 In R7RS, this is provided from @code{scheme.comparator}.
2194 @c JP
2195 @var{obj}が比較器である場合に@code{#t}を、そうでなければ@code{#f}を返します。
2196 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2197 @c COMMON
2198 @end defun
2199
2200 @deffn {Method} object-equal? (a <comparator>) (b <comparator>)
2201 @c EN
2202 Comparing two comparators by @code{equal?} compares their contents,
2203 via this method. Even @var{a} and @var{b} are comparators created
2204 separately, they can be @code{equal?} if all of their slots are
2205 the same.
2206
2207 This is Gauche's extension. The standard says nothing about
2208 equality of comparators, but it is sometimes useful if you can compare
2209 two.
2210 @c JP
2211 二つの比較器が等価かどうかを@code{equal?}で調べた場合、
2212 比較はこのメソッドを介して、各スロットが等価かどうかで判定されます。
2213 比較器@var{a}と@var{b}が別々に作られたものであっても、各スロットの内容が
2214 等価であれば@code{equal?}とみなされます。
2215
2216 これはGaucheの拡張です。標準は比較器同士の等価性については何も定義していません。
2217 けれども、時には等価判定が便利なことがあります。
2218 @c COMMON
2219
2220 @example
2221 (equal? (make-comparator #t equal? #f hash 'foo)
2222 (make-comparator #t equal? #f hash 'foo))
2223 @result{} #t
2224
2225 @c EN
2226 ;; The following may be #t or #f, depending on how the anonymous
2227 ;; procedure is allocated.
2228 @c JP
2229 ;; 次の式は、無名手続きがどのようにアロケートされるかによって、#tにも#fにも
2230 ;; なり得る。
2231 @c COMMON
2232 (equal? (make-comparator (^x x) eq? #f #f)
2233 (make-comparator (^x x) eq? #f #f))
2234 @end example
2235 @end deffn
2236
2237 @defun comparator-flavor cmpr
2238 @c EN
2239 Returns a symbol @code{ordering} if @var{cmpr} is created with
2240 @code{scheme.comparator} constructor, and
2241 returns @code{comparison} if @var{cmpr}
2242 is created with SRFI-114 constructor.
2243
2244 Usually applications don't need to distinguish these two kinds of
2245 comparators, for either kind of comparators can behave just as another
2246 kind. This procedure is for some particular cases when one
2247 wants to optimize for the underlying comparator implementation.
2248 @c JP
2249 @var{cmpr}が@code{scheme.comparator}コンストラクタで作られた場合は
2250 シンボル@code{ordering}を、
2251 SRFI-114コンストラクタで作られた場合はシンボル@code{comparison}を返します。
2252
2253 アプリケーションは通常両者を区別する必要はありません。一方の比較器は
2254 もう一方の比較器としても使うことができるからです。
2255 比較器の実装に特化した最適化をしたい場合にのみ、区別が必要です。
2256 @c COMMON
2257 @end defun
2258
2259 @defun comparator-ordered? cmpr
2260 @defunx comparator-hashable? cmpr
2261 [R7RS comparator]
2262 @c EN
2263 Returns true iff a comparator @var{cmpr} can be used to order
2264 objects, or to hash them, respectively.
2265 In R7RS, this is provided from @code{scheme.comparator}.
2266 @c JP
2267 比較器@var{cmpr}が、オブジェクトの順序づけあるいはハッシュに使える
2268 場合にそれぞれ@code{#t}を返します。
2269 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2270 @c COMMON
2271 @end defun
2272
2273 @defun comparator-type-test-procedure cmpr
2274 @defunx comparator-equality-predicate cmpr
2275 @defunx comparator-ordering-predicate cmpr
2276 @defunx comparator-hash-function cmpr
2277 [R7RS comparator]
2278 @c EN
2279 Returns type test procedure, equality predicate, ordering procedure
2280 and hash function of comparator @var{cmpr}, respectively.
2281 In R7RS, this is provided from @code{scheme.comparator}.
2282
2283 These accessors always return procedures; if you give @code{#f}
2284 to the @var{order} or @var{hash} argument of the constructor,
2285 @code{comparator-ordering-predicate} and
2286 @code{comparator-hash-function} still return a procedure,
2287 which will just raise an error.
2288 @c JP
2289 比較器の型検査述語、等価述語、順序手続きおよびハッシュ関数をそれぞれ返します。
2290 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2291
2292 これらの手続きは常に手続きを返します。@code{make-comparator}で
2293 @var{order}や@var{hash}に@code{#f}を渡した場合でも、エラーを投げるだけの
2294 手続きが返されます。
2295 @c COMMON
2296 @end defun
2297
2298 @defun comparator-comparison-procedure cmpr
2299 [SRFI-114]
2300 @c EN
2301 This is a SRFI-114 procedure, but sometimes handy with
2302 @code{scheme.comparator} comparators.
2303 Returns a procedure that takes two objects
2304 that satisfy the type predicates of @var{cmpr}. The procedure
2305 returns either -1, 0 or 1, depending on whether the first object
2306 is less than, equal to, or greater than the second. The comparator
2307 must be ordered, that is, it must have an ordering predicate
2308 (or a comparison procedure, if it is created by SRFI-114 constructor).
2309 @c JP
2310 これはSRFI-114の手続きですが、
2311 @code{scheme.comparator}比較器でも時々便利なことがあります。
2312 @var{cmpr}の型検査述語を満たす二つのオブジェクトを取り、-1、0、1のいずれかを
2313 返す手続きを返します。二つのオブジェクトのうち最初の方が小さければ-1が、
2314 等しければ0が、大きければ1が返されます。
2315 比較器は大小比較可能でなけばなりません(順序手続きが渡されるか、
2316 あるいはSRFI-114コンストラクタで比較手続きが渡されるか)。
2317 @c COMMON
2318 @end defun
2319
2320 @defun comparator-test-type cmpr obj
2321 @defunx comparator-check-type cmpr obj
2322 [R7RS comparator]
2323 @c EN
2324 Test whether @var{obj} can be handled by a comparator @var{cmpr},
2325 by applying @var{cmpr}'s type test predicate.
2326 The former (@code{comparator-test-type}) returns a boolean
2327 values, while the latter (@code{comparator-check-type})
2328 signals an error when @var{obj} can't be handled.
2329
2330 In R7RS, this is provided from @code{scheme.comparator}.
2331 @c JP
2332 @var{obj}が比較器@var{cmpr}で扱えるオブジェクトかどうかを、
2333 @var{cmpr}の型検査述語を適用して調べます。
2334 @code{comparator-test-type}は結果の真偽値を返します。
2335 @code{comparator-check-type}は@var{obj}が扱えないオブジェクトである場合に
2336 エラーを投げます。
2337
2338 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2339 @c COMMON
2340 @end defun
2341
2342 @defun =? cmpr obj obj2 obj3 @dots{}
2343 @defunx <? cmpr obj obj2 obj3 @dots{}
2344 @defunx <=? cmpr obj obj2 obj3 @dots{}
2345 @defunx >? cmpr obj obj2 obj3 @dots{}
2346 @defunx >=? cmpr obj obj2 obj3 @dots{}
2347 [R7RS comparator]
2348 @c EN
2349 Compare objects using a comparator @var{cmpr}. All of
2350 @var{obj}, @var{obj2}, @var{obj3} @dots{} must satisfy
2351 the type predicate of @var{cmpr}. When more than two objects
2352 are given, the order of comparison is undefined.
2353
2354 In order to use @code{<?}, @code{<=?}, @code{>?} and @code{>=?},
2355 comparator must be ordered.
2356
2357 In R7RS, this is provided from @code{scheme.comparator}.
2358 @c JP
2359 比較器@var{cmpr}を使ってオブジェクトを比較します。
2360 @var{obj}, @var{obj2}, @var{obj3} @dots{}は全て@code{cmpr}の
2361 型検査述語を満たさなければなりません。
2362 3つ以上のオブジェクトが渡された場合、比較の順番は規定されていません。
2363
2364 @code{<?}、@code{<=?}、@code{>?}、@code{>=?}を使うためには
2365 比較器は順序比較可能でなければなりません。
2366
2367 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2368 @c COMMON
2369 @end defun
2370
2371 @defun comparator-hash cmpr obj
2372 [R7RS comparator]
2373 @c EN
2374 Returns a hash value of @var{obj} with the hash function of
2375 a comparator @var{cmpr}. The comparator must be hashable,
2376 and @var{obj} must satisfy comparator's type test predicate.
2377
2378 In R7RS, this is provided from @code{scheme.comparator}.
2379 @c JP
2380 比較器@var{cmpr}のハッシュ関数を使って@var{obj}のハッシュ値を計算して返します。
2381 比較器はハッシュ計算可能でなければなりません。また、@var{obj}は
2382 比較器の型検査述語を満たさなければなりません。
2383
2384 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2385 @c COMMON
2386 @end defun
2387
2388 @defun comparator-compare cmpr a b
2389 [SRFI-114]
2390 @c EN
2391 Order two objects @var{a} and @var{b}
2392 using @var{cmpr}, and returns either one of
2393 -1 (@var{a} is less than @var{b}),
2394 0 (@var{a} equals to @var{b}), or
2395 1 (@var{a} is greater than @var{b}).
2396 Objects must satisfy @var{cmpr}'s type test predicate.
2397
2398 A simple comparison can be done by @code{<?} etc, but sometimes
2399 three-way comparison comes handy. So we adopt this procedure
2400 from SRFI-114.
2401 @c JP
2402 ふたつのオブジェクト@var{a}と@var{b}の順序を調べ、
2403 @var{a}が先 (小さい) なら -1を、
2404 等しければ0を、
2405 @var{a}が後 (大きい) なら 1を返します。
2406 @var{a}と@var{b}はともに@var{cmpr}の型検査述語を満たさねばなりません。
2407
2408 単純な比較なら@code{<?}等の手続きでできますが、
2409 時に3分岐の比較が便利なこともあります。そのため、SRFI-114から
2410 この手続きを採用しました。
2411 @c COMMON
2412 @end defun
2413
2414 @node Predefined comparators, Combining comparators, Comparator predicates and accessors, Basic comparators
2415 @subsubsection Predefined comparators
2416 @c NODE 用意されている比較器
2417
2418 @defvar default-comparator
2419 [SRFI-114]
2420 @c EN
2421 This variable bounds to a comparator that is used by default in
2422 many context.
2423
2424 It can compare most of Scheme objects, even between objects with
2425 different types. In fact, it is defined as follows:
2426 @c JP
2427 この変数は、様々な場所でオブジェクトを比較する際のデフォルトとして使われる
2428 比較器に束縛されています。
2429
2430 デフォルト比較器は次のとおり定義されており、
2431 ほぼすべてのSchemeオブジェクト間の比較が出来ます。
2432 @c COMMON
2433
2434 @example
2435 (define default-comparator
2436 (make-comparator/compare #t equal? compare default-hash
2437 'default-comparator))
2438 @end example
2439
2440 @c EN
2441 As you see in the definition, equality, ordering and hashing are
2442 handled by @code{equal?}, @code{compare} and @code{default-hash},
2443 respectively. They takes care of builtin objects, and
2444 also @code{equal?} and @code{compare} handle the case
2445 when two objects of different types.
2446 @c JP
2447 定義からわかるように、等価述語、比較手続き、そしてハッシュ計算はそれぞれ
2448 @code{equal?}、@code{compare}、@code{default-hash}で処理されます。
2449 組み込みオブジェクト、及び二つの異なる型の間の比較についてはそれらが処理します。
2450 @c COMMON
2451
2452 @c EN
2453 For objects of user-defined classes,
2454 those procedures call generic functions
2455 @code{object-equal?}, @code{object-compare}, and @code{object-hash},
2456 respectively. Defining methods for them automatically extended
2457 the domain of @code{default-comparator}.
2458 @c JP
2459 ユーザ定義クラスのオブジェクトについては、
2460 上記手続きがそれぞれジェネリック関数
2461 @code{object-equal?}、@code{object-compare}、@code{object-hash}を
2462 呼び出します。これらのメソッドを定義することにより、
2463 @code{default-comparator}の定義域も自動的に拡張されます。
2464 @c COMMON
2465
2466 @c EN
2467 @code{Scheme.comparator} defines another way to extend @code{default-comparator}.
2468 See @code{comparator-register-default!} below for the details.
2469 @c JP
2470 @code{scheme.comparator}は、@code{default-comparator}を拡張する別の方法を定義しています。
2471 下の@code{comparator-register-default!}の項を参照してください。
2472 @c COMMON
2473 @end defvar
2474
2475 @defun comparator-register-default! comparator
2476 [R7RS comparator]
2477 @c EN
2478 In R7RS, this is provided from @code{scheme.comparator}.
2479 This is the @code{scheme.comparator} way for user
2480 programs to extend the behavior of
2481 the @code{default-comparator}
2482 (which is what @code{make-default-comparator} returns).
2483
2484 Note that, in Gauche, you can also extend default comparator's behavior
2485 by defining specialized methods for @code{object-equal?},
2486 @code{object-compare} and @code{object-hash}.
2487 See the description of @code{default-comparator} above, for the details.
2488 @c JP
2489 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2490 これは、@code{default-comparator}(@code{make-default-comparator}が
2491 返す比較器)の振る舞いをユーザプログラムが拡張できるようにする、
2492 @code{scheme.comparator}が定める方法です。
2493
2494 Gaucheでは、@code{object-equal?}、@code{object-compare}、@code{object-hash}に
2495 特殊化したメソッドを定義することでも、デフォルト比較器を拡張できることに
2496 留意してください。詳しくは上の@code{default-comparator}の説明を参照のこと。
2497 @c COMMON
2498
2499 @c EN
2500 In fact, Gauche uses those generic functions to
2501 handle the registered comparators; methods specialized for
2502 @code{<top>} are defined for these generic functions, which
2503 catches the case when @code{default-comparator} is applied
2504 on object(s) of user-defined classes that don't have specialized
2505 methods defined for those generic functions.
2506 The catching method examines registered comparators to find
2507 one that can handle passed argument(s), and if it finds one,
2508 use it.
2509 @c JP
2510 実際、Gaucheではこれらのジェネリックファンクションを使って、
2511 登録されたデフォルト比較器を処理しています。これらのジェネリックファンクションには、
2512 あらかじめ@code{<top>}に特殊化されたメソッドが定義されており、
2513 @code{default-comparator}がユーザ定義クラスのオブジェクトに使われ、
2514 かつそのクラスに特殊化されたメソッドが定義されていない場合を捕まえます。
2515 そして、登録された比較器から与えられた引数に適用可能なものを探し、
2516 見つかればそれを使います。
2517 @c COMMON
2518
2519 @c EN
2520 You might frown at this procedure having a global side-effect.
2521 Well, @code{scheme.comparator} explicitly prohibits comparators registered
2522 by this procedure alters the behavior of the default comparator
2523 in the existing domain---it is only allowed to handle objects that
2524 aren't already handled by the system's original default comparator
2525 and other already registered comparators. So, the only effect of
2526 adding new comparator should make the default comparator
2527 work on objects that had been previously raised an error.
2528 @c JP
2529 この手続きがグローバルな副作用を持つことに顔をしかめる人もいるかもしれません。
2530 @code{scheme.comparator}では、
2531 デフォルトの比較器や登録された比較器が既にカバーしている定義域と
2532 重複する定義域を持つ比較器を登録することを禁じています。
2533 言い換えれば、@code{comparator-register-default!}で定義できるのは、
2534 デフォルトの比較器や既に登録された比較器が処理できないオブジェクトを扱う
2535 比較器だけです。従って、新たな比較器を登録することによる副作用は、
2536 それまで@code{default-comparator}が扱えなかったオブジェクトを
2537 扱えるようになるというだけで、既に扱えていたオブジェクトに対する
2538 @code{default-comparator}の動作が変わってしまうということはありません。
2539 @c COMMON
2540
2541 @c EN
2542 In reality, it is impossible to enforce the condition. If you
2543 register a comparator whose domain overlaps overlaps the domain
2544 the default comparator (and its extensions via Gauche's methods),
2545 the program becomes non-portable at that moment. In the current version,
2546 the comparators registered by @code{comparator-register-default!} has
2547 the lowest precedence on the dispatch mechanism, but you shouldn't count
2548 on that.
2549 @c JP
2550 尤も、現実にその条件を強制することは不可能です。
2551 もし、既にデフォルトの比較器の定義域(および、Gaucheのメソッドにより拡張された定義域)
2552 と重なるような定義域を持つ比較器を登録してしまったら、その時点でプログラムの
2553 移植性は損なわれます。現在のバージョンでは、@code{comparator-register-default!}
2554 で登録された比較器は最も低い優先度を持ちますが、その動作をあてにすべきではありません。
2555 @c COMMON
2556 @end defun
2557
2558 @defvar eq-comparator
2559 @defvarx eqv-comparator
2560 @defvarx equal-comparator
2561 [SRFI-114]
2562 @c EN
2563 Built-in comparators that uses @code{eq?}, @code{eqv?} and @code{equal?}
2564 for the equality predicate, respectively. They accept any kind of
2565 Scheme objects. Each has corresponding hash functions
2566 (i.e. @code{eq-hash} for @code{eq-comparator},
2567 @code{eqv-hash} for @code{eqv-comparator} and
2568 @code{default-hash} for @code{equal-comparator}).
2569 Only @code{eq-comparator} is ordered, using @code{eq-compare} to
2570 order the objects
2571 (@pxref{Comparison}, for @code{eq-compare}).
2572 @c JP
2573 それぞれ、等価述語に@code{eq?}、@code{eqv?}、@code{equal?}を使う
2574 組み込みの比較器です。全てのSchemeオブジェクトを受け付けます。
2575 対応するハッシュ関数(@code{eq-comparator}は@code{eq-hash}、
2576 @code{eqv-comparator}は@code{eqv-hash}、@code{equal-comparator}は
2577 @code{hash})を備えています。
2578 @code{eq-comparator}のみ、@code{eq-compare}を使った順序づけが可能です
2579 (@code{eq-compare}については@ref{Comparison}参照)。
2580 @c COMMON
2581
2582 @c EN
2583 Note that @code{eq-comparator} and @code{eqv-comparator} are not
2584 equivalent from what @code{make-eq-comparator} and @code{make-eqv-comparator}
2585 return, respectively. The latter two are defined in @code{scheme.comparator}
2586 and specified to use @code{default-hash} for the hash function. It is
2587 heavier than @code{eq-hash}/@code{eqv-hash}, and it can't be used
2588 for circular objects, nor for the mutable objects with which you want
2589 to hash them by identity. We provide @code{eq-comparator} and
2590 @code{eqv-comparator} in case you want to avoid limitations of
2591 @code{default-hash}.
2592 @c JP
2593 @code{eq-comparator}と@code{eqv-comparator}はそれぞれ、
2594 @code{make-eq-comparator} and @code{make-eqv-comparator}が返す比較器とは
2595 等価でないことに注意してください。後者の手続きは@code{scheme.comparator}
2596 で規定されていますが、
2597 ハッシュ関数には@code{default-hash}を使うように指定されています。
2598 @code{default-hash}は@code{eq-hash}や@code{eqv-hash}より重く、
2599 ループのある構造は扱えず、また変更可能なオブジェクトの同一性のみに基づいてハッシュ値を
2600 計算するのには使えません。
2601 こういった@code{default-hash}の制限を避けたい場合のために
2602 @code{eq-comparator}と@code{eqv-comparator}を用意しました。
2603 @c COMMON
2604 @end defvar
2605
2606 @defvar boolean-comparator
2607 @defvarx char-comparator
2608 @defvarx char-ci-comparator
2609 @defvarx string-comparator
2610 @defvarx string-ci-comparator
2611 [SRFI-114]
2612 @c EN
2613 Compare booleans, characters, and strings, respectively.
2614 The @code{*-ci-*} variants uses case-insensitive comparison.
2615 All have appropriate hash functions, too.
2616
2617 The string case-insensitive comparison uses Unicode full-string case
2618 conversion (@pxref{Full string case conversion}).
2619 @c JP
2620 それぞれ、真偽値、文字、文字列を比較する比較器です。
2621 @code{*-ci-*}がついている手続きは大文字小文字の区別をしません。
2622 全て、適切なハッシュ関数も備えています。
2623
2624 文字列の大文字小文字の区別をしない比較は、Unicodeのfull-string case conversion
2625 に従います (@ref{Full string case conversion}参照)。
2626 @c COMMON
2627 @end defvar
2628
2629 @defvar exact-integer-comparator
2630 @defvarx integer-comparator
2631 @defvarx rational-comparator
2632 @defvarx real-comparator
2633 @defvarx complex-comparator
2634 @defvarx number-comparator
2635 [SRFI-114]
2636 @c EN
2637 Compare exact integers, integers, rational numbers, real numbers,
2638 complex numbers and general numbers, respectively.
2639 In Gauche @code{number-comparator} is the same as @code{complex-comparator}.
2640
2641 The equality are determined by @code{=}.
2642 For exact integer, integer, rational and real comparators,
2643 the order is the numerical order. Two complex numbers are
2644 compared first by their real components, and then their imaginary
2645 components only if the real components are the same.
2646
2647 Note that those comparator rejects NaN.
2648 You need @code{make-inexact-real-comparator} in @code{srfi.114} module
2649 to compare NaNs with your own discretion.
2650 @xref{Comparators}, for the details.
2651 @c JP
2652 それぞれ、正確な整数、整数、有理数、実数、複素数、そして全ての数値を比較する比較器です。
2653 Gaucheでは@code{number-comparator}は@code{complex-comparator}と同じです。
2654
2655 等価性は@code{=}により判定されます。
2656 正確な整数、整数、有理数および実数の比較器では、比較手続きは数値の大小に基づいて
2657 判定されます。複素数の比較においては、まず実部の大小が比べられ、実部が等しい場合に
2658 虚部の大小が比べられます。
2659
2660 これらの比較器はNaNを扱いません。
2661 NaNを扱いたい場合は、@code{srfi.114}モジュールの@code{make-inexact-real-comparator}
2662 手続きを使って、NaNの比較方法を指定する必要があります。
2663 詳しくは@ref{Comparators}を参照してください。
2664 @c COMMON
2665 @end defvar
2666
2667 @defvar pair-comparator
2668 @defvarx list-comparator
2669 @defvarx vector-comparator
2670 @defvarx uvector-comparator
2671 @defvarx bytevector-comparator
2672 [SRFI-114]
2673 @c EN
2674 The default comparators to compare pairs, lists, vectors, uniform
2675 vectors and bytevectors (which is synonym to @code{u8vector}).
2676 Their respective elements are compared with the default comparators.
2677
2678 Note that lists are compared by dictionary order (@code{(1 2 3)} comes
2679 before @code{(1 3)}), while in vector-families
2680 shorter ones are ordered first (
2681 @code{#(1 3)} comes before @code{#(1 2 3)}).
2682 @c JP
2683 ペア、リスト、ベクタ、ユニフォームベクタ、バイトベクタ(@code{u8vector}の別名)を
2684 それぞれ比較するための比較器です。
2685 各データ型の要素についてはデフォルトの比較器(@code{default-comparator)}が
2686 使われます。
2687
2688 リストは辞書順で比較されますが(例:@code{(1 2 3)}は@code{(1 3)}より前)、
2689 ベクタの仲間はまず長さが短いものが先に来て、それから内容で比較されることに注意してください
2690 (@code{#(1 3)}は@code{#(1 2 3)}より前)。
2691 @c COMMON
2692 @end defvar
2693
2694 @defvar time-comparator
2695 @c EN
2696 A comparator to compare @code{<time>} objects (@pxref{Time}).
2697 @c JP
2698 @code{<time>}オブジェクトを比較する比較器です。@ref{Time}参照。
2699 @c COMMON
2700 @end defvar
2701
2702
2703 @node Combining comparators, , Predefined comparators, Basic comparators
2704 @subsubsection Combining comparators
2705 @c NODE 比較器を組み合わせる
2706
2707 @defun make-default-comparator
2708 [R7RS comparator]
2709 @c EN
2710 Returns a default comparator. In Gauche, this returns the
2711 @code{default-comparator} object.
2712 In R7RS, this is provided from @code{scheme.comparator}.
2713 @c JP
2714 デフォルト比較器を返します。Gaucheでは常に唯一の@code{default-comparator}が
2715 返されます。
2716 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2717 @c COMMON
2718 @end defun
2719
2720 @defun make-eq-comparator
2721 @defunx make-eqv-comparator
2722 [R7RS comparator]
2723 @c EN
2724 Returns comparators that use @code{eq?} and @code{eqv?} for its
2725 equality predicate, respectively. Note that they use @code{default-hash}
2726 for hash functions, as specified by @code{scheme.comparator},
2727 which has a few drawbacks:
2728 You can't use it if you want to hash based on identity of mutable objects,
2729 it diverges on circular objects, and it is slow if applied on a large
2730 structures. We recommend to use @code{eq-comparator} or
2731 @code{eqv-comparator} if possible (@pxref{Predefined comparators}).
2732
2733 In R7RS, this is provided from @code{scheme.comparator}.
2734 @c JP
2735 @code{eq?}および@code{eqv?}を等価述語に使う比較器をそれぞれ返します。
2736 これらの関数が返す比較器のハッシュには、@code{default-hash}を使うことが
2737 @code{scheme.comparator}で規定されていますが、それにはいくつか欠点があります。
2738 変更可能なオブジェクトの同一性に基づいたハッシュ関数が欲しい場合は使えませんし、
2739 循環するオブジェクトでは発散します。大きな構造をハッシュしようとすると遅くなります。
2740 可能ならば、@code{eq-comparator}や@code{eqv-comparator}を
2741 使うことを推奨します(@ref{Predefined comparators})参照。)
2742
2743 R7RSではこの手続きは@code{scheme.comparator}ライブラリで提供されます。
2744 @c COMMON
2745 @end defun
2746
2747 @defun make-reverse-comparator cmpr
2748 [SRFI-114]
2749 @c EN
2750 Returns a comparator with the same type test predicate,
2751 equality procedure, and hash function as the given comparator,
2752 but the comparison procedure is flipped.
2753 @c JP
2754 与えられた比較器@var{cmpr}と同じ型検査述語、等価述語、ハッシュ関数を持ち、
2755 大小比較だけが逆になっているような比較器を返します。
2756 @c COMMON
2757 @end defun
2758
2759 @defun make-key-comparator cmpr test key
2760 @c EN
2761 Suppose you have some kind of structure, but you only need to look
2762 at one part of it to compare them.
2763
2764 Returns a new comparator that uses @var{test} as type test predicate.
2765 Its equality predicate, comparison procedure and hash function are
2766 constructed by applying @var{key} to the argument(s) then passing
2767 the result to the corresponding procedure of @var{cmpr}. If @var{cmpr}
2768 lacks comparison procedure and/or hash function, so does the returned
2769 comparator.
2770 @c JP
2771 何らかの構造体があって、その比較に際してはその中の一つの要素を見るだけで良い、
2772 という場合に使える手続きです。
2773
2774 比較器を作って返します。型検査述語には@var{test}が使われます。
2775 等価述語、比較手続き、ハッシュ関数については、それらの引数に@var{key}を適用して
2776 得られた値を、比較器@var{cmpr}の対応する手続きに渡すような手続きとなります。
2777 @var{cmpr}が比較手続きやハッシュ関数を欠いている場合は、
2778 返される比較器も同様に比較手続きやハッシュ関数を欠いたものとなります。
2779 @c COMMON
2780
2781 @c EN
2782 In the following example, the tree-map @code{users} compares
2783 the given user records only by the @code{username} slots:
2784 @c JP
2785 次の例では、ツリーマップ@code{users}は
2786 userレコードの@code{username}スロットだけを見て比較を行います。
2787 @c COMMON
2788
2789 @example
2790 (use gauche.record)
2791
2792 (define-record-type user #t #t
2793 username ; string
2794 password-hash ; string
2795 comment) ; string
2796
2797 (define users ; table of users, managed by tree-map
2798 (make-tree-map
2799 (make-key-comparator string-comparator user? user-username)))
2800 @end example
2801
2802 @c EN
2803 @xref{Composing comparators}, for additional procedures
2804 to create comparator of aggregate types.
2805 @c JP
2806 集合型の比較器を作る手続きについては、@ref{Composing comparators}も参照してください。
2807 @c COMMON
2808 @end defun
2809
2810 @defun make-tuple-comparator cmpr1 cmpr2 @dots{}
2811 @c EN
2812 Creates a comparator that compares lists of the form @code{(x1 x2 @dots{})},
2813 where each element is compared with the corresponding comparator.
2814 For example, @code{(make-tuple-comparator c1 c2 c3)} will compare
2815 three-element list, whose first elements are compared by @var{c1},
2816 second elements by @var{c2} and third elements by @var{c3}.
2817 @c JP
2818 リスト@code{(x1 x2 @dots{})}の各要素をそれぞれ@var{cmpr1} @code{cmpr2} @dots{}
2819 で比較するような比較器を返します。
2820 例えば@code{(make-tuple-comparator c1 c2 c3)}が返すのは、
2821 3要素のリストを受け入れ、最初の要素が@var{c1}で、二番目の要素が@var{c2}で、
2822 最後の要素が@var{c3}で比較されるような比較器です。
2823 @c COMMON
2824
2825 @c EN
2826 @xref{Composing comparators}, for additional procedures
2827 to create comparator of aggregate types.
2828 @c JP
2829 集合型の比較器を作る手続きについては、@ref{Composing comparators}も参照してください。
2830 @c COMMON
2831 @end defun
2832
2833 @c ----------------------------------------------------------------------
2834 @node Numbers, Booleans, Equality and comparison, Core library
2835 @section Numbers
2836 @c NODE 数値
2837
2838 @c EN
2839 Gauche supports the following types of numbers
2840 @table @asis
2841 @item multi-precision exact integer
2842 There's no limit of the size of number except the memory of the machine.
2843 @item multi-precision exact non-integral rational numbers.
2844 Both denominator and numerator are represented by exact integers.
2845 There's no limit of the size of number except the memory of the machine.
2846 @item inexact floating-point real numbers
2847 Using @code{double}-type of underlying C compiler, usually IEEE 64-bit
2848 floating point number.
2849 @item inexact floating-point complex numbers
2850 Real part and imaginary part are represented by inexact floating-point
2851 real numbers.
2852 @end table
2853 @c JP
2854 Gaucheは次のタイプの数値をサポートしています。
2855 @table @asis
2856 @item 多倍長の正確な整数
2857 メモリの許す限りの精度が扱えます。
2858 @item 多倍長の正確な非整数の有理数
2859 分母と分子は正確な整数で表現されます。
2860 メモリの許す限りの精度が扱えます。
2861 @item 浮動小数点の非正確な実数
2862 実装に使われるC言語の@code{double}型で表現されます。通常IEEE 64bit浮動小数点数です。
2863 @item 浮動小数点の非正確な複素数
2864 実部と虚部はそれぞれ浮動小数点の非正確な実数で表現されます。
2865 @end table
2866 @c COMMON
2867
2868 @menu
2869 * Number classes::
2870 * Numerical predicates::
2871 * Numerical comparison::
2872 * Arithmetics::
2873 * Numerical conversions::
2874 * Basic bitwise operations::
2875 * Endianness::
2876 @end menu
2877
2878 @node Number classes, Numerical predicates, Numbers, Numbers
2879 @subsection Number classes
2880 @c NODE 数値クラス
2881
2882 @deftp {Builtin Class} <number>
2883 @deftpx {Builtin Class} <complex>
2884 @deftpx {Builtin Class} <real>
2885 @deftpx {Builtin Class} <rational>
2886 @deftpx {Builtin Class} <integer>
2887 @clindex number
2888 @clindex complex
2889 @clindex real
2890 @clindex rational
2891 @clindex integer
2892 @c EN
2893 These classes consist a class hierarchy of number objects.
2894 @code{<complex>} inherits @code{<number>}, @code{<real>} inherits
2895 @code{<complex>},@code{<rational>} inherits @code{<real>}
2896 and @code{<integer>} inherits @code{<rational>}.
2897
2898 Note that these classes do not exactly correspond to the
2899 number hierarchy defined in R7RS. Especially,
2900 only exact integers are the instances of the @code{<integer>}
2901 class. That is,
2902 @c JP
2903 数値オブジェクトのクラス階層を構成します。@code{<complex>}は
2904 @code{<number>}を継承し、@code{<real>}は@code{<complex>}を継承し、
2905 @code{<rational>}は@code{<real>}を継承し、
2906 @code{<integer>}は@code{<rational>}を継承します。
2907
2908 これらのクラスはR7RSで定義されている数値の階層とは必ずしも対応しません。
2909 特に、@code{<integer>}クラスのインスタンスはR7RSでいうexact integerのみになります。
2910 @c COMMON
2911 @lisp
2912 (integer? 1) @result{} #t
2913 (is-a? 1 <integer>) @result{} #t
2914 (is-a? 1 <real>) @result{} #t
2915
2916 (integer? 1.0) @result{} #t
2917 (is-a? 1.0 <integer>) @result{} #f
2918 (is-a? 1.0 <real>) @result{} #t
2919
2920 (class-of (expt 2 100)) @result{} #<class <integer>>
2921 (class-of (sqrt -3)) @result{} #<class <complex>>
2922 @end lisp
2923 @end deftp
2924
2925 @node Numerical predicates, Numerical comparison, Number classes, Numbers
2926 @subsection Numerical predicates
2927 @c NODE 数値に関する述語
2928
2929 @defun number? obj
2930 @defunx complex? obj
2931 @defunx real? obj
2932 @defunx rational? obj
2933 @defunx integer? obj
2934 [R7RS base]
2935 @c EN
2936 Returns @code{#t} if @var{obj} is a number, a complex number, a real number,
2937 a rational number or an integer, respectively. In Gauche, a set of
2938 numbers is the same as a set of complex numbers.
2939 A set of rational numbers is the same as a set of real numbers,
2940 except @code{+inf.0}, @code{-inf.0} and @code{+nan.0}
2941 (since we have only limited-precision floating numbers).
2942 @c JP
2943 @var{obj}がそれぞれ数、複素数、実数、有理数、整数ならば@code{#t}を返します。
2944 Gaucheでは、数の集合は複素数の集合と同一であり、有理数の集合は
2945 @code{+inf.0}, @code{-inf.0}, @code{+nan.0}を除いた実数の集合と同一
2946 (浮動小数点数が有限精度であるため)です。
2947 @c COMMON
2948
2949 @example
2950 (complex? 3+4i) @result{} #t
2951 (complex? 3) @result{} #t
2952 (real? 3) @result{} #t
2953 (real? -2.5+0.0i) @result{} #t
2954 (real? #e1e10) @result{} #t
2955 (integer? 3+0i) @result{} #t
2956 (integer? 3.0) @result{} #t
2957
2958 (real? +inf.0) @result{} #t
2959 (real? +nan.0) @result{} #t
2960 (rational? +inf.0) @result{} #f
2961 (rational? +nan.0) @result{} #f
2962 @end example
2963
2964 @c EN
2965 Note: R6RS adopts more strict definition on exactness,
2966 and notably, it defines a complex number with non-exact zero imaginary
2967 part is not a real number. Currently Gauche doesn't have
2968 exact complex numbers, and automatically coerces complex
2969 numbers with zero imaginary part to a real number.
2970 Thus R6RS code that relies on the fact that @code{(real? 1+0.0i)} is
2971 @code{#f} won't work with Gauche.
2972 @c JP
2973 R6RSでは正確性についてより厳密な定義がなされ、特に
2974 非正確なゼロを虚数部に持つ複素数は実数ではないと規定されています。
2975 Gaucheは今のところ正確な複素数を持たず、虚部がゼロの複素数は
2976 自動的に実数に変換されます。従ってR6RSのコードのうち、
2977 @code{(real? 1+0.0i)}が@code{#f}であることを当てにしているものは
2978 うまく動かないでしょう。
2979 @c COMMON
2980 @end defun
2981
2982 @defun real-valued? obj
2983 @defunx rational-valued? obj
2984 @defunx integer-valued? obj
2985 [R6RS]
2986 @c EN
2987 In Gauche these are just an alias of @code{real?}, @code{rational?}
2988 and @code{integer?}. They are provided for R6RS compatibility.
2989
2990 The difference of those and non @code{-valued} versions in R6RS is
2991 that these returns @code{#t} if @var{obj} is a complex number
2992 with nonexact zero imaginary part. Since Gauche doesn't distinguish
2993 complex numbers with zero imaginary part and real numbers, we don't
2994 have the difference.
2995 @c JP
2996 Gaucheではこれらの手続きはそれぞれ@code{real?}、@code{rational?}、
2997 および@code{integer?}の別名となっています。これらはR6RSコードとの互換性のために
2998 提供されています。
2999
3000 R6RSで規定されている、これらの手続きと@code{-valued}がついていない手続きの違いは、
3001 これらの手続きは非正確なゼロの虚部を持つ複素数に対しても@code{#t}を返すという
3002 ことです。Gaucheではゼロの虚部を持つ複素数は実数とみなしているので、
3003 この違いは現れません。
3004 @c COMMON
3005 @end defun
3006
3007 @defun exact? obj
3008 @defunx inexact? obj
3009 [R7RS base]
3010 @c EN
3011 Returns @code{#t} if @var{obj} is an exact number and an inexact number,
3012 respectively.
3013 @c JP
3014 @var{obj}がそれぞれ正確な数、非正確な数ならば@code{#t}を返します。
3015 @c COMMON
3016
3017 @example
3018 (exact? 1) @result{} #t
3019 (exact? 1.0) @result{} #f
3020 (inexact? 1) @result{} #f
3021 (inexact? 1.0) @result{} #t
3022
3023 (exact? (modulo 5 3)) @result{} #t
3024 (inexact? (modulo 5 3.0)) @result{} #f
3025 @end example
3026 @end defun
3027
3028 @defun exact-integer? obj
3029 [R7RS base]
3030 @c EN
3031 Same as @code{(and (exact? obj) (integer? obj))}, but more efficient.
3032 @c JP
3033 @code{(and (exact? obj) (integer? obj))}と等価ですが、より高速です。
3034 @c COMMON
3035 @end defun
3036
3037 @defun zero? z
3038 [R7RS base]
3039 @c EN
3040 Returns @code{#t} if a number @var{z} equals to zero.
3041 @c JP
3042 数値@var{z}がゼロに等しければ@code{#t}を返します。
3043 @c COMMON
3044
3045 @example
3046 (zero? 1) @result{} #f
3047 (zero? 0) @result{} #t
3048 (zero? 0.0) @result{} #t
3049 (zero? -0.0) @result{} #t
3050 (zero? 0.0+0.0i) @result{} #t
3051 @end example
3052 @end defun
3053
3054 @defun positive? x
3055 @defunx negative? x
3056 [R7RS base]
3057 @c EN
3058 Returns @code{#t} if a real number @var{x} is positive and negative,
3059 respectively. It is an error to pass a non-real number.
3060 @c JP
3061 実数@var{x}がそれぞれ正または負なら@code{#t}を返します。
3062 非実数を渡すとエラーになります。
3063 @c COMMON
3064
3065 @c EN
3066 Note that minus zero (@code{-0.0}) is zero, not negative.
3067 @c JP
3068 マイナスゼロ(@code{-0.0})はゼロであって負ではないことに注意してください。
3069 @c COMMON
3070 @end defun
3071
3072 @defun negative-zero? x
3073 @c EN
3074 Returns @code{#t} if a number @var{x} is a minus zero (@code{-0.0}),
3075 @code{#f} otherwise.
3076 An error is signaled if @var{x} is not a number.
3077 @c JP
3078 数値@var{x}がマイナスゼロ(@code{-0.0})の場合に@code{#t}を、
3079 そうでなければ@code{#f}を返します。@var{x}が数値でなければエラーが投げられます。
3080 @c COMMON
3081 @end defun
3082
3083 @defun finite? z
3084 @defunx infinite? z
3085 @defunx nan? z
3086 [R7RS inexact]
3087 @c EN
3088 For real numbers, returns @code{#f} iff the given number
3089 is finite, infinite, or NaN, respectively.
3090
3091 For non-real complex numbers, @code{finite?} returns @code{#t} iff
3092 both real and imaginary components are finite, @code{infinite?}
3093 returns @code{#t} if at least either real or imaginary component
3094 is infinite, and @code{nan?} returns @code{#t} if at least either
3095 real or imaginary component is NaN. (Note: It is incompatible
3096 to R6RS, in which these procedures must raise an error if
3097 the given argument is non-real number.)
3098
3099 In R7RS, these procedures are in @code{(scheme inexact)} library.
3100 @c JP
3101 実数に対して、それが有限、無限、NaNであればそれぞれ@code{#t}を返します。
3102
3103 非実数の複素数に対しては、@code{finite?}は実数部と仮数部がともに
3104 有限なら@code{#t}を、@code{infinite?}は実数部と仮数部の少なくともどちらかが
3105 無限なら@code{#t}を、@code{nan?}は実数部と仮数部の少なくともどちらかが
3106 NaNなら@code{#t}を返します。(これはR6RSとは非互換です。R6RSでは
3107 これらの手続きは引数に非実数の数が与えられた場合はエラーを通知しなければならないからです。)
3108
3109 R7RSではこれらの手続きは@code{(scheme inexact)}ライブラリにあります。
3110 @c COMMON
3111 @end defun
3112
3113 @defun odd? n
3114 @defunx even? n
3115 [R7RS base]
3116 @c EN
3117 Returns @code{#t} if an integer @var{n} is odd and even,
3118 respectively. It is an error to pass a non-integral number.
3119 @c JP
3120 整数@var{n}がそれぞれ奇数または偶数なら@code{#t}を返します。
3121 非整数を渡すとエラーになります。
3122 @c COMMON
3123
3124 @example
3125 (odd? 3) @result{} #t
3126 (even? 3) @result{} #f
3127 (odd? 3.0) @result{} #t
3128 @end example
3129 @end defun
3130
3131 @defun fixnum? n
3132 @defunx bignum? n
3133 [R7RS fixnum]
3134 @c EN
3135 Returns @code{#t} iff @var{n} is an exact integer whose internal
3136 representation is @emph{fixnum} and @emph{bignum}, respectively.
3137 R7RS-large defines @code{fixnum?} in @code{scheme.fixnum} library;
3138 @code{bignum?} is Gauche's extension.
3139 Portable Scheme programs don't need to care about the internal
3140 representation of integer. These are for certain low-level
3141 routines that does particular optimization.
3142
3143 @xref{R7RS fixnum}, for the comprehensive fixnum library.
3144 @c JP
3145 @var{n}が正確な整数で、かつ内部的にそれぞれ@emph{fixnum}もしくは@emph{bignum}
3146 で表現されているときに@code{#t}を返します。R7RS-largeは
3147 @code{scheme.fixnum}ライブラリで@code{fixnum?}を定義しています。
3148 @code{bignum?}はGauche拡張です。
3149 通常のSchemeプログラムは整数の内部表現を気にする必要はありません。
3150 これらの手続きは、ある種の最適化を行う低レベル手続きのために用意されています。
3151
3152 fixnumを扱う包括的なライブラリは@ref{R7RS fixnum}を参照してください。
3153 @c COMMON
3154 @end defun
3155
3156 @defun flonum? x
3157 [R7RS flonum]
3158 @c EN
3159 Returns @code{#t} if @var{x} is a number represented by a floating-point
3160 number, @code{#f} otherwise. In Gauche, inexact real numbers
3161 are flonums.
3162
3163 @xref{R7RS flonum}, for comprehensive flonum library.
3164 @c JP
3165 @var{x}が浮動小数点数で表現される数値の場合に@code{#t}を、それ以外の場合に
3166 @code{#f}を返します。Gaucheでは、非正確な実数がflonumです。
3167
3168 flonumを扱う包括的なライブラリは@ref{R7RS flonum}を参照してください。
3169 @c COMMON
3170 @end defun
3171
3172 @defun ratnum? x
3173 @c EN
3174 Returns @code{#t} if @var{x} is a number represented by an exact
3175 non-integral number, or @code{#f} otherwise. Internally, a number
3176 that returns @code{#t} for it is represented as a pair of two
3177 exact integers.
3178
3179 Usually you don't need to distinguish ratnums from exact integers; you
3180 can treat them as exact numbers. In performance-sensitive code, however,
3181 ratnum slows down computation a lot and you may want to detect that case.
3182 @c JP
3183 @var{x}が正確な非整数の場合に@code{#t}を、そうでなければ@code{#f}を返します。
3184 この述語に@code{#t}を返す数値は内部的には二つの正確な整数の組で表現されています。
3185
3186 通常、正確な整数とratnumとを区別する必要はありません。両方とも単なる正確数です。
3187 ただ、性能が要求されるコードにおいて、ratnumの演算が入ると計算が重くなるので、
3188 その状況を検出したい場合はあるかもしれません。
3189 @c COMMON
3190 @end defun
3191
3192 @node Numerical comparison, Arithmetics, Numerical predicates, Numbers
3193 @subsection Numerical comparison
3194 @c NODE 数値の比較
3195
3196 @defun = z1 z2 z3 @dots{}
3197 [R7RS base]
3198 @c EN
3199 If all the numbers @var{z} are equal numerically, returns @code{#t}.
3200 @c JP
3201 与えられた全ての数値@var{z}が数値として等しければ@code{#t}を返します。
3202 @c COMMON
3203
3204 @example
3205 (= 2 2) @result{} #t
3206 (= 2 3) @result{} #f
3207 (= 2/4 1/2) @result{} #t
3208 @end example
3209
3210 @c EN
3211 Exactness doesn't affect numerical comparison; inexact 1.0 and
3212 exact 1 are @code{=} to each other. Positive inexact zero (0.0) and
3213 negative inexact zero (-0.0) are also @code{=} to each other.
3214 To distinguish numerically equal
3215 exact and inexact number, you have to use @code{eqv?} or @code{equal?}.
3216 @c JP
3217 正確性は数値としての比較には影響しません。非正確な1.0と正確な1は@code{=}とみなされます。
3218 非正確な正のゼロ(0.0)と非正確な負のゼロも@code{=}です。
3219 それらを区別するには、@code{eqv?}や@code{equal?}を使ってください。
3220 @c COMMON
3221
3222 @example
3223 (= 2 2.0) @result{} #t
3224 (= 2 2.0 2.0+0i) @result{} #t
3225 (= -0.0 0.0) @result{} #t
3226
3227 ;; cf:
3228 (eqv? 2 2.0) @result{} #f
3229 (eqv? -0.0 0.0) @result{} #f
3230 @end example
3231
3232 @c EN
3233 Note that @code{+nan.0} would never @code{=} to any number, including itself.
3234 @c JP
3235 @code{+nan.0}は、それ自身を含めていかなる数値とも@code{=}になりません。
3236 @c COMMON
3237
3238 @example
3239 (= +nan.0 +inf.0) @result{} #f
3240 (= +nan.0 +nan.0) @result{} #f
3241
3242 (let ((x +nan.0)) (= x x)) @result{} #f
3243 @end example
3244 @end defun
3245
3246 @defun < x1 x2 x3 @dots{}
3247 @defunx <= x1 x2 x3 @dots{}
3248 @defunx > x1 x2 x3 @dots{}
3249 @defunx >= x1 x2 x3 @dots{}
3250 [R7RS base]
3251 @c EN
3252 Returns @code{#t} If all the real numbers @var{x} are
3253 monotonically increasing,
3254 monotonically nondecreasing, monotonically decreasing, or monotonically
3255 nonincreasing, respectively.
3256 @c JP
3257 与えられた全ての実数@var{x}がそれぞれ単調増加、単調非減少、単調減少、単調非増加している
3258 場合に@code{#t}を返します。
3259 @c COMMON
3260
3261 @c EN
3262 Since @code{(= 0.0 -0.0)} is @code{#t}, @code{(> 0.0 -0.0)} is @code{#f}.
3263 @c JP
3264 @code{(= 0.0 -0.0)}は@code{#t}なので、@code{(> 0.0 -0.0)}は@code{#f}になります。
3265 @c COMMON
3266
3267 @c EN
3268 If any of the argument is NaN, the result is always @code{#f}.
3269 Hence @code{(< x y) @result{} #f} does not imply @code{(>= x y) @result{} #t}.
3270 @c JP
3271 引数にNaNが入っていると結果は@code{#f}になります。
3272 すなわち、@code{(< x y) @result{} #f}だからといって@code{(>= x y) @result{} #t}
3273 とは限りません。
3274 @c COMMON
3275 @end defun
3276
3277
3278 @defun max x1 x2 @dots{}
3279 @defunx min x1 x2 @dots{}
3280 [R7RS base]
3281 @c EN
3282 Returns a maximum or minimum number in the given real numbers, respectively.
3283 If any of the arguments are NaN, NaN is returned.
3284 @c JP
3285 与えられた実数のうち、それぞれ最大と最小のものを返します。
3286 引数にNaNが含まれていた場合は、NaNが返されます。
3287 @c COMMON
3288
3289 @c EN
3290 See also @code{find-min} and @code{find-max} in
3291 @ref{Selection and searching in collection}.
3292 @c JP
3293 @ref{Selection and searching in collection}の
3294 @code{find-min}と@code{find-max}も参照。
3295 @c COMMON
3296 @end defun
3297
3298 @defun min&max x1 x2 @dots{}
3299 @c EN
3300 Returns a maximum and minimum number in the given real numbers.
3301 @c JP
3302 与えられた実数から、最大値と最小値の二つの値を返します。
3303 @c COMMON
3304
3305 @c EN
3306 See also @code{find-min&max} in
3307 @ref{Selection and searching in collection}.
3308 @c JP
3309 @ref{Selection and searching in collection}の
3310 @code{find-min&max}も参照。
3311 @c COMMON
3312 @end defun
3313
3314 @defun approx=? x y :optional relative-tolerance absolute-tolerance
3315 @c EN
3316 Returns @code{#t} iff two numbers are approximately equal within
3317 the given error tolerance.
3318
3319 @itemize @bullet
3320 @item
3321 If at least one of @var{x} or @var{y} is NaN, returns @code{#f}.
3322 @item
3323 If either one is infinity, returns @code{#t} iff the other one is also
3324 infinity of the same sign.
3325 @item
3326 Otherwise, return a boolean value computed as follows:
3327 @example
3328 (<= (abs (- x y))
3329 (max (* (max (abs x) (abs y)) relative-tolerance)
3330 absolute-tolerance))
3331 @end example
3332 @end itemize
3333
3334 If at least one of @var{x} or @var{y} are non-real complex
3335 number, @code{magnitude} is used in place of @code{abs}.
3336
3337 When omitted, @var{relative-tolerance} is assumed to be
3338 @code{(flonum-epsilon)}, and @var{absolute-tolerance} is
3339 @code{(least-positive-flonum)}.
3340 That is, by default, @code{approx=?} tolerates
3341 1 ULP (unit in the last place) error.
3342
3343 The @var{absolute-tolerance} argument is useful when arguments are
3344 close to zero, in which case relative tolerance becomes too small.
3345 @c JP
3346 二つの数値が与えられたエラー許容範囲内で等しいとみなせる場合に@code{#t}を、
3347 そうでなければ@code{#f}を返します。
3348
3349 @itemize @bullet
3350 @item
3351 @var{x}と@var{y}の少なくとも一方がNaNであれば、常に@code{#f}を返します。
3352 @item
3353 一方が無限大である場合、もう一方も同じ符号の無限大である場合のみ@code{#t}を、
3354 そうでなければ@code{#f}を返します。
3355 @item
3356 そうでない場合、次の式により一致が判定されます。
3357 @example
3358 (<= (abs (- x y))
3359 (max (* (max (abs x) (abs y)) relative-tolerance)
3360 absolute-tolerance))
3361 @end example
3362 @end itemize
3363
3364 @var{x}か@var{y}の少なくとも一方が非実数の複素数である場合は、
3365 @code{abs}のかわりに@code{magnitude}が使われます。
3366
3367 省略された場合、@code{relative-tolerance}には
3368 @code{(flonum-epsilon)}の値が、@var{absolute-tolerance}には
3369 @code{(least-positive-flonum)}の値が使われます。
3370 すなわち、デフォルトでは@code{approx=?}は
3371 1 ULP (unit in the last place)のエラーを許容するということです。
3372
3373 @var{absolute-tolerance}引数は、引数がともにゼロに近く、
3374 相対許容範囲が小さくなりすぎる場合に便利です。
3375 @c COMMON
3376 @end defun
3377
3378 @defun flonum-epsilon
3379 @defunx greatest-positive-flonum
3380 @defunx least-positive-flonum
3381 @defunx least-positive-normalized-flonum
3382 @c EN
3383 Returns flonums with the following characteristics, respectively:
3384 @table @code
3385 @item flonum-epsilon
3386 Returns the least positive flonum e such that, for a normalized
3387 flonum @code{x}, @code{x} and @code{(* x (+ 1.0 e))} are distinguishable.
3388 @item greatest-positive-flonum
3389 Returns the greatest positive finite flonum. It is
3390 @code{DBL_MAX} in C.
3391 @item least-positive-flonum
3392 Returns the least positive flonum representable as floating-point
3393 number. If the platform supports denormalized flonum,
3394 it returns the least positive denormalized floating-point number. Otherwise,
3395 it returns the least positive normalized floating-point number.
3396 @item least-positive-normalized-flonum
3397 Returns the least positive flonum representable as normalized floating-point
3398 number. It is @code{DBL_MIN} in C.
3399 @end table
3400 @c JP
3401 それぞれ次の性質を持つ浮動小数点数を返します:
3402 @table @code
3403 @item flonum-epsilon
3404 正規化浮動小数点数@code{x}に対し、@code{x}と@code{(* x (+ 1.0 e))}が
3405 異なる値となるような最小の正の浮動小数点数。
3406 @item greatest-positive-flonum
3407 有限な最大の正の浮動小数点数。Cで言うところの@code{DBL_MAX}。
3408 @item least-positive-flonum
3409 最小の正の浮動小数点数。
3410 プラットフォームが非正規化浮動小数点数をサポートしている場合は最小の
3411 正の非正規化浮動小数点数が、そうでなければ
3412 最小の正の正規化浮動小数点数が返ります。
3413 @item least-positive-normalized-flonum
3414 最小の正の正規化浮動小数点数。
3415 @end table
3416 @c COMMON
3417
3418 @c EN
3419 NB: For portable programs, R7RS @code{scheme.flonum} module
3420 provides constants @code{fl-epsilon}, @code{fl-greatest}, and
3421 @code{fl-least} (@pxref{R7RS flonum}).
3422 @c JP
3423 註: ポータブルなプログラムは、R7RSの@code{scheme.flonum}が提供する
3424 定数@code{fl-epsilon}、@code{fl-greatest}、@code{fl-least}を
3425 使うことができます (@ref{R7RS flonum}参照)。
3426 @c COMMON
3427 @end defun
3428
3429 @defun flonum-min-normalized
3430 @defunx flonum-min-denormalized
3431 @c DEPRECATED
3432 @c EN
3433 These are old names for @code{least-positive-normalized-flonum} and
3434 @code{least-positive-flonum}. We renamed to make the semantics clear.
3435
3436 @itemize @bullet
3437 @item
3438 The new name alignes with @code{least-fixnum} and @code{greatest-fixnum}.
3439 @item
3440 @emph{Min} or @emph{least} could mean negative value farthest from zero.
3441 Having @emph{positive} removes the ambiguity.
3442 @item
3443 Denormalized flonums may not be supported on the platform, so
3444 having @emph{denormalized} in the name is misleading.
3445 @end itemize
3446 @c JP
3447 これらは@code{least-positive-normalized-flonum}および
3448 @code{least-positive-flonum}の旧い名前です。
3449 意味を明確にするために名前を変えました。
3450
3451 @itemize @bullet
3452 @item
3453 新しい名前は@code{least-fixnum}/@code{greatest-fixnum}と統一性があります。
3454 @item
3455 @emph{min}や@emph{least}だけだと、ゼロから負の方向に一番離れている数の意味にも
3456 取れるので、@emph{positive}をつけて曖昧性を排除しました。
3457 @item
3458 非正規化浮動小数点数はサポートされていないプラットフォームがあり得るので、
3459 名前に@emph{denormalized}を入れるのを避けました。
3460 @end itemize
3461 @c COMMON
3462 @end defun
3463
3464 @node Arithmetics, Numerical conversions, Numerical comparison, Numbers
3465 @subsection Arithmetics
3466 @c NODE 数値の演算
3467
3468 @defun + z @dots{}
3469 @defunx * z @dots{}
3470 [R7RS base]
3471 @c EN
3472 Returns the sum or the product of given numbers, respectively.
3473 If no argument is given, @code{(+)} yields 0 and @code{(*)} yields 1.
3474 @c JP
3475 与えられた数の和と積をそれぞれ返します。引数が与えられない場合、
3476 @code{(+)} は 0、 @code{(*)} は 1 となります。
3477 @c COMMON
3478 @end defun
3479
3480 @defun - z1 z2 @dots{}
3481 @defunx / z1 z2 @dots{}
3482 [R7RS base]
3483 @c EN
3484 If only one number @var{z1} is given, returns its
3485 negation and reciprocal, respectively.
3486
3487 If more than one number are given, returns:
3488 @example
3489 @var{z1} - @var{z2} - @var{z3} @dots{}
3490 @var{z1} / @var{z2} / @var{z3} @dots{}
3491 @end example
3492 respectively.
3493 @c JP
3494 一つだけ数値が与えられた場合、それぞれnegationと逆数を返します。
3495
3496 2つ以上の数値が与えられた場合、それぞれ次の結果を返します。
3497 @example
3498 @var{z1} - @var{z2} - @var{z3} @dots{}
3499 @var{z1} / @var{z2} / @var{z3} @dots{}
3500 @end example
3501 @c COMMON
3502
3503 @example
3504 (- 3) @result{} -3
3505 (- -3.0) @result{} 3.0
3506 (- 5+2i) @result{} -5.0-2.0i
3507 (/ 3) @result{} 1/3
3508 (/ 5+2i) @result{} 0.172413793103448-0.0689655172413793i
3509
3510 (- 5 2 1) @result{} 2
3511 (- 5 2.0 1) @result{} 2.0
3512 (- 5+3i -i) @result{} 5.0+2.0i
3513 (/ 14 6) @result{} 7/3
3514 (/ 6+2i 2) @result{} 3.0+1.0i
3515 @end example
3516
3517 @c EN
3518 Note: Gauche didn't have exact rational number support until 0.8.8;
3519 before that, @code{/} coerced the result to inexact even if both
3520 divisor and dividend were exact numbers, when the result wasn't
3521 a whole number. It is not the case anymore.
3522
3523 If the existing code relies on the old behavior, it runs
3524 very slowly on the newer versions of Gauche, since the calculation
3525 proceeds with exact rational arithmetics that is much slower than
3526 floating point arithmetics. You want to use @code{/.} below
3527 to use fast inexact arithmetics (unless you
3528 need exact results).
3529 @c JP
3530 註:0.8.8までGaucheは正確な有理数をサポートしておらず、
3531 それ以前は除数と被除数がともに正確な数であっても商が整数にならなければ
3532 結果は非正確な数へと変換されていました。今のGaucheはそうではありません。
3533
3534 既存のコードが以前のGaucheのふるまいを当てにしていた場合、
3535 速度が大きく低下する可能性があります。正確な有理数の演算は
3536 浮動小数点数の演算よりはるかに遅いからです。
3537 (正確な結果を得たいのでない場合は)下に述べる@code{/.}を使うと良いでしょう。
3538 @c COMMON
3539 @end defun
3540
3541 @defun +. z @dots{}
3542 @defunx *. z @dots{}
3543 @defunx -. z1 z2 @dots{}
3544 @defunx /. z1 z2 @dots{}
3545 @c EN
3546 Like @code{+}, @code{*}, @code{-}, and @code{/}, but the arguments
3547 are coerced to inexact number. So they always return inexact number.
3548 These are useful when you know you don't need exact calculation
3549 and want to avoid accidental overhead of bignums and/or exact
3550 rational numbers.
3551 @c JP
3552 @code{+}、@code{*}、@code{-}、@code{/}と同様ですが、引数は非正確な
3553 数へと変換され、結果も常に非正確な数となります。
3554 正確数による計算が不要で、bignumや正確な有理数をうっかり使ってしまう
3555 ことによるオーバヘッドを避けたい時に便利です。
3556 @c COMMON
3557 @end defun
3558
3559 @defun abs z
3560 [R7RS+ base]
3561 @c EN
3562 For real number @var{z}, returns an absolute value of it.
3563 For complex number @var{z}, returns the magnitude of the number.
3564 The complex part is Gauche extension.
3565 @c JP
3566 実数の@var{z}に対しては、その絶対値を返します。
3567 複素数の@var{z}に対しては、そのmagnitudeを返します。
3568 複素数を扱うのはGaucheの拡張です。
3569 @c COMMON
3570 @example
3571 (abs -1) @result{} 1
3572 (abs -1.0) @result{} 1.0
3573 (abs 1+i) @result{} 1.4142135623731
3574 @end example
3575 @end defun
3576
3577 @defun quotient n1 n2
3578 @defunx remainder n1 n2
3579 @defunx modulo n1 n2
3580 [R7RS base]
3581 @c EN
3582 Returns the quotient, remainder and modulo of dividing an integer @var{n1}
3583 by an integer @var{n2}. The result is an exact number only if
3584 both @var{n1} and @var{n2} are exact numbers.
3585
3586 Remainder and modulo differ when either one of the arguments is negative.
3587 Remainder @var{R} and quotient @var{Q} have the following relationship.
3588 @example
3589 @var{n1} = @var{Q} * @var{n2} + @var{R}
3590 @end example
3591 where @code{abs(@var{Q}) = floor(abs(@var{n1})/abs(@var{n2}))}.
3592 Consequently, @var{R}'s sign is always the same as @var{n1}'s.
3593
3594 On the other hand, modulo works as expected for positive @var{n2},
3595 regardless of the sign of @var{n1}
3596 (e.g. @code{(modulo -1 @var{n2}) == @var{n2} - 1}).
3597 If @var{n2} is negative, it is mapped to the positive case by
3598 the following relationship.
3599 @example
3600 modulo(@var{n1}, @var{n2}) = @minus{}modulo(@minus{}@var{n1}, @minus{}@var{n2})
3601 @end example
3602 Consequently, @var{modulo}'s sign is always the same as @var{n2}'s.
3603 @c JP
3604 整数@var{n1}を整数@var{n2}で割った商(quotient)および余り(remainder, modulo)
3605 を返します。 @var{n1}と@var{n2}の両方が正確な数値の時のみ、戻り値は正確な数値になります。
3606
3607 @code{remainder}と@code{modulo} はどちらかの引数が負の時に異なる値を返します。
3608 Remainder @var{R} と商 @var{Q} とは次の関係があります。
3609 @example
3610 @var{n1} = @var{Q} * @var{n2} + @var{R}
3611 @end example
3612 ここで商について @code{abs(@var{Q}) = floor(abs(@var{n1})/abs(@var{n2}))}
3613 ですから、@var{R}の符号は常に@var{n1}と同じになります。
3614
3615 一方、moduloは@var{n2}が正の時は@var{n1}の符号に関わらず期待したように動作します
3616 (例: @code{(modulo -1 @var{n2}) == @var{n2} - 1})。
3617 @var{n2}が負の場合は次の式によって正の場合にマップできます。
3618 @example
3619 modulo(@var{n1}, @var{n2}) = @minus{}modulo(@minus{}@var{n1}, @minus{}@var{n2})
3620 @end example
3621 したがって、moduloの結果の符号は常に@var{n2}の符号と同じになります。
3622 @c COMMON
3623 @example
3624 (remainder 10 3) @result{} 1
3625 (modulo 10 3) @result{} 1
3626
3627 (remainder -10 3) @result{} -1
3628 (modulo -10 3) @result{} 2
3629
3630 (remainder 10 -3) @result{} 1
3631 (modulo 10 -3) @result{} -2
3632
3633 (remainder -10 -3) @result{} -1
3634 (modulo -10 -3) @result{} -1
3635 @end example
3636 @end defun
3637
3638 @defun quotient&remainder n1 n2
3639 @c EN
3640 Calculates the quotient and the remainder of dividing integer @var{n1}
3641 by integer @var{n2} simultaneously, and returns them as two values.
3642 @c JP
3643 整数@var{n1}を整数@var{n2}で割った商(quotient)および余り(remainder)
3644 を同時に計算し、2つの値として返します。
3645 @c COMMON
3646 @end defun
3647
3648 @defun div x y
3649 @defunx mod x y
3650 @defunx div-and-mod x y
3651 @defunx div0 x y
3652 @defunx mod0 x y
3653 @defunx div0-and-mod0 x y
3654 [R6RS]
3655 @c EN
3656 These are integer division procedures introduced in R6RS.
3657 Unlike @code{quotient}, @code{modulo} and @code{remainder},
3658 these procedures can take non-integral values.
3659 The dividend @var{x} can be an arbitrary real number,
3660 and the divisor @var{y} can be non-zero real number.
3661 @c JP
3662 これらはR6RSで導入された整数除算手続きです。
3663 @code{quotient}, @code{modulo}, @code{remainder}と違い、
3664 これらの手続きは整数でない値を取ることもできます。
3665 被除数@var{x}には任意の実数、除数@var{y}にはゼロ以外の実数が許されます。
3666 @c COMMON
3667
3668 @c EN
3669 @code{div} returns an integer @var{n}, and @code{mod} returns
3670 a real number @var{m}, such that:
3671
3672 @itemize @bullet
3673 @item
3674 @var{x} = @var{n} @var{y} + @var{m}, and
3675 @item
3676 0 <= @var{m} < |@var{y}|.
3677 @end itemize
3678
3679 Examples:
3680 @c JP
3681 @code{div}は整数@var{n}を、@code{mod}は実数@var{m}を返し、
3682 それらは以下の関係を満たします。
3683
3684 @itemize @bullet
3685 @item
3686 @var{x} = @var{n} @var{y} + @var{m}
3687 @item
3688 0 <= @var{m} < |@var{y}|
3689 @end itemize
3690
3691 例:
3692 @c COMMON
3693 @example
3694 (div 123 10) @result{} 12
3695 (mod 123 10) @result{} 3
3696
3697 (div 123 -10) @result{} -12
3698 (mod 123 -10) @result{} 3
3699
3700 (div -123 10) @result{} -13
3701 (mod -123 10) @result{} 7
3702
3703 (div -123 -10) @result{} 13
3704 (mod -123 -10) @result{} 7
3705
3706 (div 123/7 10/9) @result{} 15
3707 (mod 123/7 10/9) @result{} 19/21
3708 ;; 123/7 = 10/9 * 15 + 19/21
3709
3710 (div 14.625 3.75) @result{} 3.0
3711 (mod 14.625 3.75) @result{} 3.375
3712 ;; 14.625 = 3.75 * 3.0 + 3.375
3713 @end example
3714
3715 @c EN
3716 For a nonnegative integer @var{x} and an integer @var{y},
3717 The results of @code{div} and @code{mod} matches
3718 those of @code{quotient} and @code{remainder}. If @var{x}
3719 is negative, they differ, though.
3720 @c JP
3721 @var{x}が非負の整数、@var{y}が整数である場合は、
3722 @code{div}と@code{mod}の結果は@code{quotient}と@code{remainder}
3723 の結果に一致します。しかし@var{x}が負になると結果は異なります。
3724 @c COMMON
3725
3726 @c EN
3727 @code{div-and-mod} calculates both @code{div} and @code{mod}
3728 and returns their results in two values.
3729 @c JP
3730 @code{div-and-mod}は@code{div}と@code{mod}を同時に計算し、
3731 結果を二つの値で返します。
3732 @c COMMON
3733
3734 @c EN
3735 @var{div0} and @var{mod0} are similar, except the range of @var{m}:
3736 @c JP
3737 @var{div0}と@var{mod0}は、@code{m}の値域が異なる以外は同じです。
3738 @c COMMON
3739
3740 @itemize @bullet
3741 @item
3742 @var{x} = @var{n} @var{y} + @var{m}
3743 @item
3744 -|@var{y}|/2 <= @var{m} < |@var{y}|/2
3745 @end itemize
3746
3747 @example
3748 (div0 123 10) @result{} 12
3749 (mod0 123 10) @result{} 3
3750
3751 (div0 127 10) @result{} 13
3752 (mod0 127 10) @result{} -3
3753
3754 (div0 127 -10) @result{} -13
3755 (mod0 127 -10) @result{} -3
3756
3757 (div0 -127 10) @result{} -13
3758 (mod0 -127 10) @result{} 3
3759
3760 (div0 -127 -10) @result{} 13
3761 (mod0 -127 -10) @result{} 3
3762 @end example
3763
3764 @c EN
3765 @code{div0-and-mod0} calculates both @code{div0} and @code{mod0}
3766 and returns their results in two values.
3767 @c JP
3768 @code{div0-and-mod0}は@code{div0}と@code{mod0}を同時に計算し、
3769 結果を二つの値で返します。
3770 @c COMMON
3771
3772 @c EN
3773 Here's a visualization of R6RS and R7RS division and modulo operations:
3774 @url{http://blog.practical-scheme.net/gauche/20100618-integer-divisions}
3775 It might help to grasp how they works.
3776 @c JP
3777 R6RSとR7RSの除算・剰余操作を可視化したものが
3778 @url{http://blog.practical-scheme.net/gauche/20100618-integer-divisions}
3779 にあります。
3780 @c COMMON
3781 @end defun
3782
3783 @defun floor-quotient n d
3784 @defunx floor-remainder n d
3785 @defunx floor/ n d
3786 @defunx truncate-quotient n d
3787 @defunx truncate-remainder n d
3788 @defunx truncate/ n d
3789 [R7RS base]
3790 @c EN
3791 These are integer division operators introduced in R7RS. The names
3792 explicitly indicate how they behave when numerator and/or denominator
3793 is/are negative.
3794
3795 The arguments @var{n} and @var{d} must be an integer. If any of them are
3796 inexact, the result is inexact. If all of them are exact, the result is
3797 exact. Also, @var{d} must not be zero.
3798
3799 Given numerator @var{n}, denominator @var{d}, quotient @var{q} and
3800 remainder @var{r}, the following relations are always kept.
3801
3802 @example
3803 r = n - dq
3804 abs(r) < abs(d)
3805 @end example
3806
3807 Now, @code{(floor-quotient n d)} and @code{(truncate-quotient n d)}
3808 are the same as @code{(floor (/ n d))} and
3809 @code{(truncate (/ n d))}, respectively.
3810 The @code{*-remainder} counterparts are
3811 derived from the above relation.
3812
3813 The @code{/}-suffixed version, @code{floor/} and @code{truncate/},
3814 returns corresponding quotient and remainder as two values.
3815 @c JP
3816 R7RSで導入された整数除算オペレータです。除数や被除数が負の場合の振る舞いが、
3817 名前によって明示されています。
3818
3819 引数@var{n}と@var{d}は整数でなけばなりません。
3820 両方とも正確数であれば結果は正確数に、一方でも非正確数であれば
3821 結果は非正確数になります。また、@var{d}はゼロであってはなりません。
3822
3823 被除数@var{n}、除数@var{d}、商@var{q}、剰余@var{r}には常に以下の関係が成り立ちます。
3824
3825 @example
3826 r = n - dq
3827 abs(r) < abs(d)
3828 @end example
3829
3830 @code{(floor-quotient n d)}と @code{(truncate-quotient n d)}はそれぞれ
3831 @code{(floor (/ n d))}と@code{(truncate (/ n d))}と同じです。
3832 対応する@code{*-remainder}は、上記の関係から導かれます。
3833
3834 @code{floor/} と @code{truncate/}は、対応する商と剰余を二つの値として返します。
3835 @c COMMON
3836
3837 @example
3838 (floor-quotient 10 -3) @result{} -4
3839 (floor-remainder 10 -3) @result{} -2
3840 (truncate-quotient 10 -3) @result{} -3
3841 (truncate-remainder 10 -3) @result{} 1
3842 @end example
3843
3844 @c EN
3845 R7RS division library (@code{scheme.division}) introduces
3846 other variation of integer divisions
3847 (@pxref{R7RS integer division}).
3848 @c JP
3849 R7RS除算ライブラリ(@code{scheme.division})では、
3850 他の整数除算のバリエーションが定義されています。
3851 (@ref{R7RS integer division}参照)。
3852 @c COMMON
3853 @end defun
3854
3855 @defun gcd n @dots{}
3856 @defunx lcm n @dots{}
3857 [R7RS base]
3858 @c EN
3859 Returns the greatest common divisor or the least common multiplier
3860 of the given integers, respectively
3861 @c JP
3862 与えられた整数の、最大公約数と最小公倍数をそれぞれ返します。
3863 @c COMMON
3864
3865 @c EN
3866 Arguments must be integers, but doesn't need to be exact.
3867 If any of arguments is inexact, the result is inexact.
3868 @c JP
3869 引数は整数でなければなりませんが、正確数である必要はありません。
3870 引数が一つでも非正確なら、結果は非正確数になります。
3871 @c COMMON
3872 @end defun
3873
3874 @defun continued-fraction x
3875 @c EN
3876 Returns a lazy sequence of regular continued fraction expansion of
3877 finite real number @var{x}. An error is raised if @var{x} is infinite or
3878 NaN, or not a real number.
3879 The returned sequence is lazy, so the terms are calculated as needed.
3880 @c JP
3881 有限の実数@var{x}の正規連分数展開を、遅延シーケンスで返します。
3882 @var{x}が無限大、NaN、または非実数の場合はエラーが報告されます。
3883 返り値は遅延シーケンスなので、係数は必要になる度に計算されます。
3884 @c COMMON
3885
3886 @example
3887 (continued-fraction 13579/2468)
3888 @result{} (5 1 1 122 1 9)
3889
3890 (+ 5 (/ (+ 1 (/ (+ 1 (/ (+ 122 (/ (+ 1 (/ 9))))))))))
3891 @result{} 13579/2468
3892
3893 (continued-fraction (exact 3.141592653589793))
3894 @result{} (3 7 15 1 292 1 1 1 2 1 3 1 14 3 3 2 1 3 3 7 2 1 1 3 2 42 2)
3895
3896 (continued-fraction 1.5625)
3897 @result{} (1.0 1.0 1.0 3.0 2.0)
3898 @end example
3899 @end defun
3900
3901
3902 @defun numerator q
3903 @defunx denominator q
3904 [R7RS base]
3905 @c EN
3906 Returns the numerator and denominator of a rational number @var{q}.
3907 @c JP
3908 有理数@var{q}の分子と分母をそれぞれ返します。
3909 @c COMMON
3910 @end defun
3911
3912 @defun rationalize x ebound
3913 [R7RS base]
3914 @c EN
3915 Returns the simplest rational approximation @var{q} of a real number @var{x},
3916 such that the difference between @var{x} and @var{q} is no more than
3917 the error bound @var{ebound}.
3918
3919 Note that Gauche doesn't have inexact rational number, so if @var{x}
3920 and/or @var{ebound} is inexact, the result is coerced to
3921 floating point representation. If you want an exact result,
3922 coerce the arguments to exact number first.
3923 @c JP
3924 実数@var{x}を、誤差@var{ebound}以内で近似した最も単純な有理数@var{q}を返します。
3925
3926 Gaucheは非正確な有理数をサポートしないので、引数の少なくとも一方が非正確数だと
3927 結果の有理数が浮動小数点数へと変換され非正確数として返されることに注意してください。
3928 結果を正確数で得たい場合は、引数を正確数で渡してください。
3929 @c COMMON
3930
3931 @example
3932 (rationalize 1234/5678 1/1000) @result{} 5/23
3933
3934 (rationalize 3.141592653589793 1/10000)
3935 @result{} 3.141509433962264
3936 (rationalize (exact 3.141592653589793) 1/10000)
3937 @result{} 333/106
3938 (rationalize (exact 3.141592653589793) 1/10000000)
3939 @result{} 75948/24175
3940
3941 ;; Some edge cases
3942 (rationalize 2 +inf.0) @result{} 0
3943 (rationalize +inf.0 0) @result{} +inf.0
3944 (rationalize +inf.0 +inf.0) @result{} +nan.0
3945 @end example
3946 @end defun
3947
3948
3949 @defun floor x
3950 @defunx ceiling x
3951 @defunx truncate x
3952 @defunx round x
3953 [R7RS base]
3954 @c EN
3955 The argument @var{x} must be a real number.
3956 @code{Floor} and @code{ceiling} return a maximum integer that
3957 isn't greater than @var{x} and a minimum integer that isn't less
3958 than @var{x}, respectively.
3959 @code{Truncate} returns an integer that truncates
3960 @var{x} towards zero. @code{Round} returns an integer that is closest
3961 to @var{x}. If fractional part of @var{x} is exactly 0.5, @code{round}
3962 returns the closest even integer.
3963 @c JP
3964 引数@var{x}は実数でなければなりません。@code{floor}と@code{ceiling}はそれぞれ
3965 @var{x}を越えない最大の整数と、@var{x}を下回らない最小の整数を返します。
3966 @code{truncate}は@var{x}の小数部をゼロの方向に向かって切捨てた整数を返します。
3967 @code{round}は@var{x}に最も近い整数を返します。@var{x}の
3968 小数部が0.5ぴったりだった場合は@code{round}は最も近い偶数を返します。
3969 @c COMMON
3970
3971 @c EN
3972 Following Scheme's general rule, the result is inexact if @var{x} is an
3973 inexact number; e.g. @code{(round 2.3)} is @code{2.0}. If you need
3974 an exact integer by rounding an inexact number, you have to use @code{exact}
3975 on the result, or use one of the following procedure (@code{(floor->exact} etc).
3976 @c JP
3977 Schemeの一般的な規則に従い、@var{x}が非正確数であれば結果も非正確となります。
3978 例えば@code{(round 2.3)}の結果は@code{2.0}です。
3979 もし、非正確な数を丸めて正確な整数を得たいのであれば、結果に@code{exact}を
3980 適用するか、以下に示す@code{floor->exact}などの手続きを使ってください。
3981 @c COMMON
3982 @end defun
3983
3984 @defun floor->exact x
3985 @defunx ceiling->exact x
3986 @defunx truncate->exact x
3987 @defunx round->exact x
3988 @c EN
3989 These are convenience procedures of the popular
3990 phrase @code{(exact (floor x))} etc.
3991 @c JP
3992 これらは、頻出する@code{(exact (floor x))} 等を簡潔に書くための
3993 手続きです。
3994 @c COMMON
3995 @end defun
3996
3997 @defun clamp x :optional min max
3998 @c EN
3999 Returns
4000 @example
4001 @var{min} @r{if} @var{x} @code{<} @var{min}
4002 @var{x} @r{if} @var{min} @code{<=} @var{x} @code{<=} @var{max}
4003 @var{max} @r{if} @var{max} @code{<} @var{x}
4004 @end example
4005 If @var{min} or @var{max} is omitted or @code{#f}, it is regarded
4006 as @code{-inf.0} or @code{+inf.0}, respectively.
4007 Returns an exact integer only if all the given numbers are exact integers.
4008 @c JP
4009 @example
4010 @var{min} @r{if} @var{x} @code{<} @var{min}
4011 @var{x} @r{if} @var{min} @code{<=} @var{x} @code{<=} @var{max}
4012 @var{max} @r{if} @var{max} @code{<} @var{x}
4013 @end example
4014 を返します。もし@var{min}または@var{max}が省略されるか@code{#f}が与えられたら、
4015 それぞれ @var{-∞} もしくは @var{+∞} と解釈されます。
4016 与えられた全ての数値が正確な整数の場合に限り正確な整数を返します。
4017 @c COMMON
4018 @example
4019 (clamp 3.1 0.0 1.0) @result{} 1.0
4020 (clamp 0.5 0.0 1.0) @result{} 0.5
4021 (clamp -0.3 0.0 1.0) @result{} 0.0
4022 (clamp -5 0) @result{} 0
4023 (clamp 3724 #f 256) @result{} 256
4024 @end example
4025 @end defun
4026
4027
4028 @defun exp z
4029 @defunx log z
4030 @defunx log z1 z2
4031 @defunx sin z
4032 @defunx cos z
4033 @defunx tan z
4034 @defunx asin z
4035 @defunx acos z
4036 @defunx atan z
4037 @defunx atan y x
4038 [R7RS inexact]
4039 @c EN
4040 Transcendental functions. Work for complex numbers as well.
4041 In R7RS, these procedures are in the @code{(scheme inexact)} module.
4042 @c JP
4043 超越関数です。複素数も扱えます。
4044 R7RSではこれらの手続きは@code{(scheme inexact)}モジュールにあります。
4045 @c COMMON
4046
4047 @c EN
4048 @code{exp} returns @i{e} raised to the power of @var{z}. The one-argument
4049 version of @code{log} returns the natural logarithm of @var{z}.
4050 The two-argument version of @code{log} is added in R6RS, and returns
4051 base-@var{z2} logarithm of @var{z1}.
4052 @c JP
4053 @code{exp}は@i{e}の@var{z}乗を返します。
4054 1引数の@code{log}は@var{z}の自然対数を返します。
4055 2引数の@code{log}はR6RSで追加されたもので、
4056 @var{z2}を底とした@var{z1}の対数を返します。
4057 @c COMMON
4058
4059 @c EN
4060 The two-argument version of @code{atan} returns
4061 @code{(angle (make-rectangular x y))} for the real numbers @code{x} and @code{y}.
4062 @c JP
4063 2引数の@code{atan}は
4064 実数@var{x}と@var{y}に対して
4065 @code{(angle (make-rectangular x y))}を返します。
4066 @c COMMON
4067
4068 @c EN
4069 See also @code{real-exp} etc. below, for real-only version of these functions.
4070 @c JP
4071 実数に限定したこれらの関数については、下の@code{real-exp}等も参照してください。
4072 @c COMMON
4073 @end defun
4074
4075 @defun sinh z
4076 @defunx cosh z
4077 @defunx tanh z
4078 @defunx asinh z
4079 @defunx acosh z
4080 @defunx atanh z
4081 @c EN
4082 Hyperbolic trigonometric functions. Work for complex numbers as well.
4083
4084 See also @code{real-sinh} etc. below, for real-only version of these functions.
4085 @c JP
4086 双曲線関数です。複素数も扱えます。
4087
4088 実数に限定したこれらの関数については、下の@code{real-sinh}等も参照してください。
4089 @c COMMON
4090 @end defun
4091
4092 @defun radians->degrees rad
4093 @defunx degrees->radians deg
4094 @c EN
4095 Convert radians to degrees and vice versa.
4096 The argument must be a real number.
4097 @c JP
4098 ラジアンと度を変換します。引数は実数でなければなりません。
4099 @c COMMON
4100 @end defun
4101
4102 @defun sqrt z
4103 [R7RS inexact]
4104 @c EN
4105 Returns a square root of a complex number @var{z}.
4106 The branch cut scheme is the same as Common Lisp.
4107 For real numbers, it returns a positive root.
4108
4109 If @var{z} is the square of an exact real number, the return value
4110 is also an exact number.
4111 @c JP
4112 複素数@var{z}の平方根のひとつを返します。枝刈りの定義はCommon Lispと同じです。
4113 実数に対しては正の平方根を返します。
4114
4115 @var{z}が正確な実数の平方である場合、戻り値は正確数となります。
4116 @c COMMON
4117
4118 @example
4119 (sqrt 2) @result{} 1.4142135623730951
4120 (sqrt -2) @result{} 0.0+1.4142135623730951i
4121 (sqrt 256) @result{} 16
4122 (sqrt 256.0) @result{} 16.0
4123 (sqrt 81/169) @result{} 9/13
4124 @end example
4125
4126 @c EN
4127 See also @code{real-sqrt} below, for inexact-real-only version of @code{sqrt}.
4128 @c JP
4129 不正確な実数に限定した@code{sqrt}については、下の@code{real-sqrt}も参照してください。
4130 @c COMMON
4131 @end defun
4132
4133 @defun exact-integer-sqrt k
4134 [R7RS base]
4135 @c EN
4136 Given an exact nonnegative integer @var{k},
4137 returns two exact nonnegative integer @var{s} and @var{r}
4138 that satisfy the following equations:
4139 @c JP
4140 非負の正確な整数@var{k}に対し、次の式を満たす
4141 非負の正確な整数@var{s}と@var{r}を返します。
4142 @c COMMON
4143
4144 @example
4145 @var{k} = (+ (* @var{s} @var{s}) @var{r})
4146 @var{k} < (* (+ @var{s} 1) (+ @var{s} 1))
4147 @end example
4148
4149 @example
4150 (exact-integer-sqrt 782763574)
4151 @result{} 27977 @r{and} 51045
4152 @end example
4153 @end defun
4154
4155
4156 @defun square z
4157 [R7RS base]
4158 @c EN
4159 Returns @code{(* z z)}.
4160 @c JP
4161 @code{(* z z)}を返します。
4162 @c COMMON
4163 @end defun
4164
4165 @defun expt z1 z2
4166 [R7RS base]
4167 @c EN
4168 Returns @var{z1}^@var{z2} (@var{z1} powered by @var{z2}),
4169 where @var{z1} and @var{z2} are complex numbers.
4170 @c JP
4171 複素数@var{z1}, @var{z2}に対して、
4172 @var{z1}^@var{z2} (@var{z1}の@var{z2}乗)を返します。
4173 @c COMMON
4174
4175 @c EN
4176 Scheme standard defines @code{(expt 0 0)} as 1 for convenience.
4177 @c JP
4178 Scheme標準では便宜上@code{(expt 0 0)}は1と定めています。
4179 @c COMMON
4180 @end defun
4181
4182 @defun expt-mod base exponent mod
4183 @c EN
4184 Calculates @code{(modulo (expt base exponent) mod)} efficiently.
4185
4186 The next example shows the last 10 digits of a mersenne prime
4187 M_74207281 (2^74207281 - 1)
4188 @c JP
4189 @code{(modulo (expt base exponent) mod)} を効率よく計算します。
4190
4191 次の例は、メルセンヌ素数M_74207281 (2^74207281 - 1) の最後の10桁を
4192 求めます。
4193 @c COMMON
4194
4195 @example
4196 (- (expt-mod 2 74207281 #e1e10) 1)
4197 @result{} 1086436351
4198 @end example
4199 @end defun
4200
4201 @defun real-exp x
4202 @defunx real-expt x y
4203 @defunx real-ln x
4204 @defunx real-sqrt x
4205 @defunx real-sin x
4206 @defunx real-cos x
4207 @defunx real-tan x
4208 @defunx real-asin x
4209 @defunx real-acos x
4210 @defunx real-atan x
4211 @defunx real-atan y x
4212 [SRFI-94]
4213 @c EN
4214 Real-only version of elementary functions. An error is signaled
4215 unless the arguments are real numbers.
4216
4217 These are useful for performance-sensitive code, for they don't need to
4218 check whether the input is complex. Furthermore, they are subject to
4219 constant folding.
4220
4221 Those names are defined in SRFI-94. However, for the portable programs,
4222 you may want to use @code{scheme.flonum} module, which is a part of
4223 R7RS-large and defines
4224 flonum-only versions of elementary functions (@pxref{R7RS flonum}).
4225 @c JP
4226 実数の範囲に限定した初等関数です。引数が実数でなかったらエラーが投げられます。
4227
4228 性能を気にするコードでは有用です。複素数の処理のためのチェックが省かれるのと、
4229 定数畳み込みが行われやすくなります。
4230
4231 これらの名前はSRFI-94で定義されています。ただ、今ポータブルなコードを書きたいなら、
4232 R7RS-largeの一部である@code{scheme.flonum}を使う方が良いでしょう。
4233 そこではflonum限定の初等関数が定義されています(@ref{R7RS flonum}参照)。
4234 @c COMMON
4235
4236 @c EN
4237 Note: SRFI-94 defines @code{real-log}, which is a two-argument version
4238 of real-only @code{log}, but it takes base argument first, which is
4239 different from R7RS two-argument @code{log}. To avoid confusion,
4240 we don't support @code{real-log} in the core.
4241 @c JP
4242 註:SRFI-94は実数限定の2引数の@code{log}である@code{real-log}も定義しているのですが、
4243 対数の底を最初の引数に取るようになっていて、R7RSの@code{log}とは逆です。
4244 混乱を避けるため、コアでは@code{real-log}は提供していません。
4245 @c COMMON
4246 @end defun
4247
4248 @defun real-sinpi x
4249 @defunx real-cospi x
4250 @defunx real-tanpi x
4251 @c EN
4252 Returns sin(πx), cos(πx), and tan(πx), respectively.
4253 An error is signaled if the argument is not a real number.
4254 These come handy sometimes, as the following example show:
4255 @c JP
4256 それぞれsin(πx)、cos(πx)、tan(πx)を返します。
4257 引数が実数でなければエラーを投げます。
4258 下の例が示すように、これらはしばしば便利です:
4259 @c COMMON
4260
4261 @example
4262 (use math.const)
4263 (real-sin pi) @result{} 1.2246467991473532e-16
4264 (real-sinpi 1.0) @result{} 0.0
4265
4266 (real-cos (/ pi 2)) @result{} 6.123233995736766e-17
4267 (real-cospi 0.5) @result{} 0.0
4268 @end example
4269 @end defun
4270
4271 @defun real-sinh x
4272 @defunx real-cosh x
4273 @defunx real-tanh x
4274 @defunx real-asinh x
4275 @defunx real-acosh x
4276 @defunx real-atanh x
4277 @c EN
4278 Real-only version of hyperbolic functions and their inverses.
4279 An error is signaled if the argument is not a real number.
4280 @c JP
4281 実数限定の双曲線関数とその逆関数です。
4282 引数が実数でなければエラーが投げられます。
4283 @c COMMON
4284 @end defun
4285
4286 @defun gamma x
4287 @defunx lgamma x
4288 @c EN
4289 Gamma function and natural logarithmic of absolute value of Gamma function.
4290
4291 NB: Mathematically these functions are defined in complex domain, but
4292 currently we only support real number argument.
4293 @c JP
4294 ガンマ関数と、ガンマ関数の絶対値の自然対数です。
4295
4296 註:数学的にはこれらの関数は複素領域で定義されますが、現在の実装は実数引数だけを
4297 サポートします。
4298 @c COMMON
4299 @end defun
4300
4301 @c NB: These should be moved to a separate subsection once we got
4302 @c more fixnum-specific operation support.
4303
4304 @defun fixnum-width
4305 @defunx greatest-fixnum
4306 @defunx least-fixnum
4307 [R6RS]
4308 @c EN
4309 These procedures return the width of fixnum (@var{w}),
4310 the greatest integer representable by fixnum (@code{2^(@var{w}-1) - 1}),
4311 and the least integer representable by fixnum (@code{- 2^(@var{w}-1)}),
4312 respectively. You might want to care the fixnum range when
4313 you are writing a performance-critical section.
4314
4315 These names are defined in R6RS. Common Lisp and ChezScheme have
4316 @code{most-positive-fixnum} and @code{most-negative-fixnum}.
4317 @c JP
4318 これらの手続きは、fixnumで表現できる数値の幅 (@var{w}とします)、
4319 fixnumで表現できる最大の整数値 (@code{2^(@var{w}-1) - 1})、および
4320 fixnumで表現できる最小の整数値 (@code{- 2^(@var{w}-1)}) を
4321 それぞれ返します。性能が重要になる部分では数値がfixnumの範囲に収まるかどうかを
4322 気にかける必要があります。
4323
4324 これらの名前はR6RSで定義されました。Common LispとChezSchemeには
4325 @code{most-positive-fixnum}および@code{most-negative-fixnum}があります。
4326 @c COMMON
4327
4328 @c EN
4329 NB: Before 0.9.5, @code{fixnum-width} had a bug
4330 to return one smaller than the supposed value.
4331 @c JP
4332 註: 0.9.5以前の@code{fixnum-width}には本来より1小さい値を返すバグがありました。
4333 @c COMMON
4334 @end defun
4335
4336 @node Numerical conversions, Basic bitwise operations, Arithmetics, Numbers
4337 @subsection Numerical conversions
4338 @c NODE 数値の変換
4339
4340 @defun make-rectangular x1 x2
4341 @defunx make-polar x1 x2
4342 [R7RS complex]
4343 @c EN
4344 Creates a complex number from two real numbers, @var{x1} and @var{x2}.
4345 @code{make-rectangular} returns @var{x1} + @b{i}@var{x2}.
4346 @code{make-polar} returns @var{x1}@b{e}^(@b{i}@var{x2}).
4347
4348 In R7RS, these procedures are in the @code{(scheme complex)} library.
4349 @c JP
4350 二つの実数@var{x1}と@var{x2}から複素数を作ります。
4351 @code{make-rectangular} は @var{x1} + @b{i}@var{x2} を返します。
4352 @code{make-polar} は @var{x1}@b{e}^(@b{i}@var{x2}) を返します。
4353
4354 R7RSではこれらの手続きは@code{(scheme complex)}ライブラリにあります。
4355 @c COMMON
4356 @end defun
4357
4358 @defun real-part z
4359 @defunx imag-part z
4360 @defunx magnitude z
4361 @defunx angle z
4362 [R7RS complex]
4363 @c EN
4364 Decompose a complex number @var{z} and returns a real number.
4365 @code{real-part} and @code{imag-part} return @var{z}'s real and imaginary
4366 part, respectively. @code{magnitude} and @code{angle} return
4367 @var{z}'s magnitude and angle, respectively.
4368
4369 In R7RS, these procedures are in the @code{(scheme complex)} library.
4370 @c JP
4371 複素数@var{z}を取り、実数を返します。
4372 @code{real-part}と@code{imag-part}は@var{z}の実数部と虚数部をそれぞれ返し、
4373 @code{magnitude}と@code{angle}は@var{z}の絶対値と偏角をそれぞれ返します。
4374
4375 R7RSではこれらの手続きは@code{(scheme complex)}ライブラリにあります。
4376 @c COMMON
4377 @end defun
4378
4379 @defun decode-float x
4380 @c EN
4381 For a given finite floating-point number, returns
4382 a vector of three exact integers, @code{#(@var{m}, @var{e}, @var{sign})},
4383 where
4384 @example
4385 @var{x} = (* @var{sign} @var{m} (expt 2.0 @var{e}))
4386 @var{sign} is either 1, 0 or -1.
4387 @end example
4388
4389 If @var{x} is @code{+inf.0} or @code{-inf.0}, @var{m} is @code{#t}.
4390 If @var{x} is @code{+nan.0}, @var{m} is @code{#f}.
4391
4392 The API is taken from ChezScheme.
4393 @c JP
4394 与えられた有限の浮動小数点数@var{x}に対して、
4395 3つの正確な整数からなるベクタ @code{#(@var{m}, @var{e}, @var{sign})}
4396 を返します。ここで、
4397 @example
4398 @var{x} = (* @var{sign} @var{m} (expt 2.0 @var{e}))
4399 @var{sign} は 1, 0 または -1.
4400 @end example
4401 です。
4402
4403 特例として、@var{x}が@code{+inf.0}もしくは@code{-inf.0}の時は
4404 @var{m}が@code{#t}に、
4405 @var{x}が@code{+nan.0}の時は@var{m}が@code{#f}になります。
4406
4407 このAPIはChezSchemeから取られました。
4408 @c COMMON
4409
4410 @example
4411 (decode-float 3.1415926)
4412 @result{} #(7074237631354954 -51 1)
4413 (* 7074237631354954 (expt 2.0 -51))
4414 @result{} 3.1415926
4415
4416 (decode-float +nan.0)
4417 @result{} #(#f 0 -1)
4418 @end example
4419 @end defun
4420
4421 @defun encode-float vector
4422 @c EN
4423 This is an inverse of @code{decode-float}. @var{Vector} must be
4424 a three-element vector as returned from @code{decode-float}.
4425 @c JP
4426 これは@code{decode-float}の逆関数です。@var{vector}は
4427 @code{decode-float}が返す形式の3要素のベクタでなければなりません。
4428 @c COMMON
4429
4430 @example
4431 (encode-float '#(7074237631354954 -51 1))
4432 @result{} 3.1415926
4433
4434 (encode-float '#(#t 0 1))
4435 @result{} +inf.0
4436 @end example
4437 @end defun
4438
4439
4440 @defun fmod x y
4441 @defunx modf x
4442 @defunx frexp x
4443 @defunx ldexp x n
4444 [POSIX]
4445 @c EN
4446 These procedures can be used to compose and decompose floating
4447 point numbers. @code{Fmod} computes the remainder of dividing @var{x}
4448 by @var{y}, that is, it returns @var{x}-@var{n}*@var{y} where
4449 @var{n} is the quotient of @var{x}/@var{y} rounded towards zero
4450 to an integer. @code{Modf} returns two values; a fractional
4451 part of @var{x} and an integral part of @var{x}. @code{Frexp}
4452 returns two values, @var{fraction} and @var{exponent} of @var{x},
4453 where @var{x} = @var{fraction} * 2^@var{exponent}, and
4454 0.5 <= |@var{fraction}| < 1.0, unless @var{x} is zero.
4455 (When @var{x} is zero, both @var{fraction} and @var{exponent} are zero).
4456 @var{Ldexp} is a reverse operation of
4457 @code{frexp}; it returns a real number @var{x} * 2^@var{n}.
4458 @c JP
4459 これらの手続きは、浮動小数点数を分解したり合成するのに使えます。
4460 @code{fmod}は実数@var{x}を実数@var{y}で割った余りを返します。すなわち、
4461 @var{x}/@var{y}を0に近いほうの整数に丸めた値を@var{n}とするとき、
4462 @var{x}-@var{n}*@var{y}を返します。
4463 @code{modf}は@var{x}の少数部と整数部を返します。
4464 @code{frexp}は実数@var{x}を、仮数部と指数部に分解して返します。すなわち、
4465 @var{x}が0でない限り、
4466 @var{x} = @var{fraction} * 2^@var{exponent} かつ 0.5 <= |@var{fraction}| < 1.0
4467 であるところの@var{fraction}と@var{exponent}を返します。
4468 (@var{x}が0であれば、@var{fraction}と@var{exponent}はともに0となります。)
4469 @code{ldexp}は@code{frexp}の逆関数で、@var{x} * 2^@var{n} を返します。
4470 @c COMMON
4471
4472 @example
4473 (fmod 32.1 10.0) @result{} 2.1
4474 (fmod 1.5 1.4) @result{} 0.1
4475 (modf 12.5) @result{} 0.5 @r{and} 12.0
4476 (frexp 3.14) @result{} 0.785 @r{and} 2
4477 (ldexp 0.785 2) @result{} 3.14
4478 @end example
4479 @end defun
4480
4481 @c @defun logb x
4482 @c @defunx ilogb x
4483 @c [POSIX]
4484 @c @c EN
4485 @c These procedure returns exponent of flonum @var{x}. The return value
4486 @c of @code{logb} is a flonum, whereas the return value of @code{ilogb} is
4487 @c an exact integer.
4488
4489 @c If @var{x} is 0, infinity, or NaN, @code{logb} returns @code{-inf.0},
4490 @c @code{+inf.0} and @code{+nan.0}, respectively. What @code{ilogb} returns
4491 @c in those cases are platform-dependent, but it's consistent in one platform,
4492 @c @c JP
4493 @c 浮動小数点数@var{x}の指数部を返します。@code{logb}の戻り値は浮動小数点数、
4494 @c @code{ilogb}の戻り値は正確な整数です。
4495
4496 @c @var{x}が0、±無限大、NaNの場合、@code{logb}はそれぞれ@code{-inf.0}、
4497 @c @code{+inf.0}、@code{+nan.0}を返します。これらの場合に@code{ilogb}が返す値は
4498 @c プラットフォームに依存しますが、一つのプラットフォームの上では一貫しています。
4499 @c @c COMMON
4500
4501 @c @example
4502 @c (logb 1) @result{} 0.0
4503 @c (ilogb 1) @result{} 0
4504
4505 @c (logb 2) @result{} 1.0
4506 @c (logb -2) @result{} 1.0
4507 @c (logb -0.5) @result{} -1.0
4508
4509 @c (logb 5.0e-324) @result{} -1074.0
4510 @c (logb 1.7976931348623157e308) @result{} 1023.0
4511
4512 @c (logb 0) @result{} -inf.0
4513 @c (logb +inf.0) @result{} +inf.0
4514 @c (logb -inf.0) @result{} +inf.0
4515 @c (logb +nan.0) @result{} +nan.0
4516
4517 @c (ilogb 0) @result{} -2147483648 ;; platform dependent
4518 @c (ilogb +inf.0) @result{} 2147483647 ;; platform dependent
4519 @c (ilogb +nan.0) @result{} -2147483648 ;; platform dependent
4520 @c @end example
4521 @c @end defun
4522
4523
4524 @defun exact z
4525 @defunx inexact z
4526 [R7RS base]
4527 @c EN
4528 Returns an exact or an inexact representation of the
4529 given number @var{z}, respectively. Passing an exact number
4530 to @code{exact}, and an inexact number to @code{inexact}, are no-op.
4531
4532 Gauche doesn't have exact complex number with non-zero imaginary part,
4533 nor exact infinites and NaNs, so passing those to @code{exact} raises
4534 an error.
4535 @c JP
4536 それぞれ数@var{z}の正確な表現および非正確な表現を返します。
4537 正確数を@code{exact}に渡した場合や、非正確数を@code{inexact}に渡した場合は
4538 渡した値がそのまま返されます。
4539
4540 Gaucheは、虚部がゼロでない正確な複素数や、正確な無限大/NaNをサポートしないので、
4541 これらの数が@code{exact}に渡された場合はエラーとなります。
4542 @c COMMON
4543
4544 @example
4545 (inexact 1) @result{} 1.0
4546 (inexact 1/10) @result{} 0.1
4547 @end example
4548
4549 @c EN
4550 If an inexact finite real number is passed to @code{exact},
4551 the simplest exact rational number within the precision of the
4552 floating point representation is returned.
4553 @c JP
4554 非正確で有限な実数が@code{exact}に渡された場合は、
4555 浮動小数点数演算の精度の中で最も簡単な表現となる正確な有理数が返されます。
4556 @c COMMON
4557
4558 @example
4559 (exact 1.0) @result{} 1
4560 (exact 0.1) @result{} 1/10
4561 (exact (/ 3.0)) @result{} 1/3
4562 @end example
4563
4564 @c EN
4565 For all finite inexact real number @var{x},
4566 @code{(inexact (exact @var{x}))} is always @code{eqv?} to
4567 the original number @var{x}.
4568 @c JP
4569 あらゆる有限の非正確な実数@var{x}について、
4570 @code{(inexact (exact @var{x}))} は常に元の数@var{x}と
4571 @code{eqv?}になります。
4572 @c COMMON
4573
4574 @c EN
4575 (Note that the inverse doesn't hold, that is, an exact number @var{n}
4576 and @code{(exact (inexact @var{n}))} aren't necessarily the same.
4577 It's because many (actually, infinite number of) exact numbers
4578 can be mapped to one inexact number.)
4579 @c JP
4580 (その逆、つまり正確数 @var{n} と @code{(exact (inexact @var{n}))} は
4581 必ずしも等しくならないことに注意してください。
4582 ある非正確数へと写像される正確数は無数にあり得るためです。)
4583 @c COMMON
4584
4585 @c EN
4586 To specify the error tolerance when converting inexact real numbers
4587 to exact rational numbers, use @code{rationalize} or @code{real->rational}.
4588 @c JP
4589 誤差の許容範囲を指定して非正確な実数を正確な有理数に直したい場合は、
4590 @code{rationalize}および@code{real->rational}を参照してください。
4591 @c COMMON
4592 @end defun
4593
4594 @defun exact->inexact z
4595 @defunx inexact->exact z
4596 [R5RS]
4597 @c EN
4598 Converts exact number to inexact one, and vice versa.
4599
4600 In fact, @code{exact->inexact} returns the argument as is
4601 if an inexact number is passed, and @code{inexact->exact}
4602 returns the argument if an exact number is passed, so
4603 in Gauche they are equivalent to @code{inexact} and @code{exact},
4604 respectively. Note that other R5RS implementation may raise
4605 an error if passing an inexact number to @code{exact->inexact},
4606 for example.
4607
4608 Generally @code{exact} and @code{inexact} are preferred,
4609 for they are more concise, and you don't need to care
4610 whether the argument is exact or inexact numbers.
4611 These procedures are for compatibility with R5RS programs.
4612 @c JP
4613 それぞれ、正確数を非正確に変換、あるいはその逆を行います。
4614
4615 非正確な数を@code{exact->inexact}に渡したり、または正確な数を
4616 @code{inexact->exact}に渡した場合、Gaucheではそれをエラーにせず
4617 引数をそのまま返します。従ってこれらはGaucheでは
4618 上の@code{inexact}および@code{exact}とそれぞれ等価です。
4619 R5RS実装の中には、非正確数を@code{exact->inexact}に渡したりすると
4620 エラーになるものもあり得るので、ポータブルなコードを書く場合は
4621 注意してください。
4622
4623 一般的には、@code{exact}および@code{inexact}を使う方が
4624 簡潔で良いでしょう。こちらの手続きはR5RSプログラムとの互換性の
4625 ために用意されています。
4626 @c COMMON
4627 @end defun
4628
4629 @defun real->rational x :optional hi lo open?
4630 @c EN
4631 Find the simplest rational representation of a finite real
4632 number @var{x} within the specified error bounds. This is the low-level
4633 routine called by @code{rationalize} and @code{exact}.
4634 Typically you want to use @code{rationalize} (@pxref{Arithmetics})
4635 for this purpose. Use @code{real->rational} only when you need finer
4636 control of error bounds.
4637 @c JP
4638 指定されたエラー範囲の中で、有限な実数@var{x}の正確な有理数表現のうち
4639 最も簡単なものを返します。@code{rationalize}や@code{exact}はこの手続きを
4640 下請けとして呼び出しています。通常は@code{rationalize} (@ref{Arithmetics}参照)
4641 を使い、@code{real->rational}は誤差許容値をより細かく制御したい時のみ
4642 使うのが良いでしょう。
4643 @c COMMON
4644
4645 @c EN
4646 The result
4647 rational value @var{r} satisfies the following condition:
4648 @c JP
4649 返される有理数は次の条件を満たします。
4650 @c COMMON
4651
4652 @example
4653 (<= (- x lo) r (+ x hi)) ; when open? is #f
4654 (< (- x lo) r (+ x hi)) ; otherwise
4655 @end example
4656
4657 @c EN
4658 Note that both @var{hi} and @var{lo} must be nonnegative.
4659
4660 If @var{hi} and/or @var{lo} is omitted, it is determined by @var{x}:
4661 if @var{x} is exact, @var{hi} and @var{lo} are defaulted to zero; if
4662 @var{x} is inexact, @var{hi} and @var{lo} depend on
4663 the precision of the floating point representation of @var{x}.
4664 In the latter case, the @var{open?} also depends on @var{x}---it is true
4665 if the mantissa of @var{x} is odd, and false otherwise, reflecting
4666 the round-to-even rule. So, if you call @code{real->rational} with
4667 one finite number, you'll get the same result as @code{exact}:
4668 @c JP
4669 @var{hi}と@var{lo}は非負でなければなりません。
4670
4671 @var{hi}と@var{lo}の両方、もしくは一方が省略された場合、それは@var{x}の値に応じて
4672 決定されます。@var{x}が正確数の場合、省略された@var{hi}/@var{lo}はゼロとみなされます。
4673 @var{x}が非正確数の場合は、@var{x}の浮動小数点数表現の精度に基づいて
4674 @var{hi}/@var{lo}が決定されます。後者の場合、@var{open?}の値もまた、
4675 @var{x}の値で決まります。浮動小数点数の「偶数丸め」規則に対応して、
4676 @var{x}の仮数部が奇数であれば@var{open?}は真、そうでなければ偽となります。
4677 従って、@code{real->rational}にひとつの有限の数値だけを渡した場合、
4678 その動作は@code{exact}と同じになります。
4679 @c COMMON
4680
4681 @example
4682 (real->rational 0.1) @result{} 1/10
4683 @end example
4684
4685 @c EN
4686 Passing zeros to the error bounds makes it return the exact
4687 conversion of the floating number itself (that is, the exact
4688 calculation of @code{(* sign mantissa (expt 2 exponent))}).
4689 @c JP
4690 エラー範囲にゼロを渡すと、引数の浮動小数点数の正確な数値表現
4691 (つまり、@code{(* sign mantissa (expt 2 exponent))}を正確値で計算した結果)
4692 が返されます。
4693 @c COMMON
4694
4695 @example
4696 (real->rational 0.1 0 0) @result{} 3602879701896397/36028797018963968
4697 @end example
4698
4699 @c EN
4700 (If you give both @var{hi} and @var{lo}, but omit @var{open?},
4701 we assume closed range.)
4702 @c JP
4703 (@var{hi}と@var{lo}引数を与えて @var{open?}を省略した場合は、
4704 閉じた範囲と考えます。)
4705 @c COMMON
4706 @end defun
4707
4708 @defun number->string z :optional radix use-upper?
4709 @defunx string->number string :optional radix default-exactness
4710 [R7RS+ base]
4711 @c EN
4712 These procedures convert a number and its string representation
4713 in radix @var{radix} system.
4714 @var{radix} must be between 2 and 36 inclusive.
4715 If @var{radix} is omitted, 10 is assumed.
4716
4717 @code{Number->string} takes a number @var{z} and returns a string.
4718 If @var{z} is not an exact integer, @var{radix} must be 10.
4719 For the numbers with radix more than 10, lower case alphabet
4720 character is used for digits, unless the optional argument
4721 @var{use-upper?} is true, in that case upper case characters are used.
4722 The argument @var{use-upper?} is Gauche's extension.
4723
4724 @code{String->number} takes a string @var{string} and parses it
4725 as a number in radix @var{radix} system. If the number contains
4726 a decimal point, only radix 10 is allowed. If the given string
4727 can't be a number, @code{#f} is returned.
4728
4729 The @var{default-exactness} optional argument of @code{string->number}
4730 is Gauche's extension, and it must be either @code{#f} (default),
4731 a symbol @code{exact}, or a symbol @code{inexact}.
4732 If it is either symbol, it sets the exactness of the number if
4733 no exactness prefix (@code{#e} or @code{#i}) is given.
4734 If @var{string} has an exactness prefix, @var{default-exactness}
4735 is irrelevant.
4736 @c JP
4737 これらの手続きは数値とそれを@var{radix}進数で表現する文字列とを変換します。
4738 @var{radix}は2から36の間でなければなりません。省略された場合は10進数とみなされます。
4739
4740 @code{number->string}は数値@var{z}を取り文字列を返します。
4741 @var{z}が正確な整数以外の場合、@var{radix}は10でなければなりません。
4742 10より大きい@var{radix}に関しては、小文字のアルファベットが桁として使われます。
4743 但し、省略可能な引数@var{use-upper?}に真の値が与えられた場合は大文字のアルファベットが
4744 使われます。@var{use-upper?}引数はGaucheの拡張です。
4745
4746 @code{string->number}は文字列@var{string}を取り数値を返します。
4747 入力が小数点を含んでいる場合は10進数表記しか認識されません。
4748 与えられた文字列が数値を構成しない場合は@code{#f}が返されます。
4749
4750 @code{string->number}の省略可能引数@var{default-exactness}はGaucheの拡張で、
4751 @code{#f} (デフォルト)あるいはシンボル@code{exact}または@code{inexact}の
4752 いずれかでなければなりません。
4753 シンボルが与えられた場合は、正確数か非正確数かがプレフィクス(@code{#e}もしくは@code{#i})
4754 で明示されていない場合の正確性の解釈を指定します。
4755 文字列に正確性のプレフィクスがついていた場合は@var{default-exactness}
4756 の指定は無視されます。
4757 @c COMMON
4758
4759 @example
4760 (string->number "2.718281828459045" 10 'exact)
4761 @result{} 543656365691809/200000000000000
4762 (string->number "#i2.718281828459045" 10 'exact)
4763 @result{} 2.718281828459045
4764 (string->number "1/3" 10 'inexact)
4765 @result{} 0.3333333333333333
4766 (string->number "#e1/3" 10 'inexact)
4767 @result{} 1/3
4768 @end example
4769 @end defun
4770
4771 @deffn {Generic Function} x->number obj
4772 @deffnx {Generic Function} x->integer obj
4773 @c EN
4774 Generic coercion functions. Returns `natural' interpretation of @var{obj}
4775 as a number or an exact integer, respectively.
4776 The default methods are defined for numbers and strings; a string is
4777 interpreted by @code{string->number}, and if the string can't be
4778 interpreted as a number, 0 is returned.
4779 Other @var{obj} is simply converted to 0.
4780 If @var{obj} is naturally interpreted
4781 as a number that is not an exact integer, @code{x->integer} uses
4782 @code{round} and @code{inexact->exact} to obtain an integer.
4783
4784 Other class may provide a method to customize the behavior.
4785 @c JP
4786 数値への強制型変換手続きです。
4787 @var{obj}をそれぞれ数値もしくは正確な整数と解釈して返します。
4788 数値と文字列に対してのメソッドは定義されています
4789 (文字列は@code{string->number}を使って変換されます。
4790 数値として解釈できない文字列に関しては0が返されます)。
4791 その他の@var{obj}については単に0が返されます。
4792 @code{x->integer}は、@var{obj}が数値として表現できるけれど正確な整数では
4793 ない場合、@code{round}と@code{inexact->exact}によって正確な整数に変換します。
4794
4795 他のクラスはこのメソッドを定義することにより、独自の変換関数を提供することができます。
4796 @c COMMON
4797 @end deffn
4798
4799 @node Basic bitwise operations, Endianness, Numerical conversions, Numbers
4800 @subsection Basic bitwise operations
4801 @c NODE 基本的なビット演算
4802
4803 @c EN
4804 These procedures treat integers as half-open bit vectors.
4805 If an integer is positive, it is regarded as if infinite number
4806 of zeros are padded to the left. If an integer is negative,
4807 it is regarded in 2's complement form, and infinite number of
4808 1's are padded to the left.
4809 @c JP
4810 これらの手続きは整数を半無限のビットベクタとして扱います。
4811 正の整数の場合、数値の左側に無限に0が続いていると見倣されます。
4812 負の整数の場合、数値は2の補数で表現され、左側に無限に1が続いていると見倣されます。
4813 @c COMMON
4814
4815 @c EN
4816 In regard to the names of those operations, there are two groups
4817 in the Scheme world; Gauche follows the names of the
4818 original SLIB's ``logical'' module, which was rooted in CL.
4819 Another group uses a bit long but descriptive name such as
4820 @code{arithmetic-shift}.
4821 @c JP
4822 これらの操作の名前に関しては、Scheme界には大きく二つの流儀があります。
4823 GaucheはSLIBの元々の``logical''モジュールに合わせました。
4824 その起源はCommon Lispです。
4825 もう一つの流儀では、@code{arithmetic-shift}といった、より長く記述的な名前を使います。
4826 @c COMMON
4827
4828 @c EN
4829 R7RS bitwise library
4830 (@pxref{R7RS bitwise operations}) provides additional bitwise operations.
4831 @c JP
4832 R7RSビット演算ライブラリ(@pxref{R7RS bitwise operations})
4833 は追加のビット演算を提供しています。
4834 @c COMMON
4835
4836 @defun ash n count
4837 [SRFI-60]
4838 @c EN
4839 Shifts integer @var{n} left with @var{count} bits.
4840 If @var{count} is negative, @code{ash} shifts @var{n} right with
4841 @minus{}@var{count} bits.
4842 @c JP
4843 整数@var{n}を左に整数@var{count}ビットだけシフトします。
4844 @var{count}が負であれば、@minus{}@var{count}だけ@var{n}を右にシフトします。
4845 @c COMMON
4846
4847 @example
4848 ; @r{Note: 6 @equiv{} [...00110], and}
4849 ; @r{ -6 @equiv{} [...11010]}
4850 (ash 6 2) @result{} 24 ;@r{[...0011000]}
4851 (ash 6 -2) @result{} 1 ;@r{[...0000001]}
4852 (ash -6 2) @result{} -24 ;@r{[...1101000]}
4853 (ash -6 -2) @result{} -2 ;@r{[...1111110]}
4854 @end example
4855 @end defun
4856
4857 @defun logand n1 @dots{}
4858 @defunx logior n1 @dots{}
4859 @defunx logxor n1 @dots{}
4860 [SRFI-60]
4861 @c EN
4862 Returns bitwise and, bitwise inclusive or and bitwise exclusive or
4863 of integers @var{n1} @dots{}. If no arguments are given, @code{logand}
4864 returns @code{-1}, and @code{logior} and @code{logxor} returns @code{0}.
4865 @c JP
4866 整数@var{n1} @dots{}の、それぞれビット論理積、
4867 ビット論理和、ビット排他的論理積を返します。
4868 ゼロ個の引数が与えられた場合は、@code{logand}は@code{-1}を、
4869 @code{logior}と@code{logxor}は@code{0}を返します。
4870 @c COMMON
4871 @end defun
4872
4873 @defun lognot n
4874 [SRFI-60]
4875 @c EN
4876 Returns bitwise not of an integer @var{n}.
4877 @c JP
4878 整数@var{n}のビット否定を返します。
4879 @c COMMON
4880 @end defun
4881
4882 @defun logtest n1 n2 @dots{}
4883 [SRFI-60]
4884 @equiv{} @code{(not (zero? (logand @var{n1} @var{n2} @dots{})))}
4885 @end defun
4886
4887 @defun logbit? index n
4888 [SRFI-60]
4889 @c EN
4890 Returns @code{#t} if @var{index}-th bit of integer @var{n} is 1,
4891 @code{#f} otherwise.
4892 @c JP
4893 整数@var{n}の@var{index}目のビットが1ならば@code{#t}を、0ならば@code{#f}を
4894 返します。
4895 @c COMMON
4896 @end defun
4897
4898 @defun logset+clear n set-bits clear-bits
4899 @c EN
4900 Returns an integer such that @var{n}'s bit is set where @var{set-bits} is 1,
4901 and cleared where @var{clear-bits} is 1. If a bit is included in both
4902 @var{set-bits} and @var{clear-bits}, it is cleared.
4903
4904 It is effectively the same as
4905 @code{(logand (logior n set-bits) (lognot clear-bits))}.
4906 @c JP
4907 @var{n}のビットのうち、@var{set-bits}で1が立っているビットを立て、
4908 @var{clear-bits}で1が立っているビットをクリアした整数を返します。
4909
4910 実質的に@code{(logand (logior n set-bits) (lognot clear-bits))}と同じです。
4911 @c COMMON
4912
4913 @example
4914 (logset+clear #b11000011 #b00001100 #b01000001)
4915 @result{} 142 ;; #b10001110
4916 @end example
4917 @end defun
4918
4919 @defun bit-field n start end
4920 [R7RS bitwise]
4921 @c EN
4922 Extracts @var{start}-th bit (inclusive) to @var{end}-th bit (exclusive) from
4923 an exact integer @var{n}, where @var{start} < @var{end}.
4924 @c JP
4925 整数@var{n}の@var{start}ビット目(含む)から@var{end}ビット目(含まない)までを
4926 取り出した数値を返します。@var{start} < @var{end} でなければなりません。
4927 @c COMMON
4928 @end defun
4929
4930 @defun copy-bit index n bit
4931 [R7RS bitwise]
4932 @c EN
4933 If @var{bit} is true, sets @var{index}-th bit of an exact integer @var{n}.
4934 If @var{bit} is false, resets @var{index}-th bit of an exact integer @var{n}.
4935 @c JP
4936 @var{bit}が真の値なら、整数@var{n}の@var{index}ビット目をセットした数値を
4937 返します。
4938 @var{bit}が偽の値なら、整数@var{n}の@var{index}ビット目をリセットした数値を
4939 返します。
4940 @c COMMON
4941 @end defun
4942
4943 @defun copy-bit-field n from start end
4944 [SRFI-60]
4945 @c EN
4946 Returns an exact integer, each bit of which is the same as
4947 @var{n} except the @var{start}-th bit (inclusive) to @var{end}-th
4948 bit (exclusive), which is a copy of the lower
4949 @code{(@var{end}-@var{start})}-th bits of an exact
4950 integer @var{from}.
4951 @c JP
4952 正確な整数を返します。この整数の各ビットは@var{start}番目のビット(この
4953 ビットを含む)から@var{end}番目のビット(このビットは含まない)の部分以外
4954 は@var{n}と同じで、この区間のビットは、正確な数@var{from}の下位
4955 @code{(@var{end}-@var{start})}ビットのコピーです。
4956 @c COMMON
4957
4958 @example
4959 (number->string (copy-bit-field #b10000000 -1 1 5) 2)
4960 @result{} "10011110"
4961
4962 (number->string (copy-bit-field #b10000000 #b010101010 1 7) 2)
4963 @result{} "11010100"
4964 @end example
4965
4966 @c EN
4967 Note: The API of this procedure was originally taken from SLIB,
4968 and at that time,
4969 the argument order was @code{(copy-bit-field n start end from)}.
4970 During the discussion of SRFI-60 the argument order was changed
4971 for the consistency, and the new versions of SLIB followed it.
4972 We didn't realize the change until recently - before 0.9.4,
4973 @emph{this procedure had the old argument order}. Code that is using
4974 this procedure needs to be fixed. If you need your code to work
4975 with both versions of Gauche, have the following definition
4976 in your code.
4977 @c JP
4978 註:この手続きのAPIはSLIBから採られましたが、採用当時の引数の順序は
4979 @code{(copy-bit-field n start end from)} でした。SRFI-60の
4980 議論中に、一貫性のために引数順が変更され、SLIBの新しいバージョンも
4981 それに追従しています。Gaucheではこの引数順の変更に最近まで気づいていなかったため、
4982 0.9.4以前のバージョンでは@code{copy-bit-field}が古い引数順で定義されています。
4983 この手続きを使っていたコードは0.9.4以降のGaucheで使う際に修正しなければなりません。
4984 もしどちらのバージョンのGaucheでも動かす必要がある場合は、
4985 回避策として@code{copy-bit-field}の定義を自前で持つのが良いでしょう。
4986 @c COMMON
4987
4988 @example
4989 (define (copy-bit-field to from start end)
4990 (if (< start end)
4991 (let1 mask (- (ash 1 (- end start)) 1)
4992 (logior (logand to (lognot (ash mask start)))
4993 (ash (logand from mask) start)))
4994 from))
4995 @end example
4996
4997 @end defun
4998
4999 @defun logcount n
5000 [SRFI-60]
5001 @c EN
5002 If @var{n} is positive, returns the number of @code{1}'s in the
5003 bits of @var{n}. If @var{n} is negative,
5004 returns the number of @code{0}'s in the bits of 2's complement
5005 representation of @var{n}.
5006 @c JP
5007 @var{n}が正なら、@var{n}のビットのうち@code{1}の個数を返します。@var{n}
5008 が負なら、@var{n}の2に関する補数のビットのうち@code{0}の個数を返します。
5009 @c COMMON
5010
5011 @c EN
5012 @example
5013 (logcount 0) @result{} 0
5014 (logcount #b0010) @result{} 1
5015 (logcount #b0110) @result{} 2
5016 (logcount #b1111) @result{} 4
5017
5018 (logcount #b-0001) @result{} 0 ;; 2's complement: ....111111
5019 (logcount #b-0010) @result{} 1 ;; 2's complement: ....111110
5020 (logcount #b-0011) @result{} 1 ;; 2's complement: ....111101
5021 (logcount #b-0100) @result{} 2 ;; 2's complement: ....111100
5022 @end example
5023 @c JP
5024 @example
5025 (logcount 0) @result{} 0
5026 (logcount #b0010) @result{} 1
5027 (logcount #b0110) @result{} 2
5028 (logcount #b1111) @result{} 4
5029
5030 (logcount #b-0001) @result{} 0 ;; 2の補数: ....111111
5031 (logcount #b-0010) @result{} 1 ;; 2の補数: ....111110
5032 (logcount #b-0011) @result{} 1 ;; 2の補数: ....111101
5033 (logcount #b-0100) @result{} 2 ;; 2の補数: ....111100
5034 @end example
5035 @c COMMON
5036 @end defun
5037
5038 @defun integer-length n
5039 [R7RS bitwise]
5040 @c EN
5041 Returns the minimum number of bits required to represent an
5042 exact integer @var{n}. Negative integer is assumed to be in
5043 2's complement form. A sign bit is not considered.
5044 @c JP
5045 正確な整数@var{n}を表現するのに必要な最小ビット数を返します。負の数は2
5046 の補数で表現されるものと仮定しています。符号用のビットは考慮しません。
5047 @c COMMON
5048
5049 @example
5050 (integer-length 255) @result{} 8
5051 (integer-length 256) @result{} 9
5052
5053 (integer-length -256) @result{} 8
5054 (integer-length -257) @result{} 9
5055 @end example
5056 @end defun
5057
5058 @defun twos-exponent n
5059 @c EN
5060 If @var{n} is a power of two, that is, @code{(expt 2 k)} and @code{k >= 0},
5061 then returns @code{k}. Returns @code{#f} if @var{n} is not a power of two.
5062 @c JP
5063 @var{n}が2の冪乗@code{(expt 2 k)} (@code{k >= 0}) ならその冪 @code{k} を、
5064 そうでなければ@code{#f}を返します。
5065 @c COMMON
5066 @end defun
5067
5068 @defun twos-exponent-factor n
5069 @c EN
5070 Returns maximum @var{k} such that @code{(expt 2 k)} is a factor of @var{n}.
5071 In other words, returns the number of consecutive zero bits from LSB
5072 of @var{n}. When @var{n} is zero, we return @code{-1} for the
5073 consistency of the following equivalent expression.
5074 @c JP
5075 @code{(expt 2 k)}が@var{n}の約数であるような最大の@var{k}を返します。
5076 言い換えれば、@var{n}のLSBから連続するゼロビットの数を返します。
5077 ただし@var{n}がゼロの場合は、下の等価式との一貫性から@code{-1}が返されます。
5078 @c COMMON
5079
5080 @c EN
5081 This can be calculated by the following expression; this procedure
5082 is for speed to save creating intermediate numbers when @var{n} is bignum.
5083 @c JP
5084 これは次の式でも計算できますが、この手続きは@var{n}がbignumの場合にも
5085 中間結果を作らないので若干速いです。
5086 @c COMMON
5087 @example
5088 (- (integer-length (logxor n (- n 1))) 1)
5089 @end example
5090
5091 @c EN
5092 This procedure is also equivalent to SRFI-60's @code{log2-binary-factors} and
5093 @code{first-set-bit} (@pxref{Integers as bits}).
5094 @c JP
5095 この手続きはまた、SRFI-60の@code{log2-binary-factors}および
5096 @code{first-set-bit}と等価です(@ref{Integers as bits}参照)。
5097 @c COMMON
5098 @end defun
5099
5100 @node Endianness, , Basic bitwise operations, Numbers
5101 @subsection Endianness
5102 @c NODE エンディアンネス
5103
5104 @c EN
5105 In the Scheme world you rarely need to know about how the numbers
5106 are represented inside the machine. However, it matters
5107 when you have to exchange data to/from the outer world in
5108 binary representation.
5109 @c JP
5110 Schemeの世界では、数値がマシン上でどのように表現されているかを気にする
5111 必要はほとんどありません。しかし、外の世界とバイナリ表現でデータを
5112 やりとりする場合はそれが問題になります。
5113 @c COMMON
5114
5115 @c EN
5116 Gauche's binary I/O procedures, such as in
5117 the @code{binary.io} module (@pxref{Binary I/O}) and
5118 @code{write-uvector}/@code{read-uvector!}
5119 (@pxref{Uniform vectors}), take optional @var{endian} argument
5120 to specify the endianness.
5121 @c JP
5122 @code{binary.io}モジュール(@ref{Binary I/O}参照)や
5123 @code{write-uvector}/@code{read-uvector!}(@ref{Uniform vectors}参照)
5124 等、Gaucheのバイナリ入出力手続きはバイトオーダーを指定する
5125 省略可能な@var{endian}引数を取ります。
5126 @c COMMON
5127
5128 @c EN
5129 Currently Gauche recognizes the following endiannesses.
5130 @c JP
5131 エンディアンの指定には次のシンボルを使います。
5132 @c COMMON
5133
5134 @table @code
5135 @item big-endian
5136 @itemx big
5137 @c EN
5138 Big-endian. With this endianness, a 32-bit integer @code{#x12345678}
5139 will be written out as an octet sequence @code{#x12 #x34 #x56 #x78}.
5140
5141 Gauche has been using @code{big-endian}, but @code{scheme.bytevector}
5142 incorporated in R7RS uses @code{big}, so we recognize both.
5143 @c JP
5144 ビッグエンディアン。32ビット整数値@code{#x12345678}は@code{#x12 #x34 #x56 #x78}
5145 のようなバイトシーケンスとして出力されます。
5146
5147 Gaucheはずっと@code{big-endian}を使ってきましたが、
5148 R7RS-largeに取り入れられた@code{scheme.bytevector}が@code{big}を使うので、
5149 両方認識するようになっています。
5150 @c COMMON
5151 @item little-endian
5152 @itemx little
5153 @c EN
5154 Little-endian. With this endianness, a 32-bit integer @code{#x12345678}
5155 is written out as an octet sequence @code{#x78 #x56 #x34 #x12}.
5156
5157 Gauche has been using @code{little-endian}, but @code{scheme.bytevector}
5158 incorporated in R7RS uses @code{little}, so we recognize both.
5159 @c JP
5160 リトルエンディアン。32ビット整数値@code{#x12345678}は@code{#x78 #x56 #x34 #x12}
5161 のようなバイトシーケンスとして出力されます。
5162
5163 Gaucheはずっと@code{little-endian}を使ってきましたが、
5164 R7RS-largeに取り入れられた@code{scheme.bytevector}が@code{little}を使うので、
5165 両方認識するようになっています。
5166 @c COMMON
5167 @item arm-little-endian
5168 @c EN
5169 This is a variation of @code{little-endian}, and used in ARM
5170 processors in some specific modes. It works just like @code{little-endian},
5171 except reading/writing double-precision floating point number (@code{f64}),
5172 which is written as two little-endian 32bit words ordered by big-endian
5173 (e.g. If machine register's representation is @code{#x0102030405060708},
5174 it is written as @code{#x04 #x03 #x02 #x01 #x08 #x07 #x06 #x05}.
5175 @c JP
5176 これは@code{little-endian}のバリエーションで、ARMプロセッサの
5177 特定のモードで使われるものです。倍精度浮動小数点数以外は@code{little-endian}
5178 と同様に動作します。倍精度浮動小数点数については、ふたつのリトルエンディアンワードが
5179 ビッグエンディアンの順で書き出されます (例えばマシンレジスタ上でのビットパターンが
5180 @code{#x0102030405060708}の場合、出力は
5181 @code{#x04 #x03 #x02 #x01 #x08 #x07 #x06 #x05}となります)。
5182 @c COMMON
5183 @end table
5184
5185 @c EN
5186 When the @var{endian} argument is omitted, those procedures
5187 use the parameter @code{default-endian}:
5188 @c JP
5189 @var{endian}引数が省略された場合は、これらの手続きはパラメータ@code{default-endian}の
5190 値を使います。
5191 @c COMMON
5192
5193 @deffn {Parameter} default-endian
5194 @c EN
5195 This is a dynamic parameter (@pxref{Parameters}) to specify
5196 the endianness the binary I/O routines use when its @var{endian}
5197 argument is omitted. The initial value of this parameter is
5198 the system's native endianness.
5199 @c JP
5200 これは、バイナリ入出力ルーチンで@var{endian}指定が省略された場合に
5201 共通して使われるエンディアンを指定する動的パラメータです
5202 (@ref{Parameters}参照)。
5203 このパラメータの初期値はシステムのネイティブエンディアンです。
5204 @c COMMON
5205 @end deffn
5206
5207 @c EN
5208 The system's native endianness can be queried with the following
5209 procedure:
5210 @c JP
5211 システムのネイティブエンディアンは次の手続きで得られます。
5212 @c COMMON
5213
5214 @defun native-endian
5215 @c EN
5216 Returns a symbol representing the system's endianness.
5217 @c JP
5218 システムのエンディアンを示すシンボルを返します。
5219 @c COMMON
5220 @end defun
5221
5222
5223 @c ----------------------------------------------------------------------
5224 @node Booleans, Undefined values, Numbers, Core library
5225 @section Booleans
5226 @c NODE 論理値
5227
5228 @deftp {Builtin Class} <boolean>
5229 @clindex boolean
5230 @c EN
5231 A boolean class. Only @code{#t} and @code{#f} belong to this class.
5232 @c JP
5233 論理値のクラスです。@code{#t}と@code{#f}のみがこのクラスのインスタンスです。
5234 @c COMMON
5235 @end deftp
5236
5237 @defun not obj
5238 [R7RS base]
5239 @c EN
5240 Returns @code{#t} if and only if @var{obj} is @code{#f},
5241 and returns @code{#f} otherwise.
5242 @c JP
5243 @var{obj}が@code{#f}の時のみ@code{#t}を返し、それ以外の場合は@code{#f}を
5244 返します。
5245 @c COMMON
5246 @end defun
5247
5248 @defun boolean? obj
5249 [R7RS base]
5250 @c EN
5251 Returns @code{#t} if @var{obj} is a boolean value.
5252 @c JP
5253 @var{obj}が論理値である場合に@code{#t}を返します。
5254 @c COMMON
5255 @end defun
5256
5257 @defun boolean obj
5258 [SRFI-235]
5259 @c EN
5260 Returns @code{#f} iff @var{obj} is @code{#f}, and returns @code{#t}
5261 otherwise. Convenient to coerce a value to boolean.
5262 @c JP
5263 @var{obj}が@code{#f}であるとき@code{#f}を返し、それ以外の場合は@code{#t}を
5264 返します。値を論理値に変換したい場合に便利です。
5265 @c COMMON
5266 @end defun
5267
5268 @defun boolean=? a b c @dots{}
5269 [R7RS base]
5270 @c EN
5271 Every argument must be a boolean value. Returns @code{#t} iff all
5272 values are the same, @code{#f} otherwise.
5273 @c JP
5274 全ての引数は論理値でなければなりません。全ての引数が等しい場合に
5275 @code{#t}が、そうでなければ@code{#f}が返ります。
5276 @c COMMON
5277 @end defun
5278
5279 @c ----------------------------------------------------------------------
5280 @node Undefined values, Pairs and lists, Booleans, Core library
5281 @section Undefined values
5282 @c NODE 未定義値
5283
5284 @c EN
5285 While working with Gauche, sometimes you encounter
5286 a value printed as @code{#<undef>}, an @emph{undefined} value.
5287 @c JP
5288 Gaucheで作業していると、しばしば未定義値 @code{#<undef>}
5289 に出会うことがあるでしょう。
5290 @c COMMON
5291
5292 @example
5293 gosh> (if #f #t)
5294 #<undef>
5295 @end example
5296
5297 @c EN
5298 It is a value used as a filler where the actual value doesn't matter,
5299 or there's no other suitable value, or the binding hasn't been calculated.
5300 @c JP
5301 この値は、値そのものに意味が無いこと、
5302 ほかにふさわしい値が無いこと、あるいは束縛する値がまだ計算されていないことを示します。
5303 @c COMMON
5304
5305 @c EN
5306 Do not confuse undefined values with unbound variables;
5307 A variable can be bound to @code{#<undef>}, for it is just
5308 an ordinary first-class value. On the other hand, an
5309 unbound variable means there's no value associated with the variable.
5310 @c JP
5311 未定義値と未束縛の変数を混同しないようにしてください。
5312 @code{#<undef>}は通常の第一級の値であり、変数に束縛しておくこともできます。
5313 未束縛の変数は文字通り、変数が束縛されていない、すなわち値を持たないことを意味します。
5314 @c COMMON
5315
5316 @c EN
5317 However, @code{#<undef>} may be used in certain
5318 occasions to indicate that a value is not provided for
5319 the variable. For example,
5320 the toplevel variable can be bound to @code{#<undef>} if it is
5321 defined by @code{(define variable)} form (@pxref{Definitions}).
5322 An optional procedure parameter
5323 without default value is bound to @code{#<undef>} if an
5324 actual argument is not given (@pxref{Making procedures}).
5325
5326 Note that it cannot be distinguished from the case
5327 a value is actually provided, and the value just happens
5328 to be @code{#<undef>}. If you get an @code{#<undef>},
5329 you can say at most is that the value doesn't matter.
5330 You shouldn't let it carry too much meanings.
5331 @c JP
5332 しかし、場合によっては、変数に特定の値が提供されていないことを
5333 示すのに@code{#<undef>}が使われることもあります。
5334 例えば、トップレベル変数は、@code{(define variable)}の形式で定義された場合に
5335 @code{#<undef>}に束縛されます(@ref{Definitions}参照)。
5336 また、既定値をもたない省略可能引数に実引数が提供されなかった
5337 場合、引数の値は@code{#<undef>}となります (@ref{Making procedures}参照)。
5338
5339 これは実際に@code{#<undef>}が初期値として、あるいは引数として渡された場合と区別がつかない
5340 ことに注意してください。@code{#<undef>}を受け取ってわかることは、
5341 せいぜいその値にたいした意味がないということくらいです。
5342 @code{#<undef>}に大きな意味を持たせすぎないようにしましょう。
5343 @c COMMON
5344
5345 @c EN
5346 The @code{#<undef>} value is counted as true value in generalized
5347 boolean context,
5348 since it is not @code{#f}. However, branching based on @code{#<undef>}
5349 is dangerous---a procedure that is defined to return unspecified value
5350 may merely returning @code{#<undef>} as a provisional value; it will
5351 change the return value in future. Since the return value isn't specified,
5352 no one should be using it. The code that tests such result value as
5353 a generalized boolean may break if the procedure changes the return value.
5354
5355 In fact, we've found that there are quite a few code that accidentally tests
5356 @code{#<undef>} return value in conditionals. They can be seeds
5357 for future bugs, so we warn when @code{#<undef>} value
5358 is used in the test of branches. You can suppress the warning with
5359 setting the environment variable @code{GAUCHE_ALLOW_UNDEFINED_TEST}.
5360
5361 One typical case of such accidental use of @code{#<undef>} branching
5362 is in @code{and-let*}; the following code assumes @code{display} always return
5363 @code{#<undef>}, which is counted as a true value, and expects the control
5364 to proceeed to the next clause. It'll break if @code{display} ever changes
5365 so that it may return @code{#f} in some cases.
5366 @c JP
5367 @code{#<undef>}は一般化された真偽値としては真の値とみなされます
5368 (偽になるのは@code{#f}のみですから)。
5369 しかし、@code{#<undef>}の値を見て分岐するコードは危険です。
5370 というのも、戻り値が規定されていない手続きが暫定的に@code{#<undef>}を返している
5371 場合が良くあるからです。でも、それは将来変更されるかもしれません。
5372 戻り値が規定されていない以上、戻り値に依存するコードは無いはずだからです。
5373 もしうっかり、その戻り値に基づいて分岐しているコードがあると、変更があったときに
5374 壊れてしまいます。
5375
5376 実のところ、@code{#<undef>}に依存して分岐しているコードが結構多いことがわかりました。
5377 これは将来のバグの芽となるので、@code{#<undef>}が分岐テストに現れた場合には
5378 警告が出されます。この警告をオフにするには
5379 環境変数@code{GAUCHE_ALLOW_UNDEFINED_TEST}をセットしてください。
5380
5381 @code{#<undef>}をうっかり分岐テストに使ってしまう良くあるパターンは、
5382 @code{and-let*}です。次のコードでは、@code{display}がテスト節に現れていますが、
5383 このコードは@code{display}が常に@code{#<undef>}を返しそれが真の値であることから
5384 次のテスト節に進むことを期待しています。けれども、@code{display}が場合によっては@code{#f}を
5385 返すように変更されたら、このコードは壊れてしまいます。
5386 @c COMMON
5387
5388 @example
5389 (and-let* ([var (foo x y z)]
5390 [ (display var) ] ;; branch on #<undef>
5391 [baz (bar var)])
5392 ...)
5393 @end example
5394
5395 @c EN
5396 Being said that, there are a couple of procedures
5397 to deal with undefined values.
5398 @c JP
5399 以上の注意を念頭においた上で、未定義値を扱うには
5400 次の手続きが利用できます。
5401 @c COMMON
5402
5403 @defun undefined? obj
5404 @c EN
5405 Returns @code{#t} iff @var{obj} is an undefined value.
5406 @c JP
5407 @var{obj}が未定義値である場合に限り@code{#t}を返します。
5408 @c COMMON
5409 @end defun
5410
5411 @defun undefined
5412 @c EN
5413 Returns an undefined value.
5414 @c JP
5415 未定義値を返します。
5416 @c COMMON
5417 @end defun
5418
5419 @c ----------------------------------------------------------------------
5420 @node Pairs and lists, Symbols, Undefined values, Core library
5421 @section Pairs and lists
5422 @c NODE ペアとリスト
5423
5424 @c EN
5425 Pairs and lists are one of the most fundamental data structure in Scheme.
5426 Gauche core provides all standard list procedures, plus some useful
5427 procedures that are commonly supported in lots of implementations.
5428 If they are not enough, you can find more procedures in the modules
5429 described in @ref{R7RS lists} and
5430 @ref{Combination library}.
5431 See also @ref{Collection framework} and
5432 @ref{Sequence framework} for generic collection/sequence
5433 operations.
5434 @c JP
5435 ペアとリストはSchemeにおける最も基本的なデータ構造のひとつです。
5436 Gaucheのコアは全ての標準のリスト手続きと、多くのScheme実装に見られる
5437 便利な手続きのいくつかを提供します。それらで足りない場合は
5438 さらに多くの手続きが@ref{R7RS lists}、
5439 @ref{Combination library}
5440 といったモジュールで提供されています。
5441 また、リストに限らないジェネリックなシーケンス/コレクションの操作が
5442 @ref{Collection framework}と
5443 @ref{Sequence framework}で提供されています。
5444 @c COMMON
5445
5446 @menu
5447 * Pair and null class::
5448 * Mutable and immutable pairs::
5449 * List predicates::
5450 * List constructors::
5451 * List accessors and modifiers::
5452 * Walking over lists::
5453 * Other list procedures::
5454 * Association lists::
5455 * Extended pairs and pair attributes::
5456 @end menu
5457
5458 @node Pair and null class, Mutable and immutable pairs, Pairs and lists, Pairs and lists
5459 @subsection Pair and null class
5460 @c NODE pairクラスとnullクラス
5461
5462 @deftp {Builtin Class} <list>
5463 @clindex list
5464 @c EN
5465 An abstract class represents lists. A parent class of @code{<null>}
5466 and @code{<pair>}. Inherits @code{<sequence>}.
5467
5468 Note that a circular list is also an instance of the @code{<list>} class,
5469 while @code{list?} returns false on the circular lists and
5470 dotted lists.
5471 @c JP
5472 リストを表す抽象クラスで、クラス@code{<null>}とクラス@code{<pair>}の親クラスです。
5473 クラス@code{<sequence>}を継承します。
5474
5475 循環リストやドットリストも@code{<list>}クラスのインスタンスですが、
5476 @code{list?}は偽の値を返すことに注意して下さい。
5477 @c COMMON
5478 @lisp
5479 (use srfi.1)
5480 (list? (circular-list 1 2)) @result{} #f
5481 (is-a? (circular-list 1 2) <list>) @result{} #t
5482 @end lisp
5483 @end deftp
5484
5485 @deftp {Builtin Class} <null>
5486 @clindex null
5487 @c EN
5488 A class of empty list. @code{()} is the only instance.
5489 @c JP
5490 空リストのクラスです。@code{()}がこのクラスの唯一のインスタンスです。
5491 @c COMMON
5492 @end deftp
5493
5494 @deftp {Builtin Class} <pair>
5495 @clindex pair
5496 @c EN
5497 A class of pairs.
5498 @c JP
5499 ペアのクラスです。
5500 @c COMMON
5501 @end deftp
5502
5503 @node Mutable and immutable pairs, List predicates, Pair and null class, Pairs and lists
5504 @subsection Mutable and immutable pairs
5505 @c NODE 変更可能なペアと変更不可なペア
5506
5507 @c EN
5508 A pair may be either mutable or immutable. You can desctructively
5509 modify mutable pairs with @code{set-car!}, @code{set-cdr!}, or other
5510 destructive procedures (usually they have @code{!} at the end).
5511 An error is signaled when you try to modify an immutable pair.
5512 @c JP
5513 ペアには変更可能なものと変更不可なものがあります。
5514 変更可能なペアは、@code{set-car!}や@code{set-cdr!}等の破壊的変更手続き
5515 (通常、名前の最後に@code{!}がついています)で変更することが可能です。
5516 変更不可なペアを変更しようとするとエラーが報告されます。
5517 @c COMMON
5518
5519 @c EN
5520 In Gauche, both type of pairs can be treated the same unless you try
5521 to modify them. Both satisfies the predicate @code{pair?}. If you
5522 need to test specifically if a pair is immutable, use @code{ipair?}
5523 (@pxref{List predicates}).
5524 The traditional constructor @code{cons} creates a mutable pair; you
5525 can create an immutable pair with @code{ipair} (@pxref{List constructors}).
5526 More procedures that use immutable pairs are defined in
5527 R7RS-large @code{scheme.ilist} module (@pxref{R7RS immutable lists}).
5528 @c JP
5529 Gaucheでは、変更しようとしない限り、どちらのペアも全く同じように振る舞います。
5530 @code{pair?}にはどちらも真を返します。ペアが変更不可であることを調べたければ
5531 @code{ipair?}が使えます(@ref{List predicates}参照)。
5532 伝統的なコンストラクタ@code{cons}は変更可能なペアを作ります。
5533 変更不可なペアを作るには@code{ipair}を使ってください (@ref{List constructors}参照)。
5534 変更不可なペアを特に扱う手続きは、R7RS-largeの@code{scheme.ilist}モジュールに
5535 定義されています (@ref{R7RS immutable lists}参照)。
5536 @c COMMON
5537
5538 @c EN
5539 Note that quoted literals are immutable.
5540 Old versions of Gauche wasn't supported immutable pairs and quoted literal lists
5541 were mutable. If your code accidentally mutate such pairs, you'll get an
5542 error. If you need to run such code without tracking down the error,
5543 you can define the environment variable
5544 @code{GAUCHE_MUTABLE_LITERALS}.
5545 @c JP
5546 クオートされたリテラルは変更不可です。
5547 ただ、古いバージョンのGaucheは変更不可なペアを持っておらず、クオートされたリテラルリストも
5548 変更可能でした。その頃に書かれたコードでうっかりリテラルを変更していたら、
5549 現在のGaucheではエラーになってしまうでしょう。
5550 問題を修正せずにどうしても古いコードのまま走らせたい場合は、環境変数
5551 @code{GAUCHE_MUTABLE_LITERALS}を定義してください。
5552 @c COMMON
5553
5554
5555 @node List predicates, List constructors, Mutable and immutable pairs, Pairs and lists
5556 @subsection List predicates
5557 @c NODE リストに関する述語
5558
5559 @defun pair? obj
5560 [R7RS base]
5561 @c EN
5562 Returns @code{#t} if @var{obj} is a pair, @code{#f} otherwise.
5563 @c JP
5564 @var{obj}がペアなら@code{#t}を、そうでなければ@code{#f}を返します。
5565 @c COMMON
5566 @end defun
5567
5568 @defun ipair? obj
5569 [R7RS ilist]
5570 @c EN
5571 Returns @code{#t} iff @var{obj} is an immutable pair, @code{#f} otherwise.
5572
5573 An immutable pair is indistinguishable from a mutable pair except using
5574 this predicate, or when you attempt to modify it.
5575 @xref{Mutable and immutable pairs}.
5576 @c JP
5577 @var{obj}が変更不可なペアなら@code{#t}を、そうでなければ@code{#f}を返します。
5578
5579 変更不可なペアは、この述語を使うか、あるいはそのペアを変更しようとした場合を除いては、
5580 変更可能なペアと全く同じように動作します。
5581 詳しくは@ref{Mutable and immutable pairs}参照。
5582 @c COMMON
5583 @end defun
5584
5585 @defun null? obj
5586 [R7RS base]
5587 @c EN
5588 Returns @code{#t} if @var{obj} is an empty list, @code{#f} otherwise.
5589 @c JP
5590 @var{obj}が空リストなら@code{#t}を、そうでなければ@code{#f}を返します。
5591 @c COMMON
5592 @end defun
5593
5594 @defun null-list? obj
5595 [R7RS list]
5596 @c EN
5597 Returns @code{#t} if @var{obj} is an empty list,
5598 @code{#f} if @var{obj} is a pair. If @var{obj} is neither
5599 a pair nor an empty list, an error is signaled.
5600
5601 This can be used instead of @code{null?} to check the end-of-list
5602 condition when you want to be more picky about non-proper lists.
5603 @c JP
5604 @var{obj} が空リストなら@code{#t}を、ペアなら@code{#f}を返し、
5605 それ以外のときはエラーを報告します。
5606
5607 リスト終了条件を検査する時に、正しいリスト以外を除外したい場合に
5608 @code{null?}の代わりに使えます。
5609 @c COMMON
5610 @end defun
5611
5612 @defun list? obj
5613 [R7RS base]
5614 @c EN
5615 Returns @code{#t} if @var{obj} is a proper list, @code{#f} otherwise.
5616 This function returns @code{#f} if @var{obj} is a dotted or circular list.
5617
5618 See also @code{proper-list?}, @code{circular-list?} and
5619 @code{dotted-list?} below.
5620 @c JP
5621 @var{obj}が正しいリストなら@code{#t}を、そうでなければ@code{#f}を返します。
5622 この手続きは@var{obj}がドットリストや循環リストなら@code{#f}を返します。
5623
5624 下に説明する、
5625 @code{proper-list?}、@code{circular-list?}、@code{dotted-list?}
5626 といった手続きも参照してください。
5627 @c COMMON
5628 @end defun
5629
5630
5631 @defun proper-list? x
5632 [R7RS list]
5633 @c EN
5634 Returns @code{#t} fif x is a proper list, that is, a finite list
5635 terminated by @code{()}.
5636 @c JP
5637 @var{x} が真性リスト、つまり@code{()}で終端された有限のリストであれば
5638 @code{#t} を、そうでなければ@code{#f}を返します。
5639 @c COMMON
5640 @end defun
5641
5642 @defun circular-list? x
5643 [R7RS list]
5644 @c EN
5645 Returns @code{#t} if x is a circular list. A list is circular if
5646 you follow @code{cdr} of the pairs you'll eventually get to a pair
5647 you already visited. It doesn't necessary that the head of the list
5648 @var{x} is a part of the circle. A list isn't circular by the
5649 cycle that involves @var{car} of the paris.
5650 @c JP
5651 @var{x} が循環リストであれば @code{#t} を返します。リストを@code{cdr}方向に
5652 辿って行って、既に訪れたペアに出会ったら、それは循環リストです。
5653 リストの頭 (@code{x}) が循環に含まれている必要はありません。
5654 また、@code{car}方向への循環があってもそれだけでは循環リストとはみなされません。
5655 @c COMMON
5656 @end defun
5657
5658 @defun dotted-list? x
5659 [R7RS list]
5660 @c EN
5661 Returns @code{#t} if x is a finite, non-nil-terminated list.
5662 This includes non-pair, non-() values (e.g. symbols, numbers),
5663 which are considered to be dotted lists of length 0.
5664 @c JP
5665 @var{x} が有限の大きさで、空リストで終端していないリストなら
5666 @code{#t} を返します。これには、ペアではなく、空リストもない値(たとえば
5667 シンボルや数値)のような長さ0のドットリストと考えられるものを含みます。
5668 @c COMMON
5669 @end defun
5670
5671
5672 @node List constructors, List accessors and modifiers, List predicates, Pairs and lists
5673 @subsection List constructors
5674 @c NODE リストの作成
5675
5676 @defun cons obj1 obj2
5677 [R7RS base]
5678 @c EN
5679 Constructs a mutable pair of @var{obj1} and @var{obj2} and returns it.
5680 @c JP
5681 @var{obj1}と@var{obj2}の変更可能なペアを作成して返します。
5682 @c COMMON
5683 @lisp
5684 (cons 'a 'b) @result{} (a . b)
5685 @end lisp
5686 @end defun
5687
5688 @defun ipair obj1 obj2
5689 [R7RS ilist]
5690 @c EN
5691 Constructs an immutable pair of @var{obj1} and @var{obj2} and returns it.
5692 @c JP
5693 @var{obj1}と@var{obj2}の変更不可なペアを作成して返します。
5694 @c COMMON
5695 @lisp
5696 (ipair 'a 'b) @result{} (a . b)
5697 @end lisp
5698 @end defun
5699
5700 @defun make-list len :optional fill
5701 [R7RS base]
5702 @c EN
5703 Makes a proper list of length @var{len}. If optional argument
5704 @var{fill} is provided, each element is initialized by it. Otherwise
5705 each element is undefined.
5706 @c JP
5707 長さ@var{len}の正規のリストを返します。引数@var{fill}が与えられていれば、各要素は
5708 @var{fill}になります。そうでなければ各要素の値は不定です。
5709 @c COMMON
5710
5711 @lisp
5712 (make-list 5 #t) @result{} (#t #t #t #t #t)
5713 @end lisp
5714 @end defun
5715
5716 @defun list obj @dots{}
5717 [R7RS base]
5718 @c EN
5719 Makes a list, whose elements are @var{obj} @dots{}.
5720 @c JP
5721 要素が@var{obj} @dots{}であるリストを作成します。
5722 @c COMMON
5723 @lisp
5724 (list 1 2 3) @result{} (1 2 3)
5725 (list) @result{} ()
5726 @end lisp
5727 @end defun
5728
5729 @defun ilist obj @dots{}
5730 [R7RS ilist]
5731 @c EN
5732 Makes a list, whose elements are @var{obj} @dots{},
5733 and which consists of immutable pairs.
5734 @c JP
5735 要素が@var{obj} @dots{}であり、変更不可なペアで作られたリストを作成します。
5736 @c COMMON
5737 @lisp
5738 (ilist 1 2 3) @result{} (1 2 3)
5739 (ilist) @result{} ()
5740
5741 (list-set! (ilist 1 2 3) 1 'a)
5742 @result{} ERROR: Attempt to modify an immutable pair: (2 3)
5743 @end lisp
5744 @end defun
5745
5746 @defun list* obj1 obj2 @dots{}
5747 @defunx cons* obj1 obj2 @dots{}
5748 [R7RS list]
5749 @c EN
5750 Like @code{list}, but the last argument becomes cdr of the last pair.
5751 Two procedures are exactly the same. Gauche originally had @code{list*},
5752 and SRFI-1 (R7RS @code{(scheme list)})defines @code{cons*}.
5753 @c JP
5754 @code{list}とほぼ同じですが、最後の引数が作成されるリストの最後のペアのcdrになります。
5755 二つの手続きは全く同じです。Gaucheはもともと@code{list*}を持っていましたが、
5756 SRFI-1 (R7RS @code{(scheme list)}) が@code{cons*}という名前を定義しました。
5757 @c COMMON
5758 @lisp
5759 (list* 1 2 3) @result{} (1 2 . 3)
5760 (list* 1) @result{} 1
5761 @end lisp
5762 @end defun
5763
5764 @defun list-copy list
5765 [R7RS base]
5766 @c EN
5767 Shallow copies @var{list}.
5768 If @var{list} is circular, an error is thrown.
5769 (Detecting circular list is Gauche's extension; R7RS allows
5770 the procedure to diverge.)
5771 @c JP
5772 @var{list}の浅いコピーを行います。
5773 @var{list}が循環リストの場合、エラーが投げられます。
5774 (循環リストを検出するのはGaucheの拡張です。
5775 R7RSではこの手続きは停止しなくても良いことになっています。)
5776 @c COMMON
5777 @end defun
5778
5779 @defun iota count :optional (start 0) (step 1)
5780 [R7RS list]
5781 @c EN
5782 Returns a list of @var{count} numbers, starting from @var{start},
5783 increasing by @var{step}. @var{Count} must be a nonnegative
5784 integer. If both @var{start} and @var{step} are exact,
5785 the result is a list of exact numbers; otherwise, it is a list
5786 of inexact numbers.
5787 @c JP
5788 @var{start}から始まり、@var{step}ずつ増加する、
5789 @var{count} 個の要素からなる数値のリストを返します。@var{count}は
5790 非負の整数でなければなりません。@var{start}と@var{step}が
5791 ともに正確数であれば、結果は正確数のリストになります。そうでなければ
5792 結果は非正確数のリストです。
5793 @c COMMON
5794 @example
5795 (iota 5) @result{} (0 1 2 3 4)
5796 (iota 5 1 3/7) @result{} (1 10/7 13/7 16/7 19/7)
5797 (iota 5 0 -0.1) @result{} (0 -0.1 -0.2 -0.3 -0.4)
5798 @end example
5799
5800 @c EN
5801 This creates a list eagerly. If the list is short it is fast
5802 enough, but if you want to count tens of thousands of numbers,
5803 you may want to do so lazily. See @code{liota} (@pxref{Lazy sequences}).
5804 @c JP
5805 この手続きはリストを最後まで作って返します。リストが短ければ
5806 十分速いですが、何万という数をリストにしたければ、遅延リストを使った方が
5807 良いかもしれません。@code{liota}を見てください(@ref{Lazy sequences}参照)。
5808 @c COMMON
5809 @end defun
5810
5811 @defmac cond-list clause @dots{}
5812 @c EN
5813 Construct a list by conditionally adding entries.
5814 Each @var{clause} has a test and expressions. When its test
5815 yields true, the result of associated expression is used to
5816 construct the resulting list. When the
5817 test yields false, nothing is inserted.
5818 @c JP
5819 条件によりエントリを追加することによりリストを構築します。
5820 それぞれの@var{clause}は条件と式を持ちます。
5821 条件が真であれば、関連する式の結果が結果のリストの構築に使われます。
5822 条件が偽であれば、何も挿入されません。
5823 @c COMMON
5824
5825 @c EN
5826 @var{Clause} must be either one of the following form:
5827 @table @code
5828 @item (@var{test} @var{expr} @dots{})
5829 @var{Test} is evaluated, and when it is true,
5830 @var{expr} @dots{} are evaluated, and the return value
5831 becomes a part of the result. If no @var{expr} is given,
5832 the result of @var{test} is used if it is not false.
5833 @item (@var{test} => @var{proc})
5834 @var{Test} is evaluated, and when it is true,
5835 @var{proc} is called with the value, and the return
5836 value is used to construct the result.
5837 @item (@var{test} @@ @var{expr} @dots{})
5838 Like @code{(test expr @dots{})}, except that the result of
5839 the last @var{expr} must be a list, and it is spliced into
5840 the resulting list, like unquote-splicing.
5841 @item (@var{test} => @@ @var{proc})
5842 Like @code{(test => proc)}, except that the result of
5843 @var{proc} must be a list, and and it is spliced into
5844 the resulting list, like unquote-splicing.
5845 @end table
5846 @c JP
5847 @var{clause}は、以下のフォームのうちの1つでなければなりません。
5848 @table @code
5849 @item (@var{test} @var{expr} @dots{})
5850 @var{test}が評価され、それが真ならば@var{expr} @dots{}が評価され、
5851 戻り値が結果の一部となります。@var{expr}が与えられなければ、
5852 @var{test}の結果が偽でなければその結果が使われます。
5853 @item (@var{test} => @var{proc})
5854 @var{test}が評価され、それが真ならば@var{proc}がその値とともに
5855 呼ばれ、その戻り値が結果を構築するために使われます。
5856 @item (@var{test} @@ @var{expr} @dots{})
5857 @code{(test expr @dots{})}のように動作しますが、最後の@var{expr}の
5858 値はリストでなければならず、それは結果のリストに(unquote-splicingのように)
5859 スプライスされます。
5860 @item (@var{test} => @@ @var{proc})
5861 @code{(test => proc)}のように動作しますが、@var{proc}の戻り値
5862 はリストでなければならず、それは結果のリストに(unquote-splicingのように)
5863 スプライスされます。
5864 @end table
5865 @c COMMON
5866
5867 @example
5868 (let ((alist '((x 3) (y -1) (z 6))))
5869 (cond-list ((assoc 'x alist) 'have-x)
5870 ((assoc 'w alist) 'have-w)
5871 ((assoc 'z alist) => cadr)))
5872 @result{} (have-x 6)
5873
5874 (let ((x 2) (y #f) (z 5))
5875 (cond-list (x @@ `(:x ,x))
5876 (y @@ `(:y ,y))
5877 (z @@ `(:z ,z))))
5878 @result{} (:x 2 :z 5)
5879 @end example
5880 @end defmac
5881
5882
5883 @node List accessors and modifiers, Walking over lists, List constructors, Pairs and lists
5884 @subsection List accessors and modifiers
5885 @c NODE リストへのアクセスと変更
5886
5887 @defun car pair
5888 @defunx cdr pair
5889 [R7RS base]
5890 @c EN
5891 Returns car and cdr of @var{pair}, respectively.
5892 @c JP
5893 それぞれ@var{pair}のcarとcdrを返します。
5894 @c COMMON
5895 @end defun
5896
5897 @defun set-car! pair obj
5898 @defunx set-cdr! pair obj
5899 [R7RS base]
5900 @c EN
5901 Modifies car and cdr of @var{pair}, by @var{obj}, respectively.
5902
5903 Note: @code{(setter car)} @equiv{} @code{set-car!}, and
5904 @code{(setter cdr)} @equiv{} @code{set-cdr!}.
5905 @c JP
5906 @var{pair}のcarもしくはcdrを@var{obj}で置き換えます。
5907
5908 注: @code{(setter car)} @equiv{} @code{set-car!} であり、
5909 @code{(setter cdr)} @equiv{} @code{set-cdr!} です。
5910 @c COMMON
5911 @end defun
5912
5913 @defun caar pair
5914 @defunx cadr pair
5915 @findex cdar
5916 @findex cddr
5917 @findex caaar
5918 @findex caadr
5919 @findex cadar
5920 @findex caddr
5921 @findex cdaar
5922 @findex cdadr
5923 @findex cddar
5924 @findex cdddr
5925 @findex caaaar
5926 @findex caaadr
5927 @findex caadar
5928 @findex caaddr
5929 @findex cadaar
5930 @findex cadadr
5931 @findex caddar
5932 @findex cadddr
5933 @findex cdaaar
5934 @findex cdaadr
5935 @findex cdadar
5936 @findex cdaddr
5937 @findex cddaar
5938 @findex cddadr
5939 @dots{}
5940 @end defun
5941 @defun cdddar pair
5942 @defunx cddddr pair
5943 [R7RS base][R7RS cxr]
5944 @c EN
5945 @code{caar} @equiv{} @code{(car (car x))},
5946 @code{cadr} @equiv{} @code{(car (cdr x))}, and so on.
5947
5948 In R7RS, more than two-level of accessors are defined in the
5949 @code{(scheme cxr)} library.
5950
5951 The corresponding setters are also defined.
5952 @c JP
5953 @code{caar} @equiv{} @code{(car (car x))},
5954 @code{cadr} @equiv{} @code{(car (cdr x))}, 等々。
5955
5956 R7RSでは、2レベルよりも深いアクセサは@code{(scheme cxr)}ライブラリに含まれます。
5957
5958 対応するsetterも定義されています。
5959 @c COMMON
5960 @example
5961 (let ((x (list 1 2 3 4 5)))
5962 (set! (caddr x) -1)
5963 x)
5964 @result{} (1 2 -1 4 5)
5965 @end example
5966 @end defun
5967
5968 @defun length list
5969 [R7RS base]
5970 @c EN
5971 Returns the length of a proper list @var{list}.
5972 If @var{list} is a dotted list, an error is signaled.
5973 If @var{list} is a circular list, this function diverges.
5974 @c JP
5975 正規のリスト@var{list}の長さを返します。
5976 @var{list}がドットリストならばエラーが起きます。
5977 @var{list}が循環リストの場合、この関数は無限ループします。
5978 @c COMMON
5979 @end defun
5980
5981 @defun length+ x
5982 [R7RS list]
5983 @c EN
5984 If @var{x} is a proper list, returns its length.
5985 For all other @var{x}, including a circular list,
5986 it returns @code{#f}.
5987
5988 If you want a length of dotted list in terms of the number of pairs,
5989 use @var{num-pairs} below.
5990 @c JP
5991 @var{x} が真性リストなら、その長さを返します。
5992 @var{x} がそうでなければ(たとえ循環リストであっても)
5993 @code{#f} を返します。
5994
5995 ドットリストの「長さ」を、構成するペアの数で知りたい場合は、
5996 下の@code{num-pairs}が使えます。
5997 @c COMMON
5998 @end defun
5999
6000 @defun length=? x k
6001 @defunx length<? x k
6002 @defunx length<=? x k
6003 @defunx length>? x k
6004 @defunx length>=? x k
6005 @c EN
6006 Returns @code{#t} iff @var{x} is a (possibly improper) list whose length is
6007 equal to, less than, less than or equal to, greater than, or greater than
6008 or equal to an exact integer @var{k}, respectively.
6009 This procedure only follows the list up to the @var{k} items, so
6010 it doesn't realize elements of lazy sequence more than
6011 needed (@xref{Lazy sequences}, for the lazy sequences).
6012
6013 Dotted lists and circular lists are allowed. For the dotted list,
6014 the cdr of the last pair isn't counted; that is, a non-pair object
6015 has length 0, and @code{(a . b)} has length 1.
6016 A circular list is treated as if it has infinite length.
6017 @c JP
6018 それぞれ、リスト@var{x}の長さが正確な整数kと等しいか、k未満か、k以下か、kより大きいか、
6019 k以上かの場合に@code{#t}を、そうでなければ@code{#f}を返します。
6020 この関数は@var{k}要素までしかリストを辿らないので、特に@var{x}が遅延シーケンス
6021 (@ref{Lazy sequences}参照)である場合に、必要以上にリストを実体化しなくて済みます。
6022
6023 @var{x}はドットリストや循環リストでも構いません。
6024 ドットリストの長さを数える際には最後のペアのcdrは無視します。
6025 つまり、ペアでないオブジェクトの長さは0で、@code{(a . b)}の長さは1になります。
6026 循環リストは無限の長さを持つとみなします。
6027 @c COMMON
6028
6029 @example
6030 (length<=? '(a b) 2) @result{} #t
6031 (length<=? '(a b) 1) @result{} #f
6032 (length<=? '() 0) @result{} #t
6033
6034 ;; dotted list cases
6035 (length<=? 'a 0) @result{} #t
6036 (length<=? '(a . b) 0) @result{} #f
6037 (length<=? '(a . b) 1) @result{} #t
6038 @end example
6039
6040 @c EN
6041 NB: The name of these procedures might be misleading, for other procedures
6042 with the name @code{something<=?} etc. usually takes objects of the same type.
6043 We don't have any better idea now, unfortunately.
6044 @c JP
6045 註: これらの手続きの名前は混乱を招きやすいかもしれません。@code{something<=?}等の
6046 名前は通常、同じ型のオブジェクト同士の比較に使われるからです。
6047 残念ながら、今のところより良い名前を思いつけていません。
6048 @c COMMON
6049 @end defun
6050
6051 @defun num-pairs lis
6052 @c EN
6053 Returns the number of pairs that consists a (proper, dotted, or circular)
6054 list @var{lis}, in an exact integer.
6055 If @var{lis} is a proper list, it is the same as @code{length}.
6056 @c JP
6057 リスト@var{lis}を構成するペアの数を正確な整数で返します。@var{lis}はドットリストや循環リスト
6058 でも構いません。@var{lis}が正しいリストなら戻り値は@code{length}と同じです。
6059 @c COMMON
6060
6061 @example
6062 (num-pairs '(a b c d e)) @result{} 5
6063 (num-pairs '()) @result{} 0
6064 (num-pairs '(a b c d . e)) @result{} 4
6065 (num-pairs 'a) @result{} 0
6066 (num-pairs '#0=(a b . #0#)) @result{} 2
6067 (num-pairs '(a . #0=(b c . #0#))) @result{} 3
6068 @end example
6069 @end defun
6070
6071 @defun take x i
6072 @defunx drop x i
6073 [R7RS list]
6074 @c EN
6075 @code{take} returns the first i elements of list x.
6076 @code{drop} returns all but the first i elements of list x.
6077 @c JP
6078 @code{take} はリスト @var{x} の最初のi個の要素を返します。
6079 @code{drop} はリスト @var{x} の最初のi個の要素を除いたリストを返します。
6080 @c COMMON
6081 @example
6082 (take '(a b c d e) 2) => (a b)
6083 (drop '(a b c d e) 2) => (c d e)
6084 @end example
6085 @c EN
6086 @var{x} may be any value:
6087 @c JP
6088 @var{x} はあらゆる値をとりえます。
6089 @c COMMON
6090 @example
6091 (take '(1 2 3 . d) 2) => (1 2)
6092 (drop '(1 2 3 . d) 2) => (3 . d)
6093 (drop '(1 2 3 . d) 3) => d
6094 @end example
6095 @c EN
6096 @code{drop} is exactly equivalent to performing @var{i} cdr operations
6097 on @var{x}. The returned value shares a common tail with @var{x}.
6098 On the other hand, take always allocates a new list
6099 for result if the argument is a list of non-zero length.
6100
6101 An error is signaled if @var{i} is past the end of list @var{x}.
6102 See @code{take*} and @code{drop*} below for more tolerant version.
6103
6104 For generic subsequence extraction from any sequence, see @code{subseq}
6105 in @ref{Slicing sequence}.
6106 @c JP
6107 @code{drop} は @var{x} に @var{i} 回 cdr 操作をおこなうのと全く
6108 同じです。返される値は、@var{x} と共通の末尾を共有します。一方、
6109 take は、引数のリストが長さ0でないリストなら必ず新しいリストの
6110 領域を確保します。
6111
6112 @var{i} がリスト @var{x} の終端を超えたらエラーが発生します。
6113 より寛容な手続きについては、下の@code{take*}と@code{drop*}を見てください。
6114
6115 あらゆる並びからの部分並びを抽出する汎用的な方法に関しては、
6116 @ref{Slicing sequence} にある @code{subseq} を参照してください。
6117 @c COMMON
6118 @end defun
6119
6120 @defun take* list k :optional (fill? #f) (padding #f)
6121 @defunx drop* list k
6122 @c EN
6123 More tolerant version of @code{take} and @code{drop}.
6124 They won't raise an error even if @var{k} is larger than the size
6125 of the given list.
6126
6127 If the list is shorter than @var{k} elements,
6128 @code{take*} returns a copy of @var{list}
6129 by default. If @var{fill?} is true, @var{padding} is added
6130 to the result to make its length @var{k}.
6131
6132 On the other hand, @code{drop*} just returns an empty list
6133 when the input list is shorter than @var{k} elements.
6134 @c JP
6135 @code{take}と@code{drop}のより寛容なバージョンです。
6136 これらの手続きは、リストが@code{k}より短くてもエラーを通知しません。
6137
6138 その場合、@code{take*}はデフォルトでは@var{list}のコピーを
6139 返します。もし@var{fill?}が真であれば、足りない要素の部分に
6140 @var{padding}を追加して@var{k}要素にしたリストを返します。
6141
6142 一方、@code{drop*}はリストの長さが不足する場合は単に空リストを返します。
6143 @c COMMON
6144
6145 @example
6146 (take* '(a b c d) 3) @result{} (a b c)
6147 (take* '(a b c d) 6) @result{} (a b c d)
6148 (take* '(a b c d) 6 #t) @result{} (a b c d #f #f)
6149 (take* '(a b c d) 6 #t 'z) @result{} (a b c d z z)
6150 (drop* '(a b c d) 3) @result{} (d)
6151 (drop* '(a b c d) 5) @result{} ()
6152 @end example
6153
6154 @c EN
6155 Note: For generic subsequence extraction from any sequence,
6156 see @code{subseq} in @ref{Slicing sequence}.
6157 @c JP
6158 注意: 一般的な、いかなるシーケンスからのサブシーケンスの抽出については、
6159 @ref{Slicing sequence}の@code{subseq}を見て下さい。
6160 @c COMMON
6161 @end defun
6162
6163 @defun take-right lis k
6164 @defunx drop-right lis k
6165 [R7RS list]
6166 @c EN
6167 @code{take-right} returns the last @var{k} elements of @var{lis}.
6168 @code{drop-right} returns all but the last @var{k} elements of @var{lis}.
6169 @c JP
6170 @code{take-right} は @var{lis} の最後の @var{k}個の要素
6171 からなるリストを返します。
6172 @code{drop-right} は @var{lis} の最後の @var{k}個の要素を
6173 除いたリスト返します。
6174 @c COMMON
6175 @example
6176 (take-right '(a b c d e) 2) => (d e)
6177 (drop-right '(a b c d e) 2) => (a b c)
6178 @end example
6179 @c EN
6180 @var{lis} may be any finite list.
6181 @c JP
6182 @var{lis} は有限リストであればOKです。
6183 @c COMMON
6184 @example
6185 (take-right '(1 2 3 . d) 2) => (2 3 . d)
6186 (drop-right '(1 2 3 . d) 2) => (1)
6187 (take-right '(1 2 3 . d) 0) => d
6188 (drop-right '(1 2 3 . d) 0) => (1 2 3)
6189 @end example
6190 @c EN
6191 @code{take-right}'s return value always shares a common
6192 tail with @var{lis}.
6193 @code{drop-right} always allocates a new list
6194 if the argument is a list of non-zero length.
6195
6196 An error is signaled if @var{k} is larger than the length of @var{lis}.
6197 See @code{take-right*} and @code{drop-right*} below, for more tolerant
6198 version.
6199 @c JP
6200 @code{take-right} の返す値はいつでも @var{lis} の共通の末尾を共有します。
6201 @code{drop-right} は、引数が長さが0でないリストなら、必ず新しいリストの
6202 領域を確保します。
6203
6204 @var{k} がリスト @var{lis} の長さより大きければエラーが発生します。
6205 より寛容なバージョンについては下の@code{take-right*}, @code{drop-right*}を
6206 参照してください。
6207 @c COMMON
6208 @end defun
6209
6210 @defun take-right* list k :optional (fill? #f) (padding #f)
6211 @defunx drop-right* list k
6212 @c EN
6213 Like @code{take*} and @code{drop*}, but counts from right of @var{list}.
6214 If @var{list} is shorter than @var{k} elements, they won't raise
6215 an error. Instead, @code{drop-right*} just returns an empty list,
6216 and @code{take-right*} returns @var{list} itself by default.
6217 If @var{fill?} is true for @code{take-right*},
6218 @var{padding} is added on the left of the result to make its length @var{k}.
6219 The result still shares the @var{list}.
6220 @c JP
6221 @code{take*}及び@code{drop*}と同じですが、@var{list}の右端からカウントします。
6222 これらは@var{list}が@var{k}要素より短い場合にもエラーを通知しません。
6223 @code{drop-right*}はその場合は単に空リストを返します。
6224 @code{take-right*}はその場合はデフォルトで@var{list}そのものを
6225 返しますが、@var{fill?}が真であれば@var{list}の右側に
6226 足りない分だけ@var{padding}を足したものを返します。その場合でも
6227 結果の尾部は@var{list}と共有されます。
6228 @c COMMON
6229 @end defun
6230
6231 @defun take! lis k
6232 @defunx drop-right! lis k
6233 [R7RS list]
6234 @c EN
6235 Linear update variants of @code{take} and @code{drop-right}.
6236 Those procedures may destructively modifies @var{lis}.
6237
6238 If @var{lis} is circular, @code{take!} may return a list
6239 shorter than expected.
6240 @c JP
6241 @code{take} および @code{drop-right} の
6242 その場で更新されるバージョンです。これらの
6243 手続きは @var{lis} を破壊的に変更するかもしれません。
6244
6245 @var{lis} が循環リストなら、@code{take!} は期待されるものより短いリストを返す
6246 可能性があります。
6247 @c COMMON
6248 @end defun
6249
6250 @defun list-tail list k :optional fallback
6251 [R7RS base]
6252 @c EN
6253 Returns @var{k}-th cdr of @var{list}.
6254 @var{list} can be a proper, dotted or circular list.
6255 (If @var{list} is a dotted list, its last @code{cdr} is simply ignored).
6256
6257 If @var{k} is negative or larger than the length of @var{list},
6258 the behavior depends on whether the optional @var{fallback} argument
6259 is given or not. If @var{fallback} is given, it is returned.
6260 Otherwise, an error is signaled.
6261 @c JP
6262 @var{list}の@var{k}番目のcdrを返します。@var{list}は
6263 正規のリストでもドットリストでも循環リストでも構いません。
6264 (@var{list}がドットリストの場合、最後の@code{cdr}は無視されます)。
6265
6266 @var{k}の値が負であったり@var{list}の長さ以上の場合、
6267 @var{fallback}引数が与えられていればそれが返され、
6268 そうでなければエラーが報告されます。
6269 @c COMMON
6270 @end defun
6271
6272 @defun list-ref list k :optional fallback
6273 [R7RS+ base]
6274 @c EN
6275 Returns @var{k}-th element of @var{list}.
6276 @var{list} can be a proper, dotted or circular list.
6277
6278 By default, @code{list-ref} signals an error if @var{k} is
6279 negative, or greater than or equal to the length of @var{list}.
6280 However, if an optional argument @var{fallback} is given,
6281 it is returned for such case. This is an extension of Gauche.
6282 @c JP
6283 @var{list}の@var{k}番目の要素を返します。@var{list}は
6284 正規のリストでもドットリストでも循環リストでも構いません。
6285
6286 もし@var{k}がリストの長さを超えていたり、負数であった場合は通常はエラーが起こります。
6287 しかし、オプショナルな引数@var{fallback}が与えられていた場合は、エラーは起きず
6288 @var{fallback}が返されます。これはGaucheの拡張です。
6289 @c COMMON
6290 @end defun
6291
6292 @defun list-set! list k v
6293 [R7RS base]
6294 @c EN
6295 Modifies the @var{k}-th element of a @var{list} by @var{v}.
6296 It is an error unless @var{k} is an exact integer between 0 and
6297 one minus the length of @var{k}. If @var{list} is immutable,
6298 no error is signalled but the behavior is undefined.
6299 @c JP
6300 リスト@var{list}の@var{k}番目の要素を@var{v}へと変更します。
6301 @var{k}が0から(- リストの長さ 1)の範囲の正確な整数でない場合は
6302 エラーが報告されます。@var{list}が変更不可なリストであった場合、
6303 エラーは報告されませんが、その後の振る舞いは不定となります。
6304 @c COMMON
6305 @end defun
6306
6307
6308 @defun last-pair list
6309 [R7RS list]
6310 @c EN
6311 Returns the last pair of @var{list}.
6312 @var{list} can be a proper or dotted list.
6313 @c JP
6314 @var{list}の最後のペアを返します。@var{list}は
6315 正規のリストかドットリストです。
6316 @c COMMON
6317
6318 @example
6319 (last-pair '(1 2 3)) @result{} (3)
6320 (last-pair '(1 2 . 3)) @result{} (2 . 3)
6321 (last-pair 1) @result{} @i{error}
6322 @end example
6323 @end defun
6324
6325 @defun last pair
6326 [R7RS list]
6327 @c EN
6328 Returns the last element of the non-empty, finite list @var{pair}.
6329 It is equivalent to @code{(car (last-pair pair))}.
6330 @c JP
6331 空ではない有限リスト @var{pair} の最後の要素を返します。
6332 これは、@code{(car (last-pair pair))} と同等です。
6333 @c COMMON
6334
6335 @example
6336 (last '(1 2 3)) @result{} 3
6337 (last '(1 2 . 3)) @result{} 2
6338 @end example
6339 @end defun
6340
6341 @defun split-at x i
6342 @defunx split-at! x i
6343 [R7RS list]
6344 @c EN
6345 @code{split-at} splits the list @var{x} at index @var{i},
6346 returning a list of the first @var{i} elements, and the remaining tail.
6347 @c JP
6348 @code{split-at} はリスト @var{x} をインデックス @var{i} の
6349 位置で分割し、最初の @var{i} 個の要素からなるリストと、残りの末尾とを
6350 返します。
6351 @c COMMON
6352 @example
6353 (split-at '(a b c d e) 2) @result{} (a b) (c d e)
6354 @end example
6355 @c EN
6356 @code{split-at!} is the linear-update variant. It may destructively
6357 modifies @var{x} to produce the result.
6358 @c JP
6359 @code{split-at!} はその場で更新されるバージョンです。
6360 これは @var{x} を破壊的に更新するかもしれません。
6361 @c COMMON
6362 @end defun
6363
6364 @defun split-at* list k :optional (fill? #f) (padding #f)
6365 @c EN
6366 More tolerant version of @code{split-at}.
6367 Returns the results of @code{take*} and @code{drop*}.
6368 @c JP
6369 SRFI-1 (R7RS @code{(scheme list)})の@code{split-at}の寛容なバージョンです。
6370 @code{take*}と@code{drop*}の結果を返します。
6371 @c COMMON
6372
6373 @example
6374 (split-at* '(a b c d) 6 #t 'z)
6375 @result{} (a b c d z z) @r{and} ()
6376 @end example
6377 @end defun
6378
6379 @defun slices list k :optional fill? padding
6380 @c EN
6381 Splits @var{list} into the sublists (slices) where the length of
6382 each slice is @var{k}.
6383 If the length of @var{list} is not a multiple of @var{k},
6384 the last slice is dealt in the same way as @code{take*}; that is,
6385 it is shorter than @var{k} by default, or added @var{padding} if
6386 @var{fill?} is true.
6387 @c JP
6388 @var{list}を、それぞれの長さが@var{k}であるようなサブリスト(スライス)に
6389 分割します。
6390 @var{list}の長さが@var{k}の整数倍でない場合は、最後のスライスは
6391 @code{take*}と同じ方法で扱われます。つまり、デフォルトでは@var{k}より
6392 短いもの、あるいは@var{fill?}が真ならば@var{padding}が追加されます。
6393 @c COMMON
6394
6395 @example
6396 (slices '(a b c d e f g) 3)
6397 @result{} ((a b c) (d e f) (g))
6398 (slices '(a b c d e f g) 3 #t 'z)
6399 @result{} ((a b c) (d e f) (g z z))
6400 @end example
6401 @end defun
6402
6403 @defun intersperse item list
6404 @c EN
6405 Inserts @var{item} between elements in the @var{list}.
6406 (The order of arguments is taken from Haskell's intersperse).
6407 @c JP
6408 @var{list}の要素の間に@var{item}を挿入します。
6409 (引数の順番は、Haskellのintersperseと同じです。)
6410 @c COMMON
6411
6412 @example
6413 (intersperse '+ '(1 2 3)) @result{} (1 + 2 + 3)
6414 (intersperse '+ '(1)) @result{} (1)
6415 (intersperse '+ '()) @result{} ()
6416 @end example
6417 @end defun
6418
6419 @node Walking over lists, Other list procedures, List accessors and modifiers, Pairs and lists
6420 @subsection Walking over lists
6421 @c NODE リストをたどる手続き
6422
6423 @defun map proc list1 list2 @dots{}
6424 [R7RS+ base]
6425 @c EN
6426 Applies @var{proc} for each element(s) of given list(s),
6427 and returns a list of the results. R7RS doesn't specify
6428 the application order of @code{map}, but Gauche guarantees
6429 @var{proc} is always applied in order of the list(s).
6430 Gauche's @code{map} also terminates as soon as one of
6431 the list is exhausted.
6432 @c JP
6433 与えられたリストの各要素に対して@var{proc}を適用し、その結果をリストにして
6434 返します。R7RSでは@var{proc}の適用順序が定められていませんが、Gaucheでは
6435 常に@var{proc}はリスト内の順番で呼ばれます。
6436 複数のリストが与えられた場合、最も短いリストが終了した時点で@var{proc}の適用を
6437 打ち切ります。
6438 @c COMMON
6439
6440 @example
6441 (map car '((a b) (c d) (e f))) @result{} (a c e)
6442
6443 (map cons '(a b c) '(d e f))
6444 @result{} ((a . d) (b . e) (c . f))
6445 @end example
6446
6447 @c EN
6448 Note that the @code{gauche.collection} module (@pxref{Collection framework})
6449 extends @code{map} to work on any type of collection.
6450 @c JP
6451 @code{gauche.collection}モジュール(@ref{Collection framework}参照)
6452 を使うと、@code{map}がリスト以外のコレクション型に対しても動作するようになります。
6453 @c COMMON
6454 @end defun
6455
6456 @defun append-map f clist1 clist2 @dots{}
6457 @defunx append-map! f clist1 clist2 @dots{}
6458 [R7RS list]
6459 @c EN
6460 Functionally equivalent to the followings, though a bit more efficient:
6461 @c JP
6462 機能的には以下と同等ですが、若干効率が良いです:
6463 @c COMMON
6464
6465 @example
6466 (apply append (map @var{f} @var{clist1} @var{clist2} @dots{}))
6467 (apply append! (map @var{f} @var{clist1} @var{clist2} @dots{}))
6468 @end example
6469 @c EN
6470 At least one of the list arguments must be finite.
6471 @c JP
6472 引数のリストのうち少くともひとつは有限でなければなりません。
6473 @c COMMON
6474 @end defun
6475
6476
6477 @defun map* proc tail-proc list1 list2 @dots{}
6478 @c EN
6479 Like @code{map}, except that @var{tail-proc} is applied to the @code{cdr}
6480 of the last pair in the argument(s) to get the @code{cdr} of
6481 the last pair of the result list. This procedure allows improper
6482 list to appear in the arguments. If a single list is given,
6483 @var{tail-proc} always receives a non-pair object.
6484 @c JP
6485 @code{map}とほぼ同じですが、引数の最後のペアの@code{cdr}に@var{tail-proc}が
6486 適用され、その返り値が結果のリストの最後のペアの@code{cdr}になります。
6487 この手続きは正規でないリストを引数に取ることができます。
6488 引数のリストがひとつだけの場合、@var{tail-proc}の引数は必ずペアでないオブジェクトです。
6489 @c COMMON
6490
6491 @example
6492 (map* - / '(1 2 3 . 4)) @result{} (-1 -2 -3 . 1/4)
6493
6494 (define (proper lis)
6495 (map* values
6496 (lambda (p) (if (null? p) '() (list p)))
6497 lis))
6498
6499 (proper '(1 2 3)) @result{} (1 2 3)
6500 (proper '(1 2 3 . 4)) @result{} (1 2 3 4)
6501 @end example
6502
6503 @c EN
6504 If more than one list are given, the shortest one determines
6505 how @var{tail-proc} is called. When @code{map*} reaches the
6506 last pair of the shortest list, @var{tail-proc} is called with
6507 cdrs of the current pairs.
6508 @c JP
6509 二つ以上のリストが与えられた場合は、最も短いリストが@var{tail-proc}の呼び出しを
6510 決めます。@code{map*}が最も短いリストの最後のペアに達した時点で、
6511 その時のそれぞれのペアのcdrが@var{tail-proc}へと渡されます。
6512 @c COMMON
6513
6514 @example
6515 (map* + vector '(1 2 3 4) '(1 2 . 3))
6516 @result{} (2 4 . #((3 4) 3))
6517 @end example
6518
6519 @c EN
6520 Note: The name @code{map*} is along the line of
6521 @code{list*}/@code{cons*} that can produce improper list
6522 (@xref{List constructors}, @pxref{R7RS lists}).
6523 @c JP
6524 註: @code{map*}という名前は、正規でないリストを作り得る@code{list*}/@code{cons*}からの
6525 連想でつけられました
6526 (@ref{List constructors}、@ref{R7RS lists}参照)。
6527 @c COMMON
6528 @end defun
6529
6530 @defun for-each proc list1 list2 @dots{}
6531 [R7RS base]
6532 @c EN
6533 Applies @var{proc} for each element(s) of given list(s) in order.
6534 The results of @var{proc} are discarded. The return value of
6535 @code{for-each} is undefined. When more than one list is given,
6536 @code{for-each} terminates as soon as one of the list is exhausted.
6537 @c JP
6538 手続き@var{proc}をリストの各エレメントに対して順に適用します。
6539 @var{proc}の結果は捨てられます。@code{for-each}の戻り値は定義されていません。
6540 複数のリストが与えられた場合、一番短いリストが終了した時点で@code{for-each}は終了します。
6541 @c COMMON
6542
6543 @c EN
6544 Note that the @code{gauche.collection} module (@pxref{Collection framework})
6545 extends @code{for-each} to work on any type of collection.
6546 @c JP
6547 @code{gauche.collection}モジュール(@ref{Collection framework}参照)
6548 を使うと、@code{for-each}がリスト以外のコレクション型に対しても動作するようになります。
6549 @c COMMON
6550 @end defun
6551
6552 @defun fold kons knil clist1 clist2 @dots{}
6553 [R7RS list]
6554 @c EN
6555 The fundamental list iterator.
6556 When it is given a single list
6557 @var{clist1} = (@var{e1} @var{e2} @dots{} @var{en}),
6558 then this procedure returns
6559 @c JP
6560 基本的なリスト反復演算子です。単一のリスト
6561 @var{clist1} = (@var{e1} @var{e2} @dots{} @var{en})
6562 を与えられたときには、以下を返します。
6563 @c COMMON
6564 @example
6565 (@var{kons} @var{en} @dots{} (@var{kons} @var{e2} (@var{kons} @var{e1} @var{knil})) @dots{} )
6566 @end example
6567
6568 @c EN
6569 If @var{n} list arguments are provided, then the @var{kons}
6570 function must take @var{n}+1 parameters: one element from each list, and
6571 the "seed" or fold state, which is initially @var{knil}.
6572 The fold operation terminates when the shortest list runs out of values.
6573 At least one of the list arguments must be finite.
6574
6575 Examples:
6576 @c JP
6577 @var{n} 本のリストが与えられた場合には、@var{kons} 関数は @var{n}+1 個の引数
6578 をとる関数でなければなりません。それぞれのリストから要素をひとつずつと、
6579 初期値 @var{knil} である「種」あるいは畳み込み状態とよばれるものです。
6580 この畳み込み演算は、もっとも短いリストの要素がなくなったところで終了します。
6581 与えられるリストの少くともひとつは有限でなければなりません。
6582
6583 例:
6584 @c COMMON
6585 @example
6586 (fold + 0 '(3 1 4 1 5 9)) @result{} 23 ;@r{sum up the elements}
6587 (fold cons '() '(a b c d e)) @result{} (e d c b a) ;@r{reverse}
6588 (fold cons* '() '(a b c) '(1 2 3 4 5))
6589 @result{} (c 3 b 2 a 1) ;@r{n-ary case}
6590 @end example
6591 @end defun
6592
6593 @defun fold-right kons knil clist1 clist2 @dots{}
6594 [R7RS list]
6595 @c EN
6596 The fundamental list recursion operator.
6597 When it is given a single list
6598 @var{clist1} = (@var{e1} @var{e2} @dots{} @var{en}),
6599 then this procedure returns
6600 @c JP
6601 基本的な再帰演算子です。単一のリスト
6602 @var{clist1} = (@var{e1} @var{e2} @dots{} @var{en})
6603 を与えられたときには、以下を返します。
6604 @c COMMON
6605 @example
6606 (@var{kons} @var{e1} (@var{kons} @var{e2} @dots{} (@var{kons} @var{en} @var{knil})))
6607 @end example
6608
6609 @c EN
6610 If @var{n} list arguments are provided, then the @var{kons} function
6611 must take @var{n}+1 parameters: one element from each list, and
6612 the "seed" or fold state, which is initially @var{knil}.
6613 The fold operation terminates when the shortest list runs out of values.
6614 At least one of the list arguments must be finite.
6615
6616 Examples:
6617 @c JP
6618 @var{n} 本のリストが与えられた場合には、@var{kons} 関数は @var{n}+1 個の引数
6619 をとる関数でなければなりません。それぞれのリストから要素をひとつずつと、
6620 初期値 @var{knil} である「種」あるいは畳み込み状態とよばれものです。
6621 この畳み込み演算は、もっとも短いリストの要素がなくなったところで終了します。
6622 与えられるリストの少くともひとつは有限でなければなりません。
6623
6624 例:
6625 @c COMMON
6626 @example
6627 (fold-right cons '() '(a b c d e))
6628 @result{} (a b c d e) ;@r{copy list}
6629 (fold-right cons* '() '(a b c) '(1 2 3 4 5))
6630 @result{} (a 1 b 2 c 3) ;@r{n-ary case}
6631 @end example
6632 @end defun
6633
6634 @defun fold-left snok knil clist1 clist2 @dots{}
6635 [R6RS]
6636 @c EN
6637 This is another variation of left-associative folding.
6638 When it is given a single list
6639 @var{clist1} = (@var{e1} @var{e2} @dots{} @var{en}),
6640 then this procedure returns:
6641 @c JP
6642 これは左結合のfoldの別バージョンです。一つのリスト
6643 @var{clist1} = (@var{e1} @var{e2} @dots{} @var{en})
6644 が与えられた場合、次の値を返します。
6645 @c COMMON
6646 @example
6647 (@var{snok} (@dots{} (@var{snok} (@var{snok} @var{knil} @var{e1}) @var{e2}) @dots{}) @var{en})
6648 @end example
6649
6650 @c EN
6651 Compare this with @code{fold} above; association is the same, but the order
6652 of arguments passed to the procedure @var{snok} is reversed from the way
6653 arguments are passed to @var{kons} in @code{fold}. If @var{snok} is
6654 commutative, @code{fold} and @code{fold-left} produces the same result.
6655 @c JP
6656 上の@code{fold}と見比べてみてください。結合の順序は同じですが、
6657 @var{snok}に渡される引数の順序が、@code{fold}において@var{kons}に渡される
6658 引数の順序とは逆になっています。@code{snok}が可換な演算であれば、
6659 @code{fold}と@code{fold-left}の結果は同じになります。
6660 @c COMMON
6661
6662 @example
6663 (fold-left + 0 '(1 2 3 4 5) @result{} 15
6664
6665 (fold-left cons 'z '(a b c d))
6666 @result{} ((((z . a) . b) . c) . d)
6667
6668 (fold-left (^[a b] (cons b a)) 'z '(a b c d))
6669 @result{} (a b c d z)
6670 @end example
6671
6672 @c EN
6673 If more than one lists are given, @var{snok} is called with
6674 the current seed value @var{knil} and each corresponding
6675 element of the input lists
6676 @code{clist1} @code{clist2} @dots{}.
6677 @c JP
6678 二つ以上のリストが渡された場合、@var{snok}は現在の@var{knil}値および
6679 入力リスト@code{clist1} @code{clist2} @dots{} の対応する要素を引数として
6680 呼び出されます。
6681 @c COMMON
6682
6683 @example
6684 (fold-left list 'z '(a b c) '(A B C))
6685 @result{} (((z a A) b B) c C)
6686 @end example
6687
6688 @c EN
6689 Note: Most functional languages have left- and right- associative
6690 fold operations, which correspond to @code{fold-left} and @code{fold-right},
6691 respectively.
6692 (e.g. Haskell's @code{foldl} and @code{foldr}). In Scheme, SRFI-1
6693 first introduced @code{fold} and @code{fold-right}. R6RS introduced
6694 @code{fold-left}. (However, in R6RS the behavior is undefined if the lengths of
6695 @code{clist1} @code{clist2} @dots{} aren't the same, while in Gauche
6696 @code{fold-left} terminates as soon as any one of the lists terminates.)
6697 @c JP
6698 註:多くの関数型言語で左結合および右結合の畳み込み操作が定義されていますが、
6699 それは@code{fold-left}と@code{fold-right}に相当します。
6700 (例: Haskellの@code{foldl}と@code{foldr}。)
6701 Schemeでは、まずSRFI-1によって@code{fold}と@code{fold-right}が
6702 左/右結合の畳み込み演算として導入され、R6RSで@code{fold-left}が定義されました。
6703 (但し、R6RSの@code{fold-left}では@code{clist1} @code{clist2} @dots{}の
6704 長さがすべて同じでない場合の動作は未定義ですが、Gaucheでは
6705 最短のリストが終了した時点でそれまでの結果が返されます。)
6706 @c COMMON
6707 @end defun
6708
6709 @defun reduce f ridentity list
6710 @defunx reduce-right f ridentity list
6711 [R7RS list]
6712 @c EN
6713 Variant of @code{fold} and @code{fold-right}. @var{f} must be a
6714 binary operator, and @var{ridentity} is the value such that for
6715 any value @var{x} that is valid as @var{f}'s input,
6716 @c JP
6717 @code{fold} および @code{fold-right} の変形バージョンです。
6718 @var{f} は二項演算子でなければなりません。
6719 また、@var{ridentity} は @var{f} の入力として許される
6720 あらゆる値 @var{x} について以下を満していなければなりません。
6721 @c COMMON
6722 @example
6723 (f x ridentity) @equiv{} x
6724 @end example
6725
6726 @c EN
6727 These functions effectively do the same thing as @code{fold} or
6728 @code{fold-right}, respectively, but omit the first
6729 application of @var{f} to @var{ridentity}, using the above nature.
6730 So @var{ridentity} is used only when @var{list} is empty.
6731 @c JP
6732 これらの関数は実質的に @code{fold} や @code{fold-right} と同じことを
6733 行いますが、@var{ridentity}には上記の性質があるため、
6734 @var{f}は@var{ridentity}には適用されません。
6735 @var{ridentity}が使われるのは@var{list}が空の場合だけです。
6736 @c COMMON
6737 @end defun
6738
6739
6740
6741 @defun filter pred list
6742 @defunx filter! pred list
6743 [R7RS list]
6744 @c EN
6745 A procedure @var{pred} is applied on each element of @var{list},
6746 and a list of elements that @var{pred} returned true on it is returned.
6747 @c JP
6748 手続き @var{pred} が @var{list} の各要素に適用され、
6749 @var{pred} が真を返す要素のリストが返されます。
6750 @c COMMON
6751 @example
6752 (filter odd? '(3 1 4 5 9 2 6)) @result{} (3 1 5 9)
6753 @end example
6754 @c EN
6755 @code{filter!} is the linear-update variant. It may destructively
6756 modifies @var{list} to produce the result.
6757 @c JP
6758 @code{filter!} はその場で更新されるバージョンです。結果を生成するために
6759 @var{list} を破壊的に変更するかもしれません。
6760 @c COMMON
6761 @end defun
6762
6763 @defun filter-map f clist1 clist2 @dots{}
6764 @c EN
6765 [R7RS list]
6766 Like @code{map}, but only true values are saved.
6767 At least one of the list arguments must be finite.
6768 @c JP
6769 @code{map} と似ていますが、真になる場合の値のみが保存されます。
6770 引数として与えられるリストの少くともひとつは有限でなければなりません。
6771 @c COMMON
6772 @example
6773 (filter-map (lambda (x) (and (number? x) (* x x)))
6774 '(a 1 b 3 c 7))
6775 @result{} (1 9 49)
6776 @end example
6777 @end defun
6778
6779 @defun remove pred list
6780 @defunx remove! pred list
6781 [R7RS list]
6782 @c EN
6783 A procedure @var{pred} is applied on each element of @var{list},
6784 and a list of elements that @var{pred} returned false on it is returned.
6785 @c JP
6786 手続き @var{pred} が @var{list} の各要素に適用され、
6787 @var{pred} が偽を返す要素のリストが返されます。
6788 @c COMMON
6789 @example
6790 (remove odd? '(3 1 4 5 9 2 6)) @result{} (4 2 6)
6791 @end example
6792 @c EN
6793 @code{remove!} is the linear-update variant. It may destructively
6794 modifies @var{list} to produce the result.
6795 @c JP
6796 @code{remove!} はその場で更新されるバージョンです。結果を生成するために
6797 @var{list} を破壊的に更新するかもしれません。
6798 @c COMMON
6799 @end defun
6800
6801 @defun find pred clist
6802 [R7RS list]
6803 @c EN
6804 Applies @var{pred} for each element of @var{clist}, from
6805 left to right, and returns the first element that @var{pred} returns
6806 true on. If no element satisfies @var{pred}, @code{#f} is returned.
6807 @c JP
6808 @var{clist} の各要素に対して左から右に @var{pred} を適用し、
6809 @var{pred} が真を返す最初の要素を返します。@var{pred}を満たす要素が
6810 無い場合は@code{#f}を返します。
6811 @c COMMON
6812 @end defun
6813
6814 @defun find-tail pred clist
6815 [R7RS list]
6816 @c EN
6817 Applies @var{pred} for each element of @var{clist}, from left to right,
6818 and when @var{pred} returns a true value, returns the pair whose car
6819 is the element. If no element satisfies @var{pred}, @code{#f} is returned.
6820 @c JP
6821 @var{clist} の各要素に対して左から右に @var{pred} を適用し、@var{pred} が
6822 真を返す場合、その car がその要素であるペアを返します。
6823 @var{pred}を満たす要素が無い場合は@code{#f}を返します。
6824 @c COMMON
6825 @end defun
6826
6827 @defun any pred clist1 clist2 @dots{}
6828 [R7RS list]
6829 @c EN
6830 Applies @var{pred} across each element of @var{clist}s, and
6831 returns as soon as @var{pred} returns a non-false value.
6832 The return value of @code{any} is the non-false value @var{pred} returned.
6833 If @var{clist}s are exhausted before @var{pred} returns a non-false
6834 value, @code{#f} is returned.
6835 @c JP
6836 @var{clist} の各要素に @var{pred} を適用し、@var{pred}が偽でない
6837 値を返したら直ちにその値を返します。
6838 @var{pred}が偽でない値を返す前にリストの要素を使いきってしまったら
6839 @code{#f}が返ります。
6840 @c COMMON
6841 @end defun
6842
6843 @defun every pred clist1 clist2 @dots{}
6844 [R7RS list]
6845 @c EN
6846 Applies @var{pred} across each element of @var{clist}s, and
6847 returns @code{#f} as soon as @var{pred} returns @code{#f}.
6848 If all application of @var{pred} return a non-false value,
6849 @code{every} returns the last result of the applications.
6850 @c JP
6851 @var{clist} の各要素に @var{pred} を順に適用し、@var{pred}が
6852 偽を返した場合、直ちに偽を返します。全ての@var{pred}の適用が
6853 偽でない値を返した場合は、最後に返された値が返されます。
6854 @c COMMON
6855 @end defun
6856
6857 @defun count pred clist1 clist2 @dots{}
6858 [R7RS list]
6859 @c EN
6860 A procedure @var{pred} is applied to the @var{n}-th element
6861 of given lists, from @var{n} is zero to the length of the
6862 the shortest finite list in the given lists,
6863 and the count of times @var{pred} returned true is returned.
6864 @c JP
6865 @var{n} をゼロから与えられたリストのうち最も短いリストの
6866 長さまでとして、@var{pred} 手続きを与えられたリストの @var{n} 番目の要素に
6867 それぞれ適用します。
6868 @var{pred} が真を返した数が返ります。
6869 @c COMMON
6870
6871 @example
6872 (count even? '(3 1 4 1 5 9 2 5 6)) @result{} 3
6873 (count < '(1 2 4 8) '(2 4 6 8 10 12 14 16)) @result{} 3
6874 @end example
6875
6876 @c EN
6877 At least one of the argument lists must be finite:
6878 @c JP
6879 引数で与えられるリストの少くともひとつは有限でなければなりません。
6880 @c COMMON
6881
6882 @example
6883 (count < '(3 1 4 1) (circular-list 1 10)) @result{} 2
6884 @end example
6885 @end defun
6886
6887
6888 @defun delete x list :optional elt=
6889 @defunx delete! x list :optional elt=
6890 [R7RS list]
6891 @c EN
6892 Equivalent to
6893 @c JP
6894 以下と同等です。
6895 @c COMMON
6896 @example
6897 (remove (lambda (y) (elt= x y)) list)
6898 (remove! (lambda (y) (elt= x y)) list)
6899 @end example
6900 @c EN
6901 The comparison procedure, @var{elt=}, defaults to @code{equal?}.
6902 @c JP
6903 比較手続き @var{elt=} はデフォルトでは @code{equal?} です。
6904 @c COMMON
6905 @end defun
6906
6907 @defun delete-duplicates list :optional elt=
6908 @defunx delete-duplicates! list :optional elt=
6909 [R7RS list]
6910 @c EN
6911 Removes duplicate elements from @var{list}.
6912 If there are multiple equal elements in @var{list},
6913 the result list only contains the first or leftmost of these
6914 elements in the result. The order of these surviving elements
6915 is the same as in the original list.
6916 The comparison procedure, @var{elt=}, defaults to @code{equal?}.
6917 @c JP
6918 @var{list} から重複した要素を取り除きます。@var{list} 中に等しい要素が
6919 複数ある場合、一番左がわにある最初のものだけが残ります。これらの
6920 生き残った要素間の順番は最初のリストの順番が保存されます。
6921 比較手続き @var{elt=} のデフォルト値は、@code{equal?} です。
6922 @c COMMON
6923 @end defun
6924
6925 @node Other list procedures, Association lists, Walking over lists, Pairs and lists
6926 @subsection Other list procedures
6927 @c NODE 他のリスト手続き
6928
6929 @defun append list @dots{}
6930 [R7RS base]
6931 @c EN
6932 Returns a list consisting of the elements of the first @var{list} followed by
6933 the elements of the other lists. The resulting list is always newly
6934 allocated, except that it shares structure with the last list argument.
6935 The last argument may actually be any object; an improper list results
6936 if the last argument is not a proper list.
6937 @c JP
6938 渡されたリストの要素を繋げたリストを返します。最後の引数の部分以外は新しいセルがアロケート
6939 されて使われます。最後の引数は正規のリストである必要がありません。その場合、結果は正規でない
6940 リストとなります。
6941 @c COMMON
6942 @end defun
6943
6944 @defun append! list @dots{}
6945 [R7RS list]
6946 @c EN
6947 Returns a list consisting of the elements of the first @var{list} followed by
6948 the elements of the other lists. The cells in the lists except the last
6949 one may be reused to construct the result. The last argument may be
6950 any object.
6951 @c JP
6952 渡されたリストの要素を繋げたリストを返します。最後の引数以外のリストのセルは、結果を
6953 作成するために再利用されるかもしれません。
6954 最後の引数は正規のリストである必要はありません。
6955 @c COMMON
6956 @end defun
6957
6958 @defun concatenate list-of-lists
6959 @defunx concatenate! list-of-lists!
6960 [R7RS list]
6961 @c EN
6962 Equivalent to @code{(apply append @var{list-of-lists})} and
6963 @code{(apply append! @var{list-of-lists})}, respectively, but this
6964 can be a bit efficient by skipping overhead of @code{apply}.
6965 @c JP
6966 それぞれ、@code{(apply append @var{list-of-lists})} および
6967 @code{(apply append! @var{list-of-lists})} と同等ですが、
6968 @code{apply}のオーバヘッドが無い分、わずかに効率的です。
6969 @c COMMON
6970 @end defun
6971
6972 @defun reverse list :optional (tail '())
6973 @defunx reverse! list :optional (tail '())
6974 [R7RS+ base]
6975 @c EN
6976 Returns a list consisting of the elements of @var{list}
6977 in the reverse order.
6978 While @code{reverse} always returns
6979 a newly allocated list, @code{reverse!} may reuse the cells
6980 of @var{list}. Even @var{list} is destructively modified
6981 by @code{reverse!}, you should use its return value, for
6982 the first cell of @var{list} may not be the first cell
6983 of the returned list.
6984
6985 If an optional argument @var{tail} is given, it becomes
6986 the tail of the returned list (@var{tail} isn't copied).
6987 It is useful in the idiom to prepend the processed results
6988 on top of already existing results.
6989 @c JP
6990 @var{list}の要素を逆順に並べたリストを返します。
6991 @code{reverse}は常に新たにリストをアロケートしますが、
6992 @code{reverse!}は結果を作るために@var{list}のセルを再利用するかもしれません。
6993 但し、@var{list}の先頭のセルが@code{reverse!}の結果でも先頭になるとは
6994 限らないので、@var{list}が変更されることを当てにするのではなく、
6995 @code{reverse!}の戻り値を利用する必要があります。
6996
6997 省略可能引数@var{tail}が与えられた場合、それは結果のリストの末尾に
6998 付け足されます (@var{tail}部分はコピーされません)。
6999 これは、既にある結果のリストに新たに作った結果を付け足すイディオムで
7000 便利です。
7001 @c COMMON
7002
7003 @example
7004 (reverse '(1 2 3 4 5)) @result{} (5 4 3 2 1)
7005 (reverse '(1 2 3) '(a b)) @result{} (3 2 1 a b)
7006 @end example
7007
7008 @c EN
7009 The @var{tail} argument is Gauche's extension,
7010 and it isn't in the traditional Scheme's @code{reverse}.
7011 The rationale is the following correspondence:
7012 @c JP
7013 @var{tail}引数はGauche独自の拡張で、
7014 伝統的なSchemeの@code{reverse}にはありませんが、
7015 次の対応を考えると、そう不自然なことではありません。
7016 @c COMMON
7017
7018 @example
7019 (reverse xs) @equiv{} (fold cons xs '())
7020 (reverse xs tail) @equiv{} (fold cons xs tail)
7021 @end example
7022
7023 @c EN
7024 For portable code, @code{append-reverse}/@code{append-reverse!}
7025 below can be used in place of two-argument @code{reverse}/@code{reverse!}.
7026 @c JP
7027 ポータブルなコードでは2引数の@code{reverse}/@code{reverse!}のかわりに
7028 以下の@code{append-reverse}/@code{append-reverse!}が使えます。
7029 @c COMMON
7030 @end defun
7031
7032 @defun append-reverse rev-head tail
7033 @defunx append-reverse! rev-head tail
7034 [R7RS list]
7035 @c EN
7036 Equivalent to the two-argument @code{reverse} and @code{reverse!}.
7037 Provided for SRFI-1 (R7RS @code{(scheme list)}) compatibility.
7038 @c JP
7039 2引数の@code{reverse}および@code{reverse!}と同等です。
7040 SRFI-1 (R7RS @code{(scheme list)}) との互換のために用意されています。
7041 @c COMMON
7042 @end defun
7043
7044
7045 @defun memq obj list
7046 @defunx memv obj list
7047 @defunx member obj list :optional obj=
7048 [R7RS base]
7049 @c EN
7050 Searches @var{obj} in the @var{list}. If @code{n}-th element of
7051 @var{list} equals to @var{obj} (in the sense of @code{eq?} for @code{memq},
7052 @code{eqv?} for @code{memv}, and @code{equal?} for @code{member}),
7053 @code{(list-tail @var{list} @var{n})} is returned.
7054 Otherwise, @code{#f} is returned.
7055 @c JP
7056 @var{list}から@var{obj}を探します。もし@var{list}の@var{n}番目の要素が
7057 @var{obj}と同一ならば、@code{(list-tail @var{list} @var{n})}を返します。
7058 @code{memq}は同一性の判定に@code{eq?}を、@code{memv}は@code{eqv?}を、
7059 @code{member}は@code{equal?}を使います。
7060 @var{obj}が@var{list}中に見つからなければ@code{#f}が返されます。
7061 @c COMMON
7062
7063 @c EN
7064 If the optional @var{obj=} argument of @code{member} is given,
7065 it is used as a equivalence predicate
7066 instead of @code{equal?}.
7067 @c JP
7068 @code{member}に省略可能引数@var{obj=}が与えられた場合は、
7069 その手続きが@code{equal?}のかわりに@var{obj}と要素を比較するのに使われます。
7070 @c COMMON
7071 @example
7072 (memq 'a '(a b c)) @result{} (a b c)
7073 (memq 'b '(a b c)) @result{} (b c)
7074 (memq 'a '(b c d)) @result{} #f
7075 (memq (list 'a) '(b (a) c)) @result{} #f
7076 (memv 101 '(100 101 102)) @result{} (101 102)
7077 @end example
7078 @end defun
7079
7080 @node Association lists, Extended pairs and pair attributes, Other list procedures, Pairs and lists
7081 @subsection Association lists
7082 @c NODE 連想リスト
7083
7084 @c EN
7085 An association list is a list of pairs. Each @code{car} of a pair
7086 is a key, and each @code{cdr} of a pair is an associated value.
7087 It is the earliest data structure to represent mappings.
7088
7089 It takes O(N) to lookup so it's not suitable for large amount of data,
7090 but it is still widely used since it's easy to realize immutable mapping
7091 (the new entries can ``shadow''
7092 the existing entries with the same key, allowing to ``change'' the content
7093 without mutating existing maps).
7094 @c JP
7095 連想リストはペアのリストです。各ペアの@code{car}がキー、@code{cdr}がそのキーに
7096 結びつけられた値です。これはマッピングを表現する最も初期のデータ構造でした。
7097
7098 値のルックアップにO(N)を要するのであまり大きなデータを扱うには向いていませんが、
7099 不変データ構造を容易に実現できる (同じキーを持つエントリを追加すると既存のキーが「シャドウ」
7100 されるため、既存のデータ構造を破壊することなく内容の変更が可能) ので、今でも広く使われています。
7101 @c COMMON
7102
7103 @c EN
7104 @subsubheading Basic constructor and accessors
7105 @c JP
7106 @subsubheading 基本コンストラクタとアクセサ
7107 @c COMMON
7108
7109 @defun acons obj1 obj2 obj3
7110 @c EN
7111 Returns @code{(cons (cons @var{obj1} @var{obj2}) @var{obj3})}.
7112 Useful to put an entry at the head of an associative list.
7113
7114 (This procedure is defined in SRFI-1 (R7RS @code{(scheme list)}) as @code{alist-cons}; @pxref{R7RS lists}).
7115 @c JP
7116 @code{(cons (cons @var{obj1} @var{obj2}) @var{obj3})} を返します。
7117 連想リストの先頭に新しいエントリを加えるのに便利です。
7118
7119 (この手続きはSRFI-1 (R7RS @code{(scheme list)})では@code{alist-cons}という名前で定義されています。
7120 @ref{R7RS lists}参照)。
7121 @c COMMON
7122
7123 @lisp
7124 (acons 'a 'b '((c . d))) @result{} ((a . b) (c . d))
7125 @end lisp
7126 @end defun
7127
7128 @defun assq obj list
7129 @defunx assv obj list
7130 @defunx assoc obj list :optional key=
7131 [R7RS base]
7132 @c EN
7133 Each element in @var{list} should be a pair
7134 (Gauche ignores non-pair element in @var{list}, but other R7RS
7135 implementation may raise an error, so be aware of it when you're
7136 writing a portable code).
7137 These procedures search a pair whose car matches @var{obj}
7138 (in the sense of @code{eq?} for @code{assq},
7139 @code{eqv?} for @code{assv}, and @code{equal?} for @code{assoc})
7140 from left to right, and return the leftmost matched pair if any.
7141 If no pair matches, these return @code{#f}.
7142 @c JP
7143 @var{list}の各要素はペアでなければなりません
7144 (Gaucheは@var{list}中のペアでない要素を単に無視しますが、
7145 他のR7RS処理系はエラーを投げるかもしれないので、
7146 ポータブルなコードを書いている時は注意してください)。
7147 これらの手続きは、@var{list}の要素であるペアのうち、そのcarが
7148 @var{obj}と一致するペアを左から探して行きます。もし見付かればそのペアが、
7149 見付からなければ@code{#f}が返されます。
7150 @code{assq}は比較関数に@code{eq?}を、@code{assv}は@code{eqv?}を、
7151 @code{assoc}は@code{equal?}をそれぞれ用います。
7152 @c COMMON
7153
7154 @c EN
7155 If the optional argument of @code{assoc} is given,
7156 it is called instead of @code{equal?}
7157 to check the equivalence of @var{obj} and each key.
7158 @c JP
7159 @code{assoc}の省略可能引数が与えられた場合は、
7160 その手続きが@code{equal?}のかわりに、
7161 @var{obj}と各キーとの同一性判定に使われます。
7162 @c COMMON
7163 @end defun
7164
7165 @defun rassoc val alist :optional val=
7166 @defunx rassq val alist
7167 @defunx rassv val alist
7168 @c EN
7169 Reverse associations---given @var{val} is matched to the @emph{cdr}
7170 of each element in @var{alist}, instead of the @emph{car}.
7171 Handy to realize bidirectional associative list.
7172 @code{Rassoc} takes an optional comparison function, whose default is
7173 @code{equal?}. @code{Rassq} and @code{rassv} uses @code{eq?} and @code{eqv?}.
7174 @c JP
7175 与えられる@var{val}が@var{alist}のそれぞれの要素で、@emph{car}の代わりに
7176 @emph{cdr}にマッチするような逆になった連想リストです。
7177 両方向の連想リストと理解すると簡単です。
7178 @code{rassoc}は、そのデフォルトが@code{equal?}である、オプションの
7179 比較関数を取ります。@code{rassq}は@code{eq?}、@code{rassv}は@code{eqv?}を
7180 使います。
7181 @c COMMON
7182 @end defun
7183
7184 @c EN
7185 @subsubheading Advanced operations
7186 @c JP
7187 @subsubheading 進んだ操作
7188 @c COMMON
7189
7190
7191 @defun alist-copy alist
7192 [R7RS list]
7193 @c EN
7194 Returns a fresh copy of @var{alist}.
7195 The spine of @var{alist} and each cell that points a key and a value
7196 is copied.
7197 @c JP
7198 @var{alist} の新しい複製を返します。@var{alist} の背骨の部分、
7199 およびキーと値を指す各セルは複製されます。
7200 @c COMMON
7201 @example
7202 (define a (list (cons 'a 'b) (cons 'c 'd)))
7203 a @result{} ((a . b) (c . d))
7204
7205 (define b (alist-copy a))
7206 b @result{} ((a . b) (c . d))
7207
7208 (set-cdr! (car a) 'z)
7209 a @result{} ((a . z) (c . d))
7210 b @result{} ((a . b) (c . d))
7211 @end example
7212 @end defun
7213
7214 @defun alist-ref alist key :optional key= default
7215 @c EN
7216 Lookup @var{key} from an assoc list @var{alist},
7217 in the symmetric way with other @code{*-ref} procedures.
7218 Keys are compared with @var{key=}, which defaults to @code{equal?}.
7219
7220 This captures the common pattern of alist access:
7221 @c JP
7222 他の*-ref手続きと対称的な方法で、連想リスト@var{alist}から@var{key}を
7223 探します。キーは@var{key=}で比較され、省略時は@code{equal?}が使われます。
7224
7225 これは、一般的な連想リストアクセスのパターンを提供します。
7226 @c COMMON
7227 @example
7228 (alist-ref alist key default eq-fn)
7229 @equiv{}
7230 (cond [(assoc key alist eq-fn) => cdr]
7231 [else default])))
7232 @end example
7233
7234 @c EN
7235 If @var{default} is omitted, @code{#f} is used.
7236 @c JP
7237 @var{default}が省略されると、@code{#f}が使われます。
7238 @c COMMON
7239
7240 @c EN
7241 NB: This procedure supersedes a legacy @code{assoc-ref}, @code{assq-ref}
7242 and @code{assv-ref}, by the following reasons:
7243 Its name is very similar to @code{assoc} etc. but the
7244 argument order is different, and most other modern alist operators
7245 has the name prefix @code{alist-}.
7246 Be aware that the optional arguments of @code{alist-ref} differs
7247 from @code{assoc-ref}, when you update your code. It is to make it
7248 easier to cover the valiations of key equality procedures, e.g.
7249 @code{(assq-ref alist key)} @equiv{} @code{(alist-ref alist key eq?)}.
7250 @c JP
7251 註: この手続きは、旧式の@code{assoc-ref}、@code{assq-ref}、@code{assv-ref}を
7252 置き換えるものです。これらの手続きは、@code{assoc}等と似た名を持つのに
7253 引数順が異なり、また新しい連想リスト操作は@code{alist-}をプレフィクスに持つという
7254 原則からも外れていることから、非推奨となりました。
7255 @code{assoc-ref}を使っているコードを@code{alist-ref}に書き換える際には、
7256 省略可能引数の順序が異なっていることに注意してください。これは、@code{alist-ref}
7257 で複数のバリエーションをカバーしやすくするためです。
7258 例えば@code{(assq-ref alist key)}は@code{(alist-ref alist key eq?)}で
7259 置き換えられます。
7260 @c COMMON
7261 @end defun
7262
7263 @defun alist-key alist val :optional val= default
7264 @c EN
7265 Returns a key that has the associated value equal to @var{val}.
7266 This is to @code{alist-ref} as @code{rassoc} is to @code{assoc}.
7267 The value is compared by @var{val=}, whose default is @code{equal?}.
7268 If no entry's value matches @var{val}, @var{default} is returned,
7269 whose default is @code{#f}.
7270 @c JP
7271 値が@var{val}に一致するようなキーを連想リスト@var{alist}から探して返します。
7272 @code{alist-key}と@code{alist-ref}の関係は、
7273 @code{assoc}に対する@code{rassoc}の関係に相当します。
7274 値の等価性は@var{val=}で比較されます。デフォルトは@code{equal?}です。
7275 @var{val}に一致する値を持つエントリが無かった場合は@var{default}が
7276 返されます。そのデフォルトは@code{#f}です。
7277 @c COMMON
7278
7279 @example
7280 (alist-key alist val val= default)
7281 @equiv{}
7282 (cond ((rassoc val alist val=) => car)
7283 (else default))
7284 @end example
7285
7286 @c EN
7287 NB: This procedure supersedes legacy @code{rassoc-ref},
7288 @code{rassq-ref}, and @code{rassv-ref}. See @code{alist-ref}
7289 entry above for the rationale. Be aware of the order of
7290 optional arguments, which differs from @code{rassoc-ref}.
7291 @c JP
7292 註: この手続きは旧式の@code{rassoc-ref}、@code{rassq-ref}、@code{rassv-ref}を
7293 置き換えるものです。省略可能引数の順序が@code{rassoc-ref}と異なっていることに
7294 注意してください。
7295 @c COMMON
7296 @end defun
7297
7298 @defun alist-set! alist key val :optional key=
7299 @c EN
7300 Returns an alist who has @code{(key . val)} pair added to the @code{alist}.
7301 If @code{alist} already has an element with @var{key}, the element's
7302 @emph{cdr} is destructively modified for @var{val}.
7303 If @var{alist} doesn't have an element with @var{key}, a new pair
7304 is created and appended in front of @var{alist}; so you should use
7305 the return value to guarantee @var{key}-@var{val} pair is added.
7306
7307 The keys are compared with @var{key=}, whose default is @code{equal?}.
7308
7309 If you don't want to mutate the original alist, use @code{alist-adjoin} below.
7310 @c JP
7311 @code{alist}に@code{(key . val)}のペアが追加された連想リストを返します。
7312 @code{alist}がすでに@var{key}をキーとする要素を持っている場合、
7313 その要素の@emph{cdr}は破壊的に@var{val}に変更されます。
7314 @var{alist}が@var{key}をキーとする要素を持っていない場合は、
7315 新しいペアが作成され、@var{alist}の一番前に追加されます。
7316 したがって、@var{key}-@var{val}ペアが追加されたことを保証するために
7317 その戻り値を使うべきです。
7318
7319 キーは@var{key=}によって比較されます。デフォルトは@code{equal?}です。
7320
7321 元のalistを破壊したくない場合は、下の@code{alist-adjoin}を使ってください。
7322 @c COMMON
7323 @end defun
7324
7325 @defun alist-adjoin alist key val :optional key=
7326 @c EN
7327 A functional variation of @code{alist-set!}.
7328
7329 If @var{alist} contains an entry with @var{key}, returns a new associative list
7330 where the value of the @var{key} is replaced for @var{val}. The order
7331 of entries in @var{alist} is preserved. If @var{alist} doesn't contain
7332 the entry, it returns @code{(acons @var{key} @var{val} @var{alist})}.
7333
7334 The original @var{alist} is left unmodified. The returned associative list may
7335 share a part of its tail with the original @var{alist}, however.
7336
7337 The optional @var{key=} argument is a procedure with two arguments
7338 to be used to compare the keys; the default is @code{equal?}.
7339 @c JP
7340 @code{alist-set!}の非破壊的バージョンです。
7341
7342 @var{alist}が@var{key}をキーとするエントリを持っていた場合、その値を@var{val}に
7343 変えた新たな連想リストを作って返します。@var{alist}中のエントリの順序は保存されます。
7344 もし@var{alist}中に@var{key}をキーとするエントリが無い場合は、
7345 @code{(acons @var{key} @var{val} @var{alist})}が返されます。
7346
7347 元の@var{alist}は変更されません。但し、返された連想リストは@var{alist}と末尾部分を
7348 共有するかもしれません。
7349
7350 @var{key=}引数は2引数を取る手続きで、キーの比較に使われます。
7351 省略された場合は@code{equal?}が使われます。
7352 @c COMMON
7353 @end defun
7354
7355 @defun alist-delete key alist :optional key=
7356 @defunx alist-delete! key alist :optional key=
7357 [R7RS list]
7358 @c EN
7359 Deletes all cells in @var{alist} whose key is the same as @var{key}.
7360 Comparison is done by a procedure @var{key=}. The default is @code{equal?}.
7361
7362 The linear-update version @code{alist-delete!} may or may not modify
7363 @var{alist}.
7364 @c JP
7365 @var{alist} から @var{key}と同じキーをもつすべてのセルを削除します。
7366 比較は @var{key=} で行います。これのデフォルト値は @code{equal?} です。
7367
7368 その場で更新を行うバージョン @code{alist-delete!} は元の
7369 @var{alist} を変更してしまうことがあります。
7370 @c COMMON
7371
7372 @c EN
7373 Note the order of arguments: Unfortunately, this procedure
7374 doesn't follow the rule to take @var{alist} as the first argument
7375 This is defined in srfi-1 and followed @code{assoc}.
7376 @c JP
7377 引数順についての注意: 残念なことに、この手続きは@var{alist}を最初の引数に取るという
7378 原則から外れています。この手続きはSRFI-1で定義され、それは@code{assoc}
7379 の引数順に合わせました。
7380 @c COMMON
7381 @end defun
7382
7383 @defun alist-merge [key=] reducer alist1 alist2 @dots{}
7384 @c EN
7385 Returns a new assoc list that contains all keys in
7386 @var{alist1} @var{alist2} @dots{}. If more than one input alist
7387 have the same key, they are merged to a single entry using @var{reducer}
7388 as follows:
7389 Suppose values of those entries are @var{x}, @var{y}, and @var{z},
7390 in the order of appearance in the input alists. Then the
7391 value of the resulting entry is
7392 @code{(@var{reducer} @var{x} (@var{reducer} @var{y} @var{z})}.
7393 @c JP
7394 @var{alist1} @var{alist2} @dots{} に含まれている全てのキーを含むような
7395 新たな連想リストを返します。同じキーを持つエントリが複数の入力連想リストに
7396 含まれていた場合は、その値は@var{reducer}を用いて次のとおり計算されます:
7397 入力に含まれる同じキーを持つエントリの値が順に@var{x}、@var{y}、@var{z}であったとすると、
7398 結果の連想リストの値は
7399 @code{(@var{reducer} @var{x} (@var{reducer} @var{y} @var{z})}。
7400 @c COMMON
7401
7402 @example
7403 (alist-merge + '((a . 1) (b . 2)) '((c . 3) (a . 4)) '((b . 5)))
7404 @result{} ((a . 5) (b . 7) (c . 3))
7405 (alist-merge string=? append
7406 '(("a" 1) ("b" 2) ("c" 3))
7407 '(("b" 4) ("d" 5))
7408 '(("c" 6)))
7409 @result{} (("a" 1) ("b" 2 4) ("c" 3 6) ("d" 5))
7410 @end example
7411
7412 @c EN
7413 The order of entries of the result preserves the order of the input,
7414 except the duplicate key entries are merged into the first one.
7415 @c JP
7416 結果のエントリの順序は、重複キーのエントリが最初のエントリにマージされていること以外は
7417 入力の連想リストの順序を保存します。
7418 @c COMMON
7419
7420 @c EN
7421 Note: This assumes each alist doesn't have duplicate keys in itself.
7422 To gether entries of the same keys in an alist, you can use
7423 @code{group-collection->alist} in @code{gauche.collection}
7424 (@pxref{Collection framework}).
7425 @c JP
7426 註: この手続きは、それぞれのalist内には重複するキーのエントリが無いことを仮定しています。
7427 ひとつのalist内で同じキーを持つエントリを集めるには、
7428 @code{gauche.collection}の@code{group-collection->alist}が使えます
7429 (@ref{Collection framework}参照)。
7430 @c COMMON
7431 @end defun
7432
7433 @defun alist-update-in alist keys proc :optional key= default
7434 @c EN
7435 This procedure allows to update a nested associative list.
7436 The @var{alist} argument is a (possibly nested) associative list,
7437 @var{keys} are a list of keys, and @var{proc} is a procedure
7438 that takes one argument. First, the keys are looked up
7439 recursively in @var{alist}; then its value is passed to @var{proc}.
7440 The return value is a new (nested) associative list where the value
7441 pointed by @var{keys} is replaced with the return value of @var{proc}.
7442 @c JP
7443 この手続きは、ネストした連想リストを更新するのに使えます。
7444 @var{alist}はネストした連想リストです。
7445 @var{keys}はキーのリストで、@var{proc}は1引数を取る手続きです。
7446 まず、@var{keys}にあるキーを順に使って、ネストした連想リストから
7447 値が取り出され、@var{proc}に渡されます。
7448 手続きの戻り値は新しいネストした連想リストで、該当するエントリの値が
7449 @var{proc}の戻り値に置き換えられたものとなります。
7450 @c COMMON
7451
7452 @example
7453 (assoc-update-in '((a (b . 1) (c . 2))) '(a c) (cut + <> 1))
7454 @result{} ((a (b . 1) (c . 3))
7455 @end example
7456
7457 @c EN
7458 The order of entries are preserved. The original @var{alist}
7459 is left unmodified, but the returned value may share a part of
7460 the structure with @var{alist}.
7461 @c JP
7462 エントリの順序は保存されます。元の@var{alist}は変更を受けませんが、
7463 戻り値と部分構造を共有するかもしれません。
7464 @c COMMON
7465
7466 @c EN
7467 If @var{alist} doesn't have the entry specified by @var{keys},
7468 a new entry is added. A new entry is added at the beginning of
7469 the sequence where specified key didn't exist.
7470 @c JP
7471 @var{alist}が@var{keys}で指定されるエントリを持たない場合は新たなエントリが
7472 追加されます。新たなエントリは、キーが存在しないシーケンスの先頭に付け加えられます。
7473 @c COMMON
7474
7475 @example
7476 (assoc-update-in '((a (b . 1) (c . 2))) '(a d e) (^_ 99))
7477 @result{} ((a (d (e . 99)) (b . 1) (c . 3)))
7478 @end example
7479
7480 @c EN
7481 The @var{default} argument is passed to @var{proc} when there's
7482 no entry with specified keys. If omitted, @code{#f} is assumed.
7483 @c JP
7484 @var{default}引数は、キーに対応するエントリが存在しなかった場合に@var{proc}に
7485 渡されます。省略値は@code{#f}です。
7486 @c COMMON
7487
7488 @c EN
7489 The optional @var{key=} argument is a procedure with two arguments
7490 to be used to compare the keys; the default is @code{equal?}.
7491 @c JP
7492 @var{key=}引数は2引数を取る手続きで、キーの比較に使われます。
7493 省略された場合は@code{equal?}が使われます。
7494 @c COMMON
7495
7496 @c EN
7497 Note: For destructively updating general nested aggregate structures,
7498 setter of @code{~} is handy (@pxref{Universal accessor}). You can modify
7499 an entry in a hashtable in a vector in a list, for example. Associative
7500 list is a bit special, since you can't distinguish it from lists
7501 (thus @code{~} can't be used), and it is mostly used in functional way.
7502 So we added a special update procedure.
7503 @c JP
7504 註: ネストした集合データ構造の一部を破壊的に更新するには、
7505 @code{~}のセッタが便利です(@ref{Universal accessor}参照)。
7506 例えばハッシュテーブルのベクタのリスト、から一番奥のハッシュテーブルのエントリを
7507 更新することが出来ます。しかし連想リストはちょっと特殊で、リストと型的に区別
7508 できないため、@code{~}が使えません。連想リストはまた、関数的に使われることも
7509 多いため、専用の更新手続きを用意しました。
7510 @c COMMON
7511 @end defun
7512
7513 @c EN
7514 @subsubheading Deprecated procedures
7515 @c JP
7516 @subsubheading 非推奨の手続き
7517 @c COMMON
7518
7519 @c EN
7520 The following procedures are deprecated for the naming consistency.
7521 Except a handful historical procedures (@code{assoc} etc.), associative
7522 list operations are now named @code{alist-*} and takes alist as the
7523 first argument as long as it is relevant.
7524 @c JP
7525 以下の手続きは、名前の一貫性のために非推奨となったものです。
7526 @var{assoc}のような歴史的ないくつかの手続き以外は、現在の連想リスト操作は
7527 @code{alist-*}と命名され、原則として連想リストを第一引数に取ります。
7528 @c COMMON
7529
7530 @defun assoc-ref alist key :optional default key=
7531 @defunx assq-ref alist key :optional default
7532 @defunx assv-ref alist key :optional default
7533 @c DEPRECATED
7534 @c EN
7535 @code{(assoc-ref alist key default key=)} @equiv{}
7536 @code{(alist-ref alist key key= default)}. Note the order of
7537 the optional arguments.
7538
7539 @code{(assq-ref alist key default)} @equiv{}
7540 @code{(alist-ref alist key eq? default)}.
7541
7542 @code{(assv-ref alist key default)} @equiv{}
7543 @code{(alist-ref alist key eqv? default)}.
7544 @c JP
7545 @code{(assoc-ref alist key default key=)} @equiv{}
7546 @code{(alist-ref alist key key= default)}.
7547 省略可能引数の順序に注意。
7548
7549 @code{(assq-ref alist key default)} @equiv{}
7550 @code{(alist-ref alist key eq? default)}.
7551
7552 @code{(assv-ref alist key default)} @equiv{}
7553 @code{(alist-ref alist key eqv? default)}.
7554 @c COMMON
7555 @end defun
7556
7557 @defun rassoc-ref alist val :optioanl default val=
7558 @defunx rassq-ref alist val :optional default
7559 @defunx rassv-ref alist val :optional default
7560 @c DEPRECATED
7561 @c EN
7562 @code{(rassoc-ref alist val default val=)} @equiv{}
7563 @code{(alist-key alist val val= default)}. Note the order of
7564 the optional arguments.
7565
7566 @code{(rassq-ref alist val default)} @equiv{}
7567 @code{(alist-key alist val eq? default)}.
7568
7569 @code{(rassv-ref alist key default)} @equiv{}
7570 @code{(alist-key alist val eqv? default)}.
7571 @c JP
7572 @code{(rassoc-ref alist val default val=)} @equiv{}
7573 @code{(alist-key alist val val= default)}.
7574 省略可能引数の順序に注意。
7575
7576 @code{(rassq-ref alist val default)} @equiv{}
7577 @code{(alist-key alist val eq? default)}.
7578
7579 @code{(rassv-ref alist key default)} @equiv{}
7580 @code{(alist-key alist val eqv? default)}.
7581 @c COMMON
7582 @end defun
7583
7584 @defun assoc-set! alist key val :optional key=
7585 @defunx assq-set! alist key val
7586 @defunx assv-set! alist key val
7587 @c DEPRECATED
7588 @code{(assoc-set! alist key key=)} @equiv{} @code{(alist-set! alist key key=)}.
7589
7590 @code{(assq-set! alist key)} @equiv{} @code{(alist-set! alist key eq?)}.
7591
7592 @code{(assv-set! alist key)} @equiv{} @code{(alist-set! alist key eqv?)}.
7593 @end defun
7594
7595 @defun assoc-adjoin alist key val :optional key=
7596 @c DEPRECATED
7597 @c EN
7598 Same as @code{alist-adjoin}.
7599 @c JP
7600 @code{alist-adjoin}と同じです。
7601 @c COMMON
7602 @end defun
7603
7604 @defun assoc-update-in alist keys proc :optional default key=
7605 @c DEPRECATED
7606 @code{assoc-update-in alist keys proc default key=}
7607 @equiv{}
7608 @code{alist-update-in alist keys proc key= default}
7609
7610 @c EN
7611 Note the order of optional arguments.
7612 @c JP
7613 省略可能引数の順序に注意。
7614 @c COMMON
7615 @end defun
7616
7617 @node Extended pairs and pair attributes, , Association lists, Pairs and lists
7618 @subsection Extended pairs and pair attributes
7619 @c NODE 拡張ペアとペア属性
7620
7621 @c EN
7622 Gauche has a special kind of pairs, called @emph{extended pairs}.
7623 It behaves exactly the same as ordinary pairs, but you can associate
7624 an attribute list to it. Gauche uses it to keep source-code
7625 location information, for example.
7626 @c JP
7627 Gaucheは、拡張ペア (extended pair) と呼ばれる特別なペアを持っています。
7628 これは通常のペアと同じように振る舞いますが、属性リストを付加することができます。
7629 例えば、Gaucheはソースコードの位置情報を保持するのに拡張ペアを使っています。
7630 @c COMMON
7631
7632 @c EN
7633 Extended pairs don't incur any overhead in accessing its car/cdr;
7634 @code{set-car!}
7635 and @code{set-cdr!} has a little overhead (another reason you should avoid
7636 mutation!).
7637 Internally it takes up twice
7638 of memory than the ordinary pairs.
7639 @c JP
7640 拡張ペアのcar/cdrへのアクセスにオーバーヘッドは全くありません。
7641 @code{set-car!}と@code{set-cdr!}
7642 には少しだけオーバヘッドがあります (できるだけ副作用を避けましょう!)。
7643 内部的に、拡張ペアは通常のペアの倍のメモリを使います。
7644 @c COMMON
7645
7646 @c EN
7647 Pair attributes are not written out in the external representation,
7648 and not copied by @code{copy-list} and many other list procedures
7649 that constructs the output list from the input list.
7650 That is, they are easily lost. Use them for the ancillary information
7651 which is nice to have but not mandatory.
7652 @c JP
7653 ペア属性は外部表現には書き出されませんし、@code{copy-list}や、出力リストを
7654 入力リストを元に新たに組み立てる多くのリスト手続きでコピーされません。
7655 つまり、ペア属性は簡単に失われます。「あったら良いけど、必須ではない」という
7656 補助的な情報に使うのが良いでしょう。
7657 @c COMMON
7658
7659 @c EN
7660 Keep in mind that code using extended pairs is not easily ported to
7661 other Scheme implementations, although the
7662 feature can be emulated with a separate weak hash table.
7663 @c JP
7664 また、拡張ペアを使ったコードは、弱参照ハッシュテーブルでエミュレートできるとはいえ、
7665 他のScheme処理系には簡単に移植できないことに留意してください。
7666 @c COMMON
7667
7668 @defun extended-pair? obj
7669 @c EN
7670 Returns @code{#t} iff @var{obj} is an extended pair.
7671 @c JP
7672 @var{obj}が拡張ペアなら@code{#t}を、そうでなければ@code{#f}を返します。
7673 @c COMMON
7674 @end defun
7675
7676 @defun extended-cons car cdr :optional attrs
7677 @c EN
7678 Returns an extended pair of @var{car} and @var{cdr}.
7679 If an optional @var{attrs} argument is given, it must be an alist,
7680 specifying initial pair attributes. By default, the pair attributes
7681 of the created extended pair is empty.
7682 @c JP
7683 @var{car}と@var{cdr}からなる拡張ペアを作って返します。
7684 @var{attrs}引数が与えられた場合、
7685 それはペア属性の初期値を指定する連想リストでなければなりません。
7686 デフォルトでは作られる拡張ペアのペア属性は空です。
7687 @c COMMON
7688 @end defun
7689
7690 @defun extended-list obj obj2 @dots{}
7691 @c EN
7692 Creates and returns a list of @var{obj} @var{obj2} @dots{}, but its
7693 first pair is an extended pair. Note that the subsequent pairs are
7694 ordinary pairs.
7695 @c JP
7696 @var{obj} @var{obj2} @dots{}からなるリストを作って返しますが、
7697 最初のペアが拡張ペアになっています。二番目以降のペアは通常のペアです。
7698 @c COMMON
7699 @end defun
7700
7701 @defun pair-attributes pair
7702 @c EN
7703 Returns pair attributes of @var{pair} as an alist.
7704 You can pass an ordinary pair, in which case an empty list is returned.
7705 @c JP
7706 @var{pair}のペア属性を連想リストとして返します。
7707 通常のペアを引数に渡すこともできます。その場合は常に空リストが返ります。
7708 @c COMMON
7709
7710 @example
7711 (pair-attributes (extended-cons 'a 'b '((c . d) (e . f))))
7712 @result{} ((c . d) (e . f))
7713
7714 (pair-attributes (cons 'a 'b)
7715 @result{} ()
7716 @end example
7717 @end defun
7718
7719 @defun pair-attribute-get pair key :optional default
7720 @c EN
7721 Returns the value associated to the key @var{key} in the pair attributes
7722 of @var{pair}. @var{Key} can be any Scheme object, and compared with @code{eq?}.
7723 If there's no value associated with the given key,
7724 @var{default} is returned if it is given, otherwise an error is signaled.
7725
7726 You can pass an ordinary pair as @var{pair}; in that case, it is treated
7727 with empty pair attributes.
7728 @c JP
7729 @var{pair}のペア属性のうち、キー@var{key}に結びつけられた値を返します。
7730 @var{key}は任意のSchemeオブジェクトで、@code{eq?}で比較されます。
7731 キーに結びついた値がない場合、@var{default}が与えられていればそれが返され、
7732 与えられていなければエラーが投げられます。
7733
7734 通常のペアを@var{pair}に渡すこともできます。その場合、ペア属性は空として扱われます。
7735 @c COMMON
7736 @end defun
7737
7738 @defun pair-attribute-set! pair key value
7739 @c EN
7740 Adds a pair attribute of @var{key} with @var{value} to an extended pair
7741 @var{pair}. @var{Key} and @var{value} can be any Scheme object.
7742 An error is thrown if @var{pair} is not an exteded pair.
7743 @c JP
7744 拡張ペア@var{pair}のペア属性@var{key}に値@var{value}をセットします。
7745 @var{key}と@var{value}は任意のSchemeオブジェクトです。
7746 @var{pair}が拡張ペアでなければエラーが投げられます。
7747 @c COMMON
7748
7749 @c EN
7750 This procedure does not mutate the exising alist, but rather makes
7751 a necessary copy. The pair attributes
7752 are not supposed to be mutated frequently.
7753 @c JP
7754 この手続きは既存の連想リスト自体は変更せず、必要に応じてコピーします。
7755 ペア属性は頻繁に変更される運用を想定していません。
7756 @c COMMON
7757 @end defun
7758
7759
7760 @c ----------------------------------------------------------------------
7761 @node Symbols, Keywords, Pairs and lists, Core library
7762 @section Symbols
7763 @c NODE シンボル
7764
7765 @deftp {Builtin Class} <symbol>
7766 @clindex symbol
7767 @c EN
7768 A class for symbols.
7769 @c JP
7770 シンボルを表すクラスです。
7771 @c COMMON
7772 @end deftp
7773
7774 @deftp {Reader Syntax} @code{|@i{name}|}
7775 @lxindex |
7776 [R7RS]
7777 @c EN
7778 Denotes a symbol that has weird name, including the characters
7779 that are not usually allowed in symbols. It can also include
7780 hex-escaped characters.
7781 @c JP
7782 シンボルの定義では通常許されないような文字を使った妙な名前のシンボルを表記するのに
7783 使う構文です。16進数エスケープ表記を含めることもできます。
7784 @c COMMON
7785
7786 @example
7787 @c EN
7788 ;; @r{A symbol with spaces in its name}
7789 @c JP
7790 ;; @r{空白を名前に含むシンボル}
7791 @c COMMON
7792 '|this is a symbol| @result{} |this is a symbol|
7793
7794 @c EN
7795 ;; @r{Unicode codepoint can be used following backslash-x escape,}
7796 ;; @r{and terminated by semicolon.}
7797 @c JP
7798 ;; @r{Unicodeコードポイントを、バックスラッシュとxからなるエスケープに続けて}
7799 ;; @r{書くこともできます。セミコロンで終端します。}
7800 @c COMMON
7801 '|\x3bb;| @result{} λ
7802 @end example
7803
7804 @c EN
7805 If the interpreter is running in case-insensitive mode, this syntax
7806 can be used to include uppercase characters in a symbol
7807 (@pxref{Case-sensitivity}).
7808 @c JP
7809 インタプリタが大文字小文字を区別しないモードで走っている場合は、
7810 大文字を含むシンボルを表記するときにも使えます (@ref{Case-sensitivity}参照)。
7811 @c COMMON
7812 @end deftp
7813
7814 @deftp {Reader Syntax} @code{#:@i{name}}
7815 @c EN
7816 Denotes @emph{uninterned} symbol. Uninterned symbols can be created
7817 by @code{gensym} or @code{string->uninterned-symbol}.
7818 @c JP
7819 「インターンされていない」シンボルを表記します。インターンされていないシンボルは
7820 @code{gensym}か@code{string->uninterned-symbol}で作ることができます。
7821 @c COMMON
7822
7823 @c EN
7824 Uninterned symbols are mainly for legacy macros to avoid
7825 variable conflicts. They are not registered in the internal
7826 dictionary, so such symbols with the same name can't be @code{eq?}.
7827 @c JP
7828 インターンされていないシンボルは、良く伝統的なマクロで
7829 変数衝突を避けるために使われます。インターンされていないシンボルは
7830 内部のシンボルのテーブルに登録されないため、同じ名前のシンボルでも
7831 @code{eq?}になりません。
7832 @c COMMON
7833
7834 @example
7835 (eq? '#:foo '#:foo) @result{} #f
7836 (eq? '#:foo 'foo) @result{} #f
7837 @end example
7838
7839 @c EN
7840 To preserve @code{eq?}-ness of uninterened symbols,
7841 you need to use @code{write-shared} which
7842 shows shared structures.
7843 @c JP
7844 インターンされていないシンボルが含まれるS式を、
7845 シンボルの同一性を保って表示するには、
7846 @code{write-shared}を使います。
7847 @c COMMON
7848
7849 @example
7850 (write-shared (let1 s '#:foo (list s s)))
7851 @result{} @r{prints} (#0=#:foo #0#)
7852
7853 (write-shared (let ((s '#:foo) (t '#:foo)) (list s t s t)))
7854 @result{} @r{prints} (#0=#:foo #1=#:foo #0# #1#)
7855 @end example
7856 @end deftp
7857
7858
7859 @defun symbol? obj
7860 [R7RS base]
7861 @c EN
7862 Returns true if and only if @var{obj} is a symbol.
7863 @c JP
7864 @var{obj}がシンボルなら@code{#t}を返します。
7865 @c COMMON
7866 @example
7867 (symbol? 'abc) @result{} #t
7868 (symbol? 0) @result{} #f
7869 (symbol? 'i) @result{} #t
7870 (symbol? '-i) @result{} #f
7871 (symbol? '|-i|) @result{} #t
7872 @end example
7873 @end defun
7874
7875 @defun symbol-interned? symbol
7876 @c EN
7877 Returns @code{#t} if @var{symbol} is an interned symbol,
7878 @code{#f} if it is an uninterned symbol. An error is signaled
7879 if @var{symbol} is not a symbol.
7880 @c JP
7881 シンボル@var{symbol}がインターンされていれば@code{#t}を、
7882 そうでなければ@code{#f}を返します。シンボルでないものが渡された場合はエラーとなります。
7883 @c COMMON
7884 @end defun
7885
7886 @defun symbol=? a b c @dots{}
7887 [R7RS base]
7888 @c EN
7889 Every argument must be a symbol. Returns @code{#t} iff
7890 every pair of arguments are @code{eq?} to each other.
7891 @c JP
7892 全ての引数はシンボルでなければなりません。引数のどの二つの組み合わせを取っても
7893 それが@code{eq?}である時に限り、@code{#t}が返ります。
7894 @c COMMON
7895 @end defun
7896
7897 @defun symbol->string symbol
7898 [R7RS base]
7899 @c EN
7900 Returns the name of @var{symbol} in a string. Returned
7901 string is immutable.
7902 @c JP
7903 @var{symbol}の名前を文字列で返します。返される文字列は変更不可です。
7904 @c COMMON
7905
7906 @example
7907 (symbol->string 'foo) @result{} foo
7908 @end example
7909 @end defun
7910
7911 @defun string->symbol string
7912 [R7RS base]
7913 @c EN
7914 Returns a symbol whose name is a string @var{string}.
7915 @var{String} may contain weird characters.
7916 @c JP
7917 文字列@var{string}を名前に持つシンボルを返します。
7918 @c COMMON
7919
7920 @example
7921 (string->symbol "a") @result{} a
7922 (string->symbol "A") @result{} A
7923 (string->symbol "weird symbol name") @result{} |weird symbol name|
7924 @end example
7925 @end defun
7926
7927 @defun string->uninterned-symbol string
7928 @c EN
7929 Like @code{string->symbol}, but the created symbol is uninterned.
7930 @c JP
7931 @code{string->symbol}と似ていますが、作られたシンボルはインターンされません。
7932 @c COMMON
7933
7934 @example
7935 (string->uninterned-symbol "a") @result{} #:a
7936 @end example
7937 @end defun
7938
7939
7940 @defun gensym :optional prefix
7941 @c EN
7942 Returns a fresh, uninterned symbol. The returned symbol can never
7943 be @code{eq?} to other symbol within the process.
7944 If @var{prefix} is given, which must be a string, it is used
7945 as a prefix of the name of the generated symbol. It is mainly for
7946 the convenience of debugging.
7947 @c JP
7948 インターンされてない、新しいシンボルを作って返します。
7949 返されるシンボルは、他のシンボルとは決して@code{eq?}にならないことが保証されます。
7950 @var{prefix}が与えられた場合は、それは文字列でなければならず、
7951 それが作られるシンボルのプレフィクスに使われます。これは主としてデバッグを
7952 容易にするためのものです。
7953 @c COMMON
7954 @end defun
7955
7956 @defun symbol-sans-prefix symbol prefix
7957 @c EN
7958 Both @var{symbol} and @var{prefix} must be symbols.
7959 If the name of @var{prefix} matches the beginning part of the
7960 name of @var{symbol}, this procedure returns a symbol whose
7961 name is the name of @var{symbol} without the matched prefix.
7962 Otherwise, it returns @code{#f}.
7963 @c JP
7964 @var{symbol}と@var{prefix}は共にシンボルでなければなりません。
7965 @var{prefix}が@var{symbol}の先頭部分にマッチした場合、
7966 @var{symbol}からマッチ部分を取り除いた名前を持つシンボルを返します。
7967 マッチしない場合は@code{#f}を返します。
7968 @c COMMON
7969
7970 @example
7971 (symbol-sans-prefix 'foo:bar 'foo:) @result{} bar
7972 (symbol-sans-prefix 'foo:bar 'baz:) @result{} #f
7973 @end example
7974 @end defun
7975
7976 @defun symbol-append interned? objs @dots{}
7977 @defunx symbol-append objs @dots{}
7978 @c EN
7979 Returns a symbol with the name which is a concatenation of
7980 string representation of @var{objs}.
7981
7982 If the first argument is a boolean, it is recognized as the
7983 first form; the first argument specifies whether the resulting
7984 symbol is interned or not.
7985
7986 Each other argument is converted to a string as follows:
7987 If it is a keyword, its name (with the preceding @code{:}) is used.
7988 For all other objects, @code{x->string} is used. (The special treatment
7989 of keyword is to keep the consistency before and after
7990 keyword-symbol integration. @xref{Keyword and symbol integration}, for
7991 the details.)
7992
7993 This is upper-compatible to Bigloo's same name procedure, which
7994 only allows symbols as the arguments and the result is always interned.
7995 @c JP
7996 @var{objs}の文字列表記をつなげた名前を持つシンボルを返します。
7997
7998 最初の引数が真偽値の場合は、最初の形式と解釈されます。@var{interned?}引数は
7999 結果のシンボルがインターンされているかどうかを指定します。
8000
8001 それ以外の引数はそれぞれ次のとおり変換されます:キーワードであれば
8002 (先頭の@code{:}を含む)名前に、それ以外は@code{x->string}を適用した結果に。
8003 (キーワードを特別扱いするのは、キーワード-シンボル統合の後でも動作が
8004 変わらないようにするためです。詳しくは@ref{Keyword and symbol integration}を
8005 参照。)
8006
8007 これは、Biglooにある同名の手続きの上位互換になっています。Bigloo版は
8008 シンボルのみを引数に許し、また結果は常にインターンされます。
8009 @c COMMON
8010
8011 @example
8012 (symbol-append 'ab 'cd) @result{} abcd
8013 (symbol-append 'ab ':c 30) @result{} ab:c30
8014 (symbol-append #f 'g 100) @result{} #:g100
8015 @end example
8016 @end defun
8017
8018
8019 @c ----------------------------------------------------------------------
8020 @node Keywords, Characters, Symbols, Core library
8021 @section Keywords
8022 @c NODE キーワード
8023
8024 @deftp {Builtin Class} <keyword>
8025 @clindex keyword
8026 @c EN
8027 Keywords are a subtype of symbols that are automatically bound
8028 to itself.
8029 It is extensively used in named arguments (keyword arguments),
8030 and keyword-value list.
8031
8032 See @ref{Making procedures} for how Gauche supports keyword
8033 arguments, and @code{let-keywords} macro (@ref{Optional argument parsing})
8034 for parsing keyword-value list manually.
8035
8036 Keywords used to be a disjoint type from symbols.
8037 Since it isn't conformant to R7RS, in which symbols can begin
8038 with @code{:}, we've introduced two modes since 0.9.5; keywords
8039 can be a disjoint type of its own, or it can be a subtype of symbols.
8040
8041 The behavior can be switched by environment variables. If the environment
8042 variable @code{GAUCHE_KEYWORD_DISJOINT} is defined when @code{gosh} starts
8043 up, keywords and symbols are disjoint. Otherwise, if the environment
8044 variable @code{GAUCHE_KEYWORD_IS_SYMBOL} is defined, keywords are
8045 a subtype of symbols.
8046
8047 The default behavior when neither environment variables are defined
8048 has been switched since 0.9.8. @code{GAUCHE_KEYWORD_DISJOINT} was assumed
8049 in 0.9.7 and before, while @code{GAUCHE_KEYWORD_IS_SYMBOL} is assumed
8050 in 0.9.8 and after.
8051
8052 Most typical code run in either mode, but there can be some code
8053 that behaves differently. @xref{Keyword and symbol integration},
8054 for effect of the change.
8055
8056 In future we'll stop supporting @code{GAUCHE_KEYWORD_DISJOINT},
8057 so we recommend you to ensure applications to run on the current
8058 default mode.
8059 @c JP
8060 キーワードは、自動的に自分自身に束縛されるシンボルのサブタイプです。
8061 名前つき引数(キーワード引数)や、キーワード-値のリストで広く使われて
8062 います。
8063
8064 Gaucheにおけるキーワード引数のサポートについては@ref{Making procedures}を、
8065 また独自にキーワード-値リストをパーズする方法については
8066 @code{let-keywords} マクロ(@ref{Optional argument parsing}) も参照して下さい。
8067
8068 キーワードはかつてはシンボルと独立した型でしたが、それは
8069 @code{:}で始まる識別子もシンボルとして読まれるR7RSとは非互換でした。
8070 そこで、0.9.5からGaucheは二つのモードを持つようになりました。
8071 キーワードとシンボルが別の型になるモードと、キーワードがシンボルのサブタイプになる
8072 モードです。
8073
8074 これらのモードは環境変数によって切り替えられます。
8075 環境変数@code{GAUCHE_KEYWORD_DISJOINT}が@code{gosh}起動時に定義されていたら、
8076 キーワードとシンボルは別の型になります。
8077 そうでなく、環境変数@code{GAUCHE_KEYWORD_IS_SYMBOL}が定義されていたら、
8078 キーワードはシンボルのサブタイプになります。
8079
8080 どちらの環境変数も定義されていない場合のデフォルトの動作は、0.9.8で変更になりました。
8081 0.9.7以前は@code{GAUCHE_KEYWORD_DISJOINT}の動作がデフォルトですが、
8082 0.9.8以降は@code{GAUCHE_KEYWORD_IS_SYMBOL}がデフォルトになっています。
8083
8084 ほとんどの典型的なコードはどちらのモードでも動きますが、
8085 異なる振る舞いをするコードもあります。
8086 二つのモードの違いについては@ref{Keyword and symbol integration}を参照してください。
8087
8088 将来的に、@code{GAUCHE_KEYWORD_DISJOINT}のサポートは無くなる予定です。
8089 今のうちに、現在のデフォルトモードでアプリケーションが走ることを
8090 確認しておくことをお勧めします。
8091 @c COMMON
8092 @end deftp
8093
8094 @deftp {Reader Syntax} @code{:@var{name}}
8095 @c EN
8096 Read to a keyword whose name is @var{:name}.
8097 @c JP
8098 名前が @var{:name} であるキーワードとして読み込まれます。
8099 @c COMMON
8100 @end deftp
8101
8102 @defun keyword? obj
8103 @c EN
8104 Returns @code{#t} if @var{obj} is a keyword.
8105 @c JP
8106 @var{obj} がキーワードであれば、@code{#t} を返します。
8107 @c COMMON
8108 @end defun
8109
8110 @defun make-keyword name
8111 @c EN
8112 Returns a keyword whose name is @var{name} prepended by @code{:}.
8113 The @var{name} argument can be a string or a symbol.
8114 @c JP
8115 @var{name}の前に@code{:}を付加した名前を持つキーワードを返します。
8116 @var{name}には文字列かシンボルが許されます。
8117 @c COMMON
8118 @example
8119 (make-keyword "foo") @result{} :foo
8120
8121 (make-keyword 'foo) @result{} :foo
8122 @end example
8123 @end defun
8124
8125 @defun keyword->string keyword
8126 @c EN
8127 Returns the name (without the initial @code{:}) of the keyword @var{keyword}, in a string.
8128 @c JP
8129 キーワード @var{keyword} の(先頭の@code{:}を除いた)名前を文字列で返します。
8130 @c COMMON
8131 @example
8132 (keyword->string :foo) @result{} "foo"
8133 @end example
8134 @end defun
8135
8136 @defun get-keyword key kv-list :optional fallback
8137 @c EN
8138 A useful procedure to extract a value from key-value list.
8139 A key-value list @var{kv-list} must contains even number of elements;
8140 the first, third, fifth @dots{} elements are regarded as keys,
8141 and the second, fourth, sixth @dots{} elements are the values of
8142 the preceding keys.
8143
8144 This procedure looks for @var{key} from the keys, and if it finds one,
8145 it returns the corresponding value.
8146 If there are more than one matching keys, the leftmost one is taken.
8147 If there is no matching key, it returns @var{fallback} if provided,
8148 or signals an error otherwise.
8149
8150 It is an error if @var{kv-list} is not a proper, even-number element list.
8151
8152 Actually, `keywords' in the keyword-value list and the @var{key} argument
8153 need not be a keyword---it can be any Scheme object. Key comparison
8154 is done by @code{eq?}.
8155
8156 This procedure is taken from STk.
8157 @c JP
8158 キー-値のリストから値を取り出すのに便利な手続きです。
8159 キー-値のリスト @var{kv-list} は偶数個の要素を持たなければなりません。
8160 1つ目、3つ目、5つ目、@dots{} の要素はキーとして扱われ、
8161 2つ目、4つ目、6つ目、@dots{} の要素は、その前の要素をキーとした値と
8162 なります。
8163
8164 この手続きは、キーの集合から @var{key} を探して、それが見つかれば、
8165 対応する値を返します。
8166 2つ以上のキーにマッチしたら、最左のものとなります。
8167 マッチするキーがない場合、@var{fallback} が与えられていればそれを
8168 返し、さもなければエラーを通知します。
8169
8170 @var{kv-list} が正しい偶数個の要素を持つリストでない場合は、エラーに
8171 なります。
8172
8173 キーワード-値リストの `キーワード' と、@var{key} 引数は、実際には
8174 キーワードである必要はありません。いかなる Scheme オブジェクトで
8175 あっても良いです。キーの比較は、@code{eq?} によって行われます。
8176
8177 この手続きは、STk から導入されました。
8178 @c COMMON
8179
8180 @example
8181 (get-keyword :y '(:x 1 :y 2 :z 3))
8182 @result{} 2
8183 (get-keyword 'z '(x 1 y 2 z 3))
8184 @result{} 3
8185
8186 (get-keyword :t '(:x 1 :y 2 :z 3))
8187 @result{} #<error>
8188 (get-keyword :t '(:x 1 :y 2 :z 3) #f)
8189 @result{} #f
8190 @end example
8191 @end defun
8192
8193 @defmac get-keyword* key kv-list :optional fallback
8194 @c EN
8195 Like @code{get-keyword}, but @var{fallback} is evaluated only
8196 if @var{kv-list} does not have @var{key}.
8197 @c JP
8198 @code{get-keyword} と同様ですが、@var{kv-list} が @var{key} を
8199 含まない場合にのみ @var{fallback} が評価されることだけが違います。
8200 @c COMMON
8201 @end defmac
8202
8203 @defun delete-keyword key kv-list
8204 @defunx delete-keyword! key kv-list
8205 @c EN
8206 Removes all the keys and values from @var{kv-list} for
8207 keys that are @code{eq?} to @var{key}.
8208 @c JP
8209 @var{kv-list} から @var{key} に @code{eq?} であるキーをもつキーと値を
8210 削除します。
8211 @c COMMON
8212
8213 @c EN
8214 @code{delete-keyword} doesn't change @var{kv-list}, but the returned
8215 list may share the common tail of it.
8216 @c JP
8217 @code{delete-keyword} は @var{kv-list} を変更しません。しかし、
8218 返されたリストは共通の末尾部分を共有します。
8219 @c COMMON
8220
8221 @c EN
8222 @code{delete-keyword!} doesn't allocate, and @emph{may} destructively
8223 changes @var{kv-list}. You still have to use the returned value,
8224 for the original list may not be changed if its first key matches
8225 @var{key}.
8226 @c JP
8227 @code{delete-keyword!} は新しくアロケートされることはありません。
8228 そして、破壊的に @var{kv-list} を変更する@emph{可能性があります}。
8229 最初のキーがマッチした場合元のリストは変更されないこともありえますが、
8230 返り値のリストを使わなければいけません。
8231 @c COMMON
8232
8233 @c EN
8234 If there's no key that matches @var{key}, @var{kv-list} is returned.
8235 @c JP
8236 @var{key} にマッチするキーがない場合 @var{kv-list} が返ります。
8237 @c COMMON
8238
8239 @example
8240 (delete-keyword :y '(:x 1 :y 2 :z 3 :y 4))
8241 @result{} (:x 1 :z 3)
8242 @end example
8243
8244 @end defun
8245
8246 @defun delete-keywords keys kv-list
8247 @defunx delete-keywords! keys kv-list
8248 @c EN
8249 Similar to @code{delete-keyword} and @code{delete-keyword!}, but
8250 you can specify a list of objects in @var{keys};
8251 when a key in @var{kv-list} matches any of @var{keys},
8252 the key and the following value is removed from @var{kv-list}.
8253 @c JP
8254 @code{delete-keyword}や@code{delete-keyword!}と似ていますが、
8255 @var{keys}にオブジェクトのリストを指定できます。
8256 @var{kv-list}中のキーが@var{keys}のうちのどれかに一致すれば、
8257 そのキーと続く値が@var{kv-list}から取り除かれます。
8258 @c COMMON
8259
8260 @example
8261 (delete-keywords '(:x :y) '(:x 1 :y 2 :z 3 :y 4))
8262 @result{} (:z 3)
8263 @end example
8264
8265 @end defun
8266
8267 @menu
8268 * Keyword and symbol integration::
8269 @end menu
8270
8271 @node Keyword and symbol integration, , Keywords, Keywords
8272 @subsection Keyword and symbol integration
8273 @c NODE キーワードとシンボルの統合
8274
8275 @c EN
8276 In older versions of Gauche, keywords are of disjoint type
8277 from symbols, and they are self-evaluating objects.
8278 To maintain the compatibility, the current Gauche makes
8279 symbols that begins with @code{:} automatically bound to itself.
8280
8281 On the surface it won't make much difference;
8282 you can write a keyword @code{:key}, which evaluates to itself; so you
8283 can pass and receive keyword arguments just as they used to be.
8284 If you use @code{:key} as variables, however, e.g. @code{(define :key 3)},
8285 the value of @code{:key} in your module changes
8286 (it won't affect other modules, which refer to the binding of @code{:key}
8287 in @code{gauche.keyword} module).
8288
8289 However, there are several subtle points that do make difference, that
8290 breaks compatibility of legacy code.
8291 We explain here how to change the code that works in both ways.
8292
8293 If you find a problem in new mode and want to get the old behavior
8294 until you change the code, you can set the environment variable
8295 @code{GAUCHE_KEYWORD_DISJOINT.}
8296 @c JP
8297 以前のGaucheでは、キーワードはシンボルとは異なる型を持ち、自分自身に評価される
8298 オブジェクトでした。
8299 互換性を保つため、現在のGaucheでは@code{:}で始まるシンボルは自動的に
8300 自分自身に束縛されるようになっています。
8301
8302 表面的にはこの変更はたいした違いをもたらさないでしょう。
8303 プログラム中に表記してあるキーワードはそれ自身に評価されるので、
8304 かつてと同じようにキーワード引数を渡すことができます。
8305 キーワードを変数として使い、例えば@code{(define :key 3)}のように
8306 新たな値に束縛することはできますが、その変更は
8307 そうしているモジュールの中だけに留まります。
8308 (他のモジュールは@code{gauche.keyword}モジュールにある@code{:key}の束縛を
8309 参照するので影響を受けません。)
8310
8311 けれども、違いが現れるいくつかのわかりづらい場合が存在し、
8312 注意していないと古いコードの互換性を壊してしまうかもしれません。
8313 どちらのモードでも動くようにするコードの書き方をこれから説明します。
8314
8315 新しいモードで問題が出て、コードを直すまで以前の動作で使いたければ、
8316 環境変数@code{GAUCHE_KEYWORD_DISJOINT}をセットしてください。
8317 @c COMMON
8318
8319 @c EN
8320 @subsubheading @code{(symbol? :key)} used to return @code{#f}, now returns @code{#t}
8321 @c JP
8322 @subsubheading @code{(symbol? :key)}は以前は@code{#f}を返したが、今は@code{#t}を返す
8323 @c COMMON
8324
8325 @c EN
8326 @code{keyword?} always returns @code{#t} on keywords, but
8327 if you need to switch behavior depending whether an object is a symbol
8328 or a keyword, you should test keyword-ness first.
8329 @c JP
8330 キーワードに対して@code{keyword?}は常に@code{#t}を返しますが、
8331 シンボルかキーワードかで動作を変えるコードでは、キーワードの検査を先にするようにしてください。
8332 @c COMMON
8333
8334 @example
8335 @c EN
8336 ;; behaved differently in 0.9.7 and before
8337 @c JP
8338 ;; 0.9.7以前は動作が異なる
8339 @c COMMON
8340 (cond
8341 [(symbol? x) (x-is-symbol)]
8342 [(keyword? x) (x-is-keyword)])
8343
8344 @c EN
8345 ;; works on all versions
8346 @c JP
8347 ;; どのバージョンでも動く
8348 @c COMMON
8349 (cond
8350 [(keyword? x) (x-is-keyword)]
8351 [(symbol? x) (x-is-symbol)])
8352 @end example
8353
8354 @c EN
8355 @subsubheading Literal keywords in pattern matching
8356 @c JP
8357 @subsubheading パターンマッチ中のリテラルキーワード
8358 @c COMMON
8359
8360 @c EN
8361 In the old versions,
8362 when keywords appear in a pattern of @code{util.match}
8363 or @code{syntax-rules}, they only matched to themselves.
8364 In the current version, such keywords in
8365 a pattern are treated as pattern variables, since they are symbols.
8366 @c JP
8367 以前のバージョンでは、@code{util.match}や@code{syntax-rules}の
8368 パターンにキーワードが現れた場合、それはキーワード自身とのみマッチしました。
8369 現在のバージョンでは、キーワードはシンボルなので、パターン変数として扱われます。
8370 @c COMMON
8371
8372 @example
8373 @c EN
8374 ;; In the old versions
8375 @c JP
8376 ;; 以前のバージョン
8377 @c COMMON
8378 (match '(a b) [(:key z) (list :key z)] [_ "nope"])
8379 @result{} "nope"
8380
8381 @c EN
8382 ;; In the current version
8383 ;; :key is treated just as a pattern variable
8384 @c JP
8385 ;; 現在のバージョン
8386 ;; :keyは単なるパターン変数となる
8387 @c COMMON
8388 (match '(a b) [(:key z) (list :key z)] [_ "nope"])
8389 @result{} (a b)
8390 @end example
8391
8392 @c EN
8393 The same thing happens to the patterns in @code{syntax-rules}.
8394
8395 To make the code work in both versions, explicitly mark the keywords
8396 as literals.
8397 @c JP
8398 @code{syntax-rules}でも同じことが起きます。
8399
8400 どのバージョンでも動くコードにするには、マッチさせたいキーワードが
8401 リテラルであることを明示してください。
8402 @c COMMON
8403
8404 @itemize @bullet
8405 @item
8406 @c EN
8407 For @code{match}, quote the keywords you want to be treated as literals.
8408 @c JP
8409 @code{match}では、キーワードをクオートしてリテラルであることを示します。
8410 @c COMMON
8411 @example
8412 (match '(a b) [(':key z) (list :key z)] [_ "nope"])
8413 @result{} "nope"
8414 @end example
8415
8416 @item
8417 @c EN
8418 For @code{syntax-rules}, list the keywords as literals.
8419 @c JP
8420 @code{syntax-rules}では、キーワードをリテラルリストに含めてください。
8421 @c COMMON
8422 @example
8423 (syntax-rules (:key)
8424 [(_ :key z) (list :key z)]) ;etc.
8425 @end example
8426 @end itemize
8427
8428 @c EN
8429 As of Gauche 0.9.5, @code{match} warns if you have unquoted
8430 keywords in match patterns.
8431 @c JP
8432 Gauche 0.9.5から、@code{match}はパターンにクオートされていないキーワードが
8433 現れると警告を発します。
8434 @c COMMON
8435
8436 @c EN
8437 @subsubheading Displaying keywords
8438 @c JP
8439 @subsubheading キーワードの表示
8440 @c COMMON
8441
8442 @c EN
8443 @code{(display :key)} used to print @code{key} (no colon), while it now
8444 prints @code{:key}.
8445
8446 You can use @code{(display (keyword->string :key))} which prints @code{key}
8447 in both versions.
8448 @c JP
8449 @code{(display :key)}は以前は@code{key}(コロン無し)を表示しましたが、
8450 現在は@code{:key}を表示します。
8451
8452 @code{key}を表示したい場合は@code{(display (keyword->string :key))}とすれば、
8453 どのバージョンでも同じように動作します。
8454 @c COMMON
8455
8456 @c EN
8457 @subsubheading For R7RS code, quote them or import Gauche modules
8458 @c JP
8459 @subsubheading R7RSコードではクオートするかGaucheのモジュールをインポートする
8460 @c COMMON
8461
8462 @c EN
8463 Keywords (symbols beginning with @code{:}) are automatically bound to itself
8464 in the @code{gauche.keyword} module.
8465
8466 Gauche code inherits the @code{gauche} module by default, which inherits
8467 @code{keyword}, so you can see the binding of the keyword by default.
8468
8469 In R7RS code, however, you don't inherit @code{gauche},
8470 so symbols beginning with @code{:} are just ordinary symbols by default.
8471 Usually you do @code{(import (gauche base))} to use Gauche built-ins,
8472 and that makes binding of @code{gauche.keyword} available in your
8473 code, too (since @code{gauche.base} inherits @code{gauche.keyword}).
8474 But keep this in mind just in case you want to handle keywords in
8475 your R7RS code separate from Gauche procedures---you have to either say
8476 @code{(import (gauche keyword))} to get just the self-bound keywords,
8477 or quote them.
8478 @c JP
8479 キーワード(@code{:}で始まるシンボル)は@code{gauche.keyword}モジュール
8480 の中で自分自身に束縛されます。
8481
8482 Gaucheコードはデフォルトで@code{gauche}モジュールを継承し、
8483 それが@code{keyword}モジュールを継承しているので、
8484 キーワードの束縛は自動的に見えるようになります。
8485
8486 しかしR7RSコードでは@code{gauche}モジュールは継承されないので、
8487 @code{:}で始まるシンボルもデフォルトではただのシンボルです。
8488 通常、Gaucheの組み込み機能を使うには@code{(import (gauche base))}としますが、
8489 こうするとキーワードの自分自身への束縛もインポートされるようになっています
8490 (@code{gauche.base}が@code{gauche.keyword}も継承しているからです)。
8491 ただ、Gaucheの手続きとは別にキーワードをR7RSコード中で使いたい場合は
8492 注意してください。自己束縛されているキーワードだけが欲しければ
8493 @code{(import (gauche keyword))}とする必要がありますし、
8494 そうしない場合はキーワードに見えるシンボルでもクオートする必要があります。
8495 @c COMMON
8496
8497 @example
8498 (import (scheme base))
8499
8500 :foo @result{} @r{ERROR: unbound variable: :foo}
8501
8502 (import (gauche base))
8503
8504 :foo @result{} :foo
8505 @end example
8506
8507 @c EN
8508 In the following example, the R7RS library @code{foo} imports only
8509 @code{copy-port} from @code{(gauche base)}; in that case,
8510 you have to import @code{(gauche keyword)} separately
8511 in order to use @code{:size} keyword without quoting.
8512 (Or add @code{:size} explicitly in the imported symbol
8513 list of @code{(gauche base)}.)
8514 @c JP
8515 次の例では、R7RSライブラリ@code{foo}が@code{(gauche base)}から
8516 @code{copy-port}のみをインポートしています。こういった場合、
8517 @code{:size}キーワードをクオートなしで使うには、@code{(gauche keyword)}も
8518 別にインポートしなければなりません。
8519 (あるいは、@code{(gauche base)}からインポートするシンボルのリストに
8520 @code{:size}も明示するか)。
8521 @c COMMON
8522
8523 @example
8524 (define-library (foo)
8525 (import (scheme base)
8526 (only (gauche base) copy-port)
8527 (gauche keyword))
8528 (export cat)
8529
8530 (begin
8531 (define (cat)
8532 (copy-port (current-input-port)
8533 (current-output-port)
8534 :size 4096))))
8535 @end example
8536
8537
8538 @c ----------------------------------------------------------------------
8539 @node Characters, Character sets, Keywords, Core library
8540 @section Characters
8541 @c NODE 文字
8542
8543 @deftp {Builtin Class} <char>
8544 @clindex char
8545 @end deftp
8546
8547 @deftp {Reader Syntax} @code{#\@i{charname}}
8548 @lxindex #\
8549 [R7RS+]
8550 @c EN
8551 Denotes a literal character.
8552
8553 When the reader reads @code{#\}, it fetches a subsequent character.
8554 If it is one of @code{()[]@{@}" \|;#}, this is a character literal of itself.
8555 Otherwise, the reader reads subsequent characters until it sees
8556 a non word-constituent character. If only one character is read,
8557 it is the character. Otherwise, the reader matches the read characters
8558 with predefined character names. If it doesn't match any, an error
8559 is signaled.
8560
8561 The following character names are recognized.
8562 These character names are case insensitive.
8563 @table @code
8564 @item space
8565 Whitespace (ASCII #x20)
8566 @item newline, nl, lf
8567 Newline (ASCII #x0a)
8568 @item return, cr
8569 Carriage return (ASCII #x0d)
8570 @item tab, ht
8571 Horizontal tab (ASCII #x09)
8572 @item page
8573 Form feed (ASCII #x0c)
8574 @item alarm
8575 Bell (ASCII #x07)
8576 @item backspace
8577 Backspace (ASCII #x08)
8578 @item escape, esc
8579 Escape (ASCII #x1b)
8580 @item delete, del
8581 Delete (ASCII #x7f)
8582 @item null
8583 NUL character (ASCII #x00)
8584 @item x@var{N}
8585 A character whose Unicode codepoint is the integer @var{N},
8586 when @var{N} is a hexadecimal integer.
8587 This is R7RS lexical syntax.
8588 @item u@var{N}
8589 A character whose Unicode codepoint is the integer @var{N},
8590 where @var{N} is 4-digit or 8-digit hexadecimal number.
8591 This is legacy Gauche lexical syntax. Use @code{\xN} syntax for
8592 the new code.
8593 @end table
8594 @c JP
8595 リテラルの文字オブジェクトを表現します。
8596
8597 リーダーは@code{#\}に出会うと、まず次の文字を読み込みます。それが文字
8598 @code{()[]@{@}" \|;#} のいずれかならば、その文字自身となります。
8599 そうでなければ、単語を構成しない文字に出会うまで文字が続けて読み込まれます。
8600 もし一文字しか読まれなければ、その文字自身となります。そうでなければ
8601 その単語が文字の名前として解釈されます。
8602 それが有効な文字の名前でなければエラーとなります。
8603
8604 以下の文字の名前が認識されます。これらの文字の名前は大文字小文字を区別しません。
8605 @table @code
8606 @item space
8607 スペース (ASCII #x20)
8608 @item newline, nl, lf
8609 改行文字 (ASCII #x0a)
8610 @item return, cr
8611 復帰文字 (ASCII #x0d)
8612 @item tab, ht
8613 水平タブ (ASCII #x09)
8614 @item page
8615 フォームフィード、改ページ (ASCII #x0c)
8616 @item alarm
8617 ベル (ASCII #x07)
8618 @item backspace
8619 バックスペース (ASCII #x08)
8620 @item escape, esc
8621 エスケープ (ASCII #x1b)
8622 @item delete, del
8623 デリート (ASCII #x7f)
8624 @item null
8625 NUL文字 (ASCII #x00)
8626 @item x@var{N}
8627 @var{N} が16進表記の整数であるとき、Unicodeコードポイントが整数@var{N}
8628 であるような文字。これはR7RSの字句構文です。
8629 @item u@var{N}
8630 @var{N}が4桁または8桁の16進数整数であるとき、UCSコード@var{N}であるような文字。
8631 これはGaucheの古い構文です。新規のコードでは@code{\xN}を使ってください。
8632 @end table
8633 @c COMMON
8634
8635 @example
8636 @c EN
8637 #\newline @result{} #\newline ; @r{newline character}
8638 #\x0a @result{} #\newline ; @r{ditto}
8639 #\x41 @result{} #\A ; @r{ASCII letter 'A'}
8640 #\x3042 @result{} ; @r{Hiragana letter A}
8641 #\x2a6b2 @result{} ; @r{JISX0213 Kanji 2-94-86}
8642 @c JP
8643 #\newline @result{} #\newline ; @r{改行文字}
8644 #\x0a @result{} #\newline ; @r{改行文字}
8645 #\x41 @result{} #\A ; @r{ASCII文字 'A'}
8646 #\x3042 @result{} #\あ ; @r{平仮名「あ」}
8647 #\x2a6b2 @result{} ; @r{JISX0213 2-94-86}
8648 @c COMMON
8649 @end example
8650 @end deftp
8651
8652 @defun char? obj
8653 [R7RS base]
8654 @c EN
8655 Returns @code{#t} if @var{obj} is a character, @code{#f} otherwise.
8656 @c JP
8657 @var{obj}が文字なら@code{#t}を、そうでなければ@code{#f}を返します。
8658 @c COMMON
8659 @end defun
8660
8661 @defun char=? char1 char2 char3 @dots{}
8662 @defunx char<? char1 char2 char3 @dots{}
8663 @defunx char<=? char1 char2 char3 @dots{}
8664 @defunx char>? char1 char2 char3 @dots{}
8665 @defunx char>=? char1 char2 char3 @dots{}
8666 [R7RS base]
8667 @c EN
8668 Compares characters. Character comparison is done in internal
8669 character encoding.
8670 @c JP
8671 文字を比較します。比較は内部の文字エンコーディングで行われます。
8672 @c COMMON
8673 @end defun
8674
8675 @defun char-ci=? char1 char2 char3 @dots{}
8676 @defunx char-ci<? char1 char2 char3 @dots{}
8677 @defunx char-ci<=? char1 char2 char3 @dots{}
8678 @defunx char-ci>? char1 char2 char3 @dots{}
8679 @defunx char-ci>=? char1 char2 char3 @dots{}
8680 [R7RS char]
8681 @c EN
8682 Compares characters in case-insensitive way.
8683 The comparison is done in the internal character code
8684 of the foldcase of the each character; see @code{char-foldcase} below.
8685
8686 In R7RS, these procedures are in the @code{(scheme char)} library.
8687 @c JP
8688 文字を、大文字小文字を区別せずに比較します。
8689 比較はそれぞれの文字のfoldcaseの内部文字エンコーディングに基づいて行われます。
8690 foldcaseについては下の@code{char-foldcase}を参照してください。
8691
8692 R7RSではこれらの手続きは@code{(scheme char)}ライブラリにあります。
8693 @c COMMON
8694 @end defun
8695
8696 @defun char-alphabetic? char
8697 @defunx char-numeric? char
8698 @defunx char-whitespace? char
8699 @defunx char-upper-case? char
8700 @defunx char-lower-case? char
8701 @defunx char-title-case? char
8702 [R7RS char][SRFI-129]
8703 @c EN
8704 Returns true if a character @var{char} is an alphabetic character
8705 (Unicode character category @code{Lu}, @code{Ll}, @code{Lt},
8706 @code{Lm}, @code{Lo}, @code{Nl}),
8707 a numeric character
8708 (Unicode character category @code{Nd}),
8709 a whitespace character,
8710 (Unicode character category @code{Zs}, @code{Zp}, @code{Zl}),
8711 an upper case character
8712 (Unicode character category @code{Lu}),
8713 or a lower case character
8714 (Unicode character category @code{Ll}), respectively.
8715
8716 In R7RS, these procedures except @code{char-title-case?}
8717 are in the @code{(scheme char)} library,
8718 while @code{char-title-case?} is defined in SRFI-129.
8719 @c JP
8720 文字@var{char}がそれぞれアルファベット
8721 (Unicode文字カテゴリ @code{Lu}、@code{Ll}、@code{Lt}、
8722 @code{Lm}、@code{Lo}、@code{Nl})、
8723 数字 (Unicode文字カテゴリ @code{Nd})、
8724 空白文字 (Unicode文字カテゴリ @code{Zs}、@code{Zp}、@code{Zl})、
8725 大文字 (Unicode文字カテゴリ @code{Lu})、
8726 小文字 (Unicode文字カテゴリ @code{Ll})の時に真の値を返します。
8727
8728 R7RSでは@code{char-title-case?}以外の手続きは
8729 @code{(scheme char)}ライブラリにあります。
8730 @code{char-title-case?}はSRFI-129で定義されます。
8731 @c COMMON
8732 @end defun
8733
8734 @defun char-word-constituent? char
8735 @c EN
8736 Returns @code{#t} iff @var{char} is a character R7RS allows to be
8737 in an identifier name without escaping: ASCII alphanumeric characters,
8738 extended alphabetic characters (@code{! $ % & * + - . / : < = > ? @ ^ _ ~}),
8739 any characters whose category is
8740 Lu, Ll, Lt, Lm, Lo, Mn, Mc, Me, Nd, Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co,
8741 Zero width non-joiner (U+200C), and Zero width joiner (U+200D).
8742 @c JP
8743 @var{char}がR7RSで識別子にエスケープなしで使える文字ならば@code{#t}を、
8744 そうでなければ@code{#f}を返します。該当する文字は、ASCIIのアルファベットと数字、
8745 拡張アルファベット@code{! $ % & * + - . / : < = > ? @ ^ _ ~}、
8746 文字カテゴリが
8747 Lu, Ll, Lt, Lm, Lo, Mn, Mc, Me, Nd, Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, Coの
8748 いずれかであるもの、および
8749 Zero width non-joiner (U+200C)とZero width joiner (U+200D)です。
8750 @c COMMON
8751 @end defun
8752
8753
8754 @defun char-general-category char
8755 [R6RS]
8756 @c EN
8757 Returns one of the following symbols, representing the Unicode general category of @var{char}.
8758 @c JP
8759 文字@var{char}のUnicode general categoryを表す、以下のシンボルのいずれかを返します。
8760 @c COMMON
8761
8762 @multitable {aaa} {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}
8763 @item @code{Cc} @tab Other, Control
8764 @item @code{Cf} @tab Other, Format
8765 @item @code{Cn} @tab Other, Not Assigned
8766 @item @code{Co} @tab Other, Private Use
8767 @item @code{Cs} @tab Other, Surrogate
8768 @item @code{Ll} @tab Letter, Lowercase
8769 @item @code{Lm} @tab Letter, Modifier
8770 @item @code{Lo} @tab Letter, Other
8771 @item @code{Lt} @tab Letter, Titlecase
8772 @item @code{Lu} @tab Letter, Uppercase
8773 @item @code{Mc} @tab Mark, Spacing Combining
8774 @item @code{Me} @tab Mark, Enclosing
8775 @item @code{Mn} @tab Mark, Nonspacing
8776 @item @code{Nd} @tab Number, Decimal Digit
8777 @item @code{Nl} @tab Number, Letter
8778 @item @code{No} @tab Number, Other
8779 @item @code{Pc} @tab Punctuation, Connector
8780 @item @code{Pd} @tab Punctuation, Dash
8781 @item @code{Pe} @tab Punctuation, Close
8782 @item @code{Pf} @tab Punctuation, Final quote
8783 @item @code{Pi} @tab Punctuation, Initial quote
8784 @item @code{Po} @tab Punctuation, Other
8785 @item @code{Ps} @tab Punctuation, Open
8786 @item @code{Sc} @tab Symbol, Currency
8787 @item @code{Sk} @tab Symbol, Modifier
8788 @item @code{Sm} @tab Symbol, Math
8789 @item @code{So} @tab Symbol, Other
8790 @item @code{Zl} @tab Separator, Line
8791 @item @code{Zp} @tab Separator, Paragraph
8792 @item @code{Zs} @tab Separator, Space
8793 @end multitable
8794 @end defun
8795
8796 @defun char->integer char
8797 @defunx integer->char n
8798 [R7RS base]
8799 @c EN
8800 @code{char->integer} returns an exact integer of the unicode
8801 codepont of the character @var{char}.
8802 @code{integer->char} returns a character whose unicode codepoint
8803 is an exact integer @var{n}. The following expression is always
8804 true for valid character @var{char}:
8805 @example
8806 (eq? char (integer->char (char->integer char)))
8807 @end example
8808
8809 The result is undefined if you pass @var{n} to @code{integer->char}
8810 that doesn't have a corresponding character.
8811 @c JP
8812 @code{char->integer}は文字@var{char}のUnicodeコードポイント
8813 整数値を返します。@code{integer->char}は数値@var{n}をUnicodeコードポイントとする
8814 文字を返します。有効な文字@var{char}に対して以下の式は常に真となります。
8815 @example
8816 (eq? char (integer->char (char->integer char)))
8817 @end example
8818
8819 対応する文字が無い数値を@code{integer->char}に渡した
8820 場合の結果は不定です。
8821 @c COMMON
8822 @end defun
8823
8824 @defun char->ucs char
8825 @defunx ucs->char n
8826 @c DEPRECATED
8827 @c EN
8828 These are the same as @code{char->integer} and @code{integer->char},
8829 respectively.
8830
8831 Gauche used to be built with an internal encoding other than
8832 utf-8, in which integer character codes differ from Unicode
8833 codepoints. These procedures can be used to guarantee
8834 you can use Unicode codepoints.
8835
8836 Now that Gauche always uses utf-8, these procedures are no longer needed.
8837 @c JP
8838 それぞれ@code{char->integer}および@code{integer->char}と同じです。
8839
8840 Gaucheはかつて、utf-8以外の内部エンコーディングでもビルドすることができ、
8841 その場合文字に対応する整数の文字コードはUnicodeコードポイントとは限りませんでした。
8842 これらの手続きは確実にUnicode-コードポイントを扱いたい場合に使われました。
8843
8844 現在ではGaucheは内部エンコーディングにutf-8のみを使うので、
8845 これらの手続きはもう必要なくなりました。
8846 @c COMMON
8847 @end defun
8848
8849 @defun char-upcase char
8850 @defunx char-downcase char
8851 @defunx char-titlecase char
8852 @defunx char-foldcase char
8853 [R7RS char][SRFI-129]
8854 @c EN
8855 Returns the upper case, lower case, title case and folded case of
8856 @var{char}, respectively.
8857 The mapping is done according to Unicode-defined character-by-character
8858 case mapping.
8859
8860 R7RS defines @code{char-upcase}, @code{char-downcase}, and
8861 @code{char-foldcase} in the @code{(scheme char)} library,
8862 while @code{char-titlecase} is defined in SRFI-129.
8863 R6RS defines all of them.
8864 @c JP
8865 @var{char}の大文字、小文字、titlecase、foldcaseを
8866 それぞれ返します。
8867 変換はUnicodeで定義された文字対文字のマッピングに従います。
8868
8869 R7RSは@code{(scheme char)}ライブラリで、@code{char-upcase}、
8870 @code{char-downcase}、@code{char-foldcase}を定義しています。
8871 @code{char-titlecase}はSRFI-129で定義されます。
8872 R6RSは全ての手続きを提供しています。
8873 @c COMMON
8874
8875 @c EN
8876 The character-by-character case mapping doesn't consider a character
8877 that may map to more than one characters; a notable example is
8878 eszett (latin small letter sharp S, U+00df), which is
8879 is mapped to two capital S's in string context,
8880 but @code{char-upcase #\ß} returns #\ß. To get a full mapping,
8881 use @code{string-upcase} etc. in @code{gauche.unicode} module
8882 (@pxref{Full string case conversion}).
8883 @c JP
8884 文字対文字のマッピングでは、一文字が複数文字に展開されるようなケースマッピングは
8885 扱いません。有名な例はeszett (latin small letter sharp S, U+00df)で、
8886 文字列のコンテキストでは二つの大文字のSへとマップされますが、
8887 @code{char-upcase #\ß} は単に #\ß を返します。
8888 完全なマッピングが必要なら、@code{gauche.unicode}モジュールの
8889 @code{string-upcase}等が利用できます
8890 (@ref{Full string case conversion}参照)。
8891 @c COMMON
8892 @end defun
8893
8894 @defun digit->integer char :optional (radix 10) (extended-range? #f)
8895 @c EN
8896 If given character @var{char} is a valid digit character in radix
8897 @var{radix} number, the corresponding integer is returned. Otherwise
8898 @code{#f} is returned.
8899 @c JP
8900 文字@var{char}が @var{radix}進数の数字を構成するのに有効な文字であれば、
8901 対応する整数が、そうでなければ@code{#f}が返されます。
8902 @c COMMON
8903 @example
8904 (digit->integer #\4) @result{} 4
8905 (digit->integer #\e 16) @result{} 14
8906 (digit->integer #\9 8) @result{} #f
8907 @end example
8908
8909 @c EN
8910 If the optional @var{extended-range?} argument is true,
8911 this procedure recognizes not only ASCII digits, but also
8912 all characters with @code{Nd} general category---such as
8913 FULLWIDTH DIGIT ZERO to NINE (U+ff10 - U+ff19).
8914 @c JP
8915 省略可能引数@var{extended-range?}に真の値が与えられると、
8916 この手続きはASCIIの数字だけでなく、@code{Nd}カテゴリに属する
8917 すべての文字、例えば
8918 FULLWIDTH DIGIT ZEROからNINE (U+ff10 - U+ff19) も認識します。
8919 @c COMMON
8920
8921 @c EN
8922 R7RS has @code{digit-value}, which is equivalent to
8923 @code{(digit->integer char 10 #t)}.
8924 @c JP
8925 R7RSには@code{digit-value}という手続きが定義されていて、それは
8926 @code{(digit->integer char 10 #t)}と等価です。
8927 @c COMMON
8928
8929 @c EN
8930 Note: CommonLisp has a similar function in rather confusing name,
8931 @code{digit-char-p}.
8932 @c JP
8933 Common Lispには同様の手続きが@code{digit-char-p}というやや曖昧な名で定義されています。
8934 @c COMMON
8935 @end defun
8936
8937 @defun integer->digit integer :optional (radix 10) (basechar1 #\0) (basechar2 #\a)
8938 @c EN
8939 Reverse operation of @code{digit->integer}. Returns a character that
8940 represents the number @var{integer} in the radix @var{radix} system.
8941 If @var{integer} is out of the valid range, @code{#f} is returned.
8942 @c JP
8943 @code{digit->integer}の逆です。整数@var{integer}を @var{radix}進数 ひと桁で
8944 表現するのに使われる文字を返します。@var{integer}がひと桁で表現できない数値の場合は
8945 @code{#f}が返されます。
8946 @c COMMON
8947 @example
8948 (integer->digit 13 16) @result{} #\d
8949 (integer->digit 10) @result{} #f
8950 @end example
8951
8952 @c EN
8953 The optional @var{basechar1} argument specifies the character
8954 that stands for zero; by default, it's @code{#\0}. You can give
8955 alternative character, for example, U+0660 (ARABIC-INDIC DIGIT ZERO)
8956 to convert an integer to a arabic-indic digit character.
8957 @c JP
8958 省略可能引数@var{basechar1}はゼロに相当する文字を指定します。
8959 デフォルトは@code{#\0}です。ここに、例えばU+0660 (ARABIC-INDIC DIGIT ZERO)
8960 を与えれば、整数をアラビア・インド数字に変換できます。
8961 @c COMMON
8962
8963 @c EN
8964 Another optional @var{basechar2} argument is used for integers over 10.
8965 The default value is @code{#\a}. You can pass @code{#\A} to get
8966 upper-case hex digits, for example.
8967 @c JP
8968 もうひとつの省略可能引数@var{basechar2}は、10を越える整数に使う文字の起点を
8969 指定します。デフォルトは@code{#\a}です。ここに@code{#\A}を渡せば、
8970 16進数表記で小文字のかわりに大文字を使うようになります。
8971 @c COMMON
8972
8973 @c EN
8974 Note: CommonLisp's @code{digit-char}.
8975 @c JP
8976 Common Lispの@code{digit-char}に当たります。
8977 @c COMMON
8978 @end defun
8979
8980 @defun gauche-character-encoding
8981 @c DEPRECATED
8982 @c EN
8983 Returns a symbol @code{utf-8}.
8984 This is kept for the backward compatibility with the code
8985 written for pre-1.0 Gauche which may be compiled with internal
8986 encodings other than utf-8.
8987 @c JP
8988 シンボル@code{utf-8}を返します。
8989 これは、1.0以前のGaucheのために書かれたコードの互換性のために残されています。
8990 かつてはutf-8以外の内部エンコーディングでGaucheをコンパイルすることが可能でした。
8991 @c COMMON
8992 @end defun
8993
8994 @defun supported-character-encodings
8995 @c EN
8996 Returns a list of string names of character encoding schemes
8997 that are supported in the native multibyte encoding scheme.
8998 @c JP
8999 ネイティブなマルチバイトエンコーディングスキームでサポートされている
9000 文字エンコーディングスキームの名前を表す文字列のリストを返します。
9001 @c COMMON
9002 @end defun
9003
9004
9005
9006 @c ----------------------------------------------------------------------
9007 @node Character sets, Strings, Characters, Core library
9008 @section Character Sets
9009 @c NODE 文字集合
9010
9011 @deftp {Builtin Class} <char-set>
9012 @clindex char-set
9013 @c EN
9014 Character set class. Character set object represents a set of characters.
9015 Gauche provides built-in support of character set creation and
9016 a predicate that tests whether a character is in the set or not.
9017
9018 The class implements the collection protocol (@pxref{Collection framework}),
9019 so that the standard collection methods provided in the
9020 @code{gauche.collection} module can be used.
9021
9022 An instance of @code{<char-set>} is applicable to a character,
9023 and works as a membership predicate; see @code{char-set-contains?} below.
9024
9025 Further operations, such as set algebra, is defined in SRFI-14
9026 module (@pxref{R7RS character sets}).
9027 @c JP
9028 文字の集合を取り扱う、文字集合(キャラクタセット)のクラスです。
9029 Gaucheは文字集合オブジェクトのサポートと、
9030 ある文字がその集合に属するかどうかを調べる手続きを言語組み込みで持っています。
9031
9032 コレクションプロトコル (@ref{Collection framework}参照) を実装しているので、
9033 @code{gauche.collection}で提供される標準のコレクションメソッドが使えます。
9034
9035 @code{<char-set>}のインスタンスは文字に関数のように適用することができ、
9036 その文字が文字集合に属するかどうかを判定する述語として機能します。
9037 下記の@code{char-set-contains?}を参照してください。
9038
9039 文字集合に関する他の操作、例えば集合演算などは、SRFI-14モジュール
9040 (@ref{R7RS character sets}参照) で提供されています。
9041 @c COMMON
9042 @end deftp
9043
9044 @menu
9045 * Character set literals::
9046 * Predefined character sets::
9047 * Character set operations::
9048 @end menu
9049
9050 @node Character set literals, Predefined character sets, Character sets, Character sets
9051 @subsection Character set literals
9052 @c NODE 文字集合リテラル
9053
9054 @deftp {Reader Syntax} @code{#[@i{char-set-spec}]}
9055 @lxindex #[
9056 @c EN
9057 You can write a literal character set in this syntax.
9058 @i{char-set-spec} is a sequence of characters to be included
9059 in the set. You can include the following special sequences:
9060 @table @code
9061 @item @var{x}-@var{y}
9062 Characters between @var{x} and @var{y}, inclusive.
9063 @var{x} must be smaller than @var{y} in the Unicode codepoints.
9064 @item ^
9065 If @i{char-set-spec} begins with caret, the actual character set
9066 is a complement of what the rest of @i{char-set-spec} indicates.
9067 @item \x@var{N};
9068 A character whose Unicode codepoint is a hexadecimal number @var{N}.
9069 @item \u@var{XXXX}
9070 @itemx \U@var{XXXXXXXX}
9071 This is a legacy Gauche syntax, for a unicode character
9072 whose Unicode codepoint is represented by 4-digit and 8-digit hexadecimal
9073 numbers, respectively.
9074 @item \s
9075 Whitespace characters
9076 (space, newline, tab, form feed, vertical tab, carriage return).
9077 Members of @code{char-set:ascii-whitespace}.
9078 @item \S
9079 Complement of whitespace characters.
9080 @item \d
9081 Decimal digit characters. Members of
9082 @code{char-set:ascii-digits}.
9083 @item \D
9084 Complement of decimal digit characters.
9085 @item \w
9086 Word constituent characters (@code{#[A-Za-z0-9_]}).
9087 Members of @code{char-set:ascii-word}.
9088 @item \W
9089 Complement of word constituent characters.
9090 @item \\
9091 A backslash character.
9092 @item \-
9093 A minus character.
9094 @item \^
9095 A caret character.
9096 @item [:alnum:] @dots{}
9097 Character set a la POSIX. See the table below for the complete list of
9098 recognized character set names. The set name must be in all lower cases.
9099 This notation only includes characters in ASCII range.
9100 @item [:^alnum:] @dots{}
9101 Complement set of @code{[:alnum:]} etc.
9102 @item [:ALNUM:] @dots{}
9103 Gauche's extension of character set a la POSIX; the name must be
9104 all in upper cases, and includes full Unicode range. See the table below
9105 for the recognized names.
9106 @item [:^ALNUM:] @dots{}
9107 Complement set of @code{[:ALNUM:]} etc.
9108 @end table
9109
9110 Here's the list of POSIX-style character class names:
9111
9112 @multitable @columnfractions .15 .85
9113 @item @code{:alpha:} @tab ASCII alphabets. @code{char-set:ascii-letter}, @code{#[A-Za-z]}
9114 @item @code{:alnum:} @tab ASCII alphabets and digits. @code{char-set:ascii-letter+digits}, @code{#[0-9A-Za-z]}.
9115 @item @code{:blank:} @tab ASCII blanks. @code{char-set:ascii-blank}, tab and space.
9116 @item @code{:cntrl:} @tab ASCII control characters. @code{char-set:ascii-control}, U+0000 to U+001f and U+007f.
9117 @item @code{:digit:} @tab ASCII digits. @code{char-set:ascii-digit}, @code{#[0-9]}.
9118 @item @code{:graph:} @tab ASCII graphic characters. @code{char-set:ascii-graphic}.
9119 @item @code{:lower:} @tab ASCII lower-case alphabets. @code{char-set:ascii-lower-case}, @code{#[a-z]}.
9120 @item @code{:print:} @tab ASCII printing characters. @code{char-set:ascii-printing}.
9121 @item @code{:punct:} @tab ASCII punctuation characters. @code{char-set:ascii-punctuation}.
9122 @item @code{:space:} @tab ASCII whitespaces. @code{char-set:ascii-whitespace}.
9123 @item @code{:upper:} @tab ASCII upper-case characters. @code{char-set:ascii-upper-case}, @code{#[A-Z]}.
9124 @item @code{:word:} @tab ASCII word characters (not POSIX). @code{char-set:ascii-word}, @code{#[0-9A-Za-z_]}.
9125 @item @code{:xdigit:} @tab Hexadecimal digits. @code{char-set:hex-digit}, @code{#[0-9a-fA-F]}.
9126 @item @code{:ascii:} @tab ASCII characters (not POSIX). @code{char-set:ascii}.
9127 @item @code{:ALPHA:} @tab Unicode letters (category @code{L*}). @code{char-set:letter}.
9128 @item @code{:ALNUM:} @tab Unicode letters and digits. @code{char-set:letter+digits}.
9129 @item @code{:BLANK:} @tab Unicode blanks (tab and category @code{Zs}). @code{char-set:blank}.
9130 @item @code{:CNTRL:} @tab Unicode control characters (category @code{Cc}). @code{char-set:iso-control}.
9131 @item @code{:DIGIT:} @tab Unicode digits (category @code{Nd}). @code{char-set:digit}.
9132 @item @code{:GRAPH:} @tab Unicode graphic characters (letter, digits, punctuation, symbol, and category @code{Nl} and @code{No}). @code{char-set:graphic}.
9133 @item @code{:LOWER:} @tab Unicode lower-case letters (category @code{Ll}). @code{char-set:lower-case}, @code{#[a-z]}.
9134 @item @code{:PRINT:} @tab Unicode printing characters (graphic and whitespace). @code{char-set:printing}.
9135 @item @code{:PUNCT:} @tab Unicode punctuation characters (category @code{P*}). @code{char-set:punctuation}.
9136 @item @code{:SPACE:} @tab Unicode whitespaces (tab, LF, vertical tab, FF, CR, and category @code{Z*}). @code{char-set:whitespace}.
9137 @item @code{:TITLE:} @tab Unicode titlecase letters (category @code{Lt}). @code{char-set:title-case}.
9138 @item @code{:UPPER:} @tab Unicode upper-case letters (category @code{Lu}). @code{char-set:upper-case}, @code{#[A-Z]}.
9139 @item @code{:WORD:} @tab Unicode word characters. @code{char-set:word}.
9140 @item @code{:XDIGIT:} @tab Hexadecimal digits (same as @code{:xdigit:}).
9141 @end multitable
9142
9143 Here are some examples:
9144
9145 @example
9146 #[aeiou] ; @r{a character set consists of vowels}
9147 #[a-zA-Z] ; @r{alphabet}
9148 #[[:alpha:]] ; @r{alphabet (using POSIX notation)}
9149 #[\\\-] ; @r{backslash and minus}
9150 #[] ; @r{empty charset}
9151 #[\x0d;\x0a;\x3000;] ; @r{carriage return, newline, and ideographic space}
9152 @end example
9153 @c JP
9154 この構文で、リテラル文字集合を記述することができます。
9155 @i{char-set-spec}には集合に含める文字を列挙します。
9156 次の特殊なシーケンスを含めることができます。
9157 @table @code
9158 @item @var{x}-@var{y}
9159 文字@var{x}と文字@code{y}の間の文字全て。@var{x}と@var{y}も含みます。
9160 @var{x}は@var{y}よりも内部文字コードで比較して小さくなければなりません。
9161 @item ^
9162 カレットが@i{char-set-spec}の最初に来た場合、以降に示される文字集合の
9163 補集合がこの文字集合となります。
9164 @item \x@var{N};
9165 Unicodeコードポイントが@var{N}(16進数表記)の文字。
9166 @item \s
9167 空白文字(space, newline, tab, form feed, vertical tab, carriage return).
9168 文字集合@code{char-set:ascii-whitespace}の要素。
9169 @item \S
9170 空白でない文字。(@code{\s}の補集合)
9171 @item \d
9172 10進数の数字。
9173 文字集合@code{char-set:ascii-digit}の要素。
9174 @item \D
9175 @code{\d}の補集合
9176 @item \w
9177 単語を構成する文字の集合(@code{#[A-Za-z0-9_]})。
9178 文字集合@code{char-set:ascii-word}の要素。
9179 @item \W
9180 @code{\W}の補集合
9181 @item \\
9182 バックスラッシュ文字
9183 @item \-
9184 マイナス文字
9185 @item \^
9186 カレット文字
9187 @item [:alnum:] @dots{}
9188 POSIX風文字集合表記。サポートされる名前については下の表を参照してください。
9189 名前は全て小文字でなければなりません。この表記の文字集合はASCII範囲のみを含みます。
9190 @item [:^alnum:] @dots{}
9191 @code{[:alnum:]}等の補集合です。
9192 @item [:ALNUM:] @dots{}
9193 POSIX風文字集合表記のGauche拡張。名前は全て大文字でなければなりません。
9194 この表記の文字集合はUnicode全範囲を対象とします。
9195 サポートされる名前については下の表を参照してください。
9196 @item [:^ALNUM:] @dots{}
9197 @code{[:ALNUM:]}等の補集合です。
9198 @end table
9199
9200 POSIX風文字集合表記で認識される名前は次のとおりです。
9201
9202 @multitable @columnfractions .15 .85
9203 @item @code{:alpha:} @tab ASCIIアルファベット。@code{char-set:ascii-letter}, @code{#[A-Za-z]}
9204 @item @code{:alnum:} @tab ASCIIアルファベットと数字。@code{char-set:ascii-letter+digits}, @code{#[0-9A-Za-z]}.
9205 @item @code{:blank:} @tab ASCIIブランク文字。@code{char-set:ascii-blank}, tab and space.
9206 @item @code{:cntrl:} @tab ASCII制御文字。@code{char-set:ascii-control}, U+0000 to U+001f and U+007f.
9207 @item @code{:digit:} @tab ASCII数字。@code{char-set:ascii-digit}, @code{#[0-9]}.
9208 @item @code{:graph:} @tab ASCIIグラフィック文字。@code{char-set:ascii-graphic}.
9209 @item @code{:lower:} @tab ASCII小文字アルファベット。@code{char-set:ascii-lower-case}, @code{#[a-z]}.
9210 @item @code{:print:} @tab ASCII印字可能文字。@code{char-set:ascii-printing}.
9211 @item @code{:punct:} @tab ASCII句読点。@code{char-set:ascii-punctuation}.
9212 @item @code{:space:} @tab ASCII空白文字。@code{char-set:ascii-whitespace}.
9213 @item @code{:upper:} @tab ASCII大文字アルファベット。@code{char-set:ascii-upper-case}, @code{#[A-Z]}.
9214 @item @code{:word:} @tab ASCII単語構成文字(POSIXではありません)。 @code{char-set:ascii-word}, @code{#[0-9A-Za-z_]}.
9215 @item @code{:xdigit:} @tab 16進数の数字。@code{char-set:hex-digit}, @code{#[0-9a-fA-F]}.
9216 @item @code{:ascii:} @tab ASCII文字 (POSIXではありません). @code{char-set:ascii}.
9217 @item @code{:ALPHA:} @tab Unicode通常文字。@code{char-set:letter}.
9218 @item @code{:ALNUM:} @tab Unicode通常文字と数字。@code{char-set:letter+digits}.
9219 @item @code{:BLANK:} @tab Unicodeブランク文字。@code{char-set:blank}.
9220 @item @code{:CNTRL:} @tab Unicode制御文字。@code{char-set:iso-control}.
9221 @item @code{:DIGIT:} @tab Unicode数字。@code{char-set:digit}.
9222 @item @code{:GRAPH:} @tab Unicodeグラフィック文字。@code{char-set:graphic}.
9223 @item @code{:LOWER:} @tab Unicode小文字。@code{char-set:lower-case}, @code{#[a-z]}.
9224 @item @code{:PRINT:} @tab Unicode印字可能文字。@code{char-set:printing}.
9225 @item @code{:PUNCT:} @tab Unicode句読点。@code{char-set:punctuation}.
9226 @item @code{:SPACE:} @tab Unicode空白文字。@code{char-set:whitespace}.
9227 @item @code{:UPPER:} @tab Unicode大文字。@code{char-set:upper-case}, @code{#[A-Z]}.
9228 @item @code{:WORD:} @tab Unicode単語構成文字。@code{char-set:word}.
9229 @item @code{:XDIGIT:} @tab 16進数の数字。(@code{:xdigit:}と同じ).
9230 @end multitable
9231
9232 いくつか例を示します。
9233
9234 @example
9235 #[aeiou] ; @r{母音文字'a', 'e', 'i', 'o', 'u'の集合}
9236 #[a-zA-Z] ; @r{アルファベット}
9237 #[[:alpha:]] ; @r{アルファベット (POSIX表記)}
9238 #[\\\-] ; @r{バックスラッシュとマイナス文字}
9239 #[] ; @r{空の文字集合}
9240 #[ぁ-ん] ; @r{平仮名の集合}
9241 #[\x0d;\x0a;\x3000;] ; @r{リターン, 改行, 全角空白}
9242 @end example
9243 @c COMMON
9244
9245 @c EN
9246 Literal character sets are immutable, as other literal data. An error
9247 is signalled when you attempt to modify an immutable character set.
9248 @c JP
9249 リテラル文字集合は他のリテラルデータ同様、変更不可です。
9250 変更しようとした場合はエラーが通知されます。
9251 @c COMMON
9252
9253 @c EN
9254 @b{Note for the compatibility}:
9255 We used to recognize a syntax @code{\xNN} (two-digit hexadecimal number,
9256 without semicolon terminator) as a character; for example,
9257 @code{#[\x0d\x0a]} as a return and a newline. We still support it
9258 when we don't see the terminating semicolon, for the compatibility.
9259 There are ambiguous cases: @code{#[\x0a;]} means only a newline
9260 in the current syntax, but a newline and a semicolon in legacy syntax.
9261
9262 Setting the reader mode to @code{legacy} restores the old behavior.
9263 Setting the reader mode to @code{warn-legacy} makes it work like the default
9264 behavior, but prints warning when it finds legacy syntax.
9265 @xref{Reader lexical mode}, for the details.
9266
9267 To write code that can work both in new and old syntax, use @code{\u} escape.
9268 @c JP
9269 @b{互換性への注}:
9270 以前は、@code{\xNN} (2桁固定の16進数、終端のセミコロン無し) を文字と認識していました。
9271 例えば@code{#[\x0d\x0a]}はリターン文字と改行文字集合を意味していました。
9272 互換性のため、終端のセミコロンが見当たらない場合は古い構文もサポートされます。
9273 しかし曖昧な場合もあります。@code{#[\x0a;]}は新しい構文では
9274 改行文字のみのセットですが、古い構文では改行文字とセミコロンになります。
9275
9276 リーダのモードを@code{legacy}にセットすると、常に古い構文で認識されます。
9277 リーダのモードを@code{warn-legacy}にセットすると、
9278 デフォルトと同じように振る舞いますが、古い構文を見つけた場合は警告が出力されます。
9279 詳しくは@ref{Reader lexical mode}を参照してください。
9280
9281 古い構文と新しい構文の両方で動作するコードが必要な場合は、@code{\u}エスケープを
9282 使ってください。
9283 @c COMMON
9284 @end deftp
9285
9286 @node Predefined character sets, Character set operations, Character set literals, Character sets
9287 @subsection Predefined character sets
9288 @c NODE 定義済み文字集合
9289
9290 @c EN
9291 We provide a bunch of predefined character sets, including the ones
9292 defined in R7RS charset library (@pxref{R7RS character sets}).
9293 Those character sets are immutable.
9294 @c JP
9295 定義済みの文字集合がいくつか提供されています。
9296 R7RS文字集合ライブラリで定義されているものも含まれます(@ref{R7RS character sets}参照)。
9297 これらの文字集合は変更不可です。
9298 @c COMMON
9299
9300 @defvar char-set:letter
9301 [R7RS charset]
9302 @c EN
9303 Letters (Unicode general category @code{Lu}, @code{Ll}, @code{Lt},
9304 @code{Lm} and @code{Lo}).
9305 @c JP
9306 文字 (Unicodeカテゴリ@code{Lu}、@code{Ll}、@code{Lt}、@code{Lm}、@code{Lo})。
9307 @c COMMON
9308 @end defvar
9309
9310
9311 @defvar char-set:lower-case
9312 @defvarx char-set:upper-case
9313 @defvarx char-set:title-case
9314 [R7RS charset]
9315 @c EN
9316 Lower case, upper case and title case letters
9317 (Unicode general category @code{Ll}, @code{Lu} and @code{Lt}, respectively).
9318 @c JP
9319 小文字、大文字、タイトルケース文字
9320 (それぞれ、Unicodeカテゴリ@code{Ll}、@code{Lu}、@code{Lt})。
9321 @c COMMON
9322 @end defvar
9323
9324 @defvar char-set:digit
9325 [R7RS charset]
9326 @c EN
9327 Digit characters (Unicode general category @code{Nd}). Note that this
9328 contains many more characters than ASCII @code{0} to @code{9}. If you
9329 need @code{#[0-9]}, use @code{char-set:ascii-digit}.
9330 @c JP
9331 数字 (Unicodeカテゴリ@code{Nd})。
9332 これには非ASCIIの数字もたくさん含まれています。
9333 ASCIIの数字(@code{#[0-9]})だけが欲しい時は@code{char-set:ascii-digit}を
9334 使ってください。
9335 @c COMMON
9336 @end defvar
9337
9338 @defvar char-set:hex-digit
9339 [R7RS charset]
9340 @c EN
9341 Digit characters used for hexadecimal, i.e. @code{#[0-9A-Fa-f]}. This does
9342 not contain other Unicode digit characters, for it isn't practical
9343 to mix non-ascii digit characters with hexadecimal notation.
9344 @c JP
9345 16進数表記に使われる文字、つまり@code{#[0-9A-Fa-f]}。
9346 これにはASCII外の文字は含まれません。
9347 @c COMMON
9348 @end defvar
9349
9350 @defvar char-set:letter+digit
9351 [R7RS charset]
9352 @c EN
9353 Union of @code{char-set:letter} and @code{char-set:digit}.
9354 @c JP
9355 @code{char-set:letter}と@code{char-set:digit}の和集合です。
9356 @c COMMON
9357 @end defvar
9358
9359 @defvar char-set:graphic
9360 [R7RS charset]
9361 @c EN
9362 Characters that has some glyph. Union of letters, numbers, punctuations
9363 and symbols.
9364 @c JP
9365 何らかのグリフを持っている文字。通常文字、数字、句読点、シンボルの和集合です。
9366 @c COMMON
9367 @end defvar
9368
9369 @defvar char-set:printing
9370 [R7RS charset]
9371 @c EN
9372 Union of @code{char-set:graphic} and @code{char-set:whitespace}.
9373 @c JP
9374 @code{char-set:graphic}と@code{char-set:whitespace}の和集合です。
9375 @c COMMON
9376 @end defvar
9377
9378 @defvar char-set:whitespace
9379 @defvarx char-set:blank
9380 [R7RS charset]
9381 @c EN
9382 Whitespace and blank characters; @code{char-set:whitespace}
9383 includes @code{#\tab}, @code{#\newline}, @code{#\u000B} (vertical tab),
9384 @code{#\page}, @code{#\return}, and all characters in general category
9385 @code{Zs}, @code{Zl}, @code{Zp}, while @code{char-set:blank}
9386 includes @code{#\tab} and all characters in general category @code{Zs}.
9387 Note that @code{char-set:whitespace} is the same set of characters
9388 that Scheme reader treats as whitespace characters.
9389 @c JP
9390 空白文字およびブランク文字です。
9391 空白文字@code{char-set:whitespace}は、
9392 @code{#\tab}、@code{#\newline}、@code{#\u000B} (vertical tab)、
9393 @code{#\page}、@code{#\return}、および
9394 一般カテゴリ@code{Zs}、@code{Zl}、@code{Zp}の文字です。
9395 一方、ブランク文字@code{char-set:blank}は、
9396 @code{#\tab}と一般カテゴリ@code{Zs}の文字です。
9397 @code{char-set:whitespace}は、Schemeのリーダが空白扱いにする文字の集合と一致します。
9398 @c COMMON
9399 @end defvar
9400
9401 @defvar char-set:iso-control
9402 [R7RS charset]
9403 @c EN
9404 Control characters (Unicode general category @code{Cc}).
9405 @c JP
9406 制御文字 (Unicode一般カテゴリ@code{Cc})。
9407 @c COMMON
9408 @end defvar
9409
9410
9411 @defvar char-set:punctuation
9412 [R7RS charset]
9413 @c EN
9414 Punctuation characters (Unicode general category
9415 @code{Pc}, @code{Pd}, @code{Ps}, @code{Pe}, @code{Pi}, @code{Pf}
9416 and @code{Po}).
9417 @c JP
9418 句読点 (Unicode一般カテゴリ
9419 @code{Pc}, @code{Pd}, @code{Ps}, @code{Pe}, @code{Pi}, @code{Pf}, @code{Po})。
9420 @c COMMON
9421 @end defvar
9422
9423 @defvar char-set:symbol
9424 [R7RS charset]
9425 @c EN
9426 Symbol characters (Unicode general category @code{Sm}, @code{Sc},
9427 @code{Sk} and @code{So}).
9428 @c JP
9429 シンボル文字 (Unicode一般カテゴリ
9430 @code{Sm}, @code{Sc}, @code{Sk}, @code{So})。
9431 @c COMMON
9432 @end defvar
9433
9434 @defvar char-set:ascii
9435 [R7RS charset]
9436 @c EN
9437 Contains all ASCII characters (U+0000 to U+007f).
9438 @c JP
9439 すべてのASCII文字 (U+0000 to U+007f)。
9440 @c COMMON
9441 @end defvar
9442
9443 @defvar char-set:empty
9444 [R7RS charset]
9445 @c EN
9446 An empty character set.
9447 @c JP
9448 空の文字集合。
9449 @c COMMON
9450 @end defvar
9451
9452 @defvar char-set:full
9453 [R7RS charset]
9454 @c EN
9455 A character set that includes all characters.
9456 @c JP
9457 すべての文字を含む文字集合。
9458 @c COMMON
9459 @end defvar
9460
9461 @defvar char-set:word
9462 @c EN
9463 A word constituent characters. In the current version,
9464 it is equivalent to @code{char-set:ascii-word} (@code{#[0-9A-Za-z_]})
9465 but in future versions we may extend this to other Unicode characters.
9466 If you intend to mean ASCII-only words, use @code{char-set:ascii-word}.
9467 @c JP
9468 単語を構成する文字。今のところ、これは@code{char-set:ascii-word}、
9469 つまり@code{#[0-9A-Za-z_]}と同じです。
9470 ただ、将来はUnicodeの全域に意味を拡張するかもしれません。
9471 ASCIIの範囲内だけを扱いたい場合は@code{char-set:ascii-word}を使ってください。
9472 @c COMMON
9473 @end defvar
9474
9475
9476 @defvar char-set:ascii-letter
9477 @defvarx char-set:ascii-lower-case
9478 @defvarx char-set:ascii-upper-case
9479 @defvarx char-set:ascii-digit
9480 @defvarx char-set:ascii-letter+digit
9481 @defvarx char-set:ascii-graphic
9482 @defvarx char-set:ascii-printing
9483 @defvarx char-set:ascii-whitespace
9484 @defvarx char-set:ascii-blank
9485 @defvarx char-set:ascii-control
9486 @defvarx char-set:ascii-punctuation
9487 @defvarx char-set:ascii-symbol
9488 @defvarx char-set:ascii-word
9489 @c EN
9490 These are intersection of @code{char-set:ascii} and
9491 the corresponding char set without @code{ascii-}.
9492 (@code{char-set:ascii-control} corresponds to @code{char-set:iso-control}).
9493 @c JP
9494 これらはそれぞれ、@code{ascii-}を除いた名前の文字集合と@code{char-set:ascii}と
9495 の積集合です。
9496 @c COMMON
9497
9498 @c EN
9499 The @code{\d}, @code{\s} and @code{\w} notation in the char-set literal
9500 and regexp literal corresponds to @code{char-set:ascii-digit},
9501 @code{char-set:ascii-whitespace}, and @code{char-set:ascii-word},
9502 respectively (not the Unicode set).
9503 @c JP
9504 文字集合リテラルおよび正規表現リテラルにおける
9505 @code{\d}、@code{\s}、@code{\w}はそれぞれ
9506 @code{char-set:ascii-digit}、
9507 @code{char-set:ascii-whitespace}、@code{char-set:ascii-word}に
9508 対応します (Unicode版ではなく)。
9509 @c COMMON
9510
9511 @c EN
9512 The POSIX character class notation, such as @code{[:alpha:]} in
9513 char-set literal and regexp literal, refers to these ASCII-only
9514 charsets.
9515 @c JP
9516 また、@code{[:alpha:]}などのPOSIX文字クラス表記もこちらのASCII版の方に対応します。
9517 @c COMMON
9518
9519 @c EN
9520 Note: We don't have @code{char-set:ascii-title-case} and
9521 @code{char-set:ascii-hex-digit}. There's no titlecase letter
9522 in ASCII range. And @code{char-set:hex-digit} is limited to ASCII
9523 by definition.
9524 @c JP
9525 なお、@code{char-set:ascii-title-case}と@code{char-set:ascii-hex-digit}は
9526 ありません。ASCIIの範囲内にtitlecaseにあたる文字はなく、
9527 また@code{char-set:hex-digit}はそれ自体ASCII範囲に限定されています。
9528 @c COMMON
9529 @end defvar
9530
9531 @defvar char-set:Lu
9532 @defvarx char-set:Ll
9533 @defvarx char-set:Lt
9534 @defvarx char-set:Lm
9535 @defvarx char-set:Lo
9536 @defvarx char-set:Mn
9537 @defvarx char-set:Mc
9538 @defvarx char-set:Me
9539 @defvarx char-set:Nd
9540 @defvarx char-set:Nl
9541 @defvarx char-set:No
9542 @defvarx char-set:Pc
9543 @defvarx char-set:Pd
9544 @defvarx char-set:Ps
9545 @defvarx char-set:Pe
9546 @defvarx char-set:Pi
9547 @defvarx char-set:Pf
9548 @defvarx char-set:Po
9549 @defvarx char-set:Sm
9550 @defvarx char-set:Sc
9551 @defvarx char-set:Sk
9552 @defvarx char-set:So
9553 @defvarx char-set:Zs
9554 @defvarx char-set:Zl
9555 @defvarx char-set:Zp
9556 @defvarx char-set:Cc
9557 @defvarx char-set:Cf
9558 @defvarx char-set:Cs
9559 @defvarx char-set:Co
9560 @defvarx char-set:Cn
9561 @c EN
9562 Each character set contains the corresponding Unicode characters with
9563 the given general category; e.g. @code{char-set:Lu} contains all characters
9564 of the general category @code{Lu}.
9565 @c JP
9566 それぞれ、対応するUniocdeの一般カテゴリに属する文字の集合です。
9567 例えば@code{char-set:Lu}は一般カテゴリ@code{Lu}の文字の集合です。
9568 @c COMMON
9569 @end defvar
9570
9571 @defvar char-set:L
9572 @defvarx char-set:LC
9573 @defvarx char-set:M
9574 @defvarx char-set:N
9575 @defvarx char-set:P
9576 @defvarx char-set:S
9577 @defvarx char-set:Z
9578 @defvarx char-set:C
9579 @c EN
9580 Each character set contains the Unicode characters with the general
9581 category starting with the letter; e.g. @code{char-set:L} is union
9582 of @code{char-set:Lu}, @code{char-set:Ll}, @code{char-set:Lt},
9583 @code{char-set:Lm} and @code{char-set:Lo}.
9584
9585 @code{char-set:LC} is for cased-letters, the union of
9586 @code{char-set:Lt}, @code{char-set:Ll}, @code{char-set:Lu}.
9587 @c JP
9588 各文字集合は、その文字で始まるUnicodeの一般カテゴリのすべての文字の集合です。
9589 例えば@code{char-set:L}は、@code{char-set:Lu}、
9590 @code{char-set:Ll}、@code{char-set:Lt}、
9591 @code{char-set:Lm}、@code{char-set:Lo}の和集合です。
9592
9593 @code{char-set:LC}は大文字小文字の区別のある文字の集合、つまり
9594 @code{char-set:Lt}、@code{char-set:Ll}、@code{char-set:Lu}の和集合です。
9595 @c COMMON
9596 @end defvar
9597
9598 @node Character set operations, , Predefined character sets, Character sets
9599 @subsection Character set operations
9600 @c NODE 文字集合の操作
9601
9602 @c EN
9603 See also @ref{R7RS character sets} for the comprehensive character set
9604 operations.
9605 @c JP
9606 包括的な文字集合操作については、@ref{R7RS character sets}も参照してください。
9607 @c COMMON
9608
9609
9610 @defun char-set? obj
9611 [R7RS charset]
9612 @c EN
9613 Returns true if and only if @var{obj} is a character set object.
9614 @c JP
9615 @var{obj}が文字集合であれば真の値を返します。
9616 @c COMMON
9617 @end defun
9618
9619 @defun char-set-immutable? char-set
9620 @c EN
9621 Returns @code{#t} if @var{char-set} is an immutable char-set,
9622 @code{#f} if it's a mutable char-set.
9623 @c JP
9624 @var{char-set}が変更不可の文字集合であれば@code{#t}を、変更可能な文字集合であれば
9625 @code{#f}を返します。
9626 @c COMMON
9627 @end defun
9628
9629 @defun char-set-contains? char-set char
9630 [R7RS charset]
9631 @c EN
9632 Returns true if and only if a character set object
9633 @var{char-set} contains a character @var{char}.
9634 @c JP
9635 文字集合@var{char-set}が文字@var{char}を含んでいれば真の値を返します。
9636 @c COMMON
9637 @example
9638 (char-set-contains? #[a-z] #\y) @result{} #t
9639 (char-set-contains? #[a-z] #\3) @result{} #f
9640
9641 (char-set-contains? #[^ABC] #\A) @result{} #f
9642 (char-set-contains? #[^ABC] #\D) @result{} #t
9643
9644 @c JP
9645 (char-set-contains? #[あ-お] #\う) @result{} #t
9646 (char-set-contains? #[あ-お] #\ぷ) @result{} #f
9647 @c COMMON
9648 @end example
9649 @end defun
9650
9651 @deffn {Generic application} @var{char-set} @var{char}
9652 @c EN
9653 A char-set object can be applied to a character, and it
9654 works just like @code{(char-set-contains? char-set char)}.
9655 @c JP
9656 文字集合オブジェクトは文字に適用されると、
9657 @code{(char-set-contains? char-set char)} のように振る舞います。
9658 @c COMMON
9659
9660 @example
9661 (#[a-z] #\a) @result{} #t
9662 (#[a-z] #\A) @result{} #f
9663
9664 (use gauche.collection)
9665 (filter #[a-z] "CharSet") @result{} (#\h #\a #\r #\e #\t)
9666 @end example
9667 @end deffn
9668
9669 @defun char-set char @dots{}
9670 [R7RS charset]
9671 @c EN
9672 Creates a character set that contains @var{char} @dots{}.
9673 @c JP
9674 文字@var{char} @dots{} からなる文字集合を作成して返します。
9675 @c COMMON
9676 @example
9677 (char-set #\a #\b #\c) @result{} #[a-c]
9678 @c JP
9679 (char-set #\あ #\い #\う) @result{} #[あいう]
9680 @c COMMON
9681 @end example
9682 @end defun
9683
9684 @defun char-set-size char-set
9685 [R7RS charset]
9686 @c EN
9687 Returns a number of characters in the given charset.
9688 @c JP
9689 文字集合に含まれる文字数を返します。
9690 @c COMMON
9691
9692 @example
9693 gosh> (char-set-size #[])
9694 0
9695 gosh> (char-set-size #[[:alnum:]])
9696 62
9697 @end example
9698 @end defun
9699
9700 @defun char-set-copy char-set
9701 [R7RS charset]
9702 @c EN
9703 Copies a character set @var{char-set}.
9704 @c JP
9705 @var{char-set}のコピーを作って返します。
9706 @c COMMON
9707 @end defun
9708
9709 @defun char-set-complement char-set
9710 @defunx char-set-complement! char-set
9711 [R7RS charset]
9712 @c EN
9713 Returns a complement set of @var{char-set}. The former always
9714 returns a new set, while the latter may reuse the given charset.
9715 @c JP
9716 @var{char-set}の補集合を返します。上の手続きは常に新たな集合を作って返しますが、
9717 下の手続きは引数を変更して返す可能性があります。
9718 @c COMMON
9719 @end defun
9720
9721
9722 @c ----------------------------------------------------------------------
9723 @node Strings, Regular expressions, Character sets, Core library
9724 @section Strings
9725 @c NODE 文字列
9726
9727 @deftp {Builtin Class} <string>
9728 @clindex string
9729 @c EN
9730 A string class.
9731 @c JP
9732 文字列のクラスです。
9733 @c COMMON
9734 @end deftp
9735
9736 @c EN
9737 It should be emphasized that Gauche's @emph{internal} string object,
9738 @emph{string body}, is immutable.
9739 To comply R7RS in which strings are mutable, a Scheme-level
9740 string object is an indirect pointer to a string body.
9741 Mutating a string means that Gauche creates a new immutable
9742 string body that reflects the changes, then swap the pointer
9743 in the Scheme-level string object.
9744
9745 This may affect some assumptions on the cost of string operations.
9746
9747 @itemize
9748 @item
9749 Copying string is O(1), no matter how long the string is, since
9750 the same string body is shared.
9751 @item
9752 Taking substring usually is also O(1), for the resulting string
9753 shares the substring of the original string body. Gauche may copy
9754 a part of the string for better memory management, but the visible
9755 cost should stay pretty close to O(1). (However, note that accessing
9756 to a specific point by index within the original string may cost
9757 O(N) because of multibyte string; which is a different story).
9758 @item
9759 On the other hand, mutating a string cost O(N) where N is the length
9760 of string, even for replacing a character.
9761 @end itemize
9762
9763 Gauche does not attempt to make string mutation faster;
9764 @code{(string-set! s k c)} is exactly as slow as to take
9765 two substrings, before and after of k-th character, and
9766 concatenate them with a single-character string inbetween.
9767 So, just avoid string mutations; we believe it's a better practice.
9768 See also @ref{String constructors}.
9769 @c JP
9770 GaucheではSchemeの文字列は、内部的には、変更不可能なオブジェクト(文字列実体)を
9771 用いて表現されている、ということを強調しておきます。
9772 文字列が変更可能であるR7RSの仕様を満たすために、Schemeレベルの文字列は
9773 文字列実体への間接ポインタとなっています。文字列を変更すると、
9774 変更を反映した新しいstring bodyが作成され、Schemeレベルの文字列が
9775 新しい文字列実体を指すように変更されます。
9776
9777 このことから、文字列操作の性能を見積る場合に注意が必要です。
9778
9779 @itemize
9780 @item
9781 文字列のコピーは、それがどんなに長い文字列であっても常にO(1)です。
9782 文字列実体は共有されるからです。
9783 @item
9784 部分文字列を取る操作も通常はO(1)です。文字列実体を部分的に共有するからです。
9785 メモリ管理上の都合から文字列実体の一部がコピーされる可能性はありますが、
9786 ほとんどの場合はO(1)とみなして構いません。(ただし、マルチバイト文字処理の都合上、
9787 文字インデックスで文字列の途中を指定する操作は別途O(N)を要する場合があります)
9788 @item
9789 一方で、文字列の変更はたとえ1文字の変更であっても、文字列実体の長さNに
9790 比例したO(N)のコストを必要とします。
9791 @end itemize
9792
9793 Gaucheはそもそも文字列の変更に関して全く最適化を行っていません。
9794 @code{(string-set! s k c)}は、k番目の文字の前後の部分文字列を取って、
9795 c一文字の文字列を間に挟んで継ぎ足すことで新たな文字列を作るのと
9796 全く同じコストがかかります。
9797 文字列を変更不可として扱う方が良いプログラミングスタイルだと考えるからです。
9798 @ref{String constructors}も参照してください。
9799 @c COMMON
9800
9801 @c EN
9802 R7RS string operations are very minimal. Gauche supports some
9803 extra built-in operations, and also a rich string library
9804 defined in SRFI-13. @xref{String library}, for details about SRFI-13.
9805 @c JP
9806 R7RSに定義されている文字列操作は非常に限られています。
9807 Gaucheでは追加の組込み手続きのほか、
9808 SRFI-13に定義されている豊富な文字列ライブラリを備えています。
9809 SRFI-13については@ref{String library}を参照してください。
9810 @c COMMON
9811
9812 @menu
9813 * String syntax::
9814 * String predicates::
9815 * String constructors::
9816 * String interpolation::
9817 * String cursors::
9818 * String indexing::
9819 * String accessors & modifiers::
9820 * String comparison::
9821 * String utilities::
9822 * Incomplete strings::
9823 @end menu
9824
9825 @node String syntax, String predicates, Strings, Strings
9826 @subsection String syntax
9827 @c NODE 文字列の表記
9828
9829 @deftp {Reader Syntax} @code{"}@dots{}@code{"}
9830 [R7RS+]
9831 @c EN
9832 Denotes a literal string. Inside the double quotes, the following
9833 backslash escape sequences are recognized.
9834 @c JP
9835 リテラル文字列です。ダブルクオートの中では、
9836 以下のエスケープシーケンスが認識されます。
9837 @c COMMON
9838
9839 @table @code
9840 @item \"
9841 @c EN
9842 [R7RS] Double-quote character
9843 @c JP
9844 [R7RS] ダブルクオート文字
9845 @c COMMON
9846 @item \\
9847 @c EN
9848 [R7RS] Backslash character
9849 @c JP
9850 [R7RS] バックスラッシュ文字
9851 @c COMMON
9852 @item \n
9853 @c EN
9854 [R7RS] Newline character (ASCII 0x0a).
9855 @c JP
9856 [R7RS] 改行文字 (ASCII 0x0a)
9857 @c COMMON
9858 @item \r
9859 @c EN
9860 [R7RS] Return character (ASCII 0x0d).
9861 @c JP
9862 [R7RS] 復帰文字 (ASCII 0x0d)
9863 @c COMMON
9864 @item \f
9865 @c EN
9866 Form-feed character (ASCII 0x0c).
9867 @c JP
9868 フォームフィード (ASCII 0x0c)
9869 @c COMMON
9870 @item \t
9871 @c EN
9872 [R7RS] Tab character (ASCII 0x09)
9873 @c JP
9874 [R7RS] タブ文字 (ASCII 0x09)
9875 @c COMMON
9876 @item \a
9877 @c EN
9878 [R7RS] Alarm character (ASCII 0x07).
9879 @c JP
9880 [R7RS] アラーム文字 (ASCII 0x07)
9881 @c COMMON
9882 @item \b
9883 @c EN
9884 [R7RS] Backspace character (ASCII 0x08).
9885 @c JP
9886 [R7RS] バックスペース文字 (ASCII 0x08)
9887 @c COMMON
9888 @item \0
9889 @c EN
9890 ASCII NUL character (ASCII 0x00).
9891 @c JP
9892 NUL文字 (ASCII 0x00)
9893 @c COMMON
9894 @item \<whitespace>*<newline><whitespace>*
9895 @c EN
9896 [R7RS] Ignored. This can be used to break a long string literal for readability.
9897 This escape sequence is introduced in R6RS.
9898 @c JP
9899 [R7RS] 無視されます。長い文字列リテラルを読みやすさのために折り返す時に便利です。
9900 このエスケープシーケンスはR6RSで導入されました。
9901 @c COMMON
9902 @item \x@var{N};
9903 @c EN
9904 [R7RS] A character whose Unicode codepoint is represented by
9905 hexadecimal number @var{N}, which is any number of hexadecimal digits.
9906 (See the compatibility notes below.)
9907 @c JP
9908 [R7RS] 16進数@var{N}で表現されたUnicodeコードポイントの文字。
9909 16進数は何桁でも良い。(下の互換性に関する注参照。)
9910 @c COMMON
9911 @item \u@var{NNNN}
9912 @c EN
9913 A character whose UCS2 code is represented by four-digit
9914 hexadecimal number @var{NNNN}.
9915 @c JP
9916 4桁の16進数@var{NNNN}によって示されるUCS2コードを持つ文字。
9917 @c COMMON
9918 @item \U@var{NNNNNNNN}
9919 @c EN
9920 A character whose UCS4 code is represented by eight-digit
9921 hexadecimal number @var{NNNNNNNN}.
9922 @c JP
9923 8桁の16進数@var{NNNNNNNN}によって示されるUCS4コードを持つ文字。
9924 @c COMMON
9925 @end table
9926
9927 @c EN
9928 The following code is an example of backslash-newline escape sequence:
9929 @c JP
9930 下はバックスラッシュ-改行エスケープシーケンスの使用例です。
9931 @c COMMON
9932 @example
9933 (define *message* "\
9934 This is a long message \
9935 in a literal string.")
9936
9937 *message*
9938 @result{} "This is a long message in a literal string."
9939 @end example
9940
9941 @c EN
9942 Note the whitespace just after `message'. Since any whitespaces
9943 before `in' is eaten by the reader, you have to put a whitespace
9944 between `message' and the following backslash. If you want to include
9945 an actual newline character in a string, and any indentation after it,
9946 you can put '\n' in the next line like this:
9947 @c JP
9948 `message' の後の空白に注意してください。`in'の前の空白は読み込みルーチンによって
9949 無視されてしまうので、空白を入れたければ`message'と続くバックスラッシュの間に
9950 入れる必要があります。もし文字列中に実際に改行文字を入れ、さらにその後の
9951 文字列をインデントさせたい場合は次のようにすると良いでしょう:
9952 @c COMMON
9953
9954 @example
9955 (define *message/newline* "\
9956 This is a long message, \
9957 \n with a line break.")
9958 @end example
9959
9960 @c EN
9961 @b{Note for the compatibility}:
9962 We used to recognize a syntax @code{\xNN} (two-digit hexadecimal number,
9963 without semicolon terminator) as a character in a string; for example,
9964 @code{"\x0d\x0a"} was the same as @code{"\r\n"}. We still support it
9965 when we don't see the terminating semicolon, for the compatibility.
9966 There are ambiguous cases: @code{"\0x0a;"} means @code{"\n"} in the
9967 current syntax, while @code{"\n;"} in the legacy syntax.
9968
9969 Setting the reader mode to @code{legacy} restores the old behavior.
9970 Setting the reader mode to @code{warn-legacy} makes it work like the default
9971 behavior, but prints warning when it finds legacy syntax.
9972 @xref{Reader lexical mode}, for the details.
9973 @c JP
9974 @b{互換性に関する注}:
9975 以前は、@code{\xNN} (2桁固定の16進数、終端のセミコロン無し) を
9976 文字列中の文字と認識していました。
9977 例えば@code{"\x0d\x0a"}は@code{"\r\n"}と同じでした。
9978 互換性のため、終端のセミコロンが見当たらない場合は古い構文もサポートされます。
9979 しかし曖昧な場合もあります。@code{"\x0a;"}は新しい構文では
9980 @code{"\n"}と同じですが、、古い構文では@code{"\n;"}となります。
9981
9982 リーダのモードを@code{legacy}にセットすると、常に古い構文で認識されます。
9983 リーダのモードを@code{warn-legacy}にセットすると、
9984 デフォルトと同じように振る舞いますが、古い構文を見つけた場合は警告が出力されます。
9985 詳しくは@ref{Reader lexical mode}を参照してください。
9986 @c COMMON
9987 @end deftp
9988
9989
9990 @node String predicates, String constructors, String syntax, Strings
9991 @subsection String predicates
9992 @c NODE 文字列に関する述語
9993
9994 @defun string? obj
9995 [R7RS base]
9996 @c EN
9997 Returns @code{#t} if @var{obj} is a string, @code{#f} otherwise.
9998 @c JP
9999 @var{obj}が文字列なら@code{#t}を、そうでなければ@code{#f}を返します。
10000 @c COMMON
10001 @end defun
10002
10003 @defun string-immutable? obj
10004 @c EN
10005 Returns @code{#t} if @var{obj} is an immutable string, @code{#f} otherwise
10006
10007 String literals, and the strings returned from certain procedures such
10008 as @code{symbol->string} are immutable. To ensure you get
10009 an immutable string in a program, you can use @code{string-copy-immutable}.
10010 @c JP
10011 @var{obj}が変更不可な文字列なら@code{#t}を、そうでなければ@code{#f}を返します。
10012
10013 文字列リテラルおよび、@code{symbol->string}などいくつかの手続きから
10014 返される文字列は変更不可です。プログラム中で変更不可の文字列を確実に手に入れたい場合は
10015 @code{string-copy-immutable}が使えます。
10016 @c COMMON
10017 @end defun
10018
10019 @defun string-incomplete? obj
10020 @c EN
10021 Returns @code{#t} if @var{obj} is an incomplete string, @code{#f} otherwise
10022 @c JP
10023 @var{obj}が不完全文字列なら@code{#t}を、そうでなければ@code{#f}を返します。
10024 @c COMMON
10025 @end defun
10026
10027 @node String constructors, String interpolation, String predicates, Strings
10028 @subsection String constructors
10029 @c NODE 文字列の作成
10030
10031 @defun make-string k :optional char
10032 [R7RS base]
10033 @c EN
10034 Returns a string of length @var{k}. If optional @var{char} is given,
10035 the new string is filled with it. Otherwise, the string is filled with
10036 a whitespace. The result string is always complete.
10037
10038 @example
10039 (make-string 5 #\x) @result{} "xxxxx"
10040 @end example
10041
10042 Note that the algorithm to allocate a string by @code{make-string} and
10043 then fills it one character at a time is @emph{extremely} inefficient
10044 in Gauche, and should be avoided.
10045
10046 In Gauche, a string is simply a pointer to an immutable string content.
10047 If you mutate a string by, e.g. @code{string-set!}, Gauche allocates
10048 whole new immutable string content, copies the original content with
10049 modification, then swap the pointer of the original string. It is no
10050 more efficient than making a new copy.
10051
10052 You can use an output string port for a string construction
10053 (@pxref{String ports}).
10054 Even creating a list of characters and
10055 using @code{list->string} is faster than using @code{make-string} and
10056 @code{string-set!}.
10057 @c JP
10058 長さ@var{k}の文字列を作成して返します。
10059 @var{char}が与えられればそれで内容を満たします。@var{char}が与えられなければ
10060 空白文字で満たされます。常に完全な文字列が返されます。
10061
10062 @example
10063 (make-string 5 #\x) @result{} "xxxxx"
10064 (make-string 5 #\ふ) @result{} "ふふふふふ"
10065 @end example
10066
10067 @code{make-string}で必要な長さの文字列をアロケートして、@code{string-set!}
10068 で順番に埋めて行くアルゴリズムは、Gaucheでは@emph{極めて}非効率であることに
10069 注意してください。
10070
10071 Gaucheの文字列オブジェクトは、変更不可能な文字列本体への単なるポインタです。
10072 @code{string-set!}等の文字列を破壊的変更する操作は、
10073 実際には変更箇所以外は元の文字列本体をコピーした新たな文字列本体をアロケートして、
10074 元の文字列オブジェクトのポインタを差し替えるこようになっています。
10075 従って、文字列のコピーを作るのと同等の効率となります。
10076
10077 文字列の順次作成に適しているのは文字列ポートです
10078 (@ref{文字列ポート}参照)。それが使えない場合、
10079 文字のリストを作成し、@code{list->string}で変換する方がまだ@code{make-string}と
10080 @code{string-set!}を使うより良いでしょう。
10081 @c COMMON
10082 @end defun
10083
10084 @defun make-byte-string k :optional byte
10085 @c EN
10086 Creates and returns an incomplete string o size @var{k}.
10087 If @var{byte} is given,
10088 which must be an exact integer, and its lower 8 bits
10089 are used to initialize every byte in the created string.
10090 @c JP
10091 大きさ@var{k}の不完全な文字列を作成して返します。
10092 @var{byte}が与えられた場合は、その下位1バイトで文字列の各バイトを初期化します。
10093 @var{byte}は正確な整数でなければなりません。
10094 @c COMMON
10095 @end defun
10096
10097 @defun string char @dots{}
10098 [R7RS base]
10099 @c EN
10100 Returns a string consisted by @var{char} @dots{}.
10101 @c JP
10102 文字@var{char} @dots{} から構成された文字列を返します。
10103 @c COMMON
10104 @end defun
10105
10106 @deffn {Generic Function} x->string obj
10107 @c EN
10108 A generic coercion function.
10109 Returns a string representation of @var{obj}.
10110 The default methods are defined as follows: strings are returned
10111 as is, numbers are converted by @code{number->string}, symbols are
10112 converted by @code{symbol->string}, and other objects are
10113 converted by @code{display}.
10114
10115 Other class may provide a method to customize the behavior.
10116 @c JP
10117 文字列への強制型変換手続きです。
10118 @var{obj}の文字列表現を返します。
10119 デフォルトのメソッドでは、文字列はそのまま返され、数値は@code{number->string}で、
10120 シンボルは@code{symbol->string}で変換され、その他のオブジェクトは@code{display}表現
10121 が使われます。
10122
10123 他のクラスはこのメソッドを定義することにより、独自の変換関数を提供することができます。
10124 @c COMMON
10125 @end deffn
10126
10127 @node String interpolation, String cursors, String constructors, Strings
10128 @subsection String interpolation
10129 @c NODE 文字列の補間
10130
10131 @c EN
10132 The term "string interpolation" is used in various scripting languages
10133 such as Perl and Python to refer to the feature to embed expressions
10134 in a string literal, which are evaluated and then their results are
10135 inserted into the string literal at run time.
10136 @c JP
10137 「文字列の補間(string interpolation)」という用語は、
10138 PerlやPythonなど様々なスクリプト言語で、文字列リテラル内に式を埋め込んでおき
10139 実行時に式を評価した値をそのリテラル内に埋め込む機能を指します。
10140 @c COMMON
10141
10142 @c EN
10143 Scheme doesn't define such a feature, but Gauche implements it as a
10144 reader macro.
10145 @c JP
10146 Schemeはそのような機能を定義していませんが、Gaucheではリーダーマクロを使って
10147 文字列の補間を実装しました。
10148 @c COMMON
10149
10150 @deftp {Reader Syntax} @code{#}@var{string-literal}
10151 @lxindex #"
10152 @c EN
10153 Evaluates to a string. If @var{string-literal} contains the
10154 character sequence @code{~@var{expr}}, where
10155 @var{expr} is a valid external representation
10156 of a Scheme expression, @var{expr} is evaluated and
10157 its result is inserted in the original place (by using @code{x->string},
10158 see @ref{String constructors}).
10159 @c JP
10160 文字列に評価されます。@var{string-literal}内に、@code{~@var{expr}}
10161 というシーケンス(ここで@var{expr}は有効なScheme式の外部表現)が
10162 現われたら、@var{expr}が評価されてその結果がもとの位置に埋め込まれます。
10163 結果の文字列化には@code{x->string}が使われます(@ref{String constructors}参照)。
10164 @c COMMON
10165
10166 @c EN
10167 The tilde and the following expression must be adjacent (without containing
10168 any whitespace characters), or it is not recognized as a special sequence.
10169 @c JP
10170 チルダと続く式とは、空白文字等を入れずに隣接していなければなりません。
10171 そうでない場合は置換されません。
10172 @c COMMON
10173
10174 @c EN
10175 To include a tilde itself immediately followed by non-delimiting
10176 character, use @code{~~}.
10177 @c JP
10178 すぐ後ろに非空白文字が来る場所にチルダ自身を埋め込みたい場合は
10179 @code{~~}とします。
10180 @c COMMON
10181
10182 @c EN
10183 Other characters in the @var{string-literal} are copied as is.
10184 @c JP
10185 それ以外の@var{string-literal}内の文字シーケンスはそのままコピーされます。
10186 @c COMMON
10187
10188 @c EN
10189 If you use a variable as @var{expr} and need to delimit it from the
10190 subsequent string, you can use the symbol escape syntax
10191 using `|' character, as shown in the last two examples below.
10192 @c JP
10193 @var{Expr}に単独の変数を使う場合で、それに続く文字列と変数名を区切りたい
10194 場合は、`|'文字を使ったシンボルエスケープ構文が使えます。下の例の最後の
10195 2つを見て下さい。
10196 @c COMMON
10197
10198 @example
10199 #"This is Gauche, version ~(gauche-version)."
10200 @result{} "This is Gauche, version @VERSION@."
10201
10202 #"Date: ~(sys-strftime \"%Y/%m/%d\" (sys-localtime (sys-time)))"
10203 @result{} "Date: 2002/02/18"
10204
10205 (let ((a "AAA")
10206 (b "BBB"))
10207 #"xxx ~a ~b zzz")
10208 @result{} "xxx AAA BBB zzz"
10209
10210 #"123~~456~~789"
10211 @result{} "123~456~789"
10212
10213 (let ((n 7)) #"R~|n|RS")
10214 @result{} "R7RS"
10215
10216 (let ((x "bar")) #"foo~|x|.")
10217 @result{} "foobar"
10218 @end example
10219
10220 @c EN
10221 In fact, the reader expands this syntax into a macro call,
10222 which is then expanded into a call of @code{string-append}
10223 as follows:
10224 @c JP
10225 実は、リーダーはこの構文をマクロ呼び出しへと変換し、それが最終的には
10226 @code{string-append}への呼び出しへと変換されます。
10227 @c COMMON
10228 @example
10229 #"This is Gauche, version ~(gauche-version)."
10230 @equiv{}
10231 (string-interpolate* ("This is Gauche, version "
10232 (gauche-version)
10233 "."))
10234
10235 ;; then, it expands to...
10236
10237 (string-append "This is Gauche, version "
10238 (x->string (gauche-version))
10239 ".")
10240 @end example
10241
10242 @c EN
10243 (NB: The exact spec of @code{string-interpolate*} might change in future,
10244 so do not rely on the current behavior.)
10245 @c JP
10246 (註: @code{string-interpolate*}の厳密な仕様は将来変わるかもしれないので、
10247 現在の振る舞いに依存したコードは避けて下さい。)
10248 @c COMMON
10249
10250 @c EN
10251 Since the @code{#"..."} syntax is equivalent to a macro call
10252 of @code{string-interpolate*}, which is provided in the Gauche module,
10253 it must be visible from where you use the interpolation syntax.
10254 When you write Gauche code, typically you implicitly inherit the Gauche
10255 module so you don't need to worry; however, if you start from R7RS code,
10256 make sure you import @code{string-interpolate*}
10257 (by @code{(import (gauche base))}, for example) whenever you use
10258 string interpolation syntax. Also be careful not to shadow
10259 @code{string-interpolate*} locally.
10260 @c JP
10261 @code{#"..."}構文はマクロ@code{string-interpolate*}の呼び出しと等価なので、
10262 この構文を使う際にはGaucheモジュールの@code{string-interpolate*}が
10263 見えている必要があります。Gaucheコードを書く場合、Gaucheモジュールはデフォルトで
10264 継承されているので、普通は気にする必要はありません。R7RSコードから始めて
10265 @code{#"..."}構文を使いたくなった場合は、@code{(import (gauche base))}等で
10266 @code{string-interpolate*}を見えるようにしてください。
10267 また、ローカルに@code{string-interpolate*}をシャドウしないように気をつけてください。
10268 @c COMMON
10269 @end deftp
10270
10271 @deftp {Reader Syntax} @code{#`}@var{string-literal}
10272 @lxindex #`
10273 @c EN
10274 This is the old style of string-interpolation. It is still recognized,
10275 but discouraged for the new code.
10276
10277 Inside @var{string-literal}, you can use @code{,@var{expr}}
10278 (instead of @code{~@var{expr}}) to
10279 evaluate @var{expr}. If comma isn't immediately followed by a
10280 character starting an expression, it loses special meaning.
10281 @c JP
10282 これは文字列補間の古い書法です。まだ認識されますが、
10283 新たなコードでは使わないでください。
10284
10285 @var{string-literal}の中で、(@code{~@var{expr}} ではなく)
10286 @code{,@var{expr}} とマークされた部分の@var{expr}が評価されます。
10287 コンマのすぐ次に式を開始する文字がこなければ、コンマはその効力を失います。
10288 @c COMMON
10289
10290 @example
10291 #`"This is Gauche, version ,(gauche-version)"
10292 @end example
10293 @end deftp
10294
10295
10296 @c EN
10297 @emph{Rationale of the syntax:}
10298 There are wide variation of string interpolation syntax among scripting
10299 languages. They are usually linked with other syntax of the language
10300 (e.g. prefixing @code{$} to mark evaluating place is in sync with variable
10301 reference syntax in some languages).
10302
10303 The old style of string interpolation syntax was taken from quasiquote
10304 syntax, because those two are conceptually
10305 similar operations (@pxref{Quasiquotation}).
10306 However, since comma character is frequently used in string literals,
10307 it was rather awkward.
10308
10309 We decided that tilde is more suitable as the unquote character for
10310 the following reasons.
10311
10312 @itemize
10313 @item
10314 Traditionally, Lisp's string formatter @code{format} uses @code{~} to introduce
10315 format directives (@pxref{Formatting output}). Lispers are used to
10316 scan @code{~}'s in a string as variable portions.
10317 @item
10318 Gauche's @code{~} is a universal accessor, and the operator has a nuance
10319 of ``taking something out of it''
10320 (@pxref{Universal accessor}).
10321 @item
10322 Clojure, a new Lisp dialect, adopted @code{~} as the unquote character in
10323 the quasiquote syntax, instead of commas.
10324 @end itemize
10325
10326 Note that Scheme allows wider range of characters for valid identifier names
10327 than usual scripting languages.
10328 Consequently, you will almost always need to use `|' delimiters
10329 when you interpolate the value of a variable.
10330 For example, while you can write
10331 @code{"$year/$month/$day $hour:$minutes:$seconds"} in Perl,
10332 you should write @code{#"~|year|/~|month|/~day ~|hour|:~|minutes|:~seconds"}.
10333 It may be better always to delimit direct variable references
10334 in this syntax to avoid confusion.
10335 @c JP
10336 @emph{この構文を採用した理由:}
10337 スクリプト言語の文字列補間構文には様々なバリエーションがありますが、通常、
10338 その言語の他の構文と関連しているものが多いです
10339 (例えば、@code{$}で変数参照する言語が、@code{$}を文字列中の評価部分に前置する等)。
10340
10341 Gaucheの古い形式の文字列補間構文では、準クオートの構文を流用していました
10342 (@ref{Quasiquotation}参照)。準クオートと文字列補間は意味的に似ているからです。
10343 けれども、コンマはそれ自体が文字列中によく出てくる文字なので、少々不格好な仕様でした。
10344
10345 そこで、以下のような理由から、チルダの方がアンクオート文字としてふさわしいと判断しました。
10346
10347 @itemize
10348 @item
10349 伝統的に、Lispの文字列フォーマッティング関数@code{format}では
10350 @code{~}をフォーマット指示子の導入に使ってきました
10351 (@ref{Formatting output}参照)。Lisperは文字列中で@code{~}を走査して
10352 可変部分を見つけるのに慣れています。
10353 @item
10354 Gaucheは @code{~} を万能アクセサとして使っていて、この文字には「中から何かを取り出す」
10355 ニュアンスを付加しています
10356 (@ref{Universal accessor}参照)。
10357 @item
10358 新たなLisp方言であるClojureは、準クオート構文中のアンクオート文字に
10359 コンマでなく @code{~} を採用しています。
10360 @end itemize
10361
10362 Schemeは他のスクリプト言語より一般的により多くの文字を変数名に使うことが出来ることに注意して下さい。
10363 結果として、変数の値を文字列に挿入する際、ほとんどの場合において変数名を`|'で区切る
10364 必要があるでしょう。例えば、Perlでは
10365 @code{"$year/$month/$day $hour:$minutes:$seconds"}
10366 と書けたものが、Gaucheでは
10367 @code{#`"~|year|/~|month|/~day ~|hour|:~|minutes|:~seconds"}
10368 と書かねばなりません。
10369 混乱を避けるためには、この構文内では常に直接の変数参照は`|'で区切るようにしておくのが良いかもしれません。
10370 @c COMMON
10371
10372
10373 @node String cursors, String indexing, String interpolation, Strings
10374 @subsection String cursors
10375 @c NODE 文字列カーソル
10376
10377 @c EN
10378 String cursors are opaque objects that point into strings, similar to
10379 indexes. Cursors however are more efficient. For example, to get a
10380 character with @code{string-ref} using an index on a multibyte string,
10381 Gauche needs to iterate from the beginning of the string until that
10382 position, or @code{O(n)}. Using cursors you can access in @code{O(1)}
10383 (for singlebyte (ASCII) strings or an indexed string,
10384 Gauche does it in @code{O(1)} even with index. @xref{String indexing},
10385 for the details of indexed string.)
10386 @c JP
10387 文字列カーソルは文字列の中の文字を指示するオブジェクトです。文字列中の文字を指定するのに
10388 インデックスも使えますが、カーソルの方が効率が良いです。例えば、
10389 文字インデックスを使ってマルチバイト文字列中の文字を@code{string-ref}で取り出すには、
10390 Gaucheは文字列の最初からその文字まで文字列をたどらなければならず、
10391 インデックスnに対してO(n)かかります。カーソルを使えばO(1)でアクセスできます
10392 (ASCII文字だけからなる文字列や、索引付加済み文字列では
10393 文字インデックスを使ったアクセスもO(1)になります。
10394 索引付加済み文字列については@ref{String indexing}を参照してください。)
10395 @c COMMON
10396
10397 @c EN
10398 For a string of length n, there can be n+1 cursors. The
10399 last cursor at the end of the string does not point to any valid
10400 character, it's usually used to determine if nothing is found.
10401 @c JP
10402 長さnの文字列には、n+1個のカーソルが存在し得ます。
10403 一番最後のカーソルは文字列末尾を指し、該当する文字を持ちません。
10404 探している文字が無いことを示す値としても使われます。
10405 @c COMMON
10406
10407 @c EN
10408 A string cursor is associated with a specific string and should not be
10409 used with another string. A string cursor also becomes invalid when
10410 the associated string is modified. Accessing an invalid cursor does
10411 not always fail though. Running @code{gosh} with @code{-fsafe-string-cursors}
10412 could help catch these issues, with some performance overhead.
10413 @xref{Gosh command-line options}.
10414 @c JP
10415 文字列カーソルは特定の文字列と結びついていて、それ以外の文字列に対して使うのは無効です。
10416 また、元の文字列が変更されると文字列カーソルは無効になります。
10417 ただ、無効になったカーソルを使っても必ずしもエラーになるとは限りません。
10418 @code{gosh}を@code{-fsafe-string-cursors}オプションつきで起動すると、
10419 性能が落ちますがその種のエラーを検出することができます。
10420 詳しくは@ref{Gosh command-line options}を参照してください。
10421 @c COMMON
10422
10423 @c EN
10424 Most of the time, string cursors aren't heap-allocated. It is only
10425 allocated in heap either (1) when it points at a huge byte index,
10426 or (2) when you use @code{-fsafe-string-cursors} to enable extra
10427 run-time check.
10428
10429 The threashold of byte index to cause a string cursor to be heap-allocated
10430 is 2^56 on 64bit systems, and 2^24 on 32bit systems, in the current
10431 implementation. On 64bit systems you will never hit the threashold practically.
10432 On 32bit systems you may, if you have a huge string, but you may want to
10433 consider using other data structure rather than keeping such data in
10434 one string object.
10435 @c JP
10436 ほとんどの場合、文字列カーソルはヒープアロケーションを伴いません。
10437 文字列カーソルがヒープにアロケートされるのは (1)巨大なバイトインデックスを指す場合か、
10438 (2)@code{-fsafe-string-cursors}を使って追加の実行時検査を有効にした場合です。
10439
10440 現在の実装では、カーソルがヒープアロケートされる閾値は、64bitシステムでは
10441 2^56、32bitシステムでは2^24です。
10442 64bitシステムでこの閾値を越えることは現実的にはありえないでしょう。
10443 32bitシステムでは、超巨大な文字列オブジェクトを使った場合にあり得るかもしれませんが、
10444 それほど大きなデータを扱うならば、
10445 単一の文字列ではなくデータ構造を工夫した方が良いかもしれません。
10446 @c COMMON
10447
10448 @c EN
10449 Most procedures that take indexes in Gauche can also take
10450 cursors. Relying on this though is unportable. For example, the
10451 @code{substring} procedure in RnRS standards does not mention anything
10452 about cursors even though the Gauche version accepts cursors. For
10453 portable programs, you should only use cursors on procedures from
10454 @code{srfi.130} module (@pxref{Cursor-based string library}).
10455 @c JP
10456 文字インデックスを取るGaucheの文字列手続きのほとんどはカーソルも受け付けます。
10457 但し、それに依存したコードは移植性がありません。例えば@code{substring}は、
10458 Gauche版ではインデックスもカーソルも使えますが、RnRSではインデックスしか許していません。
10459 移植性のあるプログラムを書く際には、@code{srfi.130}モジュールにある手続きでのみ
10460 カーソルを使うようにしてください (@ref{Cursor-based string library}参照)。
10461 @c COMMON
10462
10463 @deftp {Builtin Class} <string-cursor>
10464 @c EN
10465 Represents a cursor. When printed out, you'll see the
10466 @emph{byte offset} from the beginning of the string, not the character index.
10467 @c JP
10468 文字列カーソルのクラスです。書き出される時に表示される数字は、
10469 文字インデックスではなく@emph{文字へのバイトオフセット}です。
10470 @c COMMON
10471
10472 @example
10473 (string-index->cursor "あかさたな" 2)
10474 @result{} #<string-cursor 6>
10475 @end example
10476 @end deftp
10477
10478 @defun string-cursor? @var{obj}
10479 [SRFI-130]
10480 @c EN
10481 Returns @code{#t} if @var{obj} is a string cursor, @code{#f} otherwise.
10482 @c JP
10483 @var{obj}が文字列カーソルなら@code{#t}を、そうでなければ@code{#f}を返します。
10484 @c COMMON
10485 @end defun
10486
10487 @defun string-cursor-start @var{str}
10488 [SRFI-130]
10489 @c EN
10490 Returns a cursor pointing to the start of
10491 a string @var{str}. It returns a valid cursor on an
10492 empty string too. It's the same as @code{string-cursor-end} in that
10493 case.
10494 @c JP
10495 文字列@var{str}の先頭を指す文字列カーソルを返します。
10496 @var{str}が空文字列でも有効な文字列カーソルが返されます。
10497 (@var{str}が空文字列の場合、@code{string-cursor-end}が返すカーソルは
10498 同じものです)。
10499 @c COMMON
10500 @end defun
10501
10502 @defun string-cursor-end @var{str}
10503 [SRFI-130]
10504 @c EN
10505 Returns a cursor pointing to the end of @var{str} (the point after
10506 the last character.) If @var{str} is empty, it is the same
10507 as @code{string-cursor-start}.
10508 This cursor does not point to any valid character of the string.
10509 @c JP
10510 文字列@var{str}の末尾(最後の文字の直後)を指す文字列カーソルを返します。
10511 @var{str}が空文字列の場合、@code{string-cursor-start}が返すカーソルと
10512 同じものが返されます。
10513 このカーソルは有効な文字を指しません。
10514 @c COMMON
10515 @end defun
10516
10517 @defun string-cursor-next @var{str} @var{cur}
10518 [SRFI-130]
10519 @c EN
10520 Returns the cursor into @var{str} following @var{cur}. @var{cur} can
10521 also be an index. An error is signaled if @var{cur} points to the end
10522 of the string.
10523 @c JP
10524 文字列@var{str}中で、@var{cur}が指す文字の次を指すカーソルを返します。
10525 @var{cur}に文字インデックスを渡すこともできます。@var{cur}が文字列末尾を
10526 指している場合はエラーが投げられます。
10527 @c COMMON
10528 @end defun
10529
10530 @defun string-cursor-prev @var{str} @var{cur}
10531 [SRFI-130]
10532 @c EN
10533 Returns the cursor into @var{str} preceding @var{cur}. @var{cur} can
10534 also be an index. An error is signaled if @var{cur} points to the
10535 beginning of the string.
10536 @c JP
10537 文字列@var{str}中で、@var{cur}が指す文字の一つ前を指すカーソルを返します。
10538 @var{cur}には文字インデックスを渡すこともできます。@var{cur}が文字列先頭を
10539 指している場合はエラーが投げられます。
10540 @c COMMON
10541 @end defun
10542
10543 @defun string-cursor-forward @var{str} @var{cur} @var{n}
10544 [SRFI-130]
10545 @c EN
10546 Returns the cursor into @var{str} following @var{cur} by @var{n}
10547 characters. @var{cur} can also be an index.
10548 @c JP
10549 文字列@var{str}中で、カーソル@var{cur}が指す文字から@var{n}文字先を指す
10550 カーソルを返します。@var{cur}に文字インデックスを渡すこともできます。
10551 @c COMMON
10552 @end defun
10553
10554 @defun string-cursor-back @var{str} @var{cur} @var{n}
10555 [SRFI-130]
10556 @c EN
10557 Returns the cursor into @var{str} preceding @var{cur} by @var{n}
10558 characters. @var{cur} can also be an index.
10559 @c JP
10560 文字列@var{str}中で、カーソル@var{cur}が指す文字から@var{n}文字前を指す
10561 カーソルを返します。@var{cur}に文字インデックスを渡すこともできます。
10562 @c COMMON
10563 @end defun
10564
10565 @defun string-index->cursor @var{str} @var{index}
10566 [SRFI-130]
10567 @c EN
10568 Convert an @var{index} to a cursor. If @var{index} is a cursor it will
10569 be returned as-is.
10570 @c JP
10571 文字列インデックス@var{index}をカーソルに変換します。
10572 @var{index}が既にカーソルであった場合はそれがそのまま返されます。
10573 @c COMMON
10574 @end defun
10575
10576 @defun string-cursor->index @var{str} @var{cur}
10577 [SRFI-130]
10578 @c EN
10579 Convert a cursor to an index. If @var{cur} is a an index it will be
10580 returned as-is.
10581 @c JP
10582 文字列カーソル@var{cur}をインデックスに変換します。
10583 @var{cur}が既にインデックスであった場合はそれをそのまま返します。
10584 @c COMMON
10585 @end defun
10586
10587 @defun string-cursor-diff @var{str} @var{start} @var{end}
10588 [SRFI-130]
10589 @c EN
10590 Returns the number of characters between @var{start} and @var{end}. It
10591 should be non-negative if @var{start} precedes @var{end}, non-positive
10592 otherwise. @var{start} and @var{end} also accept index.
10593 @c JP
10594 二つの文字列カーソル@var{start}と@var{end}の間にある文字数を返します。
10595 @var{start}より@var{end}が後を指していれば結果は正に、
10596 @var{end}が@var{start}より手前にあれば結果は負になります。
10597 @var{start}と@var{end}は文字インデックスであっても構いません。
10598 @c COMMON
10599 @end defun
10600
10601 @defun string-cursor=? @var{cur1} @var{cur2}
10602 @defunx string-cursor<? @var{cur1} @var{cur2}
10603 @defunx string-cursor<=? @var{cur1} @var{cur2}
10604 @defunx string-cursor>? @var{cur1} @var{cur2}
10605 @defunx string-cursor>=? @var{cur1} @var{cur2}
10606 [SRFI-130]
10607 @c EN
10608 Compares two cursors or two indexes (but not a cursor and an index)
10609 and returns @code{#t} or @code{#f} accordingly.
10610 @c JP
10611 二つの文字列カーソル、もしくは二つのインデックスの前後関係を比較します
10612 (カーソルとインデックスは比較できません)。
10613 @c COMMON
10614 @end defun
10615
10616 @node String indexing, String accessors & modifiers, String cursors, Strings
10617 @subsection String indexing
10618 @c NODE 文字列索引
10619
10620 @c EN
10621 Since Gauche stores strings in multibyte encoding, random access
10622 requires O(N) by default. In most cases, string access is either
10623 sequential or search-and-extract pattern, and Gauche provides direct
10624 means for these operations, so you don't need to deal with indexed access.
10625 However, there may be a case that you have need more efficient random
10626 access string (mostly when porting third-party code, we imagine).
10627 @c JP
10628 Gaucheは文字列をマルチバイト形式で保持しているので、
10629 デフォルトではランダムアクセスにO(N)の時間がかかります。
10630 ほとんどの場合、文字列へのアクセスは最初から順に見て行くか、
10631 検索してマッチした箇所を見るかで、Gaucheはそれらの操作をプリミティブで提供しているので、
10632 文字列を文字のインデックスでアクセスする必要は滅多にないでしょう。
10633 けれどもどうしても文字列をランダムにアクセスしたい場合があるかもしれません
10634 (サードパーティ製のライブラリの移植、などが考えられます)。
10635 @c COMMON
10636
10637 @c EN
10638 There are a couple of ways to achieve O(1) random access.
10639 @c JP
10640 O(1)ランダムアクセスを実現する方法は二つばかりあります。
10641 @c COMMON
10642
10643 @c EN
10644 First, instead of integer character indexes,
10645 you can use string cursors (@pxref{String cursors}). It is defined
10646 by @code{srfi.130}, and you can use the code that's using SRFI-130
10647 as is, without worring about slow access. However, if external interface
10648 gives you integer character index, converting index to cursor and vice versa
10649 takes O(N) after all.
10650 @c JP
10651 一つは、文字へのインデックスのかわりに、
10652 文字列カーソルを使うことです(@ref{String cursors}参照)。
10653 文字列カーソルは@code{srfi.130}で定義され、SRFI-130のインタフェースを使っている
10654 コードはそのまま、効率的に動きます。ただ、もし外部に向けたインタフェースが
10655 文字インデックスを要求していたなら、カーソルとインデックス間の相互変換のところで
10656 O(N)時間がかかってしまいます。
10657 @c COMMON
10658
10659 @c EN
10660 There's another way. You can precompute @emph{string index}, mapping from
10661 integer character index to the position in the multibyte string. It costs
10662 O(N) of time and space to compute it, but once computed, you have
10663 O(1) random access. (We store positions for every K characters, where K
10664 is between 16 to 256, so it won't take up as large storage as the
10665 actual string body).
10666 @c JP
10667 もう一つの方法は、文字のインデックスとマルチバイト文字列内の位置を表す
10668 @emph{文字列索引}をあらかじめ計算しておくことです。計算時にはO(N)の時間・空間
10669 コストがかかりますが、一度計算すれば以降はO(1)でランダムアクセスできます。
10670 (実際には、文字列の長さに応じて16から256文字ごとに位置を記録するので、
10671 文字列本体に比べて索引はそれほどメモリを取りません)。
10672 @c COMMON
10673
10674 @c EN
10675 For portability, SRFI-135 Immutable Texts provides O(1) accessible string
10676 as ``texts''. On Gauche, a text is just an immutable string with
10677 index attached.
10678 @c JP
10679 SRFI-135 (変更不可なテキスト) はO(1)アクセス可能な文字列を「テキスト」という型で
10680 扱っています。Gaucheでは、テキストは単に文字列索引つきの変更不可な文字列です。
10681 @c COMMON
10682
10683 @defun string-build-index! str
10684 @c EN
10685 Computes and attaches index to a string @var{str}, and returns @var{str}
10686 itself. The operation doesn't alter the content of @var{str}, and you can
10687 pass immutable string as well.
10688 @c JP
10689 文字列@var{str}の索引を計算して、@var{str}自身を返します。
10690 この操作は@var{str}自体の内容を変えるものではないため、変更不可な文字列にも適用できます。
10691 @c COMMON
10692
10693 @c EN
10694 If @var{str} is a single-byte string (ASCII-only, or incomplete),
10695 or a short one (less than 64 octets), no index is attached.
10696 It is ok to pass a string which already has an index; then index computation
10697 is skipped.
10698 @c JP
10699 @var{str}がシングルバイト文字列(ASCIIのみからなるか、不完全な文字列)の場合、
10700 あるいは短い(64バイト以下)の場合、索引は実際には計算されません。
10701 また、既に索引がある文字列を渡しても構いません。その場合、単に索引の計算はスキップされます。
10702 @c COMMON
10703
10704 @c EN
10705 The index is attached to the string's content. If you alter @var{str}
10706 by e.g. @code{string-set!}, the index is discarded.
10707 @c JP
10708 索引は文字列の内容そのものに対してつけられます。@var{str}の内容を@code{string-set!}などで
10709 置き換えた際には、索引は破棄されます。
10710 @c COMMON
10711 @end defun
10712
10713 @defun string-fast-indexable? str
10714 @c EN
10715 Returns @code{#t} iff index access of a string @var{str} is effectively O(1),
10716 that is, @var{str} is either a single-byte string,
10717 a short string, or a long multibyte string with index computed.
10718 @c JP
10719 文字列@var{str}への文字インデックスでのアクセスがO(1)で行える場合に@code{#t}を、
10720 そうでなければ@code{#f}を返します。
10721 @code{#t}が返されるのは、@var{str}がシングルバイト文字列か、
10722 短い文字列か、文字列索引が付加された長い文字列である場合です。
10723 @c COMMON
10724 @end defun
10725
10726
10727 @node String accessors & modifiers, String comparison, String indexing, Strings
10728 @subsection String accessors & modifiers
10729 @c NODE 文字列のアクセスと変更
10730
10731 @defun string-length string
10732 [R7RS base]
10733 @c EN
10734 Returns a length of (possibly incomplete) string @var{string}.
10735 @c JP
10736 文字列@var{string}の長さ(文字数)を返します。
10737 @var{string}は不完全な文字列であっても構いません。
10738 @c COMMON
10739 @end defun
10740
10741 @defun string-size string
10742 @c EN
10743 Returns a size of (possibly incomplete) @var{string}.
10744 A size of string is a number of bytes @var{string} occupies on memory.
10745 The same string may have different sizes if the native encoding scheme
10746 differs.
10747
10748 For incomplete string, its length and its size always match.
10749 @c JP
10750 文字列@var{string}の大きさを返します。文字列の大きさは、
10751 @var{string}が占めるメモリ上のバイト数で、これは文字列の内部エンコーディングに
10752 依存します。同じ文字列であっても内部エンコーディングが違えば違う大きさになる場合も
10753 あります。
10754
10755 不完全な文字列では、文字列の長さと大きさは常に一致します。
10756 @c COMMON
10757 @end defun
10758
10759 @defun string-ref cstring k :optional fallback
10760 [R7RS+ base]
10761 @c EN
10762 Returns @var{k}-th character of a complete string @var{cstring}.
10763 It is an error to pass an incomplete string.
10764
10765 By default, an error is signaled if @code{k} is out of range
10766 (negative, or greater than or equal to the length of @var{cstring}).
10767 However, if an optional argument @var{fallback} is given,
10768 it is returned in such case. This is Gauche's extension.
10769
10770 If @var{cstring} is a multibyte string without index attached,
10771 this procedure takes O(@var{k}) time. @xref{String indexing}, for
10772 ensuring O(1) access.
10773
10774 @var{k} can also be a string cursor (also Gauche's extension).
10775 Cursor acccess is O(1).
10776 @c JP
10777 完全な文字列@var{cstring}の@var{k}番目の文字を返します。
10778 不完全な文字列を渡すのはエラーです。
10779
10780 @var{k}が負数であったり@var{cstring}の長さと同じかそれ以上であった場合には
10781 エラーが報告されます。但し、引数@var{fallback}が与えられている場合にはエラーを
10782 報告せず@var{fallback}が返されます。これはGaucheの拡張です。
10783
10784 @var{cstring}がマルチバイト文字列でインデックスが付加されていない場合、
10785 この手続きはO(@var{k})時間かかります。O(1)アクセスを得る方法は
10786 @ref{String indexing}を参照してください。
10787
10788 @var{k}に文字列カーソルを渡すこともできます (これもGaucheの拡張です)。
10789 カーソルによるアクセスはO(1)です。
10790 @c COMMON
10791 @end defun
10792
10793 @defun string-byte-ref string k
10794 @c EN
10795 Returns @var{k-th} byte of a (possibly incomplete) string @var{string}.
10796 Returned value is an integer in the range between 0 and 255.
10797 @var{k} must be greater than or equal to zero, and less than
10798 @code{(string-size @var{string})}.
10799 @c JP
10800 (多分、不完全な)文字列@var{string}の@var{k番目}のバイトを返します。
10801 戻り値は、0から255の範囲の整数です。@var{k}は0以上、
10802 @code{(string-size @var{string})}より小でなければなりません。
10803 @c COMMON
10804 @end defun
10805
10806 @defun string-set! string k char
10807 [R7RS base]
10808 @c EN
10809 Substitute @var{string}'s @var{k}-th character by @var{char}.
10810 @var{k} must be greater than or equal to zero, and less than
10811 @code{(string-length @var{string})}.
10812 Return value is undefined.
10813
10814 If @var{string} is an incomplete string, integer value of the lower 8 bits
10815 of @var{char} is used to set @var{string}'s @var{k}-th byte.
10816
10817 See the notes in @code{make-string} about performance consideration.
10818 @c JP
10819 @var{string}の@var{k}番目の文字を@var{char}で置き換えます。
10820 @var{k}は0以上、@code{(string-length @var{string})}より小でなければ
10821 なりません。戻り値は未定義です。
10822
10823 @var{string}が不完全文字列の場合、@var{char}の下位8ビットの整数値は、
10824 @var{string}の@var{k}番目のバイトをセットするために使われます。
10825
10826 パフォーマンス上の考慮点について、@code{make-string}の説明を参照して下さい。
10827 @c COMMON
10828 @end defun
10829
10830 @defun string-byte-set! string k byte
10831 @c EN
10832 Substitute @var{string}'s @var{k}-th byte by integer @var{byte}.
10833 @var{byte} must be in the range between 0 to 255, inclusive.
10834 @var{k} must be greater than or equal to zero, and less than
10835 @code{(string-size @var{string})}.
10836 If @var{string} is a complete string, it is turned to incomplete string
10837 by this operation.
10838 Return value is undefined.
10839 @c JP
10840 @var{string}の@var{k}番目のバイトを整数@var{byte}で置き換えます。
10841 @var{byte}は0から255の範囲(255を含む)でなければなりません。
10842 @var{k}は0以上、@code{(string-size @var{string})}より小である必要があります。
10843 @var{string}が完全文字列の場合、この操作により不完全文字列になります。
10844 戻り値は未定義です。
10845 @c COMMON
10846 @end defun
10847
10848 @node String comparison, String utilities, String accessors & modifiers, Strings
10849 @subsection String comparison
10850 @c NODE 文字列の比較
10851
10852 @defun string=? string1 string2 string3 @dots{}
10853 [R7RS base]
10854 @c EN
10855 Returns @code{#t} iff all arguments are strings with the same content.
10856 @c JP
10857 全ての引数が内容の等しい文字列であれば@code{#t}を返します。
10858 @c COMMON
10859
10860 @c EN
10861 If any of arguments is incomplete string, it returns @code{#t} iff
10862 all arguments are incomplete and have exactly the same content.
10863 In other words, a complete string and an incomplete string never equal
10864 to each other.
10865 @c JP
10866 もし引数に不完全文字列がひとつでもある場合、
10867 全ての文字列が不完全でありかつ内容が同じである場合に限り@code{#t}が返ります。
10868 言い換えれば、完全な文字列と不完全な文字列は決して等しくなりません。
10869 @c COMMON
10870 @end defun
10871
10872 @defun string<? string1 string2 string3 @dots{}
10873 @defunx string<=? string1 string2 string3 @dots{}
10874 @defunx string>? string1 string2 string3 @dots{}
10875 @defunx string>=? string1 string2 string3 @dots{}
10876 [R7RS base]
10877 @c EN
10878 Compares strings in codepoint order. Returns @code{#t} iff
10879 all the arguments are ordered.
10880 @c JP
10881 文字列同士をコードポイントの順序で比較します。全ての引数が順序どおりであれば
10882 @code{#t}が、そうでなければ@code{#f}が返されます。
10883 @c COMMON
10884
10885 @c EN
10886 Comparison between an incomplete string and a complete string, or between
10887 two incomplete strings, are done by octet-to-octet comparison. If a
10888 complete string and an incomplete string have exactly the same binary
10889 representation of the content, a complete string is smaller.
10890 @c JP
10891 不完全文字列と完全文字列、もしくは不完全文字列同士の比較は、
10892 内容のオクテット同士の比較となります。内容のバイナリ表現が一致する
10893 完全文字列と不完全文字列を比較した場合は、完全文字列の方が小さいとみなされます。
10894 @c COMMON
10895 @end defun
10896
10897 @defun string-ci=? string1 string2 string3 @dots{}
10898 @defunx string-ci<? string1 string2 string3 @dots{}
10899 @defunx string-ci<=? string1 string2 string3 @dots{}
10900 @defunx string-ci>? string1 string2 string3 @dots{}
10901 @defunx string-ci>=? string1 string2 string3 @dots{}
10902 @c EN
10903 Case-insensitive string comparison.
10904 @c JP
10905 大文字小文字を無視する文字列比較です。
10906 @c COMMON
10907
10908 @c EN
10909 These procedures fold argument character-wise, according to
10910 Unicode-defined character-by-character case mapping. See
10911 @code{char-foldcase} for the details (@ref{Characters}).
10912 Character-wise case folding doesn't handles the case like
10913 German eszett:
10914 @c JP
10915 これらの手続きは、引数に「文字ごとの大文字小文字変換」を適用します。
10916 (変換にはUnicodeの文字単位の大文字小文字マッピングテーブルを使います)。
10917 詳しくは@code{char-foldcase}の説明を見てください (@ref{Characters})。
10918 文字ごとの大文字小文字変換は、ドイツ語のエスツェットのような特別な場合を
10919 考慮しません。
10920 @c COMMON
10921
10922 @example
10923 (string-ci=? "\u00df" "SS") @result{} #f
10924 @end example
10925
10926 @c EN
10927 R7RS requires @code{string-ci}* procedures to use string case folding.
10928 Gauche provides R7RS-conformant case insensitive comparison procedures
10929 in @code{gauche.unicode} (@pxref{Full string case conversion}).
10930 If you write in R7RS, importing
10931 @code{(scheme char)} library, you'll use @code{gauche.unicode}'s
10932 @code{string-ci}* procedures.
10933 @c JP
10934 R7RSでは、@code{string-ci}*手続きは文字列としての大文字小文字変換を要求しています。
10935 Gaucheは、R7RSに準拠した大文字小文字の違いを無視する比較手続きを
10936 @code{gauche.unicode}モジュールに用意しています(@ref{Full string case conversion}参照)。
10937 R7RSでプログラミングする際に@code{(scheme char)}をインポートした場合は、
10938 @code{gauche.unicode}モジュールの@code{string-ci=?}などが使われます。
10939 @c COMMON
10940 @end defun
10941
10942 @node String utilities, Incomplete strings, String comparison, Strings
10943 @subsection String utilities
10944 @c NODE 文字列を扱うその他の手続き
10945
10946 @defun substring string start end
10947 [R7RS+ base]
10948 @c EN
10949 Returns a substring of @var{string}, starting from @var{start}-th
10950 character (inclusive) and ending at @var{end}-th character (exclusive).
10951 The @var{start} and @var{end} arguments must satisfy
10952 @code{0 <= @var{start} < @var{N}},
10953 @code{0 <= @var{end} <= @var{N}}, and
10954 @code{@var{start} <= @var{end}}, where @var{N} is the length of the
10955 string.
10956
10957 @var{start} and @var{end} can also be string cursors, but this is an
10958 extension of Gauche.
10959 @c JP
10960 @var{string}の@var{start}番目の文字(これを含む)から、@var{end}番目の文
10961 字(これを含まない)までの部分文字列を返します。引数@var{start}および
10962 @var{end}は以下を満さなければなりません。
10963 @code{0 <= @var{start} < @var{N}}、
10964 @code{0 <= @var{end} <= @var{N}}、
10965 @code{@var{start} <= @var{end}}。ただし、@var{N}は与えられた文字列の長
10966 さです。
10967 @c COMMON
10968
10969 @c EN
10970 When @var{start} is zero and @var{end} is @var{N}, this procedure
10971 returns a copy of @var{string}.
10972 (See also @code{opt-substring} below, if you don't want to copy
10973 if not necessary.)
10974 @c JP
10975 @var{start}がゼロでかつ@var{end}が@var{N}の場合には、@var{string}のコ
10976 ピーが返ります。
10977 (不必要な時にコピーを避けたければ、下の@code{opt-substring}が使えます)。
10978 @c COMMON
10979
10980 @c EN
10981 Actually, extended @code{string-copy} explained below
10982 is a superset of @code{substring}. This procedure is
10983 kept mostly for compatibility of R7RS programs.
10984 See also @code{subseq} in @ref{Sequence framework},
10985 for the generic version.
10986 @c JP
10987 実は後述する拡張された@code{string-copy}は@code{substring}のスーパーセッ
10988 トになっています。この手続きの役割は主にR7RSとの互換性のためです。
10989 @ref{Sequence framework}のジェネリック版@code{subseq}も参照してください。
10990 @c COMMON
10991 @end defun
10992
10993 @defun opt-substring string :optional start end
10994 @c EN
10995 Like @code{substring}, returns a part of @var{string} between
10996 @var{start}-th character (inclusive) and @var{end}-th character (exclusive).
10997 However, if the entire @var{string} is used (e.g. @var{start} is 0 and
10998 @var{end} is the length of @var{string}, or the arguments are omitted, etc.),
10999 @var{string} is returned as is, without copying.
11000
11001 This is a typical handling of optional @var{start}/@var{end} indexes
11002 for many string utilities. Note that using @code{substring} forces
11003 copying the input string even when it's not necessary.
11004
11005 Besides exact integers, @code{#f} or @code{#<undef>} is allowed
11006 as @var{start} and @var{end}, to indicate the argument is missing.
11007 In that case, 0 is assumed for @var{start}, and
11008 the length of @var{string} is assumed for @var{end}.
11009 @c JP
11010 @code{substring}と同様に、@var{string}の@var{start}番目の文字(含む)から
11011 @var{end}番目の文字(含まない)までを切り取った文字列を返します。
11012 ただし、入力文字列全てが使われる場合(@var{start}が0で@var{end}が入力文字列長だとか、
11013 それらが省略された場合だとか)は、コピーせずに@var{string}がそのまま返されます。
11014
11015 これは、多くの文字列処理関数で省略可能な@var{start}/@var{end}引数を扱う場合に
11016 共通する処理です。
11017 @code{substring}を使うと必ず文字列がコピーされることに注意してください。
11018
11019 @var{start}/@var{end}引数には、正確な整数のほか、
11020 該当する引数が省略されたことを示すために@code{#f}と@code{#<undef>}が許されます。
11021 引数が省略された場合、@var{start}は0、@var{end}は@var{string}の長さが使われます。
11022 @c COMMON
11023 @end defun
11024
11025
11026 @defun string-append string @dots{}
11027 [R7RS base]
11028 @c EN
11029 Returns a newly allocated string whose content is concatenation of
11030 @var{string} @dots{}.
11031 @c JP
11032 @var{string} @dots{}を連結した内容を含む文字列を新しくアロケートして返
11033 します。
11034 @c COMMON
11035
11036 @c EN
11037 See also @code{string-concatenate} in @ref{SRFI-13 String reverse & append}.
11038 @c JP
11039 @ref{SRFI-13 String reverse & append}の@code{string-concatenate}も参照
11040 してください。
11041 @c COMMON
11042 @end defun
11043
11044 @defun string->list string :optional start end
11045 @defunx list->string list
11046 [R7RS base]
11047 @c EN
11048 Converts a string to a list of characters or vice versa.
11049 @c JP
11050 文字列を文字のリストへ、またはその逆の変換をします。
11051 @c COMMON
11052
11053 @c EN
11054 You can give an optional start/end indexes to @code{string->list}.
11055 @c JP
11056 @code{string->list}にはオプショナル引数として開始、終了位置のインデッ
11057 クスを渡せます。
11058 @c COMMON
11059
11060 @c EN
11061 For @code{list->string}, every elements of @var{list} must be
11062 a character, or an error is signaled. If you want to build
11063 a string out of a mixed list of strings and characters, you
11064 may want to use @code{tree->string} in @ref{Lazy text construction}.
11065 @c JP
11066 @code{list->string}では@var{list}の要素はすべて文字でなければなりません。
11067 そうでなければ、エラーシグナルがあがります。文字列や文字がまざったリス
11068 トから文字列を構成したい場合には@ref{Lazy text construction}にある
11069 @code{tree->string}が使えます。
11070 @c COMMON
11071 @end defun
11072
11073 @defun string-copy string :optional start end
11074 [R7RS base]
11075 @c EN
11076 Returns a copy of @var{string}. You can give @var{start} and/or
11077 @var{end} index to extract the part of the original string
11078 (it makes @code{string-copy} a superset of @code{substring} effectively).
11079 @c JP
11080 @var{string}のコピーを返します。@var{start}および/あるいは@var{end}の
11081 位置インデックスを渡すと元の文字列の部分文字列を取り出せます。
11082 (したがって@code{string-copy}は事実上@code{substring}のスーパーセット
11083 です)。
11084 @c COMMON
11085
11086 @c EN
11087 If only @var{start} argument is given, a substring beginning from
11088 @var{start}-th character (inclusive) to the end of @var{string} is
11089 returned. If both @var{start} and @var{end} argument are given,
11090 a substring from @var{start}-th character (inclusive) to
11091 @var{end}-th character (exclusive) is returned.
11092 See @code{substring} above for the condition that @var{start} and
11093 @var{end} should satisfy.
11094 @c JP
11095 @var{start}引数のみを与えた場合には、部分文字列は@var{start}番目の文字
11096 (これを含む)から@var{string}の最後までで、それが返ります。
11097 @var{start}と@var{end}の両方を与えたときは、部分文字列は@var{start}番
11098 目の文字(これを含む)から、@var{end}番目の文字(これを含まない)までで、
11099 それが返ります。@var{start}と@var{end}が満すべき条件については
11100 前述の@code{substring}の項を見てください。
11101 @c COMMON
11102
11103 @c EN
11104 Node: R7RS's destructive version @code{string-copy!} is provided
11105 by @code{srfi.13} module (@pxref{String library}).
11106 @c JP
11107 註: R7RSの破壊的バージョン@code{string-copy!}は@code{srfi.13}モジュールで
11108 提供されます (@ref{String library}参照)。
11109 @c COMMON
11110 @end defun
11111
11112 @defun string-copy-immutable string :optional start end
11113 @c EN
11114 If @var{string} is immutable, return it as is. Otherwise, returns
11115 an immutable copy of @var{string}. It is a dual of @code{string-copy}
11116 which always returns a mutable copy.
11117
11118 The optional @var{start} and @var{end} argument may be a nonnegative
11119 integer character index and/or string cursors to restrict the range
11120 of @var{string} to be copied.
11121 @c JP
11122 @var{string}が変更不可であればそれをそのまま返し、変更可能であれば
11123 変更不可なコピーを返します。
11124 @code{string-copy}が常に変更可能なコピーを返すのと対照的です。
11125
11126 @var{start}と@var{end}は非負整数の文字インデックスか文字列カーソルで、
11127 @var{string}中のコピーされる範囲を指定します。
11128 @c COMMON
11129 @end defun
11130
11131
11132 @defun string-fill! string char :optional start end
11133 [R7RS base]
11134 @c EN
11135 Fills @var{string} by @var{char}. Optional
11136 @var{start} and @var{end} limits the effective area.
11137 @c JP
11138 @var{string} を @var{char} で埋めます。
11139 オプションの @var{start} と @var{end} は、影響を受ける領域を
11140 制限します。
11141 @c COMMON
11142 @example
11143 (string-fill! "orange" #\X)
11144 @result{} "XXXXXX"
11145 (string-fill! "orange" #\X 2 4)
11146 @result{} "orXXge"
11147 @end example
11148
11149 @c EN
11150 See the notes in @code{make-string} about performance consideration.
11151 @c JP
11152 パフォーマンス上の考慮点について、@code{make-string}の説明を参照して下さい。
11153 @c COMMON
11154 @end defun
11155
11156 @defun string-join strs :optional delim grammar
11157 @c EN
11158 [SRFI-13] Concatenate strings in the list @var{strs},
11159 with a string @var{delim} as `glue'.
11160
11161 The argument @var{grammar} may be one of the following symbol
11162 to specify how the strings are concatenated.
11163 @c JP
11164 [SRFI-13] リスト @var{strs} 中にある文字列を、文字列 @var{delim} を'糊'
11165 として連結します。
11166
11167 引数 @var{grammar} は、文字列がどのように連結されるかを指定する
11168 シンボルで、以下のうちの一つです。
11169 @c COMMON
11170 @table @code
11171 @item infix
11172 @c EN
11173 Use @var{delim} between each string. This mode is default.
11174 Note that this mode introduce ambiguity when @var{strs}
11175 is an empty string or a list with a null string.
11176 @c JP
11177 それぞれの文字列の間に @var{delim} を使います。このモードが
11178 デフォルトです。@var{strs} が空文字列かヌル文字列を含むリスト
11179 である場合は、曖昧に(適当に)動作します。
11180 @c COMMON
11181 @example
11182 (string-join '("apple" "mango" "banana") ", ")
11183 @result{} "apple, mango, banana"
11184 (string-join '() ":")
11185 @result{} ""
11186 (string-join '("") ":")
11187 @result{} ""
11188 @end example
11189 @item strict-infix
11190 @c EN
11191 Works like @code{infix}, but empty list is not allowed to @var{strs},
11192 thus avoiding ambiguity.
11193 @c JP
11194 @code{infix} のように動作しますが、@var{strs} には空リストは
11195 許されません。したがって、曖昧さはありません。
11196 @c COMMON
11197 @item prefix
11198 @c EN
11199 Use @var{delim} before each string.
11200 @c JP
11201 @var{delim} をそれぞれの文字列の前に補います。
11202 @c COMMON
11203 @example
11204 (string-join '("usr" "local" "bin") "/" 'prefix)
11205 @result{} "/usr/local/bin"
11206 (string-join '() "/" 'prefix)
11207 @result{} ""
11208 (string-join '("") "/" 'prefix)
11209 @result{} "/"
11210 @end example
11211 @item suffix
11212 @c EN
11213 Use @var{delim} after each string.
11214 @c JP
11215 @var{delim} をそれぞれの文字列の後ろに補います。
11216 @c COMMON
11217 @example
11218 (string-join '("a" "b" "c") "&" 'suffix)
11219 @result{} "a&b&c&"
11220 (string-join '() "&" 'suffix)
11221 @result{} ""
11222 (string-join '("") "&" 'suffix)
11223 @result{} "&"
11224 @end example
11225 @end table
11226 @end defun
11227
11228 @defun string-scan string item :optional return
11229 @defunx string-scan-right string item :optional return
11230 @c EN
11231 Scan @var{item} (either a string or a character) in @var{string}.
11232 While @code{string-scan} finds the leftmost match, @code{string-scan-right}
11233 finds the rightmost match.
11234 @c JP
11235 @var{string} から @var{item} (文字列あるいは文字)を探します。
11236 @code{string-scan}は最も左にある一致を、
11237 @code{string-scan-right}は最も右にある一致を見つけます。
11238 @c COMMON
11239
11240 @c EN
11241 The @var{return} argument specifies what value should be returned
11242 when @var{item} is found in @var{string}. It must be one of the
11243 following symbols.
11244 @c JP
11245 引数 @var{return} は、@var{string} 中に @var{item} が見つかった
11246 場合にどの値が返されるかを指定します。それは以下のシンボルのうちの
11247 一つでなければなりません。
11248 @c COMMON
11249
11250 @table @code
11251 @item index
11252 @c EN
11253 Returns the index in @var{string} if @var{item} is found, or @code{#f}.
11254 This is the default behavior.
11255 @c JP
11256 @var{item} が見つかった場合は@var{string} 内でのインデックス、
11257 そうでなければ @code{#f} を返します。これがデフォルトの振る舞いです。
11258 @c COMMON
11259 @example
11260 (string-scan "abracadabra" "ada") @result{} 5
11261 (string-scan "abracadabra" #\c) @result{} 4
11262 (string-scan "abracadabra" "aba") @result{} #f
11263 @end example
11264 @item before
11265 @c EN
11266 Returns a substring of @var{string} before @var{item}, or
11267 @code{#f} if @var{item} is not found.
11268 @c JP
11269 @var{item} よりも前にある @var{string} の部分文字列、あるいは
11270 @var{item} が見つからなければ @code{#f} を返します。
11271 @c COMMON
11272 @example
11273 (string-scan "abracadabra" "ada" 'before) @result{} "abrac"
11274 (string-scan "abracadabra" #\c 'before) @result{} "abra"
11275 @end example
11276 @item after
11277 @c EN
11278 Returns a substring of @var{string} after @var{item}, or
11279 @code{#f} if @var{item} is not found.
11280 @c JP
11281 @var{item} より後ろにある @var{string} の部分文字列、あるいは
11282 @var{item} が見つからなければ @code{#f} を返します。
11283 @c COMMON
11284 @example
11285 (string-scan "abracadabra" "ada" 'after) @result{} "bra"
11286 (string-scan "abracadabra" #\c 'after) @result{} "adabra"
11287 @end example
11288 @item before*
11289 @c EN
11290 Returns a substring of @var{string} before @var{item}, and
11291 the substring after it. If @var{item} is not found, returns
11292 @code{(values #f #f)}.
11293 @c JP
11294 @var{item} の前にある @var{string} の部分文字列と後ろにある
11295 @var{string} の部分文字列を返します。@var{item} が見つからない場合は、
11296 @code{(values #f #f)} を返します。
11297 @c COMMON
11298 @example
11299 (string-scan "abracadabra" "ada" 'before*)
11300 @result{} "abrac" @r{and} "adabra"
11301 (string-scan "abracadabra" #\c 'before*)
11302 @result{} "abra" @r{and} "cadabra"
11303 @end example
11304 @item after*
11305 @c EN
11306 Returns a substring of @var{string} up to the end of @var{item},
11307 and the rest. If @var{item} is not found, returns
11308 @code{(values #f #f)}.
11309 @c JP
11310 @var{string} のうち、@var{item} の終端までの部分文字列とその残りを
11311 返します。@var{item} が見つからなかった場合は、@code{(values #f #f)}
11312 を返します。
11313 @c COMMON
11314 @example
11315 (string-scan "abracadabra" "ada" 'after*)
11316 @result{} "abracada" @r{and} "bra"
11317 (string-scan "abracadabra" #\c 'after*)
11318 @result{} "abrac" @r{and} "adabra"
11319 @end example
11320 @item both
11321 @c EN
11322 Returns a substring of @var{string} before @var{item} and
11323 after @var{item}. If @var{item} is not found, returns
11324 @code{(values #f #f)}.
11325 @c JP
11326 @var{string} のうち、@var{item} の前と @var{item} の後ろの
11327 部分文字列を返します。@var{item} が見つからない場合、
11328 @code{(values #f #f)} を返します。
11329 @c COMMON
11330 @example
11331 (string-scan "abracadabra" "ada" 'both)
11332 @result{} "abrac" @r{and} "bra"
11333 (string-scan "abracadabra" #\c 'both)
11334 @result{} "abra" @r{and} "adabra"
11335 @end example
11336 @end table
11337 @end defun
11338
11339 @defun string-split string splitter :optional grammar limit start end
11340 @defunx string-split string splitter :optional limit start end
11341 [SRFI-152+]
11342 @c EN
11343 Splits @var{string} by @var{splitter} and returns a list of strings.
11344 @var{splitter} can be a character, a character set, a string,
11345 a regexp, or a procedure.
11346
11347 If @var{splitter} is a character or a string, it is
11348 used as a delimiter. Note that SRFI-152's @code{string-split}
11349 only allows strings for @var{splitter} (it also interprets the first
11350 optional argument as a grammar; see below for the compatibility note.)
11351
11352 If @var{splitter} is a character set, any consecutive characters
11353 that are member of the character set are used as a delimiter.
11354
11355 If a procedure is given to @var{splitter}, it is called for each
11356 character in @var{string}, and the consecutive characters that caused
11357 @var{splitter} to return a true value are used as a delimiter.
11358 @c JP
11359 @var{string} を @var{splitter} で分割し、文字列のリストを返します。
11360 @var{splitter} には、文字、文字集合、文字列、正規表現、手続きが
11361 使えます。
11362
11363 @var{splitter} が文字か文字列の場合、それがそのままデリミタとして使われます。
11364 なお、SRFI-152の@code{string-split}はデリミタとして文字列しか許しません。
11365 (また、省略可能引数の最初のものは常に@var{grammar}として扱われます。
11366 後述する互換性への註を参照)。
11367
11368 @var{splitter} が文字集合の場合は、その文字集合に含まれる文字の
11369 連続がデリミタとして使われます。
11370
11371 @var{splitter} に手続きが与えられた場合、@var{string} にある各文字に
11372 対してその手続きが呼ばれ、@var{splitter} が真の値を返すような連続した
11373 文字群がデリミタとして使われます。
11374 @c COMMON
11375
11376 @example
11377 (string-split "/aa/bb//cc" #\/) @result{} ("" "aa" "bb" "" "cc")
11378 (string-split "/aa/bb//cc" "/") @result{} ("" "aa" "bb" "" "cc")
11379 (string-split "/aa/bb//cc" "//") @result{} ("/aa/bb" "cc")
11380 (string-split "/aa/bb//cc" #[/]) @result{} ("" "aa" "bb" "cc")
11381 (string-split "/aa/bb//cc" #/\/+/) @result{} ("" "aa" "bb" "cc")
11382 (string-split "/aa/bb//cc" #[\w]) @result{} ("/" "/" "//" "")
11383 (string-split "/aa/bb//cc" char-alphabetic?) @result{} ("/" "/" "//" "")
11384
11385 ;; some boundary cases
11386 (string-split "abc" #\/) @result{} ("abc")
11387 (string-split "" #\/) @result{} ("")
11388 @end example
11389
11390 @c EN
11391 The @var{grammar} argument is the same as @code{string-join} above; it
11392 must be one of symbols @code{infix}, @code{strict-infix}, @code{prefix}
11393 or @code{suffix}. When omitted, @code{infix} is assumed.
11394 @c JP
11395 @var{grammar}引数の意味は上の@code{string-join}と同じです。
11396 シンボル@code{infix}、@code{strict-infix}、@code{prefix}、
11397 @code{suffix}のいずれかでなければなりません。
11398 省略時は@code{infix}が指定されたのと同じです。
11399 @c COMMON
11400
11401 @example
11402 (string-split "/a/b/c/" "/" 'infix) @result{} ("" "a" "b" "c" "")
11403 (string-split "/a/b/c/" "/" 'prefix) @result{} ("a" "b" "c" "")
11404 (string-split "/a/b/c/" "/" 'suffix) @result{} ("" "a" "b" "c")
11405 @end example
11406
11407 @c EN
11408 In general, the following relationship holds:
11409 @c JP
11410 一般的に、以下の関係が成り立ちます。
11411 @c COMMON
11412
11413 @example
11414 (string-join XS DELIM GRAMMAR) @result{} S
11415 (string-split S DELIM GRAMMAR) @result{} XS
11416 @end example
11417
11418 @c EN
11419 If @var{limit} is given and not @code{#f}, it must be a nonnegative
11420 integer and specifies the maximum number of match to the @var{splitter}.
11421 Once the limit is reached, the rest of string is included in the result
11422 as is.
11423 @c JP
11424 @var{limit}引数が与えられた場合、それは@code{#f}か非負整数でなければなりません。
11425 非負整数の場合は@var{splitter}がマッチするデリミタの最大数を指定します。
11426 デリミタがその数だけ見つかったら、残りの文字列は分割されずにそのまま結果に含められます。
11427 @c COMMON
11428
11429 @example
11430 (string-split "a.b..c" "." 'infix 0) @result{} ("a.b..c")
11431 (string-split "a.b..c" "." 'infix 1) @result{} ("a" "b..c")
11432 (string-split "a.b..c" "." 'infix 2) @result{} ("a" "b" ".c")
11433 @end example
11434
11435 @c EN
11436 Compatibility note:
11437 The @var{grammar} argument is added for the consistency of srfis
11438 (SRFI-130, SRFI-152, @pxref{String library (reduced)}).
11439 However, for the backward compatibility and
11440 the convenience, it also accepts @var{limit} without @var{grammar} argument;
11441 it is distinguishable since @var{grammar} is a symbol and
11442 @var{limit} is an integer.
11443 For the code that's compatible to SRFI-152, use the first form that takes
11444 @var{grammar} argument.
11445 @c JP
11446 互換性への註:
11447 @var{grammar}引数はSRFI-130およびSRFI-152(@ref{String library (reduced)}参照)
11448 との一貫性のために追加されました。
11449 しかし、互換性および簡便性のため、@var{grammar}を省略して@var{limit}を与えることも
11450 できます。@var{grammar}はシンボルで@var{limit}は整数なので判別可能です。
11451 SRFI-152と互換性のあるコードを書く場合は@var{grammar}引数を取る最初の形式を使ってください。
11452 @c COMMON
11453
11454 @example
11455 (string-split "a.b..c" "." 2) @result{} ("a" "b" ".c")
11456 @end example
11457
11458 @c EN
11459 The @var{start} and @var{end} arguments limits input string
11460 in the given range before splitting.
11461 @c JP
11462 @var{start}と@var{end}引数は分割する前に入力文字列を指定の範囲に制限します。
11463 @c COMMON
11464
11465 @c EN
11466 See also @code{string-tokenize} in
11467 (@pxref{SRFI-13 Other string operations}).
11468 @c JP
11469 @code{string-tokenize} (@ref{SRFI-13 Other string operations})
11470 も参照して下さい。
11471 @c COMMON
11472 @end defun
11473
11474 @defun string-map proc str str2 @dots{}
11475 @defunx string-map proc str :optional start end
11476 [R7RS base][SRFI-13]
11477 @c EN
11478 Applies @var{proc} over each character in the input string, and
11479 gathers the characters returned from @var{proc} into a string and
11480 returns it. It is an error if @var{proc} returns non-character.
11481
11482 Because of historical reasons, this procedure has two interfaces.
11483 The first one takes one or more input strings, and @var{proc} receives
11484 as many characters as the number of input strings, each character
11485 being taken from each string. Iteration stops on the shortest string.
11486 This is defined in R7RS-small, and consistent with @code{map},
11487 @code{vector-map}, etc.
11488
11489 The second one takes only one string argument, and optional start/end
11490 arguments, which may be nonnegative integer indexes or string cursors
11491 to limit the input range of the string. This is defined in SRFI-13,
11492 string library.
11493
11494 The order in which @var{proc} is applied is not guaranteed to be left to right.
11495 You shouldn't depend on the order.
11496
11497 If @var{proc} saves a continuation and it is invoked later, the result
11498 already returned from @code{string-map} won't be affected
11499 (as specified in R7RS).
11500 @c JP
11501 入力文字列中の各文字に対して@var{proc}を適用し、その結果の文字を集めた
11502 文字列を返します。@var{proc}は文字を返さねばなりません。
11503
11504 歴史的経緯により、この手続きは2種類のインタフェースを持ちます。
11505 最初のインタフェースは1個以上の文字列を取ります。
11506 @var{proc}には文字列引数の数だけ、各文字列から取られた文字が渡されます。
11507 繰り返しは最も短い文字列でストップします。これはR7RS-smallで定義され、
11508 @code{map}、@code{vector-map}等と一貫性があります。
11509
11510 二番目のインタフェースでは、文字列引数はひとつだけで、省略可能な@var{start}/@var{end}
11511 引数を取ります。@var{start}と@var{end}は非負整数のインデックスか
11512 文字列カーソルで、入力文字列を使う範囲を制限します。
11513
11514 @var{proc}が適用される順序は左から右とは限りません。順序に依存しないようにしてください。
11515
11516 @var{proc}が継続を補足し、それが再び起動された場合、既に@code{string-map}から
11517 返された結果は影響を受けません。(R7RSで指定されています)
11518 @c COMMON
11519
11520 @example
11521 (string-map char-upcase "apple") @result{} "APPLE"
11522 (string-map (^[a b] (if (char>? a b) a b)) "orange" "apple") @result{} "orpng"
11523 (string-map char-upcase "pineapple" 0 4) @result{} "PINE"
11524 @end example
11525 @end defun
11526
11527
11528 @defun string-for-each proc str str2 @dots{}
11529 @defunx string-for-each proc str :optional start end
11530 [R7RS base][SRFI-13]
11531 @c EN
11532 Applies @var{proc} over each character in the input string in left-to-right
11533 order. The results of @var{proc} is discarded.
11534
11535 Because of historical reasons, this procedure has two interfaces,
11536 first one defined in R7RS and second one defined in SRFI-13.
11537 See @code{string-map} above for the explanation.
11538 @c JP
11539 @var{proc}を入力文字列の各文字に左から右の順で適用します。@var{proc}の結果は捨てられます。
11540
11541 歴史的経緯から、この手続きは2種類のインタフェースを持ちます。
11542 最初のインタフェースはR7RSで、二番目のインタフェースはSRFI-13で定義されています。
11543 詳しくは上の@code{string-map}の項を参照してください。
11544 @c COMMON
11545 @end defun
11546
11547
11548 @node Incomplete strings, , String utilities, Strings
11549 @subsection Incomplete strings
11550 @c NODE 不完全文字列
11551
11552 @c EN
11553 A string can be flagged as "incomplete" if it may contain
11554 byte sequences that do not consist of a valid multibyte character
11555 in the Gauche's native encoding.
11556 @c JP
11557 Gaucheの内部エンコーディングで正当なマルチバイト文字で構成されていない
11558 ようなバイト列を含む文字列は「不完全文字列」となります。
11559 @c COMMON
11560
11561 @c EN
11562 Incomplete strings may be generated in several circumstances;
11563 reading binary data as a string, reading a string data that has
11564 been 'chopped' in middle of a multibyte character, or
11565 concatenating a string with other incomplete strings, for example.
11566 @c JP
11567 不完全文字列が生成される状況はいくつかあります。たとえば、バイナリデー
11568 タを文字列として読み込んだとき、マルチバイト文字の途中で切れた文字列を
11569 読み込んだとき、別の不完全文字列が連結された場合などです。
11570 @c COMMON
11571
11572 @c EN
11573 Incomplete strings should be regarded as an exceptional case.
11574 It used to be a way to handle byte strings, but now we have
11575 u8vector (@pxref{Uniform vectors}) for that purpose.
11576 In fact, we're planning to remove it in the future releases.
11577 @c JP
11578 不完全文字列は例外的な状況であるとみなすべきです。以前はバイト列を処理するのに
11579 不完全文字列が使われていましたが、
11580 現在はu8vector (@ref{Uniform vectors}参照)を使うことができるので、
11581 将来のリリースでは削除する計画です。
11582 @c COMMON
11583
11584 @c EN
11585 Just in case, if you happen to get an incomplete string,
11586 you can convert it to a complete string by @code{string-incomplete->complete}.
11587 @c JP
11588 万が一、不完全文字列に出会ってしまったら
11589 @code{string-incomplete->complete}で完全な文字列に変換することができます。
11590 @c COMMON
11591
11592 @deftp {Reader Syntax} @code{#**"}@dots{}@code{"}
11593 @lxindex #**
11594 @c EN
11595 Denotes incomplete string. The same escape sequences as the complete
11596 string syntax are recognized.
11597 @c JP
11598 不完全な文字列のリテラル表記です。完全な文字列と同様のエスケープシーケンスが
11599 使えます。
11600 @c COMMON
11601
11602 @c EN
11603 Rationale of the syntax: @code{#*} is used for bit vectors.
11604 Since an incomplete strings is really a byte vector,
11605 it has similarity.
11606 @c JP
11607 @code{#*} という構文はCommon Lispでビットベクタの表記に使われています。
11608 不完全な文字列は実際はバイトベクタであることから、類似点を認めてこの構文を
11609 採用しました。
11610 @c COMMON
11611
11612 @c EN
11613 Note: We used @code{#*"...."} for an incomplete string on 0.9.9 and
11614 before. It turned out that it couldn't coexist with bitvectors, for
11615 @code{#*} is a valid bitvector literal (zero-length vector), and
11616 @code{"} is a delimiter, so @code{#*"...."} can be parsed as
11617 a zero-length bitvector followed by a string. From 0.9.10, we changed
11618 the incomplete string literal to @code{#**"..."}. It's a bit lengthy,
11619 but incomplete strings are anomalies and shouldn't be used often anyway.
11620
11621 For the backward compatibility, @code{#*"..."} is still read as an
11622 incomplete string literal, unless the reader lexical mode
11623 is @code{strict-r7} (@pxref{Reader lexical mode}, for the details).
11624 If the reader lexical mode is @code{warn-legacy}, it is read as
11625 an incomplete string, but a warning is issued.
11626 If the mode is @code{strict-r7}, it is read as a zero-length
11627 bitvector followed by a string.
11628
11629 In future releasers, @code{#*"..."} would be warned by default,
11630 and later we'll gradually move to @code{strict-r7} behavior.
11631 @c JP
11632 註: 0.9.9までは、不完全文字列リテラルとして@code{#*"..."}を使っていました。
11633 しかし、それはビットベクタリテラルと共存できないことが判明しました。
11634 @code{#*}は有効なビットベクタリテラル(長さ0のビットベクタ)で、
11635 また@code{"}はデリミタなので、@code{#*"...."}は長さ0のビットベクタと
11636 通常の文字列、とパーズできてしまいます。
11637 0.9.10からは、不完全文字列リテラルは@code{#**"..."}になりました。
11638 ちょっと長いですが、もともと不完全文字列は例外的に現れるもので、
11639 積極的に使うべきではありません。
11640
11641 後方互換性のため、デフォルトでは@code{#*"..."}はリーダー字句モードが
11642 @code{strict-r7}でない限りは不完全文字列リテラルとして読まれます。
11643 (リーダー字句モードについては@ref{Reader lexical mode}参照。)
11644 リーダ字句モードが@code{warn-legacy}だった場合は、
11645 このリテラルは不完全文字列として読まれますが、警告が出されます。
11646 リーダ字句モードが@code{strict-r7}であれば、
11647 このリテラルは長さ0のビットベクタと、通常の文字列として読まれます。
11648
11649 将来のリリースでは、デフォルトで@code{#*"..."}は警告を出すようにし、
11650 その後@code{strict-r7}の振る舞いに移行する予定です。
11651 @c COMMON
11652 @end deftp
11653
11654
11655 @defun string-incomplete->complete str :optional handling filler
11656 @c EN
11657 Reinterpret the content of an incomplete string @var{str}
11658 and returns a newly created complete string from it.
11659 @c JP
11660 不完全文字列@var{str}の内容を再解釈して、あらたに完全文字列を返します。
11661 @c COMMON
11662 @c EN
11663 The @var{handling} argument specifies how to handle the illegal
11664 byte sequences in @var{str}.
11665 @c JP
11666 @var{handling}引数で@var{str}中の不正なバイト列の扱いかたを指定します。
11667 @c COMMON
11668 @table @asis
11669 @item @code{#f}
11670 @c EN
11671 If @var{str} contains an illegal byte sequence, give up the
11672 conversion and returns @code{#f}. This is the default behavior.
11673 @c JP
11674 @var{str}が不正なバイト列を含んでいる場合、変換を諦めて@code{#f}を返し
11675 ます。これがデフォルトのふるまいです。
11676 @c COMMON
11677 @item @code{:omit}
11678 @c EN
11679 Omit any illegal byte sequences.
11680 @c JP
11681 不正なバイト列を捨てます。
11682 @c COMMON
11683 @c EN
11684 @item @code{:replace}
11685 Replace each byte in illegal byte sequences by a character given
11686 in @var{filler} argument, defaulted to @code{?}.
11687 @c JP
11688 @item 1文字
11689 不正なバイト列中の各バイトを、@var{filler}引数に与えられ文字で置き換えます。
11690 @var{filler}引数のデフォルトは@code{?}です。
11691 @c COMMON
11692 @item @code{:escape}
11693 Replace each byte in illegal byte sequences by a sequence of
11694 @var{filler} @code{<hexdigit>} @code{<hexdigit>}.
11695 Besides, the @var{filler} characters in the original string is replaced with
11696 @var{filler} @var{filler}.
11697 @c JP
11698 @item 1文字
11699 不正なバイト列中の各バイトを、@var{filler} @code{<hexdigit>} @code{<hexdigit>}
11700 の3文字で置き換えます。さらに、元文字列中に@var{filler}が登場した場合はそれぞれを
11701 @var{filler} @var{filler} で置き換えます。
11702 @c COMMON
11703 @end table
11704
11705 @c EN
11706 If @var{str} is already a complete string, its copy is returned.
11707 @c JP
11708 @var{str}が完全文字列なら、そのコピーが返されます。
11709 @c COMMON
11710
11711 @c EN
11712 The procedure always returns a complete string, except when
11713 the @var{handling} argument is @code{#f} (default) and the input is an
11714 incomplete string, in which case @code{#f} is returned.
11715 @c JP
11716 この手続きは、@var{handling}引数が@code{#f} (デフォルト) で入力が
11717 不完全文字列だった場合に@code{#f}を返す以外は、常に完全文字列を返します。
11718 @c COMMON
11719
11720 @example
11721 (string-incomplete->complete #**"_abc")
11722 @result{} "_abc" ; can be represented as a complete string
11723
11724 (string-incomplete->complete #**"_ab\x80;c")
11725 @result{} #f ; can't be represented as a complete string
11726
11727 (string-incomplete->complete #**"_ab\x80;c" :omit)
11728 @result{} "_abc" ; omit the illegal bytes
11729
11730 (string-incomplete->complete #**"_ab\x80;c" :replace #\_)
11731 @result{} "_ab_c" ; replace the illegal bytes
11732
11733 (string-incomplete->complete #**"_ab\x80;c" :escape #\_)
11734 @result{} "__ab_80c" ; escape the illegal bytes and escape char itself
11735 @end example
11736 @end defun
11737
11738 @c ----------------------------------------------------------------------
11739 @node Regular expressions, Vector family, Strings, Core library
11740 @section Regular expressions
11741 @c NODE 正規表現
11742
11743 @c EN
11744 Gauche has a built-in regular expression engine which is mostly
11745 upper-compatible of POSIX extended regular expression, plus
11746 some extensions from Perl 5 regexp.
11747
11748 A special syntax is provided for literal regular expressions.
11749 Also regular expressions are applicable, that is,
11750 it works like procedures that match the given string to itself.
11751 Combining with these two features enables writing some
11752 string matching idioms compact.
11753 @c JP
11754 GaucheはPOSIXの拡張正規表現にほぼ上位互換で、さらに
11755 Perl 5の正規表現から拡張機能を採り入れた正規表現エンジンを持っています。
11756 Gaucheはまた、リテラル正規表現用の構文を備えています。
11757
11758 正規表現用のリテラル構文が用意されており、
11759 また、正規表現オブジェクトは適用可能、つまり文字列に対して
11760 手続きのように振る舞い、自分自身にマッチするかどうかを判定できるようになっています。
11761 この二つの機能によって、文字列のマッチをスキャンするようなイディオムを
11762 簡潔に書けるようになっています。
11763 @c COMMON
11764
11765 @example
11766 (find #/pattern/ list-of-strings)
11767 @result{} @i{match object} or #f
11768 @end example
11769
11770 @menu
11771 * Regular expression syntax::
11772 * Using regular expressions::
11773 * Inspecting and assembling regular expressions::
11774 @end menu
11775
11776 @node Regular expression syntax, Using regular expressions, Regular expressions, Regular expressions
11777 @subsection Regular expression syntax
11778 @c NODE 正規表現の構文
11779
11780 @deftp {Reader Syntax} @code{#/@i{regexp-spec}/}
11781 @deftpx {Reader Syntax} @code{#/@i{regexp-spec}/i}
11782 @lxindex #/
11783 @c EN
11784 Denotes literal regular expression object. When read, it becomes
11785 an instance of @code{<regexp>}.
11786 @c JP
11787 リテラルの正規表現オブジェクトを表記します。読まれた際に@code{<regexp>}の
11788 インスタンスとなります。
11789 @c COMMON
11790
11791 @c EN
11792 If a letter '@code{i}' is given at the end, the created regexp
11793 becomes @emph{case-folding regexp}, i.e. it matches in the case-insensitive
11794 way.
11795 @c JP
11796 末尾に文字@code{i}が与えられた場合は、マッチ時に大文字小文字を区別しない
11797 正規表現オブジェクトとなります。
11798 @c COMMON
11799
11800 @c EN
11801 The advantage of using this syntax over @code{string->regexp} is
11802 that the regexp is compiled only once. You can use literal regexp
11803 inside loop without worrying about regexp compilation overhead.
11804 If you want to construct regexp on-the-fly, however, use @code{string->regexp}.
11805 @c JP
11806 @code{string->regexp}に対してこの構文を使う利点は、
11807 正規表現のコンパイルが一度しか行われない点です。この構文は、
11808 内部ループの中でも、正規表現のコンパイルのオーバヘッドを気にせずに
11809 使うことができます。動的に正規表現を作成したい場合のみ@code{string->regexp}を
11810 使って下さい。
11811 @c COMMON
11812 @end deftp
11813
11814 @c EN
11815 Gauche's built-in regexp syntax follows POSIX extended regular
11816 expression, with a bit of extensions taken from Perl.
11817 (Scheme Regulare Expression (SRE) is also supported as an alternative
11818 syntax; @pxref{R7RS regular expressions}, for the details of SRE.)
11819 @c JP
11820 Gaucheの組み込み正規表現構文はPOSIX拡張正規表現に準じたものに、
11821 Perlの拡張の一部を採り入れたものです。
11822 (別構文として、Scheme正規表現(SRE)もサポートされています。
11823 SREについては@ref{R7RS regular expressions}を参照してください。)
11824 @c COMMON
11825
11826 @table @code
11827 @item @i{re}*
11828 @c EN
11829 Matches zero or more repetition of @i{re}.
11830 @c JP
11831 @i{re}の0回以上の繰り返しにマッチします。
11832 @c COMMON
11833
11834 @item @i{re}+
11835 @c EN
11836 Matches one or more repetition of @i{re}.
11837 @c JP
11838 @i{re}の1回以上の繰り返しにマッチします。
11839 @c COMMON
11840
11841 @item @i{re}?
11842 @c EN
11843 Matches zero or one occurrence of @i{re}.
11844 @c JP
11845 @i{re}の0回または1回の出現にマッチします。
11846 @c COMMON
11847
11848 @item @i{re}@{@i{n}@}
11849 @itemx @i{re}@{@i{n},@i{m}@}
11850 @c EN
11851 Bounded repetition. @code{@i{re}@{@i{n}@}} matches exactly @i{n}
11852 occurrences of @i{re}.
11853 @code{@i{re}@{@i{n},@i{m}@}} matches at least @var{n} and at most
11854 @var{m} occurrences of @i{re}, where @var{n} <= @var{m}.
11855 In the latter form, either @var{n} or @var{m} can be omitted; omitted @var{n}
11856 is assumed as 0, and omitted @var{m} is assumed infinity.
11857 @c JP
11858 回数に範囲のある繰り返しです。
11859 @code{@i{re}@{@i{n}@}}は@i{re}の@i{n}回の繰り返しにマッチします。
11860 @code{@i{re}@{@i{n},@i{m}@}}は@i{re}の@i{n}回以上、@i{m}回以下の
11861 繰り返しにマッチします。但し@var{n} <= @var{m}とします。
11862 2番目の形式では@var{n}か@var{m}のどちらかを省略することが
11863 できます。@var{n}が省略された場合は0とみなされます。
11864 @var{m}が省略された場合は無限大とみなされます。
11865 @c COMMON
11866
11867 @item @i{re}*?
11868 @itemx @i{re}+?
11869 @itemx @i{re}??
11870 @itemx @i{re}@{@i{n},@i{m}@}?
11871 @c EN
11872 Same as the above repetition construct, but these syntaxes
11873 use "non-greedy" or "lazy" match strategy. That is, they try to match
11874 the minimum number of occurrences of @i{re} first, then retry
11875 longer ones only if it fails. In the last form
11876 either @var{n} or @var{m} can be omitted.
11877 Compare the following examples:
11878 @c JP
11879 上記の繰り返し構造とほぼ同じですが、これらの構文は「non-greedy」または
11880 「lazy」と呼ばれるマッチ戦略を用います。すなわち、まず@i{re}がマッチする
11881 最小の回数を試し、それが失敗したら順に繰り返しの回数を増やしてゆきます。
11882 最後の形式では@var{n}か@var{m}のどちらかは省略できます。
11883 次の例を比べてみてください:
11884 @c COMMON
11885
11886 @example
11887 (rxmatch-substring (#/<.*>/ "<tag1><tag2><tag3>") 0)
11888 @result{} "<tag1><tag2><tag3>"
11889
11890 (rxmatch-substring (#/<.*?>/ "<tag1><tag2><tag3>") 0)
11891 @result{} "<tag1>"
11892 @end example
11893
11894 @item (@i{re}@dots{})
11895 @c EN
11896 Clustering with capturing. The regular expression enclosed
11897 by parenthesis works as a single @i{re}. Besides, the string
11898 that matches @i{re} @dots{} is saved as a @emph{submatch}.
11899 @c JP
11900 捕捉クラスタリング。括弧でくくられた正規表現の列がグループとして
11901 扱われ、またそれにマッチした文字列はサブマッチとして保存されます。
11902 @c COMMON
11903
11904 @item (?:@i{re}@dots{})
11905 @c EN
11906 Clustering without capturing. @code{@i{re} @dots{}} works as
11907 a single @i{re}, but the matched string isn't saved.
11908 @c JP
11909 捕捉無しクラスタリング。@code{@i{re} @dots{}}はグループとして
11910 扱われますが、サブマッチとして保存されません。
11911 @c COMMON
11912
11913 @item (?<@i{name}>@i{re}@dots{})
11914 @c EN
11915 Named capture and clustering. Like @code{(@i{re}@dots{})},
11916 but adds the name @i{name} to the matched substring.
11917 You can refer to the matched substring by both index number
11918 and the name.
11919
11920 When the same name appears more than once in a regular
11921 expression, it is undefined which matched substring is
11922 returned as the submatch of the named capture.
11923 @c JP
11924 名前つきの捕捉とクラスタリング。@code{(@i{re}@dots{})}と同様ですが、
11925 マッチした文字列に名前@i{name}がつけられます。マッチした文字列には
11926 インデックスの数字と名前のどちらでも参照できます。
11927
11928 同じ名前が複数回正規表現内に出現した場合、どの名前付き捕捉にマッチした
11929 部分文字列が返されるかは不定です。
11930 @c COMMON
11931
11932 @item (?i:@i{re}@dots{})
11933 @itemx (?-i:@i{re}@dots{})
11934 @c EN
11935 Lexical case sensitivity control.
11936 @code{(?i:@i{re}@dots{})} makes @i{re}@dots{} matches case-insensitively,
11937 while @code{(?-i:@i{re}@dots{})} makes
11938 @i{re}@dots{} matches case-sensitively.
11939
11940 Perl's regexp allows several more flags to appear between '?' and ':'.
11941 Gauche only supports above two, for now.
11942 @c JP
11943 大文字小文字の区別の制御。
11944 @code{(?i:@i{re}@dots{})}は@i{re}@dots{}が大文字小文字にかかわらず
11945 マッチするようにします。
11946 @code{(?-i:@i{re}@dots{})}はその逆です。
11947
11948 Perlの正規表現では'?'と':'の間に他のいくつかのフラグを使うことが
11949 できますが、Gaucheでは今のところこのフラグのみをサポートしています。
11950 @c COMMON
11951
11952 @item @i{pattern1}|@i{pattern2}|@dots{}
11953 @c EN
11954 Alternation. Matches either one of patterns, where each
11955 pattern is @i{re} @dots{}.
11956 @c JP
11957 パターンのいずれかにマッチします。
11958 @c COMMON
11959
11960 @item \@i{n}
11961 @c EN
11962 Backreference. @i{n} is an integer.
11963 Matches the substring captured by the @i{n}-th capturing group.
11964 (counting from 1). When capturing groups are nested, groups
11965 are counted by their beginnings.
11966 If the @i{n}-th capturing group is in a repetition and has matched
11967 more than once, the last matched substring is used.
11968 @c JP
11969 バックリファレンス。@i{n}は整数です。
11970 @i{n}番目(1から数える)の捕捉カッコに捕捉された文字列と一致する場合に、\@i{n}が
11971 マッチします。補足カッコがネストしている場合、開きカッコの順番で数えます。
11972 @i{n}番目のカッコが繰り返しの中にあり、複数回マッチ
11973 している場合は、最後にマッチした文字列との比較が行われます。
11974 @c COMMON
11975
11976 @item \k<@i{name}>
11977 @c EN
11978 Named backreference. Matches the substring captured by
11979 the capturing group with the name @i{name}.
11980 If the named capturing group is in a repetition and has matched
11981 more than once, the last matched substring is used.
11982 If there are more than one capturing group with @i{name},
11983 matching will succeed if the input matches either one of the substrings
11984 captured by those groups.
11985 @c JP
11986 名前によるバックリファレンス。
11987 名前@i{name}を持つ捕捉カッコで捕捉された文字列と一致する場合に、
11988 \k<@i{name}>がマッチします。参照しているカッコが繰り返しの中にあり、
11989 複数回マッチしている場合は、最後にマッチした文字列との比較が行わ
11990 れます。同じ名前@i{name}を持つ捕捉カッコが複数ある場合には、
11991 それらのカッコの最後にマッチした文字列のいずれかと一致する場合、
11992 マッチが成功します。
11993 @c COMMON
11994
11995 @item .
11996 @c EN
11997 Matches any character (including newline).
11998 @c JP
11999 任意の1文字にマッチします。改行文字にもマッチします。
12000 @c COMMON
12001
12002 @item [@i{char-set-spec}]
12003 @c EN
12004 Matches any of the character set specified by @i{char-set-spec}.
12005 @xref{Character sets}, for the details of @i{char-set-spec}.
12006 @c JP
12007 @i{char-set-spec}で指定される文字集合内の文字にマッチします。
12008 @i{char-set-spec}については@ref{Character sets}を参照して下さい。
12009 @c COMMON
12010
12011 @item \s, \d, \w
12012 @c EN
12013 Matches a whitespace character (@code{char-set:ascii-whitespace},
12014 @code{#[\u0009-\u000d ]}),
12015 a digit character(@code{char-set:ascii-digit}, @code{#[0-9])}, or
12016 a word-constituent character (@code{char-set:ascii-word}, @code{#[A-Za-z0-9_]}),
12017 respectively.
12018 Note that they don't include characters outside ASCII range.
12019
12020 Can be used both inside and outside of character set.
12021 @c JP
12022 それぞれ空白文字(@code{char-set:ascii-whitespace},
12023 @code{#[\u0009-\u000d ]})、
12024 数字(@code{char-set:ascii-digit}, @code{#[0-9])}、
12025 単語を構成する文字(@code{char-set:ascii-word}, @code{#[A-Za-z0-9_]})にマッチします。
12026 ASCIIの外の文字は含まれないことに注意してください。
12027
12028 文字集合内でも、その外でも使えます。
12029 @c COMMON
12030
12031 @item \S, \D, \W
12032 @c EN
12033 Matches the complement character set of @code{\s}, @code{\d} and
12034 @code{\w}, respectively.
12035 @c JP
12036 それぞれ@code{\s}、@code{\d}、@code{\w}で指定される文字集合の補集合の
12037 文字にマッチします。
12038 @c COMMON
12039
12040 @item ^, $
12041 @c EN
12042 Beginning and end of string assertion, when appears at the beginning
12043 or end of the pattern, or optionally, beginning and end of line in
12044 multi-line mode.
12045 @c JP
12046 それぞれ、パターンの最初または最後に指定された場合、
12047 文字列の最初か最後にマッチします。
12048 @c COMMON
12049
12050 @c EN
12051 These characters loses special meanings and matches the characters
12052 themselves if they appear in the position
12053 other than the beginning of the pattern (for @code{^}) or the end
12054 (for @code{$}). For the sake of recognizing those characters,
12055 lookahead/lookbehind
12056 assertions (@code{(?=...)}, @code{(?!...)}, @code{(?<=...)},
12057 @code{(?<!...)}) and atomic clustering (@code{(?>...)}) are
12058 treated as if they are a whole pattern. That is, @code{^} at the
12059 beginning of those groupings are beginning-of-string assertion
12060 no matter where these group appear in the containing regexp.
12061 So as @code{$} at the end of these groupings.
12062 @c JP
12063 これらの文字は、パターンの最初(@code{^}の場合)か最後(@code{$}の場合)に
12064 現れた時のみ特別な意味を持ち、それ以外の場所ではこれらの文字自身にマッチします。
12065 これらの文字を特殊文字と認識する段階では、肯定および否定の先読み
12066 (@code{(?=...)}, @code{(?!...)}, @code{(?<=...)}, @code{(?<!...)})と
12067 アトミックなクラスタリング(@code{(?>...)})はあたかもそれが独立した
12068 パターンであるかのように扱われます。つまり、@code{^}がこれらの構造の先頭に現れた
12069 場合は、これらの構造が全体の正規表現中のどこにあるかには関わらず、文字列先頭への
12070 マッチとみなされます。@code{$}がこれらの構造の末尾に現れたば場合も同様です。
12071 @c COMMON
12072
12073 @item \b, \B
12074 @c EN
12075 Word boundary and non word boundary assertion, respectively.
12076 That is, @code{\b} matches an empty string between
12077 word-constituent character and non-word-constituent character,
12078 and @code{\B} matches an empty string elsewhere.
12079 @c JP
12080 @code{\b}は単語の境界の空文字列にマッチします。
12081 @code{\B}はその逆です。
12082 @c COMMON
12083
12084 @item \;
12085 @itemx \"
12086 @itemx \#
12087 @c EN
12088 These are the same as @code{;}, @code{"}, and @code{#}, respectively,
12089 and can be used to avoid confusing Emacs or other syntax-aware editors
12090 that are not familiar with Gauche's extension.
12091 @c JP
12092 これらはそれぞれ@code{;}、@code{"}、および@code{#}と同じです。
12093 Emacs等、Scheme構文を理解するエディタを混乱させないために使うことができます。
12094 @c COMMON
12095
12096 @item (?=@i{pattern})
12097 @itemx (?!@i{pattern})
12098 @c EN
12099 Positive/negative lookahead assertion.
12100 Match succeeds if @i{pattern} matches (or does not match)
12101 the input string from the current position, but this doesn't
12102 move the current position itself, so that the following
12103 regular expression is applied again from the current position.
12104
12105 For example, the following expression matches strings
12106 that might be a phone number, except the numbers in Japan
12107 (i.e. ones that begin with "81").
12108 @c JP
12109 肯定および否定の先読み。
12110 @i{pattern}が文字列の現在の位置にマッチする(あるいはマッチ
12111 しない)ときにマッチが成功しますが、現在の位置は変更しない
12112 ので、後に続く正規表現は現在と同じ位置から適用されます。
12113
12114 例えば、次の表現は、電話番号のうち日本の番号("81"から始まるもの)
12115 を除く文字列にマッチします。
12116 @c COMMON
12117
12118 @example
12119 \+(?!81)\d@{9,@}
12120 @end example
12121
12122 @item (?<=@i{pattern})
12123 @itemx (?<!@i{pattern})
12124 @c EN
12125 Positive/negative lookbehind assertion.
12126 If the input string immediately before the current
12127 input position matches @var{pattern}, this pattern
12128 succeeds or fails, respectively. Like lookahead
12129 assertion, the input position isn't changed.
12130
12131 Internally, this match is tried by reversing
12132 @var{pattern} and applies it to the backward
12133 of input character sequence. So you can
12134 write any regexp in @var{pattern}, but if the
12135 submatches depend on the matching order,
12136 you may get different submatches from when
12137 you match @var{pattern} from left to right.
12138 @c JP
12139 肯定および否定の後読み。
12140 現在の位置の左側に@var{pattern}にマッチする文字列がある場合に
12141 マッチが成功(あるいは失敗)します。先読みと同様、現在の位置は
12142 変更しません。
12143
12144 内部的にこの表現は、@i{pattern}を逆転させたうえで、現在の位置
12145 から左に向かってマッチを進めることで実現されています。したがって、
12146 @i{pattern}には任意のものにマッチする表現を含めることができますが、
12147 マッチの順番や長さが重要な場合(例えば2通りにマッチしうる捕捉の
12148 カッコ)などは、左から右に現在位置が進むときとは異なる場所に
12149 マッチするかもしれません。
12150 @c COMMON
12151
12152 @item (?>@i{pattern})
12153 @c EN
12154 Atomic clustering. Once @i{pattern} matches,
12155 the match is fixed; even if the following pattern fails,
12156 the engine won't backtrack to try the
12157 alternative match in @i{pattern}.
12158 @c JP
12159 アトミックなクラスタリング。@i{pattern}がいったんマッチすると、
12160 そのマッチは確定します。後続のパターンが失敗した場合でも、
12161 @i{pattern}内にバックトラックして他のマッチが試みられることはありません。
12162 @c COMMON
12163
12164 @item @i{re}*+
12165 @itemx @i{re}++
12166 @itemx @i{re}?+
12167 @c EN
12168 They are the same as (?>@i{re}*), (?>@i{re}+), (?>@i{re}?), respectively.
12169 @c JP
12170 それぞれ(?>@i{re}*)、(?>@i{re}+)、(?>@i{re}?)と同じです。
12171 @c COMMON
12172
12173 @item (?@i{test-pattern} @i{then-pattern})
12174 @itemx (?@i{test-pattern} @i{then-pattern}|@i{else-pattern})
12175 @c EN
12176 Conditional matching. If @var{test-pattern} counts
12177 true, @var{then-pattern} is tried; otherwise
12178 @var{else-pattern} is tried when provided.
12179
12180 @var{test-pattern} can be either one of the following:
12181
12182 @table @code
12183 @item (@i{integer})
12184 Backreference. If @var{integer}-th capturing group has a match,
12185 this test counts true.
12186
12187 @item (?=@i{pattern})
12188 @itemx (?!@i{pattern})
12189 Positive/negative lookahead assertion. It tries @var{pattern}
12190 from the current input position without consuming input,
12191 and if the match succeeds or fails, respectively, this
12192 test counts true.
12193
12194 @item (?<=@i{pattern})
12195 @itemx (?<!@i{pattern})
12196 Positive/negative lookbehind assertion. It tries @var{pattern}
12197 backward from the left size of the current input position,
12198 and if the match succeeds or fails, respectively, this
12199 test counts true.
12200 @end table
12201 @c JP
12202 条件つきマッチング。@var{test-pattern}が成功すれば
12203 @var{then-pattern}へと、そうでなければ
12204 @var{else-pattern}へと(もしあれば)マッチを進めます。
12205
12206 @var{test-pattern}には以下の形式が書けます。
12207
12208 @table @code
12209 @item (@i{integer})
12210 バックリファレンス。@var{integer}番目の捕捉クラスタリングのマッチに
12211 成功していた場合に成功となります。
12212
12213 @item (?=@i{pattern})
12214 @itemx (?!@i{pattern})
12215 肯定および否定の先読み。入力の現在位置から、入力を消費することなく
12216 @var{pattern}のマッチを試み、それがそれぞれ成功もしくは失敗した
12217 場合に、この@var{test-pattern}を成功とみなします。
12218
12219 @item (?<=@i{pattern})
12220 @itemx (?<!@i{pattern})
12221 肯定および否定の後読み。入力の現在位置から左側に向かって、
12222 @var{pattern}の逆向きにマッチを試みます、
12223 それがそれぞれ成功もしくは失敗した場合に、
12224 この@var{test-pattern}を成功とみなします。
12225 @end table
12226 @c COMMON
12227 @end table
12228
12229 @node Using regular expressions, Inspecting and assembling regular expressions, Regular expression syntax, Regular expressions
12230 @subsection Using regular expressions
12231 @c NODE 正規表現を使う
12232
12233 @c EN
12234 @subsubheading Regexp object and rxmatch object
12235 @c JP
12236 @subsubheading Regexpオブジェクトとrxmatchオブジェクト
12237 @c COMMON
12238
12239 @deftp {Builtin Class} <regexp>
12240 @clindex regexp
12241 @c EN
12242 Regular expression object. You can construct a regexp object
12243 from a string by @code{string->regexp} or @code{sre->regexp}
12244 at run time. Gauche also
12245 has a special syntax to denote regexp literals, which construct
12246 regexp object at loading time.
12247
12248 Gauche's regexp engine is fully aware of multibyte characters.
12249 @c JP
12250 正規表現オブジェクトのクラスです。@code{string->regexp}
12251 あるいは@code{sre->regexp}を使って実行時に作成できます。
12252 また、Gaucheはリテラルの正規表現を表す構文を持っており、
12253 ロード時に作成することもできます。
12254
12255 Gaucheの正規表現エンジンはマルチバイト文字列に対応しています。
12256 @c COMMON
12257 @end deftp
12258
12259 @deftp {Builtin Class} <regmatch>
12260 @clindex regmatch
12261 @c EN
12262 Regexp match object. A regexp matcher @code{rxmatch} returns
12263 this object if match. This object contains all the information
12264 about the match, including submatches.
12265
12266 The advantage of using match object, rather than substrings or
12267 list of indices, is efficiency. The regmatch object keeps internal
12268 state of match, and computes indices and/or substrings only when
12269 requested. This is particularly effective for multibyte strings,
12270 for index access is slow on them.
12271 @c JP
12272 正規表現マッチオブジェクトのクラスです。正規表現エンジン@code{rxmatch}は、
12273 一致した場合にこのオブジェクトを返します。部分一致の情報を含めた
12274 全てのマッチに関する情報がこのオブジェクトに含まれています。
12275
12276 一致した部分文字列やそのインデックスのリストではなく
12277 マッチオブジェクトを返すことの利点は効率です。
12278 regmatchオブジェクトはマッチの内部状態を保持しており、
12279 要求された時にはじめて該当する部分文字列やインデックスを計算します。
12280 これは特にマルチバイト文字列に有効です。マルチバイト文字列
12281 へのインデックスアクセスは遅いからです。
12282 @c COMMON
12283 @end deftp
12284
12285 @defun string->regexp string :key case-fold multi-line
12286 @c EN
12287 Takes @var{string} as a regexp specification, and constructs
12288 an instance of @code{<regexp>} object.
12289 @c JP
12290 文字列@var{string}を正規表現とみなして、@code{<regexp>}のインスタンスを
12291 作成して返します。
12292 @c COMMON
12293
12294 @c EN
12295 If a true value is given to the keyword argument @var{case-fold},
12296 the created regexp object becomes case-folding regexp.
12297 (See the above explanation about case-folding regexp).
12298 @c JP
12299 キーワード引数@var{case-fold}に真の値が与えられた場合、作成される正規表現は
12300 大文字小文字を区別しないものとなります。
12301 (大文字小文字を区別しない正規表現に関しては上の説明を参照して下さい)。
12302 @c COMMON
12303
12304 @c EN
12305 If a true value is given to the keyword argument @var{multi-line},
12306 @code{^} and @code{$} will assert the beginning and end of line in
12307 addition to beginning and end of string. Popular line terminators (LF
12308 only, CRLF and CR only) are recognized.
12309 @c JP
12310 キーワード引数@var{multi-line}に真の値が与えられた場合、
12311 @code{^}と@code{$}はそれぞれ入力文字列の最初と最後に加え、
12312 各行の先頭と末尾にもマッチします。
12313 行の区切りはLFのみ、CRLF、あるいはCRのみのいずれも認識されます。
12314 @c COMMON
12315 @end defun
12316
12317 @defun sre->regexp sre :key multi-line
12318 @c EN
12319 Takes a scheme regexp @var{sre} and returns a @code{<regexp>} object. The
12320 zero-th group is always captured.
12321
12322 If a false value is given to the keyword argument @var{multi-line},
12323 which is the default,
12324 @code{bol} and @code{eol} behave like @code{bos} and @code{eos}
12325 (i.e. only match at the beginning or end of string).
12326 @c JP
12327 Scheme正規表現 @var{sre} を取り、コンパイルした@code{<regexp>}オブジェクトを
12328 返します。正規表現全体が常に0番の捕捉グループになります。
12329
12330 キーワード引数@var{multi-line}に偽の値が与えられた場合
12331 (デフォルト)、@code{bol}と@code{eol}はそれぞれ@code{bos}と@code{eos}のように
12332 振る舞います (つまり、入力文字列の最初と最後にのみマッチします)。
12333 @c COMMON
12334 @end defun
12335
12336 @defun regexp? @var{obj}
12337 @c EN
12338 Returns true iff @var{obj} is a regexp object.
12339 @c JP
12340 @var{obj}が正規表現オブジェクトなら真の値を返します。
12341 @c COMMON
12342 @end defun
12343
12344 @defun regexp->string @var{regexp}
12345 @c EN
12346 Returns a source string describing the regexp @var{regexp}.
12347 The returned string is immutable.
12348 @c JP
12349 正規表現@var{regexp}を記述する元になった文字列を返します。
12350 返される文字列は変更不可な文字列です。
12351 @c COMMON
12352 @end defun
12353
12354 @defun regexp->sre @var{regexp}
12355 @c EN
12356 Returns a scheme regexp (SRE) describing the regexp @var{regexp}.
12357 @xref{R7RS regular expressions}, for the details of SRE.
12358 @c JP
12359 正規表現@var{regexp}を生成するScheme正規表現式(SRE)を返します。
12360 SREについて詳しくは@ref{R7RS regular expressions}を参照してください。
12361 @c COMMON
12362 @end defun
12363
12364 @defun regexp-num-groups regexp
12365 @defunx regexp-named-groups regexp
12366 @c EN
12367 Queries the number of capturing groups, and an alist of named capturing
12368 groups, in the given @var{regexp}, respectively.
12369
12370 The number of capturing groups corresponds to the number of matches
12371 returned by @code{rxmatch-num-matches}. Note that the entire regexp
12372 forms a group, so the number is always positive.
12373
12374 The alist returned from @code{regexp-named-groups} has the group name
12375 (symbol) in @code{car}, and its subgroup number in @code{cdr}.
12376 Note that the order of groups in the alist isn't fixed.
12377 @c JP
12378 正規表現@var{regexp}中の、捕捉グループ(サブマッチに使われるグループ)の総数、
12379 及び名前つき捕捉グループのalistをそれぞれ返します。
12380
12381 捕捉グループの総数は、この正規表現でマッチした場合のマッチオブジェクトの
12382 @code{rxmatch-num-matches}と同じになります。正規表現全体もひとつのグループだと
12383 みなされるので、総数は常に1以上です。
12384
12385 @code{regexp-named-groups}から返されるalistは
12386 @code{car}に名前(シンボル)、@code{cdr}にそのサブマッチ番号を持つペアを
12387 要素とします。alist内でのグループの順番は不定です。
12388 @c COMMON
12389
12390 @example
12391 (regexp-num-groups #/abc(?<foo>def)(ghi(?<bar>jkl)(mno))/)
12392 @result{} 5
12393 (regexp-named-groups #/abc(?<foo>def)(ghi(?<bar>jkl)(mno))/)
12394 @result{} ((bar . 3) (foo . 1))
12395 @end example
12396 @end defun
12397
12398
12399 @c EN
12400 @subsubheading Trying a match
12401 @c JP
12402 @subsubheading マッチを試みる
12403 @c COMMON
12404
12405 @defun rxmatch regexp string :optional start end
12406 @c EN
12407 @var{Regexp} is a regular expression object.
12408 A string @var{string} is matched by
12409 @var{regexp}. If it matches, the function returns a @code{<regmatch>}
12410 object. Otherwise it returns @code{#f}.
12411 @c JP
12412 正規表現オブジェクト@var{regexp}に一致するものを文字列@var{string}から
12413 探します。一致が見付かった場合は@code{<regmatch>}オブジェクトを返し、
12414 見付からなかった場合は@code{#f}を返します。
12415 @c COMMON
12416
12417 If @var{start} and/or @var{end} are given, only the substring between
12418 @var{start} (inclusive) and @var{end} (exclusive) is searched.
12419
12420 @c EN
12421 This is called @code{match}, @code{regexp-search} or @code{string-match}
12422 in some other Scheme implementations.
12423 @c JP
12424 他のScheme処理系ではこれは
12425 @code{match}、@code{regexp-search}、@code{string-match}など
12426 様々な名で呼ばれています。
12427 @c COMMON
12428
12429 @c EN
12430 Internally, Gauche uses backtracking for regexp match.
12431 When regexp has multiple match possibilities, Gauche saves
12432 an intermediate result in a stack and try one choice, and if it fails
12433 try another. Depending on regexp, the saved results may grow linear
12434 to the input. Gauche allocates a fixed amount of memory for that,
12435 and if there are too many saved results, you'll get the following
12436 error:
12437 @c JP
12438 内部的に、Gaucheは正規表現のマッチにバックトラックを使っています。
12439 複数のマッチの可能性がある場合、その時点の状態をスタックにセーブして一つの可能性を試し、
12440 だめだったら戻ってもう一つの可能性を試します。正規表現によっては、
12441 セーブする状態が入力の大きさに比例してしまう場合があります。
12442 セーブする状態が大きくなりすぎると、次のエラーが投げられます。
12443 @c COMMON
12444
12445 @example
12446 ERROR: Ran out of stack during matching regexp #/.../. Too many retries?
12447 @end example
12448
12449 @c EN
12450 If you get this error, consider using hybrid parsing approach.
12451 Our regexp engine isn't made to do everything-in-one-shot parsing;
12452 in most cases, the effect of complex regexp can be achieved better
12453 with more powerful grammar than regular grammar.
12454 @c JP
12455 このエラーが起きた場合、他のパーズ手法を組み合わせることを検討してください。
12456 Gaucheの正規表現エンジンはそれ一つで何もかもやってしまうことを目的として作られては
12457 いません。多くの場合、複雑な正規表現を駆使するよりも、
12458 正規文法より強力な文法を使う方がうまくいきます。
12459 @c COMMON
12460
12461 @c EN
12462 To apply the match repeatedly on the input string, or to match
12463 from the input stream (such as the data from the port),
12464 you may want to check @code{grxmatch} in @code{gauche.generator}
12465 (@pxref{Generator operations}).
12466 @c JP
12467 入力から複数のマッチを取り出したり、あるいはストリーム入力 (ポートから読み出すデータなど)
12468 にマッチをかけたい場合は、@code{gauche.generator}モジュールの@code{grxmatch}
12469 も使えるかもしれません (@ref{Generator operations}参照)。
12470 @c COMMON
12471 @end defun
12472
12473 @deffn {Generic application} @var{regexp} @var{string}
12474 @c EN
12475 A regular expression object can be applied directly to the string.
12476 This works the same as @code{(rxmatch @var{regexp} @var{string})},
12477 but allows shorter notation. @xref{Applicable objects}, for
12478 generic mechanism used to implement this.
12479 @c JP
12480 正規表現オブジェクトは直接文字列に対して適用することもできます。
12481 これは@code{(rxmatch @var{regexp} @var{string})}と同じ動作をしますが、
12482 表記が短くて済みます。この機能は@ref{Applicable objects} で述べているメカニズムを
12483 使って実装されています。
12484 @c COMMON
12485 @end deffn
12486
12487 @c EN
12488 @subsubheading Accessing the match result
12489 @c JP
12490 @subsubheading マッチの結果を取り出す
12491 @c COMMON
12492
12493 @defun rxmatch-start match :optional (i 0)
12494 @defunx rxmatch-end match :optional (i 0)
12495 @defunx rxmatch-substring match :optional (i 0)
12496 @c EN
12497 @var{Match} is a match object returned by @code{rxmatch}.
12498 If @var{i} equals to zero, the functions return
12499 start, end or the substring of entire match, respectively.
12500 With positive integer @var{I}, it returns those of @var{I}-th
12501 submatches. It is an error to pass other values to @var{I}.
12502 @c JP
12503 @code{rxmatch}が返すマッチオブジェクト@var{match}から情報を取り出します。
12504 @var{i}が省略されるか0の場合、これらの手続きはそれぞれ一致した
12505 文字列の開始インデックス、終了インデックス、および一致した部分文字列を
12506 返します。@var{i}に正の整数が与えられた場合は、@var{i}番目のサブマッチ
12507 に関する情報を返します。@var{i}にシンボルが与えられた場合は、名前
12508 @var{i}を持つサブマッチの情報を返します。同じ名前@var{i}を持つ複数の
12509 サブマッチがある場合には、成功したサブマッチの情報を返します。
12510 @var{i}にそれ以外の値を与えるのはエラーです。
12511 @c COMMON
12512
12513 @c EN
12514 It is allowed to pass @code{#f} to @var{match} for convenience.
12515 The functions return @code{#f} in such case.
12516 @c JP
12517 簡便のために、@var{match}に@code{#f}を渡すことも許されています。
12518 その場合、これらの手続きは@code{#f}を返します。
12519 @c COMMON
12520
12521 @c EN
12522 These functions correspond to scsh's @code{match:start}, @code{match:end}
12523 and @code{match:substring}.
12524 @c JP
12525 これらの手続きはScshで@code{match:start}、@code{match:end}、
12526 @code{match:substring}と呼ばれているものと等価です。
12527 @c COMMON
12528 @end defun
12529
12530 @defun rxmatch-after match :optional (i 0)
12531 @defunx rxmatch-before match :optional (i 0)
12532 @c EN
12533 Returns substring of the input string after or before @var{match}.
12534 If optional argument is given, the @var{i}-th submatch is used
12535 (0-th submatch is the entire match).
12536 @c JP
12537 マッチオブジェクト@var{match}の前および後の文字列を返します。
12538 正の整数が@var{i}に与えられた場合はi番目のサブマッチの前および後の
12539 文字列を返します。シンボルが与えられた場合は、その名前を持つ
12540 サブマッチの前後の文字列を返します。
12541 @c COMMON
12542
12543 @example
12544 (define match (rxmatch #/(\d+)\.(\d+)/ "pi=3.14..."))
12545
12546 (rxmatch-after match) @result{} "..."
12547 (rxmatch-after match 1) @result{} ".14..."
12548
12549 (rxmatch-before match) @result{} "pi="
12550 (rxmatch-before match 2) @result{} "pi=3."
12551 @end example
12552 @end defun
12553
12554 @defun rxmatch-substrings match :optional start end
12555 @defunx rxmatch-positions match :optional start end
12556 @c EN
12557 Retrieves multiple submatches (again, 0-th match is the entire match),
12558 in substrings and in a cons of start and end position, respectively.
12559 @c JP
12560 複数のサブマッチ (0番目のサブマッチはマッチ全体) を取り出す手続きです。
12561 それぞれ、部分文字列のリストと、開始位置と終了位置のコンスのリストが返されます。
12562 @c COMMON
12563
12564 @example
12565 (rxmatch-substrings (#/(\d+):(\d+):(\d+)/ "12:34:56"))
12566 @result{} ("12:34:56" "12" "34" "56")
12567
12568 (rxmatch-positions (#/(\d+):(\d+):(\d+)/ "12:34:56"))
12569 @result{} ((0 . 8) (0 . 2) (3 . 5) (6 . 8))
12570 @end example
12571
12572 @c EN
12573 For the convenience, you can pass @code{#f} to @var{match}; those
12574 procedures returns @code{()} in that case.
12575 @c JP
12576 簡便のために、@var{match}に@code{#f}を渡すことも許されています。
12577 その場合、これらの手続きは@code{()}を返します。
12578 @c COMMON
12579
12580 @c EN
12581 The optional @var{start} and @var{end} arguments specify the
12582 range of submatch index. If omitted, @var{start} defaults to 0 and
12583 @var{end} defaults to @code{(rxmatch-num-matches match)}.
12584 For example, if you don't need the whole match, you can give @code{1}
12585 to @var{start} as follows:
12586 @c JP
12587 省略可能な@var{start}と@var{end}引数は取り出すサブマッチのインデックスの
12588 範囲を指定します。省略された場合、@var{start}は0、
12589 @var{end}は@code{(rxmatch-num-matches match)}の値が使われます。
12590 例えばマッチ全体が不要なら、@var{start}に@code{1}を渡せば良いのです。
12591 @c COMMON
12592
12593 @example
12594 (rxmatch-substrings (#/(\d+):(\d+):(\d+)/ "12:34:56") 1)
12595 @result{} ("12" "34" "56")
12596 @end example
12597 @end defun
12598
12599
12600 @defun rxmatch->string regexp string :optional selector @dots{}
12601 @c EN
12602 A convenience procedure to match a string to the given regexp,
12603 then returns the matched substring, or @code{#f} if it doesn't match.
12604
12605 If no @var{selector} is given, it is the same as this:
12606 @c JP
12607 文字列に正規表現でマッチをかけ、マッチした文字列を得る、便利な関数です。
12608 マッチしなかった場合は@code{#f}が帰ります。
12609
12610 @var{selector}が与えられなかった場合、この手続きは次の式と同じです。
12611 @c COMMON
12612
12613 @example
12614 (rxmatch-substring (rxmatch @var{regexp} @var{string}))
12615 @end example
12616
12617 @c EN
12618 If an integer is given as a selector, it returns the substring
12619 of the numbered submatch.
12620 @c JP
12621 @var{selector}に整数が与えられた場合は、
12622 それで指定されるサブマッチの文字列が返されます。
12623 @c COMMON
12624
12625 @c EN
12626 If a symbol @code{after} or @code{before} is given, it returns
12627 the substring after or before the match. You can give these symbols
12628 and an integer to extract a substring before or after the numbered
12629 submatch.
12630 @c JP
12631 @var{selector}にはシンボル@code{after}か@code{before}を与えることも出来ます。
12632 その場合は、マッチした文字列の前や後の文字列が返されます。これらのシンボルの後に
12633 さらにサブマッチを指定する整数を与えることもできます。
12634 @c COMMON
12635
12636 @example
12637 gosh> (rxmatch->string #/\d+/ "foo314bar")
12638 "314"
12639 gosh> (rxmatch->string #/(\w+)@@([\w.]+)/ "foo@@example.com" 2)
12640 "example.com"
12641 gosh> (rxmatch->string #/(\w+)@@([\w.]+)/ "foo@@example.com" 'before 2)
12642 "foo@@"
12643 @end example
12644 @end defun
12645
12646 @deffn {Generic application} @var{regmatch} :optional @var{index}
12647 @deffnx {Generic application} @var{regmatch} @code{'before} :optional @var{index}
12648 @deffnx {Generic application} @var{regmatch} @code{'after} :optional @var{index}
12649 @c EN
12650 A regmatch object can be applied directly to the integer index,
12651 or a symbol @code{before} or @code{after}.
12652 They works the same as @code{(rxmatch-substring @var{regmatch} @var{index})},
12653 @code{(rxmatch-before @var{regmatch})}, and
12654 @code{(rxmatch-after @var{regmatch})}, respectively.
12655 This allows shorter notation. @xref{Applicable objects}, for
12656 generic mechanism used to implement this.
12657 @c JP
12658 マッチオブジェクトは直接整数のインデックスもしくはシンボルに対して適用することが
12659 できます。整数に適用したときは@code{(rxmatch-substring @var{regmatch} @var{index})}、
12660 シンボル@code{before}のときは@code{(rxmatch-before @var{regmatch})}、シンボル
12661 @code{after}のときは@code{(rxmatch-after @var{regmatch})}、そのほかのシンボルのときは
12662 @code{(rxmatch-substring @var{regmatch} @var{symbol})}と同じ動作をします。
12663
12664 表記が短くて済みます。
12665 この機能は@ref{Applicable objects} で述べているメカニズムを使って実装されています。
12666 @c COMMON
12667
12668 @example
12669 (define match (#/(\d+)\.(\d+)/ "pi=3.14..."))
12670
12671 (match) @result{} "3.14"
12672 (match 1) @result{} "3"
12673 (match 2) @result{} "14"
12674
12675 (match 'after) @result{} "..."
12676 (match 'after 1) @result{} ".14..."
12677
12678 (match 'before) @result{} "pi="
12679 (match 'before 2) @result{} "pi=3."
12680
12681 (define match (#/(?<integer>\d+)\.(?<fraction>\d+)/ "pi=3.14..."))
12682
12683 (match 1) @result{} "3"
12684 (match 2) @result{} "14"
12685
12686 (match 'integer) @result{} "3"
12687 (match 'fraction) @result{} "14"
12688
12689 (match 'after 'integer) @result{} ".14..."
12690 (match 'before 'fraction) @result{} "pi=3."
12691 @end example
12692 @end deffn
12693
12694 @defun rxmatch-num-matches match
12695 @defunx rxmatch-named-groups match
12696 @c EN
12697 Returns the number of matches, and an alist of named groups and whose
12698 indices, in @var{match}.
12699 This corresponds @code{regexp-num-groups} and @code{regexp-named-groups}
12700 on a regular expression that has been used to generate @var{match}.
12701 These procedures are useful to inspect @var{match} object without having
12702 the original regexp object.
12703
12704 The number of matches includes the "whole match", so it is always a positive
12705 integer for a @code{<regmatch>} object. The number also includes
12706 the submatches that don't have value (see the examples below).
12707 The result of @code{rxmatch-named-matches} also includes all the
12708 named groups in the original regexp, not only the matched ones.
12709
12710 For the convenience, @code{rxmatch-num-matches} returns 0
12711 and @code{rxmatch-named-groups} returns @code{()}
12712 if @var{match} is @code{#f}.
12713 @c JP
12714 それぞれ、@var{match}の持つマッチの数、
12715 および名前つきグループの名前とインデックスのalistを返します。
12716 これらは、@var{match}を返した正規表現オブジェクトに対する
12717 @code{regexp-num-groups}と@code{regexp-named-groups}手続きに対応します。
12718 元の正規表現オブジェクトなしに、@var{match}の中身を調べたい時に便利です。
12719
12720 返されるマッチの数には「マッチ全体」も含まれます。
12721 つまり、@code{<regmatch>}オブジェクトに対しては常に正の整数が返ることになります。
12722 値を持たないマッチもカウントされます(下の例を参照)。
12723 @code{rxmatch-named-matches}が返すalistについても、元の正規表現の持つ
12724 名前つきグループの情報がマッチの有無によらず返されます。
12725
12726 簡便のために、@var{match}に@code{#f}を渡すこともできます。
12727 その場合、@code{rxmatch-num-matches}は0を、
12728 @code{rxmatch-named-groups}は@code{()}を返します。
12729 @c COMMON
12730
12731 @example
12732 (rxmatch-num-matches (rxmatch #/abc/ "abc")) @result{} 1
12733 (rxmatch-num-matches (rxmatch #/(a(.))|(b(.))/ "ba")) @result{} 5
12734 (rxmatch-num-matches #f) @result{} 0
12735
12736 (rxmatch-named-groups
12737 (rxmatch #/(?<h>\d\d):(?<m>\d\d)(:(?<s>\d\d))?/ "12:34"))
12738 @result{} ((s . 4) (m . 2) (h . 1))
12739 @end example
12740 @end defun
12741
12742 @c EN
12743 @subsubheading Convenience utilities
12744 @c JP
12745 @subsubheading 便利なユーティリティ
12746 @c COMMON
12747
12748 @defun regexp-replace regexp string substitution
12749 @defunx regexp-replace-all regexp string substitution
12750 @c EN
12751 Replaces the part of @var{string} that matched to @var{regexp}
12752 for @var{substitution}. @code{regexp-replace} just replaces
12753 the first match of @var{regexp}, while @code{regexp-replace-all}
12754 repeats the replacing throughout entire @var{string}.
12755 @c JP
12756 @var{string}中で@code{regexp}にマッチした部分を@var{substitution}で
12757 置き換えます。@code{regexp-replace}は最初にマッチした部分のみを置き換え、
12758 @code{regexp-replace-all}は全てのマッチを置き換えます。
12759 @c COMMON
12760
12761 @c EN
12762 @var{substitution} may be a string or a procedure. If it is a string,
12763 it can contain references to the submatches by
12764 digits preceded by a backslash (e.g. @code{\2})
12765 or the named submatch reference (e.g. @code{\k<@var{name}>}.
12766 @code{\0} refers to the
12767 entire match. Note that you need two backslashes to include
12768 backslash character in the literal string; if you want to include a backslash
12769 character itself in the @var{substitution}, you need four backslashes.
12770 @c JP
12771 @var{substitution}は文字列か手続きです。
12772 文字列の場合、バックスラッシュに続く数値、もしくは
12773 @code{\k<@var{name}>}という形式でサブマッチ文字列を参照できます
12774 @code{\0}はマッチ文字列全体を参照します。文字列リテラルにバックスラッシュを
12775 埋め込む場合は二つのバックスラッシュが必要であることに注意して下さい。
12776 バックスラッシュそのものを@var{substitution}中で使いたい場合は
12777 二つのバックスラッシュを重ねます; 文字列リテラルの場合は4つのバックスラッシュが
12778 必要になります。
12779 @c COMMON
12780
12781 @example
12782 (regexp-replace #/def|DEF/ "abcdefghi" "...")
12783 @result{} "abc...ghi"
12784 (regexp-replace #/def|DEF/ "abcdefghi" "|\\0|")
12785 @result{} "abc|def|ghi"
12786 (regexp-replace #/def|DEF/ "abcdefghi" "|\\\\0|")
12787 @result{} "abc|\\0|ghi"
12788 (regexp-replace #/c(.*)g/ "abcdefghi" "|\\1|")
12789 @result{} "ab|def|hi"
12790 (regexp-replace #/c(?<match>.*)g/ "abcdefghi" "|\\k<match>|")
12791 @result{} "ab|def|hi"
12792 @end example
12793
12794 @c EN
12795 If @var{substitution} is a procedure, for every match in @var{string}
12796 it is called with one argument, regexp-match object. The returned
12797 value from the procedure is inserted to the output string using
12798 @code{display}.
12799 @c JP
12800 @var{substitution}が手続きである場合、@var{string}中の各マッチについて、
12801 マッチオブジェクトを引数としてその手続きが呼ばれます。その手続きが返す
12802 値を@code{display}で表現したものが置換文字列として使われます。
12803 @c COMMON
12804
12805 @example
12806 (regexp-replace #/c(.*)g/ "abcdefghi"
12807 (lambda (m)
12808 (list->string
12809 (reverse
12810 (string->list (rxmatch-substring m 1))))))
12811 @result{} "abfedhi"
12812 @end example
12813
12814 @c EN
12815 Note: @code{regexp-replace-all} applies itself recursively to the remaining
12816 of the string after match. So the beginning of string assertion
12817 in @var{regexp} doesn't only mean the beginning of input string.
12818 @c JP
12819 註: @code{regexp-replace-all} は文字列でマッチした部分の後ろの部分に
12820 ついて再帰的に自分自身を適用します。従って、@var{regexp}が
12821 文字列先頭のアサーション (@code{^}) を含んでいても、それは@var{string}の
12822 先頭だけにマッチするとは限りません。
12823 @c COMMON
12824
12825 @c EN
12826 Note: If you want to operate on multiple matches in the string
12827 instead of replacing it, you can use @code{lrxmatch} in @code{gauche.lazy}
12828 module or @code{grxmatch} in @code{gauche.generator} module. Both can
12829 match a regexp @emph{repeatedly} and @emph{lazily} to the given string,
12830 and @code{lrxmatch}
12831 returns a lazy sequence of @code{regmatch}es, while @code{grxmatch}
12832 returns a generator that yields @code{regmatch}es.
12833 @c JP
12834 註: 文字列中の、正規表現にマッチする部分すべてに対して何か操作をしたいが、
12835 置き換えた文字列が欲しいわけではない、という場合は、
12836 @code{gauche.lazy}モジュールの@code{lrxmatch}や、
12837 @code{gauche.generator}モジュールの@code{grxmatch}が使えるでしょう。
12838 これらは文字列に対して繰り返し正規表現でのマッチを、必要に応じて適用し、
12839 前者はマッチオブジェクトの遅延シーケンスを、後者はマッチオブジェクトを生成する
12840 ジェネレータを返します。
12841 @c COMMON
12842
12843 @example
12844 (map rxmatch-substring (lrxmatch #/\w+/ "a quick brown fox!?"))
12845 @result{} ("a" "quick" "brown" "fox")
12846 @end example
12847 @end defun
12848
12849 @defun regexp-replace* string rx1 sub1 rx2 sub2 @dots{}
12850 @defunx regexp-replace-all* string rx1 sub1 rx2 sub2 @dots{}
12851 @c EN
12852 First applies @code{regexp-replace} or @code{regexp-replace-all} to
12853 @var{string} with a regular expression @var{rx1} substituting for
12854 @var{sub1}, then applies the function on the result string
12855 with a regular expression @var{rx2} substituting for @var{sub2}, and
12856 so on. These functions are handy when you want to apply
12857 multiple substitutions sequentially on a string.
12858 @c JP
12859 まず、@code{regexp-replace} あるいは @code{regexp-replace-all} を
12860 正規表現 @var{rx1}、置換 @var{sub1} で @var{string} に適用し、
12861 その結果にさらに @code{regexp-replace} あるいは
12862 @code{regexp-replace-all} を正規表現 @var{rx2}、置換 @var{sub2} で
12863 適用し、以下同様です。これらの関数はひとつの文字列上で複数回置換を行う
12864 ときに便利です。
12865 @c COMMON
12866 @end defun
12867
12868 @defun regexp-quote string
12869 @c EN
12870 Returns a string with the characters that are special to regexp escaped.
12871 @c JP
12872 @var{string}中で、正規表現において特別な意味を持つ文字を全てエスケープした
12873 文字列を返します。
12874 @c COMMON
12875
12876 @example
12877 (regexp-quote "[2002/10/12] touched foo.h and *.c")
12878 @result{} "\\[2002/10/12\\] touched foo\\.h and \\*\\.c"
12879 @end example
12880 @end defun
12881
12882
12883 @c EN
12884 In the following macros, @var{match-expr} is an expression
12885 which produces a match object or @code{#f}. Typically
12886 it is a call of @code{rxmatch}, but it can be any expression.
12887 @c JP
12888 以下のマクロにおいて、@var{match-expr}はマッチオブジェクトか
12889 @code{#f}を生成する式でなければなりません。通常それは
12890 @code{rxmatch}を呼ぶ式になりますが、それだけに限られるわけではありません。
12891 @c COMMON
12892
12893 @defmac rxmatch-let match-expr (var @dots{}) form @dots{}
12894
12895 @c EN
12896 Evaluates @var{match-expr}, and if matched, binds @var{var @dots{}}
12897 to the matched strings, then evaluates @var{form}s.
12898 The first @var{var} receives the entire match, and subsequent
12899 variables receive submatches. If the number of submatches are
12900 smaller than the number of variables to receive them, the rest
12901 of variables will get @code{#f}.
12902 @c JP
12903 @var{match-expr}を評価し、それがマッチオブジェクトを返したら、
12904 マッチした文字列を@var{var @dots{}}に束縛し、@var{form}を評価します。
12905 最初の@var{var}はマッチした文字列全体に束縛され、
12906 以降の変数はサブマッチ文字列に束縛されます。実際のサブマッチ文字列が
12907 与えられた変数より少なかった場合は、余った変数は@code{#f}に束縛されます。
12908 @c COMMON
12909
12910 @c EN
12911 It is possible to put @code{#f} in variable position, which says
12912 you don't care that match.
12913 @c JP
12914 特定のマッチ文字列を受け取る必要が無いときは、その場所の
12915 変数の変わりに@code{#f}を置いておくこともできます。
12916 @c COMMON
12917
12918 @example
12919 (rxmatch-let (rxmatch #/(\d+):(\d+):(\d+)/
12920 "Jan 1 23:59:58, 2001")
12921 (time hh mm ss)
12922 (list time hh mm ss))
12923 @result{} ("23:59:58" "23" "59" "58")
12924
12925 (rxmatch-let (rxmatch #/(\d+):(\d+):(\d+)/
12926 "Jan 1 23:59:58, 2001")
12927 (#f hh mm)
12928 (list hh mm))
12929 @result{} ("23" "59")
12930 @end example
12931
12932 @c EN
12933 This macro corresponds to scsh's @code{let-match}.
12934 @c JP
12935 このマクロはscshの@code{let-match}に相当します。
12936 @c COMMON
12937 @end defmac
12938
12939 @defmac rxmatch-if match-expr (var @dots{}) then-form else-form
12940 @c EN
12941 Evaluates @var{match-expr}, and if matched, binds @var{var} @dots{}
12942 to the matched strings and evaluate @var{then-form}.
12943 Otherwise evaluates @var{else-form}.
12944 The rule of binding @var{var}s is the same as @code{rxmatch-let}.
12945 @c JP
12946 @var{match-expr}を評価し、それがマッチオブジェクトを返したら
12947 マッチした文字列を変数@var{var} @dots{}に束縛して@var{then-form}を
12948 評価します。マッチオブジェクトが返されなければ束縛は行われず、
12949 @var{else-form}が評価されます。変数@var{var}をマッチ文字列に
12950 束縛するルールは@code{rxmatch-let}と同じです。
12951 @c COMMON
12952
12953 @example
12954 (rxmatch-if (rxmatch #/(\d+:\d+)/ "Jan 1 11:22:33")
12955 (time)
12956 (format #f "time is ~a" time)
12957 "unknown time")
12958 @result{} "time is 11:22"
12959
12960 (rxmatch-if (rxmatch #/(\d+:\d+)/ "Jan 1 11-22-33")
12961 (time)
12962 (format #f "time is ~a" time)
12963 "unknown time")
12964 @result{} "unknown time"
12965 @end example
12966
12967 @c EN
12968 This macro corresponds to scsh's @code{if-match}.
12969 @c JP
12970 このマクロはscshの@code{if-match}に相当します。
12971 @c COMMON
12972 @end defmac
12973
12974 @defmac rxmatch-cond clause @dots{}
12975 @c EN
12976 Evaluate condition in @var{clause}s one by one.
12977 If a condition of a clause satisfies, rest portion of the clause
12978 is evaluated and becomes the result of @code{rxmatch-cond}.
12979 @var{Clause} may be one of the following pattern.
12980 @c JP
12981 @var{clause}の条件を順に評価してゆき、条件を満たすものが現れたら
12982 その@var{clause}の残りのフォームを評価し、最後のフォームの値を
12983 @code{rxmatch-cond}の値とします。@var{clause}は以下のいずれかの
12984 形式でなければなりません。
12985 @c COMMON
12986
12987 @table @code
12988 @item (@var{match-expr} (@var{var} @dots{}) @var{form} @dots{})
12989 @c EN
12990 Evaluate @var{match-expr}, which may return a regexp match
12991 object or @code{#f}. If it returns a match object, the matches
12992 are bound to @var{var}s, like @var{rxmatch-let}, and @var{form}s
12993 are evaluated.
12994 @c JP
12995 @var{match-expr}を評価し、それがマッチオブジェクトを返した場合は
12996 マッチ文字列を変数@var{var} @dots{}に束縛した上で
12997 @var{form} @dots{}を評価します。
12998 @c COMMON
12999
13000 @item (test @var{expr} @var{form} @dots{})
13001 @c EN
13002 Evaluates @var{expr}. If it yields true, evaluates @var{form}s.
13003 @c JP
13004 @var{expr}を評価し、それが真の値を返した場合は@var{form} @dots{}を評価します。
13005 @c COMMON
13006
13007 @item (test @var{expr} => @var{proc})
13008 @c EN
13009 Evaluates @var{expr} and if it is true,
13010 calls @var{proc} with the result of @var{expr} as the only argument.
13011 @c JP
13012 @var{expr}を評価し、それが真の値を返した場合は
13013 それを唯一の引数として手続き@var{proc}を呼びます。
13014 @c COMMON
13015
13016 @item (else @var{form} @dots{})
13017 @c EN
13018 If this clause exists, it must be the last clause.
13019 If other clauses fail, @var{form}s are evaluated.
13020 @c JP
13021 この@var{clause}は、もし与えられたとすれば最後の@var{clause}でなければ
13022 なりません。全ての@var{clause}が失敗した場合に、@var{form} @dots{}が
13023 評価されます。
13024 @c COMMON
13025 @end table
13026
13027 @c EN
13028 If no @code{else} clause exists, and all the other clause fail,
13029 an undefined value is returned.
13030 @c JP
13031 @code{else} @var{clause}が与えられず、かつ全ての@var{clause}が
13032 失敗した場合の戻り値は未定義です。
13033 @c COMMON
13034
13035 @example
13036 @c EN
13037 ;; @r{parses several possible date format}
13038 @c JP
13039 ;; @r{何通りかの日付のフォーマットをパーズする}
13040 @c COMMON
13041 (define (parse-date str)
13042 (rxmatch-cond
13043 ((rxmatch #/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/ str)
13044 (#f mm dd yyyy)
13045 (map string->number (list yyyy mm dd)))
13046 ((rxmatch #/^(\d\d\d\d)\/(\d\d?)\/(\d\d?)$/ str)
13047 (#f yyyy mm dd)
13048 (map string->number (list yyyy mm dd)))
13049 ((rxmatch #/^\d+\/\d+\/\d+$/ str)
13050 (#f)
13051 (errorf "ambiguous: ~s" str))
13052 (else (errorf "bogus: ~s" str))))
13053
13054 (parse-date "2001/2/3") @result{} (2001 2 3)
13055 (parse-date "12/25/1999") @result{} (1999 12 25)
13056 @end example
13057
13058 @c EN
13059 This macro corresponds to scsh's @code{match-cond}.
13060 @c JP
13061 このマクロはscshの@code{match-cond}に相当します。
13062 @c COMMON
13063 @end defmac
13064
13065 @defmac rxmatch-case string-expr clause @dots{}
13066 @c EN
13067 @var{String-expr} is evaluated, and @var{clause}s are interpreted
13068 one by one. A @var{clause} may be one of the following pattern.
13069 @c JP
13070 @var{string-expr}がまず評価され、続いて@var{clause}が順に検査されます。
13071 @var{clause}は以下のいずれかの形式でなければなりません。
13072 @c COMMON
13073
13074 @table @code
13075 @item (@var{re} (@var{var} @dots{}) @var{form} @dots{})
13076 @c EN
13077 @var{Re} must be a literal regexp object (@pxref{Regular expressions}).
13078 If the result of @var{string-expr} matches @var{re},
13079 the match result is bound to @var{var}s
13080 and @var{form}s are evaluated, and @code{rxmatch-case} returns
13081 the result of the last @var{form}.
13082 @c JP
13083 @var{re}はリテラル正規表現オブジェクトでなければなりません
13084 (@ref{Regular expressions}参照)。@var{string-expr}の結果が文字列であり
13085 @var{re}にマッチした場合は、マッチ文字列が変数@var{var} @dots{}に
13086 束縛され、@var{form}が評価されます。最後の@var{form}の値が@code{rxmatch-case}
13087 の値となります。
13088 @c COMMON
13089
13090 @c EN
13091 If @var{re} doesn't match the result of @var{string-expr},
13092 @var{string-expr} yields non-string value, the interpretation proceeds
13093 to the next clause.
13094 @c JP
13095 @var{string-expr}の結果の文字列が@var{re}にマッチしないか、
13096 @var{string-expr}の結果が文字列以外であった場合は次の@var{clause}へと
13097 処理が進みます。
13098 @c COMMON
13099
13100 @item (test @var{proc} @var{form} @dots{})
13101 @c EN
13102 A procedure @var{proc} is applied on the result of @var{string-expr}.
13103 If it yields true value, @var{form}s are evaluated, and
13104 @code{rxmatch-case} returns the result of the last @var{form}.
13105 @c JP
13106 手続き@var{proc}が@var{string-expr}の結果を引数として呼ばれます。
13107 それが真の値を返した場合は@var{form}が順に評価され、最後の@var{form}の
13108 値が@code{rxmatch-case}の値として返されます。
13109 @c COMMON
13110
13111 @c EN
13112 If @var{proc} yields @code{#f}, the interpretation proceeds
13113 to the next clause.
13114 @c JP
13115 @var{proc}が@code{#f}を返した場合は次の@var{clause}へと
13116 処理が進みます。
13117 @c COMMON
13118
13119 @item (test @var{proc} => @var{proc2})
13120 @c EN
13121 A procedure @var{proc} is applied on the result of @var{string-expr}.
13122 If it yields true value, @var{proc2} is applied on the result,
13123 and its result is returned as the result of @code{rxmatch-case}.
13124 @c JP
13125 手続き@var{proc}が@var{string-expr}の結果を引数として呼ばれます。
13126 それが真の値を返した場合は、その値を引数として@var{proc2}が呼ばれ、
13127 その返り値が@code{rxmatch-case}の値として返されます。
13128 @c COMMON
13129
13130 @c EN
13131 If @var{proc} yields @code{#f}, the interpretation proceeds
13132 to the next clause.
13133 @c JP
13134 @var{proc}が@code{#f}を返した場合は次の@var{clause}へと
13135 処理が進みます。
13136 @c COMMON
13137
13138 @item (else @var{form} @dots{})
13139 @c EN
13140 This form must appear at the end of @var{clause}s, if any.
13141 If other clauses fail, @var{form}s are evaluated,
13142 and the result of the last @var{form} becomes the result of
13143 @code{rxmatch-case}.
13144 @c JP
13145 このフォームは、与えられる場合は最後の@var{clause}でなければなりません。
13146 他の全ての@var{clause}が失敗した場合に、@var{form}が順に評価され、最後の@var{form}の
13147 値が@code{rxmatch-case}の値として返されます。
13148 @c COMMON
13149
13150 @item (else => @var{proc})
13151 @c EN
13152 This form must appear at the end of @var{clause}s, if any.
13153 If other clauses fail, @var{proc} is evaluated, which should
13154 yield a procedure taking one argument. The value of @var{string-expr}
13155 is passed to @var{proc}, and its return values become the
13156 return values of @code{rxmatch-case}.
13157 @code{rx}
13158 @c JP
13159 このフォームは、与えられる場合は最後の@var{clause}でなければなりません。
13160 他の全ての@var{clause}が失敗した場合に、@var{proc}が評価されます。
13161 その値は一引数の手続きにならなければなりません。
13162 その手続きが、@var{string-expr}の値を引数として呼ばれます。
13163 @var{proc}の結果が@code{rxmatch-case}の値となります。
13164 @c COMMON
13165 @end table
13166
13167 @c EN
13168 If no @code{else} clause exists, and all other clause fail,
13169 an undefined value is returned.
13170 @c JP
13171 @code{else} @var{clause}が与えられず、かつ全ての@var{clause}が
13172 失敗した場合の戻り値は未定義です。
13173 @c COMMON
13174
13175 @c EN
13176 The @code{parse-date} example above becomes simpler if you use
13177 @code{rxmatch-case}
13178 @c JP
13179 上の@code{parse-date}の例は@code{rxmatch-case}を使うとより単純になります。
13180 @c COMMON
13181
13182 @example
13183 (define (parse-date2 str)
13184 (rxmatch-case str
13185 (test (lambda (s) (not (string? s))) #f)
13186 (#/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/ (#f mm dd yyyy)
13187 (map string->number (list yyyy mm dd)))
13188 (#/^(\d\d\d\d)\/(\d\d?)\/(\d\d?)$/ (#f yyyy mm dd)
13189 (map string->number (list yyyy mm dd)))
13190 (#/^\d+\/\d+\/\d+$/ (#f)
13191 (errorf "ambiguous: ~s" str))
13192 (else (errorf "bogus: ~s" str))))
13193 @end example
13194 @end defmac
13195
13196 @node Inspecting and assembling regular expressions, , Using regular expressions, Regular expressions
13197 @subsection Inspecting and assembling regular expressions
13198 @c NODE 正規表現の調査と合成
13199
13200 @c EN
13201 When Gauche reads a string representation of regexp, first it parses
13202 the string and construct an abstract
13203 syntax tree (AST), performs some optimizations on it,
13204 then compiles it into an instruction sequence to be
13205 executed by the regexp engine.
13206 @c JP
13207 Gaucheはregexpの文字列表記を読むと、その文字列をパーズして
13208 抽象構文木 (AST) を作り、それにいくらかの最適化を施したのち、
13209 正規表現エンジンで実行されるインストラクション列へとコンパイルします。
13210 @c COMMON
13211
13212 @c EN
13213 The following procedures expose this process to
13214 user programs. It may be easier for programs to
13215 manipulate an AST than a string representation.
13216 @c JP
13217 以下の手続きはこのプロセスをユーザプログラムに見せるものです。
13218 プログラム的に正規表現をいじる場合は、文字列形式よりも
13219 ASTの方が扱いやすいでしょう。
13220 @c COMMON
13221
13222 @defun regexp-parse string :key case-fold multi-line
13223 @c EN
13224 Parses a string specification of regexp in @var{string}
13225 and returns its AST, represented in S-expression.
13226 See below for the spec of AST.
13227 @c JP
13228 正規表現の文字列表記である@var{string}をパーズし、S式で表現された
13229 ASTを返します。ASTの仕様は下で述べます。
13230 @c COMMON
13231
13232 @c EN
13233 When a true value is given to the keyword argument @var{case-fold},
13234 returned AST will match case-insensitively.
13235 (Case insensitive regexp is handled in parser level,
13236 not by the engine).
13237 @c JP
13238 @var{case-fold}キーワード引数に真の値が与えられた場合は、
13239 大文字小文字を区別せずにマッチを行うASTが変えされます
13240 (エンジン自体に「大文字小文字を区別しない」モードがあるわけではなく、
13241 パーザの段階で異なるASTが生成されます。)
13242 @c COMMON
13243 @end defun
13244
13245 @defun regexp-parse-sre sre
13246 @c EN
13247 Parses @var{sre} as a Scheme Regular Expression (SRE) as described in
13248 SRFI-115 and returns its AST.
13249 @xref{R7RS regular expressions}
13250 @c JP
13251 @var{sre}をSRFI-115で定義されるScheme正規表現(SRE)としてパーズし、
13252 結果をASTで返します。
13253 SREについて詳しくは@ref{R7RS regular expressions}を参照してください。
13254 @c COMMON
13255 @pxref{R7RS regular expressions}.
13256 @end defun
13257
13258 @defun regexp-optimize ast
13259 @c EN
13260 Performs some rudimental optimization on the regexp AST,
13261 returning regexp AST.
13262
13263 Currently it only optimizes some trivial cases. The plan is
13264 to make it cleverer in future.
13265 @c JP
13266 正規表現のASTに対して、いくつかの原始的な最適化を施して結果のASTを返します。
13267
13268 現在のところ、最適化はごく簡単なものです。将来はもっと賢くする予定です。
13269 @c COMMON
13270 @end defun
13271
13272 @defun regexp-compile ast :key multi-line
13273 @c EN
13274 Takes a regexp @var{ast} and returns a regexp object.
13275 Currently the outermost form of @var{ast} must be
13276 the zero-th capturing group. (That is, @var{ast}
13277 should have the form @code{(0 #f @var{x} @dots{})}.)
13278 The outer grouping is always added
13279 by @code{regexp-parse} to capture the entire regexp.
13280 @c JP
13281 正規表現のASTを受け取り、マッチに使える正規表現オブジェクトを返します。
13282 渡されるASTの一番外側は、0番めの捕捉グループでなければなりません
13283 (@var{ast}は@code{(0 #f @var{x} @dots{})}という形でなければ
13284 ならない、ということです)。@code{regexp-parse}は常にこの捕捉グループを
13285 追加します。正規表現にマッチした全体の文字列を捕捉するためです。
13286 @c COMMON
13287
13288 @c EN
13289 Note: The function does some basic check to see the given AST
13290 is valid, but it may not reject invalid ASTs. In such case,
13291 the returned regexp object doesn't work properly. It is
13292 caller's responsibility to provide a properly constructed AST.
13293 (Even if it rejects an AST, error messages are often
13294 incomprehensible. So, don't use this procedure as a AST validness checker.)
13295 @c JP
13296 註:この関数は渡されたASTが有効なものであるかどうかについて
13297 簡単なチェックを行いますが、有効でないASTを受け入れてしまうかもしれません。
13298 その場合、変えされる正規表現オブジェクトの動作は不定です。
13299 正しい形式のASTを渡すのは呼出側の責任です
13300 (この関数が有効でないASTを見つけてエラーにする場合でも、
13301 そのエラーメッセージからどこがおかしいかを判断するのが難しい場合があります。
13302 この手続きをASTが有効であるかどうかのチェッカーとして使うのは避けましょう。)
13303 @c COMMON
13304 @end defun
13305
13306 @defun regexp-ast regexp
13307 @c EN
13308 Returns AST used for the regexp object @var{regexp}.
13309 @c JP
13310 正規表現オブジェクト@var{regexp}が使っているASTを返します。
13311 @c COMMON
13312 @end defun
13313
13314 @defun regexp-unparse ast :key (on-error :error)
13315 @c EN
13316 From the regexp's @var{ast}, reconstruct the string representation
13317 of the regexp. The keyword argument @var{on-error} can be
13318 a keyword @code{:error} (default) or @code{#f}. If it's the former,
13319 an error is signaled when @var{ast} isn't valid regexp AST.
13320 If it's the latter, @code{regexp-unparse} just returns @code{#f}.
13321 @c JP
13322 正規表現の@var{ast}から、その正規表現の文字列表記を再構成して返します。
13323 キーワード引数@var{on-error}は、キーワード@code{:error} (デフォルト)
13324 もしくは@code{#f}です。それが@code{:error}の場合、@var{ast}が不正
13325 であればエラーが報告され、@code{#f}の場合は@code{regexp-unparse}から
13326 @code{#f}が返されます。
13327 @c COMMON
13328 @end defun
13329
13330 @c EN
13331 This is the structure of AST. Note that this is originally
13332 developed only for internal use, and not very convenient to manipulate
13333 from the code (e.g. if you insert or delete a subtree, you have to
13334 renumber capturing groups to make them consistent.)
13335 @c JP
13336 以下にASTの構造を示します。この仕様は当初、内部的に使うためだけに設計されたので、
13337 コードで直接いじるのには若干不便です (例えば、部分木を削除したり
13338 追加した場合、捕捉グループの番号を振りなおして一貫性を保つ必要があるかもしれません。)
13339 @c COMMON
13340
13341 @smallexample
13342 <ast> : <clause> ; special clause
13343 | <item> ; matches <item>
13344
13345 <item> : <char> ; matches char
13346 | <char-set> ; matches char set
13347 | (comp . <char-set>) ; matches complement of char set
13348 | any ; matches any char
13349 | bos | eos ; beginning/end of string assertion
13350 | bol | eol ; beginning/end of line assertion
13351 | bow | eow | wb | nwb ; word-boundary/negative word boundary assertion
13352 | bog | eog ; beginning/end of grapheme assertion
13353
13354 <clause> : (seq <ast> ...) ; sequence
13355 | (seq-uncase <ast> ...) ; sequence (case insensitive match)
13356 | (seq-case <ast> ...) ; sequence (case sensitive match)
13357 | (alt <ast> ...) ; alternative
13358 | (rep <m> <n> <ast> ...) ; repetition at least <m> up to <n> (greedy)
13359 ; <n> may be `#f'
13360 | (rep-min <m> <n> <ast> ...)
13361 ; repetition at least <m> up to <n> (lazy)
13362 ; <n> may be `#f'
13363 | (rep-while <m> <n> <ast> ...)
13364 ; like rep, but no backtrack
13365 | (<integer> <symbol> <ast> ...)
13366 ; capturing group. <symbol> may be #f.
13367 | (cpat <condition> (<ast> ...) (<ast> ...))
13368 ; conditional expression
13369 | (backref . <integer>) ; backreference by group number
13370 | (backref . <symbol>) ; backreference by name
13371 | (once <ast> ...) ; standalone pattern. no backtrack
13372 | (assert . <asst>) ; positive lookahead assertion
13373 | (nassert . <asst>) ; negative lookahead assertion
13374
13375 <condition> : <integer> ; (?(1)yes|no) style conditional expression
13376 | (assert . <asst>) ; (?(?=condition)...) or (?(?<=condition)...)
13377 | (nassert . <asst>) ; (?(?!condition)...) or (?(?<!condition)...)
13378
13379 <asst> : <ast> ...
13380 | ((lookbehind <ast> ...))
13381 @end smallexample
13382
13383 @c ----------------------------------------------------------------------
13384 @node Vector family, Dictionaries, Regular expressions, Core library
13385 @section Vector family
13386 @c NODE ベクタの仲間
13387
13388 @c EN
13389 Vectors are fixed-size, O(1) accessible sequence of values.
13390 Scheme has traditionally offered a vector of arbitrary objects, which is
13391 described in @ref{Vectors}.
13392
13393 In R7RS-large, there're also homogeneous numeric vectors (uvectors),
13394 which can contain fixed range of numeric objects efficiently.
13395 We explain them in @ref{Uniform vectors}.
13396
13397 Gauche also supports bitvectors, which can contain sequence of bits.
13398 @xref{Bitvectors}, for the details.
13399
13400 Finally, weak vectors are a vector of arbitrary objects using
13401 weak pointers. @xref{Weak vectors}.
13402 @c JP
13403 ベクタは固定長でO(1)アクセス可能な値の並びです。
13404 Schemeは伝統的に、任意の値を格納できるベクタを提供してきました。
13405 これは@ref{Vectors}で説明されます。
13406
13407 R7RS-largeでは、均質な数値型だけを効率よく格納できるベクタ(uvector)も定義されています。
13408 @ref{Uniform vectors}を見てください。
13409
13410 Gaucheはまた、ビット列を格納するビットベクタも提供します。
13411 @ref{Bitvectors}で説明します。
13412
13413 最後に、weakベクタは任意の要素をweakポインタを使って格納できるベクタです。
13414 @ref{Weak vectors}参照。
13415 @c COMMON
13416
13417 @menu
13418 * Vectors::
13419 * Uniform vectors::
13420 * Bitvectors::
13421 * Weak vectors::
13422 @end menu
13423
13424 @node Vectors, Uniform vectors, Vector family, Vector family
13425 @subsection Vectors
13426 @c NODE ベクタ
13427
13428 @deftp {Builtin Class} <vector>
13429 @clindex vector
13430 @c EN
13431 A vector is a simple 1-dimensional array of Scheme objects.
13432 You can access its element by index in constant time.
13433 Once created, a vector can't be resized.
13434
13435 Class @code{<vector>} inherits @code{<sequence>} and
13436 you can use various generic functions such as @code{map} and @code{fold}
13437 on it. @xref{Collection framework}, and @xref{Sequence framework}.
13438
13439 If you keep only a homogeneous numeric type, you may be able
13440 to use uniform vectors (@pxref{Uniform vectors}).
13441
13442 R7RS defines bytevectors; in Gauche, they're just @code{u8vector}s
13443 in @code{gauche.uvector} module (r7rs modules defines aliases.
13444 @pxref{R7RS base library}).
13445
13446 @xref{R7RS vectors}, for additional operations on vectors.
13447 @c JP
13448 ベクタはSchemeオブジェクトの単純な一次元配列です。
13449 インデックスを用いて定数時間でその要素にアクセスできます。
13450 一度作成されたベクタはその大きさを変えることはできません。
13451
13452 @code{<vector>}クラスはまた@code{<sequence>}クラスを継承し、
13453 @code{map}や@code{fold}など様々な総称関数を使うことができます。
13454 @ref{Collection framework} と
13455 @ref{Sequence framework} を参照して下さい。
13456
13457 数値しか要素に持たないベクタを使う場合、
13458 ユニフォームベクタも使えるかもしれません (@ref{Uniform vectors}参照)。
13459
13460 R7RSはバイトベクタを定義しています。Gaucheではそれは単に
13461 @code{gauche.uvector}モジュールの@code{u8vector}です
13462 (R7RSモジュールは別名を定義しています。@ref{R7RS base library}参照。)
13463
13464 より多くのベクタに対する操作が@ref{R7RS vectors}で提供されています。
13465 @c COMMON
13466 @end deftp
13467
13468 @defun vector? obj
13469 [R7RS base]
13470 @c EN
13471 Returns @code{#t} if @var{obj} is a vector, @code{#f} otherwise.
13472 @c JP
13473 @var{obj}がベクタなら@code{#t}を、そうでなければ@code{#f}を返します。
13474 @c COMMON
13475 @end defun
13476
13477 @defun make-vector k :optional fill
13478 [R7RS base]
13479 @c EN
13480 Creates and returns a vector with length @var{k}.
13481 If optional argument @var{fill} is given, each element of the vector
13482 is initialized by it. Otherwise, the initial value of each element
13483 is undefined.
13484 @c JP
13485 長さ@var{k}のベクタを作成して返します。
13486 省略可能な引数@var{fill}が与えられていれば、ベクタの各要素はその値で
13487 初期化されます。そうでなければベクタの各要素の値は不定です。
13488 @c COMMON
13489 @end defun
13490
13491 @defun vector obj @dots{}
13492 [R7RS base]
13493 @c EN
13494 Creates a vector whose elements are @var{obj} @dots{}.
13495 @c JP
13496 要素が@var{obj} @dots{}であるようなベクタを作成して返します。
13497 @c COMMON
13498 @end defun
13499
13500 @defun vector-tabulate len proc
13501 @c EN
13502 Creates a vector of length @var{len},
13503 initializing @var{i}-th
13504 element of which by @code{(@var{proc} @var{i})}
13505 for all @var{i} between @code{0} and @var{len}
13506 @c JP
13507 長さ@var{len}のベクタを作成し、@code{0}以上@var{len}未満の@var{i}について
13508 @var{i}番目の要素を@code{(@var{proc} @var{i})}の値で初期化します。
13509 @c COMMON
13510
13511 @example
13512 (vector-tabulate 5 (^x (* x x)))
13513 @result{} #(0 1 4 9 16)
13514 @end example
13515 @end defun
13516
13517 @defun vector-length vector
13518 [R7RS base]
13519 @c EN
13520 Returns the length of a vector @var{vector}.
13521
13522 With @code{gauche.collection} module,
13523 you can also use a method @code{size-of}.
13524 @c JP
13525 ベクタ@var{vector}の長さを返します。
13526
13527 @code{gauche.collection}モジュールをロードしていれば、
13528 メソッド@code{size-of}も同じ目的で使えます。
13529 @c COMMON
13530 @end defun
13531
13532 @defun vector-ref vector k :optional fallback
13533 [R7RS+ base]
13534 @c EN
13535 Returns @var{k}-th element of vector @var{vector}.
13536
13537 By default, @code{vector-ref} signals an error if @var{k} is
13538 negative, or greater than or equal to the length of @var{vector}.
13539 However, if an optional argument @var{fallback} is given,
13540 it is returned for such case. This is an extension of Gauche.
13541
13542 With @code{gauche.sequence} module,
13543 you can also use a method @code{ref}.
13544 @c JP
13545 ベクタ@var{vector}の@var{k}番目の要素を返します。
13546
13547 @code{vector-ref}は@var{k}が負の値であったりベクタの長さより
13548 大きかったりした場合はエラーを通知します。但し、省略可能な引数@var{fallback}
13549 が与えられている場合はその値が返されます。これはGaucheの拡張です。
13550
13551 @code{gauche.sequence}モジュールをロードしていれば、
13552 メソッド@code{ref}も同じ目的で使えます。
13553 @c COMMON
13554 @end defun
13555
13556 @defun vector-set! vector k obj
13557 [R7RS base]
13558 @c EN
13559 Sets @var{k}-th element of the vector @var{vector} to @var{obj}.
13560 It is an error if @var{k} is negative or greater than or equal to the
13561 length of @var{vector}.
13562
13563 With @code{gauche.sequence} module, you can also use
13564 a setter method of @code{ref}.
13565 @c JP
13566 ベクタ@var{vector}の@var{k}番目の要素を@var{obj}に変更します。
13567 @var{k}が負数であったりベクタの長さより大きい場合はエラーとなります。
13568
13569 @code{gauche.sequence}モジュールをロードしていれば、
13570 メソッド@code{ref}のsetterメソッドも使えます。
13571 @c COMMON
13572 @end defun
13573
13574 @defun vector->list vector :optional start end
13575 @defunx list->vector list :optional start end
13576 [R7RS+ base]
13577 @c EN
13578 Converts a vector to a list, or vice versa.
13579
13580 The optional @var{start} and @var{end} arguments
13581 limit the range of the source.
13582 (R7RS don't define @var{start} and @var{end} arguments
13583 for @code{list->vector}.)
13584 @c JP
13585 ベクタをリストに変換したり、その逆を行う手続きです。
13586
13587 省略可能な引数@var{start}と@var{end}を与えることにより、
13588 値を取り出す範囲を制限することができます。
13589 (R7RSの@code{list->vector}は@var{start}と@var{end}引数を規定していません。)
13590 @c COMMON
13591 @example
13592 (vector->list '#(1 2 3 4 5)) @result{} (1 2 3 4 5)
13593 (list->vector '(1 2 3 4 5)) @result{} #(1 2 3 4 5)
13594 (vector->list '#(1 2 3 4 5) 2 4) @result{} (3 4)
13595 (list->vector (circular-list 'a 'b 'c) 1 6)
13596 @result{} #(b c a b c)
13597 @end example
13598
13599 @c EN
13600 With @var{gauche.collection} module, you can use
13601 @code{(coerce-to <list> @var{vector})} and
13602 @code{(coerce-to <vector> @var{list})} as well.
13603 @c JP
13604 @code{gauche.collection}モジュールをロードしていれば、
13605 @code{(coerce-to <list> @var{vector})} と
13606 @code{(coerce-to <vector> @var{list})} も同じ目的で使えます。
13607 @c COMMON
13608 @end defun
13609
13610 @defun reverse-list->vector list :optional start end
13611 [R7RS vector]
13612 @c EN
13613 Without optional arguments, it returns the same thing as
13614 @code{(list->vector (reverse list))}, but does not
13615 allocate the intermediate list. The optional @var{start} and
13616 @var{end} argument limits the range of the input list.
13617 @c JP
13618 省略可能引数が無い場合、
13619 @code{(list->vector (reverse list))}と同じ結果を返しますが、
13620 中間リストを作りません。省略可能引数@var{start}および@var{end}が
13621 与えられた場合は、それは@var{list}の範囲を指定します。
13622 @c COMMON
13623 @example
13624 (reverse-list->vector '(a b c d e f g) 1 5)
13625 @result{} #(e d c b)
13626 @end example
13627 @end defun
13628
13629 @defun vector->string vector :optional start end
13630 @defunx string->vector string :optional start end
13631 [R7RS base]
13632 @c EN
13633 Converts a vector of characters to a string, or vice versa.
13634 It is an error to pass a vector that contains other than characters
13635 to @code{vector->string}.
13636
13637 The optional @var{start} and @var{end} arguments
13638 limit the range of the source.
13639 @c JP
13640 文字のベクタを文字列に変換したり、その逆を行う手続きです。
13641 @code{vector->string}に、文字以外の要素を含むベクタを渡した場合はエラーになります。
13642
13643 省略可能な引数@var{start}と@var{end}を与えることにより、
13644 値を取り出す範囲を制限することができます。
13645
13646 @c COMMON
13647 @example
13648 (vector->string '#(#\a #\b #\c #\d #\e)) @result{} "abcde"
13649 (string->vector "abcde") @result{} #(#\a #\b #\c #\d #\e)
13650 (vector->string '#(#\a #\b #\c #\d #\e) 2 4) @result{} ("cd")
13651 @end example
13652
13653 @c EN
13654 With @var{gauche.collection} module, you can use
13655 @code{(coerce-to <string> @var{vector})} and
13656 @code{(coerce-to <vector> @var{string})} as well.
13657 @c JP
13658 @code{gauche.collection}モジュールをロードしていれば、
13659 @code{(coerce-to <string> @var{vector})} と
13660 @code{(coerce-to <vector> @var{string})} も同じ目的で使えます。
13661 @c COMMON
13662 @end defun
13663
13664 @defun vector-fill! vector fill :optional start end
13665 [R7RS base]
13666 @c EN
13667 Sets all elements in a vector @var{vector} to @var{fill}.
13668
13669 Optional @var{start} and @var{end} limits the range
13670 of effect between @var{start}-th index (inclusive) to
13671 @var{end}-th index (exclusive). @var{Start} defaults to
13672 zero, and @var{end} defaults to the length of @var{vector}.
13673 @c JP
13674 ベクタ@var{vector}の全ての要素を@var{fill}に変更します。
13675
13676 省略可能な引数@var{start}と@var{end}が与えられた場合、
13677 @var{start}番目の要素から@var{end}-1番目の要素までのみに
13678 @var{fill}を格納します。@var{start}と@var{end}の既定値は
13679 それぞれ0と@var{vector}の大きさです。
13680 @c COMMON
13681 @end defun
13682
13683 @defun vector-copy vector :optional start end fill
13684 [R7RS base]
13685 @c EN
13686 Copies a vector @var{vector}. Optional @var{start} and @var{end}
13687 arguments can be used to limit the range of @var{vector} to be copied.
13688 If the range specified by @var{start} and @var{end} falls outside of
13689 the original @var{vector}, the @var{fill} value is used to fill
13690 the result vector.
13691 @c JP
13692 ベクタ@var{vector}をコピーします。引数@var{start}と@var{end}を与えることで
13693 コピーされる範囲を制限することができます。
13694 @var{start}と@var{end}で指定される範囲が元の@var{vector}の範囲を越えた
13695 場合は、その部分が@var{fill}で埋められます。
13696 @c COMMON
13697
13698 @example
13699 (vector-copy '#(1 2 3 4 5)) @result{} #(1 2 3 4 5)
13700 (vector-copy '#(1 2 3 4 5) 2 4) @result{} #(3 4)
13701 (vector-copy '#(1 2 3 4 5) 3 7 #f) @result{} #(4 5 #f #f)
13702 @end example
13703 @end defun
13704
13705 @defun vector-copy! target tstart source :optional sstart send
13706 [R7RS base]
13707 @c EN
13708 Copies the content of @var{source} vector into the @var{target} vector
13709 starting from @var{tstart} in the target. The @var{target} vector
13710 must be mutable.
13711 Optional @var{sstart} and @var{send} limits the range of source
13712 vector.
13713 @c JP
13714 ベクタ@var{source}の内容をベクタ@var{target}のインデックス@var{tstart}以降に
13715 コピーします。@var{target}は変更可能でなければなりません。
13716 省略可能な@var{sstart}と@var{send}引数はコピー元ベクタの範囲を限定します。
13717 @c COMMON
13718
13719 @example
13720 (rlet1 v (vector 'a 'b 'c 'd 'e)
13721 (vector-copy! v 2 '#(1 2)))
13722 @result{} #(a b 1 2 e)
13723 (rlet1 v (vector 'a 'b 'c 'd 'e)
13724 (vector-copy! v 2 '#(1 2 3 4) 1 3))
13725 @result{} #(a b 2 3 e)
13726 @end example
13727
13728 @c EN
13729 An error is raised if the portion to be copied is greater than
13730 the room in the target (that is, between @var{tstart} to the end).
13731 @c JP
13732 コピーされるデータが、コピー先の領域(@var{tstart}から末尾まで)より
13733 大きい場合はエラーが報告されます。
13734 @c COMMON
13735
13736 @c EN
13737 It is ok to pass the same vector to @var{target} and @var{source};
13738 it always works even if the regions of source and destination are
13739 overlapping.
13740 @c JP
13741 @var{target}と@var{source}に同じベクタを渡しても構いません。
13742 コピー元とコピー先の領域に重なりがある場合でもこの手続きは使えます。
13743 @c COMMON
13744 @end defun
13745
13746 @defun vector-append vec @dots{}
13747 [R7RS base]
13748 @c EN
13749 Returns a newly allocated vector whose contents are concatenation
13750 of elements of @var{vec} in order.
13751 @c JP
13752 ベクタ@var{vec}を順に継ぎ足した内容を持つベクタを新たに作成して返します。
13753 @c COMMON
13754
13755 @example
13756 (vector-append '#(1 2 3) '#(a b)) @result{} #(1 2 3 a b)
13757 (vector-append) @result{} #()
13758 @end example
13759 @end defun
13760
13761 @defun vector-map proc vec1 vec2 @dots{}
13762 [R7RS base]
13763 @c EN
13764 Returns a new vector, @var{i}-th of which is calculated
13765 by applying @var{proc} on the list of each @var{i}-th element
13766 of @var{vec1} @var{vec2} @dots{}.
13767 The length of the result vector is the same as the shortest vector
13768 of the arguments.
13769 @c JP
13770 ベクタ@var{vec1} @var{vec2} @dots{}の各@var{i}番目の要素に@var{proc}を
13771 適用したものを@var{i}番目の要素とする新たなベクタを作って返します。
13772 結果のベクタの長さは、引数のベクタのうち最も短いものと同じになります。
13773 @c COMMON
13774
13775 @example
13776 (vector-map + '#(1 2 3) '#(4 5 6 7))
13777 @result{} #(5 7 9)
13778 @end example
13779
13780 @c EN
13781 The actual order @var{proc} is called is undefined, and may change
13782 in the future versions, so @var{proc} shouldn't use side effects
13783 affected by the order.
13784 @c JP
13785 @var{proc}が呼ばれる順番は定義されておらず、将来のバージョンで変わるかもしれないので、
13786 @var{proc}では順序に影響されるような副作用を起こしてはいけません。
13787 @c COMMON
13788
13789 @c EN
13790 Note: If you use @code{gauche.collection}, you can get the same
13791 function by @code{(map-to <vector> proc vec1 vec2 @dots{})}.
13792 @c JP
13793 註: @code{gauche.collection}をuseして
13794 @code{(map-to <vector> proc vec1 vec2 @dots{})} としても同じ機能は得られます。
13795 @c COMMON
13796 @end defun
13797
13798 @defun vector-map-with-index proc vec1 vec2 @dots{}
13799 @c EN
13800 Like @code{vector-map}, but @var{proc} receives the current index
13801 as the first argument.
13802 @c JP
13803 @code{vector-map}と似ていますが、@var{proc}の第1引数に
13804 現在のインデックスが渡されます。
13805 @c COMMON
13806
13807 @example
13808 (vector-map-with-index list '#(a b c d e) '#(A B C))
13809 @result{} #((0 a A) (1 b B) (2 c C))
13810 @end example
13811
13812 @c EN
13813 This is what SRFI-43 calls @code{vector-map}. @xref{Vector library (Legacy)}.
13814 @c JP
13815 これがSRFI-43で@code{vector-map}と呼ばれている手続きです。
13816 @ref{Vector library (Legacy)}参照。
13817 @c COMMON
13818
13819 @c EN
13820 Note: If you use @code{gauche.collection}, you can get the same
13821 function by @code{(map-to-with-index <vector> proc vec1 vec2 @dots{})}.
13822 @c JP
13823 註: @code{gauche.collection}をuseして
13824 @code{(map-to-with-index <vector> proc vec1 vec2 @dots{})}
13825 としても同じ機能は得られます。
13826 @c COMMON
13827 @end defun
13828
13829 @defun vector-map! proc vec1 vec2 @dots{}
13830 [R7RS vector]
13831 @c EN
13832 For each index @var{i}, calls @var{proc} with @var{i}-th index
13833 of @var{vec1} @var{vec2} @dots{}, and set the result back to
13834 @var{vec1}. The value is calculated up to the minimum
13835 length of input vectors.
13836 @c JP
13837 各インデックス@var{i}について、ベクタ@var{vec1} @var{vec2} @dots{}の
13838 @var{i}番目の要素を引数として@var{proc}を呼び出した結果、@var{vec1}の
13839 @var{i}番目の要素にセットします。ベクタの長さが異なる場合は最も短いベクタ
13840 の範囲が計算されます。
13841 @c COMMON
13842
13843 @example
13844 (rlet1 v (vector 1 2 3)
13845 (vector-map! ($ + 1 $) v))
13846 @result{} #(2 3 4)
13847
13848 (rlet1 v (vector 1 2 3 4)
13849 (vector-map! + v '#(10 20)))
13850 @result{} #(11 22 3 4)
13851 @end example
13852 @end defun
13853
13854 @defun vector-map-with-index! proc vec1 vec2 @dots{}
13855 @c EN
13856 Like @code{vector-map!}, but @var{proc} receives the current
13857 index as the first argument. This is equivalent to SRFI-43's
13858 @code{vector-map!} (@pxref{Vector library (Legacy)}).
13859 @c JP
13860 @code{vector-map!}と似ていますが、@var{proc}の第1引数に
13861 現在のインデックスが渡されます。SRFI-43で@code{vector-map!}
13862 と定義されているものと同じ動作です (@ref{Vector library (Legacy)}参照)。
13863 @c COMMON
13864
13865 @example
13866 (rlet1 v (vector 'a 'b 'c)
13867 (vector-map-with-index! list v))
13868 @result{} #((0 a) (1 b) (2 c))
13869 @end example
13870
13871 @end defun
13872
13873 @defun vector-for-each proc vec1 vec2 @dots{}
13874 [R7RS base]
13875 @c EN
13876 For all @var{i} below the minimum length of input vectors,
13877 calls @var{proc} with @var{i}-th elements of @var{vec1} @var{vec2}
13878 @dots{}, in increasing order of @var{i}.
13879 @c JP
13880 0から渡されたベクタのうち一番短いものの最大のインデックスまでの@var{i}について、
13881 @var{vec1} @var{vec2} @dots{}のそれぞれ@var{i}番目の要素を引数に
13882 @var{proc}を呼び出します。
13883 @c COMMON
13884
13885 @example
13886 (vector-for-each print '#(a b c))
13887 @result{} @r{prints @code{a}, @code{b} and @code{c}}.
13888 @end example
13889 @end defun
13890
13891 @defun vector-for-each-with-index proc vec1 vec2 @dots{}
13892 @c EN
13893 Like @code{vector-for-each}, but @var{proc} receives the current index
13894 in the first argument.
13895
13896 This is equivalent to SRFI-43's @code{vector-for-each}.
13897 @xref{Vector library (Legacy)}.
13898 @c JP
13899 @code{vector-for-each}と似ていますが、@var{proc}の第1引数に
13900 現在のインデックスが渡されます。
13901
13902 この手続きはSRFI-43の@code{vector-for-each}と等価です。
13903 @ref{Vector library (Legacy)}参照。
13904 @c COMMON
13905 @end defun
13906
13907 @node Uniform vectors, Bitvectors, Vectors, Vector family
13908 @subsection Uniform vectors
13909 @c NODE ユニフォームベクタ
13910
13911 @c EN
13912 Uniform vectors, or homogeneous numeric vectors, are a special
13913 type of vectors whose elements are of the same numeric type.
13914 It was introduced originally as SRFI-4, revised by SRFI-160,
13915 and now a part of R7RS large (as @code{scheme.vector.@@}).
13916 @c JP
13917 ユニフォームベクタ、あるいは同質な数値ベクタは、
13918 要素として特定の数値型のみを格納する特別なベクタです。
13919 もともとSRFI-4として導入され、SRFI-160で改訂されたのち、
13920 R7RS largeの一部となりました(@code{scheme.vector.@@}モジュール)。
13921 @c COMMON
13922
13923 @c EN
13924 The @code{@@} part is actually one of the following tags, indicating
13925 the type of elements:
13926 @c JP
13927 @code{@@}の部分は実際には要素の型を示す以下のタグのいずれかです。
13928 @c COMMON
13929
13930 @table @code
13931 @item u8
13932 @c EN
13933 Unsigned 8-bit integer - an exact integer between 0 and 255.
13934 @c JP
13935 8ビット符号無し整数 - 0から255までの正確な整数。
13936 @c COMMON
13937 @item s8
13938 @c EN
13939 Signed 8-bit integer - an exact integer between -128 and 127.
13940 @c JP
13941 8ビット符号つき整数 - -128から127までの正確な整数。
13942 @c COMMON
13943 @item u16
13944 @c EN
13945 Unsigned 16-bit integer - an exact integer between 0 and 65535.
13946 @c JP
13947 16ビット符号無し整数 - 0から65535までの正確な整数。
13948 @c COMMON
13949 @item s16
13950 @c EN
13951 Signed 16-bit integer - an exact integer between -32678 and 32767.
13952 @c JP
13953 16ビット符号つき整数 - -32768から32767までの正確な整数。
13954 @c COMMON
13955 @item u32
13956 @c EN
13957 Unsigned 32-bit integer - an exact integer between 0 and 2^32 - 1.
13958 @c JP
13959 32ビット符号無し整数 - 0から 2^32 - 1 までの正確な整数。
13960 @c COMMON
13961 @item s32
13962 @c EN
13963 Signed 32-bit integer - an exact integer between -(2^31) and 2^31 - 1.
13964 @c JP
13965 32ビット符号つき整数 - -(2^31) から 2^31 - 1 までの正確な整数。
13966 @c COMMON
13967 @item u64
13968 @c EN
13969 Unsigned 64-bit integer - an exact integer between 0 and 2^64 - 1.
13970 @c JP
13971 64ビット符号無し整数 - 0から 2^64 - 1 までの正確な整数。
13972 @c COMMON
13973 @item s64
13974 @c EN
13975 Signed 64-bit integer - an exact integer between -(2^63) and 2^63 - 1.
13976 @c JP
13977 64ビット符号つき整数 - -(2^63) から 2^63 - 1 までの正確な整数。
13978 @c COMMON
13979 @item f16
13980 @c EN
13981 16-bit floating point number (10-bit mantissa and 5-bit exponent),
13982 as inexact real.
13983 @c JP
13984 16ビット浮動小数点数(仮数部10ビット、指数部5ビット)で表される非正確な実数
13985 @c COMMON
13986 @item f32
13987 @c EN
13988 IEEE single-precision floating point number
13989 as inexact real.
13990 @c JP
13991 IEEE単精度浮動小数点数で表される非正確な実数
13992 @c COMMON
13993 @item f64
13994 @c EN
13995 IEEE double-precision floating point number
13996 as inexact real.
13997 @c JP
13998 IEEE倍精度浮動小数点数で表される非正確な実数
13999 @c COMMON
14000 @item c32
14001 @c EN
14002 Inexact complex, consists of a pair of 16-bit floating point numbers.
14003 @c JP
14004 2つの16ビット浮動小数点数で表される非正確な複素数
14005 @c COMMON
14006 @item c64
14007 @c EN
14008 Inexact complex, consists of a pair of IEEE single-precision floating
14009 point numbers.
14010 @c JP
14011 2つのIEEE単精度浮動小数点数で表される非正確な複素数
14012 @c COMMON
14013 @item c128
14014 @c EN
14015 Inexact complex, consists of a pair of IEEE double-precision floating
14016 point numbers.
14017 @c JP
14018 2つのIEEE倍精度浮動小数点数で表される非正確な複素数
14019 @c COMMON
14020 @end table
14021
14022 @c EN
14023 There are some advantages of using uniform vectors over normal
14024 (heterogeneous) vectors. It may be more compact than the normal
14025 vectors. Some operations (especially Gauche's extension of vector
14026 arithmetic operations) can bypass type check and conversion of
14027 individual elements, thus be more efficient. And it is much easier
14028 and efficient to communicate with external libraries that require
14029 homogeneous array of numbers; for example, OpenGL binding of Gauche
14030 uses uniform vectors extensively.
14031 @c JP
14032 通常のベクタではなくユニフォームベクタを使うことにより得られる利点がいくつかあります。
14033 まず、ユニフォームベクタは通常のベクタよりもコンパクトです。
14034 いくつかのオペレーション(特に、Gaucheの拡張仕様であるベクタ上の数値演算)では、
14035 型検査と型変換を個々の要素に対して行わなくても良いため、
14036 極めて効率の良い演算が可能です。さらに、
14037 数値の配列を扱う外部のライブラリとのインタフェースが容易です。
14038 例えば、GaucheのOpenGLバインディングではユニフォームベクタを多用しています。
14039 @c COMMON
14040
14041 @c EN
14042 Gauche has only a handful primitive operations on uniform vectors
14043 as a built-in, but the @code{gauche.uvector} module, or
14044 @code{scheme.vector.@@} module (@code{(scheme vector @@)} library
14045 in R7RS programs), provide a complehensive set of operations.
14046 @xref{Uniform vector library}, and @pxref{R7RS uniform vectors}.
14047 @c JP
14048 Gaucheは組み込みではごく基本的な手続きしか提供しませんが、
14049 @code{gauche.uvector}モジュールや@code{scheme.vector.@@}モジュール
14050 (R7RSでは@code{(scheme vector @@)}ライブラリ)では包括的な操作を提供しています。
14051 @ref{Uniform vector library}および@ref{R7RS uniform vectors}参照。
14052 @c COMMON
14053
14054 @c EN
14055 @subsubheading Uvector classes
14056 @c JP
14057 @subsubheading uvectorクラス
14058 @c COMMON
14059
14060 @deftp {Abstract Class} <uvector>
14061 @c EN
14062 The base class of uniform vector classes. It inherits @code{<sequence>}
14063 (@pxref{Sequence framework}).
14064 @c JP
14065 ユニフォームベクタクラスのベースクラスです。@code{<sequence>}を継承します
14066 (@ref{Sequence framework}参照)。
14067 @c COMMON
14068 @end deftp
14069
14070
14071 @deftp {Builtin Class} <@@vector>
14072 @clindex s8vector
14073 @clindex u8vector
14074 @clindex s16vector
14075 @clindex u16vector
14076 @clindex s32vector
14077 @clindex u32vector
14078 @clindex s64vector
14079 @clindex u64vector
14080 @clindex f16vector
14081 @clindex f32vector
14082 @clindex f64vector
14083 @clindex c32vector
14084 @clindex c64vector
14085 @clindex c128vector
14086 @c MOD gauche.uvector
14087 @c EN
14088 A class for @@vector, where @code{@@} is one of the uvector tags
14089 (@code{u8}, @code{s8}, @dots{}).
14090 It inherits @code{<uvector>}.
14091
14092 It implements sequence protocol (@pxref{Sequence framework})),
14093 so you can convert a sequence of
14094 real numbers into a uvector using @code{coerce-to},
14095 if every elements is valid for the uvector.
14096 @c JP
14097 @@vectorのクラス。@code{@@}の部分はuvectorタグ
14098 (@code{u8}、@code{s8}、@dots{}) です。
14099 @code{<uvector>}を継承します。
14100
14101 sequenceプロトコル(@ref{Sequence framework}参照)を実装しているので、
14102 数値の並びを@code{coerce-to}を使ってuvectorに変換することができます。
14103 ただし各要素はuvectorの要素として有効な範囲の値でなればなりません。
14104 @c COMMON
14105
14106 @example
14107 (use gauche.sequence)
14108 (coerce-to <u8vector> '(1 2 3)) @result{} #u8(1 2 3)
14109 @end example
14110 @end deftp
14111
14112 @c EN
14113 @subsubheading Uvector literals
14114 @c JP
14115 @subsubheading uvectorリテラル
14116 @c COMMON
14117
14118 @deftp {Reader Syntax} @code{#u8(@var{n} @dots{})}
14119 @deftpx {Reader Syntax} @code{#s8(@var{n} @dots{})}
14120 @deftpx {Reader Syntax} @code{#u16(@var{n} @dots{})}
14121 @deftpx {Reader Syntax} @code{#s16(@var{n} @dots{})}
14122 @deftpx {Reader Syntax} @code{#u32(@var{n} @dots{})}
14123 @deftpx {Reader Syntax} @code{#s32(@var{n} @dots{})}
14124 @deftpx {Reader Syntax} @code{#u64(@var{n} @dots{})}
14125 @deftpx {Reader Syntax} @code{#s64(@var{n} @dots{})}
14126 @deftpx {Reader Syntax} @code{#f16(@var{n} @dots{})}
14127 @deftpx {Reader Syntax} @code{#f32(@var{n} @dots{})}
14128 @deftpx {Reader Syntax} @code{#f64(@var{n} @dots{})}
14129 @deftpx {Reader Syntax} @code{#c32(@var{n} @dots{})}
14130 @deftpx {Reader Syntax} @code{#c64(@var{n} @dots{})}
14131 @deftpx {Reader Syntax} @code{#c128(@var{n} @dots{})}
14132 @lxindex #s8
14133 @lxindex #u8
14134 @lxindex #s16
14135 @lxindex #u16
14136 @lxindex #s32
14137 @lxindex #u32
14138 @lxindex #s64
14139 @lxindex #u64
14140 @lxindex #f16
14141 @lxindex #f32
14142 @lxindex #f64
14143 @lxindex #c32
14144 @lxindex #c64
14145 @lxindex #c128
14146 @c EN
14147 Denotes a literal homogeneous vector.
14148
14149 (Note: R7RS bytevector is the same as u8vector, and can be written
14150 as @code{#u8(@dots{})}.)
14151 @c JP
14152 リテラルの単一型のベクタを記述します。
14153
14154 (註: R7RSのバイトベクタはu8vectorと同じで、@code{#u8(@dots{})}で表記できます。)
14155 @c COMMON
14156 @example
14157 #s8(3 -2 4)
14158 #u32(4154 88357 2 323)
14159 #f32(3.14 0.554525 -3.342)
14160 @end example
14161
14162 @c EN
14163 Gauche also supports SRFI-207 (String-notated bytevector) style bytevector
14164 literal. It is a prefix @code{#u8} followed by a string literal, in which
14165 only ASCII characters and escaped single-octets (i.e. @code{\xNN;} where
14166 @code{N} is a hexadecimal digit) are allowed. It allows to naturally
14167 use bytevectors as a bytestring.
14168 @xref{String-notated bytevectors}, for operations on bytestrings.
14169 @c JP
14170 Gaucheはまた、SRFI-207 (文字列表示のバイトベクタ) 形式の
14171 バイトベクタリテラルをサポートします。これは、@code{#u8}プレフィクスの後に
14172 文字列リテラルが続くものです。ただしその文字列リテラルには、
14173 ASCII文字か@code{\xNN;} (@code{N}は十六進数) でエスケープされたオクテットのみが
14174 許されます。この表記で、バイトベクタをバイトストリングとして自然に扱うことができます。
14175 バイトストリングの操作に関しては@ref{String-notated bytevectors}を参照してください。
14176 @c COMMON
14177
14178 @example
14179 #u8"ABC\x00;D" @result{} #u8(65 66 67 0 68)
14180 @end example
14181 @end deftp
14182
14183 @c EN
14184 @subsubheading Uvector constructors
14185 @c JP
14186 @subsubheading uvectorのコンストラクタ
14187 @c COMMON
14188
14189 @defun make-s8vector len :optional fill
14190 @defunx make-s8vector len :optional fill
14191 @defunx make-u8vector len :optional fill
14192 @defunx make-s16vector len :optional fill
14193 @defunx make-u16vector len :optional fill
14194 @defunx make-s32vector len :optional fill
14195 @defunx make-u32vector len :optional fill
14196 @defunx make-s64vector len :optional fill
14197 @defunx make-u64vector len :optional fill
14198 @defunx make-f16vector len :optional fill
14199 @defunx make-f32vector len :optional fill
14200 @defunx make-f64vector len :optional fill
14201 @defunx make-c32vector len :optional fill
14202 @defunx make-c64vector len :optional fill
14203 @defunx make-c128vector len :optional fill
14204 [R7RS vector.@@]
14205 @c EN
14206 Constructs a @@vector of length @var{len}. The elements are
14207 initialized by a number @var{fill}. For exact integer vectors,
14208 @var{fill} must be an exact integer and in the valid range.
14209 If @var{fill} is omitted, the content of the vector is undefined.
14210 @c JP
14211 長さ@var{len}の@@vectorを作成して返します。各要素は@var{fill}で
14212 初期化されます。正確な整数のベクタに対しては、@var{fill}は正確な整数でなければならず、
14213 また有効な範囲内の値でなければなりません。
14214 @var{fill}が省略された場合、各要素の初期値は不定です。
14215 @c COMMON
14216 @example
14217 (make-u8vector 4 0) @result{} #u8(0 0 0 0)
14218 @end example
14219 @end defun
14220
14221 @c EN
14222 @subsubheading Uvector generic operations
14223 @c JP
14224 @subsubheading uvectorのジェネリックな操作
14225 @c COMMON
14226
14227 @defun uvector? obj
14228 @c EN
14229 Returns @code{#t} iff @var{obj} is one of the uniform vectors.
14230 See below for predicates for specific type of uvector.
14231 @c JP
14232 @var{obj}がユニフォームベクタのいずれかなら@code{#t}を、
14233 そうでなければ@code{#f}を返します。
14234 特定の型のuvectorを検査する述語については後で説明します。
14235 @c COMMON
14236 @end defun
14237
14238 @defun uvector-length uv
14239 @c EN
14240 Returns the length (the number of elements) of uvector @var{uv}.
14241 An error is raised if @var{uv} is not a uvector.
14242
14243 Type specific length procedures are provided in @code{scheme.vector.@@}
14244 and @code{gauche.uvector} (@pxref{Uniform vector library}).
14245
14246 To get the size of the binary data the content of the uvector actually
14247 occupies, use @code{uvector-size} in @code{gauche.uvector}.
14248 @c JP
14249 uvector@var{uv}の長さ(要素数)を返します。
14250 @var{uv}がuvectorでなければエラーを投げます。
14251
14252 特定の型のuvectorの長さを取る手続きは、@code{scheme.vector.@@}および
14253 @code{gauche.uvector}にあります (@ref{Uniform vector library}参照)。
14254
14255 uvectorの内容がバイナリデータとして占有する大きさを知りたければ、
14256 @code{gauche.uvector}の@code{uvector-size}が使えます。
14257 @c COMMON
14258 @end defun
14259
14260 @defun uvector-ref uv k :optional fallback
14261 @c EN
14262 Generic uvector accessor. Returns @var{k}-th element of a uniform
14263 vector @var{uv}. If @var{k} is out-of-range, @var{fallback} is
14264 returned if provided, or an error is thrown otherwise.
14265
14266 This is handy to write a generic code that works on any kind of
14267 uniform vector, but this is slower than the specific versions.
14268 Gauche's compiler recognizes the specific versions of referencer and
14269 generate very efficient code for them, while this generic version
14270 becomes a normal procedure call. In inner-loop it can make a big
14271 difference.
14272
14273 See below for the type-specific accessors.
14274
14275 @code{(setter uvector-ref)} is @code{uvector-set!}.
14276 @c JP
14277 汎用的なuvectorのアクセサです。uvector @var{uv}の@var{k}番目の
14278 要素を返します。@var{k}が範囲外の場合、@var{fallback}が与えられていればそれが
14279 返され、そうでなければエラーが投げられます。
14280
14281 この手続きは様々な種類のユニフォームベクタに対して動作するような一般的なコードを
14282 書く際にとても便利ですが、それぞれの種類のユニフォームベクタ専用の
14283 アクセサに比べると遅いです。Gaucheのコンパイラは@code{@@vector-ref}の
14284 呼び出しを認識して非常に効率の良いコードを出すのに対し、
14285 この手続きは通常の手続き呼び出しになるからです。内部のループ内で呼び出す場合、
14286 これは大きな差になるかもしれません。
14287
14288 型ごと専用のアクセサは下で説明します。
14289
14290 なお、@code{(setter uvector-ref)}は@code{uvector-set!}です。
14291 @c COMMON
14292 @end defun
14293
14294 @defun uvector-set! uv k val :optional clamp
14295 @c EN
14296 Generic uvector setter. Mutate @var{k}-th element of
14297 uvector @var{uv} with @var{val}.
14298 An error is thrown if @var{k} is out-of-range, or @var{uv} is immutable.
14299
14300 Optional @var{clamp} argument specifies the behavior when
14301 @var{val} is out of valid range. It can be @code{#f} or
14302 one of the symbols @code{low}, @code{high}, or @code{both}.
14303 @xref{Uniform vector library}, for the meanings of the clamp argument.
14304 The default is @code{#f}, which raises an error on out-of-range value.
14305 @c JP
14306 汎用的なuvectorのセッターです。uvector @var{uv}の@var{k}番目の要素を
14307 @var{val}で置き換えます。
14308 @var{k}が範囲外であったり、
14309 @var{uv}が変更不可である場合はエラーが投げられます。
14310
14311 省略可能な引数@var{clamp}が、@var{val}が正しい範囲外の数であった場合の動作を指定します。
14312 この引数は@code{#f}か、
14313 シンボル@code{low}、@code{high}、@code{both}のいずれかでなければなりません。
14314 この意味については@ref{Uniform vector library}を参照してください。
14315 デフォルトは@code{#f}で、範囲外の値についてはエラーを投げます。
14316 @c COMMON
14317 @end defun
14318
14319
14320 @c EN
14321 @subsubheading Uvector type-specific operations
14322 @c JP
14323 @subsubheading uvectorの型ごとの操作
14324 @c COMMON
14325
14326 @c EN
14327 Type-specific predicates, accessors and modifiers are provided in the core
14328 library; all the rest are in @code{scheme.vector.@@} or @code{gauche.uvector}
14329 (@pxref{Uniform vector library}).
14330 @c JP
14331 型ごとの述語、アクセサ、セッタはここで提供されます。
14332 他の手続きについては@code{scheme.vector.@@}や@code{gauche.uvector}を
14333 利用してください (@ref{Uniform vector library}参照)。
14334 @c COMMON
14335
14336 @deffn {Function} @@vector? obj
14337 @findex s8vector?
14338 @findex u8vector?
14339 @findex s16vector?
14340 @findex u16vector?
14341 @findex s32vector?
14342 @findex u32vector?
14343 @findex s64vector?
14344 @findex u64vector?
14345 @findex f16vector?
14346 @findex f32vector?
14347 @findex f64vector?
14348 @findex c32vector?
14349 @findex c64vector?
14350 @findex c128vector?
14351 [R7RS vector.@@]
14352 @c EN
14353 Returns @code{#t} iff @var{obj} is a @@vector, @code{#f} otherwise.
14354 The @code{@@} part is one of the uvector tags (@code{u8} etc.).
14355 @c JP
14356 @var{obj}が@@vectorなら@code{#t}を、そうでなければ@code{#f}を返します。
14357 @code{@@}の部分はuvectorタグ(@code{u8}等)です。
14358 @c COMMON
14359 @end deffn
14360
14361 @deffn {Function} @@vector-ref vec k :optional fallback
14362 @findex u8vector-ref
14363 @findex s8vector-ref
14364 @findex u16vector-ref
14365 @findex s16vector-ref
14366 @findex u32vector-ref
14367 @findex s32vector-ref
14368 @findex u64vector-ref
14369 @findex s64vector-ref
14370 @findex f16vector-ref
14371 @findex f32vector-ref
14372 @findex f64vector-ref
14373 @findex c32vector-ref
14374 @findex c64vector-ref
14375 @findex c128vector-ref
14376 [R7RS vector.@@]
14377 @c EN
14378 Returns the @var{k}-th element of @@vector @var{vec}.
14379 The @code{@@} part is one of the uvector tags (@code{u8} etc.).
14380
14381 If the index @var{k} is out of the valid range, an error is signaled
14382 unless an optional argument @var{fallback} is given; in that case,
14383 @var{fallback} is returned.
14384
14385 Note that the generic function @code{ref} can be used as well,
14386 if you import @code{gauche.collection}.
14387 @c JP
14388 @@vector @var{vec}の@var{k}番目の要素を返します。
14389 @code{@@}の部分はuvectorタグ(@code{u8}等)です。
14390
14391 @var{k}が有効な範囲外であった場合、通常はエラーが通知されますが、
14392 省略可能な引数@var{fallback}が与えられている場合はそれが返されます。
14393
14394 モジュール@code{gauche.collection}をインポートしていれば、
14395 総称関数@code{ref}を使うこともできます。
14396 @c COMMON
14397
14398 @example
14399 (u16vector-ref '#u16(111 222 333) 1) @result{} 222
14400
14401 (use gauche.collection)
14402 (ref '#u16(111 222 333) 1) @result{} 222
14403 @end example
14404
14405 @c EN
14406 Setter of @code{@@vector-ref} is @code{@@vector-set!}.
14407 @c JP
14408 @code{@@vector-ref}のsetterは@code{@@vector-set!}です。
14409 @c COMMON
14410
14411 @example
14412 (use gauche.uvector)
14413 (define v (u8vector 1 2 3))
14414 (set! (u8vector-ref v 1) 99)
14415
14416 v @result{} #u8(1 99 3)
14417 @end example
14418 @end deffn
14419
14420 @deffn {Function} @@vector-set! vec k n :optional clamp
14421 @findex u8vector-set!
14422 @findex s8vector-set!
14423 @findex u16vector-set!
14424 @findex s16vector-set!
14425 @findex u32vector-set!
14426 @findex s32vector-set!
14427 @findex u64vector-set!
14428 @findex s64vector-set!
14429 @findex f16vector-set!
14430 @findex f32vector-set!
14431 @findex f64vector-set!
14432 @findex c32vector-set!
14433 @findex c64vector-set!
14434 @findex c128vector-set!
14435 [R7RS vector.@@]
14436 @c EN
14437 Sets a number @var{n} to the @var{k}-th element of @@vector @var{vec}.
14438 The @code{@@} part is one of the uvector tags (@code{u8} etc.).
14439
14440 Optional @var{clamp} argument specifies the behavior when
14441 @var{n} is out of valid range. It can be @code{#f} or
14442 one of the symbols @code{low}, @code{high}, or @code{both}.
14443 @xref{Uniform vector library}, for the meanings of the clamp argument.
14444 The default is @code{#f}, which raises an error on out-of-range value.
14445
14446 Note that the setter of the generic function @code{ref} can be used as well,
14447 if you import @code{gauche.collection}.
14448 @c JP
14449 @@vector @var{vec}の@var{k}番目の要素に数値@var{n}をセットします。
14450 @code{@@}の部分はuvectorタグ(@code{u8}等)です。
14451 省略可能な引数@var{clamp}が、@var{n}が正しい範囲外の数であった場合の動作を指定します。
14452 この引数は@code{#f}か、
14453 シンボル@code{low}、@code{high}、@code{both}のいずれかでなければなりません。
14454 この意味については@ref{Uniform vector library}を参照してください。
14455 デフォルトは@code{#f}で、範囲外の値についてはエラーを投げます。
14456
14457 モジュール@code{gauche.collection}をインポートしていれば、
14458 総称関数@code{ref}のsetter手続きを使うこともできます。
14459 @c COMMON
14460 @example
14461 (let ((v (s32vector -439 852 8933)))
14462 (s32vector-set! v 1 4)
14463 v)
14464 @result{} #s32vector(-439 4 8933)
14465
14466 (use gauche.collection)
14467 (let ((v (s32vector -439 852 8933)))
14468 (set! (ref v 1) 4)
14469 v)
14470 @result{} #s32vector(-439 4 8933)
14471 @end example
14472 @end deffn
14473
14474 @c EN
14475 @subsubheading Conversion between strings and uvectors
14476 @c JP
14477 @subsubheading 文字列とuvectorの変換
14478 @c COMMON
14479
14480 @c EN
14481 Two sets of conversion procedures are provided. The first set is
14482 to convert strings to u8/s8 vector and vice versa, taking multibyte
14483 representation of a string as a byte vector. The second set is
14484 to convert strings to u32/s32 vector and vice versa, regarding
14485 a string as a sequence of Unicode codepoints.
14486 @c JP
14487 二種類の変換手続きが提供されます。
14488 最初のは、文字列とu8/s8ベクタとを相互に変換するもので、
14489 文字列のマルチバイト表現をバイトベクタとみなします。
14490 もうひとつは文字列とu32/s32ベクタとを相互に変換するもので、
14491 文字列をUnicodeコードポイントの列とみなします。
14492 @c COMMON
14493
14494 @c EN
14495 For portable Scheme code, SRFI-181 provides conversion between
14496 strings and bytevectors, specifying character encodings
14497 (@pxref{Transcoded ports}).
14498 @c JP
14499 ポータブルなSchemekコードを書くには、SRFI-181が提供する
14500 文字列とバイトベクタの変換手続きが使えるでしょう。
14501 文字エンコーディングを指定することもできます
14502 (@ref{Transcoded ports}参照)。
14503 @c COMMON
14504
14505 @defun string->s8vector string :optional start end immutable?
14506 @defunx string->u8vector string :optional start end immutable?
14507 @c EN
14508 Returns an s8vector or u8vector whose byte sequence is the same
14509 as the internal representation of the given string.
14510 Optional range arguments @var{start} and @var{end} specifies
14511 the @emph{character position} (not the byte position) inside @var{string} to be
14512 converted.
14513
14514 By default, the content of the string is copied to a newly created
14515 mutable uvector. However, if a true value is given to the
14516 optional @var{immutable?} argument, the result is an immutable
14517 uvector, and it may avoid copying the string body (note that
14518 in Gauche, the body of string is immutable; @code{string-set!} creates
14519 a new body, so changing the original string won't affect the
14520 uvector created by @code{string->u8vector} with @code{immutable?} flag.)
14521
14522 These procedures are useful when you want to access byte
14523 sequence of the string randomly.
14524 @c JP
14525 与えられた文字列の内部表現のバイト列と同じバイト列を持つs8vectorもしくは
14526 u8vectorを返します。省略可能な範囲引数@var{start}、@var{end}は、
14527 変換される文字列中の文字位置を指定します (バイト位置ではないことに注意)。
14528
14529 デフォルトでは、元の文字列の内容が新たに作られる変更可能なユニフォームベクタへと
14530 コピーされ、そのベクタが返されます。しかし、省略可能引数@var{immutable?}に
14531 真の値が渡された場合、返されるユニフォームベクタは変更不可能となり、
14532 また文字列本体のコピーが避けられる可能性があります。
14533 (Gaucheでは、文字列本体は変更不可能で、@code{string-set!}は新たな
14534 文字列本体を作り出します。したがって@code{string->u8vector}の
14535 @code{immutable?}に@code{#t}を渡してユニフォームベクタを作った後、
14536 元の文字列を変更しても、作られたユニフォームベクタは変更されません。)
14537
14538 これらの手続きは、文字を構成するバイト列をランダムにアクセスしたい場合などに
14539 有用です。
14540 @c COMMON
14541
14542 @example
14543 (string->u8vector "abc") @result{} #u8(97 98 99)
14544
14545 @c JP
14546 ;; 内部コードがEUCの場合
14547 (string->u8vector "いろは") @result{} #u8(164 164 164 237 164 207)
14548 @c COMMON
14549 @end example
14550
14551 @example
14552 (string->u8vector "very large string .... " 0 -1 #t)
14553 @c EN
14554 @result{} #u8(...) ; @r{immutable, sharing content with the original string}
14555 @c JP
14556 @result{} #u8(...) ; @r{変更不可、元の文字列と内容を共有}
14557 @c COMMON
14558 @end example
14559
14560 @end defun
14561
14562 @defun string->s8vector! target tstart string :optional start end
14563 @defunx string->u8vector! target tstart string :optional start end
14564 @c EN
14565 @var{Target} must be an s8vector or a u8vector, respectively.
14566 @var{Target} must be mutable.
14567 Like copies the raw byte representation of @var{string}
14568 into @var{target} beginning from index @var{tstart}.
14569 @c JP
14570 @var{target} は、それぞれ s8vector あるいは u8vector でなければなりません。
14571 @var{target} は、変更可能でなければなりません。
14572 @var{string} の生バイト表現を @var{target} へインデックス @var{tstart}
14573 からコピーします。
14574 @c COMMON
14575
14576 @c EN
14577 Returns @var{target}.
14578 @c JP
14579 @var{target} を返します。
14580 @c COMMON
14581
14582 @example
14583 (let ((target (make-u8vector 10 0)))
14584 (string->u8vector! target 3 "abcde"))
14585 @result{} #u8(0 0 0 97 98 99 100 101 0 0)
14586 @end example
14587
14588 @end defun
14589
14590 @defun s8vector->string vec :optional start end terminator
14591 @defunx u8vector->string vec :optional start end terminator
14592 @c EN
14593 Converts a byte sequence in s8vector or u8vector to a string that
14594 has the same byte sequence. Optional range arguments @var{start} and
14595 @var{end} specifies the byte position in @var{vec} to be converted.
14596
14597 The optional @var{terminator} argument can be an exact integer or
14598 @code{#f} (default). If it is an exact integer, and it appears
14599 in @var{vec}, the string terminates right before it.
14600 For example, you can give 0 as @var{terminator}
14601 to read a NUL-terminated string from a buffer.
14602
14603 @example
14604 (u8vector->string '#u8(65 66 0 67 68) 0 5) @result{} "AB\0CD"
14605 (u8vector->string '#u8(65 66 0 67 68) 0 5 0) @result{} "AB"
14606 @end example
14607
14608 Note that these procedure may result an incomplete string if
14609 @var{vec} contains a byte sequence invalid as utf-8 encoding.
14610 @c JP
14611 与えられたs8vectorもしくはu8vector @var{vec}のバイト列と同じ内部バイト列を
14612 持つ文字列を作成して返します。省略可能な範囲引数@var{start}、@var{end}は、
14613 @var{vec}中の変換されるべき範囲をバイト位置で指定します。
14614
14615 省略可能引数@var{terminator}は正確な整数か@code{#f}でなければなりません
14616 (@code{#f}がデフォルト)。正確な整数が与えられた場合、@var{vec}の中に
14617 その数値が現れれば、その直前までが結果の文字列となります。
14618 例えば0を与えることで、バッファからNUL終端された文字列を読むことができます。
14619
14620 @example
14621 (u8vector->string '#u8(65 66 0 67 68) 0 5) @result{} "AB\0CD"
14622 (u8vector->string '#u8(65 66 0 67 68) 0 5 0) @result{} "AB"
14623 @end example
14624
14625 @var{vec}中のバイト列がutf-8として不正な値を持っていた場合は、
14626 不完全な文字列が返されます。
14627 @c COMMON
14628 @end defun
14629
14630 @defun string->s32vector string :optional start end endian
14631 @defunx string->u32vector string :optional start end endian
14632 @c EN
14633 Returns an s32vector or u32vector whose elements are
14634 the internal codes of the characters in the string.
14635 Optional range arguments @var{start} and @var{end} specifies
14636 the @emph{character position} inside @var{string} to be
14637 converted.
14638 @c JP
14639 与えられた文字列@var{string}の各文字の内部コードを値として持つ
14640 s32vectorもしくはu32vectorを返します。
14641 省略可能な範囲引数@var{start}、@var{end}は、
14642 変換される文字列中の文字位置を指定します。
14643 @c COMMON
14644
14645 @c EN
14646 The optional @var{endian} argument specifies the endianness to store
14647 codepoint value into the uvector. When omitted or @code{#f},
14648 we use the platform's
14649 native endianness. You can give a symbol @code{big-endian}, @code{big},
14650 @code{little-endian}, @code{little} or @code{arm-little-endian} to use a specific
14651 endianness. Note that when you access the resulting uvector,
14652 the platform's native endianness is used.
14653 @c JP
14654 省略可能な@var{endian}引数は、uvectorにコードポイント値を格納する際の
14655 バイトオーダーを指定します。省略された場合や@code{#f}の場合は、
14656 プラットフォームのネイティブバイトオーダーが使われます。
14657 シンボル@code{big-endian}、@code{big}、
14658 @code{little-endian}、@code{little}、@code{arm-little-endian}で
14659 特定のバイトオーダーを指定できます。
14660 結果のuvectorにアクセスする時にはネイティブバイトオーダーが使われることに注意してください。
14661 @c COMMON
14662
14663 @c EN
14664 These procedures are useful when you want to access
14665 the characters in the string randomly.
14666 @c JP
14667 これらの手続きは、文字列中の文字をランダムにアクセスする場合に便利です。
14668 @c COMMON
14669
14670
14671 @end defun
14672
14673 @defun string->s32vector! target tstart string :optional start end endian
14674 @defunx string->u32vector! target tstart string :optional start end endian
14675 @c EN
14676 @var{Target} must be a mutable s32vector or u32vector, respectively.
14677 Fill the @var{target} from position @var{tstart} with the codepoint
14678 of each character of @var{string}, until either @var{string} is exhausted
14679 or @var{target} is filled to the end.
14680
14681 Optional range arguments @var{start} and @var{end} specifies
14682 the @emph{character position} inside @var{string} to be
14683 considered.
14684 @c JP
14685 @var{target}は変更可能なs32vectorもしくはu32vectorでなければなりません。
14686 @var{target}の場所@var{tstart}から、@var{string}の各文字のコードポイントを
14687 順に埋めてゆきます。@var{target}ベクタの終端に達するか、文字が無くなるまで繰り返します。
14688
14689 省略可能な引数@var{start}と@var{end}は@var{string}内の文字位置のインデックスで、
14690 考慮する@var{string}の範囲を制限します。
14691 @c COMMON
14692
14693 @c EN
14694 The optional @var{endian} argument specifies the endianness to store
14695 codepoint value into the uvector. When omitted or @code{#f},
14696 we use the platform's
14697 native endianness. You can give a symbol @code{big-endian}, @code{big},
14698 @code{little-endian}, @code{little} or @code{arm-little-endian} to use a specific
14699 endianness. Note that when you access the resulting uvector,
14700 the platform's native endianness is used.
14701 @c JP
14702 省略可能な@var{endian}引数は、uvectorにコードポイント値を格納する際の
14703 バイトオーダーを指定します。省略された場合や@code{#f}の場合は、
14704 プラットフォームのネイティブバイトオーダーが使われます。
14705 シンボル@code{big-endian}、@code{big}、
14706 @code{little-endian}、@code{little}、@code{arm-little-endian}で
14707 特定のバイトオーダーを指定できます。
14708 結果のuvectorにアクセスする時にはネイティブバイトオーダーが使われることに注意してください。
14709 @c COMMON
14710 @end defun
14711
14712 @defun s32vector->string vec :optional start end terminator endian
14713 @defunx u32vector->string vec :optional start end terminator endian
14714 @c EN
14715 Without @var{start} and @var{end}, these procedures work like this:
14716 @c JP
14717 @var{start}と@var{end}を考えなければ、
14718 これらの手続きは次のコードのような動作をします:
14719 @c COMMON
14720 @example
14721 (lambda (vec) (map-to <string> integer->char vec)))
14722 @end example
14723 @c EN
14724 Optional range arguments @var{start} and @var{end} limits
14725 the range of conversion between them.
14726 @c JP
14727 省略可能な範囲引数@var{start}、@var{end}は、
14728 @var{vec}中の変換されるべき範囲を指定します。
14729 @c COMMON
14730
14731 @c EN
14732 The optional @var{terminator} argument must be an exact
14733 integer or @code{#f} (default). If an integer is given,
14734 and the integer is found in the input,
14735 the output string terminates right before it.
14736 @c JP
14737 省略可能引数@var{terminator}は、正確な整数か@code{#f}でなければ
14738 なりません (@code{#f}がデフォルト)。正確な整数が与えられ、
14739 入力にその数値が見つかった場合は、出力の文字列はその直前で
14740 打ちきられます。
14741 @c COMMON
14742
14743 @c EN
14744 The optional @var{endian} argument specifies the endianness to store
14745 codepoint value into the uvector. When omitted or @code{#f},
14746 we use the platform's
14747 native endianness. You can give a symbol @code{big-endian}, @code{big},
14748 @code{little-endian}, @code{little} or @code{arm-little-endian} to use a specific
14749 endianness.
14750 @c JP
14751 省略可能な@var{endian}引数は、uvectorにコードポイント値を格納する際の
14752 バイトオーダーを指定します。省略された場合や@code{#f}の場合は、
14753 プラットフォームのネイティブバイトオーダーが使われます。
14754 シンボル@code{big-endian}、@code{big}、
14755 @code{little-endian}、@code{little}、@code{arm-little-endian}で
14756 特定のバイトオーダーを指定できます。
14757 @c COMMON
14758
14759 @example
14760 (u32vector->string '#u32(65 66 0 67 68) 0 5 0) @result{} "AB"
14761 @end example
14762 @end defun
14763
14764
14765 @node Bitvectors, Weak vectors, Uniform vectors, Vector family
14766 @subsection Bitvectors
14767 @c NODE ビットベクタ
14768
14769 @c EN
14770 A bitvector is a sequence of bits. Each bit can be considered either
14771 an exact integer 0/1, or a boolean values @code{#f}/@code{#t}.
14772 In the former view, it is similar to a uniform vector, but it has the
14773 interface sufficiently different from uvectors and we provided it as
14774 a disjoint type.
14775
14776 Gauche provides a handful of procedures in the core,
14777 and @code{gauche.bitvector} provides comprehensive utilities.
14778 @xref{Bitvector utilities}, for the details.
14779 For the portable programs, SRFI-178 defines bitvector library,
14780 which is a subset of what Gauche provides (@pxref{Bitvector library}).
14781 @c JP
14782 ビットベクタはビットの並びです。各「ビット」は、0/1の数値としても、
14783 @code{#f}/@code{#t}の論理値としても解釈可能です。
14784 最初の見方では、ビットベクタをユニフォームベクタの一種と考えることもできますが、
14785 インタフェースがそこそこ違っているので、別の型としました。
14786
14787 Gaucheはコアでごく基本的な手続きを提供し、また
14788 @code{gauche.bitvector}モジュールで包括的なビットベクタユーティリティを提供します
14789 (@ref{Bitvector utilities}参照)。
14790 ポータブルなプログラムを書く場合は、SRFI-178がビットベクタライブラリを定義しているので
14791 それを使うと良いでしょう。SRFI-178はGaucheの提供するもののサブセットになっています
14792 (@ref{Bitvector library}参照)。
14793 @c COMMON
14794
14795 @deftp {Builtin class} <bitvector>
14796 @clindex bitvector
14797 @c EN
14798 Bitvector class. Inherits @code{<sequence>}, so generic sequence opertaions
14799 can be used. (Generic @code{ref} uses @code{bitvector-ref/int}, for
14800 it matches the external representation of a bitvector.)
14801 @c JP
14802 ビットベクタクラス。@code{<sequence>}を継承し、ジェネリックなシーケンス操作も使えます。
14803 (ジェネリックな@code{ref}については、
14804 外部表現との親和性から@code{bitvector-ref/int}が使われます)。
14805 @c COMMON
14806 @end deftp
14807
14808 @deftp {Reader Syntax} @code{#*@var{b}@dots{}}
14809 @lxindex #*
14810 [SRFI-178]
14811 @c EN
14812 A bitvector literal is @code{#*} followed by zero or more binary digits
14813 @code{0} or @code{1}.
14814 @c JP
14815 ビットベクタリテラルは、@code{#*}のあとに@code{0}や@code{1}が0個以上続いたものです。
14816 @c COMMON
14817
14818 @example
14819 #*10010010 ; bitvector of length 8
14820 #* ; bitvector of length 0
14821 @end example
14822
14823 @c EN
14824 A bitvector literal is delimited by one of delimiter character or an EOF.
14825 @c JP
14826 ビットベクタリテラルはデリミタ文字かEOFで区切られます。
14827 @c COMMON
14828
14829 @example
14830 #*10010abc ; error
14831 #*10001(a b c) ; a bitvector, followed by a list
14832 @end example
14833
14834 @c EN
14835 Note: With this rule, @code{#*"..."} should be read as a zero-length
14836 bitvector followed by a string, for @code{"} is a delimiter. However,
14837 Gauche used that syntax for incomplete strings (our overlook!).
14838 Since incomplete string literals is rare (incomplete strings are
14839 something that unexpectedly happen in the practical situation, but
14840 not to be used actively), we changed incomplete string literals to
14841 @code{#**"..."} since 0.9.10 (@pxref{Incomplete strings}).
14842 @c JP
14843 註: このルールでは、@code{#*"..."}は、
14844 長さゼロのビットベクタと文字列、と解釈されるべきです。@code{"}は区切り文字ですから。
14845 しかし、Gaucheでは長らくこの構文を不完全文字列に使っていました。
14846 (長さゼロのビットベクタがあることを見落としてました!)
14847 不完全文字列の外部表記が必要になることは滅多にないので
14848 (不完全文字列は現実のデータを扱う際にどうしても「生じてしまう」もので、
14849 積極的に使うべきではありません)、
14850 その表記は0.9.10から@code{#**"..."}に変更されました (@ref{Incomplete strings})。
14851 @c COMMON
14852
14853 @c EN
14854 For the backward compatibility, the current version reads @code{#*"..."}
14855 as an incomplete string. If the reader lexical mode is
14856 @code{warn-legacy} (@pxref{Reader lexical mode}), such literals are
14857 warned. We'll gradually migrate to make @code{#*"..."} read
14858 as a bytevector followed by a string.
14859 @c JP
14860 後方互換性のため、現在のバージョンでは@code{#*"..."}は不完全文字列として読まれます。
14861 リーダー字句モードが@code{warn-legacy}であれば、この形のリテラルに対して警告が出されます
14862 (@ref{Reader lexical mode})。
14863 将来的には@code{#*"..."}はビットベクタと文字列として読まれるように徐々に以降する予定です。
14864 @c COMMON
14865 @end deftp
14866
14867 @defun bit->integer bit
14868 @defunx bit->boolean bit
14869 [SRFI-178]
14870 @c EN
14871 Many bitvector operations can accept bit as a boolean (@code{#f}/@code{#t})
14872 or an exact integer (0/1). These are utility procedures to obtain
14873 desired type. The @var{bit} argument must be either one of @code{#f}, @code{#t},
14874 0 or 1. They return 0/1 and @code{#f}/@code{#t}, respectively.
14875 An error is signalled if @var{bit} is other than those values.
14876 @c JP
14877 ビットベクタAPIでビットが必要なところには、論理値(@code{#f}/@code{#t})あるいは
14878 正確な整数 (0/1)を渡すことができます。これらの手続きは有効なビット値をそれぞれ0/1もしくは
14879 @code{#f}/@code{#t}に揃えます。@var{bit}が有効なビット値でなければエラーが投げられます。
14880 @c COMMON
14881 @end defun
14882
14883 @defun bitvector b @dots{}
14884 [SRFI-178]
14885 @c EN
14886 Creates and returns a bitvector whose elements are @var{b} @dots{}.
14887 Each argument must be a bit (boolean or 0 or 1).
14888 @c JP
14889 要素が@var{b} @dots{}であるビットベクタを作って返します。
14890 各引数はビット値でなければなりません (論理値か0か1)。
14891 @c COMMON
14892
14893 @example
14894 (bitvector 0 1 0 0 1 0 0 0 1) @result{} #*010010001
14895 (bitvector) @result{} #*
14896 @end example
14897 @end defun
14898
14899 @defun make-bitvector len :optional init
14900 [SRFI-178]
14901 @c EN
14902 Creates and returns a bitvector with length @var{len}, and all elements
14903 being initialized by @var{init}, which must be a bit
14904 (boolean or 0 or 1).
14905
14906 If @var{init} is omitted, the content of the bitvector is undefined
14907 (currently we fill it with 0, but don't count on it.)
14908 @c JP
14909 長さ@var{len}のビットベクタを作って返します。各要素は@var{init}で初期化されます。
14910 @var{init}はビット値(論理値か0か1)でなければなりません。
14911
14912 @var{init}が省略された場合、ビットベクタの内容は未定義です。
14913 (今のところ0で初期化されますが、それをあてにしてはいけません)。
14914 @c COMMON
14915
14916 @example
14917 (make-bitvector 5 #f) @result{} #*00000
14918 (make-bitvector 7 1) @result{} #*1111111
14919 @end example
14920 @end defun
14921
14922 @defun bitvector? obj
14923 [SRFI-178]
14924 @c EN
14925 Return @code{#t} iff @var{obj} is an bitvector.
14926 @c JP
14927 @var{obj}がビットベクタなら@code{#t}を、そうでなければ@code{#f}を返します。
14928 @c COMMON
14929 @end defun
14930
14931 @defun list->bitvector lis
14932 [SRFI-178]
14933 @c EN
14934 @var{Lis} must be a list of bits (0, 1 or booleans). Returns a bitvector
14935 whose elements consist of elements of @var{lis}.
14936 @c JP
14937 @var{lis}はビット値(論理値、0、1)のリストでなければなりません。
14938 それらの値を要素とするビットベクタを作って返します。
14939 @c COMMON
14940
14941 @example
14942 (list->bitvector '(#t #f #t #t #f)) @result{} #*10110
14943 (list->bitvector '(0 1 1 1 0 1 0 1)) @result{} #*01110101
14944 @end example
14945 @end defun
14946
14947 @defun string->bitvector s
14948 [SRFI-178]
14949 @c EN
14950 If @var{s} is a valid bitvector literal (@code{#*@var{b}...} where @var{b}
14951 is either @code{0} or @code{1}), returns a bitvector represented by
14952 the string. Otherwise, @code{#f} is returned.
14953 @c JP
14954 @code{s}がビットベクタリテラルとして有効な文字列
14955 (@code{#*@var{b}...}で@var{b}が@code{0}か@code{1})
14956 であれば、それで表現されるビットベクタを返します。そうでなければ@code{#f}が返されます。
14957 @c COMMON
14958
14959 @example
14960 (string->bitvector "#*1010001") @result{} #*1010001
14961 (string->bitvector "#*1001020") @result{} #f
14962 @end example
14963
14964 @c EN
14965 Note that this isn't a sequence-conversion, but rather a conversion from
14966 external representation.
14967 @c JP
14968 これはシーケンスとしての変換ではなく、外部表現からの変換であることに注意してください。
14969 @c COMMON
14970 @end defun
14971
14972 @defun bitvector->string bv
14973 [SRFI-178]
14974 @c EN
14975 Convert a bitvector @var{bv} to a string representation @code{#*@var{b}...}.
14976 @c JP
14977 ビットベクタ@var{bv}の外部表現@code{#*@var{b}...}を文字列として返します。
14978 @c COMMON
14979
14980 @example
14981 (bitvector->string #*1001010) @result{} "#*1001010"
14982 @end example
14983
14984 @c EN
14985 Note that this isn't a sequence-conversion, but rather a conversion to
14986 external representation.
14987 @c JP
14988 これはシーケンスとしての変換ではなく、外部表現への変換であることに注意してください。
14989 @c COMMON
14990 @end defun
14991
14992 @defun bitvector-ref/int bv k :optional fallback
14993 @defunx bitvector-ref/bool bv k :optional fallback
14994 [SRFI-178+]
14995 @c EN
14996 Retrieves the @var{k}-th bit of a bitvector @var{bv} as an integer or
14997 a boolean value, respectively. If @var{k} is out of range,
14998 @var{fallback} is returned if it is given, or an error is raised otherwise.
14999 The @var{fallback} argument is Gauche's extension.
15000 @c JP
15001 ビットベクタ@var{bv}の@var{k}番目の要素を、それぞれ整数0/1か論理値として返します。
15002 @var{k}が範囲外だった場合、@var{fallback}が与えられていればそれが返され、
15003 与えられていなければエラーが投げられます。
15004 @var{fallback}引数はGaucheの拡張です。
15005 @c COMMON
15006
15007 @example
15008 (bitvector-ref/int #*1010001 0) @result{} 1
15009 (bitvector-ref/bool #*1010001 0) @result{} #t
15010 @end example
15011
15012 @c EN
15013 If you use a universal accessor @code{ref}/@code{~}, it returns
15014 the bit value as an integer (@pxref{Universal accessor}).
15015 @c JP
15016 万能アクセサ@code{ref}/@code{~}をビットベクタに使った場合は、
15017 整数値が返されます (@ref{Universal accessor})。
15018 @c COMMON
15019
15020 @example
15021 (~ #*11001001 1) @result{} 1
15022 @end example
15023 @end defun
15024
15025 @defun bitvector-set! bv k bit
15026 [SRFI-178]
15027 @c EN
15028 Sets the @var{k}-th bit of a bitvector @var{bv} with @var{bit}, which must
15029 be either one of 0, 1, @code{#f} or @code{#t}. An error is raised
15030 if @var{k} is out of range.
15031 @c JP
15032 ビットベクタ@var{bv}の@var{k}番目の要素にビット値@var{bit}をセットします。
15033 @var{bit}は0、1、@code{#f}、@code{#t}のいずれかでなければなりません。
15034 @var{k}が範囲外ならエラーが投げられます。
15035 @c COMMON
15036
15037 @c EN
15038 This procedure is set as the setter of @code{bitvector-ref/int} and
15039 @code{bitvector-ref/bool}.
15040 Since a bitvector is a sequence, you can also use
15041 @code{(setter ref)}/@code{(setter ~)}:
15042 @c JP
15043 この手続きは@code{bitvector-ref/int}と@code{bitvector-ref/bool}のsetterとして
15044 設定されています。また、ビットベクタはシーケンスなので、
15045 @code{(setter ref)}/@code{(setter ~)}も使えます。
15046 @c COMMON
15047
15048 @example
15049 (rlet1 z (make-bitvector 5 0)
15050 (set! (~ z 2) #t))
15051 @result{} #00100
15052 @end example
15053 @end defun
15054
15055 @defun bitvector-copy bv :optional start end
15056 [SRFI-178]
15057 @c EN
15058 Returns a copy of a bitvector @var{bv}. If optional @var{start} and
15059 @var{end} indexes are given, the copy is limited in that range,
15060 where @var{start} is inclusive and @var{end} is exclusive.
15061 @c JP
15062 ビットベクタ@var{bv}のコピーを作って返します。
15063 省略可能引数@var{start}、@var{end}でインデックスが与えられた場合は、
15064 その範囲内がコピーされます。@var{start}は含まれ、@var{end}は含まれません。
15065 @c COMMON
15066
15067 @example
15068 (bitvector-copy #*101001000 3) @result{} #*001000
15069 (bitvector-copy #*100101000 2 7) @result{} #*01010
15070 @end example
15071 @end defun
15072
15073 @defun bitvector-copy! target tstart src :optional sstart send
15074 [SRFI-178]
15075 @c EN
15076 Copy a bitvector @var{src} into a mutable bitvector @var{target} starting
15077 from @var{tstart}, mutating @var{target}. Optional @var{sstart} and
15078 @var{send} delimits the range in @var{src}.
15079 @c JP
15080 ビットベクタ@var{src}の内容を、
15081 変更可能なビットベクタ@var{target}の@var{tstart}インデックス以降にコピーして
15082 @var{target}の内容を書き換えます。省略可能な@var{sstart}、@var{send}は
15083 @var{src}のコピーされる範囲を限定します。
15084 @c COMMON
15085
15086 @example
15087 (rlet1 v (make-bitvector 10 0)
15088 (bitvector-copy! v 3 #*101101110 2 6))
15089 @result{} #*0001101000
15090 @end example
15091 @end defun
15092
15093 @defun bitvector-any-value? bv bit :optional start end
15094 @defunx bitvector-every-value? bv bit :optional start end
15095 @c EN
15096 Check if any or every bit of a bitvector @var{bv} is @var{bit}, respectively.
15097 You can pass a boolean value or an exact integer 0 or 1 as @var{bit}.
15098
15099 Optional @var{start}/@var{end} arguments limit the range of bitvector
15100 to look at.
15101 @c JP
15102 それぞれ、ビットベクタ@var{bv}の少なくともひとつ/全てのビットが@var{bit}であるかどうかを
15103 調べます。@var{bit}には真偽値もしくは正確な整数0または1を渡すことができます。
15104
15105 省略可能引数@var{start}/@var{end}は検査する範囲を指定します。
15106 @c COMMON
15107
15108 @example
15109 ;; See if at least one '1'
15110 (bitvector-any-value? #*000100 1) @result{} #t
15111 (bitvector-any-value? #*000000 #t) @result{} #f
15112
15113 ;; See if at least one '0'
15114 (bitvector-any-value? #*110111 #f) @result{} #t
15115 (bitvector-any-value? #*111111 0) @result{} #f
15116
15117 ;; See if all bits are '1'
15118 (bitvector-every-value? #*11111 #t) @result{} #t
15119 (bitvector-every-value? #*00000 1) @result{} #f
15120
15121 ;; See if all bits are '0'
15122 (bitvector-every-value? #*11111 #f) @result{} #f
15123 (bitvector-every-value? #*00000 0) @result{} #t
15124 @end example
15125 @end defun
15126
15127
15128 @node Weak vectors, , Bitvectors, Vector family
15129 @subsection Weak vectors
15130 @c NODE Weakベクタ
15131
15132 @c EN
15133 A weak pointer is a reference to an object that doesn't prevent
15134 the object from being garbage-collected.
15135 Gauche provides weak pointers as a @emph{weak vector} object.
15136 A weak vector is like a vector of objects, except each object
15137 can be garbage collected if it is not referenced from objects
15138 other than weak vectors. If the object is collected, the
15139 entry of the weak vector is replaced for @code{#f.}
15140 @c JP
15141 Weak ポインタとは、それが参照しているオブジェクトがガベージコレクトされることを
15142 許すようなポインタです。
15143 Gaucheは@emph{weak ベクタ}オブジェクトによってweak ポインタの機能を提供します。
15144 Weak ベクタは通常のベクタに似ていますが、要素のオブジェクトがweak ベクタ以外から
15145 参照されていない場合、オブジェクトはガベージコレクトされ、weak ベクタの該当するエントリは
15146 @code{#f}で置き換えられます。
15147 @c COMMON
15148 @example
15149 gosh> (define v (make-weak-vector 1))
15150 v
15151 gosh> (weak-vector-ref v 0)
15152 #f
15153 gosh> (weak-vector-set! v 0 (cons 1 1))
15154 #<undef>
15155 gosh> (weak-vector-ref v 0)
15156 (1 . 1)
15157 gosh> (gc)
15158 #<undef>
15159 gosh> (gc)
15160 #<undef>
15161 gosh> (weak-vector-ref v 0)
15162 #f
15163 @end example
15164
15165 @c EN
15166 @xref{R7RS ephemerons}, for R7RS-large way of weak pointers.
15167 @c JP
15168 R7RS-largeでのweakポインタについては@ref{R7RS ephemerons}を参照してください。
15169 @c COMMON
15170
15171 @deftp {Builtin Class} <weak-vector>
15172 @clindex weak-vector
15173 @c EN
15174 The weak vector class. Inherits @code{<sequence>} and @code{<collection>},
15175 so you can use
15176 @code{gauche.collection} (@pxref{Collection framework}) and
15177 @code{gauche.sequence} (@pxref{Sequence framework}).
15178 @c JP
15179 Weak ベクタのクラスです。@code{<sequence>}と@code{<collection>}を継承しているので、
15180 @code{gauche.collection} (@ref{Collection framework}参照) と
15181 @code{gauche.sequence} (@ref{Sequence framework}参照) も使えます。
15182 @c COMMON
15183 @example
15184 (coerce-to <weak-vector> '(1 2 3 4))
15185 @result{} a weak vector with four elements
15186 @end example
15187 @end deftp
15188
15189 @defun make-weak-vector size
15190 @c EN
15191 Creates and returns a weak vector of size @var{size}.
15192 @c JP
15193 大きさ@var{size}のweak ベクタを作成して返します。
15194 @c COMMON
15195 @end defun
15196
15197 @defun weak-vector-length wvec
15198 @c EN
15199 Returns the length of a weak vector @var{wvec}.
15200 @c JP
15201 weak ベクタ @var{wvec}の大きさを返します。
15202 @c COMMON
15203 @end defun
15204
15205 @defun weak-vector-ref wvec k :optional fallback
15206 @c EN
15207 Returns @var{k}-th element of a weak vector @var{wvec}.
15208
15209 By default, @code{weak-vector-ref} signals an error if @var{k} is
15210 negative, or greater than or equal to the size of @var{wvec}.
15211 However, if an optional argument @var{fallback} is given,
15212 it is returned for such case.
15213
15214 If the element has been garbage collected, this procedure returns
15215 @var{fallback} if it is provided, @code{#f} otherwise.
15216
15217 With @code{gauche.sequence} module,
15218 you can also use a method @code{ref}.
15219 @c JP
15220 weak ベクタ @var{wvec}の@var{k}番目の要素を返します。
15221
15222 @code{weak-vector-ref}は@var{k}が負の値であったりベクタの長さより
15223 大きかったりした場合はエラーを通知します。但し、省略可能な引数@var{fallback}
15224 が与えられている場合はその値が返されます。
15225
15226 該当する要素が既にガベージコレクトされていた場合、@var{fallback}が
15227 与えられていればそれが、そうでなければ@code{#f}が返されます。
15228
15229 @code{gauche.sequence}モジュールをロードしていれば、
15230 メソッド@code{ref}も同じ目的で使えます。
15231 @c COMMON
15232 @end defun
15233
15234 @defun weak-vector-set! wvec k obj
15235 @c EN
15236 Sets @var{k}-th element of the weak vector @var{wvec} to @var{obj}.
15237 It is an error if @var{k} is negative or greater than or equal to the
15238 size of @var{wec}.
15239 @c JP
15240 weak ベクタ @var{wvec}の@var{k}番目の要素を@var{obj}に変更します。
15241 @var{k}が負数であったりベクタの長さより大きい場合はエラーとなります。
15242 @c COMMON
15243 @end defun
15244
15245 @c ----------------------------------------------------------------------
15246 @node Dictionaries, Procedures and continuations, Vector family, Core library
15247 @section Dictionaries
15248 @c NODE ディクショナリ
15249
15250 @c EN
15251 A dictionary is a data structure that associates key to value.
15252 Gauche provides hashtables (@pxref{Hashtables}) and treemaps (@pxref{Treemaps})
15253 as the built-in dictionaries. Some additional libraries provide more
15254 dictionary-type data structures.
15255
15256 A generic interface is defined as a dictionary framework
15257 (@pxref{Dictionary framework}), by which you can use dictionaries without
15258 knowing its details.
15259
15260 R7RS also defines an abstract dictionary interface as @emph{mapping};
15261 @pxref{R7RS mappings}, for the details.
15262 @c JP
15263 ディクショナリは、キーと値を結びつけるデータ構造です。
15264 Gaucheは組み込みのディクショナリとして、ハッシュテーブル(@ref{Hashtables}参照)と
15265 ツリーマップ(@ref{Treemaps}参照)を用意しています。
15266 ライブラリには他にもディクショナリとして振る舞うデータ構造がいくつか提供されます。
15267
15268 さらに、ディクショナリ汎用のインタフェースが、
15269 ディクショナリフレームワークとして提供されます (@ref{Dictionary framework}参照)。
15270 ディクショナリの種類に関わらない操作を書くのに使えます。
15271
15272 R7RSでは、抽象化されたディクショナリインタフェースを@emph{マッピング}として定義しています。
15273 @ref{R7RS mappings}を参照してください。
15274 @c COMMON
15275
15276 @menu
15277 * Hashtables::
15278 * Treemaps::
15279 @end menu
15280
15281 @node Hashtables, Treemaps, Dictionaries, Dictionaries
15282 @subsection Hashtables
15283 @c NODE ハッシュテーブル
15284
15285 @c EN
15286 R7RS-large defines hashtable (@code{scheme.hash-table} module,
15287 @pxref{R7RS hash tables}) but its API is not completely consistent
15288 with Gauche's original hashtables and other native APIs.
15289
15290 Rather than mixing different flavor of APIs, we keep Gauche's native
15291 API consistent, and provide R7RS procedures that are inconsistent
15292 with aliases---specifically, those procedures are suffixed with @code{-r7}
15293 in @code{gauche} module. For portable programs, you can import
15294 @code{scheme.hash-table} to get R7RS names.
15295 @c JP
15296 R7RS-largeにはハッシュテーブルが定義されています
15297 (@code{scheme.hash-table}モジュール、@ref{R7RS hash tables}参照)。
15298 しかし、そのAPIはGaucheにもともとあったハッシュテーブルや他のネイティブAPIと一貫性を
15299 欠いている部分があります。
15300
15301 APIをごちゃまぜにするよりは、GaucheのネイティブなAPIの一貫性を保つことを重視し、
15302 R7RSの手続きのうちGaucheにそぐわないものは、組み込み関数では別名
15303 (サフィックス@code{-r7}がついたもの)をつけて提供しています。
15304 ポータブルなコードを書く場合は、@code{scheme.hash-table}をインポートすれば
15305 R7RSの名前が使えます。
15306 @c COMMON
15307
15308 @deftp {Builtin Class} <hash-table>
15309 @clindex hash-table
15310 @c EN
15311 Hash table class. Inherits @code{<collection>} and @code{<dictionary>}.
15312
15313 Gauche doesn't provide immutable hash tables for now.
15314 (If you need immutable maps, @pxref{Immutable map}).
15315 @c JP
15316 ハッシュテーブルのクラスです。@code{<collection>}と@code{<dictionary>}を
15317 継承します。
15318
15319 Gaucheは今のところ、変更不可なハッシュテーブルは提供しません。
15320 (変更不可なマップが必要な場合は、@ref{Immutable map}を参照してください。)
15321 @c COMMON
15322 @end deftp
15323
15324 @c EN
15325 @subheading Hash table properties
15326 @c JP
15327 @subheading ハッシュテーブルのプロパティ
15328 @c COMMON
15329
15330 @defun hash-table? obj
15331 [R7RS hash-table]
15332 @c EN
15333 Returns @code{#t} iff @var{obj} is a hash table.
15334 @c JP
15335 @var{obj}がハッシュテーブルであれば@code{#t}を返します。
15336 @c COMMON
15337 @end defun
15338
15339 @defun hash-table-mutable? ht
15340 [R7RS hash-table]
15341 @c EN
15342 Returns @code{#t} iff a hash table @var{ht} is mutable.
15343 Gauche doesn't have immutable hash tables, so this procedure always
15344 returns @code{#t} for any hash tables.
15345 @c JP
15346 ハッシュテーブル@var{ht}が変更可能なら@code{#t}を返します。
15347 Gaucheは変更不可なハッシュテーブルを持たないので、
15348 どんなハッシュテーブルに関しても手続きは@code{#t}を返します。
15349 @c COMMON
15350 @end defun
15351
15352 @defun hash-table-comparator ht
15353 @c EN
15354 Returns a comparator used in the hashtable @var{ht}.
15355 @c JP
15356 ハッシュテーブル@var{ht}で使われている比較器を返します。
15357 @c COMMON
15358 @end defun
15359
15360 @defun hash-table-num-entries ht
15361 @defunx hash-table-size ht
15362 [R7RS hash-table]
15363 @c EN
15364 Return the number of entries in the hash table @var{ht}.
15365 R7RS name is @code{hash-table-size}.
15366 @c JP
15367 ハッシュテーブル@var{ht}中の要素の個数を返します。
15368 R7RSの名前は@code{hash-table-size}.
15369 @c COMMON
15370 @end defun
15371
15372 @defun hash-table-type ht
15373 @c DEPRECATED
15374 @c EN
15375 This is a deprecated API, superseded by @code{hash-table-comparator}.
15376
15377 Returns one of symbols @code{eq?}, @code{eqv?}, @code{equal?},
15378 @code{string=?}, @code{general}, indicating the type of the hash table @var{ht}.
15379 @c JP
15380 これは古いAPIで、@code{hash-table-comparator}によって置き換えられました。
15381
15382 ハッシュテーブル@var{ht}のタイプに応じて、シンボル
15383 @code{eq?}、@code{eqv?}、@code{equal?}、@code{string=?}、
15384 @code{general}のいずれかを返します。
15385 @c COMMON
15386 @end defun
15387
15388
15389 @c EN
15390 @subheading Hash table constructors and converters
15391 @c JP
15392 @subheading ハッシュテーブルのコンストラクタとコンバータ
15393 @c COMMON
15394
15395 @defun make-hash-table :optional comparator
15396 [R7RS+ hash-table]
15397 @c EN
15398 Creates a hash table. The @var{comparator} argument
15399 specifies key equality and hash function using a comparator
15400 (@pxref{Basic comparators}). If omitted, @code{eq-comparator}
15401 is used. Note that in R7RS, @var{comparator}
15402 argument can't be omitted.
15403
15404 As Gauche's extension, the @var{comparator} argument can also
15405 be one of the symbols
15406 @code{eq?}, @code{eqv?}, @code{equal?} or @code{string=?}.
15407 If it is one of those symbols, @code{eq-comparator},
15408 @code{eqv-comparator}, @code{equal-comparator} and
15409 @code{string-comparator} will be used, respectively.
15410
15411 The comparator must have hash function, of course. @xref{Hashing},
15412 for the built-in hash functions. In general, comparators derived from
15413 other comparators having hash functions also have appropriate
15414 hash functions.
15415 @c JP
15416 ハッシュテーブルを作成します。@var{comparator}引数には、
15417 キーの等価判定とハッシュに使う比較器(@ref{Basic comparators}参照)を渡します。
15418 省略された場合は@code{eq-comparator}が使われます。
15419 (R7RSでは@var{comparator}は省略できません。)
15420
15421 Gauche独自拡張として、@var{comparator}にシンボル
15422 @code{eq?}、@code{eqv?}、@code{equal?}、@code{string=?}のいずれかを
15423 指定することもできます。
15424 @code{eq-comparator}、
15425 @code{eqv-comparator}、@code{equal-comparator}、
15426 @code{string-comparator}が使われます。
15427
15428 比較器はハッシュ関数を持っていなければなりません。組み込みのハッシュ関数については
15429 @ref{Hashing}を参照してください。比較器を組み合わせて作られた比較器については、
15430 元の比較器がハッシュ関数を持っていれば、通常は適切なハッシュ関数が設定されます。
15431 @c COMMON
15432 @end defun
15433
15434 @defun hash-table-from-pairs comparator key&value @dots{}
15435 @c EN
15436 Constructs and returns a hash table from given
15437 list of arguments.
15438 The @var{comparator} argument is the same as of @code{make-hash-table}.
15439 Each @var{key&value} must be a pair, and its car is used as a key
15440 and its cdr is used as a value.
15441
15442 Note: This is called @code{hash-table} by 0.9.5. R7RS introduced
15443 a procedure with the same name, but different interface.
15444 We see R7RS version makes more sense, so we'll eventually switch to it,
15445 but the transition will take long time.
15446 The R7RS interface is available as
15447 @code{hash-table-r7}, and we urge you to use it in the new code,
15448 and replace existing @code{hash-table} with @code{hash-table-from-pairs}.
15449 @c JP
15450 与えられたキーと値の列からハッシュテーブルを構築して
15451 返します。@var{comparator}引数の意味は@code{make-hash-table}と同じです。
15452 各@var{key&value}はペアでなければならず、そのcarがキー、cdrが値として使われます。
15453
15454 註:これは0.9.5まで@code{hash-table}と呼ばれていた手続きです。
15455 R7RSは同名で異なるインタフェースを持つインタフェースを定義しました。
15456 そちらの方が使いやすいので、長期的にはR7RSインタフェースへとスイッチする予定ですが、
15457 それはかなり将来のことになります。
15458 R7RSインタフェースは@code{hash-table-r7}という名前で利用可能なので、
15459 新たなコードはそちらを使うことを強くお勧めします。
15460 また、既存のコードで@code{hash-table}を使っていたら、
15461 @code{hash-table-from-pairs}に直してください。
15462 @c COMMON
15463
15464 @example
15465 (hash-table-from-pairs 'eq? '(a . 1) '(b . 2))
15466 @equiv{}
15467 (rlet1 h (make-hash-table 'eq?)
15468 (hash-table-put! h 'a 1)
15469 (hash-table-put! h 'b 2))
15470 @end example
15471 @end defun
15472
15473 @defun hash-table comparator key&value @dots{}
15474 @c EN
15475 An alias of @code{hash-table-from-pairs} above. R7RS introduced the same name
15476 procedure with different interface (see @code{hash-table-r7} below), and
15477 we'd like to switch to it in future. For now, use either
15478 @code{hash-table-from-pairs} or @code{hash-table-r7},
15479 or import @code{scheme.hash-table} and write in R7RS.
15480 @c JP
15481 @code{hash-table-from-pairs}の別名です。
15482 R7RSが同名で別インタフェースの手続き(下の@code{hash-table-r7}参照)を導入し、
15483 将来的にはGaucheもそちらに移行する予定です。なので今のところ、
15484 @code{hash-table-from-pairs}か@code{hash-table-r7}を使うか、
15485 @code{scheme.hash-table}をインポートしてR7RSとして書いてください。
15486 @c COMMON
15487 @end defun
15488
15489 @defun hash-table-r7 comparator args @dots{}
15490 @c EN
15491 Create and returns a hash table using @var{comparator}.
15492 The @var{args} @dots{} are the contents, alternating keys and values.
15493
15494 This is defined as @code{hash-table} in R7RS @code{scheme.hash-table}
15495 (@pxref{R7RS hash tables}).
15496 @c JP
15497 @var{comparator}を比較器に使うハッシュテーブルを作って返します。
15498 @var{args} @dots{}はキーと値を交互に並べたもので、ハッシュテーブルの内容を指定します。
15499
15500 これはR7RS @code{scheme.hash-table}で@code{hash-table}と定義されている手続きです
15501 (@ref{R7RS hash tables}参照)。
15502 @c COMMON
15503
15504 @example
15505 (hash-table-r7 'eq? 'a 1 'b 2)
15506 @equiv{}
15507 (rlet1 h (make-hash-table 'eq?)
15508 (hash-table-put! h 'a 1)
15509 (hash-table-put! h 'b 2))
15510 @end example
15511
15512 @c EN
15513 Note: An R7RS compliant implementation of @code{hash-table}
15514 may return an immutable hash table. Since Gauche doesn't have
15515 immutable hash tables (we have immutable maps instead; @pxref{Immutable map}),
15516 we return mutable hash tables. However, the portable program should
15517 refrain from mutating the returned hash tables.
15518 @c JP
15519 註: R7RS準拠の実装には、@code{hash-table}が変更不可なハッシュテーブルを
15520 返すものがあります。Gaucheは変更不可なハッシュテールを持っていないので
15521 (変更不可なマップならあります: @ref{Immutable map}参照)、
15522 変更可能なハッシュテーブルが返されます。
15523 ただ、ポータブルなプログラムを書いている場合は、この手続きが返したハッシュテーブルを
15524 変更しないように注意してください。
15525 @c COMMON
15526 @end defun
15527
15528 @defun hash-table-unfold p f g seed comparator :rest args
15529 [R7RS hash-table]
15530 @c EN
15531 Constructs and returns a new hash table with those repetitive steps.
15532 Each iteration keeps the current seed value, whose initial value is @var{seed}.
15533 @enumerate
15534 @item
15535 Apply a stop predicate @var{p} to the current seed value. If it returns
15536 a true value, stop.
15537 @item
15538 Apply a value producer @var{f} to the current seed value. It must return
15539 two values, which are used as a key and the corresponding value, of the
15540 hash table.
15541 @item
15542 Apply a next procedure @var{g} to the current seed value. The value
15543 it returns becomes the next seed value.
15544 @end enumerate
15545 @c JP
15546 次の手順で新たなハッシュテーブルを作り返します。
15547 各繰り返しは「現在のシード値」を参照しますが、その初期値は@var{seed}です。
15548 @enumerate
15549 @item
15550 停止述語@var{p}を現在のシード値に適用します。それが真の値を返したら、そこで終了です。
15551 @item
15552 生産手続き@var{f}を現在のシード値に適用します。@var{f}は二つの値を返さねばなりません。
15553 最初の値がキー、二番目がキーに対応する値として、作られているハッシュテーブルに挿入されます。
15554 @item
15555 手続き@var{g}が現在のシード値に適用され、その戻り値が次の繰り返しでのシード値となります。
15556 @end enumerate
15557 @c COMMON
15558 @end defun
15559
15560 @defun hash-table-copy ht :optional mutable?
15561 [R7RS hash-table]
15562 @c EN
15563 Returns a new copy of a hash table @var{ht}.
15564
15565 R7RS defines this procedure to return an immutable hash table if
15566 the implementation supports one, unless the optional @var{mutable?}
15567 argument is provided and not false. Gauche doesn't have immutable
15568 hash tables so it ignores the optional argument and
15569 always returns a mutable hash table. But when you write
15570 a portable programs, keep it in mind.
15571 @c JP
15572 ハッシュテーブル@var{ht}のコピーを作って返します。
15573
15574 R7RSは、実装が変更不可なハッシュテーブルをサポートする場合、
15575 @var{mutable?}引数に真の値が与えられない限りは、
15576 この手続きは変更不可なハッシュテーブルを返すと規定しています。
15577 Gaucheは変更不可なハッシュテーブルを持たないので、@var{mutable?}引数は無視され、
15578 常に変更可能なハッシュテーブルが返されますが、
15579 ポータブルなコードを書いている場合は気をつけてください。
15580 @c COMMON
15581 @end defun
15582
15583 @defun hash-table-empty-copy ht
15584 [R7RS hash-table]
15585 @c EN
15586 Returns a new mutable empty hash table that has the same properties as
15587 the given hash table @var{ht}.
15588 @c JP
15589 ハッシュテーブル@var{ht}と同じ性質を持つ空の変更可能なハッシュテーブルを作成して
15590 返します。
15591 @c COMMON
15592 @end defun
15593
15594 @defun alist->hash-table alist :optional comparator
15595 [R7RS+ hash-table]
15596 @c EN
15597 Creates and returns a hash table that has entries of
15598 each element in alist, using its car as the key and
15599 its cdr as the value. The @var{comparator} argument
15600 is the same as in @code{make-hash-table}. The default value
15601 of @var{comparator} is @code{eq-comparator}.
15602
15603 R7RS doesn't allow to omit @var{comparator}.
15604 @c JP
15605 alistに含まれるそれぞれの要素をエントリとして持つハッシュテーブルを
15606 作成して返します。その時、要素のcarがキーとして、要素のcdrが値として
15607 使われます。@var{comparator}引数の意味は@code{make-hash-table}と同じです。
15608 @var{comparator}のデフォルト値は@code{eq-comparator}です。
15609
15610 R7RSでは@var{comparator}は省略不可です。
15611 @c COMMON
15612 @end defun
15613
15614 @defun hash-table->alist hash-table
15615 [R7RS hash-table]
15616 @example
15617 (hash-table-map h cons)
15618 @end example
15619 @end defun
15620
15621 @c EN
15622 @subheading Hash table lookup and mutation
15623 @c JP
15624 @subheading ハッシュテーブルのルックアップと変更
15625 @c COMMON
15626
15627 @defun hash-table-get ht key :optional default
15628 @c EN
15629 Search @var{key} from a hash table @var{ht}, and returns its value
15630 if found. If the key is not found in the table and @var{default} is
15631 given, it is returned. Otherwise an error is signaled.
15632 @c JP
15633 キー@var{key}をハッシュテーブル@var{ht}から探します。見つかればキーに対応する
15634 値を返します。キーが見つからなかった場合、@var{default}が与えられていればそれを
15635 返し、そうでなければエラーを報告します。
15636 @c COMMON
15637 @end defun
15638
15639 @defun hash-table-put! ht key value
15640 @c EN
15641 Puts a key @var{key} with a value @var{value} to the hash table @var{ht}.
15642 @c JP
15643 キー@var{key}と対応する値@var{value}をハッシュテーブル@var{ht}に挿入します。
15644 @c COMMON
15645 @end defun
15646
15647 @deffn {Method} ref (ht <hash-table>) key :optional default
15648 @deffnx {Method} {(setter ref)} (ht <hash-table>) key value
15649 @c EN
15650 Method versions of @code{hash-table-get} and @code{hash-table-put!}.
15651 @c JP
15652 @code{hash-table-get}と@code{hash-table-put!}のメソッド版です。
15653 @c COMMON
15654 @end deffn
15655
15656 @defun hash-table-ref ht key :optional failure success
15657 [R7RS hash-table]
15658 @c EN
15659 This is R7RS way to look up a hash table.
15660
15661 Look up a value associated to the @var{key} in the table @var{ht},
15662 then pass it to a procedure @var{success}, and returns its value.
15663 If @var{success} is omitted, an identity function is used.
15664
15665 If there's no association for @var{key} in @var{ht},
15666 a thunk @var{failure} is called and its result is returned.
15667 The default value of @var{failure} throws an error.
15668
15669 It is more general than Gauche's @code{hash-table-get}, but if you
15670 need to simply return a fallback value in case of failure, you need
15671 to wrap it with a clojure, which is annoying. In R7RS, you can
15672 use @code{hash-table-ref/default} below.
15673 @c JP
15674 これがR7RS方式のハッシュテーブルルックアップです。
15675
15676 ハッシュテーブル@var{ht}中の、@var{key}に結びつけられた値を探し、
15677 それを手続き@var{success}に渡して、その結果を返します。
15678 @var{success}が省略された場合は単に値そのものが返されます。
15679
15680 @var{key}に対応する値が@var{ht}に無い場合は、引数を取らない手続き@var{failure}が
15681 呼ばれ、その結果が返されます。@var{failure}が省略されていた場合はエラーが報告されます。
15682
15683 これはGaucheの@code{hash-table-get}よりも汎用的ですが、
15684 キーが見つからなかった場合に単純に既定値を返したいといった場合に、
15685 それをいちいちクロージャで包むのは面倒です。R7RSではそのために
15686 下に説明する@code{hash-table-ref/default}があります。
15687 @c COMMON
15688 @end defun
15689
15690 @defun hash-table-ref/default ht key default
15691 [R7RS hash-table]
15692 @c EN
15693 Looks up @var{key} in a hash table @var{ht} and returns the associated
15694 value. If there's no @var{key} in the table, returns @var{default}.
15695
15696 This is same as Gauche's @code{hash-table-get}, except that
15697 @var{default} is not optional. We provide both, for
15698 @code{hash-table-get} is short and handy.
15699 @c JP
15700 ハッシュテーブル@var{ht}から@var{key}を探し、対応する値を返します。
15701 @var{key}が見つからない場合は@var{default}を返します。
15702
15703 これは、@var{default}が省略できないことを除いては、Gaucheの
15704 @code{hash-table-get}と同じです。@code{hash-table-get}の方が短くて便利なので
15705 両方提供しています。
15706 @c COMMON
15707 @end defun
15708
15709 @defun hash-table-set! ht args @dots{}
15710 [R7RS hash-table]
15711 @c EN
15712 This is R7RS version to put associations into a hash table.
15713 The @var{args} @dots{} is a list of alternating keys and values; so,
15714 unlike Gauche's @code{hash-table-put!}, you can insert more than
15715 one associations at once. It is an error if @var{args} @dots{} have
15716 odd number of arguments.
15717 @c JP
15718 これが、ハッシュテーブルに新たなエントリを追加するR7RS式のインタフェースです。
15719 @var{args} @dots{}にはキーと値を交互に並べたリストを指定します。
15720 Gaucheの@code{hash-table-put!}と違い、いくつものエントリを一度に追加することができます。
15721 @var{args} @dots{}が偶数要素でなければエラーです。
15722 @c COMMON
15723
15724 @example
15725 (hash-table-set! ht 'a 1 'b 2)
15726 @equiv{}
15727 (begin (hash-table-put! ht 'a 1)
15728 (hash-table-put! ht 'b 2))
15729 @end example
15730 @end defun
15731
15732 @defun hash-table-intern!-r7 ht key failure
15733 @c EN
15734 This is defined in R7RS as @code{hash-table-intern!}. We add @code{-r7}
15735 suffix to remind that it takes a failure thunk,
15736 which is consistent with R7RS hash-table interface but not Gauche's way.
15737
15738 Lookup @var{key} in @var{ht}. If there's already an entry, it just returns
15739 the value.
15740 Otherwise, it calls a thunk @var{failure}, and insert the association
15741 of @var{key} and the return value of @var{failure} into @var{ht},
15742 and returns the value.
15743 @c JP
15744 これはR7RSで@code{hash-table-intern!}として定義されています。
15745 Gaucheの慣習と異なり、R7RSの方式で@var{failure}にサンクを取ることを強調するために
15746 @code{-r7}サフィックスをつけました。
15747
15748 @var{ht}から@var{key}を探します。もし既にエントリがあれば、その値を返します。
15749 エントリが無ければ、サンク@var{failure}を呼び、その戻り値を@var{key}に対応する
15750 値として@var{ht}に挿入して、@var{failure}の戻り値を返します。
15751 @c COMMON
15752 @end defun
15753
15754 @defun hash-table-exists? ht key
15755 @defunx hash-table-contains? ht key
15756 [R7RS hash-table]
15757 @c EN
15758 Returns @code{#t} if a hash table @var{ht} has a key @var{key}.
15759
15760 R7RS name is @code{hash-table-contains?}.
15761 @c JP
15762 ハッシュテーブル@var{ht}にキー@var{key}を持つエントリがあれば@code{#t}を返します。
15763
15764 R7RSでの名前は@code{hash-table-contains?}です。
15765 @c COMMON
15766 @end defun
15767
15768 @defun hash-table-delete! ht key
15769 @c EN
15770 Deletes an entry that has a key @var{key} from the hash table @var{ht}.
15771 Returns @code{#t} if the entry has exist, or @code{#f} if the entry
15772 hasn't exist. The same function is called @code{hash-table-remove!} in STk
15773 (except that it returns an undefined value); I use `delete' for consistency
15774 to SRFI-1, SRFI-13 and other parts of the libraries.
15775
15776 Note: This is different from R7RS @code{hash-table-delete!}, so we provide
15777 R7RS interface with an alias @code{hash-table-delete!-r7}.
15778 @c JP
15779 ハッシュテーブル@code{ht}からキー@var{key}を持つエントリを削除します。
15780 @var{key}を持つエントリが実際に存在して削除された場合は@code{#t}を、
15781 エントリが存在しなかった場合は@code{#f}を返します。
15782 この手続きはSTkで@code{hash-table-remove!}と呼ばれているものです
15783 (STkのは戻り値が定義されていませんが)。GaucheではSRFI-1, SRFI-13やその他の
15784 ライブラリとの一貫性のために `delete' を採用しました。
15785
15786 註: これはR7RSの@code{hash-table-delete!}と異なります。
15787 R7RSインタフェースは@code{hash-table-delete!-r7}という別名で提供されます。
15788 @c COMMON
15789 @end defun
15790
15791 @defun hash-table-delete!-r7 ht key @dots{}
15792 @c EN
15793 Delets entries that have @var{key} @dots{} from the hash table @var{ht}.
15794 The @var{key} which isn't in @var{ht} has no effect. Returns the number
15795 of entries actually deleted.
15796
15797 This is called @code{hash-table-delete!} in R7RS, and so as in
15798 @code{scheme.hash-table}. We provide this under different name,
15799 for Gauche's @code{hash-table-delete!} returns a boolean value.
15800 @c JP
15801 @var{key} @dots{}を持つエントリをハッシュテーブル@var{ht}から削除します。
15802 @var{ht}に含まれなかったキーは単に無視されます。実際に削除されたエントリの数が返されます。
15803
15804 これはR7RSで@code{hash-table-delete!}と呼ばれており、
15805 @code{scheme.hash-table}でもその名前で提供されます。
15806 Gaucheの@code{hash-table-delete!}は真偽値を返すので、
15807 組み込みとしては別名で提供することにしました。
15808 @c COMMON
15809 @end defun
15810
15811 @defun hash-table-clear! ht
15812 [R7RS hash-table]
15813 @c EN
15814 Removes all entries in the hash table @var{ht}.
15815 @c JP
15816 ハッシュテーブル@var{ht}の全てのエントリを削除します。
15817 @c COMMON
15818 @end defun
15819
15820 @defun hash-table-push! ht key value
15821 @c EN
15822 Conses @var{value} to the existing value for the key @var{key} in the
15823 hash table @var{ht} and makes it the new value for @var{key}.
15824 If there's no entry for @var{key}, an entry
15825 is created with the value @code{(list @var{value})}.
15826
15827 Works the same as the following code, except that this function
15828 only looks up the @var{key} once, thus it's more efficient.
15829 @c JP
15830 ハッシュテーブル@var{ht}中の、キー@var{key}に対応する値に@var{value}をコンスし、
15831 それを@var{key}に対する新たな値とします。もし@var{key}に対応する値がまだ無ければ、
15832 新たなエントリが作成され、@code{(list @var{value})}がその値となります。
15833
15834 この手続きは次のコードと同じ動作をしますが、キーの探索が一度しか行われないためより高速です。
15835 @c COMMON
15836 @example
15837 (hash-table-put! @var{ht} @var{key}
15838 (cons @var{value} (hash-table-get @var{ht} @var{key} '())))
15839 @end example
15840 @end defun
15841
15842 @defun hash-table-pop! ht key :optional default
15843 @c EN
15844 Looks for the value for the key @var{key} in the hash table @var{ht}.
15845 If found and it is a pair, replaces the value for its cdr and returns
15846 car of the original value. If no entry for @var{key} is in the table,
15847 or the value is not a pair, the table is not modified and
15848 the procedure returns @var{default} if given, or signals an error otherwise.
15849
15850 During the operation the key is looked for only once, thus runs
15851 efficiently.
15852
15853 Note: R7RS has @code{hash-table-pop!} but its totally different.
15854 We provide R7RS version as an alias @code{hash-table-pop!-r7}
15855 @c JP
15856 ハッシュテーブル@var{ht}中のキー@var{key}に対応する値が存在し、かつペアで
15857 あった場合に、そのエントリーを元の値のcdrで置き換え、元の値のcarを返します。
15858 @var{key}に対応する値が存在しないかペアではなかった場合、テーブルは変更されず、
15859 @var{default}が与えられていればそれが返され、与えられていなければエラーが報告されます。
15860
15861 値が置き換えられる場合でもキーの探索は一度しか行われないため効率が良いです。
15862
15863 註:R7RSも@code{hash-table-pop!}を定義していますが、全く違う操作です。
15864 そこで、R7RSバージョンは@code{hash-table-pop!-r7}として提供しています。
15865 @c COMMON
15866 @end defun
15867
15868 @defun hash-table-pop!-r7 ht
15869 @c EN
15870 Removes one arbitrary entry from @var{ht}, and returns the removed
15871 entry's key and value as two values. If @var{ht} is empty, an error
15872 is thrown.
15873
15874 This is called @code{hash-table-pop!} in R7RS, and so as in
15875 @code{scheme.hash-table}.
15876 @c JP
15877 ハッシュテーブル@var{ht}中の任意のエントリをひとつ削除し、
15878 そのエントリのキーと値を二つの戻り値として返します。
15879 @var{ht}が空ならエラーが報告されます。
15880
15881 R7RSではこれが@code{hash-table-pop!}と呼ばれていて、
15882 @code{scheme.hash-table}でもその名前で提供されます。
15883 @c COMMON
15884 @end defun
15885
15886 @defun hash-table-update! ht key proc :optional default
15887 @c EN
15888 A more general version of @code{hash-table-push!} etc.
15889 It works basically as the following code piece,
15890 except that the lookup of @var{key} is only done once.
15891 @c JP
15892 @code{hash-table-push!}等のより一般的なバージョンです。
15893 ハッシュテーブルの探索が一度しか行われないことを除いては、
15894 基本的に次のように動作します。
15895 @c COMMON
15896 @example
15897 (let ((tmp (@var{proc} (hash-table-get @var{ht} @var{key} @var{default}))))
15898 (hash-table-put! @var{ht} @var{key} tmp)
15899 tmp)
15900 @end example
15901
15902 @c EN
15903 For example, when you use a hash table to count the occurrences
15904 of items, the following line is suffice to increment the counter
15905 of the item, regardless of whether @var{item} has already appeared or not.
15906 @c JP
15907 例えば、ハッシュテーブルを使ってオブジェクトの個数を数えているとしましょう。
15908 次の1行で、オブジェクト@var{item}が既に出現したかどうかを気にせずに
15909 その個数をインクリメントできます。
15910 @c COMMON
15911
15912 @example
15913 (hash-table-update! ht item (cut + 1 <>) 0))
15914 @end example
15915
15916 @c EN
15917 R7RS provides @code{hash-table-update!} with different interface,
15918 so we provide R7RS version as an alias @code{hash-table-update!-r7}.
15919 @c JP
15920 R7RSも@code{hash-table-update!}を定義していますが、インタフェースが異なるので、
15921 GaucheではR7RS版を別名@code{hash-table-update!-r7}として提供します。
15922 @c COMMON
15923 @end defun
15924
15925 @defun hash-table-update!-r7 ht key updater :optional failure success
15926 @c EN
15927 This is R7RS version of @code{hash-table-update!}. With no optional
15928 arguments, it works like Gauche's @code{hash-table-update!}. But in
15929 practice you often needs to specify the behavior when @var{key} hasn't
15930 been in @var{ht}, in which case R7RS differs from Gauche.
15931
15932 The R7RS version works like this but potentially more efficiently:
15933 @c JP
15934 これがR7RS版の@code{hash-table-update!}です。
15935 省略可能引数を全て省略した場合はGaucheの@code{hash-table-update!}と同じになりますが、
15936 実際には@var{key}が@var{ht}に無かった場合の振る舞いを指定する必要があることが多く、
15937 その場合R7RSのインタフェースはGaucheと異なってきます。
15938
15939 R7RS版は、効率を除けば次のとおり動作します。
15940 @c COMMON
15941
15942 @example
15943 (hash-table-put! ht key (updater (hash-table-ref ht key failure success)))
15944 @end example
15945 @end defun
15946
15947 @defun hash-table-update!/default ht key updater default
15948 [R7RS hash-table]
15949 @c EN
15950 This is the same as Gauche's @code{hash-table-update!}, except that
15951 the default value can't be omitted.
15952 @c JP
15953 これは@var{default}が省略できないことを除けば、
15954 Gaucheの@code{hash-table-update!}と同じです。
15955 @c COMMON
15956 @end defun
15957
15958 @c EN
15959 @subheading Hash table scanners
15960 @c JP
15961 @subheading ハッシュテーブルの走査
15962 @c COMMON
15963
15964 @defun hash-table-for-each ht proc
15965 @defunx hash-table-map ht proc
15966 @c EN
15967 A procedure @var{proc} is called with two arguments, a key and its associated
15968 value, over all the entries in the hash table @var{ht}.
15969 @c JP
15970 ハッシュテーブル@var{ht}内の全てのエントリについて、各エントリのキーと値を
15971 2つの引数として手続き@var{proc}を呼びます。
15972 @c COMMON
15973 @end defun
15974
15975 @defun hash-table-fold ht kons knil
15976 @c EN
15977 For all entries in the hash table @var{ht},
15978 a procedure @var{kons} is called with three arguments;
15979 a key, its associated value, and the previous return value of @var{kons}.
15980 The first call of @var{kons} receives @var{knil} as the third argument.
15981 The return value of the last call of @var{kons} is returned
15982 from @code{hash-table-fold}.
15983 @c JP
15984 ハッシュテーブル@var{ht}内の全てのエントリについて@var{kons}を呼びます。
15985 @var{kons}には3つの引数が渡されます。
15986 各エントリのキーと値、および一つ前の@var{kons}の返り値です。
15987 最初の@var{kons}の呼び出しの時には、第3引数に@var{knil}が渡されます。
15988 最後の@var{kons}の返り値が@code{hash-table-fold}の返り値となります。
15989 @c COMMON
15990 @end defun
15991
15992 @defun hash-table-find ht pred :optional failure
15993 @c EN
15994 Apply @var{pred} with each key and value in the hash table @var{ht}.
15995 Once @var{pred} returns a true value, that return value is immediately returned
15996 from @code{hash-table-find}.
15997 If no key-value satisfies @var{pred}, a thunk @var{failure} is
15998 invoked and its result is returned. If @var{failure} is
15999 omitted, @code{(lambda () #f)} is assumed.
16000 @c JP
16001 @var{pred}をハッシュテーブル@var{ht}の各エントリのキーと値を引数にして
16002 呼び出し、それが真の値を返したら直ちにそれを戻り値とします。
16003 @var{pred}を満たすキーと値が無ければ、無引数の手続き@var{failure}が呼び出され、
16004 その値が戻り値となります。@var{failure}が省略された場合は
16005 @code{(lambda () #f)}が使われます。
16006 @c COMMON
16007
16008 @c EN
16009 Note: The convention starting from SRFI-1 is that
16010 @code{*-find} returns an item in the collection that
16011 satisfy the predicate, while @code{*-any} returns a non-false
16012 value the predicate returns. SRFI-125 broke the convention.
16013 The justification given in SRFI-125 discussion
16014 was that the ``any'' semantics is strictly upper-compatible to the
16015 ``find'' semantics so we can combine two. So far, though, SRFI-125
16016 is the only exception of this convention.
16017 @c JP
16018 註: SRFI-1から始まった慣習では、@code{*-find}というAPIは
16019 述語を満たすようなコレクション内の要素を返し、@code{*-any}というAPIが
16020 述語が偽でない値を返した時にその値をそのまま返り値とします。
16021 SRFI-125が慣習を破った理由は、
16022 ``any''のセマンティクスで従来の ``find'' の動作もエミュレートできるので
16023 ``find''が ``any'' の動作も兼ねてしまえばよいというものです。
16024 しかし、現在までのところ、この慣習を破っているのはSRFI-125のみです。
16025 @c COMMON
16026
16027 @example
16028 @c EN
16029 ;; Find if hash tables ha and hb has a common key.
16030 @c JP
16031 ;; ハッシュテーブルhaとhbに共通のキーがあるかどうか調べる
16032 @c COMMON
16033 (hash-table-find ha (^[k v] (hash-table-exists? hb k)))
16034 @end example
16035 @end defun
16036
16037 @defun hash-table-keys ht
16038 @defunx hash-table-values ht
16039 @c EN
16040 Returns all the keys or values of hash table @var{ht} in a list,
16041 respectively.
16042 @c JP
16043 それぞれ、ハッシュテーブル@var{ht}内の全てのキーまたは値をリストにして返します。
16044 @c COMMON
16045 @end defun
16046
16047 @c EN
16048 @subheading Hash table as sets
16049 @c JP
16050 @subheading 集合としてのハッシュテーブル
16051 @c COMMON
16052
16053 @defun hash-table-compare-as-sets ht1 ht2 :optional value=? fallback
16054 @c EN
16055 A hash table can be viewed as a set of pairs of key and value.
16056 This procedure compares two hash tables @var{ht1} and @var{ht2} as such
16057 sets.
16058
16059 The key comparators of two tables must match (in terms of @code{equal?}
16060 of the comparators). Otherwise, an error is signaled.
16061
16062 Two elements of the set are equal to each other iff their keys match
16063 with the equality predicate of the key comparator, and their values
16064 match with @var{value=?} procedure. If omitted, @code{equal?} is
16065 used for @var{value=?}
16066 @c JP
16067 ハッシュテーブルは、キーと値の組を要素とする集合とみなすことができます。
16068 この手続きは二つのハッシュテーブル@var{ht1}と@var{ht2}を集合として比較します。
16069
16070 二つのハッシュテーブルのキー比較器は同じ (@code{equal?}の意味で)
16071 でなければなりません。そうでない場合はエラーが投げられます。
16072
16073 二つの要素は、キー同士がキー比較器によって等価と判断され、かつ
16074 値同士が@var{value=?}手続きによって等価と判断された場合に等しいとみなされます。
16075 @var{value=?}が省略された場合は@code{equal?}が使われます。
16076 @c COMMON
16077
16078 @c EN
16079 There can be four cases.
16080 @itemize
16081 @item
16082 If @var{ht1} is a pure subset of @var{ht2}, returns -1 (@var{ht1} is smaller
16083 than @var{ht2}).
16084 @item
16085 If @var{ht2} is a pure subset of @var{ht1}, returns 1 (@var{ht1} is greater
16086 than @var{ht2}).
16087 @item
16088 If @var{ht1} and @var{ht2} contains exactly the same elements,
16089 returns 0 (@var{ht1} equals to @var{ht2}).
16090 @item
16091 Neither @var{ht1} nor @var{ht2} is a subset of another. In this case,
16092 @var{fallback} is returned if it is given, or an error is thrown.
16093 @end itemize
16094 @c JP
16095 4通りの結果が有り得ます。
16096 @itemize
16097 @item
16098 @var{ht1}が@var{ht2}の純粋部分集合である場合は-1が返されます
16099 (@var{ht1} < @var{ht2})。
16100 @item
16101 @var{ht2}が@var{ht1}の純粋部分集合である場合は1が返されます
16102 (@var{ht1} > @var{ht2})。
16103 @item
16104 @var{ht1}と@var{ht2}がまったく同じだけの要素を含んでいる場合は0が返されます
16105 (@var{ht1} = @var{ht2})。
16106 @item
16107 @var{ht1}と@var{ht2}がお互いに相手の部分集合でない場合は、
16108 @var{fallback}が与えられていればそれが返され、
16109 省略された場合はエラーが投げられます。
16110 @end itemize
16111 @c JP
16112 @c COMMON
16113 @end defun
16114
16115 @defun hash-table=? value-cmpr ht1 ht2
16116 [R7RS hash-table]
16117 @c EN
16118 This also compares two hash tables @var{ht1} and @var{ht2} as sets,
16119 and returns true iff two are the same. That is, every element in @var{ht1}
16120 is also in @var{ht2} and vice versa.
16121
16122 Two element are the same iff their keys are the same in terms of
16123 the equality predicate of the tables' key comparator, and their values
16124 are the same in terms of the equality predicate of a comparator
16125 @var{value-cmpr}.
16126
16127 It is an error if @var{ht1} and @var{ht2} has different key comparators.
16128 See also @code{hash-table-compare-as-sets} above.
16129 @c JP
16130 この手続きも@var{ht1}と@var{ht2}を集合として比較し、
16131 二つのテーブルが等しい集合である場合、つまり@var{ht1}の要素がすべて@var{ht2}の要素でもあり、
16132 またその逆も真である場合に@code{#t}を、そうでなければ@code{#f}を返します。
16133
16134 二つの要素は、キー同士がキー比較器によって等価と判定され、かつ
16135 また値同士が比較器@var{value-cmpr}によって等価と判定された場合に
16136 等しいとみなされます。
16137
16138 @var{ht1}と@var{ht2}のキー比較器が異なっていた場合はエラーが投げられます。
16139 上の@code{hash-table-compare-as-sets}も参照してください。
16140 @c COMMON
16141 @end defun
16142
16143 @defun hash-table-union! ht1 ht2
16144 @defunx hash-table-intersection! ht1 ht2
16145 @defunx hash-table-difference! ht1 ht2
16146 @defunx hash-table-xor! ht1 ht2
16147 [R7RS hash-table]
16148 @c EN
16149 Perform set operations on two hashtables @var{ht1} and @var{ht2},
16150 and modify @var{ht1} to store the result.
16151 Note that these procedures only look at the keys for operation; if
16152 the values of the same key differ between @var{ht1} and @var{ht2},
16153 the value in @var{ht1} is taken.
16154 @c JP
16155 二つのハッシュテーブル間で集合演算を行い、結果を@var{ht1}に格納します。
16156 これらの手続きでは、集合の要素としてキーだけを見ます。
16157 もし同じキーを持つ要素の値が@var{ht1}と@var{ht2}で異なっていた場合、
16158 @var{ht1}の値が優先されます。
16159 @c COMMON
16160
16161 @itemize
16162 @item
16163 @c EN
16164 The union operation picks each entry that is in at least one of @var{ht1}
16165 or @var{ht2}.
16166 @c JP
16167 unionは、@var{ht1}か@var{ht2}の少なくとも一方に入っている要素を集めます。
16168 @c COMMON
16169 @item
16170 @c EN
16171 The intersection operation picks each entry that is both in @var{ht1} and
16172 @var{ht2}.
16173 @c JP
16174 intersectionは、@var{ht1}と@var{ht2}の両方に含まれる要素のみを集めます。
16175 @c COMMON
16176 @item
16177 @c EN
16178 The difference operation picks each entry that is in @var{ht1} but
16179 not in @var{ht2}.
16180 @c JP
16181 differenceは、@var{ht1}に含まれるが@var{ht2}には含まれない要素のみを集めます。
16182 @c COMMON
16183 @item
16184 @c EN
16185 The xor operation picks each entry that is in only one of @var{ht1} or
16186 @var{ht2}, but not in both.
16187 @c JP
16188 xorは、@var{ht1}か@var{ht2}の一方のみに含まれる要素のみを集めます。
16189 @c COMMON
16190 @end itemize
16191 @end defun
16192
16193
16194 @c ----------------------------------------------------------------------
16195 @node Treemaps, , Hashtables, Dictionaries
16196 @subsection Treemaps
16197 @c NODE ツリーマップ
16198
16199 @deftp {Builtin Class} <tree-map>
16200 @clindex tree-map
16201 @c EN
16202 Tree map class. Tree maps are a data structure that maps key objects
16203 to value objects. It's like hash tables except tree maps uses
16204 balanced tree internally. Insertion and lookup is O(log n).
16205 @c JP
16206 ツリーマップクラス。ツリーマップはキーオブジェクトから値オブジェクトへ
16207 の写像をあらわすデータ構造です。ツリーマップでは平衡木を使うということ
16208 以外はハッシュテーブルと同じです。ツリーマップでは挿入と検索の手間は
16209 O(log n)です。
16210 @c COMMON
16211
16212 @c EN
16213 Unlike hashtables, a tree map keeps the order of the keys, so
16214 it is easy to traverse entries in the order of keys, to find
16215 minimum/maximum keys, or to find a key closest to the given value.
16216 @c JP
16217 ハッシュテーブルとはちがい、キーの順序は保存されます。したがってキーの
16218 順序どおりにトラバースするのは簡単で、キーの最小値/最大値を見つけたり、
16219 指定したキーにもっとも近いキーを探すのも簡単です。
16220 @c COMMON
16221
16222 @c EN
16223 The @code{<tree-map>} class inherits @code{<sequence>} and
16224 @code{<ordered-dictionary>}.
16225 @c JP
16226 @code{<tree-map>}クラスは@code{<sequence>}および
16227 @code{<ordered-dictionary>}を継承しています。
16228 @c COMMON
16229 @end deftp
16230
16231 @defun make-tree-map :optional comparator
16232 @defunx make-tree-map key=? key<?
16233 @c EN
16234 Creates and returns an instance of @code{<tree-map>}.
16235 The keys are compared by @var{comparator},
16236 whose default is @code{default-comparator}.
16237 The comparator must have a comparison procedure, for
16238 we need a total order in the keys.
16239 @xref{Basic comparators}, for the details.
16240
16241 For the backward compatibility, @code{make-tree-map} also
16242 accepts a procedure as a @var{comparator}; the procedure must
16243 take two keys and returns either @code{-1}, @code{0}, or @code{1},
16244 depending on whether the first key is less than, equal to, or
16245 greater than the second key, respectively. In other words, it
16246 is a comparison procedure of a comparator.
16247
16248 The second form of @code{make-tree-map} is also for the
16249 backward compatibility; it takes two procedures, each must
16250 be a procedure that takes two keys; the first one returns
16251 @code{#t} iff two keys are equal, and the second one returns
16252 @code{#t} iff the first key is strictly smaller than the second.
16253 @c JP
16254 @code{<tree-map>}オブジェクトを作成して返します。
16255 キーは比較器@var{comparator}を使って比較されます。@var{comparator}の
16256 デフォルト値は@code{default-comparator}です。キーには全順序関係が必要なので、
16257 比較器は比較手続きを持っていなければなりません。
16258 詳しくは@ref{Basic comparators}を参照してください。
16259
16260 互換性のため、@code{make-tree-map}は@var{comparator}引数に
16261 単なる手続きを取ることもできます。渡される手続きは2引数を取り、
16262 最初の引数が2番目の引数より小さいか、等しいか、大きいかに応じて
16263 @code{-1}、@code{0}、@code{1}をそれぞれ返します。つまり
16264 この手続きは比較器の比較手続きそのものです。
16265
16266 @code{make-tree-map}の2番目の呼び出し形式も互換性のためのものです。
16267 それぞれ2引数の2つの手続きを取り、
16268 最初の手続き@var{key=?}は、2つのキーが等しい場合にのみ真を返し、
16269 2番目の手続き@var{key<?}は、最初のキーが2番目のキーより前にある(小さい)場合にのみ
16270 真を返すようにします。
16271 @c COMMON
16272 @end defun
16273
16274 @defun tree-map-comparator tree-map
16275 @c EN
16276 Returns the comparator used in the tree map.
16277 @c JP
16278 @var{tree-map}で使われている比較器を返します。
16279 @c COMMON
16280 @end defun
16281
16282 @defun tree-map-copy tree-map
16283 @c EN
16284 Copies and returns @var{tree-map}. Modification
16285 on the returned tree doesn't affect the original tree.
16286 @c JP
16287 @var{tree-map}のコピーを作り、それを返します。返された木に対す
16288 る破壊的操作は、元の木に影響を与えません。
16289 @c COMMON
16290 @end defun
16291
16292 @defun tree-map-empty? tree-map
16293 @c EN
16294 Returns @code{#t} if @var{tree-map} doesn't have any elements,
16295 or @code{#f} otherwise.
16296 @c JP
16297 @var{tree-map}が要素を持たないなら@code{#t}を、そうでなければ@code{#f}を
16298 返します。
16299 @c COMMON
16300 @end defun
16301
16302 @defun tree-map-num-entries tree-map
16303 @c EN
16304 Returns the number of elements in @var{tree-map}.
16305 @c JP
16306 @var{tree-map}内の要素の個数を返します。
16307 @c COMMON
16308 @end defun
16309
16310 @defun tree-map-exists? tree-map key
16311 @c EN
16312 Returns @code{#t} if @var{tree-map} has an entry with @var{key},
16313 or @code{#f} otherwise.
16314 @c JP
16315 @var{tree-map}にキー@var{key}を持つエントリがあれば@code{#t}を、
16316 そうでなければ@code{#f}を返します。
16317 @c COMMON
16318 @end defun
16319
16320 @defun tree-map-get tree-map key :optional fallback
16321 @c EN
16322 Looks for @var{key} in @var{tree-map}. If the entry is found,
16323 returns a value corresponding to the key. Otherwise, returns
16324 @var{fallback} if it is provided, or signals an error.
16325 @c JP
16326 キー@var{key}を@var{tree-map}から探します。見つかれば@var{key}に対応する値を返
16327 します。キーが見つからなかった場合、@var{fallback}が与えられていればそれ
16328 を返し、そうでなければエラーを報告します。
16329 @c COMMON
16330 @end defun
16331
16332 @defun tree-map-put! tree-map key value
16333 @c EN
16334 Inserts an entry with a @var{key} and corresponding @var{value}
16335 into @var{tree-map}. If there already exists an entry with a
16336 key which is equivalent (under @var{key=?}), the entry is modified
16337 to have @var{value}.
16338 @c JP
16339 キー@var{key}と対応する値@var{value}を@var{tree-map}に挿入します。もし、@var{key}と、
16340 @var{key=?}における意味で同じキーがすでに存在する場合、キーに対応する値
16341 は新たな値に置き換えられます。
16342 @c COMMON
16343 @end defun
16344
16345 @defun tree-map-delete! tree-map key
16346 @c EN
16347 Deletes an entry with @var{key} from @var{tree-map} if such an entry
16348 exists, and returns @code{#t}.
16349 If @var{tree-map} doesn't have such an entry, @code{#f} is returned.
16350 @c JP
16351 @var{tree-map}からキー@var{key}を持つエントリを削除します。@var{key}を持つエン
16352 トリが実際に存在して削除された場合は@code{#t}を、エントリが存在しなかっ
16353 た場合は@code{#f}を返します。
16354 @c COMMON
16355 @end defun
16356
16357 @defun tree-map-clear! tree-map
16358 @c EN
16359 Removes all entries in @var{tree-map}.
16360 @c JP
16361 @var{tree-map}内の全てのエントリを削除します。
16362 @c COMMON
16363 @end defun
16364
16365 @defun tree-map-update! tree-map key proc :optional fallback
16366 @c EN
16367 A generalized version of @code{tree-map-push!} etc.
16368 It works like the following code, except that searching
16369 for the key is done only once.
16370 @c JP
16371 @code{tree-map-push!}等のより一般的なバージョンです。木の探索が一度
16372 しか行われないことを除いては、基本的に次のように動作します。
16373 @c COMMON
16374 @example
16375 (let ((tmp (proc (tree-map-get @var{tree-map} @var{key} @var{fallback}))))
16376 (tree-map-put! @var{tree-map} @var{key} tmp)
16377 tmp)
16378 @end example
16379 @end defun
16380
16381 @defun tree-map-push! tree-map key value
16382 @c EN
16383 Looks for an entry with @var{key} in @var{tree-map}. If it exists,
16384 the procedure conses @var{value} to the original value and makes
16385 it as a new value.
16386 Otherwise, the procedure creates a new entry for the @var{key}
16387 and makes @code{(list @var{value})} its value.
16388 @c JP
16389 @var{tree-map}中の、キー@var{key}に対応する値に@var{value}をコンスし、
16390 それを@var{key}
16391 に対する新たな値とします。もし@var{key}に対応する値がまだ無ければ、新た
16392 なエントリが作成され、@code{(list @var{value})}がその値となります。
16393 @c COMMON
16394 @end defun
16395
16396 @defun tree-map-pop! tree-map key :optional fallback
16397 @c EN
16398 Looks for an entry with @var{key} in @var{tree-map}. If it exists
16399 and its value is a pair, then the procedure updates
16400 its value with @code{cdr} of the original value, and returns
16401 @code{car} of the original entry. If such an entry does not
16402 exist, or has a non-pair value, the procedure doesn't
16403 modify @var{tree-map} and returns @var{fallback} if it is given,
16404 otherwise reports an error.
16405 @c JP
16406 @var{tree-map}中のキー@var{key}に対応する値が存在し、かつペアであった場合
16407 に、そのエントリの値を元の値のcdrで置き換え、元の値のcarを返します。
16408 @var{key}に対応する値が存在しないかペアではなかった場合、@var{tree-map}は
16409 変更されず、@var{fallback}が与えられていればそれが返され、与えられていな
16410 ければエラーが報告されます。
16411 @c COMMON
16412 @end defun
16413
16414 @defun tree-map-min tree-map
16415 @defunx tree-map-max tree-map
16416 @c EN
16417 Returns a pair of a key and its value with the minimum
16418 or maximum key, respectively. If @var{tree-map} is empty,
16419 @code{#f} is returned.
16420 @c JP
16421 それぞれ、@var{tree-map}に含まれる最小および最大のキーを探索し、その
16422 キーと値のペアを返します。@var{tree-map}が空だった場合は@code{#f}が返されます。
16423 @c COMMON
16424 @end defun
16425
16426 @defun tree-map-pop-min! tree-map
16427 @defunx tree-map-pop-max! tree-map
16428 @c EN
16429 Looks for an entry with minimum or maximum key, respectively,
16430 then deletes the entry from @var{tree-map} and returns
16431 a pair of the key and its value of the original entry.
16432 If @var{tree-map} is empty, @code{#f} is returned.
16433 @c JP
16434 それぞれ、@var{tree-map}に含まれる最小および最大のキーを探索し、そ
16435 のエントリを@var{tree-map}から削除したうえで、そのキーと値のペアを
16436 返します。@var{tree-map}が空だった場合は@code{#f}が返されます。
16437 @c COMMON
16438 @end defun
16439
16440 @defun tree-map-fold tree-map proc seed
16441 @defunx tree-map-fold-right tree-map proc seed
16442 @c EN
16443 Iterate over elements in @var{tree-map}, applying
16444 @var{proc} which has a type @code{(key, value, seed) -> seed}.
16445 The difference of @code{tree-map-fold} and @code{tree-map-fold-right}
16446 is the associative order of applying @var{proc},
16447 just like the difference between @code{fold} and @code{fold-right}.
16448 @c JP
16449 @var{tree-map}の各要素に対し、@code{(key, value, seed) -> seed} の型を持つ
16450 @var{proc}を適用してゆきます。
16451 @code{tree-map-fold}と@code{tree-map-fold-right}の違いは
16452 @code{fold}の@code{fold-right}違いと同じ、すなわち
16453 結合の方向にあります。
16454 @c COMMON
16455 @example
16456 tree-map-fold:
16457 (proc Kn Vn (proc Kn-1 Vn-1 ... (proc K0 V0 seed)))
16458
16459 tree-map-fold-right
16460 (proc K0 V0 (proc K1 V1 ... (proc Kn Vn seed)))
16461 @end example
16462
16463 @c EN
16464 Some examples:
16465 @c JP
16466 例:
16467 @c COMMON
16468 @example
16469 (define tree (alist->tree-map '((3 . a) (7 . b) (5 . c)) = <))
16470
16471 (tree-map-fold tree list* '())
16472 @result{} (7 b 5 c 3 a)
16473 (tree-map-fold-right tree list* '())
16474 @result{} (3 a 5 c 7 b)
16475 @end example
16476 @end defun
16477
16478 @defun tree-map-map tree-map proc
16479 @c EN
16480 Calls @var{proc}, which must take two arguments,
16481 with each key/value pair in @var{tree-map},
16482 and collect the results into a list and returns it. The order
16483 of results corresponds to the order of keys---that is, the first element
16484 of the result list is what @var{proc} returns with minimum key and its value,
16485 and the last element of the result list is what @var{proc} returns
16486 with the maximum key and its value.
16487 (Note: Like @code{map}, the order that @var{proc} is actually called
16488 is unspecified; @var{proc} is better to be side-effect free.)
16489 @c JP
16490 2引数を取る手続き@var{proc}を、@var{tree-map}の各キーおよび値のペアに
16491 対して呼び出し、結果をリストにして返します。
16492 結果のリストは、キーの昇順に並んでいます。つまり、最小のキーとその値で呼び出した
16493 @var{proc}の結果が最初の要素に、最大のキーとその値で呼び出した@var{proc}の
16494 結果が最後の要素になります。
16495 (@code{map}と同様、実際に@var{proc}が呼ばれる順序は保証されていません。
16496 したがって@var{proc}は副作用の無いものにすべきです)。
16497 @c COMMON
16498 @end defun
16499
16500 @defun tree-map-for-each tree-map proc
16501 @c EN
16502 Calls @var{proc}, which must take two arguments,
16503 with each key/value pair in @var{tree-map},
16504 in the increasing order of the keys. @var{proc} is called purely
16505 for side effects; the returned values are discarded.
16506 @c JP
16507 2引数を取る手続き@var{proc}を、@var{tree-map}の各キーおよび値のペアに対して、
16508 キーの昇順に呼び出します。@var{proc}は副作用のためだけに呼ばれ、結果は捨てられます。
16509 @c COMMON
16510 @end defun
16511
16512 @defun tree-map-floor tree-map probe :optional fallback-key fallback-value
16513 @defunx tree-map-ceiling tree-map probe :optional fallback-key fallback-value
16514 @defunx tree-map-predecessor tree-map probe :optional fallback-key fallback-value
16515 @defunx tree-map-successor tree-map probe :optional fallback-key fallback-value
16516 @c EN
16517 These procedures search the entry which has the closest key
16518 to the given @var{probe}. If such an entry is found, returns
16519 two values, its key and its value. Otherwise, returns two values,
16520 @var{fallback-key} and @var{fallback-value}, both defaulted to @code{#f}.
16521
16522 The criteria of ``closest'' differ slightly among these procedures;
16523 @code{tree-map-floor} finds the maximum key which is no greater than
16524 @var{probe}; @code{tree-map-ceiling} finds the minimum key which is
16525 no less than @var{probe}; @code{tree-map-predecessor} finds the
16526 maximum key which is strictly less than @var{probe};
16527 and @code{tree-map-successor} finds the minimum key which
16528 is strictly greater than @var{probe}.
16529 @c JP
16530 これらの手続きは、@var{probe}に最も近いキーを持つエントリを@var{tree-map}から
16531 探します。そのようなエントリが見つかれば、該当するキーと値が2つの戻り値となります。
16532 見つからない場合は、@var{fallback-key}と@var{fallback-value}が
16533 2つの戻り値として返されます。それぞれの省略時の値は@code{#f}です。
16534
16535 それぞれの手続きは異なった「最も近い」の基準を持っています。
16536 @code{tree-map-floor}は@var{probe}以下で最大のキーを、
16537 @code{tree-map-ceiling}は@var{probe}以上で最小のキーを、
16538 @code{tree-map-predecessor}は@var{probe}未満で最大のキーを、
16539 @code{tree-map-successor}は@var{probe}を越える最小のキーを探します。
16540 @c COMMON
16541 @end defun
16542
16543 @defun tree-map-floor-key tree-map probe @var{optional} fallback-key
16544 @defunx tree-map-ceiling-key tree-map probe @var{optional} fallback-key
16545 @defunx tree-map-predecessor-key tree-map probe @var{optional} fallback-key
16546 @defunx tree-map-successor-key tree-map probe @var{optional} fallback-key
16547 @c EN
16548 Like @code{tree-map-floor} etc., but only returns the key of
16549 the found entry (or @var{fallback-key} if there's no entry which satisfies
16550 the criteria).
16551 @c JP
16552 @code{tree-map-floor}等と同様ですが、見つかったエントリのキーのみを返します。
16553 該当エントリが見つからない場合は@var{fallback-key}の値(デフォルトは@code{#f})が
16554 返されます。
16555 @c COMMON
16556 @end defun
16557
16558 @defun tree-map-floor-value tree-map probe @var{optional} fallback-value
16559 @defunx tree-map-ceiling-value tree-map probe @var{optional} fallback-value
16560 @defunx tree-map-predecessor-value tree-map probe @var{optional} fallback-value
16561 @defunx tree-map-successor-value tree-map probe @var{optional} fallback-value
16562 @c EN
16563 Like @code{tree-map-floor} etc., but only returns the value of
16564 the found entry (or @var{fallback-value} if there's no entry which satisfies
16565 the criteria).
16566 @c JP
16567 @code{tree-map-floor}等と同様ですが、見つかったエントリの値のみを返します。
16568 該当エントリが見つからない場合は@var{fallback-value}の値(デフォルトは@code{#f})が
16569 返されます。
16570 @c COMMON
16571 @end defun
16572
16573 @defun tree-map->generator/key-range tree-map :key > >= < <= descending
16574 @c EN
16575 Returns a generator (@pxref{Generators}) that yields pairs of key and value
16576 such that the key is in the specified range.
16577 If the @var{descending} keyword argument is @code{#f} (default),
16578 it yields the pairs with increasing keys; otherwise,
16579 it yields them with descending keys.
16580
16581 The keyword argument @code{>} and @code{>=} specifies the lower bound
16582 of the key, including and excluding the given key value itself, respectively.
16583 If both are given, either one of them is considered.
16584
16585 The keyword argument @code{<} and @code{<=} specifies the upper bound
16586 of the key, including and excluding the given key value itself, respectively.
16587 If both are given, either one of them is considered.
16588 @c JP
16589 キーが指定された範囲に入っているようなキーと値のペアを生成するジェネレータを作って
16590 返します (@ref{Generators}参照)。
16591 もし@var{descending}キーワード引数が@code{#f}(デフォルト値)なら、ペアは
16592 キーの昇順に生成されます。それが真の値なら、ペアはキーの降順に生成されます。
16593
16594 キーワード引数@code{>}と@code{>=}はキーの下限を指定します。前者は指定値を含み、
16595 後者は含みません。両方指定された場合はどちらかひとつだけが有効です。
16596
16597 キーワード引数@code{<}と@code{<=}はキーの下限を指定します。前者は指定値を含み、
16598 後者は含みません。両方指定された場合はどちらかひとつだけが有効です。
16599 @c COMMON
16600
16601 @example
16602 (define tm (alist->tree-map '((0 . a) (1 . b) (2 . c) (3 . d) (4 . e))
16603 default-comparator))
16604
16605
16606 (use gauche.generator)
16607
16608 (generator->list
16609 (tree-map->generator/key-range tm :>= 1 :< 4))
16610 @result{} ((1 . b) (2 . c) (3 . d))
16611
16612 (generator->list
16613 (tree-map->generator/key-range tm :>= 1 :< 4 :descending #t))
16614 @result{} ((3 . d) (2 . c) (1 . b))
16615
16616 (generator->list
16617 (tree-map->generator/key-range tm :<= 2))
16618 @result{} ((0 . a) (1 . b) (2 . c))
16619
16620 (generator->list
16621 (tree-map->generator/key-range tm :> 2))
16622 @result{} ((3 . d) (4 . e))
16623 @end example
16624 @end defun
16625
16626
16627 @defun tree-map-keys tree-map
16628 @defunx tree-map-values tree-map
16629 @c EN
16630 Returns a list of all keys and all values, respectively.
16631 The keys and values are in ascending order of the keys.
16632 @c JP
16633 それぞれ、@var{tree-map}内の全てのキーまたは値をリストにして返しま
16634 す。返されるリストの要素はキーの昇順に並んでいます。
16635 @c COMMON
16636 @end defun
16637
16638 @defun tree-map->alist tree-map
16639 @c EN
16640 Returns a list of pairs of keys and values for all entries.
16641 The pairs are in ascending order of the keys.
16642 @c JP
16643 @var{tree-map}含まれる要素を連想リストにして返します。返される連
16644 想リストのキーは昇順に並んでいます。
16645 @c COMMON
16646 @end defun
16647
16648 @defun alist->tree-map alist :optional comparator
16649 @defunx alist->tree-map alist key=? key<?
16650 @c EN
16651 Creates a new tree map with the @var{comparator} or
16652 @var{key=?}/@var{key<?} procedures, then
16653 populates it with @var{alist}, each pair in which are
16654 interpreted as a cons of a key and its value.
16655 The meaning of @var{comparator}, @var{key=?} and @var{key<?} are
16656 the same as @code{make-tree-map}.
16657 @c JP
16658 @var{comparator}または@var{key=?}, @var{key<?} によって新たなtreemapを作成し、
16659 連想リスト@var{alist}に含まれる要素を追加した上で返します。
16660 @var{alist}の各ペアのcarがキーに、cdrが値に使われます。
16661 @var{comparator}, @var{key=?}, @code{key<?}引数の意味は
16662 @code{make-tree-map}と同じです。
16663 @c COMMON
16664 @end defun
16665
16666 @c EN
16667 The following two procedures compares two tree maps with slightly different
16668 views.
16669 @c JP
16670 以下の二つの手続きは二つのツリーマップを比較しますが、見方が異なります。
16671 @c COMMON
16672
16673 @defun tree-map-compare-as-sets tree-map1 tree-map2 :optional value=? fallback
16674 @c EN
16675 Compares two tree maps as sets of entries. If we look at tree maps
16676 as sets of entries, we can define a partial order between two maps;
16677 they are equal to each other if they have exactly the same entries,
16678 and tree-map A is smaller than tree-map B if A us a strict subset of B.
16679
16680 If @var{tree-map1} and @var{tree-map2} are the same, 0 is
16681 returned. If @var{tree-map1} is smaller than @var{tree-map2}, -1
16682 is returned. If @var{tree-map1} is greater than @var{tree-map2}, 1
16683 is returned.
16684
16685 If one argument isn't subset of the other, we can't determine the order.
16686 In such a case, if @var{fallback} is given, it is returned. Otherwise,
16687 an error is signalled.
16688
16689 The comparators of @var{tree-map1} and @var{tree-map2} must be
16690 the same (@code{equal?}), otherwise an error is signalled.
16691 @xref{Basic comparators}, about the comparators.
16692
16693 An entry is equal to another entry if their keys match in terms
16694 of the comparator of the tree-map, and also their values match
16695 with the provided @var{value=?} predicate, which is defaulted to
16696 @code{equal?}.
16697 @c JP
16698 二つのツリーマップを、エントリの集合として比較します。エントリの集合として見れば、
16699 ツリーマップ間に半順序関係を定義できます。すなわち、全てのエントリが等しければ
16700 ツリーマップ同士も等しく、ツリーマップAがツリーマップBの真部分集合であれば
16701 AはBより小さい、とします。
16702
16703 @var{tree-map1}と@var{tree-map2}が等しければ0が、
16704 @var{tree-map1}の方が@var{tree-map2}より小さければ-1が、
16705 @var{tree-map1}の方が@var{tree-map2}より大きければ1が返されます。
16706
16707 どちらのツリーマップも相手の部分集合になっていない場合は、順序が決められません。
16708 その場合、@var{fallback}引数が与えられていればその値が返され、
16709 与えられていなければエラーが報告されます。
16710
16711 @var{tree-map1}と@var{tree-map2}の比較器は@code{equal?}の意味で
16712 等しくなければなりません。比較器については@ref{Basic comparators}を参照してください。
16713
16714 エントリは、それぞれのキーがツリーマップの比較器による比較で等しく、
16715 かつ対応する値が@var{value=?}手続きによる比較で等しい場合にのみ等しいとみなされます。
16716 @var{value=?}が省略された場合は@code{equal?}が使われます。
16717 @c COMMON
16718
16719 @example
16720 (tree-map-compare-as-sets
16721 (alist->tree-map '((1 . a) (2 . b) (3 . c)) default-comparator)
16722 (alist->tree-map '((3 . c) (1 . a) (2 . b)) default-comparator))
16723 @result{} 0
16724
16725 (tree-map-compare-as-sets
16726 (alist->tree-map '((1 . a) (3 . c)) default-comparator)
16727 (alist->tree-map '((3 . c) (1 . a) (2 . b)) default-comparator))
16728 @result{} -1
16729
16730 (tree-map-compare-as-sets
16731 (alist->tree-map '((1 . a) (3 . c) (4 . d) (2 . b)) default-comparator)
16732 (alist->tree-map '((3 . c) (1 . a) (2 . b)) default-comparator))
16733 @result{} 1
16734
16735 (tree-map-compare-as-sets
16736 (alist->tree-map '((1 . a) (3 . c) (4 . d)) default-comparator)
16737 (alist->tree-map '((3 . c) (1 . a) (2 . b)) default-comparator))
16738 @result{} ERROR: tree-maps can't be ordered
16739
16740 (tree-map-compare-as-sets
16741 (alist->tree-map '((1 . a) (3 . c) (4 . d)) default-comparator)
16742 (alist->tree-map '((3 . c) (1 . a) (2 . b)) default-comparator)
16743 eq?
16744 #f)
16745 @result{} #f
16746 @end example
16747 @end defun
16748
16749 @defun tree-map-compare-as-sequences tree-map1 tree-map2 :optional value-cmp
16750 @c EN
16751 Compares two tree maps as sequence of entries, ordered by keys.
16752 If both maps have entries with the same key, we use a comparator
16753 @var{value-cmp} to break the tie (naturally, @var{value-cmp} must
16754 have ordering predicate.)
16755 If @var{value-cmp} is omitted, @code{default-comparator} is used.
16756
16757 The comparators of @var{tree-map1} and @var{tree-map2} must be
16758 the same (@code{equal?}), otherwise an error is signalled.
16759 @xref{Basic comparators}, about the comparators.
16760
16761 If @var{tree-map1} and @var{tree-map2} are the same, 0 is
16762 returned. If @var{tree-map1} is smaller than @var{tree-map2}, -1
16763 is returned. If @var{tree-map1} is greater than @var{tree-map2}, 1
16764 is returned.
16765
16766 Unlike @code{tree-map-compare-as-sets}, this procedure defines total order
16767 of tree maps which share the same comparator.
16768 @c JP
16769 二つのツリーマップを、キーの順序で並べられたエントリのシーケンスとして比較します。
16770 両マップにキーが同じであるエントリがあった場合は、
16771 対応する値同士を@var{value-cmp}比較器で比べます
16772 (従って、@var{value-cmp}は比較述語を持っていなければなりません。)
16773 @var{value-cmp}が省略された場合は@code{default-comparator}が使われます。
16774
16775 @var{tree-map1}と@var{tree-map2}の比較器は@code{equal?}の意味で
16776 等しくなければなりません。比較器については@ref{Basic comparators}を参照してください。
16777
16778 @var{tree-map1}と@var{tree-map2}が等しければ0が、
16779 @var{tree-map1}の方が@var{tree-map2}より小さければ-1が、
16780 @var{tree-map1}の方が@var{tree-map2}より大きければ1が返されます。
16781
16782 @code{tree-map-compare-as-sets}と異なり、
16783 この手続きは比較器が同じであるようなツリーマップについて全順序関係を定義します。
16784 @c COMMON
16785
16786 @example
16787 (tree-map-compare-as-sequences
16788 (alist->tree-map '((1 . a) (3 . c)) default-comparator)
16789 (alist->tree-map '((3 . c) (2 . b)) default-comparator))
16790 @result{} -1
16791
16792 (tree-map-compare-as-sequences
16793 (alist->tree-map '((2 . b) (3 . d)) default-comparator)
16794 (alist->tree-map '((3 . c) (2 . b)) default-comparator))
16795 @result{} 1
16796 @end example
16797 @end defun
16798
16799 @c ----------------------------------------------------------------------
16800 @node Procedures and continuations, Parameters and dynamic states, Dictionaries, Core library
16801 @section Procedures and continuations
16802 @c NODE 手続きと継続
16803
16804 @c EN
16805 In Scheme, @emph{procedures} are fundamental blocks to build
16806 a program (@pxref{Making procedures}).
16807 A procedure represents a certain computation,
16808 possibly parameterized, and can be @emph{applied} to the actual
16809 arguments to execute the computation. Scheme also provides
16810 the means to extract the continuation of the current computation
16811 and wraps it in a procedure (@pxref{Continuations}).
16812 @c JP
16813 Schemeでは、プログラムを組み立てる最も基本となるブロックが@emph{手続き}です
16814 (@ref{Making procedures}も参照)。
16815 手続きは、特定の計算を表現します。引数を取ることも出来ます。
16816 そして、実引数に@emph{適用}されると、その計算を実行します。
16817 Schemeはまた、現在の計算の継続を取り出して手続きにラップして返す手段を
16818 提供しています(@ref{Continuations}参照)。
16819 @c COMMON
16820
16821 @c EN
16822 Gauche extends the concept of procedure application, allowing
16823 you to apply any object as if it's a procedure;
16824 for example, you can set up Gauche to
16825 accept @code{("abc" 2)} can be a valid application syntax.
16826 @xref{Applicable objects}, for the details.
16827 @c JP
16828 Gaucheは手続きの適用の概念を拡張し、どんなオブジェクトでもそれが手続きであるかのように
16829 適用できるようにしました。例えば@code{("abc" 2)}が有効な適用であるように
16830 Gaucheをセットアップすることができます。
16831 詳しくは@ref{Applicable objects}を参照してください。
16832 @c COMMON
16833
16834 @menu
16835 * Procedure class and applicability::
16836 * Universal accessor::
16837 * Combinators::
16838 * Optional argument parsing::
16839 * Procedure arity::
16840 * Applicable objects::
16841 * Continuations::
16842 * Continuation prompts::
16843 * Continuation marks::
16844 * Multiple values::
16845 * Folding generated values::
16846 @end menu
16847
16848 @node Procedure class and applicability, Universal accessor, Procedures and continuations, Procedures and continuations
16849 @subsection Procedure class and applicability
16850 @c NODE procedureクラスと適用可能性
16851
16852 @deftp {Builtin Class} <procedure>
16853 @clindex procedure
16854 @c EN
16855 Represents a procedure. Ordinary Scheme procedures created by @code{lambda}
16856 is an instance of this class, as well as built-in primitive procedures
16857 written in C. Note that, in Gauche, other type of objects can behave
16858 as a procedure; so checking whether an object is a procedure or not doesn't
16859 mean much unless you want to mess around with Gauche internals.
16860 @c JP
16861 手続きのクラスです。@code{lambda}で作られた手続きや
16862 組み込みのプリミティブ手続きはこのクラスのインスタンスです。
16863 Gaucheではどんな型のオブジェクトも適用可能にできるので、あるオブジェクトが
16864 @code{<procedure>}クラスのインスタンスであるかとうかということは
16865 あまり気にする必要はありません。Gaucheの中身をいじってみる時以外は。
16866 @c COMMON
16867 @end deftp
16868
16869 @defun procedure? obj
16870 [R7RS base]
16871 @c EN
16872 Returns @code{#t} if @var{obj} is @emph{inherently} applicable
16873 objects, @code{#f} otherwise. By @emph{inherently} applicable
16874 we mean Gauche unconditionally understands that @var{obj} can be called
16875 as a procedure; an instance of @code{<procedure>} is so,
16876 as well as generic functions (@code{<generic>}) and methods (@code{<method>}).
16877 @xref{Generic function and method}, for the details.
16878 @c JP
16879 @var{obj}が@emph{生得的}に適用可能なオブジェクトであれば@code{#t}を、
16880 そうでなければ@code{#f}を返します。@emph{生得的}にというのは、
16881 Gaucheが最初から手続きとして呼び出せるオブジェクトとして備えているもの、程度の意味です。
16882 @code{<procedure>}クラスのインスタンスや、
16883 ジェネリックファンクションやメソッドがそうです。
16884 (ジェネリックファンクションとメソッドに関しては
16885 @ref{Generic function and method}を参照してください)。
16886 @c COMMON
16887
16888 @c EN
16889 Since you can make any type of objects applicable at any time
16890 (@pxref{Applicable objects}), the fact that @code{procedure?} returned
16891 @code{#f} doesn't mean that the object cannot be applied.
16892 To check if an object can be applied or not, use @code{applicable?} below.
16893 @c JP
16894 Gaucheでは、どんなオブジェクトも適用可能にすることができます
16895 (@ref{Applicable objects}参照)。従って、@code{procedure?}が@code{#f}を
16896 返したからといってそのオブジェクトを手続きのように呼び出せないとは限りません。
16897 オブジェクトが適用可能かどうかをより正確に調べるには、
16898 下に説明する@code{applicable?}を使ってください。
16899 @c COMMON
16900 @end defun
16901
16902 @defun apply proc arg1 @dots{} args
16903 [R7RS base]
16904 @c EN
16905 Calls a procedure @var{proc} with a list of arguments,
16906 @code{(@var{arg1} @dots{} . @var{args})}.
16907 The last argument @var{args} must be a proper list.
16908 Returns (a) value(s) @var{proc} returns.
16909 @c JP
16910 @code{(@var{arg1} @dots{} . @var{args})}を引数として手続き@var{proc}を呼びます。
16911 最後の引数@var{args}は正規のリストでなければなりません。 @var{proc}が返す
16912 値をそのまま返します。
16913 @c COMMON
16914 @example
16915 (apply list 'a 'b '(c d e)) @result{} (a b c d e)
16916
16917 (apply + 1 2 '(3 4 5)) @result{} 15
16918 @end example
16919 @end defun
16920
16921 @defun applicable? obj class @dots{}
16922 @c EN
16923 Checks if @var{obj} can be called with the types of arguments
16924 listed in @var{class} @dots{}. That is,
16925 when @code{(applicable? foo <string> <integer>)} returns @code{#t},
16926 then you can call @code{foo} as @code{(foo "x" -2)}, for example.
16927 (It doesn't mean you won't get an error; @code{foo} may be accept
16928 only nonnegative integers, which you cannot tell from the result of
16929 @code{applicable?}. But if @code{applicable?} returns @code{#t},
16930 Gauche won't complain ``foo is not applicable'' when you call @code{foo}.
16931 @c JP
16932 それぞれの型が@var{class} @dots{}であるような引数リストを伴って
16933 @var{obj}を呼び出すことができるかどうかを調べます。
16934 例えば@code{(applicable? foo <string> <integer>)}が@code{#t}を
16935 返したなら、@code{foo}を@code{(foo "x" -2)}のように呼び出せるということです。
16936 (これは、エラーが出ないことを保証するものではありません。@code{foo}は
16937 もしかする非負整数しか受け取れないかもしれませんが、そのことは
16938 @code{applicable?}の結果からはわかりません。でも、@code{applicable?}が@code{#t}を
16939 返したなら、@code{foo}を呼び出した時に``foo is not applicable''と
16940 Gaucheに文句を言われることはありません。)
16941 @c COMMON
16942
16943 @c EN
16944 This procedure takes applicable objects into account. So, for example,
16945 @code{(applicable? #/a/ <string>)} returns @code{#t}, for the regular
16946 expressions are applicable to a string (@pxref{Regular expressions}).
16947 @c JP
16948 この手続きは適用可能オブジェクトも考慮に入れます。
16949 従って、例えば@code{(applicable? #/a/ <string>)}は@code{#t}を返します。
16950 正規表現は文字列に適用可能だからです (@ref{Regular expressions}参照)。
16951 @c COMMON
16952
16953 @c EN
16954 For generic functions, @code{applicable?} returns @code{#t} if it has
16955 at least one method such that each of its specifiers is a superclass
16956 of the corresponding @var{class} argument given to @code{applicable?}.
16957 @c JP
16958 ジェネリックファンクションに対しては、
16959 渡された@var{class}引数それぞれが、対応する特定化子と一致するかサブクラスになっている
16960 ようなメソッドが最低ひとつあれば、@code{applicable?}は@code{#t}を返します。
16961 @c COMMON
16962
16963 @example
16964 (define-method foo ((x <sequence>) (y <integer>)) #f)
16965
16966 (applicable? foo <sequence> <integer>) @result{} #t
16967 (applicable? foo <string> <integer>) @result{} #t
16968 (applicable? foo <hash-table> <integer>) @result{} #f
16969 (applicable? foo <string> <real>) @result{} #f
16970 @end example
16971
16972 @c EN
16973 The second example returns @code{#t} since @code{<string>} is
16974 a subclass of @code{<sequence>}, while
16975 the third example returns @code{#f} since @code{<hash-table>}
16976 isn't a subclass of @code{<sequence>}. The fourth example
16977 returns @code{#f} since @code{<real>} isn't a subclass of @code{<integer>}.
16978 @c JP
16979 2番目の例では、@code{<string>}は@code{<sequence>}のサブクラスなので
16980 @code{#t}が返ります。一方、3番目の例では@code{<hash-table>}は
16981 @code{<sequence>}のサブクラスではないので@code{#f}となります。
16982 4番めの例が@code{#f}なのは、@code{<real>}が@code{<integer>}のサブクラスではないからです。
16983 @c COMMON
16984
16985 @c EN
16986 Traditional Scheme procedures (such as ones created by @code{lambda})
16987 only cares the number of arguments but not their types; it accepts
16988 any type as far as the number of arguments matches. To check such
16989 a condition, pass @code{<top>} as the argument class. (@code{<top>} is
16990 a superclass of all classes.)
16991 @c JP
16992 伝統的なSchemeの手続き (@code{lambda}で作られるようなもの) は
16993 引数の数のみで呼び出し可能かどうかが判断されます。オブジェクトが
16994 引数の型にかかわらず、特定の個数の引数を取るかどうかを判定するには、
16995 @var{class}引数に@code{<top>}を渡します。(@code{<top>}は
16996 全てのクラスのスーパークラスです。)
16997 @c COMMON
16998
16999 @example
17000 (applicable? cons <top> <top>) @result{} #t
17001 @end example
17002
17003 @c EN
17004 If you want to check an object is applicable to a certain
17005 number of @emph{some} class of arguments, you can pass @code{<bottom>}
17006 as the argument class instead. (@code{<bottom>} is a subclass of all
17007 classes.)
17008 @c JP
17009 逆に、@emph{何らかの}特定の型の引数を取るかどうかを調べたい場合は、
17010 @code{<bottom>}を渡してください。(@code{<bottom>}は全てのクラスのサブクラスです。)
17011 @c COMMON
17012
17013 @example
17014 (define-method foo ((x <sequence>) (y <integer>)) #f)
17015
17016 (applicable? foo <top> <top>) @result{} #f
17017 (applicable? foo <bottom> <bottom>) @result{} #t
17018 @end example
17019
17020 @c EN
17021 @xref{Types and classes}, for the details of @code{<top>}, @code{<bottom>} and
17022 Gauche's type handling.
17023 @c JP
17024 @code{<top>}, @code{<bottom>}クラスおよびGaucheでの型の扱いについては
17025 @ref{Types and classes}を参照してください。
17026 @c COMMON
17027 @end defun
17028
17029 @defun procedure-type proc
17030 @c EN
17031 The argument must be a procedure. Returns a descriptive type
17032 of the @var{proc}, as much as the system knows.
17033 @xref{Types and classes}, for the details of procedure types.
17034 @c JP
17035 引数は手続きでなければなりません。手続き@var{proc}の記述的な型を、
17036 わかる範囲で返します。
17037 手続きの型について詳しくは@ref{Types and classes}を参照してください。
17038 @c COMMON
17039
17040 @c EN
17041 The ``type'' returned by this procedure is just a hint.
17042 Currently, most Scheme-defined procedures doesn't have much type info.
17043 @c JP
17044 この手続きで返される型は一種のヒントにすぎません。
17045 今のところ、ほとんどのSchemeで定義された手続きからは、あまり詳しい型情報は取れません。
17046 @c COMMON
17047
17048 @example
17049 (procedure-type filter) @result{} #<^ <top> <top> -> *>
17050 @end example
17051
17052 @c EN
17053 Some of subrs (C-defined procedures) has a bit more info, derived
17054 from C type information.
17055 @c JP
17056 subr (Cで定義された手続き) の中には、Cの型情報を使って多少詳しい情報が
17057 取れるものもあります。
17058 @c COMMON
17059 @example
17060 (procedure-type cons) @result{} #<^ <top> <top> -> <pair>>
17061 @end example
17062
17063 @c EN
17064 Eventually we'll improve this system to return more precise type info,
17065 and use it for optimizations and other static analysis.
17066 @c JP
17067 いずれ、より正確な型情報を取れるようにして、
17068 最適化やその他の静的解析に使えるようにする予定です。
17069 @c COMMON
17070 @end defun
17071
17072
17073 @node Universal accessor, Combinators, Procedure class and applicability, Procedures and continuations
17074 @subsection Universal accessor
17075 @c NODE 万能アクセサ
17076
17077 @defun ~ obj key keys @dots{}
17078 @defunx {(setter ~)} obj key keys @dots{}
17079 @c EN
17080 The procedure @code{~} can be used to access a part of various
17081 aggregate types.
17082 @c JP
17083 手続き@code{~}は、様々な集合型のオブジェクトの部分にアクセスするのに使えます。
17084 @c COMMON
17085
17086 @example
17087 ;; Access to an element of a sequence by index
17088 (~ '(a b c) 0) @result{} a
17089 (~ '#(a b c) 2) @result{} c
17090 (~ "abc" 1) @result{} #\b
17091 (~ '#u8(10 20 30) 1) @result{} 20
17092
17093 ;; Access to an element of a collection by key
17094 (~ (hash-table 'eq? '(a . 1) '(b . 2)) 'a)
17095 @result{} 1
17096
17097 ;; Access to a slot of an object by slot name
17098 (~ (sys-localtime (sys-time)) 'hour)
17099 @result{} 20
17100 @end example
17101
17102 @c EN
17103 The access can be chained:
17104 @c JP
17105 アクセスはチェインすることができます。
17106 @c COMMON
17107
17108 @example
17109 (~ '#((a b c) (d e f) (g h i)) 1 2) @result{} f
17110
17111 (~ (hash-table 'eq? '(a . "abc") '(d . "def")) 'a 2)
17112 @result{} #\c
17113 @end example
17114
17115 @c EN
17116 You can think @code{~} as left-associative, that is,
17117 @c JP
17118 @code{~}は左結合します。つまり、
17119 @c COMMON
17120 @example
17121 (~ x k j) @equiv{} (~ (~ x k) j)
17122 @end example
17123 @c EN
17124 and so on.
17125 @c JP
17126 等。
17127 @c COMMON
17128
17129 @c EN
17130 The generalized setter @code{set!} can be used with @code{~} to
17131 replace the specified element.
17132 @c JP
17133 一般化された@code{set!}を@code{~}に使えば、アクセスされる要素を置き換えることができます。
17134 @c COMMON
17135
17136 @example
17137 (define z (vector 'a 'b 'c))
17138 (set! (~ z 1) 'Z)
17139
17140 z @result{} #(a Z c)
17141
17142 (define z (vector (list (vector 'a 'b 'c)
17143 (vector 'd 'e 'f)
17144 (vector 'g 'h 'i))
17145 (list (vector 'a 'b 'c)
17146 (vector 'd 'e 'f)
17147 (vector 'g 'h 'i))))
17148
17149 z @result{} #((#(a b c) #(d e f) #(g h i))
17150 (#(a b c) #(d e f) #(g h i)))
17151
17152 (set! (~ z 1 2 0) 'Z)
17153 z @result{} #((#(a b c) #(d e f) #(g h i))
17154 (#(a b c) #(d e f) #(Z h i)))
17155 @end example
17156 @end defun
17157
17158 @c EN
17159 Internally, a call to @code{~} is implemented by a generic
17160 function @code{ref}. See @ref{Object system} for more about
17161 generic functions.
17162 @c JP
17163 @code{~}は内部的にジェネリックファンクション@code{ref}を使って実現されています。
17164 ジェネリックファンクションについて詳しくは@ref{Object system}を参照してください。
17165 @c COMMON
17166
17167 @deffn {Generic function} ref object key :optional args @dots{}
17168 @deffnx {Generic function} {(setter ref)} object key value
17169 @c EN
17170 Many aggregate types defines a specialized method of these
17171 to provide uniform access and mutation. Meaning of
17172 optional arguments @var{args} of @code{ref} depends
17173 on each specialized method,
17174 but it is common that the first optional argument of @code{ref}
17175 is a @emph{fallback} value, which is to be returned when
17176 @var{object} doesn't have a meaningful association with @var{key}.
17177 @c JP
17178 多くの集合型はこのジェネリックファンクションを特殊化し、
17179 統一されたアクセス方法と変更方法を提供しています。
17180 @code{ref}のオプショナル引数@var{args}の意味はメソッド毎に異なりますが、
17181 最初のオプショナル引数は、@var{object}の@var{key}に対する値が無い場合の
17182 フォールバック値として使われるのが普通です。
17183 @c COMMON
17184
17185 @c EN
17186 The manual entry of each aggregate type shows the specialized
17187 method and its semantics in detail.
17188 @c JP
17189 正確な動作の定義は、@code{ref}メソッドを提供しているクラスごとに説明されています。
17190 @c COMMON
17191 @end deffn
17192
17193 @c EN
17194 Conceptually, @code{~} can be understood as follows:
17195 @c JP
17196 @code{~}の動作は次のコードで理解できるでしょう。
17197 @c COMMON
17198
17199 @example
17200 (define ~
17201 (getter-with-setter
17202 (case-lambda
17203 [(obj selector) (ref obj selector)]
17204 [(obj selector . more) (apply ~ (ref obj selector) more)])
17205 (case-lambda
17206 [(obj selector val) ((setter ref) obj selector val)]
17207 [(obj selector selector2 . rest)
17208 (apply (setter ~) (ref obj selector) selector2 rest)])))
17209 @end example
17210
17211 @c EN
17212 (Gauche may use some short-cut for optimization, though,
17213 so this code may not reflect the actual implementation.)
17214 @c JP
17215 (Gaucheは最適化のためにいくつかの型で短絡経路を使うこともあるので、
17216 実際の実装とは異なります)
17217 @c COMMON
17218
17219 @node Combinators, Optional argument parsing, Universal accessor, Procedures and continuations
17220 @subsection Combinators
17221 @c NODE コンビネータ
17222
17223 @c EN
17224 Gauche has some primitive procedures that allows combinatory programming.
17225 @c JP
17226 Gaucheには、combinatory programmingに使えるいくつかの基本手続きがあります。
17227 @c COMMON
17228
17229 @defun pa$ proc arg @dots{}
17230 @c EN
17231 Partial application. Returns a procedure, and when it is
17232 called with arguments @var{m} @dots{}, it is equivalent to call
17233 @code{(proc arg @dots{} m @dots{})}.
17234 @c JP
17235 部分適用。手続きを返します。その手続きが引数@var{m} @dots{}を伴って
17236 呼ばれた場合、それは@code{(proc arg @dots{} m @dots{})}と等価になります。
17237 @c COMMON
17238
17239 @example
17240 (define add3 (pa$ + 3))
17241 (add3 4) @result{} 7
17242
17243 (map (pa$ * 2) '(1 2 3)) @result{} (2 4 6)
17244 @end example
17245
17246 @c EN
17247 Macros @code{cut} and @code{cute} defined in SRFI-26 provide
17248 a similar abstraction, with a bit more flexible but less compact
17249 notation. @xref{Making procedures}.
17250 @c JP
17251 SRFI-26で定義されているマクロ@code{cut}と@code{cute}も似たような抽象化の
17252 方法を提供しますが、@code{pa$}より多少柔軟性が高く、その分やや冗長です。
17253 @ref{Making procedures}を参照して下さい。
17254 @c COMMON
17255
17256 @c EN
17257 SRFI-235 defines @code{left-section}, which is effectively the same
17258 as @code{pa$} (@pxref{Combinators (SRFI)}).
17259 @c JP
17260 SRFI-235で定義される@code{left-section}は実質的に@code{pa$}と同じです。
17261 @ref{Combinators (SRFI)}参照。
17262 @c COMMON
17263 @end defun
17264
17265 @defun apply$ proc
17266 @defunx map$ proc
17267 @defunx for-each$ proc
17268 @c EN
17269 Partial application versions of @code{apply}, @code{map} and @code{for-each}.
17270 @c JP
17271 @code{apply}, @code{map}と@code{for-each}の部分適用版です。
17272 @c COMMON
17273
17274 @example
17275 (define map2* (map$ (pa$ * 2)))
17276 (map2* '(1 2 3)) @result{} (2 4 6)
17277 @end example
17278
17279 @end defun
17280
17281 @defun count$ pred
17282 @defunx fold$ kons :optional knil
17283 @defunx fold-right$ kons :optional knil
17284 @defunx reduce$ f :optional ridentity
17285 @defunx reduce-right$ f :optional ridentity
17286 @defunx filter$ pred
17287 @defunx remove$ pred
17288 @defunx partition$ pred
17289 @defunx member$ item
17290 @defunx find$ pred
17291 @defunx find-tail$ pred
17292 @defunx any$ pred
17293 @defunx every$ pred
17294 @defunx delete$ pred
17295 @defunx assoc$ item
17296 @c EN
17297 Partial application versions of some SRFI-1 (R7RS @code{(scheme list)})
17298 procedures (@pxref{R7RS lists}).
17299 @c JP
17300 SRFI-1 (R7RS @code{(scheme list)})
17301 (@ref{R7RS lists}参照)の手続に対応する部分適用版手続。
17302 @c COMMON
17303 @end defun
17304
17305 @defun .$ f @dots{}
17306 @defunx compose f @dots{}
17307 @c EN
17308 Combine procedures. All arguments must be procedures.
17309 When two procedures are given, @code{(.$ f g)} is equivalent to
17310 the following code:
17311 @c JP
17312 複数の手続きを結合します。引数は全て手続きでなければなりません。
17313 2つの引数が渡された時、@code{(.$ f g)}は次の式と等価です。
17314 @c COMMON
17315 @example
17316 (lambda args (call-with-values (lambda () (apply g args)) f))
17317 @end example
17318
17319 @c EN
17320 When more than two arguments are passed, they are composed
17321 as follows:
17322 @c JP
17323 2つ以上の引数が渡された場合は、次のように結合されます。
17324 @c COMMON
17325 @example
17326 (.$ f g h ...) @equiv{} (.$ (.$ f g) h ...)
17327 @end example
17328
17329 @c EN
17330 Some examples:
17331 @c JP
17332 いくつか例を示します。
17333 @c COMMON
17334
17335 @example
17336 (define not-zero? (.$ not zero?))
17337 (not-zero? 3) @result{} #t
17338 (not-zero? 0) @result{} #f
17339
17340 (define dot-product (.$ (apply$ +) (map$ *)))
17341 (dot-product '(1 2 3) '(4 5 6)) @result{} 32
17342 @end example
17343
17344 @c EN
17345 A couple of edge cases: if only one argument is given, the argument
17346 itself is returned. If no arguments are given, the procedure @code{values}
17347 is returned.
17348 @c JP
17349 境界のケース:ひとつだけ引数が渡された場合は、その引数がそのまま返されます。
17350 引数が全く渡されなかった場合は手続き@var{values}が返されます。
17351 @c COMMON
17352
17353 @c EN
17354 Note: The name @code{.$} comes from the fact that @code{.} is
17355 commonly used for function composition in literatures and some
17356 programming languages, and that Gauche uses suffix @code{$} to
17357 indicate combinators. However, since it is not a valid R7RS
17358 identifier, portable programs may want to use the alias @code{compose},
17359 with which you can easily add a portable definition using SRFI-0,
17360 for example.
17361 @c JP
17362 註: @code{.$}という名前は、文献やいくつかの他のプログラミング言語で
17363 @code{.}が関数合成によく使われること、そしてGaucheではコンビネータの末尾に
17364 @code{$}をつける習慣があることから来ています。ただ、これはR7RSの
17365 範囲内では有効な識別子でないので、ポータビリティを考えるプログラムは
17366 別名の@code{compose}を使った方が良いでしょう。そうすればSRFI-0などを
17367 使って容易に移植が可能です。
17368 @c COMMON
17369
17370 @c EN
17371 SRFI-210 provides @code{compose-left} and @code{compose-right};
17372 @pxref{Procedures and syntax for multiple values}.
17373 @c JP
17374 なお、SRFI-210に@code{compose-left}と@code{compose-right}が定義されています。
17375 @ref{Procedures and syntax for multiple values}参照。
17376 @c COMMON
17377 @end defun
17378
17379 @defun identity obj
17380 @c EN
17381 Returns @var{obj}. You can use @code{values} to get the same
17382 effect for the porable code,
17383 but using this emphasizes that you're dealing with exactly one value.
17384 @c JP
17385 @var{obj}を返します。ポータブルなコードでは@code{values}を使って同じ効果を
17386 得ることができますが、これを使うことにより単一の値を扱っていることを強調できます。
17387 @c COMMON
17388
17389 @c EN
17390 Note: SRFI-210 introduces multi-valued @code{identity} (unfortunately), which is
17391 a synonym to @code{values} (@pxref{Procedures and syntax for multiple values}).
17392 @c JP
17393 註: SRFI-210は複数の値を扱う@code{identity}を(残念ながら)導入してしまいました。
17394 それは@code{values}の別名にすぎません。
17395 @ref{Procedures and syntax for multiple values}参照。
17396 @c COMMON
17397 @end defun
17398
17399 @defun constantly obj @dots{}
17400 [SRFI-235]
17401 @c EN
17402 Returns a procedure that takes arbitrary number of arguments, discards
17403 them, and returns @var{obj} obj @dots{}.
17404 Same as @code{(^ _ (values obj @dots{}))}.
17405 @c JP
17406 任意個の引数をとり、それらを無視して@var{obj}を返す関数を返します。
17407 @code{(^ _ (values obj @dots{}))}と同じです。
17408 @c COMMON
17409 @end defun
17410
17411 @defun complement pred
17412 [SRFI-235]
17413 @c EN
17414 Returns a procedure that reverses the meaning of the predicate @var{pred}.
17415 That is, for the arguments for which @var{pred} returns true return
17416 false, and vice versa.
17417 @c JP
17418 述語@var{pred}の意味を逆にした手続きを返します。すなわち、@var{pred}が真を
17419 返すような引数にたいして偽を返す、またその逆も同様であるような手続きです。
17420 @c COMMON
17421
17422 @example
17423 (map (complement even?) '(1 2 3)) @result{} '(#t #f #t)
17424 (map (complement =) '(1 2 3) '(1 1 3)) @result{} '(#f #t #f)
17425 ((complement (lambda () #f))) @result{} #t
17426 @end example
17427 @end defun
17428
17429 @defun flip proc
17430 [SRFI-235]
17431 @c EN
17432 Returns a procedure that passes its arguments to @var{proc} in
17433 reverse order, that is, @code{((flip proc) a b @dots{} y z)} is
17434 @code{(proc z y @dots{} b a)}.
17435 @c JP
17436 渡された引数を逆順で@var{proc}に渡すような手続きを返します。すなわち、
17437 @code{((flip proc) a b @dots{} y z)}は
17438 @code{(proc z y @dots{} b a)}と同じです。
17439 @c COMMON
17440 @end defun
17441
17442 @defun swap proc
17443 [SRFI-235]
17444 @c EN
17445 @var{Proc} must be a procedure that takes two arguments or more.
17446 Returns a procedure that passes its first and second arguments
17447 swapped to @var{proc}, that is,
17448 @code{((swap proc) a b arg @dots{})} is
17449 @code{(proc b a arg @dots{})}.
17450 @c JP
17451 @var{proc}は2つ以上の引数を取る手続きでなければなりません。
17452 渡された引数の最初と2番めの引数の順序を入れ替えて@var{proc}を呼び出す手続きを
17453 返します。すなわち、
17454 @code{((swap proc) a b arg @dots{})}は
17455 @code{(proc b a arg @dots{})}と同じです。
17456 @c COMMON
17457 @end defun
17458
17459 @defun any-pred pred @dots{}
17460 @c EN
17461 Returns a procedure which applies given argument(s) to
17462 each predicate @var{pred}. If any @var{pred} returns
17463 a non-@code{#f} value, the value is returned. If all the @var{pred}s
17464 return @code{#f}, @code{#f} is returned.
17465 @c JP
17466 与えられた引数をそれぞれ述語@var{pred}に適用する手続きを返します。
17467 いずれかの@var{pred}が@code{#f}でない値を返す場合、その値を返します。
17468 全ての@var{pred}が@code{#f}を返す場合、@code{#f}を返します。
17469 @c COMMON
17470
17471 @example
17472 (define string-or-symbol? (any-pred string? symbol?))
17473 (string-or-symbol? "abc") @result{} #t
17474 (string-or-symbol? 'abc) @result{} #t
17475 (string-or-symbol? 3) @result{} #f
17476
17477 (define <> (any-pred < >))
17478 (<> 3 4) @result{} #t
17479 (<> 3 3) @result{} #f
17480
17481 ((any-pred (cut memq <> '(a b c))
17482 (cut memq <> '(1 2 3)))
17483 'b) @result{} '(b c)
17484 @end example
17485 @end defun
17486
17487 @defun every-pred pred @dots{}
17488 @c EN
17489 Returns a procedure which applies given argument(s) to
17490 each predicate @var{pred}. If every @var{pred} returns
17491 a non-@code{#f} value, the value returned by the last @var{pred}
17492 is returned. If any @var{pred} returns @code{#f}, @code{every-pred}
17493 returns @code{#f} without calling further @var{pred}s.
17494 @c JP
17495 与えられた引数をそれぞれ述語@var{pred}に適用する手続きを返します。
17496 全ての@var{pred}が@code{#f}でない値を返す場合、戻り値は最後の
17497 @var{pred}の戻り値になります。いずれかの@var{pred}が@code{#f}を
17498 返す場合、@code{every-pred}はそれ以降の@var{pred}を呼び出さずに
17499 @code{#f}を返します。
17500 @c COMMON
17501
17502 @example
17503 ((every-pred odd? positive?) 3) @result{} #t
17504 ((every-pred odd? positive?) 4) @result{} #f
17505 ((every-pred odd? positive?) -3) @result{} #f
17506
17507 (define safe-length (every-pred list? length))
17508 (safe-length '(a b c)) @result{} 3
17509 (safe-length "aaa") @result{} #f
17510 @end example
17511 @end defun
17512
17513 @node Optional argument parsing, Procedure arity, Combinators, Procedures and continuations
17514 @subsection Optional argument parsing
17515 @c NODE 省略可能引数のパージング
17516
17517 @c EN
17518 Gauche supports optional and keyword arguments in extended
17519 lambda syntax (@pxref{Making procedures}). However, you can
17520 also use the following macros to parse optional and keyword
17521 arguments, without relying Gauche's extension.
17522 @c JP
17523 Gaucheは省略可能引数やキーワード引数を拡張lambda構文で
17524 サポートしています (@ref{Making procedures}参照)。
17525 けれども、Gauche拡張に頼らずに、以下のマクロを使って独自にこれらの引数を
17526 パーズすることもできます。
17527 @c COMMON
17528
17529 @example
17530 (define (foo a b :optional (c #f) (d 'none))
17531 body ...)
17532
17533 @c EN
17534 ;; is roughly equivalent to ...
17535 @c JP
17536 ;; は次の式とだいたい同じ:
17537 @c COMMON
17538
17539 (define (foo a b . args)
17540 (let-optionals* args ((c #f) (d 'none))
17541 body ...))
17542 @end example
17543
17544 @c EN
17545 Explicitly parsing the extended arguments may be useful for
17546 portable programs, since it is rather straightforward to
17547 implement those macros rather than extend lambda syntax.
17548
17549 Those macros can also be useful to factor out common
17550 argument parsing routines.
17551 @c JP
17552 明示的に拡張引数をパーズする方法は、ポータブルなコードを書く時に
17553 役に立つでしょう。以下のマクロを実装するのは、lambdaの構文を
17554 拡張するより簡単だからです。
17555
17556 また、共通する拡張引数の処理ルーチンを括り出す場合にもこれらのマクロは有用です。
17557 @c COMMON
17558
17559 @defmac let-optionals* restargs (var-spec @dots{}) body @dots{}
17560 @defmacx let-optionals* restargs (var-spec @dots{} . restvar) body @dots{}
17561 @c EN
17562 Given a list of values @var{restargs}, binds variables according
17563 to @var{var-spec}, then evaluates @var{body}.
17564 @c JP
17565 与えられた値のリスト@var{restargs}を、@var{var-spec}にしたがって
17566 変数に束縛し、@var{body}を評価します。
17567 @c COMMON
17568
17569 @c EN
17570 @var{Var-spec} can be either a symbol, or a list of two elements
17571 and its car is a symbol. The symbol is the bound variable name.
17572 The values in @var{restargs} are bound to the symbol in order.
17573 If there are not as many values in @var{restargs} as @var{var-spec},
17574 the rest of @var{symbol}s are bound to the default values, determined
17575 as follows: If @var{var-spec} is just a symbol, the default value is
17576 undefined. If @var{var-spec} is a list, the default value is
17577 the result of evaluation of the second element of the list.
17578 In the latter case the second
17579 element is only evaluated when there are not enough arguments.
17580 The binding proceeds in the order of @var{var-spec}, so the second
17581 element may refer to the bindings of previous @var{var-spec}.
17582 @c JP
17583 @var{var-spec}はシンボルか、そのcarがシンボルである2要素のリストの
17584 いずれかです。シンボルは束縛された変数名です。
17585 @var{restargs}にある値は、順番にシンボルに束縛されます。
17586 @var{restargs}に@var{var-spec}に示される数の値がない場合は、
17587 残りの@var{symbol}は以下に従ってデフォルト値が束縛されます。
17588 @var{var-spec}が単なるシンボルなら、デフォルト値は未定義です。
17589 @var{var-spec}がリストなら、デフォルト値はリストの2番目の要素を
17590 評価した結果です。後者の場合、2番目の要素は十分な引数がない場合にのみ
17591 評価されます。
17592 束縛は@var{var-spec}の順番にしたがって行われるので、2番目の要素は
17593 以前の@var{var-spec}のバインディングを参照するかも知れません。
17594 @c COMMON
17595
17596 @c EN
17597 In the second form, @var{restvar} must be a symbol and bound to
17598 the list of values whatever left from @var{restargs} after binding
17599 to @var{var-spec}.
17600 @c JP
17601 2番目のフォームでは、@var{restvar}はシンボルでなければならず、
17602 @var{var-spec}に束縛された後、@var{restargs}に残っている値のリストに
17603 束縛されます。
17604 @c COMMON
17605
17606 @c EN
17607 It is not an error if @var{restarg} has more values than @var{var-spec}s.
17608 The extra values are simply ignored in the first form.
17609 @c JP
17610 @var{restarg}が@var{var-spec}よりも多い値を持っていてもエラーでは
17611 ありません。最初のフォームでは、余分な値は単に無視されます。
17612 @c COMMON
17613
17614 @example
17615 (define (proc x . args)
17616 (let-optionals* args ((a 'a)
17617 (b 'b)
17618 (c 'c))
17619 (list x a b c)))
17620
17621 (proc 0) @result{} (0 a b c)
17622 (proc 0 1) @result{} (0 1 b c)
17623 (proc 0 1 2) @result{} (0 1 2 c)
17624 (proc 0 1 2 3) @result{} (0 1 2 3)
17625
17626 (define (proc2 . args)
17627 (let-optionals* args ((a 'a) . b)
17628 (list a b)))
17629
17630 (proc2) @result{} (a ())
17631 (proc2 0) @result{} (0 ())
17632 (proc2 0 1) @result{} (0 (1))
17633 (proc2 0 1 2) @result{} (0 (1 2))
17634
17635 (define (proc3 . args)
17636 (let-optionals* args ((a 0)
17637 (b (+ a 1))
17638 (c (+ b 1)))
17639 (list a b c)))
17640
17641 (proc3) @result{} (0 1 2)
17642 (proc3 8) @result{} (8 9 10)
17643 (proc3 8 2) @result{} (8 2 3)
17644 (proc3 8 2 -1) @result{} (8 2 -1)
17645 @end example
17646 @end defmac
17647
17648 @defmac get-optional restargs default
17649 @c EN
17650 This is a short version of @code{let-optionals*} where you have only
17651 one optional argument. Given the optional argument list @var{restargs},
17652 this macro returns the value of optional argument if one is given,
17653 or the result of @var{default} otherwise. @var{Default} is not
17654 evaluated unless @var{restargs} is an empty list.
17655 @c JP
17656 これは@code{let-optionals*}の短いバージョンで、オプショナル引数が
17657 1つしかないときに使います。オプショナル引数のリストとして@var{restargs}が
17658 与えらると、このマクロはオプショナル引数が与えられていればその値を返し、
17659 そうでなければ@var{default}の結果を返します。@var{default}は@var{restargs}が
17660 空リストでなければ評価されません。
17661 @c COMMON
17662
17663 @example
17664 (define (proc x . maybe-opt)
17665 (let ((option (get-optional maybe-opt #f)))
17666 (list x option)))
17667
17668 (proc 0) @result{} (0 #f)
17669 (proc 0 1) @result{} (0 1)
17670 @end example
17671 @end defmac
17672
17673 @defmac let-keywords restarg (var-spec @dots{}) body @dots{}
17674 @defmacx let-keywords restarg (var-spec @dots{} . restvar) body @dots{}
17675 @c EN
17676 This macro is for keyword arguments. @var{Var-spec} can be
17677 one of the following forms:
17678 @c JP
17679 このマクロはキーワード引数のためのものです。@var{var-spec}は
17680 以下のフォームのうちのいずれかです。
17681 @c COMMON
17682
17683 @table @code
17684 @item (@var{symbol} @var{expr})
17685 @c EN
17686 If the @var{restarg} contains keyword which has the same name as @var{symbol},
17687 binds @var{symbol} to the corresponding value. If such a keyword doesn't
17688 appear in @var{restarg}, binds @var{symbol} to the result of @var{expr}.
17689 @c JP
17690 @var{restarg}が@var{symbol}と同じ名前を持つキーワードを含んでいる場合、
17691 @var{symbol}を対応する値に束縛します。そのようなキーワードが@var{restarg}に
17692 ない場合は、@var{symbol}を@var{expr}の結果に束縛します。
17693 @c COMMON
17694 @item (@var{symbol} @var{keyword} @var{expr})
17695 @c EN
17696 If the @var{restarg} contains keyword @var{keyword},
17697 binds @var{symbol} to the corresponding value. If such a keyword doesn't
17698 appear in @var{restarg}, binds @var{symbol} to the result of @var{expr}.
17699 @c JP
17700 @var{restarg}がキーワード@var{keyword}を含む場合、
17701 @var{symbol}を対応する値に束縛します。そのようなキーワードが@var{restarg}に
17702 ない場合、@var{symbol}を@var{expr}の結果に束縛します。
17703 @c COMMON
17704 @end table
17705
17706 @c EN
17707 The default value @var{expr} is only evaluated when the keyword is
17708 not given to the @var{restarg}.
17709 @c JP
17710 デフォルト値@var{expr}は、@var{restarg}にキーワードが与えられてなかった
17711 場合にのみ評価されます。
17712 @c COMMON
17713
17714 @c EN
17715 If you use the first form, @code{let-keyword} throws an error
17716 when @code{restarg} contains a keyword argument that is not listed
17717 in @var{var-spec}s.
17718 When you want to allow keyword arguments other than listed in
17719 @var{var-spec}s, use the second form.
17720
17721 In the second form, @var{restvar} must be either a symbol or @code{#f}.
17722 If it is a symbol, it is bound to a list of keyword arguments
17723 that are not processed by @var{var-spec}s. If it is @code{#f},
17724 such keyword arguments are just ignored.
17725 @c JP
17726 1番目のフォームでは、@var{var-spec}にないキーワード引数が@var{restarg}に
17727 現れるとエラーとなります。
17728 他のキーワード引数を許したい場合は次の2番目のフォームを使ってください。
17729
17730 2番目のフォームでは、@var{restvar}はシンボルか@code{#f}でなければなりません。
17731 シンボルのときは、@var{var-spec}に束縛されなかった@var{restargs}のキーワード
17732 リストが@var{restvar}に束縛されます。@code{#f}のときは、それらの@var{restargs}
17733 のキーワードは単に無視されます。
17734 @c COMMON
17735
17736 @example
17737 (define (proc x . options)
17738 (let-keywords options ((a 'a)
17739 (b :beta 'b)
17740 (c 'c)
17741 . rest)
17742 (list x a b c rest)))
17743
17744 (proc 0) @result{} (0 a b c ())
17745 (proc 0 :a 1) @result{} (0 1 b c ())
17746 (proc 0 :beta 1) @result{} (0 a 1 c ())
17747 (proc 0 :beta 1 :c 3 :unknown 4) @result{} (0 a 1 3 (:unknown 4))
17748 @end example
17749 @end defmac
17750
17751 @defmac let-keywords* restarg (var-spec @dots{}) body @dots{}
17752 @defmacx let-keywords* restarg (var-spec @dots{} . restvar) body @dots{}
17753 @c EN
17754 Like @code{let-keywords}, but the binding is done in the order of
17755 @var{var-spec}s. So each @var{expr} can refer to the variables bound by
17756 preceding @var{var-spec}s.
17757 @c JP
17758 このマクロは@code{let-keywords}とほぼ同じですが、束縛が@var{var-spec}での
17759 順番に行われるところが異なります。@var{expr}は以前の@var{var-spec}により
17760 束縛された変数を参照できます。
17761 @c COMMON
17762 @end defmac
17763
17764 @node Procedure arity, Applicable objects, Optional argument parsing, Procedures and continuations
17765 @subsection Procedure arity
17766 @c NODE 手続きのアリティ
17767
17768 @c EN
17769 Interface to query procedure's arity.
17770 The API is taken from MzScheme (PLT Scheme).
17771 @c JP
17772 手続きのアリティを問い合わせるインターフェースです。
17773 APIは、MzScheme (PLT Scheme)を参考にしました。
17774 @c COMMON
17775
17776 @defun arity @var{proc}
17777 @c EN
17778 Given procedure @var{proc},
17779 returns an integer, an @emph{arity-at-least} object, or
17780 a list of integer(s) and @emph{arity-at-least} objects.
17781 @c JP
17782 手続き@var{proc}を与え、整数、@emph{arity-at-least}オブジェクト、
17783 整数と@emph{arity-at-least}オブジェクトからなるリストのいずれかを
17784 返します。
17785 @c COMMON
17786
17787 @c EN
17788 An integer result indicates @var{proc} takes exactly that number
17789 of arguments. An @emph{arity-at-least} indicates @var{proc} takes
17790 at least @code{(arity-at-least-value @emph{arity-at-least})}
17791 arguments. The list indicates there are multiple procedures
17792 with different arities.
17793 @c JP
17794 整数の戻り値は、@var{proc}が正確にその数の引数を取ることを表します。
17795 @emph{arity-at-least}は、@var{proc}が最低でも
17796 引数@code{(arity-at-least-value @emph{arity-at-least})}を取ることを
17797 表します。リストは、異なるアリティを持つ複数の手続きがあることを
17798 表します。
17799 @c COMMON
17800
17801 @c EN
17802 Since one can add methods to an existing procedure or generic function
17803 at any moment in Gauche, the value returned by @code{arity} only
17804 indicates the current state of the procedure. It will change
17805 if new method is added to the procedure/generic-function.
17806 @c JP
17807 Gaucheではいつでも、既存の手続きやジェネリック関数にメソッドを追加
17808 できるので、@code{arity}が返す値はその手続きの現在の状態を示すに
17809 過ぎません。その手続きやジェネリック関数に新しいメソッドが追加
17810 されると、それも変更されます。
17811 @c COMMON
17812
17813 @example
17814 (arity cons) @result{} 2
17815 (arity list) @result{} #<arity-at-least 0>
17816 (arity make) @result{} (#<arity-at-least 1>)
17817 @end example
17818 @end defun
17819
17820 @defun arity-at-least? @var{obj}
17821 @c EN
17822 Returns true if @var{obj} is an arity-at-least object.
17823 @c JP
17824 @var{obj}がarity-at-leastオブジェクトなら、真を返します。
17825 @c COMMON
17826 @end defun
17827
17828 @defun arity-at-least-value @var{arity-at-least}
17829 @c EN
17830 Returns the number of required arguments the arity-at-least object
17831 indicates.
17832 @c JP
17833 arity-at-leastオブジェクトが表す必須引数の数を返します。
17834 @c COMMON
17835 @end defun
17836
17837 @defun procedure-arity-includes? @var{proc} @var{k}
17838 @c EN
17839 If a procedure @var{proc} can take @var{k} arguments, returns @code{#t}.
17840 Otherwise returns @code{#f}.
17841 @c JP
17842 手続き@var{proc}が引数@var{k}を取れる場合、@code{#t}を返します。
17843 そうでなければ@code{#f}を返します。
17844 @c COMMON
17845 @end defun
17846
17847
17848 @node Applicable objects, Continuations, Procedure arity, Procedures and continuations
17849 @subsection Applicable objects
17850 @c NODE 適用可能なオブジェクト
17851
17852 @c EN
17853 Gauche has a special hook to make an arbitrary object @emph{applicable}.
17854 @c JP
17855 Gaucheでは、特別な組み込みの機構によって任意のオブジェクトを
17856 「適用可能」にすることができます。
17857 @c COMMON
17858
17859 @deffn {Generic Function} object-apply @var{object} @var{arg} @dots{}
17860 @c EN
17861 If an object that is neither a procedure nor a generic function
17862 is applied to some arguments,
17863 the object and the arguments are passed to a generic function
17864 @code{object-apply}.
17865
17866 This can be explained better by examples.
17867 @c JP
17868 手続きでもジェネリックファンクションでもないオブジェクトが何らかの引数に
17869 適用されたとき、そのオブジェクトと引数がジェネリックファンクション@code{object-apply}
17870 に渡されます。
17871
17872 この機能は、具体的な例を挙げた方が説明し易いでしょう。
17873 @c COMMON
17874 @end deffn
17875
17876 @c EN
17877 For example, suppose you try to evaluate the
17878 following expression:
17879 @c JP
17880 例えば、次のような式を評価しようとしたとします。
17881 @c COMMON
17882
17883 @example
17884 ("abcde" 2)
17885 @end example
17886
17887 @c EN
17888 The operator evaluates to a string, which is neither a procedure
17889 nor a generic function. So Gauche interprets the expression
17890 as if it were like this:
17891 @c JP
17892 オペレータは文字列に評価されますから、手続きでもジェネリックファンクションでも
17893 ありません。そこで、Gaucheはこの式を、あたかも次のような式が与えられた
17894 かのように解釈します。
17895 @c COMMON
17896
17897 @example
17898 (object-apply "abcde" 2)
17899 @end example
17900
17901 @c EN
17902 Gauche doesn't define a method of @code{object-apply} that takes
17903 @code{<string>} and @code{<integer>} by default, so this signals an error.
17904 However, if you define such a method:
17905 @c JP
17906 デフォルトでは、@code{<string>}と@code{<integer>}を引数とする
17907 @code{object-apply}のメソッドは定義されていないので、
17908 この式はエラーになります。しかし、次のようなメソッドを定義すると:
17909 @c COMMON
17910
17911 @example
17912 (define-method object-apply ((s <string>) (i <integer>))
17913 (string-ref s i))
17914 @end example
17915
17916 @c EN
17917 Then the first expression works as if a string is @emph{applied} on
17918 the integer:
17919 @c JP
17920 最初の式はまるで文字列が整数に適用されたかのように動作します。
17921 @c COMMON
17922
17923 @example
17924 ("abcde" 2) @result{} #\c
17925 @end example
17926
17927 @c EN
17928 This mechanism works on almost all occasions where a procedure is allowed.
17929 @c JP
17930 このメカニズムは手続きが許されるほとんどの箇所で使うことができます。
17931 @c COMMON
17932
17933 @example
17934 (apply "abcde" '(1)) @result{} (#\b)
17935 (map "abcde" '(3 2 1)) @result{} (#\d #\c #\b)
17936 @end example
17937
17938 @c EN
17939 Among Gauche built-in objects, @code{<regexp>} object and
17940 @code{<regmatch>} object have @code{object-apply} defined.
17941 @xref{Regular expressions}.
17942 @c JP
17943 Gauche組み込みオブジェクトのうち、@code{<regexp>}オブジェクトと
17944 @code{<regmatch>}オブジェクトに対しては@code{object-apply}メソッドが定義されて
17945 います。@ref{Regular expressions}を参照して下さい。
17946 @c COMMON
17947
17948 @c EN
17949 Note: Defining @code{object-apply} method affect globally. Although it is cool
17950 to define @code{object-apply} on strings as in the above example,
17951 it is not recommended as a general trick, for
17952 it'll change the behavior of string across the entire program.
17953
17954 Keep the above example personal experiments. In general, you should
17955 only define @code{object-apply} on your own classes.
17956 @c JP
17957 註: @code{object-apply}メソッドの定義はグローバルに影響します。
17958 上の例のように文字列に@code{object-apply}を定義するのはおもしろいですが、
17959 一般的なトリックとしては推奨されません。これによってプログラム全体での
17960 文字列の振る舞いが変わってしまうからです。
17961
17962 上の例は個人的な実験に留めておきましょう。一般的には、
17963 自分で定義したクラスに対してのみ@code{object-apply}を定義するのが良いです。
17964 @c COMMON
17965
17966
17967 @deffn {Generic Function} {(setter object-apply)} @var{object} @var{arg} @dots{} @var{value}
17968 @c EN
17969 If a form of applying an applicable object appears in the first position
17970 of @code{set!} form, this method is called, that is:
17971 @c JP
17972 適用可能オブジェクトを適用するフォームが@code{set!}フォームの第一ポジションに
17973 現れた場合、そのフォームは下に示すように展開され、このメソッドが呼ばれます。
17974 @c COMMON
17975 @example
17976 (set! (@var{object} @var{arg} @dots{}) @var{value})
17977 @result{} ((setter object-apply) @var{object} @var{arg} @dots{} @var{value})
17978 @end example
17979 @end deffn
17980
17981
17982
17983
17984 @node Continuations, Continuation prompts, Applicable objects, Procedures and continuations
17985 @subsection Continuations
17986 @c NODE 継続
17987
17988
17989 @defun call-with-current-continuation proc
17990 @defunx call/cc proc
17991 [R7RS base]
17992 @c EN
17993 Encapsulates the current continuation to a procedure
17994 (``continuation procedure''), and calls @var{proc} with it.
17995 When @var{proc} returns, its value becomes @code{call/cc}'s value.
17996 When the continuation procedure is invoked with zero or more arguments
17997 somewhere, the further calculation is abandoned and @code{call/cc} returns
17998 with the arguments given to the continuation procedure.
17999 @c JP
18000 現在の継続を手続き (継続手続き) にパッケージ化して、それを引数として
18001 @var{proc}を呼び出します。@var{proc}が戻ったら、その返り値が@code{call/cc}の
18002 値となります。作成された継続手続きがどこかで0個または複数個の引数を伴って呼ばれたら、
18003 あたかも@code{call/cc}から戻ったかのように実行が継続されます。その場合、
18004 @code{call/cc}は、継続手続きに与えられた引数を複数の値として返します。
18005 @c COMMON
18006
18007 @c EN
18008 First class continuation is one of the most distinct feature of Scheme, but
18009 this margin is too small to contain explanation.
18010 Please consult to the appropriate documents.
18011 @c JP
18012 ファーストクラスの継続はSchemeの最も特徴的な機能のひとつですが、それを
18013 十分に説明するにはこの本の余白は狭すぎます。適切なドキュメントを参照してください。
18014 @c COMMON
18015
18016 @c EN
18017 There's a nontrivial interaction between C language runtime and
18018 Scheme continuation. Suppose the following scenario:
18019 @c JP
18020 Schemeの継続とC言語の実行環境との間に、ちょっとわかりずらい干渉が生じることがあります。
18021 次のシナリオを考えます。
18022 @c COMMON
18023
18024 @enumerate
18025 @item
18026 @c EN
18027 An application's C runtime calls back a Scheme routine. For example,
18028 GUI framework calls back a draw routine written in Scheme.
18029 @c JP
18030 アプリケーションのCランタイムがSchemeで書かれた手続きをコールバックします。
18031 例えば、GUIフレームワークがSchemeで書かれた描画ルーチンを呼ぶ、というようなケースを考えてください。
18032 @c COMMON
18033 @item
18034 @c EN
18035 A continuation is captured in the Scheme routine.
18036 @c JP
18037 そのSchemeルーチンで継続が捕捉される。
18038 @c COMMON
18039 @item
18040 @c EN
18041 The Scheme routine returns to the C runtime.
18042 @c JP
18043 Schemeルーチンが終了してCランタイムに制御を戻す。
18044 @c COMMON
18045 @item
18046 @c EN
18047 The continuation captured in 2 is invoked.
18048 @c JP
18049 2で捕捉した継続が起動される。
18050 @c COMMON
18051 @end enumerate
18052
18053 @c EN
18054 It is no problem to invoke the continuation, but if the control
18055 is about to return to the Scheme routine to the C runtime (that is,
18056 to execute step 3 again), an error is signaled as follows.
18057 @c JP
18058 継続を起動すること自体には問題は無いのですが、
18059 制御がSchemeからCへと再び戻ろうとすると (つまり、step 3が再び実行されようとすると)
18060 次のようなエラーが投げられます。
18061 @c COMMON
18062
18063 @example
18064 *** ERROR: attempt to return from a ghost continuation.
18065 @end example
18066
18067 @c EN
18068 This is because C routines don't expect the calling function to return
18069 more than once. The C stack frame on which the Scheme callback was
18070 originally called
18071 is likely to be deallocated or modified at the time the continuation
18072 is invoked.
18073
18074 If you think of a continuation as a chain of control
18075 frames, growing from root towards upward,
18076 you can imagine that, once a control returns to the C world, the chain is
18077 cut at the boundary. You can still execute such rootless
18078 continuations, but you have to move the control away from it before it tries
18079 to return to its root that no longer exists.
18080 You can call another continuation, or raise an exception, for example.
18081 @c JP
18082 これは、Cの世界では関数が1回より多く戻ってくることを想定していないからです。
18083 最初にSchemeのコールバックが呼ばれた時のCのスタックフレームは、
18084 継続が再び呼ばれた時には状態が変わっているか、捨てられてしまっているでしょう。
18085
18086 継続を、根から上へ向かって成長する制御フレームの連鎖のようにイメージした場合、
18087 Cの世界へ戻った時点でその連鎖が断ち切られる、と考えることができます。
18088 そのような根無しの継続も実行することはできますが、既に失った根に戻る前に
18089 別の箇所へと制御を移さねばなりません。他の箇所で捕まえた継続を呼んだり、
18090 例外を投げるといったことが考えられます。
18091 @c COMMON
18092
18093 @c EN
18094 Using partial continuations (or delimited continuations) is another
18095 way to avoid such complications.
18096 @xref{Partial continuations}.
18097 @c JP
18098 部分継続(限定継続)を使うのも手です。
18099 @ref{Partial continuations}を参照してください。
18100 @c COMMON
18101 @end defun
18102
18103 @defmac let/cc var body @dots{}
18104 @c EN
18105 This macro expands to :
18106 @c JP
18107 このマクロは次のように展開されます :
18108 @c COMMON
18109 @code{(call/cc (lambda (@var{var}) @var{body} @dots{}))}.
18110 @c EN
18111 The API is taken from PLT Scheme.
18112 @c JP
18113 APIはPLT Schemeから取りました。
18114 @c COMMON
18115 @end defmac
18116
18117
18118 @defun dynamic-wind before body after
18119 [R7RS base]
18120 @c EN
18121 This is a primitive to manage @emph{dynamic environment}.
18122 Dynamic environment is a set of states which are kept during execution
18123 of a certain expression. For example, the current output ports
18124 are switched @emph{during} execution of @code{with-output-to-port}.
18125 They can be nested dynamically, as opposed to
18126 the lexical environment, in which nesting is determined statically
18127 from the program source.
18128
18129 @var{Before}, @var{body} and @var{after} are all procedures with
18130 no arguments.
18131 In normal situation, @code{dynamic-wind} calls @var{before}, then @var{body},
18132 then @var{after}, then returns whatever value(s) @var{body} returned.
18133
18134 The intention is that the @var{before} thunk sets up the dynamic
18135 environment for execution of @var{body}, and the @var{after} thunk
18136 restores it to the previous state.
18137
18138 If a control flow goes out from @var{body} by invoking a continuation
18139 captured outside of the dynamic scope of @code{dynamic-wind}
18140 (for example, an error is signaled in @var{body}),
18141 @var{after} is called.
18142
18143 If a control flow goes into @var{body} by invoking a continuation
18144 captured inside @var{body} from outside of the dynamic
18145 scope of @code{dynamic-wind}, @var{before} is called.
18146 @c JP
18147 これは@emph{動的環境}を管理するための基本手続きです。
18148 動的環境とは、ある式を実行している間、維持される状態のセットのことです。
18149 例えば「現在の出力ポート」というのは、@code{with-output-to-port}手続きの
18150 @emph{実行中}だけ切り替えることができます。
18151 動的環境は動的にネストできます。これは、プログラムのソースから静的に
18152 ネストが決定できる字句環境とは異なります。
18153
18154 @var{before}、@var{body}および@var{after} は引数を取らない手続きです。
18155 @code{dynamic-wind}はまず@var{before}を呼び出し、続いて@var{body}を呼び出し、
18156 続いて@var{after}を呼び出します。そして@var{body}が返した値を返します。
18157
18158 @var{before}手続きが@var{body}を実行するための動的環境を
18159 設定し、@var{after}手続きが動的環境を元に戻す、ということが意図されています。
18160
18161 もし@code{dynamic-wind}のダイナミックスコープの外で捕捉された継続が
18162 @var{body}の中で呼ばれることにより制御が@var{body}から飛び出した場合、
18163 (@var{body}の中でエラーが起こった場合などが考えられます)、
18164 @var{after}が呼ばれます。
18165
18166 もし、@var{body}の中で捕捉された継続が@code{dynamic-wind}のダイナミックスコープの
18167 外で呼ばれることにより制御が@var{body}の中へ飛び込んだ場合、
18168 @var{before}が呼ばれます。
18169 @c COMMON
18170 @example
18171 (letrec ((paths '())
18172 (c #f)
18173 (add (lambda (s) (push! paths s))))
18174 (dynamic-wind
18175 (lambda () (add 'connect))
18176 (lambda ()
18177 (add (call/cc (lambda (c0) (set! c c0) 'talk1))))
18178 (lambda () (add 'disconnect)))
18179 (if (< (length paths) 4)
18180 (c 'talk2)
18181 (reverse paths)))
18182 @result{} (connect talk1 disconnect connect talk2 disconnect)
18183 @end example
18184
18185 @c EN
18186 Note: Since @var{after} is guaranteed to be called when
18187 an error causes @var{body} to abort, it may appear tempting
18188 to use @code{dynamic-wind} to use resource clean-up, just like
18189 @code{try-catch} construct in Java. It's @emph{not} for that.
18190 Since the control may return to @var{body}, the situation
18191 @code{dynamic-wind} handles should be considered more like
18192 a context switch.
18193
18194 For resource clean-up, you can use exception handling mechanism
18195 such as @code{guard} and @code{unwind-protect}
18196 (@pxref{High-level exception handling mechanism}),
18197 which is built on top of @code{dynamic-wind}.
18198
18199 As a rule of thumb, @var{after} should do things that can be
18200 reverted by @var{before}, such as manipulating error handler stack
18201 (instead of actually handling errors).
18202 @c JP
18203 註:エラーにより@var{body}が中断された時に必ず@var{after}が呼ばれることから、
18204 @code{dynamic-wind}を例えばJavaの@code{try-catch}構文のように考えて
18205 リソースの後処理などに使いたくなるかもしれません。
18206 しかし@code{dynamic-wind}はそのためのものでは@emph{ありません}。
18207 一旦離れた制御が@var{body}に再び戻ってくる可能性があるので、
18208 @code{dynamic-wind}が管理するのはむしろコンテキストスイッチに近い状況です。
18209
18210 リソースの後処理には、@code{guard}や@code{unwind-protect}などの例外処理
18211 が使えます(@ref{High-level exception handling mechanism}参照)。
18212 それらは@code{dynamic-wind}を使って構築されています。
18213
18214 基本的な指針として、@var{after}は常に@var{before}によって効果を戻せる
18215 処理だけを行うべきです。例えば、(エラーを直接処理するのではなく)
18216 エラーハンドラスタックを操作する、といった具合に。
18217 @c COMMON
18218 @end defun
18219
18220 @node Continuation prompts, Continuation marks, Continuations, Procedures and continuations
18221 @subsection Continuation prompts
18222 @c NODE 継続プロンプト
18223
18224 @c EN
18225 Continuations are often explained as ``the rest of computation''.
18226 It is enough for theorists to write papers, but in practice,
18227 we cannot reify the computations ``from now on for ever''. There has
18228 to be an end--it may be until a single program terminates, or
18229 until a server returns a response to a request, or a REPL
18230 prints the result of evaluation. Implementations
18231 have chosen the ``end'' of continuations suitable for there needs.
18232 Sometimes, though, the ambiguity caused confusion.
18233 @c JP
18234 継続はよく「計算の残りの部分」と説明されます。理論家が論文を書くにはそれで充分なんですが、
18235 現実には、「未来永劫の計算全て」を具体化することはできません。
18236 どこかに終わりがないと困ります。それはひとつのプログラムの終了かもしれませんし、
18237 サーバーがリクエストに対するレスポンスを送り終えるまでかもしれませんし、
18238 REPLが与えられた式の評価結果を出力し終わるまでかもしれませんが。
18239 従来は、実装が必要に応じて継続の「終わり」を選んできたのですが、
18240 これはしばしば混乱の元になっていました。
18241 @c COMMON
18242
18243 @c EN
18244 Continuation prompts are to make the ``end'' of continuation explicit.
18245 It is called a prompt because, in the interactive environment,
18246 REPL prompt is usually delimits the continuation. If you think
18247 of activation records as a stack, a continuation prompt is
18248 the ``bottom'' of the stack.
18249 @c JP
18250 継続プロンプトは、継続の「終わり」を明示するものです。
18251 「プロンプト」の名前の由来は、インタラクティブな環境ではREPLのプロンプトが
18252 継続の区切りになっていることです。アクティベーションレコードを良くあるスタックモデルで
18253 理解するなら、継続プロンプトはスタックの「底」にあたります。
18254 @c COMMON
18255
18256 @c EN
18257 Furthermore, you can have multiple kinds of continuation prompts,
18258 so that multiple features that use continuation prompts independently
18259 won't step on each other.
18260 @c JP
18261 さらに、複数種類の継続プロンプトを使うことができます。これは、
18262 継続プロンプトを利用して実装された複数の独立した機能が、うっかり干渉し合わないように
18263 するためのものです。
18264 @c COMMON
18265
18266 @c EN
18267 (Partial continuations can also be defined on top of continuation prompts,
18268 and SRFI-226 indeed defines so. We'll integrate existing partial
18269 continuations with continuation prompts in future versions.)
18270 @c JP
18271 (部分継続は継続プロンプトを使って実装でき、実際、SRFI-226はそのように定義しています。
18272 Gaucheの従来の部分継続は将来のバージョンで継続プロンプトと統合される予定です。)
18273 @c COMMON
18274
18275 @defun make-continuation-prompt-tag :optional name
18276 [SRFI-226]
18277 @c EN
18278 Creates and returns a new continuation prompt tag,
18279 which is an opaque object to specify the boundary
18280 of continuation frames. A new boundary can be introduced
18281 with @code{call-with-continuation-prompt}. You can nest bounded
18282 continuation frames with the smae continuation prompt tag. Operations
18283 that takes a continuation prompt tag seraches the innermost boundary
18284 with the tag.
18285
18286 The optional @var{name} argument is the name of the continuation
18287 prompt tag. It is for display purpose only to help diagnostics.
18288 @c JP
18289 新たな継続プロンプトタグを作って返します。
18290 継続プロンプトタグは、継続フレームの境界を指定するのに使うオブジェクトです。
18291 新しい境界は@code{call-with-continuation-prompt}で導入されます。
18292 ひとつの継続プロンプトタグを使いまわして、継続フレームの境界をネストすることもできます。
18293 継続プロンプトタグを取る手続きは、そのタグを持つ最も内側の境界を使います。
18294
18295 省略可能な@var{name}は継続プロンプトタグの名前です。
18296 これは単に、診断を容易にするために表示するためだけのものです。
18297 @c COMMON
18298 @end defun
18299
18300 @defun default-continuation-prompt-tag
18301 [SRFI-226]
18302 @c EN
18303 Returns a default continuation prompt tag.
18304 When the program starts, the initial continuation boundary
18305 has the default continaution prompt tag.
18306 Most procedures that takes an optional continuation prompt tag
18307 assumes the default tag if the argument is omitted.
18308 @c JP
18309 デフォルト継続プロンプトタグを返します。
18310 プログラムが開始された時、最初の継続フレームの境界はデフォルト継続プロンプトタグを持ちます。
18311 継続プロンプトタグを省略可能引数として取る手続きはほとんど、
18312 省略時にデフォルト継続プロンプトタグを使います。
18313 @c COMMON
18314 @end defun
18315
18316 @defun continuation-prompt-tag? obj
18317 [SRFI-226]
18318 @c EN
18319 Returns @code{#t} if @var{obj} is a continuation prompt tag,
18320 @code{#f} otherwise.
18321 @c JP
18322 @var{obj}が継続プロンプトタグなら@code{#t}を、そうでなければ@code{#f}を返します。
18323 @c COMMON
18324 @end defun
18325
18326 @defun call-with-continuation-prompt thunk :optional prompt-tag abort-handler
18327 [SRFI-226]
18328 @c EN
18329 Calls @var{thunk} with a continuation delimited by a continuation prompt tag
18330 @var{prompt-tag}. If @var{prompt-tag} is omitted, the default prompt
18331 tag is assumed.
18332
18333 The @var{abort-handler} is a procedure to be called when, during executing
18334 @var{thunk}, its continuation is aborted by
18335 @code{abort-current-continuation}. The objects passed to
18336 @code{abort-current-continuation} are passed to @var{abort-handler},
18337 which is called with the continuation of @var{call-with-continuation-prompt}
18338 itself. If @var{thunk} doesn't abort the continuation,
18339 @var{abort-handler} won't be called.
18340
18341 When @var{abort-handler} is omitted, it installs a default abort handler,
18342 which work in a very specific way. First, it takes one argument, which must
18343 be a thunk (let's call it @var{continuation-thunk} for now).
18344 The default abort handler reinstates
18345 the continuation with the continuation prompt tag @var{prompt-tag} and
18346 calls the continuation thunk. Say, it works like a trampoline to push
18347 back the control to the same context as @var{thunk} is called.
18348 @c JP
18349 継続プロンプトタグ@var{prompt-tag}で区切られた継続の上で@var{thunk}を呼び出します。
18350 @var{prompt-tag}が省略された場合はデフォルト継続プロンプトタグが使われます。
18351
18352 @var{abort-handler}は手続きで、@var{thunk}実行中にその継続が
18353 @code{abort-current-continuation}によって破棄された場合に呼ばれます。
18354 @code{abort-current-continuation}に渡されるオブジェクトが@var{abort-handler}
18355 に引数として渡されます。
18356 @var{abort-handler}自身は、@code{call-with-continuation-prompt}の継続の上で
18357 実行されます。
18358 @var{thunk}が実行中に継続を破棄しなかった場合は@var{abort-handler}は呼ばれません。
18359
18360 @var{abort-handler}が省略された場合はデフォルトのアボートハンドラが使われますが、
18361 それはちょっと特殊な動作をします。まず、デフォルトアボートハンドラは
18362 一つだけ引数を取り、それはサンクでなければなりません
18363 (ここでは@var{continuation-thunk}と呼ぶことにします)。
18364 デフォルトアボートハンドラは@var{prompt-tag}で区切られた継続を改めて導入し、
18365 @var{continuation-thunk}を呼び出します。いわば、トランポリンのように、
18366 @var{thunk}がもともと呼ばれた文脈に制御を戻すようなものです。
18367 @c COMMON
18368
18369 @c EN
18370 See the entry of @code{abort-current-continuation} below
18371 for exmaples.
18372 @c JP
18373 例については下の@code{abort-current-continuation}の項を参照してください。
18374 @c COMMON
18375 @end defun
18376
18377 @defun abort-current-continuation prompt-tag obj @dots{}
18378 [SRFI-226]
18379 @c EN
18380 Aborts all active procedure calls in the current continuation up to
18381 the continuation prompt tagged with @var{prompt-tag}. The control
18382 goes to the abort handler installed by the most recent
18383 @code{call-with-continuation-prompt} with the @var{prompt-tag}.
18384 The rest of the arguments @var{obj} @dots{} are passed to the
18385 abort handler.
18386
18387 When the current continuation does not have a continuation prompt
18388 tagged with @var{prompt-tag}, a @code{<continuation-violation>} error
18389 is thrown.
18390 @c JP
18391 現在の継続から、@var{prompt-tag}でタグ付けられた継続プロンプトまでの
18392 継続を破棄して、その@var{prompt-tag}を導入した
18393 @code{call-with-continuation-prompt}のアボートハンドラに制御を移します。
18394 残りの引数@var{obj} @dots{}はアボートハンドラに引数として渡されます。
18395
18396 現在の継続の先に@var{prompt-tag}を持つ継続プロンプトが無かった場合は
18397 @code{<continuation-violation>}エラーが投げられます。
18398 @c COMMON
18399
18400 @example
18401 (let ([tag (make-continuation-prompt-tag)])
18402 (call-with-continuation-prompt
18403 (^[] (+ 1 (abort-current-continuation tag 'foo 'bar) 2))
18404 tag
18405 list))
18406 @result{} (foo bar)
18407 @end example
18408
18409 @c EN
18410 If a dynamic handlers are inserted in the continuation frames
18411 to be aborted, their `after' handlers are executed before
18412 the abort handler is called.
18413 @c JP
18414 もし動的ハンドラが破棄される継続フレーム中に挿入されていたら、
18415 その `after' ハンドラはアボートハンドラの前に実行されます。
18416 @c COMMON
18417
18418 @example
18419 (let ((tag (make-continuation-prompt-tag)))
18420 (call-with-continuation-prompt
18421 (^[]
18422 (dynamic-wind
18423 (^[] #f)
18424 (^[] (abort-current-continuation tag 'foo))
18425 (^[] (print 'yo))))
18426 tag
18427 print))
18428 @result{} @r{prints @code{yo}, then prints @code{foo}}.
18429 @end example
18430 @end defun
18431
18432
18433 @c EN
18434 You may wonder the difference between the traditional @code{call/cc}
18435 and the combination of @code{call-with-continuation-prompt} and
18436 @code{abort-current-continuation}. Actually the latter is more
18437 lower-level construct, and @var{call/cc} is a high-level construct
18438 implemented on top of it.
18439 @c JP
18440 ここまで読んできて、従来の@code{call/cc}に対して、
18441 @code{call-with-continuation-prompt}と@code{abort-current-continuation}
18442 の組み合わせがどう違うのかと思ったかもしれません。
18443 実は後者はより低レベルの構造で、@code{call/cc}はその上に実装される高レベル構造なのです。
18444 @c COMMON
18445
18446 @node Continuation marks, Multiple values, Continuation prompts, Procedures and continuations
18447 @subsection Continuation marks
18448 @c NODE 継続マーク
18449
18450 @c EN
18451 Continuation marks are a set of key-value associations
18452 attached to continuation frames. Keys and values are arbitrary
18453 Scheme object. It sounds obscure, but it allows to implement
18454 various useful language features; notably, the new @code{parameterize}
18455 is implemented on top of continuation marks, allowing its body
18456 to be evaluated in tail context (@pxref{Parameters}).
18457 @c JP
18458 継続マークは、継続フレームに付加されるキーと値の関連です。
18459 キーと値には任意のSchemeuオブジェクトが使えます。
18460 これだけ聞いてもなんだかよく分からないかもしれませんが、
18461 継続マークを使って色々便利な言語機能を実装することができます。
18462 例えば、新しい@code{parameterize}は本体を末尾コンテクストで評価することが
18463 できますが、それは継続マークを使って実装されているからです。
18464 @c COMMON
18465
18466 @itemize @bullet
18467 @item
18468 @c EN
18469 You can have dynamic-scoped data without compromizing tail-calls.
18470 Using @code{dynamic-wind} requires to run the `after' thunk after
18471 evaluating the body, so if you wrap a tail expression with it,
18472 the original expression won't be in tail context anymore.
18473 Continuation marks, on the other hand, will be discarded when
18474 the continuation frame they are attached to is `popped', so you
18475 don't need to clean up after the body is executed. So the body
18476 is exected in the tail context if the dynmaic-scope itself
18477 is in tail context.
18478 @c JP
18479 適切な末尾呼び出し条件を犠牲にすることなしに、動的スコープを持つデータを実装できます。
18480 @code{dynamic-wind}を使う方法だと、本体を実行したあとに `after' サンクを
18481 実行しなければならないので、元の式が末尾位置にあったとしても、
18482 @code{dynamic-wind}でくるむと末尾位置でなくなってしまいます。
18483 継続マークは、それが付加された継続フレームが「ポップ」されると
18484 一緒に捨てられるため、本体実行後に後始末コードを走らせる必要がありません。
18485 なので元の式が末尾位置にあれば、本体を末尾位置で実行することができます。
18486 @c COMMON
18487 @item
18488 @c EN
18489 Since tail expression shares a continuation frame with its
18490 caller, you can detect whether an expression is evaluated
18491 at the tail position @emph{at run-time}.
18492 @c JP
18493 末尾式は継続フレームを呼び出し元と共有するので、
18494 ある式が末尾位置で実行されるかどうかを@emph{実行時に}判定することができます。
18495 @c COMMON
18496 @end itemize
18497
18498 @c EN
18499 In general, though, continuations marks are low-level tools
18500 to construct high-level features, rather than to be
18501 used as day-to-day tools.
18502 @c JP
18503 ただ、一般的には継続マークは他の高レベルな言語機能を
18504 実装するための低レベルなツールと考えるべきでしょう。
18505 日常的なコードで使うものではありません。
18506 @c COMMON
18507
18508 @c EN
18509 @subsubheading Marking a continuation frame
18510 @c JP
18511 @subsubheading 継続フレームをマークする
18512 @c COMMON
18513
18514 @defspec with-continuation-mark key value expr
18515 [SRFI-226]
18516 @c EN
18517 Both @var{key} and @var{value} are evaluated, and
18518 adds the key-value association as a mark to the current continuation,
18519 then evaluate @var{expr} with the same continuation as this form.
18520 That is, if this form is in the tail context, @var{expr} is
18521 evaluated in the same tail context.
18522 @c JP
18523 まず@var{key}と@var{value}が評価され、そのキー-値の関連が
18524 現在の継続のマークに追加されます。
18525 そして、@var{expr}がこのフォームの継続と同じ継続で評価されます。
18526 つまり、このフォーム自体が末尾コンテクストにあれば、
18527 @var{expr}も末尾コンテクストで評価されます。
18528 @c COMMON
18529
18530 @c EN
18531 If the current continuation is already marked with @var{key}, then its value
18532 is replaced with @var{value}.
18533 @c JP
18534 現在の継続フレームのマークに既に@var{key}があれば、その値が@var{value}で置き換えられます。
18535 @c COMMON
18536 @end defspec
18537
18538 @defmac with-continuation-marks ((key value) @dots{}) expr
18539 [SRFI-226]
18540 @c EN
18541 All @var{key}s and @var{value}s are evaluted, then
18542 add those key-value associations as marks to the current continuation,
18543 then evaluate @var{expr} with the same continuation as this form.
18544 @c JP
18545 @var{key}と@var{value}がすべて評価された後、それらキー-値ペア全てが
18546 現在の継続のマークに追加され、同じ継続で@var{expr}が評価されます。
18547 @c COMMON
18548 @end defmac
18549
18550 @c EN
18551 @subsubheading Extracting continuation marks
18552 @c JP
18553 @subsubheading 継続マークを取り出す
18554 @c COMMON
18555
18556 @defun call-with-immediate-continuation-mark key proc :optional fallback
18557 [SRFI-226]
18558 @c EN
18559 Tail-calls @var{proc} with the value for @var{key} associated
18560 in the current continuation. If the current continuation doesn't have
18561 a value for @var{key}, @var{fallback} is passed to @var{proc} instead.
18562 If @var{fallback} is omitted, @code{#f} is assumed.
18563 @c JP
18564 現在の継続のマーク中の@var{key}に対応する値を引数として、@var{proc}を末尾呼び出しします。
18565 現在の継続のマーク中に@var{key}がなければ@var{fallback}が使われます。
18566 @var{fallback}が省略された場合は@code{#f}が使われます。
18567 @c COMMON
18568
18569 @example
18570 (with-continuation-mark 'a 'b
18571 (call-with-immediate-continuation-mark 'a list))
18572 @result{} (b)
18573
18574 (with-continuation-mark 'a 'b
18575 (cons (call-with-immediate-continuation-mark 'a list) 1))
18576 @result{} ((#f) . 1)
18577 @end example
18578 @end defun
18579
18580 @defun continuation-marks cont :optional prompt-tag
18581 [SRFI-226]
18582 @c EN
18583 Returns a continuation mark set object, which contains continuation
18584 marks of the confinutaion frames between the continuation @var{cont}
18585 and the continuation delimited by @var{prompt-tag}. If @var{prompt-tag}
18586 is omitted, default prompt tag is assumed.
18587 @c JP
18588 継続@var{cont}から@var{prompt-tag}で区切られる継続フレームまでの継続マークを
18589 集めた、継続マークセットオブジェクトを返します。
18590 @var{prompt-tag}が省略された場合はデフォルトプロンプトタグが使われます。
18591 @c COMMON
18592 @end defun
18593
18594 @defun current-continuation-marks :optional prompt-tag
18595 [SRFI-226]
18596 @c EN
18597 Returns a continuation mark set object, which contains continuation
18598 marks of the confinutaion frames between the current continuation
18599 and the continuation delimited by @var{prompt-tag}. If @var{prompt-tag}
18600 is omitted, default prompt tag is assumed.
18601 @c JP
18602 現在の継続から@var{prompt-tag}で区切られる継続フレームまでの継続マークを
18603 集めた、継続マークセットオブジェクトを返します。
18604 @var{prompt-tag}が省略された場合はデフォルトプロンプトタグが使われます。
18605 @c COMMON
18606 @end defun
18607
18608 @c EN
18609 @subsubheading Continuation mark set
18610 @c JP
18611 @subsubheading 継続マークセット
18612 @c COMMON
18613
18614 @defun continuation-mark-set? obj
18615 [SRFI-226]
18616 @c EN
18617 Returns @code{#t} if @var{obj} is a continuation mark set,
18618 @code{#f} otherwise.
18619 @c JP
18620 @var{obj}が継続マークセットなら@code{#t}を、そうでなければ@code{#f}を返します。
18621 @c COMMON
18622 @end defun
18623
18624 @defun continuation-mark-set->list mark-set key :optional prompt-tag
18625 [SRFI-226]
18626 @c EN
18627 Pick up values associated to @var{key} from a continuation mark set
18628 @var{mark-set}, and returns a fresh list of them. A value in more
18629 recent continuation frames come earlier in the list.
18630
18631 You can pass @code{#f} to @var{mark-set} to make the procedure
18632 use @code{(current-continuation-marks prompt-tag)}.
18633
18634 It searches the mark set up to the continuation frame delimited
18635 by a continuation prompt @var{prompt-tag}.
18636 If @var{prompt-tag} is omitted, the default prompt tag is used.
18637 @c JP
18638 継続マークセット@var{mark-set}から、@var{key}を持つマークに対応する値を
18639 全て取り出し、新しいリストにして返します。より新しい継続フレームに対応する値ほど
18640 リストの先頭の方に置かれます。
18641
18642 @var{mark-set}に@code{#f}を渡すこともできます。その場合、
18643 @code{(current-continuation-marks prompt-tag)}が使われます。
18644
18645 @var{key}は、継続マークセット中の、@var{prompt-tag}で指定される継続プロンプト
18646 に対応する継続マークまで探されます。@var{prompt-tag}が省略された場合は
18647 デフォルトプロンプトタグが使われます。
18648 @c COMMON
18649 @end defun
18650
18651 @defun continuation-mark-set-first mark-set key :optional fallback prompt-tag
18652 [SRFI-226]
18653 @c EN
18654 Returns the most recent value associated with @var{key} in the
18655 continuation mark set @var{mark-set}. If there's a mark with @var{key} exists,
18656 it matches @code{(car (continuation-mark-set->list key prompt-tag)}.
18657
18658 If there's no mark with @var{key} in the mark set, @var{fallback}
18659 is returned. If @var{fallback} is omitted, @code{#f} is assumed.
18660
18661 If @var{prompt-tag} is omitted, the default prompt tag is used.
18662 @c JP
18663 継続マークセット@var{mark-set}のうち、@var{key}に結びつけられた最も新しい値を
18664 返します。もし@var{key}がマークセットの中にあるなら、
18665 値は@code{(car (continuation-mark-set->list key prompt-tag)}と同じになります。
18666
18667 @var{key}がマークセット中に無い場合は@var{fallback}が返ります。
18668 @var{fallback}が省略された場合は@code{#f}になります。
18669
18670 @var{prompt-tag}が省略された場合はデフォルトプロンプトタグが使われます。
18671 @c COMMON
18672 @end defun
18673
18674 @c EN
18675 @subsubheading Continuation mark key
18676 @c JP
18677 @subsubheading 継続マークキー
18678 @c COMMON
18679
18680 @c EN
18681 You can use arbitrary Scheme object as keys for continuation marks,
18682 but you if you're writing libraries, you want to make sure that
18683 your keys won't conflict with the keys used by other parts of the code.
18684
18685 A continuation mark key is an opaque object that is guaranteed to
18686 be different (in terms of @code{equal?}) to other continuation mark keys.
18687 @c JP
18688 継続マークのキーには任意のSchemeオブジェクトを使えますが、
18689 例えばライブラリを書いている場合、使っているキーが偶然他で使われているキーと
18690 かぶってしまうのは望ましくありません。
18691
18692 継続マークキーは、他の継続マークキーと(@code{equal?}で)等しくならないことが
18693 保証されているオブジェクトです。
18694 @c COMMON
18695
18696 @defun make-continuation-mark-key :optional name
18697 [SRFI-226]
18698 @c EN
18699 Returns a newly created continuation key, which is guaranteed never
18700 to be equal to any prior or future continuation mark keys.
18701
18702 The optional @var{name} argument is for debugging purpose.
18703 @c JP
18704 これ以前の継続マークキーとも、以降のマークキーとも決して重ならない
18705 新たな継続マークキーを作って返します。
18706
18707 @var{name}引数はデバッグ用です。
18708 @c COMMON
18709
18710 @c EN
18711 Note that SRFI-226 does not require a continuation mark key has disjoint
18712 types from other Scheme types. Currently, Gauche uses an uninterned
18713 symbol as a continuation mark key. It may be changed in future,
18714 so do not count on it.
18715 @c JP
18716 SRFI-226は継続マークキーが他のSchemebオブジェクトと異なる型であることを
18717 要請していないことに注意してください。今のところ、Gaucheではインターンされていない
18718 シンボルを継続マークキーとして返しています。これは将来変わるかもしれないので、
18719 それに依存したコードは書かないようにしてください。
18720 @c COMMON
18721 @end defun
18722
18723 @defun continuation-mark-key? obj
18724 [SRFI-226]
18725 @c EN
18726 Returns @code{#t} if @var{obj} can be an object returned by
18727 @code{make-continuation-mark-key}, @code{#f} otherwise.
18728
18729 Note that SRFI-226 does not require a continuation mark key has a disjoint
18730 type, so this may return @code{#t} for an object that's not
18731 created by @code{make-continuation-mark-key}.
18732 In fact, Gauche currently uses an uninterned symbol for a continuation
18733 mark key, and this procedure returns @code{#t} for any symbols.
18734 @c JP
18735 @var{obj}が@code{make-continuation-mark-key}が返したオブジェクトである可能性が
18736 あれば@code{#t}を、そうでなければ@code{#f}を返します。
18737
18738 SRFI-226は継続マークキーが独自の型を持つことを要請していないので、この手続きは
18739 @var{obj}が@code{make-continuation-mark-key}で作られたものでなくても@code{#t}を
18740 返し得ることに注意してください。
18741 実際、Gaucheは今のところインターンされていないシンボルを継続マークキーとして
18742 返しているので、この手続きはシンボルに対して@code{#t}を返します。
18743 @c COMMON
18744 @end defun
18745
18746 @node Multiple values, Folding generated values, Continuation marks, Procedures and continuations
18747 @subsection Multiple values
18748 @c NODE 多値
18749
18750 @defun values obj @dots{}
18751 [R7RS base]
18752 @c EN
18753 Returns @var{obj} @dots{} as multiple values.
18754 Caller can capture multiple values by a built-in syntax
18755 @code{receive} or @code{let-values}
18756 (@ref{Binding constructs}), or the R7RS procedure
18757 @code{call-with-values} described below.
18758 @c JP
18759 @var{obj} @dots{} を多値として返します。
18760 呼び出し側は、組み込み構文の @code{receive}や@code{let-values}
18761 (@ref{Binding constructs}参照)か、
18762 下に説明するR7RSの手続き@code{call-with-values}を使って多値を受け取ることが
18763 できます。
18764 @c COMMON
18765 @example
18766 (values 1 2) @result{} 1 @r{and} 2
18767 @end example
18768 @end defun
18769
18770 @defun call-with-values producer consumer
18771 [R7RS base]
18772 @c EN
18773 Call a procedure @var{producer} with no argument.
18774 Then applies a procedure @var{consumer} on the
18775 value(s) @var{producer} returned. Returns the value(s) @var{consumer}
18776 returns.
18777 @c JP
18778 手続き@var{producer}を引数無しで呼びます。そして、それが返した値
18779 を引数として@var{consumer}を呼びます。@var{consumer}が返す値を
18780 返します。
18781 @c COMMON
18782 @example
18783 (call-with-values (lambda () (values 1 2)) cons)
18784 @result{} (1 . 2)
18785 @end example
18786 @end defun
18787
18788 @defmac values-ref mv-expr k
18789 @c EN
18790 Returns @var{k}-th value of what @var{mv-expr} returns.
18791 Conceptually, it is the same as the following code.
18792 @c JP
18793 @var{mv-expr}が返す多値の@var{k}-番目の値を返します。概念としては、
18794 以下のコードと同じです。
18795 @c COMMON
18796 @example
18797 (call-with-values (lambda () mv-expr) (lambda r (list-ref r k)))
18798 @end example
18799 @c EN
18800 This macro uses shortcuts for the typical cases like @var{k} is zero.
18801
18802 Similar to Common Lisp's @code{nth-value}, but the argument order
18803 is flipped to match other Scheme's @code{*-ref} procedures.
18804 @c JP
18805 このマクロは k がゼロであるような典型的な場合にはより単純な形へと
18806 展開されます。
18807
18808 Common Lisp の @code{nth-value} に似ていますが、引数の順が逆になっています。
18809 Scheme の他の@code{*-ref} 手続きと合わせるためです。
18810 @c COMMON
18811
18812 @c EN
18813 SRFI-210's @code{value/mv} is an enhancement of @code{values-ref}
18814 (@pxref{Procedures and syntax for multiple values}).
18815 @c JP
18816 SRFI-210の@code{value/mv}は@code{values-ref}の拡張になっています
18817 (@ref{Procedures and syntax for multiple values}参照)。
18818 @c COMMON
18819
18820 @example
18821 (values-ref mv-expr k) @equiv{} (value/mv k mv-expr)
18822 @end example
18823 @end defmac
18824
18825 @defmac values->list mv-expr
18826 @c EN
18827 Evaluates @var{mv-expr}, puts all the results into a list
18828 and returns it. It is called @code{multiple-value-list} in
18829 Common Lisp.
18830 @c JP
18831 @var{mv-expr}を評価し、結果の値をリストにして返します。Common Lispで
18832 @code{multiple-value-list}と呼ばれているものです。
18833 @c COMMON
18834
18835 @example
18836 (values->list (div-and-mod 10 3)) @result{} (3 1)
18837
18838 (values->list 1) @result{} (1)
18839 @end example
18840
18841 @c EN
18842 SRFI-210's @code{list/mv} is an enhancement of @code{values->list}
18843 (@pxref{Procedures and syntax for multiple values}).
18844 @c JP
18845 SRFI-210の@code{list/mv}は@code{values->list}の拡張になっています
18846 (@ref{Procedures and syntax for multiple values}参照)。
18847 @c COMMON
18848
18849 @example
18850 (values->list mv-expr) @equiv{} (list/mv mv-expr)
18851 @end example
18852 @end defmac
18853
18854 @node Folding generated values, , Multiple values, Procedures and continuations
18855 @subsection Folding generated values
18856 @c NODE 生成された値の畳み込み
18857
18858 @c EN
18859 Sometimes a procedure is used as a @emph{generator} of a series
18860 of values, by yielding one value at a time. Customary an EOF
18861 object is used to mark the end of the series. For example,
18862 @code{read-char} is such a procedure that yields a series
18863 of characters, terminated by EOF.
18864 @c JP
18865 一回呼ばれる度にひとつの値を生成するような手続きは、
18866 一連の値を生成する@emph{ジェネレータ}として使われることがあります。
18867 値の終端を表すマークとしては、慣例としてEOFが使われます。
18868 例えば@code{read-char}はそうした、一連の文字を生成し、終端としてEOFを返す手続きです。
18869 @c COMMON
18870
18871 @c EN
18872 Since it is such a handy abstraction, Gauche provides a
18873 set of utilities (see @ref{Generators}) to construct and generators
18874 out of various sources, including other generators.
18875 @c JP
18876 こうした抽象化は手軽であるため、Gaucheは、他のジェネレータを含むさまざまなソースから
18877 ジェネレータを構築するユーティリティをひとそろい提供しています。
18878 @c COMMON
18879
18880 @c EN
18881 The generated values needs to be consumed eventually. Here we
18882 provide several procedures to do that. These are useful
18883 when combined with input procedures like @code{read}, so we
18884 have them built-in instead of putting them in a separate module.
18885 @c JP
18886 生成された値は最終的に消費されなければなりません。そのための手続きもいくつか
18887 提供されています。こうした手続きは、@code{read}のような入力手続きと組み合わせるのに
18888 有用です。このため、別のモジュールに分割するのではなく、組み込み手続きになっています。
18889 @c COMMON
18890
18891 @defun generator-fold proc seed gen gen2 @dots{}
18892 [R7RS generator]
18893 @c EN
18894 Works like @code{fold} on the generated values by generator
18895 procedures @var{gen} @var{gen2} @dots{} (@xref{Walking over lists},
18896 for the details of @code{fold}).
18897 @c JP
18898 ジェネレータである手続き @var{gen} @var{gen2} @dots{} が生成する値に対して
18899 @code{fold} のように働きます(@code{fold}の詳細は@ref{Walking over lists}参照)。
18900 @c COMMON
18901
18902 @c EN
18903 When one generator is given, for each value @var{v} generated by @var{gen},
18904 @var{proc} is called as @code{(@var{proc} @var{v} @var{r})}, where
18905 @var{r} is the current accumulated result; the initial value of the
18906 accumulated result is @var{seed},
18907 and the return value from @var{proc} becomes the next accumulated result.
18908 When @var{gen} returns EOF, the accumulated result at that time is returned
18909 from @code{generator-fold}.
18910 @c JP
18911 引数としてジェネレータがひとつ与えられると、その @var{gen} が生成する各値 @var{v} に
18912 対して、@var{proc} が @code{(@var{proc} @var{v} @var{r})} のように呼び出されます。
18913 @var{r}は現在の積算結果であり、その初期値は @var{seed} です。そして、@var{proc} が
18914 返す値が次回の @var{proc} 呼び出し時の積算値として渡されることになります。
18915 @var{gen}がEOFを返すと、その時点の積算値が @code{generator-fold} から値として
18916 返されます。
18917 @c COMMON
18918
18919 @c EN
18920 When more than one generator is given, @var{proc} is
18921 called as @code{(@var{proc} @var{v1} @var{v2} @dots{} @var{r})},
18922 where @var{v1}, @var{v2} @dots{} are the values yielded from
18923 @var{gen}, @var{gen2}, @dots{}, respectively, and @var{r} is
18924 the current accumulated result. The iteration terminates when
18925 any one of the generators returns EOF.
18926 @c JP
18927 2つ以上のジェネレータが渡された場合は、@var{proc}は
18928 @code{(@var{proc} @var{v1} @var{v2} @dots{} @var{r})} のように呼び出されます。
18929 @var{v1}, @var{v2} @dots{} はそれぞれ @var{gen}, @var{gen2}, @dots{} が生成
18930 した値であり、@var{r}は現在の積算値です。ジェネレータのどれかひとつ以上がEOFを返すと、
18931 イテレーションは終了します。
18932 @c COMMON
18933
18934 @example
18935 (with-input-from-string "a b c d e"
18936 (cut generator-fold cons 'z read))
18937 @result{} (e d c b a . z)
18938 @end example
18939 @end defun
18940
18941 @defun generator-fold-right proc seed gen gen2 @dots{}
18942 @c EN
18943 Works like @code{fold-right} on the generated values by generator
18944 procedures @var{gen} @var{gen2} @dots{} (@pxref{Walking over lists},
18945 for the details of @code{fold-right}).
18946 @c JP
18947 ジェネレータである手続き@var{gen} @var{gen2} @dots{}が生成する値に対して
18948 @code{fold-right}のように働きます(@code{fold-right}の詳細は@ref{Walking over lists}参照)。
18949 @c COMMON
18950
18951 @c EN
18952 This is provided for completeness, but it isn't a good way to
18953 handle generators; in order to combine values right-associatively,
18954 we should read all the values from the generators (until any one
18955 of the generator returns EOF), then start
18956 calling @var{proc} as
18957 @c JP
18958 この手続きは完全性のために提供されていますが、ジェネレータとの相性はあまり良くありません。
18959 値を右結合で計算していくためには、ジェネレータから(少なくともどれかひとつのジェネレータがEOFを返すまで)
18960 全ての値を読み取らなければなりません。そうして初めて @var{proc} の呼び出しが始まることになります。
18961 @c COMMON
18962 @example
18963 (proc v0_0 v1_0 ... (proc v0_1 v1_1 ... (proc v0_n v1_n ... seed) ...))
18964 @end example
18965 @c EN
18966 where @var{vn_m} is the @var{m}-th value yielded by @var{n}-th generator.
18967 @c JP
18968 @var{vn_m}は、@var{n}番目のジェネレータが@var{m}回目の呼び出しで返した値です。
18969 @c COMMON
18970
18971 @example
18972 (with-input-from-string "a b c d e"
18973 (cut generator-fold-right cons 'z read))
18974 @result{} (a b c d e . z)
18975 @end example
18976
18977 @c EN
18978 As you see, keeping all intermediate values kind of defeats the
18979 benefit of generators.
18980 @c JP
18981 ごらんのように、全ての中間値を保持することで、ジェネレータの利点が
18982 ある意味帳消しになってしまうのです。
18983 @c COMMON
18984 @end defun
18985
18986 @defun generator-for-each proc gen gen2 @dots{}
18987 [R7RS generator]
18988 @c EN
18989 A generator version of @code{for-each}. Repeatedly applies @var{proc} on
18990 the values yielded by @var{gen}, @var{gen2} @dots{} until any one of
18991 the generators yields EOF. The values returned from @var{proc} are discarded.
18992 @c JP
18993 ジェネレータ版の@code{for-each}です。@var{gen}, @var{gen2} @dots{} が生成する
18994 値に対して、ジェネレータのどれかがEOFを返すまで @var{proc} を繰り返し適用していきます。
18995 @var{proc}が返す値は無視されます。
18996 @c COMMON
18997
18998 @c EN
18999 This is a handy procedure to consume generated values with side effects.
19000 @c JP
19001 これは、生成される値を副作用で消費するのに便利です。
19002 @c COMMON
19003 @end defun
19004
19005 @defun generator-map proc gen gen2 @dots{}
19006 @c EN
19007 A generator version of @code{map}. Repeatedly applies @var{proc} on
19008 the values yielded by @var{gen}, @var{gen2} @dots{} until any one of
19009 the generators yields EOF. The values returned from @var{proc}
19010 are collected into a list and returned.
19011 @c JP
19012 ジェネレータ版の@code{map}です。@var{gen}, @var{gen2} @dots{} が生成する
19013 値に対して、ジェネレータのどれかがEOFを返すまで @var{proc} を繰り返し適用していきます。
19014 @var{proc}が返す値をひとつのリストに束ねて返します。
19015 @c COMMON
19016
19017 @example
19018 (with-input-from-string "a b c d e"
19019 (cut generator-map symbol->string read))
19020 @result{} ("a" "b" "c" "d" "e")
19021 @end example
19022
19023 @c EN
19024 The same effects can be achieved by combining @code{generator->list}
19025 and @code{gmap} (@pxref{Generator operations}). This procedure
19026 is provided for the backward compatibility.
19027 @c JP
19028 @code{generator->list}と@code{gmap}(@ref{Generator operations}参照)の組み合わせと
19029 同じ挙動を実現します。この手続きは後方互換性のために提供されています。
19030 @c COMMON
19031
19032 @example
19033 (generator->list (gmap proc gen gen2 @dots{}))
19034 @end example
19035 @end defun
19036
19037 @defun generator-find pred gen
19038 [R7RS generator]
19039 @c EN
19040 Returns the first item from the generator @var{gen} that satisfies
19041 the predicate @var{pred}.
19042 @c JP
19043 ジェネレータ@var{gen}から返された中から、述語@var{pred}を満たす最初の要素を返します。
19044 @c COMMON
19045
19046 @c EN
19047 The following example returns the first line matching the regexp
19048 @code{#/XYZ/} from the file @file{foo.txt}.
19049 @c JP
19050 以下の例は、ファイル@file{foo.txt}の中から正規表現@code{#/XYZ/}にマッチする最初の行を返します。
19051 @c COMMON
19052
19053 @example
19054 (with-input-from-file "foo.txt"
19055 (cut generator-find #/XYZ/ read-line))
19056 @end example
19057
19058 @c EN
19059 Note: If you want to pick all the lines matching the regexp,
19060 like the @code{grep} command,
19061 you can use @code{gfilter} and @code{generator->list}.
19062 @c JP
19063 註: @code{grep}コマンドのように、正規表現にマッチする全ての行を取り出したいなら、
19064 @code{gfilter}と@code{generator->list}が使えます。
19065 @c COMMON
19066 @end defun
19067
19068 @c ----------------------------------------------------------------------
19069 @node Parameters and dynamic states, Boxes, Procedures and continuations, Core library
19070 @section Parameters and dynamic states
19071 @c NODE パラメータと動的状態
19072
19073 @c EN
19074 A @emph{parameter} is Scheme's way to implement dynamically scoped variables.
19075 It is codified in SRFI-39 and incorporated into R7RS.
19076 @c JP
19077 「パラメータ」はSchemeで動的スコープを持つ変数を実現します。
19078 もともとSRFI-39で仕様が定められ、R7RSからは言語の一部になりました。
19079 @c COMMON
19080
19081 @c EN
19082 @b{Note:} Starting from 0.9.13, we're adopting SRFI-226 semantics
19083 of parameters, which behaves slightly different from our legacy parameters.
19084 @xref{Transition to SRFI-226 parameters}, for the details.
19085 @c JP
19086 @b{註:} 0.9.13より、パラメータのセマンティクスを従来のものからSRFI-226で定義される
19087 ものに切り替えつつあります。両者は微妙に振る舞いが異なります。
19088 詳しくは@ref{Transition to SRFI-226 parameters}で説明しています。
19089 @c COMMON
19090
19091 @c EN
19092 It is a special procedure created by @code{make-parameter}. It accepts
19093 zero or one argument. When called without an argument, it returns the
19094 value in the current dynamic environment.
19095 If an argument is passed, it alters its value
19096 with the given value in the current dynamic environment,
19097 and returns the previous value.
19098 @c JP
19099 パラメータは@code{make-parameter}で作られる特殊な手続きで、
19100 ゼロ個または1個の引数を取ります。引数無しで呼ばれた場合は現在の動的環境での値を返し、
19101 引数つきで呼び出された場合はその引数を現在の動的環境での値にセットして
19102 以前の値を返します。
19103 @c COMMON
19104
19105 @c EN
19106 Using @code{parameterize} macro, which is similar to @code{let} syntactially,
19107 rebinds the parameters' value during execution of its body, dynamically
19108 rather than lexically.
19109 @c JP
19110 @code{parameterize}マクロは@code{let}に構文的に似ていて、
19111 本体の実行の間、パラメータの値を一時的に置き換えます。
19112 これは字句的(静的スコープ)ではなく動的スコープで動作します。
19113 @c COMMON
19114
19115 @example
19116 (define var (make-parameter 0))
19117
19118 (define (show-var) (print (var)))
19119
19120 (show-var) ; prints 0
19121
19122 (parameterize ((var 1))
19123 (show-var)) ; prints 1
19124
19125
19126 (define f)
19127
19128 (parameterize ((var 2))
19129 (set! f (lambda () (show-var))))
19130
19131 (f) ; prints 0, since its out of the dynamic extent of var=2
19132 @end example
19133
19134 @c EN
19135 A parameter's value can be mutated by calling the parameter with
19136 the new value:
19137 @c JP
19138 パラメータの値はまた、新たな値を引数としてパラメータを呼ぶことで変更することができます。
19139 @c COMMON
19140
19141 @example
19142 (define var (make-parameter 0))
19143
19144 (var) ; @result{} 0
19145
19146 (var 1)
19147
19148 (var) ; @result{} 1
19149
19150 ;; Gauche extension: you can use set! too
19151 (set! (var) 2)
19152
19153 (var) ; @result{} 2
19154 @end example
19155
19156 @c EN
19157 Originally, parameters in Scheme were simply a hack with an ordinary procedure
19158 and @code{dynamic-wind} to emulate dynamically scoped variables.
19159 The same mechanism have been used to manage dynamically scoped states, too.
19160
19161 As the experience accumulated, however, it is learned that it's better
19162 to treat dynamically scoped variables and dynamically scoped states
19163 differently; efficient implementations differ, and they have slightly
19164 different semantics with delimited continuations. SRFI-226 incorporated
19165 this distinction.
19166
19167 As of Gauche 0.9.13, we adopt this distinction, too.
19168 @xref{Difference of parameters and dynamic states}, for the details.
19169 @c JP
19170 元々、Schemeのパラメータは通常の手続きと@code{dynamic-wind}を使って
19171 動的束縛の変数をエミュレートするハックでした。
19172 同じメカニズムはまた、動的な状態の管理にも使うことができました。
19173
19174 しかし使い込まれてゆくうちに、動的変数と動的状態は別に扱った方が良いという
19175 知見が得られてきました。効率の良い実装が異なるのと、
19176 限定継続があると振る舞いに差があるためです。
19177 SRFI-226でこの違いが明確化されました。
19178
19179 Gaucheも0.9.13からこの区別を採り入れています。
19180 詳しくは@ref{Difference of parameters and dynamic states}を参照してください。
19181 @c COMMON
19182
19183 @c EN
19184 If you're a long time Gauche user (thanks!), remember to check
19185 out the changes on 0.9.13 and how to transition to it
19186 (@pxref{Transition to SRFI-226 parameters}).
19187 @c JP
19188 これまで長くGaucheを使っていた方は、一度0.9.13での変更点と
19189 移行方法をチェックしておいてください
19190 (@ref{Transition to SRFI-226 parameters}参照)。
19191 @c COMMON
19192
19193 @menu
19194 * Parameters::
19195 * Dynamic states::
19196 * Difference of parameters and dynamic states::
19197 * Transition to SRFI-226 parameters::
19198 @end menu
19199
19200 @node Parameters, Dynamic states, Parameters and dynamic states, Parameters and dynamic states
19201 @subsection Parameters
19202 @c NODE パラメータ
19203
19204 @c EN
19205 Because of historical reasons,
19206 parameters come with three flavors; their differences are subtle,
19207 and only visible when you use @emph{mutation} in @emph{multi-thread code}.
19208 If you only use parameters for dynamic binding (i.e. within R7RS spec),
19209 all flavors of parameters behave the same.
19210 @c JP
19211 歴史的事情から、パラメータには、少しだけ振る舞いが違う3つの種類があります。
19212 但し、その違いはマルチスレッドコードで破壊的変更をしない限りは見えません。
19213 R7RSの範囲、すなわちパラメータを動的束縛にだけ使っている場合は、
19214 どのパラメータも同じように振る舞います。
19215 @c COMMON
19216
19217 @c EN
19218 The three flavors are @emph{shared parameters}, @emph{thread parametres},
19219 and @emph{legacy parameters}. The first two is defined in SRFI-226
19220 (though it doesn't use the term ``shared'', for the ordinary parameters
19221 are shared parameters). The third one is compatible to the parameters
19222 in Gauche 0.9.12 and before.
19223
19224 The following table shows whether a mutation in one thread is visible from
19225 another thread:
19226
19227 @multitable {Toplevel mutation visible?===} {AAAAAA===} {AAAAAA===} {AAAAAA===}
19228 @headitem @tab Share @tab Thread @tab Legacy
19229 @item Toplevel mutation visible? @tab yes @tab no @tab no
19230 @item Dynamic mutation visible? @tab yes @tab no @tab yes
19231 @end multitable
19232
19233 Here, ``toplevel mutation'' is a mutation done for a parameter
19234 outside of any @code{parameterize} form, and ``dynamic mutation''
19235 is a mutation done for a parameter in a dynamic scope of
19236 @code{parameterize} form:
19237
19238 @example
19239 (define p (make-parameter 0))
19240
19241 (p 1) ; toplevel mutation
19242
19243 (parameteize ((p 2))
19244 (p 3) ; dynamic mutaiton
19245 )
19246
19247 (p 4) ; toplevel mutation
19248 @end example
19249
19250 For the shared and legacy parameters, dynamic mutation is only visible
19251 for the thread that shares the same dynamic binding.
19252 @c JP
19253 その3つの種類は、@emph{共有パラメータ}、@emph{スレッドパラメータ}、
19254 そして@emph{レガシーパラメータ}です。
19255 最初のふたつはSRFI-226で定義されます。
19256 (SRFI-226では「共有パラメータ」とは呼んでいませんが、@code{make-parmaeter}で
19257 作られる通常のパラメータが共有パラメータになります)。
19258 最後のものはGauche 0.9.12以前と互換なパラメータです。
19259
19260 次の表に、パラメータの破壊的変更が他のスレッドから見えるかどうかをまとめます。
19261
19262 @multitable {トップレベルの変更が見えるか?===} {AAAAAA===} {AAAAAA===} {AAAAAA===}
19263 @headitem @tab 共有 @tab スレッド @tab レガシー
19264 @item トップレベルの変更が見えるか? @tab yes @tab no @tab no
19265 @item 動的範囲での変更が見えるか? @tab yes @tab no @tab yes
19266 @end multitable
19267
19268 ここで「トップレベルの変更」とは@code{parameterize}がされていない動的環境での
19269 変更、「動的範囲での変更」とは@code{parameterize}が有効な動的環境での変更です。
19270
19271 @example
19272 (define p (make-parameter 0))
19273
19274 (p 1) ; トップレベルの変更
19275
19276 (parameteize ((p 2))
19277 (p 3) ; 動的範囲での変更
19278 )
19279
19280 (p 4) ; トップレベルの変更
19281 @end example
19282
19283 共有パラメータとレガシーパラメータについては、
19284 動的範囲での変更が見えるのは、同じ動的環境を共有しているスレッド間のみです。
19285 @c COMMON
19286
19287 @defun make-parameter value :optional converter
19288 @defunx make-shared-parameter value :optional converter
19289 @defunx make-thread-parameter value :optional converter
19290 @defunx make-legacy-parameter value :optional converter
19291 [R7RS base][SRFI-226]
19292 @c EN
19293 Creates a parameter whose initial value is @var{value}.
19294 If an optional argument @var{converter} is given, it must be
19295 a procedure that takes one argument and returns one value;
19296 whenever the parameter's value is about to change, the procedure
19297 is called with the given value, and the value the procedure
19298 returns will be the parameter's value. The converter procedure
19299 can raise an error or reject to change the parameter's value.
19300 @c JP
19301 初期値が@var{value}であるパラメータを作成します。
19302 もし省略可能な引数@var{converter}が与えられた場合、
19303 それは一つの引数を取る手続きでなければなりません。
19304 パラメータの値が変更されようとした時、@var{converter}は与えられた値を
19305 引数として呼ばれ、@var{converter}が返した値がパラメータの新しい値と
19306 なります。@var{converter}はエラーを報告したりパラメータの値を変えずに置くことも
19307 可能です。
19308 @c COMMON
19309
19310 @c EN
19311 As described above (@pxref{Parameters}), parameters have three
19312 flavors; @code{make-shared-parameter}, @code{make-thread-parameter},
19313 and @code{make-legacy-parameter} creates shared, thread, and legacy
19314 parameters, respectively.
19315 @c JP
19316 上で説明したように(@ref{Parameters}参照)、パラメータには3種類あります。
19317 @code{make-shared-parameter}、@code{make-thread-parameter}、
19318 @code{make-legacy-parameter}はそれぞれ
19319 共有パラメータ、スレッドパラメータ、レガシーパラメータを作ります。
19320 @c COMMON
19321
19322 @c EN
19323 For the compatibility, @code{make-parameter} behaves differently
19324 depending on which module you uses.
19325
19326 @itemize @bullet
19327 @item
19328 The @code{make-parameter} in @code{gauche} module works as
19329 @code{make-legacy-parameter} in 0.9.13, but it will be switched
19330 to @code{make-shared-parameter} in future versions. To keep
19331 the legacy code working, you should either use @code{gauche.parameter}
19332 module, or replace @code{make-parameter} for @code{make-legacy-parameter}.
19333 @item
19334 If you use @code{gauche.parameter}, @code{make-parameter}
19335 works as @code{make-legacy-parameter}. This won't change, since
19336 @code{gauche.parameter} is kept for the backward compatibility.
19337 @item
19338 If you use @code{srfi.226}, @code{make-parameter} is as SRFI-226
19339 defines, that is, @code{make-shared-parameter}.
19340 @end itemize
19341 @c JP
19342 互換性のため、@code{make-parameter}はどのモジュールをuseするかで
19343 動作が変わります。
19344
19345 @itemize @bullet
19346 @item
19347 @code{gauche}モジュールの@code{make-parameter}は、0.9.13では
19348 互換性のために@code{make-legacy-parameter}と同じ動作ですが、
19349 将来は@code{make-shared-parameter}に切り替わります。
19350 以前のコードを使いつづけるには、@code{gauche.parameter}モジュールをuseするか、
19351 @code{make-parameter}を@code{make-legacy-parameter}に置き換えてください。
19352 @item
19353 @code{gauche.parameter}モジュールをuseすると、
19354 @code{make-parameter}は@code{make-legacy-parameter}と同じ動作になります。
19355 これは今後も変わりません。@code{gauche.parameter}は互換性のためのモジュールとなります。
19356 @item
19357 @code{srfi.226}をuseした場合、@code{make-parameter}はSRFI-226で
19358 定義されているとおり、すなわち@code{make-shared-parameter}の動作となります。
19359 @end itemize
19360 @c COMMON
19361
19362 @c EN
19363 NB: R7RS defines @code{make-parameter}. SRFI-226 defines
19364 @code{make-parameter} and @code{make-thread-parameter}.
19365 The other two names, @code{make-shared-parameter} and
19366 @code{make-legacy-parameter}, are Gauche specific.
19367 @c JP
19368 註: R7RSは@code{make-parameter}を、
19369 SRFI-226は@code{make-parameter}と@code{make-thread-parameter}を
19370 定義しています。
19371 他のふたつ、@code{make-shared-parameter}と
19372 @code{make-legacy-parameter}はGauche独自の名前です。
19373 @c COMMON
19374
19375 @c EN
19376 NB: In 0.9.9 and before, this procedure returns a parameter
19377 object, and we used @code{object-apply} method to make it behave
19378 like a procedure. However, R7RS explicitly defines the return
19379 values to be a procedure; notably, portable code expects
19380 @code{(procedure? (make-parameter 'z))} returns @code{#t}.
19381 As of 0.9.10, we switched @code{make-parameter} to return
19382 a procedure. It won't change the external behavior, except
19383 when you test the parameter @var{p} with
19384 @code{(is-a? p <parameter>)}; you have to use @code{parameter?} instead.
19385 @c JP
19386 註: 0.9.9までは、この手続きはパラメータオブジェクトを返していました。
19387 パラメータオブジェクトは @code{object-apply}メソッドによって手続きであるかのように
19388 振る舞います。しかし、R7RSは@code{make-parameter}が手続きを返すように
19389 規定しており、ポータブルなコードでは
19390 @code{(procedure? (make-parameter 'z))}は@code{#t}でなければなりません。
19391 0.9.10から、@code{make-parameter}は手続きを返すようになりました。
19392 通常のパラメータの使い方をしている限り、外部に見える振る舞いは変わりません。
19393 ただし、@code{make-parameter}で作られたオブジェクトかどうかを
19394 @code{(is-a? p <parameter>)}でテストしているコードは
19395 後述する@code{parameter?}を使うように変更する必要があります。
19396 @c COMMON
19397 @end defun
19398
19399 @defmac parameterize ((param value) @dots{}) body @dots{}
19400 [R7RS base][SRFI-226]
19401 @c EN
19402 Evaluates @var{body} @dots{}, with
19403 change parameter @var{param}'s value to the given @var{value} within
19404 the dynamic scope of @var{body} @dots{}.
19405 Returns the value(s) of the result of the last @var{body}.
19406 @c JP
19407 @var{body} @dots{}を評価します。
19408 但し、@var{body} @dots{} の実行中のみ、パラメータ@var{param}の値を
19409 @var{value}に変更します。最後の@var{body}の返した値を返します。
19410 @c COMMON
19411
19412 @c EN
19413 If @code{parameterize} form is at a tail position and all @var{param}s
19414 are parameter objects , @var{body} is
19415 also evaluated at a tail position. (This is required by SRFI-226,
19416 though not required by R7RS).
19417 @c JP
19418 @code{parameterize}フォームが末尾位置にあり、
19419 全ての@var{param}がパラメータに評価された場合、
19420 @var{body}は末尾位置で評価されます。
19421 (これはR7RSでは要請されていませんが、SRFI-226で要請されます)。
19422 @c COMMON
19423
19424 @c EN
19425 Note that R7RS and SRFI-226 requires @var{param} to be evaluated
19426 to a parameter. Gauche's @code{parameterize} has been acceping
19427 dynamic states as well, but such usage is
19428 deprecated; you should use @code{temporarily} instead (@pxref{Dynamic states}).
19429 To ease transition, Gauche 0.9.13 checks if every @var{param} yields a
19430 parameter, at runtime, and if not, it switches to the legacy implementation
19431 which does @emph{not} evaluate @var{body} at a tail position.
19432 In future we remove this compatibility feature. If you want to
19433 check your code is compatible to the new spec, add @code{(use srfi.226)}
19434 to your code.
19435 @c JP
19436 R7RSとSRFI-226は@var{param}がパラメータへと評価されることを要求しています。
19437 Gaucheは伝統的に、@var{param}に動的状態も許してきましたが、
19438 そのような使い方は非推奨となりました。動的状態の切り替えには@code{temporarily}を
19439 使うようにしてください (@ref{Dynamic states}参照)。
19440 経過措置として、
19441 Gauche 0.9.13では実行時に全ての@var{param}がパラメータに評価されたかどうかを
19442 チェックし、パラメータ以外のものが混じっている場合は旧式の実装へと切り替えます
19443 (その場合、@var{body}は末尾位置では評価されません)。
19444 将来のバージョンではこの措置は無くなります。現在のコードが将来に渡って使えるかどうか
19445 確かめるにはコードに@code{(use srfi.226)}を加えてみてください。
19446 @c COMMON
19447
19448 @c EN
19449 Some examples:
19450 @c JP
19451 例:
19452 @c COMMON
19453 @example
19454 (define a (make-parameter 1))
19455 (a) @result{} 1
19456 (a 2) @result{} 1
19457 (a) @result{} 2
19458 (parameterize ((a 3))
19459 (a)) @result{} 3
19460 (a) @result{} 2
19461 @end example
19462 @end defmac
19463
19464 @defun parameter? obj
19465 [SRFI-226]
19466 @c EN
19467 Returns @code{#t} iff @var{obj} is an object created by
19468 @code{make-parameter}.
19469 @c JP
19470 @var{obj}が@code{make-parameter}で作られたものであった場合は@code{#t}を、
19471 そうでなければ@code{#f}を返します。
19472 @c COMMON
19473 @end defun
19474
19475 @defun current-parameterization
19476 [SRFI-226]
19477 @c EN
19478 Returns a @emph{parameterization} object that reifies
19479 the current dynamic bindings of parameters. It can be
19480 passed to @code{call-with-parameterization} to carry over
19481 the parameterization.
19482 @c JP
19483 現在のパラメータの動的束縛の状態を具体化した@emph{パラメタライゼーション}オブジェクト
19484 を返します。@emph{パラメタライゼーション}は@code{call-with-parameterization}に
19485 渡すことで別の継続へと受け渡すことができます。
19486 @c COMMON
19487 @end defun
19488
19489 @defun parameterization? obj
19490 [SRFI-226]
19491 @c EN
19492 Returns @code{#t} if @var{obj} is a parameterization,
19493 @code{#f} otherwise.
19494 @c JP
19495 @var{obj}がパラメタライゼーションなら@code{#t}を、そうでなければ@code{#f}を返します。
19496 @c COMMON
19497 @end defun
19498
19499 @defun call-with-parameterization parameterization thunk
19500 [SRFI-226]
19501 @c EN
19502 Invoke @var{thunk} with a continuation same as
19503 the call of @code{call-with-parameterization} except its
19504 parameterization is swapped with @var{parameterization}.
19505 That is, if the call to this form is in a tail context,
19506 the call to @var{thunk} is also a tail context.
19507 @c JP
19508 @code{call-with-parameterization}の呼び出しの継続から
19509 パラメタライゼーションだけ@var{parameterization}と置き換えた継続のもとで
19510 @var{thunk}を呼び出します。
19511 すなわち、この手続きが末尾コンテクストで呼ばれたなら、
19512 @var{thunk}の呼び出しも末尾コンテクストになります。
19513 @c COMMON
19514
19515 @example
19516 @end example
19517 @end defun
19518
19519
19520 @defmac parameterize/dynwind ((param value) @dots{}) body @dots{}
19521 @c EN
19522 This handles the parameter bindings using @code{dynamic-wind}.
19523 It is fully compatible with pre-0.9.13 @code{parameterize}.
19524 This form is mainly provided to make legacy code work.
19525 @c JP
19526 これは@code{dynamic-wind}を使ってパラメータ束縛を管理するフォームです。
19527 0.9.13より前の@code{parameterize}と全く同じ動作をします。
19528 このフォームは主に、レガシーコードを動かすために提供されています。
19529 @c COMMON
19530
19531 @c EN
19532 This differs from the current @code{parameterize} in the following points:
19533 @c JP
19534 これは現在の@var{parameterize}と、次の点が異なります。
19535 @c COMMON
19536
19537 @itemize @bullet
19538 @item
19539 @c EN
19540 You can use non-parameter procedure (a procedure which isn't
19541 created by @code{make-parameter}) as @var{param}, as long as it
19542 follows the parameter protocol. Note that if you want to use
19543 such 'parameter-like' procedures to manage dynamic states,
19544 you should use @code{temporarily} below (@pxref{Dynamic states}).
19545 @c JP
19546 パラメータと同じプロトコルに従う限り、@code{make-parameter}で作られたのではない
19547 手続きを@var{param}に渡すことができます。
19548 新しいコードでそのような「パラメータっぽい」手続きを動的状態の管理に使いたい場合は、
19549 下の@code{temporarily}を使ってください (@ref{Dynamic states}参照)。
19550 @c COMMON
19551
19552 @item
19553 @c EN
19554 The last expression of @var{body} is @emph{not} evaluated in the
19555 tail context, even this form itself is in the tail context.
19556 @c JP
19557 このフォーム自体が末尾位置にあっても、@var{body}の最後の式は
19558 末尾コンテクストでは評価されません。
19559 @c COMMON
19560
19561 @item
19562 @c EN
19563 This can handle the 'observer' feature of the legacy
19564 parameters introduced by @code{gauche.parameter}. Our experience
19565 shows the feature has been hardly used, and is incompatible with SRFI-226
19566 semantics, so we deprecated it.
19567 @c JP
19568 @code{gauche.parameter}モジュールで有効になる、
19569 レガシーなパラメータの 'observer' 機能は、このフォームを使わないと実現できません。
19570 ただ、我々ののこれまでの経験ではこの機能はほとんど使われておらず、
19571 SRFI-226とも非互換なので、今後は非推奨としました。
19572 @c COMMON
19573 @end itemize
19574
19575 @c EN
19576 Note: If you use @code{gauche.parameter} module, it shadows built-in
19577 @code{parameterize} with its own @code{parameterize}, the latter of which
19578 is an alias of @code{parameterize/dynwind}, so that the compatibility
19579 is kept. New code should not use @code{gauche.parameter} module.
19580 @xref{Parameters (legacy)}.
19581 @c JP
19582 註:@code{gauche.parameter}モジュールをuseすると、組み込みの@code{parameterize}
19583 の束縛はモジュール独自の@code{parameterize}でシャドウされ、それは
19584 @code{parameterize/dynwind}の別名となります。これはコードの互換性を保つためです。
19585 新しいコードでは@code{gauche.parmaeter}をuseすべきではありません。
19586 詳しくは@ref{Parameters (legacy)}参照。
19587 @c COMMON
19588 @end defmac
19589
19590
19591 @node Dynamic states, Difference of parameters and dynamic states, Parameters, Parameters and dynamic states
19592 @subsection Dynamic states
19593 @c NODE 動的状態
19594
19595 @c EN
19596 A dynamic state is a state associated to a certain dynamic extent
19597 of the code execution. (In SRFI-226, it is called ``parameter-like objects'').
19598
19599 It can be managed with a procedure that
19600 follows this protocol:
19601 @c JP
19602 動的状態とは、特定の動的エクステントに結びつけられた状態です。
19603 (SRFI-226では「パラメータのようなオブジェクト(parameter-like object)」と
19604 呼ばれています)。
19605
19606 動的状態は次のプロトコルを持つ手続きにより実現されます:
19607 @c COMMON
19608
19609 @itemize @bullet
19610 @item
19611 @c EN
19612 The procedure can be called with zero or one argument.
19613 @c JP
19614 手続きは0個または1個の引数を取る
19615 @c COMMON
19616 @item
19617 @c EN
19618 If it is called without arguments, it returns the current state.
19619 @c JP
19620 引数なしで呼ばれた場合、現在の値を返す
19621 @c COMMON
19622 @item
19623 @c EN
19624 If it is called with one argument, the state is set to the argument.
19625 (The return value is ignored).
19626 @c JP
19627 1引数で呼ばれた場合、引数を状態の新たな値とする。
19628 (戻り値は無視される)
19629 @c COMMON
19630 @end itemize
19631
19632 @c EN
19633 You can use @code{temporarily} macro in place of @code{parameterize} to
19634 change the state dynamically.
19635 @c JP
19636 @code{parameterize}のかわりに@code{temporarily}マクロを使って
19637 状態を動的に変えることができます。
19638 @c COMMON
19639
19640 @example
19641 (define state
19642 (let val 0
19643 (case-lambda
19644 [() val]
19645 [(newval) (set! val newval)])))
19646
19647 (define (get-state) (state))
19648
19649 (get-state) @result{} 0
19650
19651 (temporarily ([state 1])
19652 (get-state)) @result{} 1
19653 @end example
19654
19655 @c EN
19656 If you just manage a value, it is not much different from a parameter
19657 (without a converter) and @code{parameterize}.
19658 However, unlike @code{parameterize}, it is guaranteed that state is
19659 reset by calling the dynamic state with the previous value,
19660 when the control goes out of the dynamic scope.
19661 You can do
19662 more than just changing the internal values inside the procedure,
19663 such as switching state of external resource.
19664 @c JP
19665 値を変えるだけなら、これは(converterなしの)パラメータと@code{parameterize}を
19666 使うのと大して変わらないように見えるでしょう。
19667 けれど、@code{parameterize}と違って、@code{temporarily}の動的環境から
19668 出たり再入したりした場合に、手続きが1引数で呼ばれることが保証されています。
19669 従って、その時に外部リソースの状態も一緒に変えるなど、
19670 値を保存する以外のアクションを取ることができます。
19671 @c COMMON
19672
19673 @defmac temporarily ((proc value) @dots{}) body @dots{}
19674 [SRFI-226]
19675 @c EN
19676 Evaluates @var{proc}s and @var{value}s. Each @var{proc} must yield a
19677 dynamic state, i.e. a procedure that takes zero or one arguments.
19678 @c JP
19679 まず@var{proc}と@var{value}が評価されます。@var{proc}は動的状態、
19680 すなわち0個または1個の引数をとる手続きを返さなければなりません。
19681 @c COMMON
19682
19683 @c EN
19684 Then the current state each @var{proc} represents is changed
19685 to @var{value} during evaluating @var{body} @dots{}. The state
19686 is restored when the control leaves @var{body} @dots{}.
19687 The results of the last expression of @var{body} will be returned.
19688 @c JP
19689 そして、@var{proc}が保持する値が@var{value}に置き換えられ、
19690 @var{body} @dots{} が評価されます。制御が@var{body} @dots{}を
19691 離れる際に、@var{proc}が保持する値が元の値に復元されます。
19692 @var{body}の最後の式の値が@code{temporarily}の値となります。
19693 @c COMMON
19694
19695 @c EN
19696 Whenver control trasfers out of @var{body}, or reenters to @var{body},
19697 the state of each @var{proc} is saved and restored.
19698 @c JP
19699 制御が@var{body}から脱出したり、再入したりする度に、
19700 それぞれの@var{proc}が保持する値が回復されます。
19701 @c COMMON
19702 @end defmac
19703
19704
19705 @node Difference of parameters and dynamic states, Transition to SRFI-226 parameters, Dynamic states, Parameters and dynamic states
19706 @subsection Difference of parameters and dynamic states
19707 @c NODE パラメータと動的状態の違い
19708
19709 @c EN
19710 At a first grance, parameters and dynamic states look almost same; both
19711 are procedures taking zero or one arguments; when called with no arguments,
19712 it returns the ``current'' value; when called with one argument,
19713 it replaces the ``current'' value with the given argument.
19714 @c JP
19715 一見すると、パラメータと動的状態はほとんど同じに見えます。
19716 どちらも0個または1個の引数を取る手続きで、
19717 引数無しで呼ばれたら「現在の」値を返し、
19718 引数つきで呼ばれたら「現在の」値を置き換えると。
19719 @c COMMON
19720
19721 @c EN
19722 The difference is that the ``state'' of a parameter, or a parameterization,
19723 is tied to a continuation.
19724 If a continuation frame where @code{parameterize} is evaluated is
19725 popped, the parameterization simply goes away with it, and the previous
19726 parameterization (tied to the previous continuation) automatically
19727 becomes visible, instead of the explicit operation of restoring
19728 the previous value. That's why the body of @code{parameterize}
19729 can be evaluated in tail context---we don't have a restore
19730 operation to perform after the body is evaluated.
19731 @c JP
19732 違いは、パラメータの状態、「パラメタライゼーション」が継続と結びつけられていることです。
19733 @code{parameterize}が評価される継続フレームがポップされると、
19734 それに結びつけられていたパラメタライゼーションは消滅し、
19735 ポップ後に見えている継続に結びつけられていたパラメタライゼーションが
19736 自動的に見えるようになります。つまり、明示的に
19737 「@code{parameterize}の外側の値を回復する」というアクションが不要です。
19738 これが、@code{parameterize}のボディが末尾コンテクストで実行可能な理由です。
19739 ボディを実行した後で値を回復するというアクションを走らせる必要がないからです。
19740 @c COMMON
19741
19742 @c EN
19743 On the other hand, dynamic states rely on the `after' handler
19744 of @code{dyanmic-wind} to restore the state, hence
19745 the body in @code{temporarily} can't be evaluated in a tail context.
19746 @c JP
19747 一方、動的状態は@code{dynamic-wind}のafterサンクを使って状態の復帰を行います。
19748 なので@code{temporarily}のボディは末尾コンテクストでは実行されません。
19749 @c COMMON
19750
19751 @c EN
19752 You want to use dynamic states when the change of state requires
19753 some actions other than storing a value, e.g. notifying the change
19754 to a resource manager. When a dynamic state procedure is called with
19755 a new value, you can take necessary actions.
19756 Restoration of parameter values after
19757 leaving a dynamic extent is implicit; you can't know when the
19758 parameter value is restored.
19759 @c JP
19760 単に値を置き換える以外のアクション、例えば状態の変更をリソース管理モジュールに
19761 通知したい、といったものがあるなら、動的状態を使うのが良いでしょう。
19762 動的状態の値が変更されるときは必ず動的状態手続きが引数つきで呼ばれるので、
19763 その時に必要なアクションをトリガできます。
19764 パラメータだと、動的エクステントを離れる時に値は暗黙に復帰されるので、
19765 値が変わったことの通知を受けることができません。
19766 @c COMMON
19767
19768 @c EN
19769 Parameters can have @emph{converter} procedure to coerce
19770 the value to be set. Dynamic states aren't supposed to have the
19771 converter procedure, though. If the dynamic extent is inactivated and then
19772 resumed by continuations, the dynamic value needs to be restored
19773 without passing through the converter procedure, so it requires
19774 additional protocol, which isn't standardized.
19775 @c JP
19776 パラメータはまた、converter手続きを使って、セットされる値を変換することができますが、
19777 動的状態はconvertert手続きを使いません。
19778 というのも、継続によって動的エクステントが一時中断され後で復帰した場合に、
19779 動的状態の値を戻すためにはconverterをバイパスして値をセットしなければならないからです。
19780 そうするためには別のプロトコルが必要ですが、その点に関しては標準と呼べるものがありません。
19781 @c COMMON
19782
19783 @node Transition to SRFI-226 parameters, , Difference of parameters and dynamic states, Parameters and dynamic states
19784 @subsection Transition to SRFI-226 parameters
19785 @c NODE SRFI-226パラメータへの移行
19786
19787 @c EN
19788 @subsubheading First, here's rule of thumb:
19789 @c JP
19790 @subsubheading まず、大まかなルールを:
19791 @c COMMON
19792
19793 @itemize @bullet
19794 @item
19795 @c EN
19796 If you bind parameters only with @code{parameterize}, you won't see
19797 any changes.
19798 @c JP
19799 パラメータの値を@code{parameterize}で束縛しているだけなら、違いはありません。
19800 @c COMMON
19801 @item
19802 @c EN
19803 If the code explicitly use @code{gauche.parameter}, it'll preserve
19804 the previous behavior. This helps legacy code to keep working.
19805 @c JP
19806 コード中で明示的に@code{gauche.parameter}をuseしている場合は、
19807 以前の振る舞いのままになります。レガシーコードが壊れてしまうことはありません。
19808 @c COMMON
19809 @item
19810 @c EN
19811 For other code, you can gradually revise your code as follows:
19812 @c JP
19813 そうでない場合、以下の方針でコードを徐々にアップデートしてください。
19814 @c COMMON
19815 @itemize @minus
19816 @item
19817 @c EN
19818 If you used parameters as thread-local storage, replace it with
19819 @emph{thread locals} (@pxref{Thread local storage}).
19820 @c JP
19821 パラメータをスレッドローカル変数として使っている場合は、かわりに
19822 @emph{スレッドーローカル}を使うようにします(@ref{Thread local storage}参照)。
19823 @c COMMON
19824 @item
19825 @c EN
19826 If you manage dynamic state with @code{parameterize}, replace
19827 it with @code{temporarily} (@pxref{Dynamic states}).
19828 @c JP
19829 動的状態と@code{parameterize}で変更している場合は、
19830 かわりに@code{temporarily}を使うようにします
19831 (@ref{Dynamic states}参照)。
19832 @c COMMON
19833 @item
19834 @c EN
19835 If you used parameters for both thread-local storage @emph{and} dynamic
19836 binding, use @code{make-thread-parameter} @emph{and}
19837 @code{parameterize/dynwind}, in place of
19838 @code{make-parameter} and @code{parameterize}.
19839 (@pxref{Parameters}).
19840 @c JP
19841 パラメータを、スレッドローカル変数かつ動的束縛として使っている場合は、
19842 @code{make-parameter}と@code{parameterize}のかわりに
19843 @code{make-thread-parameter}と@code{parameterize/dynwind}を使うようにします。
19844 @c COMMON
19845 @end itemize
19846 @end itemize
19847
19848 @c EN
19849 @subsubheading Under the hood:
19850 @c JP
19851 @subsubheading ボンネットの下:
19852 @c COMMON
19853
19854 @c EN
19855 Here we call the parameter implementation before 0.9.13 as ``legacy model'',
19856 while the one in 0.9.13 and later as ``new model''.
19857 @c JP
19858 ここでは0.9.13より前のパラメータ実装を「旧モデル」、
19859 0.9.13とそれ以降を「新モデル」と呼ぶことにします。
19860 @c COMMON
19861
19862 @c EN
19863 In the legacy model, parameterization is realized by swapping
19864 each parameter's value in dynamic wind's before and after thunk.
19865 Roughly speaking, @code{parameterize} is expanded as follows
19866 (this assumes Gauche's parameter protocol that returns previous
19867 value when a new value is set. Also, we omit consideration of
19868 converter, for simplicity):
19869 @c JP
19870 旧モデルでは、パラメタライゼーションはdynamic-windのbefore/afterサンクで
19871 パラメータの値を入れ替えることで実現されていました。
19872 おおまかに言えば、@code{parameterize}は次のように展開されます
19873 (Gaucheのパラメータは変更した時に以前の値を返す、というのを使っています。
19874 また、説明の単純化のためにconverterの処理は省略しています):
19875 @c COMMON
19876
19877 @example
19878 (parameterize ((param expr)) body @dots{})
19879 @equiv{}
19880 (let ((p param) (v expr))
19881 (dynamic-wind
19882 (lambda () (set! v (p v)))
19883 (lambda () body @dots{})
19884 (lambda () (set! v (p v)))))
19885 @end example
19886
19887 @c EN
19888 This model directly replaces the value of the parameter in the dynamic
19889 scope of @var{body} @dots{}. So the parameter value needs to be
19890 thread-specific, otherwise the swapping of the value would be visible
19891 from other threads, which is not desirable.
19892 @c JP
19893 このモデルは@var{body} @dots{}を実行している間、
19894 パラメータの値を直接置き換えています。このモデルを取る場合、
19895 パラメータの値はスレッドごとにせざるを得ません。
19896 でないとあるスレッドが動的スコープに入る度に他のスレッドから見えるパラメータの値が
19897 変わっちゃいます。
19898 @c COMMON
19899
19900 @c EN
19901 Note that even parameter value is thread-specifc, you can still
19902 invoke a continuation captured in a different thread and expect
19903 the parameter values are carried over, for the switching conitnuation
19904 triggers execution of before/after thunks, which restores the
19905 values of parameters in the thread that invokes the continuation.
19906 @c JP
19907 このモデルでは、パラメータの値がスレッドごとでも、ある動的環境で捕捉された継続を別のスレッドで
19908 起動したら、捕捉されたパラメータの値は新たなスレッドに引き継がれます。
19909 継続の呼び出し時にdynamic-windのbefore/afterサンクが実行されて、
19910 継続捕捉時のパラメータの値が復元されるからです。
19911 @c COMMON
19912
19913 @c EN
19914 Also keep in mind that the body can't be in tail context even
19915 the parameterize form is, since you have to execute @emph{after} thunk
19916 after the body is evaluated.
19917 @c JP
19918 もうひとつ、このモデルでは、parameterizeフォームが末尾位置にあっても
19919 bodyは末尾呼び出しできないということに留意してください。
19920 bodyの後でafterサンクを実行しないとならないからです。
19921 @c COMMON
19922
19923 @c EN
19924 In the new model, we keep a chain of dynamic binding frames,
19925 and parameter value is looked up from it. The dynamic chain is a part of
19926 continuation, so when a continuation is popped, the dynamic frame
19927 created in the current continuation frame is also popped implicitly.
19928 With this model, @code{parameterize} is expanded something like this:
19929 @c JP
19930 新モデルでは、動的束縛のフレームのチェインを持っていて、
19931 パラメータの値はまずそこから探されます。動的束縛のチェインは継続の一部なので、
19932 継続がポップされると、その継続フレームで使われていた動的束縛のフレームも
19933 自動的にポップされます。このモデルでは@code{parameterize}は概念的に
19934 こんな感じで展開されます:
19935 @c COMMON
19936
19937 @example
19938 (parameterize ((param expr)) body @dots{})
19939 @equiv{}
19940 ((lambda (p v)
19941 (push-dynamic-frame! p v)
19942 body @dots{})
19943 param expr)
19944 @end example
19945
19946 @c EN
19947 Here, @code{push-dynamic-frame!} is a hypothetical procedure that pushes
19948 new dynamic frame in the current continuation.
19949 When the control returns to the continuation of the parameterize
19950 form, the additional dynamic frame is popped automatically
19951 so we don't need a special operation. If a continuation is captured
19952 in @var{body}, the dynamic frame chain is saved along the continuation.
19953 When the continuation is invoked in another thread, the dynamic frame chain
19954 is restored.
19955 This allows the body to be run in tail context if @code{parameterize}
19956 itself is in tail context.
19957 @c JP
19958 @code{push-dynamic-frame!}は新しい動的束縛フレームを
19959 現在の継続にプッシュする仮想的な手続きです。
19960 制御がparameterizeフォームの継続に渡った時には、プッシュされた動的束縛フレームは
19961 自動的にポップされているので、特別な後処理が必要ありません。
19962 @var{body}実行中に継続が捕捉された場合、動的束縛フレームのチェインも継続とともに
19963 保存されるので、その継続が別のスレッドで起動されたら、動的束縛フレームも復元されます。
19964 このことから、@code{parameterize}が末尾位置にあれば、
19965 @var{body}も末尾式として評価されます。
19966 @c COMMON
19967
19968 @c EN
19969 If you mutate parameter value (as opposed to binding it with
19970 @code{parameterize}), the dynamic frame is mutated. If the frame
19971 is shared between multiple threads, those mutations are visible immediately;
19972 they're pretty much the same as lexical frames, except the scopes.
19973 @c JP
19974 このモデルでは、@code{parameterize}を使わずに直接パラメータの値を変更した場合、
19975 その変更は動的束縛フレームに反映されます。したがって同じ動的束縛フレームが
19976 複数スレッドで共有されていれば、この変更は直ちに他のスレッドからも見えます。
19977 @c COMMON
19978
19979 @c EN
19980 SRFI-226 thread parameters are required to contain mutations within
19981 a thread. So we create a new thread-local whenever a thread parameter
19982 is dynamically bound by @code{parameterize} and keep the parameter's
19983 value in it. The mutation on a thread
19984 parameter is never visible from other thread, even if the dynamic
19985 frames are shared, or a continuation having it is passed to another
19986 thread. So, be careful using thread parameters. For example,
19987 if you create a future (@pxref{Futures}), the expression in it
19988 is evaluated in another thread, so it may not see the same
19989 value in thread parameters as the caller. Thread parameters
19990 also incur overhead for every @code{parameterize}, to allocate
19991 a new thread local.
19992 @c JP
19993 SRFI-226スレッドパラメータは、破壊的変更がスレッド内に止まることを要求します。
19994 なので、スレッドパラメータを@code{parameterize}する度に、スレッドローカルが
19995 作られてパラメータの動的な値はそこに格納されます。
19996 スレッドパラメータの破壊的変更は、同じ動的環境がスレッド間で共有されていたり、
19997 継続が他のスレッドに渡されて実行された場合などでも、他のスレッドには見えません。
19998 スレッドパラメータを使う時はこの点に留意してください。
19999 例えばfutureを作った場合、式は別スレッドで実行されるので、作成側で
20000 見えているスレッドパラメータの値と式内で見えるそれが異なる可能性があります
20001 (@ref{Futures}参照)。
20002 スレッドパラメータはまた、@code{parameterize}ごとにスレッドローカルを
20003 アロケートするので遅いです。
20004 @c COMMON
20005
20006 @c EN
20007 The new model also restricts @code{parameterize} to bind
20008 only parameters. ``Parameter-like'' objects, a procedure that
20009 merely follows the parameter protocol, can't be handled
20010 in @code{parameterize}. You should separate them and use
20011 @code{temporarily} for the latter (@pxref{Dynamic states}).
20012
20013 To ease transition, 0.9.13's @code{parameterize} checks if the given
20014 ``parameters'' are all actual parameters at run-time, and if not,
20015 it evalues as if the form is @code{parameterize/dynwind} instead.
20016 This kind of loose behavior tends to be the source of bugs,
20017 so we'll eventually make it stricter. You can check if your code
20018 is conforming the new model by using @code{(use srfi.226.parameter)}.
20019 @c JP
20020 新モデルでは、@code{parameterize}で動的束縛できるのはパラメータに限られます。
20021 パラメータプロトコルに従っているだけの「パラメータのような」手続きは
20022 @code{parameterize}では処理できません。それらは別にして、
20023 @code{tempporarily}を使ってください (@ref{Dynamic states}参照)。
20024
20025 経過措置として、0.9.13の@code{parameterize}は実行時にパラメータが
20026 本当のパラメータであるかどうか検査し、そうでなければ
20027 @code{parameterize/dynwind}に切り替えて実行します。
20028 ただ、こういった緩い仕様はバグのもとになるので、
20029 将来のリリースでは@code{parameterize}はパラメータ以外はエラーにするでしょう。
20030 現在のコードが新モデルで動くかどうかは@code{(use srfi.226.parameter)}としておけば
20031 確かめられます。
20032 @c COMMON
20033
20034
20035 @c ------------------------------------------------------------
20036 @node Boxes, Lazy evaluation, Parameters and dynamic states, Core library
20037 @section Boxes
20038 @c NODE ボックス
20039
20040 @c EN
20041 A box is a mutable container that can hold (possibly multiple) values.
20042 It can be used as a minimal data storage, or a sort of mutable indirect
20043 ``pointer''.
20044 @c JP
20045 ボックスは0個以上の値を格納できる変更可能なコンテナです。
20046 小さなデータストア、あるいは間接参照のための「ポインタ」として使うことができます。
20047 @c COMMON
20048
20049 @c EN
20050 Traditionally, a list or a vector has been used for this purpose.
20051 However, such datatypes imply sequences of objects, Using boxes
20052 emphasizes your intention is just for indirection, and not so much for
20053 sequencing.
20054 @c JP
20055 伝統的に、この目的にはリストやベクタが使われてきました。
20056 しかし、リストやベクタはオブジェクトの列を扱うものと考えられます。
20057 ボックスを使うことにより、目的がオブジェクトの列ではなく間接参照であると強調できます。
20058 @c COMMON
20059
20060 @c EN
20061 It is originally introduced by SRFI-111, which was later adopted in
20062 R7RS-large as @code{scheme.box}. SRFI-195 enhances it to deal with
20063 multiple values.
20064 @c JP
20065 ボックスはSRFI-111で導入され、R7RS-largeに@code{scheme.box}として採り入れられました。
20066 SRFI-195はボックスを多値に拡張しました。
20067 @c COMMON
20068
20069 @c EN
20070 The srfis leave some details to implementations. Here are our choices:
20071 @c JP
20072 SRFIではいくつかの詳細を実装依存にしています。Gaucheの選択は次のとおりです。
20073 @c COMMON
20074 @itemize
20075 @item
20076 @c EN
20077 We don't support autoboxing; that is, it is an error to pass non-box
20078 value to the procedure expecting boxed value and vice versa.
20079 @c JP
20080 暗黙に値とボックスを変換するオートボクシングはサポートしません。つまり、
20081 ボックスを期待しているところにそうでない値を渡したり、その逆をするとエラーになります。
20082 @c COMMON
20083 @item
20084 @c EN
20085 Comparing two boxes with @code{equal?} compares their contents when
20086 two are not @code{eqv?}. In the spec, when two boxes are @code{eqv?}
20087 then they must also be @code{equal?} to each other, but it's up
20088 to the implementation when two are not @code{eqv?}.
20089 @c JP
20090 二つのボックスを@code{equal?}で比較すると、ボックス自体が@code{eqv?}でない場合、
20091 その内容を@code{equal?}で比較します。
20092 SRFIでは、二つのボックスが@code{eqv?}でない場合の@code{equal?}の振る舞いは
20093 規定されていません。
20094 @c COMMON
20095 @end itemize
20096
20097 @c EN
20098 When you're writing portable code, be careful not to depend on the
20099 @code{equal?} behavior.
20100 @c JP
20101 ポータブルなコードを書いている時は、上記@code{equal?}の振る舞いに依存しないように
20102 気をつけてください。
20103 @c COMMON
20104
20105 @defun box val @dots{}
20106 [R7RS box][SRFI-195]
20107 @c EN
20108 Returns a fresh box object that contains the value @code{val} @dots{}.
20109 @c JP
20110 @code{val} @dots{}を内容とする新たなボックスを作って返します。
20111 @c COMMON
20112 @end defun
20113
20114 @defun box? obj
20115 [R7RS box]
20116 @c EN
20117 Returns @code{#t} iff @var{obj} is a box object.
20118 @c JP
20119 @var{obj}がボックスなら@code{#t}を、そうでなければ@code{#f}を返します。
20120 @c COMMON
20121 @end defun
20122
20123 @defun box-arity box
20124 [SRFI-195]
20125 @c EN
20126 Returns the number of values @var{box} holds.
20127 @c JP
20128 @var{box}が保持している値の数を返します。
20129 @c COMMON
20130 @end defun
20131
20132 @defun unbox box
20133 [R7RS box]
20134 @c EN
20135 Returns @var{box}'s content. If @var{box} has N values,
20136 it returns N values.
20137 @c JP
20138 @var{box}の内容を返します。@var{box}がN個の値を保持していれば、N個の値が返されます。
20139 @c COMMON
20140
20141 @c EN
20142 NB: If @var{box} is a single-valued box, @code{unbox} can be used
20143 with generalized setters. This is Gauche's extension.
20144 @c JP
20145 註: @var{box}が一つの値だけを保持している場合、@code{unbox}は一般化セッターと
20146 一緒に使えます。これはGaucheの独自拡張です。
20147 @c COMMON
20148
20149 @example
20150 (define b (box 1))
20151 (set! (unbox b) 2)
20152 b @result{} #<box 2>
20153
20154 (define b (box '()))
20155 (push! (unbox b) 'x)
20156 (push! (unbox b) 'y)
20157 b @result{} #<box (y x)>
20158 @end example
20159 @end defun
20160
20161 @defun unbox-value box i
20162 [SRFI-195]
20163 @c EN
20164 Returns @var{i}-th value held in @var{box}.
20165 @c JP
20166 @var{box}の値のうち、@var{i}番めのものを返します。
20167 @c COMMON
20168
20169 @c EN
20170 NB: This can be used with generalized setters. This is Gauche's extension.
20171 @c JP
20172 註: これは一般化セッターと一緒に使えます。Gaucheの独自拡張です。
20173 @c COMMON
20174
20175 @example
20176 (define mb (box 10 20 30))
20177 (inc! (unbox-value mb 1)
20178 mb @result{} #<mv-box[3] 10 21 30>
20179 @end example
20180 @end defun
20181
20182 @defun set-box! box val @dots{}
20183 [R7RS box][SRFI-195]
20184 @c EN
20185 Alters the content of @var{box} with @var{val} @dots{}.
20186 The numer of values must match the arity of the box.
20187 Returns unspecified value.
20188 @c JP
20189 @var{box}の内容を@var{val} @dots{}で置き換えます。
20190 値の数はボックスのアリティと同じでなければなりません。
20191 戻り値は未定義です。
20192 @c COMMON
20193 @end defun
20194
20195 @defun set-box-value! box i val
20196 [SRFI-195]
20197 @c EN
20198 Alters @var{i}-th value of @var{box} with @var{val}.
20199 Returns unspecified value.
20200 @c JP
20201 @var{box}の@var{i}番めの値を@var{val}で置き換えます。
20202 戻り値は未定義です。
20203 @c COMMON
20204 @end defun
20205
20206 @c ------------------------------------------------------------
20207 @node Lazy evaluation, Exceptions, Boxes, Core library
20208 @section Lazy evaluation
20209 @c NODE 遅延評価
20210
20211 @c EN
20212 Gauche has two primitive lazy evaluation mechanisms.
20213 @c JP
20214 Gaucheには、ふたつの組み込みの遅延評価メカニズムがあります。
20215 @c COMMON
20216
20217 @c EN
20218 The first one is an explicit mechanism, defined in the Scheme
20219 standard: You mark
20220 an expression to be evaluated lazily by @code{delay},
20221 and you use @code{force} to make the evaluation happen when
20222 needed. Gauche also support another primitive @code{lazy},
20223 as defined in SRFI-45, for space-efficient tail-recursive
20224 lazy algorithms.
20225 @c JP
20226 ひとつめはScheme標準で定められている、明示的なメカニズムです。遅延評価したい式を
20227 @code{delay}構文でマークし、値が必要になったところで@code{force}により
20228 評価を強制します。Gaucheはさらに、SRFI-45で導入された、
20229 末尾再帰アルゴリズムでメモリを効率的に利用するための@code{lazy}というプリミティブも
20230 サポートしています。
20231 @c COMMON
20232
20233 @c EN
20234 The second one is a lazy sequence, in which evaluation happens
20235 implicitly. From a Scheme program, a lazy sequence just looks
20236 as a list---you can take its @code{car} and @code{cdr}, and
20237 you can apply @code{map} or other list procedures on it. However,
20238 internally, its element isn't calculated until it is required.
20239 @c JP
20240 もうひとつは遅延シーケンスです。こちらは評価を@code{force}で明示する必要が
20241 ありません。Schemeプログラムからは、遅延シーケンスは通常のリストと全く
20242 同じに見えます。@code{car}や@code{cdr}を使ったり、@code{map}を始めとする
20243 様々なリスト手続きをそのまま適用することができます。けれども内部的には、
20244 遅延シーケンスの要素は必要になるまで計算されません。
20245 @c COMMON
20246
20247 @menu
20248 * Delay force and lazy::
20249 * Lazy sequences::
20250 @end menu
20251
20252
20253 @node Delay force and lazy, Lazy sequences, Lazy evaluation, Lazy evaluation
20254 @subsection Delay, force and lazy
20255 @c NODE Delayとforceとlazy
20256
20257 @c EN
20258 Scheme has traditionally provided an explicit delayed evaluation mechanism
20259 using @code{delay} and @code{force}. After R5RS, however,
20260 it is found that it didn't mix well with tail-recursive
20261 algorithms: It required unbound memory, despite that the
20262 body of the algorithm could be expressed in iterative manner.
20263 SRFI-45 showed that introducing another primitive syntax @code{lazy}
20264 addresses the issue.
20265 For the detailed explanation please look at the SRFI-45 document.
20266 Here we explain how to use those primitives.
20267 @c JP
20268 Schemeは伝統的に、@code{delay}と@code{force}を使った
20269 明示的な遅延評価メカニズムを提供してきました。しかし、R5RSの後で、
20270 それが末尾再帰的なアルゴリズムとの相性がよくないことがわかりました。
20271 末尾再帰的なアルゴリズムの本体が反復的に表現できるにもかかわらず、
20272 メモリを際限なく要求してしまうのです。SRFI-45によって、
20273 新たなプリミティブ構文@code{lazy}を使えばその問題が回避できることが示されました。
20274 詳しい議論はSRFI-45のドキュメントを見てください。
20275 ここではこれらのプリミティブの使い方を説明します。
20276 @c COMMON
20277
20278 @defspec delay expression
20279 @defspecx lazy expression
20280 [R7RS lazy][SRFI-45]
20281 @c EN
20282 These forms creates a @emph{promise} that delays the evaluation
20283 of @var{expression}. @var{Expression} will be evaluated
20284 when the promise is passed to @code{force}.
20285 @c JP
20286 これらの形式は@var{expression}の評価を遅延する@emph{プロミス}を生成し
20287 ます。@var{Expression} はこのプロミスが@code{force}にわたったときに評
20288 価されます。
20289 @c COMMON
20290
20291 @c EN
20292 If @var{expression} itself is expected to yield a promise,
20293 you should use @code{lazy}. Otherwise, you should use @code{delay}.
20294 If you can think in types, the difference may be clearer.
20295 @c JP
20296 @var{expression}自身がプロミスを返す式なら@code{lazy}を、
20297 そうでなければ、@code{delay}を使います。
20298 型で考えるとわかりやすいでしょう。
20299 @c COMMON
20300
20301 @example
20302 lazy : Promise a -> Promise a
20303 delay : a -> Promise a
20304 @end example
20305
20306 @c EN
20307 Since we don't have static typing, we can't enforce this usage.
20308 The programmer has to choose appropriate one from the context.
20309 Generally, @code{lazy} appears only to surround the entire
20310 body of function that express a lazy algorithm.
20311 @c JP
20312 Schemeでは静的な型付けをしないので、この使い分けを強制することができません。
20313 文脈にしたがってプログラマが適切に選択する必要があります。
20314 一般的には@code{lazy}は遅延アルゴリズムを表現している関数本体全体を囲む場合
20315 にのみ出現します。
20316 @c COMMON
20317
20318 @c EN
20319 NB: In R7RS, @code{lazy} is called @code{delay-force}, for the operation
20320 is conceptually similar to @code{(delay (force expr))} (note that the
20321 type of @code{force} is @code{Promise a -> a}).
20322 @c JP
20323 註: R7RSでは@code{lazy}は@code{delay-force}と呼ばれています。概念的に
20324 @code{(delay (force expr))}という操作と考えられるからです
20325 (@code{force}の型は@code{Promise a -> a}であると考えられます)。
20326 @c COMMON
20327
20328 @c EN
20329 For the real-world example of use of @code{lazy},
20330 you may want to check the implementation of @code{util.stream}
20331 (@pxref{Stream library}).
20332 @c JP
20333 @code{lazy}の実用的な使用例については@code{util.stream}
20334 (@ref{Stream library})の実装をチェックするといいでしょう。
20335 @c COMMON
20336
20337 @c EN
20338 Note that @var{expression} may be evaluated more than once;
20339 it may require the value of its own promise recursively, or more than one
20340 thread may evaluate @var{expression} simultaneously.
20341 In general, you shouldn't have side-effecting computation
20342 in @var{expression}---even if it is only evaluated once,
20343 you may not exactly know when the evaluation occur, so
20344 having side-effects there is a bad ides.
20345 (See @code{force} below for multi-thread semantics).
20346 @c JP
20347 @var{expression}は一回以上評価され得ることに気をつけてください。
20348 @var{expression}の評価中に再帰的にそれ自身のプロミスの値を必要とするかも
20349 しれませんし、複数のスレッドが@var{expression}の計算を並行して行うかもしれません。
20350 一般的に、@var{expression}の中に副作用を持つ式を入れるべきではありません。
20351 たとえ@var{expression}が一度しか評価されないとしても、
20352 それがいつ評価されるかわからないかもしれないわけですから、
20353 副作用を持つのはまずいでしょう。
20354 (複数のスレッドがある場合のセマンティクスについては下の@code{force}を
20355 参照してください)。
20356 @c COMMON
20357 @end defspec
20358
20359 @defun eager obj @dots{}
20360 @defunx make-promise obj @dots{}
20361 [SRFI-45][SRFI-226]
20362 @c EN
20363 Returns a promise that returns @var{obj} @dots{}.
20364 The name @code{eager} is introduced in SRFI-45. It takes single argument,
20365 but Gauche enhanced it to take multiple values.
20366 SRFI-226 defines @code{make-promise}, which is the same
20367 as multi-value @code{eager}.
20368 (Note that R7RS-small also defines @code{make-promise} in
20369 @code{scheme.lazy} library (@pxref{R7RS lazy evaluation}).
20370 It is slightly different that it only takes one argument,
20371 and if the argument is a promise, it will be returned as is.
20372 This change is intentional; see SRFI-226 for the details.)
20373 @c JP
20374 @var{obj} @dots{}を返すプロミスを作って返します。
20375 @code{eager}という名前はSRFI-45で導入されました。SRFI-45では一つの引数のみを
20376 取るように定義されていますが、Gaucheでは複数の値を取って複数の値を返せるように
20377 拡張されています。SRFI-226は@code{make-promise}を定義しましたが、
20378 それは複数の値を取る@code{eager}と同じです。
20379 (R7RS-smallも@code{scheme.lazy}ライブラリで@code{make-promise}を
20380 定義しています(@ref{R7RS lazy evaluation}参照)が、
20381 この組み込み版とは少し異なります。
20382 R7RS版はひとつだけ引数を取るのと、引数が既にプロミスならそのまま返されます。
20383 この変更は意図的なものです。詳しくはSRFI-226を参照してください)。
20384 @c COMMON
20385
20386 @c EN
20387 Since that these are procedures, arguments are evaluated
20388 before they are called; so they work as a type converter
20389 (@code{a -> Promise a}) without delaying the evaluation.
20390 Used mainly to construct promise-returning functions.
20391 @c JP
20392 これらは通常の手続きなので、引数の評価は遅延されせん。
20393 評価を遅延することなく型変換(@code{a -> Promise a})だけを行いたい
20394 場合に使います。プロミスを返すことが要求される手続きで使われます。
20395 @c COMMON
20396 @end defun
20397
20398 @defun force promise
20399 [R7RS lazy][SRFI-226]
20400 @c EN
20401 If @var{promise} is not a promise, it is just returned.
20402
20403 Otherwise, if @var{promise}'s value hasn't been computed,
20404 @code{force} makes @var{promise}'s encapsulated expression
20405 be evaluated in the same parameterization where the promise
20406 is created, and returns the result.
20407
20408 Once @var{promise}'s value is computed, it is memorized in it
20409 so that subsequent @code{force} on it won't cause the computation.
20410 @c JP
20411 もし、@var{promise}がプロミスでなければ、それをそのまま返します。
20412
20413 そうではない場合で、もし@var{promise}の値がまだ計算されていない場合には、
20414 @code{force}は@var{promise}が内包している式を
20415 @var{promise}が作られた時点でのパラメタライゼーションで評価し、その結果を返します。
20416
20417 いったん、@var{promise}の値が計算されると、その値はメモ化され、あとで
20418 再び@code{force}されても、再計算がおこなわれることはありません。
20419 @c COMMON
20420
20421 @c EN
20422 In Gauche, if the delayed expression yields multiple values, @code{force}
20423 yields multiple values as well. (It is unspecified in R7RS).
20424
20425 @c JP
20426 Gaucheでは、遅延された式が複数の値を返した場合、@code{force}もそれらの値を返します。
20427 (R7RSではその場合の動作は未定義です)。
20428 @c COMMON
20429
20430 @c EN
20431 Note that if uncomputed promise is forced simultaneously
20432 by more than one thread, its expression may be evaluated concurrently.
20433 The first delivered value becomes the value of the promise; if another
20434 thread finishes computation and see the value of promise is already
20435 determined, it discards its computation result and returns the determined
20436 value.
20437 @c JP
20438 まだ計算されていないプロミスが複数のスレッドで同時にforceされた場合、
20439 プロミスに内包される式の計算は複数のスレッドで並行して進行します。
20440 一番最初に出た結果がプロミスの値として確定します。
20441 他のスレッドは、自分の計算が終わった時に既にプロミスの値が確定していたら、
20442 自分の計算結果を捨てて確定済みの値を返します。
20443 @c COMMON
20444
20445 @c EN
20446 The following example shows the promise is evaluated with the
20447 parameterization of @code{delay}:
20448 @c JP
20449 下の例は、プロミスが@code{delay}のあるパラメタライゼーションで評価される
20450 ことを示しています:
20451 @c COMMON
20452
20453 @example
20454 (define p (make-parameter 1))
20455
20456 (let1 v (parameterize ((p 2)) (delay (p)))
20457 (parameterize ((p 3))
20458 (force v)))
20459 @result{} 2
20460 @end example
20461
20462 @c EN
20463 Note: R7RS defines @code{force} to evaluate the unevaluated promise's body
20464 in the dynamic environment of the caller of @code{force}, but it is
20465 regarded as a mistake. In general, you shouldn't care which @code{force} call
20466 actually evaluates the promise's body, so the result shouldn't depend
20467 on the context of @code{force} call. SRFI-226 addressed it.
20468 @c JP
20469 註: R7RSでは未評価のプロミス本体は@code{force}の呼び出された動的環境で
20470 評価されるとしていましたが、これは間違いであったとみなされています。
20471 一般的に、どの@code{force}の呼び出しが実際にプロミス本体を評価するのかは
20472 気にされるべきではなく、従ってどこで@code{force}を呼び出すかによって結果が変わるのは
20473 おかしいからです。SRFI-226でこれは正されました。
20474 @c COMMON
20475 @end defun
20476
20477 @defun promise? obj
20478 [R7RS lazy]
20479 @c EN
20480 Returns @code{#t} iff @var{obj} is a promise object.
20481 @c JP
20482 @var{obj}がプロミスオブジェクトである場合に
20483 @code{#t}を返します。
20484 @c COMMON
20485 @end defun
20486
20487 @c TODO: example - use lazy tarai function
20488
20489 @node Lazy sequences, , Delay force and lazy, Lazy evaluation
20490 @subsection Lazy sequences
20491 @c NODE 遅延シーケンス
20492
20493 @c EN
20494 @subsubheading Introduction
20495 @c JP
20496 @subsubheading イントロダクション
20497 @c COMMON
20498
20499 @c EN
20500 A lazy sequence is a list-like structure
20501 whose elements are calculated lazily.
20502 Internally we have a special type of pairs, whose @code{cdr}
20503 is evaluated on demand.
20504 However, in Scheme level, you'll never see a distinct
20505 ``lazy-pair'' type. As soon as you try to access a
20506 lazy pair, Gauche automatically @emph{force} the delayed
20507 calculation, and the lazy pair turns into an ordinary pair.
20508 @c JP
20509 遅延シーケンスはリストのようなデータ構造ですが、要素は必要になるまで
20510 計算されません。内部的には、これは@code{cdr}の評価が遅延される特別な種類の
20511 ペアを使って実現されています。しかし、Schemeのレベルで
20512 「遅延ペア」のような特別なデータ型が見えることは決してありません。
20513 遅延ペアにアクセスしようとした途端、Gaucheは自動的に
20514 遅延されていた計算を@emph{force}して、遅延ペアは通常のペアに変化してしまうからです。
20515 @c COMMON
20516
20517 @c EN
20518 It means you can pass lazy sequences to ordinary list-processing
20519 procedures such as @code{car}, @code{cdr} or @code{map}.
20520 @c JP
20521 これはつまり、遅延シーケンスを@code{car}、@code{cdr}、@code{map}といった
20522 通常のリスト処理手続きにそのまま渡せるということです。
20523 @c COMMON
20524
20525 @c EN
20526 Look at the following example; @code{generator->lseq}
20527 takes a procedure that generates one value at a time, and
20528 returns a lazy sequence that consists of those values.
20529 @c JP
20530 次の例を見てください。@code{generator->lseq}は、
20531 「呼ばれる度に次の値を返す」という手続きを取り、返される値からなる遅延シーケンス
20532 にして返す手続きです。
20533 @c COMMON
20534
20535 @example
20536 (with-input-from-file "file"
20537 (^[] (let loop ([cs (generator->lseq read-char)] [i 0])
20538 (match cs
20539 [() #f]
20540 [(#\c (or #\a #\d) #\r . _) i]
20541 [(c . cs) (loop cs (+ i 1))]))))
20542 @end example
20543
20544 @c EN
20545 It returns the position of the first occurrence of
20546 character sequence ``car'' or ``cdr'' in the file @file{file}.
20547 The loop treats the lazy sequence just like an ordinary list, but
20548 characters are read as needed, so once the sequence is
20549 found, the rest of the file won't be read. If we do
20550 it eagerly, we would have to read the entire file first no matter how
20551 big it is, or to give up using the mighty @code{match} macro and
20552 to write a basic state machine that reads one character one at a time.
20553 @c JP
20554 このコードは、ファイル@file{file}中に最初に出現する
20555 ``car''または``cdr''という文字列の場所を返します。
20556 ループは遅延シーケンスを通常のリストのように扱っていますが、
20557 文字は必要に応じて読まれ、目的の文字列が見つかれば残りは読まれません。
20558 これを遅延無しでやろうとすると、一旦全てのファイルを読み込んでリストに
20559 変換するか、あるいは便利な@code{match}マクロを使うのを諦めて
20560 一文字つづ読み込んで処理する原始的な状態機械を書くしかないでしょう。
20561 @c COMMON
20562
20563 @c EN
20564 Other than implicit forcing, Gauche's lazy sequences are
20565 slightly different than the typical lazy stream implementations in Scheme
20566 in the following ways:
20567 @c JP
20568 暗黙のforceの他にも、Gaucheの遅延シーケンスは
20569 Schemeの典型的な遅延ストリーム実装に比べて次のような違いがあります。
20570 @c COMMON
20571
20572 @enumerate
20573 @item
20574 @c EN
20575 When you construct a lazy sequence in an iterative lazy algorithm,
20576 only @code{cdr} side of the lazy pair is lazily evaluated;
20577 the @code{car} side is evaluated immediately. On the other hand, with
20578 @code{stream-cons} in @code{util.stream} (@pxref{Stream library}),
20579 both @code{car} and @code{cdr} sides won't be evaluated until
20580 it is absolutely needed.
20581 @c JP
20582 遅延シーケンスを、繰り返しによる怠惰なアルゴリズムから構築する際に、
20583 遅延ペアの@code{cdr}側のみが遅延評価の対象となります。
20584 ペアの@code{car}側は直ちに評価されます。
20585 一方、@code{util.stream}の@code{stream-cons}では、
20586 @code{car}と@code{cdr}のどちらも遅延評価の対象となり、
20587 必要となるまで評価されません (@ref{Stream library}参照)。
20588 @c COMMON
20589 @item
20590 @c EN
20591 Gauche's lazy sequence always evaluates @emph{one item ahead}.
20592 Once you get a lazy pair, its @code{car} part is already
20593 calculated, even if you don't use it. In most cases
20594 you don't need to care, for calculating one item more
20595 is a negligible overhead. However, when you create
20596 a self-referential lazy structure, in which the earlier
20597 elements of a sequence is used to calculate the latter
20598 elements of itself, a bit of caution is needed;
20599 a valid code for fully lazy circular structure may not
20600 terminate in Gauche's lazy sequences. We'll show a
20601 concrete example later. This bit of eagerness
20602 is also visible when side effects are involved;
20603 for example, lazy character sequence reading from a port
20604 may read one character ahead.
20605 @c JP
20606 Gaucheの遅延シーケンスは、常に@emph{ひとつ余分に}評価します。
20607 遅延ペアを手にした段階で、その中身にアクセスするかしないかにかかわらず、
20608 既にその@code{car}は評価済みであるということです。
20609 ひとつ余分に計算してしまうことのコストは、通常はあまり問題にならないでしょう
20610 (全てを余分に計算するよりは良いわけですから)。けれども、自分自身を参照
20611 する遅延データ構造、つまり、遅延シーケンスの次の要素を計算するために
20612 そのシーケンスの前の方の要素を参照する必要がある場合は注意が必要です。
20613 遅延評価言語で正しい自己参照遅延データの生成コードが、
20614 そのままではGaucheで停止しなくなる場合があります。後で例を示します。
20615 また、評価に副作用がある場合にもこの差異が観測される場合があります。
20616 例えば、ポートから一文字づつ読む遅延シーケンスは、
20617 見かけよりも一文字余分に読むことになるでしょう。
20618 @c COMMON
20619 @end enumerate
20620
20621 @c EN
20622 Note: R7RS @code{scheme.lseq} (SRFI-127)
20623 provides a portable alternative of lazy sequence
20624 (@pxref{R7RS lazy sequences}). It uses
20625 dedicated APIs (e.g. @code{lseq-cdr}) to operate on lazy sequences
20626 so that portable implementation is possible. In Gauche, we just
20627 use our built-in lazy sequence as SRFI-127 lazy sequence; if you
20628 want your code to be portable, consider using SRFI-127, but be careful
20629 not to mix lazy sequences and ordinary lists; Gauche won't complain,
20630 but other Scheme implementation may choke on it.
20631 @c JP
20632 註: ポータブルな遅延シーケンスはR7RSの@code{scheme.lseq} (SRFI-127)でも提供されています
20633 (@ref{R7RS lazy sequences}参照)。SRFI-127では、遅延シーケンスを扱う
20634 専用のAPI (@code{lseq-cdr}等) を提供することで、ポータブルな実装を可能にしています。
20635 GaucheではSRFI-127の遅延シーケンスはGaucheの組み込み遅延シーケンスそのものです。
20636 移植性が重要であれば、SRFI-127を使うのが良いでしょう。但し、遅延シーケンスと
20637 通常のリストを混ぜないように気をつけてください。Gaucheは問題なく処理しますが、
20638 他のScheme処理系は喉を詰まらせてしまうかもしれません。
20639 @c COMMON
20640
20641 @c EN
20642 @subsubheading Primitives
20643 @c JP
20644 @subsubheading プリミティブ
20645 @c COMMON
20646
20647 @defun generator->lseq generator
20648 @defunx generator->lseq item @dots{} generator
20649 [R7RS lseq]
20650 @c EN
20651 Creates a lazy sequence that consists of items produced
20652 by @var{generator}, which is just a procedure with zero arguments that yields
20653 an item at a time. Returning EOF marks the end of the sequence
20654 (EOF itself isn't included in the sequence).
20655 For example, @code{read-char} can work as a generator.
20656 Gauche has a set of convenient utilities to deal with generators
20657 (@pxref{Generators}).
20658 @c JP
20659 ジェネレータ手続き@var{generator}から生成される値の列を、遅延シーケンスとして返します。
20660 ジェネレータ手続きは引数を取らない手続きで、呼ばれる度に次の値を返すようなものです。
20661 EOFが返されたら、シーケンスの終了とみなされます (EOF自体はシーケンスには含まれません)。
20662 例えば@code{read-char}はそのまま@var{generator}に渡せます。
20663 ジェネレータ手続きを作ったり加工したりする便利なユーティリティが
20664 @code{gauche.generator}モジュールで提供されています (@ref{Generators}参照)。
20665 @c COMMON
20666
20667 @c EN
20668 In the second form, the returned lazy sequence is prepended by
20669 @var{item} @dots{}. Since there's no way to distinguish lazy
20670 pairs and ordinary pairs, you can write it as
20671 @code{(cons* item @dots{} (generator->lseq generator))},
20672 but that's more verbose.
20673 @c JP
20674 二番目の形式では、@var{item} @dots{}が遅延シーケンスの先頭に
20675 配置されます。遅延ペアと通常のペアは区別できないので、これは
20676 @code{(cons* item @dots{} (generator->lseq generator))}とも書けますが、
20677 少々冗長になるでしょう。
20678 @c COMMON
20679
20680 @c EN
20681 Internally, Gauche's lazy sequence is optimized to be built
20682 on top of generators, so this procedure is the most efficient
20683 way to build lazy sequences.
20684 @c JP
20685 内部的には、Gaucheの遅延シーケンスはジェネレータを使うように最適化
20686 されています。遅延シーケンスを作る最も効率の良い方法はこの手続きを使うことです。
20687 @c COMMON
20688
20689 @c EN
20690 Note: SRFI-127 also has @code{generator->lseq}, which is exactly
20691 the same as this in Gauche.
20692 @c JP
20693 註: SRFI-127も@code{generator->lseq}を定義していますが、Gaucheではそれは
20694 この手続きと同じものです。
20695 @c COMMON
20696 @end defun
20697
20698 @defmac lcons car cdr
20699 @c EN
20700 Returns a lazy pair consists of @var{car} and @var{cdr}.
20701 The expression @var{car} is evaluated at the call of @code{lcons},
20702 but evaluation of @var{cdr} is delayed.
20703 @c JP
20704 @var{car}と@var{cdr}からなる遅延ペアを作って返します。
20705 @var{car}は@code{lcons}を呼び出した時点で評価されますが、
20706 @var{cdr}の評価は遅延されます。
20707 @c COMMON
20708
20709 @c EN
20710 You can't distinguish a lazy pair from an ordinary pair. If you
20711 access either its @code{car} or @code{cdr}, or even you ask @code{pair?}
20712 to it, its cdr part is implicitly forced and you get an ordinary pair.
20713 @c JP
20714 遅延ペアと通常のペアを区別する方法はありません。ペアの@code{car}や@code{cdr}に
20715 アクセスしたり、それどころか@code{pair?}によって型を確かめただけでも、
20716 遅延ペアのcdr側はforceされて、遅延ペアは通常のペアへと変化します。
20717 @c COMMON
20718
20719 @c EN
20720 Unlike @code{cons}, @var{cdr} should be an expression that yields
20721 a (lazy or ordinary) list, including an empty list.
20722 In other words, lazy sequences can always be a null-terminated list
20723 when entirely forced; there are no ``improper lazy sequences''.
20724 (Since Scheme isn't statically typed, we can't force the @var{cdr}
20725 expression to be a proper list before actually evaluating it.
20726 Currently if @var{cdr} expression yields non-list, we just ignore
20727 it and treat as if it yielded an empty list.)
20728 @c JP
20729 @code{cons}と違って、遅延ペアの@var{cdr}はリスト (遅延でも通常でも) を返す
20730 関数でなければなりません。遅延シーケンスは全てforceされたら、
20731 常に空リストで終端されているリストになる、と言っても良いでしょう。つまり、
20732 ドット対を最後に持つような「不完全なリスト」に対応する「不完全な遅延シーケンス」
20733 というものはありません。(Schemeは静的型ではないので、実際に評価するまで
20734 @var{cdr}が完全なリストを生成することを保証することができません。
20735 現在の実装では、@var{cdr}がリストでない値を生成した場合、
20736 それを単に無視して空リストが返されたかのように扱います)。
20737 @c COMMON
20738
20739 @example
20740 (define z (lcons (begin (print 1) 'a) (begin (print 2) '())))
20741 @c EN
20742 @result{} ; prints '1', since the car part is evaluated eagerly.
20743 @c JP
20744 @result{} ; car部はすぐに評価されるので、'1'が表示される
20745 @c COMMON
20746
20747 @c EN
20748 (cdr z) @result{} () ;; and prints '2'
20749 @c JP
20750 (cdr z) @result{} () ;; そして'2'が表示される
20751 @c COMMON
20752
20753 @c EN
20754 ;; This also prints '2', for accessing car of a lazy pair forces
20755 ;; its cdr, even the cdr part isn't used.
20756 @c JP
20757 ;; これも'2'を表示する。遅延ペアのcarにアクセスすると、その時点で
20758 ;; cdr部の評価もforceされるので。
20759 @c COMMON
20760 (car (lcons 'a (begin (print 2) '()))) @result{} a
20761
20762 @c EN
20763 ;; So as this; asking pair? to a lazy pair causes forcing its cdr.
20764 @c JP
20765 ;; これも同じ。pair?と聞くだけで遅延ペアはforceされる
20766 @c COMMON
20767 (pair? (lcons 'a (begin (print 2) '()))) @result{} #t
20768
20769 @c EN
20770 ;; To clarify: This doesn't print '2', because the second lazy
20771 ;; pair never be accessed, so its cdr isn't evaluated.
20772 @c JP
20773 ;; 念のため。次の例では'2'は出力されない。二番目の遅延ペアはアクセス
20774 ;; されていないので、そのcdrも評価されない。
20775 @c COMMON
20776 (pair? (lcons 'a (lcons 'b (begin (print 2) '())))) @result{} #t
20777 @end example
20778
20779 @c EN
20780 Now, let me show you a case where ``one item ahead'' evaluation becomes
20781 an issue. The following is an elegant definition of infinite
20782 Fibonacci sequence using self-referential lazy structure
20783 (@code{lmap} is a lazy map, defined in @code{gauche.lazy} module):
20784 @c JP
20785 Gaucheの「一つ先の要素まで計算」が問題となる例も見ておきましょう。
20786 次の例は、自己参照する遅延シーケンスを使った、とても美しい無限フィボナッチ数列の
20787 定義です (@code{lmap}は遅延バージョンのmapで、@code{gauche.lazy}モジュールで
20788 提供されています)。
20789 @c COMMON
20790
20791 @example
20792 (use gauche.lazy) ;; for lmap
20793 (define *fibs* (lcons* 0 1 (lmap + *fibs* (cdr *fibs*)))) ;; BUGGY
20794 @end example
20795
20796 @c EN
20797 Unfortunately, Gauche can't handle it well.
20798 @c JP
20799 残念ながら、Gaucheではこれはうまく動きません。
20800 @c COMMON
20801
20802 @example
20803 (car *fibs*)
20804 @result{} 0
20805 (cadr *fibs*)
20806 @result{} *** ERROR: Attempt to recursively force a lazy pair.
20807 @end example
20808
20809 @c EN
20810 When we want to access the second argument (@code{cadr}) of @code{*fibs*},
20811 we take the car of the second pair,
20812 which is a lazy pair of @code{1} and @code{(lmap ...)}. The lazy pair
20813 is forced and its cdr part needs to be calculated. The first thing
20814 @code{lmap} returns needs to see the first and second element of @code{*fibs*},
20815 but the second element of @code{*fibs*} is what we're calculating now!
20816 @c JP
20817 @code{*fibs*}の二番目の要素(@code{cadr})にアクセスするということは、
20818 @code{*fibs*}の二番目のペアのcarを取るということです。@code{*fibs*}の
20819 二番目のペアは@code{1}と@code{(lmap ...)}の遅延ペアになっています。
20820 carを取ろうとした時点でこの遅延ペアはforceされ、そのcdrが計算されます。
20821 @code{lmap}が最初に返さなければならないのは、@code{*fibs*}の一番目と二番目の
20822 要素の和です。しかし@code{*fibs*}の二番目の要素は、今まさにアクセスしようと
20823 している値です!
20824 @c COMMON
20825
20826 @c EN
20827 We can workaround this issue by
20828 avoiding accessing the immediately preceding value.
20829 Fibonacci numbers F(n) = F(n-1) + F(n-2) = 2*F(n-2) + F(n-3), so we
20830 can write our sequence as follows.
20831 @c JP
20832 この問題は、ある要素を計算するために直前の要素を参照しなければ回避できます。
20833 フィボナッチ数はF(n) = F(n-1) + F(n-2) = 2*F(n-2) + F(n-3)と変形できるので、
20834 遅延フィボナッチシーケンスはこう定義できます。
20835 @c COMMON
20836
20837 @example
20838 (define *fibs*
20839 (lcons* 0 1 1 (lmap (^[a b] (+ a (* b 2))) *fibs* (cdr *fibs*))))
20840 @end example
20841
20842 @c EN
20843 And this works!
20844 @c JP
20845 これでok!
20846 @c COMMON
20847
20848 @example
20849 (take *fibs* 20)
20850 @result{} (0 1 1 2 3 5 8 13 21 34 55 89 144 233
20851 377 610 987 1597 2584 4181)
20852 @end example
20853
20854 @c EN
20855 Many lazy algorithms are defined in terms of fully-lazy cons
20856 at the bottom. When you port such algorithms to Gauche using @code{lcons},
20857 keep this bit of eagerness in mind.
20858 @c JP
20859 多くの遅延アルゴリズムは、完全な遅延評価をするconsを基礎にしています。
20860 そういったアルゴリズムを@code{lcons}を使ってGaucheに移植する際には、
20861 Gaucheのこのちょっとした「熱心さ」に気をつけてください。
20862 @c COMMON
20863
20864 @c EN
20865 Note also that @code{lcons} needs to create a thunk to delay
20866 the evaluation. So the algorithm to construct lazy list using
20867 @code{lcons} has an overhead of making closure for each item.
20868 For performance-critical part,
20869 you want to use @code{generator->lseq} whenever possible.
20870 @c JP
20871 @code{lcons}は、実行の度にcdr部の評価を遅延するためのクロージャを
20872 作るということにも注意してください。@code{lcons}を使った遅延アルゴリズムでは
20873 要素ひとつにつきクロージャをひとつ作るオーバヘッドがかかります。
20874 性能が重要な部分では、可能な限り@code{generator->lseq}を使いましょう。
20875 @c COMMON
20876 @end defmac
20877
20878 @c EN
20879 @subsubheading Utilities
20880 @c JP
20881 @subsubheading ユーティリティ
20882 @c COMMON
20883
20884 @defmac lcons* x @dots{} tail
20885 @defmacx llist* x @dots{} tail
20886 @c EN
20887 A lazy version of @code{cons*} (@pxref{List constructors}).
20888 Both @code{lcons*} and @code{llist*} do the same thing; both
20889 names are provided for the symmetry to @code{cons*}/@code{list*}.
20890 @c JP
20891 遅延バージョンの@code{cons*}です (@ref{List constructors}参照)。
20892 @code{lcons*}と@code{llist*}は全く同じです。
20893 @code{cons*}/@code{list*}との対称性から両方の名前が定義されています。
20894 @c COMMON
20895
20896 @c EN
20897 The @var{tail} argument should be an expression that yields a
20898 (possibly lazy) list. It is evaluated lazily. Note that
20899 the preceding elements @var{x} @dots{} are evaluated eagerly.
20900 The following equivalences hold.
20901 @c JP
20902 @var{tail}引数は(遅延もしくは通常の)リストを生成する式でなければなりません。
20903 @var{tail}引数の評価は遅延されます。@var{x} @dots{}引数はすぐに
20904 評価されます。次の関係が成り立ちます。
20905 @c COMMON
20906
20907 @example
20908 (lcons* a) @equiv{} a
20909 (lcons* a b) @equiv{} (lcons a b)
20910 (lcons* a b ... y z) @equiv{} (cons* a b @dots{} (lcons y z))
20911 @end example
20912 @end defmac
20913
20914 @defun lrange start :optional end step
20915 @c EN
20916 Creates a lazy sequence of numbers starting from @var{start},
20917 increasing by @var{step} (default 1), to the maximum value that doesn't
20918 exceed @var{end}. The default of @var{end} is @code{+inf.0},
20919 so it creates an infinite list. (Don't type just
20920 @code{(lrange 0)} in REPL, or it won't terminate!)
20921 @c JP
20922 @var{start}から@var{step}づつ増加し、@var{end}を越える直前までの遅延数列を
20923 返します。@var{step}のデフォルトは1、@var{end}のデフォルトは無限大です。
20924 @var{end}を省略すると無限数列になるので、REPLで安易に
20925 @code{(lrange 0)}など評価しないようにしましょう。
20926 @c COMMON
20927
20928 @c EN
20929 If any of @var{start} or @code{step} is inexact, the resulting sequence
20930 has inexact numbers.
20931 @c JP
20932 @var{start}と@var{step}の少なくとも一方が非正確数なら、
20933 非正確数列が返されます。
20934 @c COMMON
20935
20936 @example
20937 (take (lrange -1) 3) @result{} (-1 0 1)
20938
20939 (lrange 0.0 5 0.5)
20940 @result{} (0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5)
20941
20942 (lrange 1/4 1 1/8)
20943 @result{} (1/4 3/8 1/2 5/8 3/4 7/8)
20944 @end example
20945 @end defun
20946
20947 @defun liota :optional (count +inf.0) (start 0) (step 1)
20948 @c EN
20949 A lazy version of @code{iota} (@pxref{List constructors}); returns
20950 a lazy sequence of @var{count} integers (default: positive infinity),
20951 starting from @var{start} (default: 0), stepping by @var{step} (default: 1).
20952 @c JP
20953 遅延バージョンの@code{iota}です (@ref{List constructors}参照)。
20954 @var{start}(デフォルト0)から@var{step}(デフォルト1)づつ増加する、
20955 @var{count}個(デフォルト無限大)の遅延数列を返します。
20956 @c COMMON
20957
20958 @c EN
20959 Just like @code{iota}, the result consists of exact numbers
20960 if and only if both @var{start} and @var{step} are exact; otherwise
20961 the result consists of inexact numbers.
20962 @c JP
20963 @code{iota}と同様、@var{start}と@var{step}の両方が正確数の時に限り、
20964 結果は正確数のリストとなり、そうでなければ非正確数のリストとなります。
20965 @c COMMON
20966 @end defun
20967
20968 @defun port->char-lseq :optional port
20969 @defunx port->byte-lseq :optional port
20970 @defunx port->string-lseq :optional port
20971 @defunx port->sexp-lseq :optional port
20972 @c EN
20973 These are the same as the following expressions, respectively.
20974 They are provided for the convenience, since this pattern appears
20975 frequently.
20976 @c JP
20977 これらの手続きは以下の式とそれぞれ同等です。このパターンは良く現れるので、
20978 簡便のために用意しました。
20979 @c COMMON
20980
20981 @example
20982 (generator->lseq (cut read-char port))
20983 (generator->lseq (cut read-byte port))
20984 (generator->lseq (cut read-line port))
20985 (generator->lseq (cut read port))
20986 @end example
20987
20988 @c EN
20989 If @var{port} is omitted, the current input port is used.
20990
20991 Note that the lazy sequence may buffer some items, so
20992 once you make an lseq from a port, only use the resulting lseq
20993 and don't ever read from @var{port} directly.
20994 @c JP
20995 @var{port}が省略された場合はcurrent-input-portが使われます。
20996
20997 遅延シーケンスが入力をいくらかバッファする可能性があるので、
20998 一度lseqを作った後では、@var{port}から直接読み出しをしないようにしてください。
20999 @c COMMON
21000
21001 @c EN
21002 Note that the lazy sequence terminates when EOF is read from the port,
21003 but the port isn't closed. The port should be managed in larger
21004 dynamic extent where the lazy sequence is used.
21005 @c JP
21006 遅延シーケンスはポートがEOFを返した時点で終端となりますが、
21007 ポート自体はクローズされないことに注意してください。ポートの管理は、
21008 遅延シーケンスを使う部分全体を囲むような大きな動的エクステントで
21009 行う必要があります。
21010 @c COMMON
21011
21012 @c EN
21013 You can also convert input data into various lists by
21014 the following expressions (@pxref{Input utility functions}).
21015 Those procedures read the port eagerly until EOF and returns
21016 the whole data in a list, while @code{lseq} versions read
21017 the port lazily.
21018 @c JP
21019 入力ポートを色々なリストに変換するには、他に次のような手続きがあります
21020 (@ref{Input utility functions}参照)。@code{lseq}版がポートを
21021 必要に応じて読むのに対し、
21022 これらの手続きはポートをEOFに達するまで一気に読み込み、
21023 全てのデータをリストにしてから返します。
21024 @c COMMON
21025
21026 @example
21027 (port->list read-char port)
21028 (port->list read-byte port)
21029 (port->string-list port)
21030 (port->sexp-list port)
21031 @end example
21032
21033 @c EN
21034 Those procedures make (lazy) lists out of ports. The opposite can be
21035 done by @code{open-input-char-list} and @code{open-input-byte-list};
21036 @xref{Virtual ports}, for the details.
21037 @c JP
21038 これらの手続きは、ポートからリストを作りだします。反対の手続きとして、
21039 @code{open-input-char-list}と@code{open-input-byte-list}があります
21040 (@ref{Virtual ports}参照)。
21041 @c COMMON
21042 @end defun
21043
21044
21045 @c EN
21046 See also @ref{Lazy sequence utilities}, for more utility procedures
21047 that creates lazy sequences.
21048 @c JP
21049 遅延シーケンスを作るユーティリティ関数は他にもたくさん提供されています。
21050 @ref{Lazy sequence utilities}を参照してください。
21051 @c COMMON
21052
21053 @c EN
21054 @subsubheading Examples
21055 @c JP
21056 @subsubheading 例
21057 @c COMMON
21058
21059 @c EN
21060 Let's consider calculating an infinite sequence of prime numbers.
21061 (Note: If you need prime numbers in your application, you don't
21062 need to write one; just use @code{math.prime}. @pxref{Prime numbers}).
21063 @c JP
21064 素数の無限列を計算してみましょう。(註:
21065 アプリケーションで素数が必要な場合は、わざわざ書かなくても
21066 @code{math.prime}が使えます。@ref{Prime numbers}参照。)
21067 @c COMMON
21068
21069 @c EN
21070 Just pretend we already have some prime numbers
21071 calculated in a variable @code{*primes*}, and you need
21072 to find a prime number equal to or grater than @var{n}
21073 (for simplicity, we assume @var{n} is an odd number).
21074 @c JP
21075 まず、既にある程度の計算済みの素数列が@code{*primes*}にあるとします。
21076 すると、与えられた@var{n}以上の素数をひとつ見つける手続きが次のとおり書けます
21077 (@var{n}は奇数とします。)
21078 @c COMMON
21079
21080 @example
21081 (define (next-prime n)
21082 (let loop ([ps *primes*])
21083 (let1 p (car ps)
21084 (cond [(> (* p p) n) n]
21085 [(zero? (modulo n p)) (next-prime (+ n 2))]
21086 [else (loop (cdr ps))]))))
21087 @end example
21088
21089 @c EN
21090 This procedure loops over the list of prime numbers, and
21091 if no prime number @var{p} less than or equal to @code{(sqrt n)}
21092 divides @var{n}, we can say @var{n} is prime. (Actual test
21093 is done by @code{(> (* p p) n)} instead of @code{(> p (sqrt n))},
21094 for the former is faster.)
21095 If we find some @var{p} divides @var{n}, we try a new value
21096 @code{(+ n 2)} with @code{next-prime}.
21097 @c JP
21098 この手続きは素数列をループし、@code{(sqrt n)}以下の素数で
21099 @var{n}を割ろうとします。一つも割りきれる素数がなければ、@var{n}が素数です。
21100 (実際の条件は、@code{(> p (sqrt n))}より効率の良い@code{(> (* p p) n)}を
21101 使っています)。
21102 @var{n}を割り切る素数があった場合は、
21103 @code{next-prime}を再帰的に呼んで@code{(+ n 2)}を試します。
21104 @c COMMON
21105
21106 @c EN
21107 Using @code{next-prime}, we can make a generator that keeps generating
21108 prime numbers. The following procedure returns a generator
21109 that returns primes above @var{last}.
21110 @c JP
21111 @code{next-prime}を使うと、次々に素数を生成してゆくジェネレータを書くことができます。
21112 次の手続きは@var{last}より大きい素数を次々に生成するジェネレータです。
21113 @c COMMON
21114
21115 @example
21116 (define (gen-primes-above last)
21117 (^[] (set! last (next-prime (+ last 2))) last))
21118 @end example
21119
21120 @c EN
21121 Using @code{generator->lseq}, we can turn the generator returned
21122 by @code{gen-primes-above} into a lazy list, which can be used
21123 as the value of @code{*prime*}. The only caveat is that we need
21124 to have some pre-calculated prime numbers:
21125 @c JP
21126 @code{generator->lseq}を使えば、
21127 @code{gen-primes-above}を遅延シーケンスに変換することができ、
21128 それを@code{*prime*}の値とすることができます。最初の方の素数を計算するために、
21129 あらかじめ計算済みの素数をいくつか用意しておくのがポイントです。
21130 @c COMMON
21131
21132 @example
21133 (define *primes* (generator->lseq 2 3 5 (gen-primes-above 5)))
21134 @end example
21135
21136 @c EN
21137 Be careful not to evaluate @code{*primes*} directly on REPL,
21138 since it contains an infinite list and it'll blow up your REPL.
21139 You can look at the first 20 prime numbers instead:
21140 @c JP
21141 @code{*primes*}を直接REPLで評価しないように。無限リストなので、
21142 REPLの表示が終わらなくなります。
21143 かわりに、例えばこんなふうにして最初の20個の素数を見たり:
21144 @c COMMON
21145
21146 @example
21147 (take *primes* 20)
21148 @result{} (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71)
21149 @end example
21150
21151 @c EN
21152 Or find what the 10000-th prime number is:
21153 @c JP
21154 10000番目の素数は何かを見たり:
21155 @c COMMON
21156
21157 @example
21158 (~ *primes* 10000)
21159 @result{} 104743
21160 @end example
21161
21162 @c EN
21163 Or count how many prime numbers there are below 1000000:
21164 @c JP
21165 あるいは1000000以下の素数はいくつあるかを調べたりできます:
21166 @c COMMON
21167
21168 @example
21169 (any (^[p i] (and (>= p 1000000) i)) *primes* (lrange 0))
21170 @result{} 78498
21171 @end example
21172
21173 @c EN
21174 Note: If you're familiar with the lazy functional approach, this example
21175 may look strange. Why do we use side-effecting generators
21176 while we can define a sequence of prime numbers in
21177 pure functional way, as follows?
21178 @c JP
21179 註:遅延評価な関数型言語に慣れたプログラマには、この例は奇妙に見えるかもしれません。
21180 わざわざ副作用のあるジェネレータを経由しないでも、
21181 次に示すとおり、素数列は純粋に関数的な方法で定義できます。
21182 @c COMMON
21183
21184 @example
21185 (use gauche.lazy)
21186
21187 (define (prime? n)
21188 (not (any (^p (zero? (mod n p)))
21189 (ltake-while (^k (<= (* k k) n)) *primes*))))
21190
21191 (define (primes-from k)
21192 (if (prime? k)
21193 (lcons k (primes-from (+ k 2)))
21194 (primes-from (+ k 2))))
21195
21196 (define *primes* (llist* 2 3 5 (primes-from 7)))
21197 @end example
21198
21199 @c EN
21200 (The module @code{gauche.lazy} provides @code{ltake-while}, which
21201 is a lazy version of @code{take-while}. We don't need lazy version
21202 of @code{any}, since it immediately stops when the predicate returns
21203 a true value.)
21204 @c JP
21205 (@code{gauche.lazy}モジュールには、@code{take-while}の
21206 遅延バージョン@code{ltake-while}が定義されています。
21207 @code{any}については、遅延バージョンは必要ありません。@code{any}はもともと
21208 述語が真を返したら直ちに評価をやめて残りは見ないからです)。
21209 @c COMMON
21210
21211 @c EN
21212 The use of @code{lcons} and co-recursion in @code{primes-from}
21213 is a typical idiom in functional programming. It's perfectly ok
21214 to do so in Gauche; except that the generator version is @emph{much} faster
21215 (when you take first 5000 primes, generator version ran 17 times faster
21216 than co-recursion version on the author's machine).
21217 @c JP
21218 @code{primes-from}での@code{lcons}を使った余再帰は、
21219 関数型プログラミングでの典型的なイディオムです。もちろん、
21220 Gaucheでもこのようなコードを書くことに何の問題もありません。
21221 ただし、Gaucheではジェネレータを使った方が@emph{ずっと}効率が良くなります
21222 (筆者のマシンでは、最初の5000個の素数を計算するのに、
21223 ジェネレータ版は余再帰版より17倍速いです)。
21224 @c COMMON
21225
21226 @c EN
21227 It doesn't mean you should avoid co-recursive code; if an algorithm
21228 can be expressed nicely in co-recursion, it's perfectly ok. However,
21229 watch out the subtle semantic difference from lazy functional
21230 languages---straightforward porting may or may not work.
21231 @c JP
21232 だからといって何が何でも余再帰を避けるべきということにはなりません。
21233 アルゴリズムが余再帰で自然にかけるならそうして構わないでしょう。
21234 ただその場合でも、遅延評価な関数型言語とのセマンティクスの違いを
21235 いつも気をつけるようにしてください。単に遅延評価アルゴリズムのコードを
21236 そのまま移植しても動くとは限りません。
21237 @c COMMON
21238
21239 @c ----------------------------------------------------------------------
21240 @node Exceptions, Eval and repl, Lazy evaluation, Core library
21241 @section Exceptions
21242 @c NODE 例外
21243
21244 @c EN
21245 Gauche's exception system consists of three components;
21246 (1) the way to signal an exceptional case has occurred,
21247 (2) the way to specify how to handle such a case,
21248 and (3) the standard objects (@emph{conditions})
21249 to communicate the code that
21250 signals an exceptional case and the code that handles it.
21251 @c JP
21252 Gaucheの例外システムは次の3つのコンポーネントから構成されています。
21253 (1)例外状況が発生したことを通知する方法、
21254 (2)例外状況をどのように処理するかを指定する方法、
21255 (3)例外状況を知らせたコードとそれを処理するコードがやりとりするための
21256 標準オブジェクト(@emph{コンディション})。
21257 @c COMMON
21258
21259 @c EN
21260 Those three components are typically used together, so first
21261 we explain the typical usage patterns using examples. Then
21262 we describe each feature in detail.
21263 @c JP
21264 普通これらの3つのコンポーネントは一緒に使われます。
21265 そこで、最初に例を用いて典型的な使い方について説明し、
21266 そのあとでそれぞれの機能について詳しく解説します。
21267 @c COMMON
21268
21269 @c EN
21270 Note for terminology: some languages use the word @emph{exception}
21271 to refer to an object used to communicate the code that encountered
21272 an exceptional situation with a handler that deals with it.
21273 Gauche uses a term @emph{condition} to refer to such objects,
21274 following SRFI-35. @emph{Exception} is the situation, and
21275 @emph{condition} is a runtime object that describes it.
21276 @c JP
21277 用語について: いくつかの言語では@emph{例外(exception)}というと、
21278 例外的状況に遭遇したコードとそのハンドラがやりとりをするために用られる
21279 オブジェクトのことを指します。Gaucheではそのようなオブジェクトのことを言うときには、
21280 SRFI-35にならって@emph{コンディション(condition)}を使います。
21281 @emph{例外}というのは、状況であり、@emph{コンディション}はそれを記述する
21282 実行時のオブジェクトです。
21283 @c COMMON
21284
21285 @menu
21286 * Exception handling overview::
21287 * Signaling exceptions::
21288 * Handling exceptions::
21289 * Conditions::
21290 @end menu
21291
21292 @node Exception handling overview, Signaling exceptions, Exceptions, Exceptions
21293 @subsection Exception handling overview
21294 @c NODE 例外処理の概要
21295
21296 @c EN
21297 @subsubheading Catching specific errors
21298 @c JP
21299 @subsubheading 特定のエラーを捕まえる
21300 @c COMMON
21301
21302 @c EN
21303 One of the most typical exception handling is to catch a
21304 specific error raised by some built-in or library procedures.
21305 A macro @code{guard} can be used for such a purpose. The code
21306 looks like this:
21307 @c JP
21308 最もよくある例外処理のひとつは、組み込みあるいは
21309 ライブラリの手続きから発生した特定のエラーを捕捉するというものです。
21310 @code{guard}マクロがこのような目的の場合に使えます。
21311 コードは以下のような感じになるでしょう。
21312 @c COMMON
21313
21314 @example
21315 (guard (exc [(condition-has-type? exc <read-error>)
21316 (format #t "read error!")
21317 'read-error]
21318 [else 'other-error])
21319 (read-from-string "(abc"))
21320 @end example
21321
21322 @c EN
21323 The cadr of @code{guard} clause is a form of
21324 @code{(@var{variable} @var{clause} @dots{})}. In this example,
21325 the variable is @code{exc}, and it has two clauses.
21326 Each @var{clause} has the form like the one in @code{cond}.
21327 @c JP
21328 @code{guard}節の cadr 部は @code{(@var{variable} @var{clause} @dots{})} という
21329 形式です。この例では、変数は @code{exc}で、2つの節があります。
21330 それぞれの @var{clause} は @code{cond} と似た形式になります。
21331 @c COMMON
21332
21333 @c EN
21334 The cddr of @code{guard} is the body, a list of expressions. This
21335 example has only one expression, @code{(read-from-string "(abc")}.
21336 @c JP
21337 @code{guard} の cddr 部は本体で、式のリストです。この例では、式は
21338 @code{(read-from-string "(abc")} のひとつだけです。
21339 @c COMMON
21340
21341 @c EN
21342 @code{guard} starts executing its body.
21343 @code{read-from-string} raises an error of type @code{<read-error>}
21344 when it encounters syntactic errors. The form @code{guard} intercepts
21345 the error, and binds the condition object to the variable @var{exc},
21346 then checks the clauses following @var{exc} in a similar manner
21347 to @code{cond}---in this case, the thrown condition is of type
21348 @code{<read-error>}, so the test of the first clause is satisfied,
21349 and the rest of clause is executed, i.e. @code{"read error!"} is
21350 printed and a symbol @code{read-error} is returned.
21351 @c JP
21352 @code{guard} はその本体部を実行するところから始めます。
21353 @code{read-from-string} は構文エラーに出くわすと、@code{<read-error>}型の
21354 エラーを発生させます。@code{guard}フォームがこのエラーを捕捉し、
21355 そのコンディションオブジェクトを変数@var{exc}に束縛し、@var{exc}の後の
21356 節を、@code{cond}と同じようにチェックします。この場合、投げられた
21357 コンディションは @code{<read-error>}なので、最初の節のテストを満し、
21358 その節の残りの部分が実行されます。すなわち、@code{"read error!"} が
21359 印字され、シンボル @code{read-error} が返ります。
21360 @c COMMON
21361
21362 @c EN
21363 If you're familiar with other languages, you may recognize the
21364 pattern. The cddr of @code{guard} form is like @var{try} clause
21365 of C++/Java or the cadr of @code{handler-case} of Common Lisp;
21366 and the cdadr of @code{guard} form is like @code{catch} clauses
21367 or the cddr of @code{handler-case}.
21368 @c JP
21369 他の言語を使い慣れていれば、同じパターンであることがわかると思います。
21370 @code{guard} フォームの cddr 部は、C++やJavaの @var{try} 節、あるいは、
21371 Common Lisp の @code{handler-case} の cadr 部に似ています。
21372 また、@code{guard} フォームの cdadr 部は、@code{catch} 節あるいは、
21373 @code{handler-case} の cddr 部に似ています。
21374 @c COMMON
21375
21376 @c EN
21377 In the test expressions it is common to check the type of
21378 thrown condition. The function @code{condition-has-type?} is
21379 defined in SRFI-35 but it's rather lengthy. Gauche's condition
21380 classes can also work like a predicate, so you can write the
21381 above expression like this.
21382 @c JP
21383 テスト式においては、投げられたコンディションのタイプをチェックする
21384 のが普通です。@code{condition-has-type?} という関数が
21385 SRFI-35 で定義されていますが、これはちょっと冗長です。Gauche の
21386 コンディションクラスは述語のようにも使えるようになっており、上の
21387 式は以下のように書くこともができます。
21388 @c COMMON
21389
21390 @example
21391 (guard (exc [(<read-error> exc)
21392 (format #t "read error!")
21393 'read-error]
21394 [else 'other-error])
21395 (read-from-string "(abc"))
21396 @end example
21397
21398 @c EN
21399 @emph{Note:} Generally you can't use @code{is-a?} to test if
21400 the thrown condition is of a specific type, since a condition
21401 may be @emph{compound}. See @ref{Conditions} about compound
21402 conditions.
21403 @c JP
21404 @emph{注意事項:} 一般的には、投げられたコンディションが特定の
21405 タイプであるかをチェックするのに@code{is-a?}は使えません。
21406 コンディションが合成されたものである可能性があるからです。
21407 合成されたコンディションについての
21408 詳細は @ref{Conditions} を参照してください。
21409 @c COMMON
21410
21411 @c EN
21412 If no tests of @var{clause}s satisfy and no @code{else} clause is given,
21413 the exception `falls off' the @code{guard} construct, i.e.
21414 it will be handled by the outer level of @code{guard} form or
21415 top-level. For example, the following @code{guard} form
21416 only handles @code{<read-error>} and @code{<system-error>};
21417 if the body throws other type of conditions, it must be handled
21418 by outer level.
21419 @c JP
21420 もし、@var{clause} のどのテストも満されず、かつ @code{else} 節があたえられて
21421 いなければ、その例外は @code{guard} から「抜け」ます。すなわち、@code{guard}
21422 の外側のレベルあるいはトップレベルで処理されることになります。たとえば、
21423 以下の @code{guard} フォームでは、@code{<read-error>} と
21424 @code{<system-error>} としか処理できず、もし、本体が他のタイプのコンディション
21425 を投げてきたら、その外側のレベルで処理しなければなりません。
21426 @c COMMON
21427
21428 @example
21429 (guard (exc [(<read-error> exc) (handle-read-error)]
21430 [(<system-error> exc) (handle-system-error)])
21431 body @dots{})
21432 @end example
21433
21434 @c EN
21435 See @ref{Handling exceptions} for more details on @code{guard} and
21436 other lower-level exception handling constructs.
21437 @c JP
21438 @code{guard}および他の低レベルの例外処理の構成についての詳細は
21439 @ref{Handling exceptions} を参照してください。
21440 @c COMMON
21441
21442
21443 @c EN
21444 @subsubheading Signaling exceptions from your code
21445 @c JP
21446 @subsubheading 自分のコードから例外を通知する
21447 @c COMMON
21448
21449 @c EN
21450 The generic way to signal an exception is to use @code{raise} procedure.
21451 @c JP
21452 例外を通知する一般的な方法は @code{raise}手続きを使うことです。
21453 @c COMMON
21454
21455 @example
21456 (raise @var{condition})
21457 @end example
21458
21459 @c EN
21460 You can pass any object to @var{condition}; its interpretation
21461 solely depends on the exception handler. If you know the code
21462 raises an integer as a condition, you can catch it by @code{guard}
21463 as this:
21464 @c JP
21465 @var{condition}にはどんなオブジェクトでも渡すことができます。
21466 それをどのように解釈するかはひとえに例外ハンドラにかかってます。
21467 もし、コンディションとして整数があがってくるというのが判っていれば、
21468 @code{guard} で以下のように捕捉することができます。
21469 @c COMMON
21470
21471 @example
21472 (guard (exc [(integer? exc) 'raised])
21473 (raise 3))
21474 @end example
21475
21476 @c EN
21477 However, as a convention, it is preferable to use an instance
21478 of @code{<condition>} or one of its subclasses. A macro @code{condition}
21479 can be used to create a condition object. The following examples
21480 show how to create a condition with some slot values and then raise it.
21481 @c JP
21482 とはいうものの、@code{<condition>} あるいはそのサブクラスのインスタンスを
21483 使うのが好ましいというのが通例です。@code{condition} マクロはコンディション
21484 オブジェクトを作成するのに使えます。以下の例は、いくつかのスロット値をもち
21485 それらを発生させるコンディションの作りかたを示したものです。
21486 @c COMMON
21487
21488 @example
21489 ;; create and raise an error condition
21490 (raise (condition
21491 (<error> (message "An error occurred."))))
21492
21493 ;; create and raise a system error condition
21494 (raise (condition
21495 (<system-error> (message "A system error occurred.")
21496 (errno EINTR))))
21497 @end example
21498
21499 @c EN
21500 See @ref{Conditions} for the details of @code{condition} macro
21501 and what kind of condition classes are provided.
21502 @c JP
21503 @code{condition} マクロおよび、どのようなコンディションクラスが用意
21504 されているかの詳細については @ref{Conditions} を参照してください。
21505 @c COMMON
21506
21507 @c EN
21508 The most common type of condition is an error condition, so
21509 a convenience procedure @code{error} and @code{errorf} are
21510 provided. They create an error condition with a message and
21511 raise it.
21512 @c JP
21513 最も一般的なコンディションのタイプはエラーコンディションなので、
21514 @code{error} および @code{errorf} という便利な手続きが
21515 用意されています。これらはメッセージ付きのエラーコンディションを
21516 生成し、それを発生させます。
21517 @c COMMON
21518
21519 @example
21520 ;; `error' concatenates the arguments into a message.
21521 (unless (integer? obj)
21522 (error "Integer expected, but got:" obj))
21523
21524 ;; `errorf' uses format to create a message.
21525 (unless (equal? x y)
21526 (errorf "~s and ~s don't match" x y))
21527 @end example
21528
21529 @c EN
21530 Unlike the exception throwing constructs in some languages,
21531 such as @code{throw} of C++/Java, which abandons its continuation,
21532 Scheme's @code{raise} may return to its caller. If you don't
21533 want @code{raise} to return, a rule of thumb is always to pass
21534 one of error conditions to it; then Gauche guarantees @code{raise}
21535 wont return. See the description of @code{raise} in
21536 @ref{Signaling exceptions} for more details.
21537 @c JP
21538 いくつかの言語での例外を投げる機構、たとえば、
21539 C++やJavaの @code{throw} はその継続を破棄します。これとは違い
21540 Schemeの @code{raise} はその呼び出し元へ戻ることができます。もし、
21541 @code{raise} で元へもどらないで欲しいのなら、簡便な方法としては、
21542 常にエラーコンディションの一つをわたるようにするというのがあります。
21543 そうすると Gauche では @code{raise} は戻らないことを保証します。
21544 @code{raise}の詳細については、@ref{Signaling exceptions}を参照してください。
21545 @c COMMON
21546
21547 @c EN
21548 Note: R7RS adopted slightly different semantics; it splits
21549 @code{raise} and @code{raise-continuable}, the former is for
21550 noncontinuable exception (if the exception handler returns,
21551 it raises another error), and the latter is for continuable
21552 exception. When you're in R7RS environment, R7RS-compatible
21553 @code{raise} will be used instead of this @code{raise}.
21554 @c JP
21555 註: R7RSでは少し違ったセマンティクスを採用しています。
21556 @code{raise}は継続不可能な例外を投げるものとして(もし例外ハンドラから
21557 制御が戻ってきたら、別のエラーを報告します)、
21558 別に継続可能な例外を投げる@code{raise-continuable}という手続きを
21559 設けました。R7RS環境にいるときは、本項の@code{raise}ではなく
21560 R7RS互換の@code{raise}が見えるようになっています。
21561 @c COMMON
21562
21563 @c EN
21564 @subsubheading Defining your own condition
21565 @c JP
21566 @subsubheading 独自のコンディションを定義する
21567 @c COMMON
21568
21569 @c EN
21570 You can also define your own condition classes
21571 to pass application-specific information from the point of
21572 raising exception to the handlers.
21573 @c JP
21574 独自のコンディションクラスを定義することが可能で、そうすることで、
21575 アプリケーション固有の情報を例外が発生した点からハンドラへ渡すことが
21576 できます。
21577 @c COMMON
21578
21579 @c EN
21580 To fit to Gauche's framework (SRFI-35), it is desirable that
21581 the new condition class inherits a built-in @code{<condition>} class
21582 or one of its descendants, and also is an instance of a metaclass
21583 @code{<condition-meta>}.
21584 @c JP
21585 Gauche のフレームワーク(SRFI-35)に適合させるためには、新しく定義する
21586 コンディションクラスは組み込みの @code{<condition>} クラスあるいは
21587 その子孫を継承し、また、メタクラス @code{<condition-meta>}
21588 のインスタンスであることが望まれます。
21589 @c COMMON
21590
21591 @c EN
21592 One way of ensuring the above convention as well as increasing
21593 portability is to use @code{define-condition-type} macro, defined
21594 in @code{srfi.35}.
21595 @c JP
21596 可搬性を増すと同時に上の慣例を確実にするための方法のひとつは、
21597 @code{define-condition-type}マクロを使うことです。これは、
21598 @code{srfi.35}で定義されています。
21599 @c COMMON
21600
21601 @example
21602 (define-condition-type <myapp-error> <error>
21603 myapp-error?
21604 (debug-info myapp-error-debug-info)
21605 (reason myapp-error-reason))
21606 @end example
21607
21608 @c EN
21609 This defines a condition type (which is a class in Gauche)
21610 @code{<myapp-error>}, with a predicate @code{myapp-error?}
21611 and slots with accessors. Then you can use the new
21612 condition type like the following code:
21613 @c JP
21614 これは、(Gauche内のクラス)@code{<myapp-err>}を定義するもので、
21615 このクラスには@code{myapp-error?}という述語とアクセサのあるスロット
21616 があります。こうすれば、以下のようなコードで新しいコンディション
21617 型が使えます。
21618 @c COMMON
21619
21620 @example
21621 (guard (exc
21622 [(myapp-error? exc)
21623 (let ([debug-info (myapp-error-debug-info exc)]
21624 [reason (myapp-error-reason exc)])
21625 ... handle myapp-error ...)])
21626 ...
21627 ...
21628 (if (something-went-wrong)
21629 (raise (condition
21630 (<myapp-error> (debug-info "during processing xxx")
21631 (reason "something went wrong")))))
21632 ...
21633 ...
21634 )
21635 @end example
21636
21637 @c EN
21638 If you don't mind to lose srfi compatibility, you can use
21639 Gauche's extended @code{error} and @code{errorf} procedures to write
21640 more concise code to raise a condition of subtype of @code{<error>}:
21641 @c JP
21642 SRFIとの互換性が重要でないなら、Gaucheの拡張された@code{error}手続きを
21643 使うと@code{<error>}のサブタイプであるコンディションを投げるコードを
21644 より簡潔に書くことができます。
21645 @c COMMON
21646
21647 @example
21648 (if (something-went-wrong)
21649 (error <myapp-error>
21650 :debug-info "during processing xxx"
21651 :reason "something went wrong"))
21652 @end example
21653
21654
21655 @c EN
21656 See the description of @code{define-condition-type} macro
21657 for how the condition type is implemented in Gauche's object system.
21658 @c JP
21659 Gauche のオブジェクトシステムでコンディション型がどのように実装されているかは
21660 @code{define-condition-type}マクロの解説を参照してください。
21661 @c COMMON
21662
21663 @node Signaling exceptions, Handling exceptions, Exception handling overview, Exceptions
21664 @subsection Signaling exceptions
21665 @c NODE 例外の通知
21666
21667 @c EN
21668 @subsubheading Signaling errors
21669 @c JP
21670 @subsubheading エラーの通知
21671 @c COMMON
21672
21673 @c EN
21674 The most common case of exceptions is an error.
21675 Two convenience functions to signal an error condition
21676 in simple cases are provided.
21677 To signal a compound condition, you can use @code{raise} as explained below.
21678 @c JP
21679 最も良くある例外ケースはエラーです。単純なエラーを通知するために、
21680 ふたつの簡単な関数が用意されています。
21681 複合コンディションを通知する必要がある場合は
21682 下で説明する@code{raise}手続きを使って下さい。
21683 @c COMMON
21684
21685 @defun error string arg @dots{}
21686 @defunx error condition-type keyword-arg @dots{} string arg @dots{}
21687 [R7RS+ base][SRFI-23+]
21688 @c EN
21689 Signals an error. The first form creates an @code{<error>}
21690 condition, with a message consists of @var{string} and @var{arg} @dots{},
21691 and raises it. It is compatible to R7RS and SRFI-23's @code{error} behavior.
21692 @c JP
21693 エラーを通知します。最初の形式は、
21694 @var{string}と@var{arg} @dots{}からなるメッセージを持つ
21695 @code{<error>}コンディションを作成それを@code{raise}します。
21696 この形式はR7RS及びSRFI-23の@code{error}と互換です。
21697 @c COMMON
21698
21699 @example
21700 gosh> (define (check-integer x)
21701 (unless (integer? x)
21702 (error "Integer required, but got:" x)))
21703 check-integer
21704 gosh> (check-integer "a")
21705 *** ERROR: Integer required, but got: "a"
21706 Stack Trace:
21707 _______________________________________
21708 @end example
21709
21710 @c EN
21711 The second form can be used to raise an error other than the
21712 @code{<error>} condition. @var{condition-type} must be
21713 a condition type (see @ref{Conditions} for more explanation of
21714 condition types). It may be followed by keyword-value list
21715 to initialize the condition slots, and then optionally followed by
21716 a string and other objects that becomes an error message.
21717 @c JP
21718 2番目の形式は@code{<error>}以外のエラーコンディションを通知したいときに
21719 使います。@var{condition-type}はコンディションタイプ
21720 でなければなりません (コンディションタイプについては@ref{Conditions}を
21721 参照して下さい)。その後に、キーワードと値のリストを与えることで
21722 コンディションのスロットを初期化することができます。また、その後に
21723 メッセージを構成する文字列と他のオブジェクトのリストを与えることができます。
21724 @c COMMON
21725
21726 @example
21727 (define-condition-type <my-error> <error> #f
21728 (reason)
21729 (priority))
21730
21731 ...
21732 (unless (memq operation *supported-operations*)
21733 (error <my-error>
21734 :reason 'not-supported :priority 'urgent
21735 "Operation not supported:" operation))
21736 ...
21737 @end example
21738 @end defun
21739
21740 @defun errorf fmt-string arg @dots{}
21741 @defunx errorf condition-type keyword-arg @dots{} fmt-string arg @dots{}
21742 @c EN
21743 Similar to @code{error}, but the error message is formatted by
21744 @code{format}, i.e. the first form is equivalent to:
21745 @c JP
21746 @code{error}に似ていますが、エラーメッセージは@code{format}によりフォーマット
21747 されます。すなわち、最初のフォームは以下と等価です。
21748 @c COMMON
21749 @example
21750 (define (errorf fmt . args)
21751 (error (apply format #f fmt args)))
21752 @end example
21753
21754 @c EN
21755 The second form can be used to raise an error other than an
21756 @code{<error>} condition. Meaning of @var{condition-type} and
21757 @var{keyword-arg}s are the same as @code{error}.
21758 @c JP
21759 2番目の形式は@code{<error>}以外のエラーコンディションを通知するのに
21760 使えます。@var{condition-type}, @var{keyword-arg}の意味については
21761 @code{error}と同じです。
21762 @c COMMON
21763 @end defun
21764
21765 @c EN
21766 @subsubheading Signaling generic conditions
21767 @c JP
21768 @subsubheading 一般的な条件の通知
21769 @c COMMON
21770
21771 @defun raise condition
21772 [SRFI-18][R7RS base]
21773 @c EN
21774 This is the base mechanism of signaling exceptions.
21775
21776 The procedure invokes the current exception handler.
21777 The argument @var{condition} represents the nature of the exception,
21778 and passed to the exception handler.
21779 Gauche's built-in and library functions always use
21780 an instance of @code{<condition>} or one of its subclasses as @var{condition},
21781 but you can pass any Scheme object to @code{raise}. The interpretation
21782 of @var{condition} is up to the exception handler.
21783
21784 @emph{Note:} Unlike some of the mainstream languages in which
21785 "throwing" an exception never returns, you can set up an exception
21786 handler in the way that @code{raise} may return. The details
21787 are explained in @ref{Handling exceptions}.
21788
21789 If you don't want @code{raise} to return, the best way is to
21790 pass a condition which is an instance of @code{<serious-condition>}
21791 or one of its subclasses. Gauche's internal mechanism
21792 guarantees raising such an exception won't return.
21793 See @ref{Conditions} for the hierarchy of built-in conditions.
21794
21795 R7RS adopted slightly different semantics regarding returning from
21796 @code{raise}; in R7RS, @code{raise} never returns---if the exception
21797 handler returns, another exception is raised.
21798 R7RS has @code{raise-continuable} to explicitly allow returning from
21799 the exception handler. For portable programs, always
21800 pass @code{<serious-condition>} or its subclasses to @code{raise}.
21801 @c JP
21802 これは、例外事態を通知する基本となるメカニズムです。
21803
21804 この手続きは現在の例外ハンドラを呼び出します。引数@var{condition}は
21805 例外の性質を表現するのに使われ、例外ハンドラに渡されます。
21806 Gaucheの組み込み手続きやライブラリ手続きは常に、@code{<condition>}クラス
21807 もしくはそのサブクラスのインスタンスを@var{condition}として用いますが、
21808 ユーザは任意のオブジェクトを@code{raise}に渡すこともできます。
21809 渡された@var{condition}の解釈は例外ハンドラに任されます。
21810
21811 @emph{注意事項:} いくつかの主流の言語では、例外を「投げる」と制御はそこに
21812 戻りません。Gaucheでは@code{raise}から戻って来れるように
21813 セットアップすることが可能です。詳細は@ref{Handling exceptions}を
21814 参照してください。
21815
21816 @code{raise}から戻って来ることが無いようにしたい場合は、
21817 @code{<serious-condition>}やそのサブクラスのインスタンスを@var{condition}
21818 として@code{raise}に渡すのが確実です。
21819 組み込みコンディションのクラス階層については@ref{Conditions}を参照して下さい。
21820
21821 R7RSではやや異なるセマンティクスを採用しています。R7RSの@code{raise}は
21822 決して戻りません---もしハンドラが戻ってきた場合は、別の例外が投げられます。
21823 R7RSは@code{raise-continuable}という別の手続きで、ハンドラから
21824 戻っても良いことを明示します。ポータブルなプログラムでは、
21825 @code{raise}には常に@code{<serious-condition>}かそのサブクラスを
21826 渡すようにするのが良いでしょう。
21827 @c COMMON
21828 @end defun
21829
21830
21831 @node Handling exceptions, Conditions, Signaling exceptions, Exceptions
21832 @subsection Handling exceptions
21833 @c NODE 例外の処理
21834
21835 @menu
21836 * High-level exception handling mechanism::
21837 * Behavior of unhandled exception::
21838 * Low-level exception handling mechanism::
21839 @end menu
21840
21841 @node High-level exception handling mechanism, Behavior of unhandled exception, Handling exceptions, Handling exceptions
21842 @subsubsection High-level exception handling mechanism
21843 @c NODE 上位レベルの例外処理機構
21844
21845 @defmac guard (var clause @dots{}) body @dots{}
21846 [R7RS base]
21847 @c EN
21848 This is @emph{the} high-level form to handle errors in Gauche.
21849 @c JP
21850 これはGaucheでのエラー処理の高水準フォームです。
21851 @c COMMON
21852
21853 @c EN
21854 @var{var} is a symbol, and @var{clause}s are the same form as
21855 @code{cond}'s clauses, i.e. each clause can be either one of
21856 the following forms:
21857 @c JP
21858 @var{var} はシンボルで @var{clause} は @code{cond} 節と同じ形式です。
21859 つまり、各節は以下の形式のどれかひとつです。
21860 @c COMMON
21861 @enumerate
21862 @item
21863 @code{(@var{test} @var{expr} @dots{})}
21864 @item
21865 @code{(@var{test} => @var{proc})}
21866 @end enumerate
21867
21868 @c EN
21869 The last @var{clause} may be @code{(else @var{expr} @dots{})}.
21870 @c JP
21871 最後の@var{clause}は@code{(else @var{expr} @dots{})}という形式も許されます。
21872 @c COMMON
21873
21874 @c EN
21875 This form evaluates @var{body} @dots{} and returns the value(s) of
21876 the last @var{body} expression in normal case.
21877 If an exception is raised during the evaluation of body expressions,
21878 the raised exception is bound to a variable @var{var}, then
21879 evaluates @var{test} expression of each clause. If one of @var{test}
21880 expressions returns true value, then the corresponding @var{expr}s
21881 are evaluated if the clause is the first form above, or an @var{proc}
21882 is evaluated and the result of @var{test} is passed to the procedure
21883 @var{proc} if the clause is the second form.
21884 @c JP
21885 このフォームは通常の場合には @var{body} @dots{} を評価し最後の
21886 @var{body} の式の値を返します。本体の式を評価している最中に例外が
21887 発生した場合、発生した例外を変数 @var{var} に束縛し、その後
21888 各節の @var{test} 式を評価します。もし、@var{test} 式のひとつが
21889 真値を返したとき、その節が上述の最初の形式であれば、対応する
21890 @var{expr} が評価されます。あるいは、節が二番目の形式であれば、
21891 手続き@var{proc}に@var{test}の結果が渡されます。
21892 @c COMMON
21893
21894 @c EN
21895 When the @var{test}(s) and @var{expr}(s) in the clauses are evaluated,
21896 the exception handler that is in effect of the caller of @code{guard} are
21897 installed; that is, if an exception is raised again within @var{clause}s,
21898 it is handled by the @emph{outer} exception handler or @code{guard} form.
21899 @c JP
21900 指定された節の @var{test} および @var{expr} が評価されるとき、
21901 @code{guard}を呼び出した時点での例外ハンドラが設定されます。つまり、
21902 @var{clause} 内部で再び例外が発生した場合、その例外は、@emph{外側の}
21903 例外ハンドラまたは @code{guard} フォームで処理されます。
21904 @c COMMON
21905
21906 @c EN
21907 If no @var{test} returns true value and the last @code{clause} is
21908 @code{else} clause, then the associated @var{expr}s are evaluated.
21909 If no @var{test} returns true value and there's no @code{else} clause,
21910 the raised exception is re-raised, to be handled by the outer exception
21911 handler.
21912 @c JP
21913 もし、どの @var{test} も真値を返さず、最後の @code{clause} が
21914 @code{else} 節であれば、それに結びつけられた @var{expr} が評価されます。
21915 もし、どの @var{test} も真値を返さず、@code{else} 節がなければ、再び
21916 例外が発生し、外側の例外ハンドラで処理されます。
21917 @c COMMON
21918
21919 @c EN
21920 When the exception is handled by one of @code{clause}s, @code{guard}
21921 returns the value(s) of the last @var{expr} in the handling clause.
21922 @c JP
21923 例外が @code{clause} のどれかで処理された時には、@code{guard} は
21924 それを処理した節の最後の @var{expr} の値を返します。
21925 @c COMMON
21926
21927 @c EN
21928 The @var{clause}s are evaluated in the same dynamic environment as
21929 the @code{guard} form, i.e. any @code{dynamic-wind}s inside @code{body}
21930 are unwound before evaluation of the @var{clause}s. It is different
21931 from the lower level forms
21932 @code{with-error-handler} and @code{with-exception-handler}, whose
21933 handler is evaluated before the dynamic environment are unwound.
21934 @c JP
21935 @var{clause}は@code{guard}と同じ動的環境で評価されます。すなわち、
21936 @code{body}中の@code{dynamic-wind}は@var{clause}の評価の前に
21937 巻戻されます。これは低レベル関数の@code{with-error-handler}や
21938 @code{with-exception-handler}とは異なることに注意してください。
21939 これら低レベル関数では例外ハンドラが呼ばれてから動的環境が巻戻されます。
21940 @c COMMON
21941
21942 @example
21943 (let ([z '()])
21944 (guard (e [else (push! z 'caught)])
21945 (dynamic-wind (lambda () (push! z 'pre))
21946 (lambda () (error "foo"))
21947 (lambda () (push! z 'post))))
21948 (reverse z))
21949 @result{} (pre post caught)
21950
21951 (guard (e [else (print 'OUTER) #f])
21952 (with-output-to-string
21953 (lambda ()
21954 (print 'INNER)
21955 (error "foo"))))
21956 @c EN
21957 @result{} prints OUTER to the current output port of guard,
21958 not to the string port.
21959 @c JP
21960 @result{} OUTERを文字列ポートではなくguard実行時の
21961 current-output-portに出力。
21962 @c COMMON
21963 @end example
21964 @end defmac
21965
21966 @defmac unwind-protect expr cleanup @dots{}
21967 @c EN
21968 Executes @var{expr}, then executes @var{cleanup}s, and
21969 returns the result(s) of @var{expr}. If an uncontinuable exception is raised
21970 within @var{expr}, @var{cleanup}s are executed before the
21971 exception escapes from the @code{unwind-protect} form.
21972 For example, the following code calls @code{start-motor},
21973 @code{drill-a-hole}, and @code{stop-motor} in order if
21974 everything goes ok, and if anything goes wrong in @code{start-motor}
21975 or @code{drill-a-hole}, @code{stop-motor} is still called
21976 before the exception escapes @code{unwind-protect}.
21977 @c JP
21978 @var{expr}を実行してから@var{cleanup} @dots{}を実行し、@var{expr}の結果を返します。
21979 @var{expr}内で継続不可能な例外が挙がった場合、その例外が@code{unwind-protect}フォー
21980 ムを抜ける前に、@var{cleanup} @dots{}が実行されます。たとえば、以下のコードで
21981 はなにも問題が起きなければ、@code{start-motor}、@code{drill-a-hole}、
21982 @code{stop-motor}が、この順で呼ばれます。何か不具合が
21983 @code{start-motor}あるいは@code{drill-a-hole}で起った場合でも、例外が
21984 @code{unwind-protect}を抜ける前に@code{stop-motor}が呼ばれます。
21985 @c COMMON
21986
21987 @example
21988 (unwind-protect
21989 (begin (start-motor)
21990 (drill-a-hole))
21991 (stop-motor))
21992 @end example
21993
21994 @c EN
21995 The @var{cleanup} forms are evaluated in the same dynamic environment
21996 as @code{unwind-protect}.
21997 If an exception is thrown within @var{cleanup}, it will be
21998 handled outside of the @code{unwind-protect} form.
21999 @c JP
22000 @var{cleanup}フォームは@code{unwind-protect}と同じ動的環境で評価されま
22001 す。例外が@var{cleanup}内で投げられた場合その例外は、
22002 @code{unwind-protect}フォームの外側で処理されることになります。
22003 @c COMMON
22004
22005 @c EN
22006 Although this form looks similar to @code{dynamic-wind}, they
22007 work at different layers and should not be confused.
22008 @code{dynamic-wind} is the bottom-level
22009 building block and used to manage current exception handlers,
22010 current i/o ports, parameters, etc.
22011 @code{dynamic-wind}'s @var{before} and @var{after} thunks are
22012 called whenever any of those control flow transition occurs.
22013 On the other hand, @code{unwind-protect} only cares about
22014 the Gauche's exception system. @code{unwind-protect}'s @var{cleanup}
22015 is called only when @var{expr} exits normally or
22016 throws Gauche's exception.
22017 In the above example, if control escapes from @code{drill-a-hole}
22018 by calling a continuation captured outside of @code{unwind-protect},
22019 @var{cleanup} is not called; because the control may return to
22020 @code{drill-a-hole} again. It can happen if user-level thread
22021 system is implemented by @code{call/cc}, for example.
22022 @c JP
22023 このフォームは@code{dynamic-wind}と似ていますが、この2つは動作するレイ
22024 ヤが違いますので混同しないようにしてください。
22025 @code{dynamic-wind}は最下位レイヤのもので、現在の例外ハンドラ、現在の入出力
22026 ポート、パラメータなどを管理するのに用います。
22027 @code{dynamic-wind}の@var{before}および@var{after}のサンクは
22028 対応する制御フローの遷移が起きたときに必ず呼ばれます。
22029 一方、@code{unwind-protect}はGaucheの例外システムの面倒しか見ません。
22030 @code{unwind-protect}の@var{cleanup}は@var{expr}が正常終了するか
22031 Gaucheの例外を投げたときにのみ呼びだされます。上述の例で、@code{unwind-protect}の外側で
22032 補足された継続が呼ばれ、制御が@code{drill-a-hole}を抜けると、
22033 @var{cleanup}は呼ばれません。制御が再び@code{drill-a-hole}に戻る可能性
22034 があるからです。たとえば、ユーザレベルのスレッドシステムが
22035 @code{call/cc}で実装されているような場合にこのようなことが起こる可能性
22036 があります。
22037 @c COMMON
22038
22039 @c EN
22040 You can go back to the body @var{expr}
22041 from outside of @code{unwind-protect} by invoking continuations
22042 captured within @var{expr}.
22043
22044 However, keep in mind that once @var{cleanup} are executed,
22045 some resources might not be available in @var{expr}.
22046 We still allow it since the reexecuted part of @var{expr} may not
22047 depend on the resources cleaned up with @var{cleanup}.
22048
22049 Even if @var{expr} returns (normally or abnormally),
22050 @var{cleanup} only executed once, in the first time.
22051 @c JP
22052 @var{expr}内で捕捉された継続を@code{unwind-protect}の外側で起動することで、
22053 @var{expr}内に再び戻ることは可能です。
22054
22055 ただ、ひとたび@var{cleanup}が実行されてしまったら、それによってクリーンアップ
22056 されたリソースは@var{expr}内から使えなくなっているという可能性に留意してください。
22057 そういったリソースに依存しない計算なら再実行できるので、再起動自体は禁止されていません。
22058
22059 @var{expr}から複数回戻った場合(通常の評価でもエラーでも)、@var{cleanup}が
22060 実行されるのは最初の時のみです。
22061 @c COMMON
22062
22063 @c EN
22064 The name of this form is taken from Common Lisp. Some Scheme
22065 systems have similar macros in different names, such as
22066 @code{try-finally}.
22067 @c JP
22068 このフォームの名前はCommon Lispから取りました。同様のマクロに
22069 @code{try-finally}というような別の名前を使っているSchemeの処理系もあります。
22070 @c COMMON
22071 @end defmac
22072
22073
22074 @defun with-error-handler handler thunk
22075 @c EN
22076 Makes @var{handler} the active error handler and executes @var{thunk}.
22077 If @var{thunk} returns normally, the result(s) will be returned.
22078 If an error is signaled during execution of @var{thunk},
22079 @var{handler} is called with one argument, an exception object
22080 representing the error, with the continuation of @code{with-error-handler}.
22081 That is, @code{with-error-handler} returns whatever value(s) @var{handler}
22082 returns.
22083 @c JP
22084 @var{handler}をアクティブなエラーハンドラにし、@var{thunk}を実行します。
22085 @var{thunk}が正常に戻ったら、その結果が返されます。
22086 @var{thunk}の実行中にエラーが通知されたら、エラーを表す例外オブジェクトを
22087 1引数とする@var{handler}が、@code{with-error-handler}の継続とともに呼ばれます。
22088 すなわち、@code{with-error-handler}は、@var{handler}が返す値を返します。
22089 @c COMMON
22090
22091 @c EN
22092 If @var{handler} signals an error, it will be handled by the
22093 handler installed when @code{with-error-handler} called.
22094 @c JP
22095 @var{handler}がエラーを通知したら、それは@code{with-error-handler}が
22096 呼ばれたときにインストールされていたハンドラにより処理されます。
22097 @c COMMON
22098
22099 @c EN
22100 The dynamic environment where @var{handler} is executed is
22101 the same as the error occurs. If @code{dynamic-wind} is used
22102 in @var{thunk}, its @var{after} method is called after @var{handler}
22103 has returned, and before @code{with-error-handler} returns.
22104 @c JP
22105 @var{handler}が実行される場合の動的な環境は、エラーが起きたときのそれと
22106 同じです。@var{thunk}内で@code{dynamic-wind}が使われていたら、
22107 その@var{after}メソッドは@var{handler}が戻った後、かつ@code{with-error-handler}が
22108 戻る前に呼ばれます。
22109 @c COMMON
22110
22111 @c EN
22112 Note: Using this procedure directly is @emph{no longer recommended}, since
22113 @code{guard} is more safe and portable. We'll keep this for
22114 a while for the backward compatibility, but we recommend to rewrite
22115 code to use @code{guard} instead of this.
22116 The common idiom of "cleanup on error"
22117 code:
22118 @c JP
22119 註: この手続きを直接使うことはもはや@emph{推奨されません}。@code{guard}の方が
22120 より安全でポータブルだからです。互換性を保つためまだしばらくは
22121 この手続きを残しますが、この手続きを使っているコードを@code{guard}によって
22122 書き直すことを推奨します。「エラー時に後始末をする」というよくある次のような処理は:
22123 @c COMMON
22124 @example
22125 (with-error-handler (lambda (e) (cleanup) (raise e))
22126 (lambda () body @dots{}))
22127 @end example
22128 @c EN
22129 should be written like this:
22130 @c JP
22131 次のように書き直すことができます。
22132 @c COMMON
22133 @example
22134 (guard (e [else (cleanup) (raise e)])
22135 body @dots{})
22136 @end example
22137 @end defun
22138
22139 @node Behavior of unhandled exception, Low-level exception handling mechanism, High-level exception handling mechanism, Handling exceptions
22140 @subsubsection Behavior of unhandled exception
22141 @c NODE 処理されなかった例外のふるまい
22142
22143 @c EN
22144 If an exception is raised where no program-defined exception handler is
22145 installed, the following action is taken.
22146 @c JP
22147 プログラムで定義した例外ハンドラを設定していないところで例外が発生した
22148 場合以下のようなことが起ります。
22149 @c COMMON
22150
22151 @enumerate
22152 @item
22153 @c EN
22154 If an unhandled exception occurs within a thread other than the primordial
22155 one, it terminates the thread, and the thrown condition
22156 is wrapped by @code{<uncaught-exception>} condition and stored in the
22157 thread object. If other thread calls @code{thread-join!} to retrieve
22158 result, the the @code{<uncaught-exception>} is thrown in that thread.
22159 Note that no messages are displayed when the original uncaught exception
22160 is thrown. @xref{Thread programming tips}, for the details.
22161 @c JP
22162 もしメインスレッド以外のスレッドで捕捉されない例外が起きた場合、そのスレッドは終了し、
22163 投げられた例外は@code{<uncaught-exception>}でラップされて
22164 スレッドオブジェクトに保存されます。他のスレッドが@code{thread-join!}で
22165 スレッドの結果を取り出そうとした時に、その@code{<uncaught-exception>}が投げられます。
22166 元の捕捉されない例外が起きた時点では何もメッセージなどが表示されないことに注意してください。
22167 詳しくは@ref{Thread programming tips}を参照。
22168 @c COMMON
22169 @item
22170 @c EN
22171 Otherwise,
22172 if the program is running interactively (in repl), the information
22173 of the thrown exception and stack trace are displayed, and
22174 the program returns to the toplevel prompt.
22175 @c JP
22176 そうでなく、プログラムが対話的に走っている場合(REPL)、投げられた例外の情報とスタッ
22177 クトレースが表示され、プログラムはトップレベルのプロンプトに戻ります。
22178 @c COMMON
22179 @item
22180 @c EN
22181 If the program is running non-interactively, the information
22182 of the thrown exception and stack trace are displayed, then
22183 the program exits with an exit status @code{EX_SOFTWARE} (70).
22184 @c JP
22185 そうでなく、プログラムが対話的に走っているのではない場合は、投げられた例外の情報と
22186 スタックトレースが表示された後、プログラムは終了コード
22187 @code{EX_SOFTWARE} (70)で終了します。
22188 @c COMMON
22189 @end enumerate
22190
22191 @c EN
22192 The default error message and stack trace in the above case 2 and case 3
22193 is printed by @code{report-error} procedure. You can use it
22194 in your error handler if you need the same information.
22195 @c JP
22196 上の2と3でのエラーメッセージとスタックトレースは、@code{report-error}手続きによって
22197 出力されています。自分のエラーハンドラ内で同じ情報を出力したければ
22198 これを使うことができます。
22199 @c COMMON
22200
22201 @defun report-error exn :optional sink
22202 @c EN
22203 Prints type and message of a thrown condition object @var{exn},
22204 then print the current stack trace. This is the procedure
22205 the system calls when you see an error reported on REPL.
22206
22207 Since you can @code{raise} any object, @var{exn} can be any
22208 object; it's not needed to be an instance of @code{<condition>}.
22209 A suitable message is chosen by @code{report-error}.
22210
22211 You can specify where the output goes by the optional @var{sink}
22212 argument: If it is an output port, the output goes there; you can
22213 also pass @code{#t} for the current output port and @code{#f} for
22214 the output string port, just like @code{format}. That is, when
22215 you pass @code{#f}, the message goes to a temporary output string
22216 port, and gathered string is returned. For all the other cases,
22217 an undefined value is returned. If @var{sink} is omitted or
22218 any other object listed above, the current error port is used.
22219
22220 Internally, this procedure calls @code{print-default-error-heading}
22221 and @code{print-additional-error-heading}
22222 to print the info about @var{exn}, then prints the stack trace.
22223 You can call those procedures separately if you don't want
22224 the stack trace.
22225
22226 Note: As of 0.9.5, this procedure prints stack trace of
22227 the context where @code{report-error} is called, rather than
22228 the context where @var{exn} is thrown. It doesn't matter much
22229 as far as you call @code{report-error} directly inside the
22230 error handler, but in general what
22231 you want to print is the latter, and we have a plan to
22232 attach stack trace info to @code{<condition>} object in future.
22233 @c JP
22234 投げられたコンディションオブジェクト@var{exn}の型とメッセージを表示し、
22235 それからスタックトレースを出力します。REPLでエラーが報告される時の
22236 表示を出しているのがこの手続きです。
22237
22238 @code{raise}は任意のオブジェクトをコンディションとして投げることが出来るので、
22239 @var{exn}も@code{<condition>}オブジェクトの
22240 インスタンスである必要はなく、どんな型でも許されます。
22241 @code{report-error}は適切なメッセージを選んで表示します。
22242
22243 出力の行き先は省略可能引数@var{sink}で指定できます。出力ポートを渡せば
22244 そこに出力されます。また、@code{format}と同様に、@code{#t}を渡すことで
22245 現在の出力ポートに、@code{#f}を渡すことで一時的な文字列ポートに出力できます。
22246 @code{#f}を渡した場合、一時的な文字列ポートに出力された文字列が
22247 返り値となります。その他の場合は未定義値が返されます。
22248 @var{sink}が省略されるか、上記以外の値であった場合は
22249 現在のエラーポートが使われます。
22250
22251 内部的に、この手続きは@var{exn}の情報を表示するために
22252 @code{print-default-error-heading}および
22253 @code{print-additional-error-heading}を呼び、その後スタックトレースを表示します。
22254 スタックトレースが不要な場合、これらの手続きを直接呼ぶこともできます。
22255
22256
22257 註: 0.9.5の時点で、この手続きは@var{exn}が投げられたコンテキストでの
22258 スタックトレースではなく、@code{report-error}自身が呼ばれたコンテキストでの
22259 スタックトレースを表示します。@code{report-error}をエラーハンドラから
22260 直接呼んでいる限りにおいてはあまり違いは出ませんが、一般的に望ましいのは
22261 前者なので、将来的には@code{<condition>}オブジェクトにスタックトレース情報を
22262 つける予定があります。
22263 @c COMMON
22264 @end defun
22265
22266 @defun print-default-error-heading exn out
22267 @c EN
22268 Prints the first line of the default error report regarding
22269 the thrown condition @var{exn} to an output port @var{out}.
22270 @c JP
22271 投げられたコンディション@var{exn}について、デフォルトのエラーレポートの
22272 1行目を出力ポート@var{out}に書き出します。
22273 @c COMMON
22274
22275 @c EN
22276 If @var{exn} is a @code{<condition>}, the message
22277 consists of the condition class name (without brackets, and capitalized),
22278 followed by the message of the condition:
22279 @c JP
22280 @var{exn}が@code{<condition>}なら、
22281 コンディションクラス名(からブラケットを取り除き、大文字化したもの)と、
22282 コンディションメッセージが出力されます:
22283 @c COMMON
22284
22285 @example
22286 *** READ-ERROR: Read error at "foo":line 1: EOF inside a list (starting from line 1)
22287 @end example
22288
22289 @c EN
22290 If @var{exn} is not a @code{<condition>}, it assumes that the exception is
22291 intended to be caught but somehow escaped, so it prints something
22292 like this:
22293 @c JP
22294 @var{exn}が@code{<condition>}でない場合は、
22295 本来補足されるべきであったコンディションがすり抜けたとみなし、
22296 例えば次のようなメッセージが出力されます:
22297 @c COMMON
22298
22299 @example
22300 *** ERROR: unhandled exception: foo
22301 @end example
22302
22303 @c EN
22304 This is called by @code{report-error}, but you can use this procedure
22305 separately.
22306 @c JP
22307 この手続きは@code{report-error}が使っていますが、
22308 この手続きだけを直接呼び出すことも可能です。
22309 @c COMMON
22310 @end defun
22311
22312 @defun print-additional-error-heading exn out
22313 @c EN
22314 Prints the additional information of the thrown condition
22315 @var{exn} to an output port @var{out}.
22316 @c JP
22317 投げられたコンディション@var{exn}について、追加の情報を出力ポート@var{out}に書き出します。
22318 @c COMMON
22319
22320 @c EN
22321 If @var{exn} is not a @code{<condition>}, no information is printed.
22322 @c JP
22323 @var{exn}が@code{<condition>}でなければ、何も出力されません。
22324 @c COMMON
22325
22326 @c EN
22327 If @var{exn} is a compound condition, it is decomposed into
22328 individual conditions.
22329 @c JP
22330 @var{exn}が複合コンディションの場合は、まず個々のコンディションに分解されます。
22331 @c COMMON
22332
22333 @c EN
22334 Then, for each condition that does not inherit @code{<mixin-condition>},
22335 @code{report-additional-condition} method is invoked on it.
22336 Afterwards,
22337 for each of the remaining conditions (those inherit @code{<mixin-condition>}),
22338 @code{report-additional-condition} method is invoked on it.
22339 @c JP
22340 次に、各コンディションのうち@code{<mixin-condition>}を継承していない
22341 コンディションについて@code{report-additional-condition}メソッドが呼ばれ、
22342 最後に@code{<mixin-condition>}を継承しているコンディションについて
22343 @code{report-additional-condition}メソッドが呼ばれます。
22344 @c COMMON
22345
22346 @c EN
22347 For example, when you see the following error report:
22348 @c JP
22349 例えば、次のようなエラーレポートがあった場合:
22350 @c COMMON
22351
22352 @example
22353 *** UNBOUND-VARIABLE-ERROR: unbound variable: load
22354 NOTE: `load' is exported from the following modules:
22355 - scheme.r5rs
22356 - scheme.load
22357 While loading "/home/shiro/src/Gauche/src/../src/ttt.scm" at line 3
22358 While compiling "./tttt.scm" at line 1: (use ttt)
22359 While loading "./tttt.scm" at line 1
22360 @end example
22361
22362 @itemize @bullet
22363 @item
22364 @c EN
22365 The first line (beginning with @code{***}) is printed by
22366 @code{print-default-error-heading}. The rest is printed
22367 by @code{print-additional-error-heading}.
22368 @c JP
22369 最初の行(@code{***}で始まる行)は
22370 @code{print-default-error-heading}が出しています。
22371 残りは@code{print-additional-error-heading}が出しています。
22372 @c COMMON
22373 @item
22374 @c EN
22375 The thrown condition is a compound condition of
22376 @code{<unbound-variable-error>}, @code{<load-condition-mixin>},
22377 @code{<compile-error-mixin>},
22378 and another @code{<load-condition-mixin>}.
22379 @c JP
22380 投げられたコンディションは、
22381 @code{<unbound-variable-error>}、@code{<load-condition-mixin>}、
22382 @code{<compile-error-mixin>}、そしてもうひとつの
22383 @code{<load-condition-mixin>}の複合コンディションです。
22384 @c COMMON
22385 @item
22386 @c EN
22387 The three lines beginning with @code{NOTE} is printed by
22388 @code{report-additional-condition} method of
22389 @code{<unbound-variable-error>}.
22390 @c JP
22391 @code{NOTE}から始まる3行は、@code{<unbound-variable-error>}の
22392 @code{report-additional-condition}メソッドが出力しています。
22393 @c COMMON
22394 @item
22395 @c EN
22396 The @code{While loading ...} lines are printed by
22397 @code{report-additional-condition} method of
22398 @code{<load-condition-mixin>}.
22399 @c JP
22400 @code{While loading ...}の行は@code{<load-condition-mixin>}の
22401 @code{report-additional-condition}メソッドが出力しています。
22402 @c COMMON
22403 @item
22404 @c EN
22405 The @code{While compiling ...} line is printed by
22406 @code{<compile-error-mixin>}.
22407 @c JP
22408 @code{While compiling ...}の行は@code{<compile-error-mixin>}の
22409 @code{report-additional-condition}メソッドが出力しています。
22410 @c COMMON
22411 @end itemize
22412
22413 @c EN
22414 This is called by @code{report-error}, but you can use this procedure
22415 separately.
22416 @c JP
22417 この手続きは@code{report-error}が使っていますが、
22418 この手続きだけを直接呼び出すことも可能です。
22419 @c COMMON
22420 @end defun
22421
22422 @deffn {Generic Function} report-additional-condition condition out
22423 @c EN
22424 Used to print additional information about a condition object
22425 @var{condition}, to an output port @var{out}.
22426 Some built-in conditions specializes this generic function.
22427 See @code{print-additional-error-heading} above for an example.
22428 @c JP
22429 コンディションオブジェクト@var{condition}についての追加の情報を
22430 出力ポート@var{out}に出力します。
22431 いくつかの組み込みのコンディションはこのジェネリックファンクションを特定化しています。
22432 具体例は上の@code{print-additional-error-heading}の項を見てください。
22433 @c COMMON
22434 @end deffn
22435
22436
22437 @node Low-level exception handling mechanism, , Behavior of unhandled exception, Handling exceptions
22438 @subsubsection Low-level exception handling mechanism
22439 @c NODE 下位レベルの例外処理機構
22440
22441 @c EN
22442 This layer provides SRFI-18 compatible simple exception mechanism.
22443 You can override the behavior of higher-level constructs such as
22444 @code{with-error-handler} by using @code{with-exception-handler}.
22445 @c JP
22446 このレイヤはSRFI-18互換のシンプルな例外メカニズムを提供します。
22447 @code{with-error-handler}のような高次元の構造の振る舞いを、
22448 @code{with-exception-handler}を使って上書きすることができます。
22449 @c COMMON
22450
22451 @c EN
22452 Note that it is a double-edged sword. You'll get a freedom to
22453 construct your own exception handling semantics, but the Gauche
22454 system won't save if something goes wrong. Use these primitives
22455 when you want to customize the system's higher-level semantics
22456 or you are porting from other SRFI-18 code.
22457 @c JP
22458 これは諸刃の剣であることに注意して下さい。あなたは独自の例外処理
22459 セマンティクスを構築する自由がありますが、Gaucheシステムは何か
22460 間違いがあっても救ってくれません。システムの高次元のセマンティクスを
22461 カスタマイズしたいか、他のSRFI-18準拠のコードを移植している場合にのみ、
22462 これらのプリミティブを使って下さい。
22463 @c COMMON
22464
22465 @defun current-exception-handler
22466 [SRFI-18]
22467 @c EN
22468 Returns the current exception handler.
22469 @c JP
22470 現在の例外ハンドラを返します。
22471 @c COMMON
22472 @end defun
22473
22474 @defun exception-handler-stack
22475 [SRFI-226]
22476 @c EN
22477 Returns a fresh list of handlers in the current exception handler stack.
22478 The most recent one coming first.
22479 @c JP
22480 現在の例外ハンドラスタックにある例外ハンドラのリストを返します。
22481 リストは新にアロケートされたもので、最後に設定されたハンドラが最初に来ます。
22482 @c COMMON
22483 @end defun
22484
22485
22486 @defun with-exception-handler handler thunk
22487 [R7RS base][SRFI-34]
22488 @c EN
22489 A procedure @var{handler} must take one argument. This procedure
22490 sets @var{handler} to the current exception handler and calls
22491 @var{thunk}.
22492 (Note that this slightly differs from SRFI-18 @code{with-exception-handler};
22493 we'll explain it below.)
22494 @c JP
22495 @var{handler}は1引数を取る手続きです。この手続きは、@var{handler}を
22496 現在の例外ハンドラにセットし、@var{thunk}を呼び出します。
22497 (この手続きはSRFI-18の@code{with-exception-handler}と微妙に異なります。)
22498 @c COMMON
22499 @end defun
22500
22501 @c EN
22502 When an exception is raised by @code{raise} or @code{error},
22503 @var{handler} is called with the thrown condition in the
22504 exactly same dynamic environment of @code{raise} or @code{error},
22505 except that the exception handler at the time @code{with-exception-handler}
22506 is called is restored.
22507 @c JP
22508 例外が@code{raise}や@code{error}で通知されると、
22509 投げられたコンディションを引数として@var{handler}が
22510 呼び出し元の動的環境のうち、例外ハンドラだけが@code{with-exception-handler}
22511 呼び出し時点のものに置き換えられた環境で呼び出されます。
22512 @c COMMON
22513
22514 @c EN
22515 Note: SRFI-18 specifies the exception handler installed with
22516 @code{with-exception-handler} will be called with exactly the same
22517 dynamic environment, including the exception handler settings.
22518 It means if an exception is raised within the handler, it will be
22519 caught with the same handler. The reasoning is that
22520 @code{with-exception-handler} is the bottom layer and kept as simple
22521 as possible, and further semantics should be built on top of it.
22522
22523 Until 0.9.10 we supported SRFI-18 semantics natively, and provided
22524 R7RS semantics on top of it. However, the bare SRFI-18 semantics
22525 turned out to be error prone--users tended to assume errors from a handler
22526 would be handled by outer handler, and were perplexed when they ran into
22527 infinite recursion of handlers (which eventually caused a segfault, for
22528 the recursion eats up C stack). We decided to switch to R7RS semantics,
22529 for it is virtually always what users want.
22530 @c JP
22531 註: SRFI-18の@code{with-exception-handler}では、
22532 例外ハンドラは例外発生箇所と全く同じ動的環境で呼び出されるとしています。
22533 つまり例外ハンドラ中で例外が発生すると、同じハンドラが再び呼ばれます。
22534 これは、@code{with-exception-handler}を最も基本的なレイヤとして、
22535 その上に必要なセマンティクスを実装することが意図されていたからです。
22536
22537 0.9.10まではGaucheの組み込みの@code{with-exception-handler}はSRFI-18の
22538 セマンティクスで、その上にR7RSの@code{with-exception-handler}が実装されていました。
22539 しかし、SRFI-18セマンティクスは非常に使い方を間違えられやすかったのです。
22540 ユーザはハンドラ中で発生した例外は外側のハンドラで処理されると思い込みがちでした。
22541 正しくハンドラの置き換えを行わないと、ハンドラ中の例外はハンドラへの無限再帰を引き起こし、
22542 Cのスタックを食いつぶしてsegfaultします。実質的に全ての場合においてユーザが期待するのは
22543 R7RSセマンティクスなので、切り替えることにしました。
22544 @c COMMON
22545
22546 @c EN
22547 If an exception is raised by @code{error}, or the thrown condition
22548 inherits @code{<serious-condition>}, it is prohibited to return from
22549 @var{handler}. If @var{handler} ever returns in such cases, another
22550 error is signaled, with replacing the current exception handler to the
22551 outer handler. So the caller of @code{error}, or the caller of @code{raise}
22552 with @code{<serious-condition>}, can assume it never returns.
22553 @c JP
22554 例外が@code{error}により投げられた場合、あるいは投げられたコンディションが
22555 @code{<serious-condition>}を継承していた場合、
22556 @var{handler}から戻ることは禁止されます。もし戻ってしまったら、
22557 ハンドラを外側のものに置き換えた上で別のエラーが投げられます。
22558 したがって、@code{error}の呼び出し元、あるいは@code{<serious-condition>}を
22559 引数とした@code{raise}の呼び出し元は、
22560 その呼び出しが決して戻らないと考えて構いません。
22561 @c COMMON
22562
22563 @c EN
22564 The behavior of those procedures can be explained in
22565 the following conceptual Scheme code.
22566 @c JP
22567 これらの手続きの振る舞いは、次の概念的なSchemeコードによって
22568 説明されるでしょう。
22569 @c COMMON
22570
22571 @example
22572 @c EN
22573 ;; @r{Conceptual implementation of low-level exception mechanism.}
22574 ;; @r{Suppose %xh is a list of exception handlers}
22575 @c JP
22576 ;; @r{低レベルな例外メカニズムの概念的な実装}
22577 ;; @r{%xhは例外ハンドラのリスト}
22578 @c COMMON
22579
22580 (define (current-exception-handler) (car %xh))
22581
22582 (define (raise exn)
22583 (let ((prev %xh))
22584 (dynamic-wind
22585 (lambda () (set! %xh (cdr %xh)))
22586 (lambda ()
22587 (receive r ((current-exception-handler) exn)
22588 (if (uncontinuable-exception? exn)
22589 (raise (@r{@i{make-error}} "returned from uncontinuable exception"))
22590 (apply values r))))
22591 (lambda () (set! %xh prev)))))
22592
22593 (define (with-exception-handler handler thunk)
22594 (let ((prev %xh))
22595 (dynamic-wind
22596 (lambda () (set! %xh (cons handler %xh)))
22597 thunk
22598 (lambda () (set! %xh prev)))))
22599 @end example
22600
22601
22602 @node Conditions, , Handling exceptions, Exceptions
22603 @subsection Conditions
22604 @c NODE コンディション
22605
22606 @c EN
22607 @subsubheading Built-in Condition classes
22608 @c JP
22609 @subsubheading 組み込みコンディションクラス
22610 @c COMMON
22611
22612 @c EN
22613 Gauche currently has the following hierarchy of built-in condition
22614 classes. It approximately reflects SRFI-35 and SRFI-36 condition hierarchy,
22615 although they have Gauche-style class names. If there's a corresponding
22616 SRFI condition type, the class has the SRFI name as well.
22617 @c JP
22618 現在のところGaucheには以下の組み込みコンディションクラスの階層があります。
22619 これは、おおよそのところ SRFI-35 および SRFI-36 のコンディションの階層を
22620 反映したものですが、Gauche風のクラス名になっています。対応する SRFI の
22621 コンディションタイプがあるものについては、SRFI でのクラス名も使えます。
22622 @c COMMON
22623
22624 @example
22625 <condition>
22626 +- <compound-condition>
22627 +- <serious-condition>
22628 | +- <serious-compound-condition> ; also inherits <compound-condition>
22629 +- <message-condition>
22630 +- <error> ; also inherits <serious-condition>
22631 +- <system-error>
22632 +- <unhandled-signal-error>
22633 +- <continuation-violation>
22634 +- <read-error>
22635 +- <io-error>
22636 +- <port-error>
22637 +- <io-read-error>
22638 | +- <io-decoding-error>
22639 +- <io-write-error>
22640 | +- <io-encoding-error>
22641 +- <io-closed-error>
22642 +- <io-unit-error>
22643 +- <io-invalid-position-error>
22644 @end example
22645
22646 @c EN
22647 Note that some conditions may occur simultaneously; for example,
22648 error during reading from a file because of device failure may consist
22649 both @code{<system-error>} @emph{and} @code{<io-read-error>}.
22650 In such cases, a @emph{compound condition} is raised.
22651 So you can't just use, for instance, @code{(is-a? obj <io-read-error>)}
22652 to check if @code{<io-read-error>} is thrown.
22653 See the "Condition API" section below.
22654 @c JP
22655 いくつかのコンディションが同時に発生することがあることに注意してください。
22656 たとえば、ファイルの読み込がデバイスの欠陥により失敗した場合は、
22657 @code{<system-error>} @emph{および} @code{<io-read-error>} の両方からなる
22658 エラーとなるでしょう。
22659 このような場合、@emph{合成したコンディション (compound condition)} が発生します。
22660 したがって、たとえば、@code{<io-read-error>} が投げられたかどうかをチェック
22661 するのに、単に @code{(is-a? obj <io-read-error>)} を使えばよいというわけ
22662 にはいきません。
22663 後述の「コンディション API」の節を参照してください。
22664 @c COMMON
22665
22666 @deftp {Metaclass} <condition-meta>
22667 @clindex condition-meta
22668 @c EN
22669 Every condition class is an instance of this class.
22670 This class defines @code{object-apply} so that you can use
22671 a condition class as a predicate, e.g.:
22672 @c JP
22673 すべてのコンディションクラスはこのクラスのインスタンスです。
22674 このクラスは @code{object-apply} を定義していますので、
22675 コンディションクラスは述語として使うことができます。たとえば、
22676 @c COMMON
22677
22678 @example
22679 (<error> obj) @equiv{} (condition-has-type? obj <error>)
22680 @end example
22681 @end deftp
22682
22683
22684 @deftp {Class} <condition>
22685 @deftpx {Condition Type} &condition
22686 @clindex condition
22687 @vindex &condition
22688 [SRFI-35]
22689 @c EN
22690 The root class of the condition hierarchy.
22691 @c JP
22692 コンディションの階層のルートクラスです。
22693 @c COMMON
22694 @end deftp
22695
22696 @deftp {Class} <compound-condition>
22697 @clindex compound-condition
22698 @c EN
22699 Represents a compound condition. A compound condition can be
22700 created from one or more conditions by @code{make-compound-condition}.
22701 Don't use this class directly.
22702 @c JP
22703 合成コンディションを表現します。合成コンディションは
22704 @code{make-compound-condition} を用いて1つ以上のコンディションから
22705 生成することができます。このクラスを直接使ってはいけません。
22706 @c COMMON
22707
22708 @c EN
22709 A compound condition returns @code{#t} for @code{condition-has-type?}
22710 if any of the original conditions has the given type.
22711 @c JP
22712 合成コンディションは@code{condition-has-type?} に対して、
22713 元のコンディションのどれかが、与えられたタイプなら、@code{#t} を返します。
22714 @c COMMON
22715 @end deftp
22716
22717 @deftp {Class} <serious-condition>
22718 @deftpx {Condition Type} &serious
22719 @clindex serious-condition
22720 @vindex &serious
22721 [SRFI-35]
22722 @c EN
22723 Conditions of this class are for the situations that are too serious
22724 to ignore or continue. Particularly, you can safely assume that
22725 if you @code{raise} this type of condition, it never returns.
22726 @c JP
22727 このクラスのコンディションは無視して先を続けることはできない深刻な
22728 状況のためにあります。特に、このタイプのコンディションを @code{raise}
22729 したら、それは元には絶対に戻らないと考えて問題ありません。
22730 @c COMMON
22731 @end deftp
22732
22733 @deftp {Class} <serious-compound-condition>
22734 @clindex serious-compound-condition
22735 @c EN
22736 This is an internal class to represent a compound condition
22737 with any of its component condition is serious. Inherits both
22738 @code{<compound-condition>} and @code{<serious-condition>}.
22739 @code{make-compound-condition} uses this class if the passed
22740 conditions includes a serious one.
22741 Don't use this class directly.
22742 @c JP
22743 深刻なコンディションを含む合成コンディションを表現するための
22744 内部クラスです。@code{<compound-condition>} および
22745 @code{<serious-condition>} の両方を継承しています。
22746 @code{make-compound-condition} は深刻なコンディションを含む複数の
22747 コンディションを渡されると、このクラスを使います。このクラスを
22748 直接使ってはいけません。
22749 @c COMMON
22750 @end deftp
22751
22752 @deftp {Class} <message-condition>
22753 @deftpx {Condition Type} &message
22754 @clindex message-condition
22755 [SRFI-35]
22756 @c EN
22757 This class represents a condition with a message. It has one slot.
22758 @c JP
22759 このクラスはメッセージ付のコンディションを表現し、スロットを一つ
22760 もっています。
22761 @c COMMON
22762
22763 @defivar {<message-condition>} message
22764 @c EN
22765 A message.
22766 @c JP
22767 メッセージ
22768 @c COMMON
22769
22770 @end defivar
22771 @end deftp
22772
22773 @deftp {Class} <error>
22774 @deftpx {Condition Type} &error
22775 @clindex error
22776 @vindex &error
22777 [SRFI-35]
22778 @c EN
22779 Indicates an error. Inherits @code{<serious-condition>}
22780 and @code{<message-condition>}, thus has @code{message} slot.
22781 @c JP
22782 エラーを表します。@code{<serious-condition>} および
22783 @code{<message-condition>} を継承しています。したがって、
22784 @code{message} スロットを持っています。
22785 @c COMMON
22786
22787 @c EN
22788 Note: SRFI-35 @code{&error} condition only inherits @code{&serious}
22789 and not @code{&message}, so you have to use compound condition
22790 to attach a message to the error condition. Gauche uses multiple
22791 inheritance here, largely because of backward compatibility.
22792 To write a portable code, an error condition should be used
22793 with a message condition, like this:
22794 @c JP
22795 注意事項: SRFI-35 の@code{&error}コンディションは @code{&serious}
22796 のみを継承し、@code{&message} は継承していません。したがって、
22797 このエラーコンディションにメッセージを付与するためには、
22798 合成コンディションを使わなければなりません。Gauche は
22799 主として過去のバージョンとの互換性を確保するために、
22800 ここで多重継承を用いています。
22801 可搬性のあるコードを書くには、以下のようにメッセージコンディション
22802 付きのエラーコンディションを使うべきです。
22803 @c COMMON
22804
22805 @example
22806 (condition
22807 (&message (message "Error message"))
22808 (&error))
22809 @end example
22810 @end deftp
22811
22812 @defun message-condition? obj
22813 @defunx serious-condition? obj
22814 @defunx error? obj
22815 [SRFI-35]
22816 @c EN
22817 These are SRFI-35 compatible predicates to see if @var{obj} is
22818 a condition of type @code{&message}, @code{&serious}, and @code{&error},
22819 respectively.
22820 @c JP
22821 これらはSRFI-35互換の述語で、それぞれ@var{obj}が
22822 @code{&message}、@code{&serious}、あるいは@code{&error}型のコンディションであるか
22823 どうかを検査します。
22824 @c COMMON
22825 @end defun
22826
22827
22828 @deftp {Class} <system-error>
22829 @clindex system-error
22830 @c EN
22831 A subclass of @code{<error>}.
22832 When a system call returns an error, this type of exception is
22833 thrown. The @code{message} slot usually contains the description
22834 of the error (like the one from @code{strerror(3)}).
22835 Besides that, this class has one more instance slot:
22836 @c JP
22837 @code{<error>} のサブクラス。
22838 システムコールがエラーを返したとき、この型の例外が投げられます。
22839 @code{message} スロットには通常エラーの(@code{strerror(3)}のような)説明が
22840 含まれています。それ以外に、このクラスにはもうひとつ次のような
22841 インスタンススロットがあります。
22842 @c COMMON
22843
22844 @defivar {<system-error>} errno
22845 @c EN
22846 Contains an integer value of system's error number.
22847
22848 Error numbers may differ among systems. Gauche defines
22849 constants for typical Unix error values (e.g. @code{EACCES}, @code{EBADF},
22850 etc), so it is desirable to use them instead of literal numbers.
22851 See the description of @code{sys-strerror} in @ref{System inquiry}
22852 for available constants.
22853 @c JP
22854 システムのエラー番号の整数値を持ちます。
22855
22856 エラー番号はシステムによって異なる可能性があります。Gaucheは典型的な
22857 Unixのエラー番号に対して定数を定義している(例: @code{EACCES}, @code{EBADF})ので、
22858 それを使うと良いでしょう。定義されている定数に関しては
22859 @ref{System inquiry}の@code{sys-strerror}の説明を参照してください。
22860 @c COMMON
22861 @end defivar
22862
22863 @c EN
22864 This class doesn't have corresponding SRFI condition type,
22865 but important to obtain OS's raw error code. In some cases,
22866 this type of condition is compounded with other condition
22867 types, like @code{<io-read-error>}.
22868 @c JP
22869 このクラスには対応する SRFI のコンディションタイプがありませんが、
22870 OSの生のエラーコードを取得するのに重要です。いくつかのケースで
22871 このタイプのコンディションは他の、たとえば @code{<io-read-error>}
22872 のようなコンディションと合成されます。
22873 @c COMMON
22874 @end deftp
22875
22876 @deftp {Class} <unhandled-signal-error>
22877 @clindex unhandled-signal-error
22878 @c EN
22879 A subclass of @code{<error>}. The default handler of most of
22880 signals raises this condition. See @ref{Handling signals} for
22881 the details.
22882 @c JP
22883 @code{<error>}のサブクラス。多くのシグナルのデフォルトハンドラは
22884 このコンディションを投げます。詳しくは@ref{Handling signals}を
22885 参照してください。
22886 @c COMMON
22887 @defivar {<unhandled-signal-error>} signal
22888 @c EN
22889 An integer indicating the received signal number.
22890 There are constants defined for typical signal numbers; see
22891 @ref{Signals and signal sets}.
22892 @c JP
22893 受け取ったシグナル番号を示す整数値。典型的なシグナル番号については
22894 定数が定義されています。@ref{Signals and signal sets}を参照のこと。
22895 @c COMMON
22896 @end defivar
22897 @end deftp
22898
22899 @deftp {Class} <read-error>
22900 @deftpx {Condition Type} &read-error
22901 @clindex read-error
22902 @vindex &read-error
22903 [SRFI-36]
22904 @c EN
22905 A subclass of @code{<error>}.
22906 When the reader detects a lexical or syntactic error during
22907 reading an S-expression, this type of condition is raised.
22908 @c JP
22909 @code{<error>} のサブクラス。リーダがS式を読み込み中に、字句エラー
22910 または構文エラーを検出したとき、この型のコンディションが投げられます。
22911 @c COMMON
22912
22913 @defivar {<read-error>} port
22914 @c EN
22915 A port from which the reader is reading.
22916 (NB: SRFI-36's @code{&read-error} doesn't have this slot. Portable
22917 program shouldn't rely on this slot).
22918 @c JP
22919 リーダがS式を読みこんでいたポート。
22920 (註: SRFI-36 の @code{&read-error} はこのスロットを定義していません。
22921 ポータブルなプログラムを書く場合はこのスロットを使わないで下さい)。
22922 @c COMMON
22923 @end defivar
22924
22925 @defivar {<read-error>} line
22926 @c EN
22927 A line count (1-base) of the input where the reader raised this error.
22928 It may be -1 if the reader is reading from a port that doesn't keep
22929 track of line count.
22930 @c JP
22931 リーダがこのエラーを発生させたときの入力行カウント(1がベース)。
22932 リーダが行カウントを保持しないポートから読み込むときには、-1 となる。
22933 @c COMMON
22934 @end defivar
22935
22936 @defivar {<read-error>} column
22937 @defivarx {<read-error>} position
22938 @defivarx {<read-error>} span
22939 @c EN
22940 These slots are defined in SRFI-36's @code{&read-error}.
22941 For the time being, these slots always hold @code{#f}.
22942 @c JP
22943 これらのスロットは、SRFI-36 の @code{&read-error} で定義されています。
22944 今のところ、これらのスロットは常に @code{#f} を保持するようになっています。
22945 @c COMMON
22946 @end defivar
22947
22948 @end deftp
22949
22950 @deftp {Class} <io-error>
22951 @deftpx {Condition Type} &io-error
22952 @clindex io-error
22953 @vindex &io-error
22954 [SRFI-36]
22955 @c EN
22956 A base class of I/O errors. Inherits @code{<error>}.
22957 @c JP
22958 I/O エラーのベースとなるクラス。@code{<error>} を継承しています。
22959 @c COMMON
22960 @end deftp
22961
22962 @deftp {Class} <port-error>
22963 @deftpx {Condition Type} &io-port-error
22964 @clindex port-error
22965 @vindex &io-port-error
22966 [SRFI-36]
22967 @c EN
22968 An I/O error related to a port. Inherits @code{<io-error>}.
22969 @c JP
22970 ポート関連の I/O エラー。@code{<io-error>} を継承しています。
22971 @c COMMON
22972
22973 @defivar <port-error> port
22974 @c EN
22975 Holds the port where the error occurred.
22976 @c JP
22977 エラーを起したポートを保持。
22978 @c COMMON
22979 @end defivar
22980 @end deftp
22981
22982 @deftp {Class} <io-read-error>
22983 @deftpx {Condition Type} &io-read-error
22984 @clindex io-read-error
22985 @vindex &io-read-error
22986 [SRFI-36]
22987 @c EN
22988 An I/O error during reading from a port. Inherits @code{<port-error>}.
22989 @c JP
22990 ポートから読み込み中の I/O エラー。@code{<port-error>} を継承しています。
22991 @c COMMON
22992 @end deftp
22993
22994 @deftp {Class} <io-write-error>
22995 @deftpx {Condition Type} &io-write-error
22996 @clindex io-write-error
22997 @vindex &io-write-error
22998 [SRFI-36]
22999 @c EN
23000 An I/O error during writing to a port. Inherits @code{<port-error>}.
23001 @c JP
23002 ポートへの書き出し中の I/O エラー。@code{<port-error>} を継承しています。
23003 @c COMMON
23004 @end deftp
23005
23006 @deftp {Class} <io-closed-error>
23007 @deftpx {Condition Type} &io-closed-error
23008 @clindex io-closed-error
23009 @vindex &io-closed-error
23010 [SRFI-36]
23011 @c EN
23012 An I/O error when read/write is attempted on a closed port.
23013 Inherits @code{<port-error>}.
23014 @c JP
23015 クローズされたポートで読み込み/書き出しをしようしたときの I/O エラー。
23016 @code{<port-error>} を継承しています。
23017 @c COMMON
23018 @end deftp
23019
23020 @deftp {Class} <io-unit-error>
23021 @clindex io-unit-error
23022 @c EN
23023 An I/O error when the read/write is requested with a unit
23024 that is not supported by the port (e.g. a binary I/O is requested
23025 on a character-only port). Inherits @code{<port-error>}.
23026 @c JP
23027 対象となるポートでサポートされていない単位での読み/書き要求
23028 (たとえば、キャラクタ専用ポートでのバイナリ I/O 要求)の際の I/O エラー。
23029 @code{<port-error>} を継承しています。
23030 @c COMMON
23031 @end deftp
23032
23033 @deftp {Class} <continuation-violation>
23034 @deftpx {Condition Type} &continuation
23035 @clindex continuation-violation
23036 @vindex &continuation
23037 [SRFI-226]
23038 @c EN
23039 An error thrown on violation of requirements related to continuations.
23040 A typical case is that a requested continuation prompt tag doesn't
23041 exist in the context. @xref{Continuation prompts}, for the details.
23042 @c JP
23043 継続に関する制約が破られた場合に投げられるエラーです。
23044 典型的なのは、指定された継続プロンプトタグがコンテクスト中に見つからない場合です。
23045 詳しくは@ref{Continuation prompts}を参照してください。
23046 @c COMMON
23047 @end deftp
23048
23049 @defun make-continuation-violation prompt-tag
23050 [SRFI-226]
23051 @c EN
23052 Creates a new continuation violation condition, with @var{prompt-tag}
23053 as the continuation prompt tag that caused the violation.
23054 @c JP
23055 @code{<continuation-violation>}コンディションを作ります。
23056 @var{prompt-tag}は原因となった継続プロンプトタグです。
23057 @c COMMON
23058 @end defun
23059
23060 @defun continuation-violation? obj
23061 [SRFI-226]
23062 @c EN
23063 Returns @code{#t} if @var{obj} is a @code{<continuation-violation>}
23064 condition, @code{#f} otherwise.
23065 @c JP
23066 @var{obj}が@code{<continuation-violation>}コンディションなら
23067 @code{#t}を、そうでなければ@code{#f}を返します。
23068 @c COMMON
23069 @end defun
23070
23071 @defun continuation-violation-prompt-tag condition
23072 [SRFI-226]
23073 @c EN
23074 Extract the value of @var{prompt-tag} slot
23075 from @var{condition}, which must be a @code{<continuation-violation>}
23076 condition.
23077 @c JP
23078 @code{<continuation-violation>}コンディションである@var{condition}の、
23079 @var{prompt-tag}スロットの値を取り出します。
23080 @c COMMON
23081 @end defun
23082
23083
23084 @c EN
23085 @subsubheading Condition API
23086 @c JP
23087 @subsubheading コンディションAPI
23088 @c COMMON
23089
23090 @defmac define-condition-type name supertype predicate field-spec @dots{}
23091 [SRFI-35+]
23092 @c EN
23093 Defines a new condition type. In Gauche, a condition type is
23094 a class, whose metaclass is @code{<condition-meta>}.
23095 @c JP
23096 新しいコンディションタイプを定義します。Gaucheでは、コンディションタイプは
23097 クラスであり、そのメタクラスは @code{<condition-meta>} です。
23098 @c COMMON
23099
23100 @c EN
23101 @var{Name} becomes the name of the new type, and also the variable
23102 of that name is bound to the created condition type.
23103 @var{Supertype} is the name of the supertype (direct superclass)
23104 of this condition type. A condition type must inherit from
23105 @code{<condition>} or its descendants.
23106 (Multiple inheritance can't be specified by this form, and generally
23107 should be avoided in condition type hierarchy. Instead, you
23108 can use compound conditions, which don't introduce multiple inheritance.)
23109 @c JP
23110 @var{name} が新しいタイプの名前になり、この名前の変数が作成された
23111 コンディションタイプに束縛されます。@var{supertype} はこのコンディション
23112 タイプのスーパータイプ(直接のスーパークラス)の名前です。コンディション
23113 タイプは @code{<condition>} を継承するか、その子孫を継承しなければ
23114 なりません。(この形式では、多重継承を指定することはできません。
23115 一般的にいって、コンディションタイプの階層の中では多重継承は避ける
23116 べきです。そのかわりに、合成コンディションを使えます。合成コンディションは
23117 多重継承を使いません。)
23118 @c COMMON
23119
23120 @c EN
23121 A variable @var{predicate} is bound to a predicate procedure for
23122 this condition type.
23123 @c JP
23124 変数 @var{predicate} はこのコンディションタイプ用の述語手続きに
23125 束縛されます。
23126 @c COMMON
23127
23128 @c EN
23129 Each @code{field-spec} is a form of @code{(field-name accessor-name)},
23130 and the condition will have fields named by @var{field-name}, and
23131 a variable @var{accessor-name} will be bound to a procedure that
23132 accesses the field. In Gauche, each field becomes a slot of
23133 the created class.
23134
23135 Gauche extends SRFI-35 to allow @var{predicate} and/or @code{accessor-name}
23136 to be @code{#f}, or @code{accessor-name} to be omitted,
23137 if you don't need to them to be defined.
23138 @c JP
23139 各 @code{field-spec} は @code{(field-name accessor-name)} の形式で
23140 このコンディションは、フィールド名は @var{field-name} で決まります。
23141 変数 @var{accessor-name} はそのフィールドにアクセスする手続きに
23142 束縛されます。Gauche では、それぞれのフィールドは生成された
23143 クラスのスロットとなります。
23144
23145 GaucheはSRFI-35を拡張して、@var{predicate}や@var{accessor-name}を
23146 定義する必要が無い場合はその位置に@code{#f}を指定できるようにしています。
23147 @var{accessor-name}が必要無い場合はそれを省略することもできます。
23148 @c COMMON
23149
23150 @c EN
23151 When @code{define-condition-type} is expanded into a class
23152 definition, each slot gets a @code{:init-keyword} slot option
23153 with the keyword whose name is the same as the slot name.
23154 @c JP
23155 @code{define-condition-type}がクラス定義に展開される際に、
23156 各スロットは@code{:init-keyword}スロットオプションにスロット名と
23157 同名のキーワードを取るように定義されます。
23158 @c COMMON
23159 @end defmac
23160
23161 @defun condition-type? obj
23162 [SRFI-35]
23163 @c EN
23164 Returns @code{#t} iff @var{obj} is a condition type. In Gauche,
23165 it means @code{(is-a? obj <condition-meta>)}.
23166 @c JP
23167 @var{obj}がコンディションタイプである場合で、その場合にかぎり、
23168 @code{#t} を返します。Gauche では @code{(is-a? obj <condition-meta>)}
23169 と同じです。
23170 @c COMMON
23171 @end defun
23172
23173 @defun make-condition-type name parent field-names
23174 [SRFI-35]
23175 @c EN
23176 A procedural version to create a new condition type.
23177 @c JP
23178 新しいコンディションタイプを生成する手続き版です。
23179 @c COMMON
23180 @end defun
23181
23182 @defun make-condition type field-name value @dots{}
23183 [SRFI-35]
23184 @c EN
23185 Creates a new condition of condition-type @var{type}, and
23186 initializes its fields as specified by @code{field-name} and @code{value}
23187 pairs.
23188 @c JP
23189 コンディションタイプ @var{type} のコンディションを生成し、
23190 @code{field-name} および @code{value} のペアで指定されたように
23191 フィールドを初期化します。
23192 @c COMMON
23193 @end defun
23194
23195 @defun condition? obj
23196 [SRFI-35]
23197 @c EN
23198 Returns @code{#t} iff @var{obj} is a condition. In Gauche,
23199 it means @code{(is-a? obj <condition>)}.
23200 @c JP
23201 @var{obj} がコンディションである場合で、その場合にかぎり、
23202 @code{#t} を返します。Gauche では @code{(is-a? obj <condition>)} と
23203 同じです。
23204 @c COMMON
23205 @end defun
23206
23207 @defun condition-has-type? obj type
23208 [SRFI-35]
23209 @c EN
23210 Returns @code{#t} iff @var{obj} belongs to a condition type @var{type}.
23211 Because of compound conditions, this is not equivalent to @code{is-a?}.
23212 @c JP
23213 @var{obj} がコンディションタイプ @var{type} に属している場合で、その
23214 場合にかぎり、@code{#t} を返します。合成コンディションがあるので、
23215 これは、@code{is-a?} と同じではありません
23216 @c COMMON
23217 @end defun
23218
23219 @defun condition-ref condition field-name
23220 [SRFI-35]
23221 @c EN
23222 Retrieves the value of field @var{field-name} of @var{condition}.
23223 If @var{condition} is a compound condition, you can access to the
23224 field of its original conditions; if more than one original condition
23225 have @var{field-name}, the first one passed to @code{make-compound-condition}
23226 has precedence.
23227 @c JP
23228 @var{condition} のフィールド @var{field-name} の値を検索します。
23229 @var{condition} が合成コンディションであれば、元のコンディションの
23230 フィールドにアクセスできます。もし、複数の元のコンディションが、
23231 @var{field-name} を持つ場合には、最初に @code{make-compound-condition}
23232 に渡されたものが優先されます。
23233 @c COMMON
23234
23235 @c EN
23236 You can use @code{slot-ref} and/or @code{ref} to access to the field
23237 of conditions; compound conditions define a @code{slot-missing} method
23238 so that @code{slot-ref} behaves as if the compound conditions have all the
23239 slots of the original conditions. Using @code{condition-ref} increases
23240 portability, though.
23241 @c JP
23242 コンディションのフィールドにアクセスするには、@code{slot-ref} および
23243 @code{ref} の両方あるいはどちらかを使えます。合成コンディションでは、
23244 @code{slot-missing} メソッドが定義されますので、@code{slot-ref} は
23245 あたかも、合成コンディションが元になったコンディションの全てのスロットを
23246 もつかのように振舞います。しかしながら、@code{condition-ref} を
23247 使う方が可搬性が増します。
23248 @c COMMON
23249 @end defun
23250
23251 @defun condition-message condition :optional fallback
23252 [SRFI-35+]
23253 @c EN
23254 This is a convenience procedure to retrieve a message if
23255 @var{condition} has a type @code{<message-condition>},
23256 and returns @var{fallback} otherwise. If @var{fallback}
23257 is omitted, @code{#f} is assumed.
23258
23259 Often, in a generic routine you want to intercept a raised
23260 condition and retrieve a message for logging or user feedback.
23261 Since any object can be raised in Scheme, an exception may not
23262 contain the message slot, and you need to check the type
23263 of the condition. We've written such code enough so that we
23264 add this procedure.
23265 @c JP
23266 @var{condition}が@code{<message-condition>}を持っていれば
23267 その@code{message}スロットを、そうでなければ@var{fallback}を返す手続きです。
23268 @var{fallback}が省略された場合は@code{#f}が指定されたとみなします。
23269
23270 投げられたコンディションを一度捕まえてメッセージを記録したりユーザに見せたりする
23271 一般的なコードはよくあります。Schemeでは任意のオブジェクトを@code{raise}できるため、
23272 捕まえたコンディションがメッセージスロットを持っているとは限りません。
23273 従ってそういったコードはいちいちコンディションの型を検査して分岐することになります。
23274 そのパターンは充分によくあるので、この手続きが追加されました。
23275 @c COMMON
23276 @end defun
23277
23278 @defun make-compound-condition condition0 condition1 @dots{}
23279 [SRFI-35]
23280 @c EN
23281 Returns a compound condition that has all @var{condition0} @var{condition1}
23282 @dots{}. The returned condition's fields are the union of all the fields
23283 of given conditions; if any conditions have the same name of fields,
23284 the first one takes precedence. The returned condition also has
23285 condition-type of all the types of given conditions.
23286 (This is not a multiple inheritance. See @code{<compound-condition>} above.)
23287 @c JP
23288 @var{condition0} @var{condition1} @dots{} のすべてを持つ合成コンディション
23289 を返します。返されたコンディションのフィールドは、与えられたコンディション
23290 のすべてのフィールドの和集合になります。同じ名前のフィールドを持つ
23291 コンディションがある場合には最初に与えられものが優先されます。
23292 返されたコンディションは元になったコンディションのすべてのタイプの
23293 コンディションタイプをもつことになります。
23294 (これは多重継承ではありません。上の @code{<compound-condition>} を参照)
23295 @c COMMON
23296 @end defun
23297
23298 @defun extract-condition condition condition-type
23299 [SRFI-35]
23300 @c EN
23301 @var{Condition} must be a condition and have type @var{condition-type}.
23302 This procedure returns a condition of @var{condition-type},
23303 with field values extracted from @var{condition}.
23304 @c JP
23305 @var{condition} はコンディションで、@var{condition-type}タイプで
23306 なければなりません。この手続きは @var{condition-type} のコンディション
23307 を返し、@var{condition} からとりだされた値のフィールドを持ちます。
23308 @c COMMON
23309 @end defun
23310
23311 @defmac condition type-field-binding @dots{}
23312 [SRFI-35]
23313 @c EN
23314 A convenience macro to create a (possibly compound) condition.
23315 @var{Type-field-binding} is a form of
23316 @code{(@var{condition-type} (@var{field-name} @var{value-expr}) @dots{})}.
23317 @c JP
23318 コンディションを生成するのに便利なマクロ。
23319 合成されたコンディションも生成できます。
23320 @var{Type-field-binding} は、
23321 @code{(@var{condition-type} (@var{field-name} @var{value-expr}) @dots{})}
23322 という形式になります。
23323 @c COMMON
23324
23325 @example
23326 (condition
23327 (type0 (field00 value00) ...)
23328 (type1 (field10 value10) ...)
23329 ...)
23330 @equiv{}
23331 (make-compound-condition
23332 (make-condition type0 'field00 value00 ...)
23333 (make-condition type1 'field10 value10 ...)
23334 ...)
23335 @end example
23336 @end defmac
23337
23338
23339 @c ----------------------------------------------------------------------
23340 @node Eval and repl, Input and output, Exceptions, Core library
23341 @section Eval and repl
23342 @c NODE eval と repl
23343
23344 @defun eval expr env
23345 [R7RS eval]
23346 @c EN
23347 Evaluate @var{expr} under the environment @var{env}.
23348 In Gauche, @var{env} is just a @code{<module>} object.
23349 @c JP
23350 @var{expr}を環境@var{env}内で評価します。
23351 Gaucheにおいて、@var{env}は単なる@code{<module>}オブジェクトです。
23352 @c COMMON
23353 @end defun
23354
23355 @c EN
23356 R5RS and R7RS provide a portable way to obtain environment.
23357 R5RS way is described below. R7RS way is
23358 described in @ref{R7RS eval}.
23359 @c JP
23360 R5RSとR7RSは、環境@var{env}を得るポータブルな方法を定義しています。
23361 R5RSの方法を以下に示します。R7RSの方法は@ref{R7RS eval}を参照してください。
23362 @c COMMON
23363
23364 @defun null-environment version
23365 @defunx scheme-report-environment version
23366 @defunx interaction-environment
23367 [R5RS]
23368 @c EN
23369 Returns an environment specifier which can be used as the second
23370 argument of @code{eval}. Right now an environment specifier
23371 is just a module. @code{(null-environment 5)} returns
23372 a @code{null} module, which contains just the syntactic bindings
23373 specified in R5RS, @code{(scheme-report-environment 5)}
23374 returns a @code{scheme} module, which contains syntactic and procedure
23375 bindings in R5RS, and @code{(interaction-environment)} returns
23376 a @code{user} module that contains all the Gauche built-ins plus
23377 whatever the user defined.
23378 It is possible that the Gauche adopts a first-class environment object
23379 in future, so do not rely on the fact that the environment specifier
23380 is just a module.
23381 @c JP
23382 @code{eval}の第2引数として使われる環境識別子を返します。
23383 現時点では、環境識別子は単にモジュールです。
23384 @code{(null-environment 5)}は、R5RSで規定されている単なる構文的な
23385 束縛を含む@code{null}モジュールを返します。
23386 @code{(scheme-report-environment 5)}は、R5RSで規定されている
23387 構文的な束縛と手続きの束縛を含む@code{scheme}モジュールを返します。
23388 @code{(interaction-environment)}は、全てのGaucheのビルトインと
23389 ユーザ定義の全てを含んだ@code{user}モジュールを返します。
23390 将来、Gaucheがファーストクラスの環境オブジェクトを採用する可能性が
23391 あるので、環境識別子が単なるモジュールであることを当てにしないで
23392 下さい。
23393 @c COMMON
23394
23395 @c EN
23396 An error is signaled if a value other than 5 is passed as @var{version}
23397 argument.
23398 @c JP
23399 引数@var{version}に5以外の値を渡すとエラーが通知されます。
23400 @c COMMON
23401 @end defun
23402
23403 @defun read-eval-print-loop :optional reader evaluator printer prompter
23404 @c EN
23405 This exports @code{Gosh}'s default read-eval-print loop to applications.
23406 Each argument can be @code{#f}, which indicates it to use Gauche's
23407 default procedure(s), or a procedure that satisfies the
23408 following conditions.
23409 @c JP
23410 @code{gosh}のデフォルトのread-eval-printループをアプリケーションに
23411 エクスポートします。それぞれの引数は、Gaucheのデフォルトの手続きを使うことを
23412 示す@code{#f}であっても良いですし、以下の条件を満たす手続きであっても構いません。
23413 @c COMMON
23414
23415 @table @emph
23416 @item reader
23417 @c EN
23418 A procedure that takes no arguments. It is supposed to read an expression
23419 and returns it.
23420 @c JP
23421 引数を取らない手続きです。式を読み込んでそれを返すことを期待されます。
23422 @c COMMON
23423 @item evaluator
23424 @c EN
23425 A procedure that takes two arguments, an expression and an environment
23426 specifier. It is supposed to evaluate the expression and returns zero or
23427 more value(s).
23428 @c JP
23429 式と環境識別子を2引数として取る手続きです。式を評価して、0個以上の値を
23430 返すことを期待されます。
23431 @c COMMON
23432 @item printer
23433 @c EN
23434 A procedure that takes zero or more arguments. It is supposed to
23435 print out these values. The result of this procedure is discarded.
23436 @c JP
23437 0個以上の引数を取る手続きです。それらの値を出力することを期待されます。
23438 この手続きの戻り値は無視されます。
23439 @c COMMON
23440 @item prompter
23441 @c EN
23442 A procedure that takes no arguments. It is supposed to print
23443 out the prompt. The result of this procedure is discarded.
23444 @c JP
23445 引数を取らない手続きです。プロンプトを出力することを期待されます。
23446 この手続きの戻り値は無視されます。
23447 @c COMMON
23448 @end table
23449
23450 @c EN
23451 Given those procedures, @code{read-eval-print-loop} runs as follows:
23452 @c JP
23453 これらの手続きが与えられると、@code{read-eval-print-loop}は以下のように
23454 動作します。
23455 @c COMMON
23456
23457 @enumerate
23458 @item
23459 @c EN
23460 Prints the prompt by calling @var{prompter}.
23461 @c JP
23462 @var{prompter}を呼んでプロンプトを出力します。
23463 @c COMMON
23464 @item
23465 @c EN
23466 Reads an expression by calling @var{reader}. If it returns EOF,
23467 exits the loop and returns from @code{read-eval-print-loop}.
23468 @c JP
23469 @var{reader}を呼んで式を読み込みます。EOFが返されたら、ループを終了し
23470 @code{read-eval-print-loop}から戻ります。
23471 @c COMMON
23472 @item
23473 @c EN
23474 Evaluates an expression by calling @var{evaluator}
23475 @c JP
23476 @var{evaluator}を呼んで式を評価します。
23477 @c COMMON
23478 @item
23479 @c EN
23480 Prints the result by calling @var{printer}, then repeats from 1.
23481 @c JP
23482 @var{printer}を呼んで結果を出力し、その後、1から繰り返します。
23483 @c COMMON
23484 @end enumerate
23485
23486 @c EN
23487 When an error is signaled from one of those procedures, it is
23488 captured and reported by the default escape handler, then
23489 the loop restarts from 1.
23490 @c JP
23491 これらの手続きのうちの1つからエラーが通知されると、そのエラーは
23492 デフォルトのエスケープハンドラにより捕捉・報告され、その後、
23493 ループが1から再開します。
23494 @c COMMON
23495
23496 @c EN
23497 It is OK to capture a continuation within those procedures
23498 and re-invoke them afterwards.
23499 @c JP
23500 これらの手続きの内部で継続を捕捉し、後で再起動することは
23501 許されています。
23502 @c COMMON
23503 @end defun
23504
23505 @c ----------------------------------------------------------------------
23506 @node Input and output, Loading Programs, Eval and repl, Core library
23507 @section Input and Output
23508 @c NODE 入出力
23509
23510 @menu
23511 * Ports::
23512 * Port and threads::
23513 * Common port operations::
23514 * File ports::
23515 * String ports::
23516 * Coding-aware ports::
23517 * Input::
23518 * Output::
23519 @end menu
23520
23521 @node Ports, Port and threads, Input and output, Input and output
23522 @subsection Ports
23523 @c NODE ポート
23524
23525 @deftp {Builtin Class} <port>
23526 @clindex port
23527 @c EN
23528 A port class. A port is Scheme's way of abstraction of I/O channel.
23529 Gauche extends a port in number of ways so that it can be used
23530 in wide range of applications.
23531 @c JP
23532 Portは、Schemeにおいて抽象化された入出力のインタフェースを提供します。
23533 Gaucheはportにいくつかの拡張を行い、いろいろなアプリケーションに対応できるようにしました。
23534 @c COMMON
23535
23536 @table @asis
23537 @c EN
23538 @item Textual and binary I/O
23539 R7RS defines textual and binary ports. In Gauche, most ports
23540 can mix both text I/O and binary I/O. It is cleaner to think
23541 the two is distinct, for they are sources/sinks of different types of
23542 objects and you don't need to mix textual and binary I/O.
23543
23544 In practice, however, a port is often a tap to an
23545 untyped pool of bytes and you may want to decide
23546 interpret it later. One example is the standard I/O; in Unix-like
23547 environment, it's up to the program to use pre-opened ports
23548 for textual or binary I/O. R7RS defines the initial ports
23549 for @code{current-input-port} etc. are textual ports; in Gauche,
23550 you can use either way.
23551 @c JP
23552 @item テキストとバイナリI/O
23553 R7RSはテキストポートとバイナリポートを定義しています。
23554 Gaucheでは、ほとんどのポートはテキストI/OとバイナリI/Oを混ぜて使えます。
23555 概念的には、異なる型のオブジェクトのソース/シンクは別物と考える方が綺麗ですし、
23556 ひとつのポートでテキストI/OとバイナリI/Oを混在して使うことは滅多にありません。
23557
23558 しかし現実には、ポートを型の無いデータの集まりにつながったものとして、
23559 データをどう解釈するかは後から決めたい、という場合があります。
23560 例えば標準入出力です。Unix的な環境では、あらかじめオープンされている標準入出力
23561 に対してテキストI/Oを行うかバイナリI/Oを行うかはプログラムに任されています。
23562 R7RSでは、@code{current-input-port}等の初期値はテキストポートであると
23563 規定しています。Gaucheではどちらにも使うことができます。
23564 @c COMMON
23565
23566 @c EN
23567 @item Conversion
23568 Some ports can be used to convert a data stream from one format
23569 to another; one of such applications is character code conversion
23570 ports, provided by @code{gauche.charconv} module
23571 (@pxref{Character code conversion}, for details).
23572 SRFI-181 also provides this feature (@pxref{Transcoded ports}).
23573 @c JP
23574 @item 変換
23575 ポートはまた、データストリームを変換するのにも使えます。例えば@code{gauche.charconv}
23576 モジュールでは、文字コード間の変換を行うポートを提供しています
23577 (詳しくは@ref{Character code conversion}を参照)。
23578 SRFI-181もこの機能を提供します(@ref{Transcoded ports}参照)。
23579 @c COMMON
23580
23581 @c EN
23582 @item Extra features
23583 There are also a ports with special functionality.
23584 A coding-aware port (@pxref{Coding-aware ports}) recognizes a special
23585 "magic comment" in the file to know which character encoding the
23586 file is written.
23587 Virtual ports (@pxref{Virtual ports}) allows you to program the
23588 behavior of the port in Scheme. It is also provided by
23589 SRFI-181 (@pxref{Custom ports}).
23590
23591 Ports can be combined to provide communication channel.
23592 @xref{Plumbing ports}, for utilities to do so.
23593 @c JP
23594 @item 追加機能
23595 また、特殊な機能を実現するポートもあります。
23596 コーディング認識ポート(@ref{Coding-aware ports}参照)は
23597 ファイル中の特殊なコメントを認識して、そのファイルがどの文字エンコーディング
23598 で書かれているかを検出します。
23599 仮想ポート(@ref{Virtual ports}参照)はSchemeでふるまいをプログラムできる
23600 ポートを提供します。同様の機能はSRFI-181にもあります
23601 (@ref{Custom ports})。
23602
23603 ポートを組み合わせて通信チャネルを作ることもできます。
23604 @ref{Plumbing ports}で説明しています。
23605 @c COMMON
23606 @end table
23607
23608 @end deftp
23609
23610 @node Port and threads, Common port operations, Ports, Input and output
23611 @subsection Port and threads
23612 @c NODE ポートとスレッド
23613
23614 @c EN
23615 The builtin port operations locks the port internally, so that port access
23616 from multiple threads will be serialized.
23617 (It is required by SRFI-18, BTW).
23618 Here, "builtin port operations" are the port access functions
23619 that takes a port and does some I/O or query on it,
23620 such as @code{read}/@code{write}, @code{read-char}/@code{write-char},
23621 @code{port->string}, etc.
23622 Note that @code{call-with-*} and @code{with-*} procedures do not
23623 lock the port during calling the given procedures, since the
23624 procedure may pass the reference of the port to the other thread,
23625 and Gauche wouldn't know if that's the case.
23626 @c JP
23627 組み込みのポート操作関数は内部的にポートをロックして、
23628 複数のスレッドからの同一のポートへのアクセスがポートの内部状態を壊さないように
23629 しています。
23630 (SRFI-18によって要求されている動作です)。
23631 ここで「組み込みのポート操作関数」はGaucheにより提供される、
23632 ポートを引数に取り何らかのI/O動作や問い合わせを行う手続きで、
23633 @code{read}/@code{write}、@code{read-char}/@code{write-char}、
23634 @code{port->string}等を含みます。
23635 但し、@code{call-with-*}や@code{with-*}系関数は、
23636 与えられた手続きを呼ぶ際にはポートをロックしません。
23637 その手続きが別のスレッドにポートを渡すかもしれず、Gaucheにはそれを知ることが
23638 できないからです。
23639 @c COMMON
23640
23641 @c EN
23642 This means you don't need to be too paranoia to worry about
23643 ports under multithreaded environment. However, keep it in
23644 mind that this locking mechanism is meant to be a safety net
23645 from breaking the port's internal state, and not to be
23646 a general mutex mechanism. It assumes port accesses rarely
23647 conflict, and uses spin lock to reduce the overhead of majority
23648 cases. If you know there will be more than one thread accessing
23649 the same port, you should use explicit mutex to avoid conflicts.
23650 @c JP
23651 従って、マルチスレッド環境でポートへのアクセス競合により
23652 ポートの内部状態を壊してしまうんじゃないか、などとあまり神経質に
23653 なる必要はありません。但し、このロック機構はあくまで予想外の
23654 アクセス競合によってポートがおかしな状態になってしまうことを
23655 防ぐための安全ネットであって、一般的な排他制御機構として使われる
23656 ことは想定していないのに注意して下さい。このロックの実装は、
23657 ポートへのアクセス競合は例外的な場合のみであると仮定し、
23658 通常のアクセスにおけるオーバヘッドを避けるために、スピンロックを
23659 使用します。もし、意図的にポートアクセスが競合するようなコードを書く場合は、
23660 明示的に排他制御をしてください。
23661 @c COMMON
23662
23663 @defun with-port-locking port thunk
23664 @c EN
23665 Executes @var{thunk}, while making the calling thread
23666 hold the exclusive lock of @var{port} during the dynamic extent
23667 of @var{thunk}.
23668
23669 Calls of the builtin port functions during the lock is held
23670 would bypass mutex operations and yield better performance.
23671
23672 Note that the lock is held during the dynamic extent of @var{thunk};
23673 so, if @var{thunk} invokes a continuation captured outside of
23674 @code{with-port-locking}, the lock is released. If the continuation
23675 captured within @var{thunk} is invoked afterwards, the lock is re-acquired.
23676
23677 @code{With-port-locking} may be nested. The lock is valid during
23678 the outermost call of @code{with-port-locking}.
23679
23680 Note that this procedure uses the port's built-in lock mechanism
23681 which uses busy wait when port access conflicts. It should be
23682 used only for avoiding fine-grain lock overhead; use explicit
23683 mutex if you know there will be conflicts.
23684 @c JP
23685 @var{port}をロックし、@var{thunk}を実行します。
23686 ロックは@var{thunk}のダイナミックエクステントの期間有効です。
23687
23688 @var{port}がロックされている期間での組み込みのポートアクセス関数の
23689 呼び出しは排他制御をバイパスするため、性能向上が見込まれます。
23690
23691 ロックの有効期間は@var{thunk}のダイナミックエクステントなので、
23692 @var{thunk}内から@code{with-port-locking}の外で捕捉された
23693 継続を呼んだ場合、ロックは解放されます。その後、@var{thunk}内で
23694 捕捉された継続が呼ばれた場合、再びロックが獲得されます。
23695
23696 @code{with-port-locking}はネスト可能です。ロックは最も外側の
23697 @code{with-port-locking}の期間中有効となります。
23698
23699 この手続きはポート組込みのロック機構を利用します。つまり、ポートアクセスが
23700 競合した場合はbusy waitになるということです。この手続きはあくまで
23701 頻繁なロックによるオーバヘッドを回避するためのものです。
23702 もし本当に競合が予測される場合は明示的に排他制御を行ってください。
23703 @c COMMON
23704 @end defun
23705
23706 @node Common port operations, File ports, Port and threads, Input and output
23707 @subsection Common port operations
23708 @c NODE ポート共通の操作
23709
23710 @defun port? obj
23711 @defunx input-port? obj
23712 @defunx output-port? obj
23713 [R7RS base]
23714 @c EN
23715 Returns true if @var{obj} is a port, an input port and an output port,
23716 respectively. @code{Port?} is not listed in the
23717 R5RS standard procedures, but mentioned in the "Disjointness of Types"
23718 section.
23719 @c JP
23720 @var{obj} がそれぞれポート、入力ポート、出力ポートなら真を返します。
23721 @code{port?}はR5RSの"Standard Procedures"の項には
23722 載っていませんが、"Disjointness of Types"の項に挙げられています。
23723 @c COMMON
23724 @end defun
23725
23726 @defun port-closed? port
23727 @c EN
23728 Returns true if @var{obj} is a port and it is already closed.
23729 A closed port can't be reopened.
23730 @c JP
23731 @var{obj}がポートであり、既に閉じられていた場合に真を返します。
23732 一度閉じたポートは再び開くことはできません。
23733 @c COMMON
23734 @end defun
23735
23736 @deffn {Parameter} current-input-port
23737 @deffnx {Parameter} current-output-port
23738 @deffnx {Parameter} current-error-port
23739 [R7RS base]
23740 @c EN
23741 Returns the current input, output and error output port, respectively.
23742
23743 R7RS defines that the initial values of these ports are textual ports.
23744 In Gauche, initial ports can handle both textual and binary I/O.
23745 @c JP
23746 現在の入力ポート、出力ポート、エラー出力ポートをそれぞれ返します。
23747
23748 R7RSではこれらのポートの初期値はテキストポートであると規定されています。
23749 Gaucheでは、これらのポートの初期値はテキスト入出力もバイナリ入出力も扱えます。
23750 @c COMMON
23751
23752 @c EN
23753 Values of the current ports can be temporarily changed by @code{parameterize}
23754 (@pxref{Parameters}), though you might want the convenience procedures
23755 such as @code{with-output-to-string} or @code{with-input-from-file}
23756 in typical cases.
23757 @c JP
23758 現在のポートの値は@code{parameterize}を使って一時的に変更できます
23759 (@ref{Parameters}参照)。もっとも、典型的な場合には
23760 より簡単な@code{with-output-to-string}や@code{with-input-from-file}などの
23761 手続きが使えるでしょう。
23762 @c COMMON
23763
23764 @example
23765 (let1 os (open-output-string)
23766 (parameterize ((current-output-port os))
23767 (display "foo"))
23768 (get-output-string os))
23769 @result{} "foo"
23770 @end example
23771 @end deffn
23772
23773 @deffn {Parameter} current-trace-port
23774 @c EN
23775 A paremeter that holds an output port which debug trace goes to.
23776 The initial value is the same as the initial value of @code{current-error-port}.
23777 @c JP
23778 デバッグトレース出力に使われる出力ポートを保持するパラメータです。
23779 初期値は@code{current-error-port}の初期値と同じです。
23780 @c COMMON
23781
23782 @c EN
23783 The @code{debug-print} feature (@pxref{Debugging aid}) and
23784 the macro trace feature (@pxref{Tracing macro expansion}) uses
23785 this port.
23786 @c JP
23787 @code{debug-print}機能(@ref{Debugging aid}参照)と、
23788 マクロトレース機能(@ref{Tracing macro expansion}参照)がこのポートを使っています。
23789 @c COMMON
23790 @end deffn
23791
23792
23793 @deffn {Parameter} standard-input-port
23794 @deffnx {Parameter} standard-output-port
23795 @deffnx {Parameter} standard-error-port
23796 @c EN
23797 Returns standard i/o ports at the time the program started.
23798 These ports are the default values
23799 of @code{current-input-port}, @code{current-output-port}
23800 and @code{current-error-port}, respectively.
23801
23802 You can also change value of these procedures by @code{parameterize},
23803 but note that (1) @code{current-*-port}s are initialized before
23804 the program execution, so changing values of @code{standard-*-port}
23805 won't affect them, and (2) changing values these procedures only affect
23806 Scheme-world, and does not change system-level stdio file descriptors
23807 low-level libraries referring.
23808 @c JP
23809 プログラム開始時点の標準入出力ポートを返します。これらの値が
23810 @code{current-input-port}、@code{current-output-port}、
23811 @code{current-error-port}のデフォルトとなります。
23812
23813 これらの手続きの値も@code{parameterize}で変えることができますが、
23814 (1) @code{current-*-port}はプログラム実行前に初期化されるので、
23815 プログラム中で@code{standard-*-port}を変更しても影響は及ばない、
23816 (2) これらの手続きの値の変更はScheme世界だけのことで、低レベルライブラリが
23817 参照しているシステムのstdioファイルディスクリプタは変更されない、
23818 という点に注意してください。
23819 @c COMMON
23820 @end deffn
23821
23822 @defun with-input-from-port port thunk
23823 @defunx with-output-to-port port thunk
23824 @defunx with-error-to-port port thunk
23825 @c EN
23826 Calls @var{thunk}. During evaluation of thunk, the current input port, current
23827 output port and current error port are set to @var{port}, respectively.
23828 Note that @var{port} won't be closed after thunk is executed.
23829 @c JP
23830 それぞれ入力、出力、エラーポートを@var{port}にセットした状態で@var{thunk}を呼び出します。
23831 @code{port}は@var{thunk}実行後にも閉じられないことに注意してください。
23832 @c COMMON
23833 @end defun
23834
23835 @defun with-ports iport oport eport thunk
23836 @c EN
23837 Does the above three functions at once.
23838 Calls @var{thunk} while the current input, output, and error ports are
23839 set to @var{iport}, @var{oport}, and @var{eport}, respectively.
23840 You may pass @code{#f} to any port argument(s) if you don't need
23841 to alter the port(s).
23842
23843 Note that @var{port} won't be closed after thunk is executed.
23844 (Unfortunately, recent Scheme standards added a similar
23845 named procedure, @code{call-with-port},
23846 which does close the port. See below.)
23847 @c JP
23848 上の3つの動作を同時に行う手続きです。
23849 入力、出力、エラーの各ポートをそれぞれ@var{iport}, @var{oport}, @var{eport}に
23850 セットして@var{thunk}を呼び出します。変更する必要がないポートの引数には
23851 @code{#f}を渡すことができます。
23852
23853 @code{port}は@var{thunk}実行後にも閉じられないことに注意してください
23854 (最近のScheme標準は良く似た名前の手続き@code{call-with-port}を追加しましたが、
23855 生憎そちらはポートを閉じる仕様になっています。@code{call-with-port}については
23856 下で説明します。)
23857 @c COMMON
23858 @end defun
23859
23860 @defun close-port port
23861 @defunx close-input-port port
23862 @defunx close-output-port port
23863 [R7RS base]
23864 @c EN
23865 Closes the port. @code{Close-port} works both input and
23866 output ports, while @code{close-input-port} and @code{close-output-port}
23867 work only for the respective ports and throws an error if another type
23868 of port is passed.
23869
23870 Theoretically, only @code{close-port} would suffice; having those three
23871 is merely for historical reason.
23872 R5RS has @code{close-input-port} and @code{close-output-port};
23873 R6RS and R7RS support all three.
23874 @c JP
23875 ポートを閉じます。@code{close-port}は入力ポートも出力ポートも閉じられますが、
23876 @code{close-input-port}と@code{close-output-port}はそれぞれ対応するポートのみに
23877 使え、異なる種類のポートが渡されたらエラーを通知します。
23878
23879 理屈の上では、@code{close-port}だけあれば十分です。3つ手続きがあるのは歴史的理由です。
23880 R5RSには@code{close-input-port} and @code{close-output-port}だけがありました。
23881 R6RSとR7RSは3つ全てをサポートしています。
23882 @c COMMON
23883 @end defun
23884
23885
23886 @defun call-with-port port proc
23887 [R7RS base]
23888 @c EN
23889 Calls @var{proc} with one argument, @var{port}. After @var{proc} returns,
23890 or it throws an uncaptured error, @var{port} is closed. Value(s) returned
23891 from @var{proc} will be the return value(s) of @code{call-with-port}.
23892
23893 @c JP
23894 @var{proc}を、@var{port}を引数として呼び出します。@var{proc}からリターンするか、
23895 エラーが投げられた場合は@var{port}がクロースざれます。
23896 @var{proc}が返す値がそのまま@code{call-with-port}の返り値となります。
23897 @c COMMON
23898 @end defun
23899
23900 @defun port-type port
23901 @c EN
23902 Returns the type of @var{port} in one of the symbols @code{file},
23903 @code{string} or @code{proc}.
23904 @c JP
23905 @var{port}のタイプを、シンボル@code{file}、@code{string}、@code{proc}の
23906 いずれかで返します。
23907 @c COMMON
23908 @end defun
23909
23910 @defun port-name port
23911 @c EN
23912 Returns the name of @var{port}. If the port is associated to a file,
23913 it is the name of the file. Otherwise, it is some description of the port.
23914 @c JP
23915 @var{port}の名前を返します。ポートがファイルに関連付けられている場合は、ポートの名前は
23916 ファイル名です。そうでない場合、ポートを説明する文字列が返されます。
23917 @c COMMON
23918 @end defun
23919
23920 @defun port-buffering port
23921 @defunx {(setter port-buffering)} port buffering-mode
23922 @c EN
23923 If @var{port} is type of file port (i.e. @code{(port-type @var{port})}
23924 returns @code{file}), these procedures gets and sets the port's
23925 buffering mode. For input ports, the port buffering mode may be
23926 either one of @code{:full}, @code{:modest} or @code{:none}.
23927 For output ports, @code{port-buffering}, it may be
23928 one of @code{:full}, @code{:line} or @code{:none}.
23929 @xref{File ports}, for explanation of those modes.
23930
23931 If @code{port-buffering} is applied to ports other than file ports,
23932 it returns @code{#f}. If the setter of port-buffering is
23933 applied to ports other than file ports, it signals an error.
23934 @c JP
23935 ファイルポート(@code{(port-type @var{port})}が@code{file}を返すもの)
23936 に対して、そのバッファリングモードを読みだし、もしくは変更します。
23937 入力ポートではバッファリングモードは
23938 @code{:full}、 @code{:modest}、@code{:none}のいずれかです。
23939 出力ポートでは
23940 @code{:full}、 @code{:line}、@code{:none}のいずれかです。
23941 バッファリングモードの詳細な説明は、@ref{File ports} を参照してください。
23942
23943 @code{port-buffering}がファイルポート以外のポートに対して呼ばれた場合は
23944 @code{#f}を返します。@code{port-buffering}のsetterが
23945 ファイルポート以外のポートに対して呼ばれた場合はエラーとなります。
23946 @c COMMON
23947 @end defun
23948
23949 @defun port-link! input-port output-port
23950 @defunx port-unlink! port
23951 @c EN
23952 An input port and an output port can be @emph{linked}. After being
23953 linked, attempt to read from @var{input-port} causes flushing
23954 @var{output-port}'s buffer. A port cannot be linked to more
23955 than one port.
23956 @c JP
23957 入力ポートと出力ポートを@emph{リンク}することができます。
23958 リンクされている入力ポートから読み出そうとすると、まず出力ポートのバッファが
23959 フラッシュされます。ポートは2つ以上のポートとリンクすることはできません。
23960 @c COMMON
23961
23962 @c EN
23963 By default, standard input port is linked to standard output port.
23964 @c JP
23965 デフォルトでは、標準入力ポートと標準出力ポートがリンクされています。
23966 @c COMMON
23967
23968 @c EN
23969 The @code{port-link!} procedure links the given input port and
23970 output port. Both port must not be already linked, or an error
23971 is signaled.
23972 @c JP
23973 @code{port-link!}は引数の入力ポートと出力ポートをリンクします。
23974 どちらのポートもリンクされていない状態でなければなりません。
23975 さもなくばエラーが投げられます。
23976 @c COMMON
23977
23978 @c EN
23979 The @code{port-unlink!} procedure removes the link between the given
23980 port and another port, if there's a link. If the given port
23981 is not linked, it does nothing.
23982 @c JP
23983 @code{port-unlink!}は、与えられたポートが他のポートとリンクされていたら
23984 そのリンクを解除します。リンクされていないポートが与えられた場合は何もしません。
23985 @c COMMON
23986
23987 @c EN
23988 You can use @code{link} slot of the port to see if a port is
23989 linked or not, and if linked, to which port.
23990 @c JP
23991 ポートの@code{link}スロットを見れば、ポートがリンクされているか、
23992 またされている場合はどのポートか、がわかります。
23993 @c COMMON
23994 @end defun
23995
23996
23997 @defun port-current-line port
23998 @c EN
23999 Returns the current line count of @var{port}. This information is
24000 only available on file-based port, and as long as you're doing
24001 sequential character I/O on it. Otherwise, this returns -1.
24002 @c JP
24003 @var{port}の現在の行番号を返します。行番号は、ファイルに関連付けられたポートで
24004 かつシーケンシャルなキャラクタI/Oを行っている場合のみ有効です。それ以外の場合は
24005 -1を返します。
24006 @c COMMON
24007 @end defun
24008
24009 @defun port-file-number port :optional dup?
24010 @c EN
24011 Returns an integer file descriptor, if the @var{port} is associated
24012 to the system file I/O. Returns @code{#f} otherwise.
24013
24014 If a true value is passed to @var{dup?}, the procedure calls @code{dup(2)}
24015 and returns a duplicated file descriptor. In such case, the returned
24016 file descriptor can be closed independently with the port, and it is
24017 caller's responsibility to close it (by @code{sys-close}) once it's done.
24018 @c JP
24019 @var{port}がファイルに関連付けられている場合、そのファイルディスクリプタ番号を
24020 返します。それ以外の場合は@code{#f}を返します。
24021
24022 @var{dup?}引数に真の値が与えられると、この手続きは@code{dup(2)}を呼んで
24023 複製したファイルディスクリプタを返します。この場合、返されたファイルディスクリプタは
24024 呼び出し側が責任を持って閉じなければなりません (@code{sys-close}が使えます)。
24025 @c COMMON
24026 @end defun
24027
24028 @defun port-position port
24029 [SRFI-192]
24030 @c EN
24031 Returns the current position of @var{port}. For the input port,
24032 the current position is where the next data will be read from,
24033 and for the output port, it is where the next data will be written to.
24034 (Note that @code{peek-char}/@code{peek-byte} won't move the current position).
24035
24036 If @var{port} is a simple file port or a string port, the position is
24037 represented as an integer byte offset from the top of the stream.
24038 If it is more complicated ports, such as the one doing the character encoding
24039 conversion, the port position may not be available, or returned
24040 object may not correspond to the byte offset.
24041 If @var{port} is a procedural (virtual) port (@pxref{Virtual ports}),
24042 the returned value can
24043 be an arbitrary Scheme object, it can only
24044 be valid to be used for @code{set-port-position!}.
24045
24046 An error is thrown if @var{port} doesn't support port positions.
24047 You can use @code{port-has-port-position?} to check if the port supports
24048 port positions.
24049
24050 For portable code: SRFI-192 defines the following conditions.
24051
24052 @itemize @bullet
24053 @item
24054 Return value is an arbitrary Scheme object and you should treat it as an
24055 opaque object. In general, it is only
24056 safe to pass it to the @code{set-port-position!} on the same port.
24057 @item
24058 If the port is a binary port and the returned position is a nonnegative
24059 exact integer, it represents the byte offset of the position.
24060 @end itemize
24061 @c JP
24062 @var{port}の現在の位置を返します。現在の位置とは、
24063 入力ポートでは次の読み込みでデータが読まれる位置、
24064 出力ポートでは次の書き込みでデータが書かれる位置です。
24065 (@code{peek-char}/@code{peek-byte}では現在の位置は動きません)。
24066
24067 @var{port}が単純なファイルポートや文字列ポートなら、
24068 ポートの位置はストリームの先頭からのバイトオフセットを表す正確な整数です。
24069 より複雑なポート、例えば文字エンコーディング変換ポートでは、
24070 ポート位置を取ることはできないか、取れた場合でもその値はバイトオフセットに対応するとは
24071 限りません。
24072 仮想ポート(@ref{Virtual ports}参照)では、現在位置は任意のSchemeオブジェクトで、
24073 @code{set-port-position!}に渡す以外に使うことはできません。
24074
24075 @var{port}がポート位置をサポートしていなければエラーが投げられます。
24076 ポート位置をサポートしているかどうかは@code{port-has-port-position?}で調べられます。
24077
24078 ポータブルなコードを書くときは、以下のSRFI-192の条件に気をつけてください。
24079
24080 @itemize @bullet
24081 @item
24082 ポート位置は任意のSchemeオブジェクトであり、
24083 同じポートに対して@code{set-port-position!}するのにだけ使うことができます。
24084 @item
24085 ただし、ポートがバイナリポートで、位置が正確な非負整数の場合は、
24086 それはバイトオフセットを表しています。
24087 @end itemize
24088 @c COMMON
24089 @end defun
24090
24091 @defun port-has-port-position? port
24092 [SRFI-192]
24093 @c EN
24094 Returns @code{#t} iff the port supports @code{port-position} procedure.
24095 @c JP
24096 ポートが@code{port-position}手続きをサポートしていれば@code{#t}を、
24097 そうでなければ@code{#f}を返します。
24098 @c COMMON
24099 @end defun
24100
24101 @defun set-port-position! port pos
24102 [SRFI-192]
24103 @c EN
24104 Sets the current position of @var{port} to @var{pos}. For the input port,
24105 the current position is where the next data will be read from,
24106 and for the output port, it is where the next data will be written to.
24107
24108 Interpretation of @var{pos} is up to the @var{port},
24109 and generally it must be an object returned previously
24110 by @code{port-position} on the same port. If @var{port} is a simple
24111 file port (a port opened on file, without CES conversion) or
24112 an input string port, you may pass a nonnegative exact integer as the byte
24113 offset.
24114
24115 An error is signaled if the position is not settable, or @var{pos} is
24116 not acceptable as a position for @var{port}. You can check if position
24117 of @var{port} is settable by @code{port-has-set-port-position!?}.
24118 @c JP
24119 @var{pos}を@var{port}の現在の位置としてセットします。
24120 現在の位置とは、
24121 入力ポートでは次の読み込みでデータが読まれる位置、
24122 出力ポートでは次の書き込みでデータが書かれる位置です。
24123
24124 @var{pos}の解釈は@var{port}に依存します。一般的には、
24125 @var{port}に対する@code{port-position}で以前返されたオブジェクトしか渡せません。
24126 ただし、@var{port}が単純なファイルポート(ファイルに対してオープンされ、
24127 文字コード変換などを行っていないポート)や入力文字列ポートならば、
24128 非負の正確な整数をバイトオフセットとして渡すことができます。
24129
24130 ポートが位置のセットを許さない場合や、@var{pos}が位置として不正な場合は
24131 エラーが投げられます。@var{port}に位置がセットできるかどうかは
24132 @code{port-has-set-port-position!?}で検査できます。
24133 @c COMMON
24134 @end defun
24135
24136 @defun port-has-set-port-position!? port
24137 [SRFI-192]
24138 @c EN
24139 Returns @code{#t} iff the port supports @code{set-port-position!} procedure.
24140 @c JP
24141 ポートが@code{set-port-position!}手続きをサポートしていれば@code{#t}を、
24142 そうでなければ@code{#f}を返します。
24143 @c COMMON
24144 @end defun
24145
24146
24147 @defun port-seek port offset :optional whence
24148 @c EN
24149 (This procedure is deprecated. Use @code{port-position} and
24150 @code{set-port-position!} for the new code.
24151 @c JP
24152 (この手続きは非推奨です。新しいコードには@code{port-position}および
24153 @code{set-port-position!}を使ってください)。
24154 @c COMMON
24155
24156 @c EN
24157 If the given @var{port} allows random access, this procedure sets
24158 the read/write pointer of the @var{port} according to the given @var{offset}
24159 and @var{whence}, then returns the updated offset (number of bytes
24160 from the beginning of the data). If @var{port} is not random-accessible,
24161 @code{#f} is returned. In the current version, file ports and
24162 input string ports are fully random-accessible. You can only query
24163 the current byte offset of output string ports.
24164 @c JP
24165 @var{port}がランダムアクセス可能なポートの場合、
24166 この手続きは@var{port}のread/writeポインタを@var{offset}と@var{whence}の値によって
24167 設定し、新たなread/writeポインタの値(データの先頭からのバイトオフセット)を
24168 返します。@var{port}がランダムアクセス可能でない場合は@code{#f}が返されます。
24169 現在のバージョンでは、ファイルポートおよび入力文字列ポートがランダムアクセス可能です。
24170 出力文字列ポートは現在のポインタの値を問い合わせる動作だけが可能です。
24171 @c COMMON
24172
24173 @c EN
24174 Note that port position is represented by byte count, not character count.
24175 @c JP
24176 ポートのポインタはバイト数で表現され、文字数とは異なることに注意して下さい。
24177 @c COMMON
24178
24179 @c EN
24180 It is allowed to seek after the data if @var{port} is an output
24181 file port. See POSIX lseek(2) document for details of the behavior.
24182 For input file port and input string port, you can't seek after the data.
24183 @c JP
24184 @var{port}が出力ファイルポートの場合は、データの終端を超えた位置までseek
24185 することが可能です。その場合の動作はPOSIXのlseek(2)に準じます。
24186 入力ファイルポートや入力文字列ポートではデータの終端以降にseekすることはできません。
24187 @c COMMON
24188
24189 @c EN
24190 The @var{whence} argument must be a small integer that represents
24191 from where @var{offset} should be counted. The following constant
24192 values are defined.
24193 @c JP
24194 @var{whence}引数は、@var{offset}の基準を指定する小さな整数です。
24195 以下の定数が定義されています。
24196 @c COMMON
24197
24198 @table @code
24199 @item SEEK_SET
24200 @c EN
24201 @var{Offset} represents the byte count from the beginning of the data.
24202 This is the default behavior when @var{whence} is omitted.
24203 @c JP
24204 @var{offset}はデータ先頭からのバイト数を指定します。
24205 @var{whence}が省略された場合のデフォルトの動作です。
24206 @c COMMON
24207
24208 @item SEEK_CUR
24209 @c EN
24210 @var{Offset} represents the byte count relative to the current read/write
24211 pointer. If you pass 0 to @var{offset}, you can get the current
24212 port position without changing it.
24213 @c JP
24214 @var{offset}は現在のread/writeポインタからの相対バイト数を指定します。
24215 @var{offset}が0であれば、ポインタを動かさずに現在のポート位置を知ることができます。
24216 @c COMMON
24217
24218 @item SEEK_END
24219 @c EN
24220 @var{Offset} represents the byte count relative to the end of the data.
24221 @c JP
24222 @var{offset}はデータの終端からの相対バイト数を指定します。
24223 @c COMMON
24224 @end table
24225 @end defun
24226
24227 @defun port-tell port
24228 @c EN
24229 Returns the current read/write pointer of @var{port} in byte count,
24230 if @var{port} is random-accessible. Returns @code{#f} otherwise.
24231 This is equivalent to the following call:
24232 @c JP
24233 @var{port}の現在のread/writeポインタの値をバイト数で返します。
24234 @var{port}がランダムアクセス可能でない場合は@code{#f}が返されます。
24235 これは以下の呼び出しと等価です。
24236 @c COMMON
24237 @example
24238 (port-seek @var{port} 0 SEEK_CUR)
24239 @end example
24240 @end defun
24241
24242 @c EN
24243 @emph{Note on the names}: @code{Port-seek} is called
24244 @code{seek}, @code{file-position} or @code{input-port-position}/
24245 @code{output-port-position} on some implementations.
24246 @code{Port-tell} is called @code{tell}, @code{ftell} or
24247 @code{set-file-position!}. Some implementations have
24248 @code{port-position} for different functionality.
24249 CommonLisp has @code{file-position}, but it is not suitable
24250 for us since @var{port} need not be a file port. @code{Seek} and
24251 @code{tell} reflects POSIX name, and with Gauche naming convention
24252 we could use @code{sys-seek} and @code{sys-tell}; however, @var{port}
24253 deals with higher level of abstraction than system calls, so I dropped
24254 those names, and adopted new names.
24255 @c JP
24256 @emph{名前に関するメモ}: @code{port-seek}は他の処理系で
24257 @code{seek}、@code{file-position}、@code{input-port-position}/
24258 @code{output-port-position}等と呼ばれています。
24259 @code{port-tell}は@code{tell}、@code{ftell}、@code{set-file-position!}等と
24260 呼ばれています。いくつかの処理系は@code{port-position}という手続きを
24261 持っていますが、@code{port-seek}とは別の機能を実現しています。
24262 @code{file-position}はCommonLisp由来の名前ですが、
24263 fileポート以外のものも扱うため採用しませんでした。
24264 また、@code{seek}と@code{tell}はPOSIXの名前由来であり、
24265 Gaucheの名前付け規則を使って@code{sys-seek}と@code{sys-tell}としても
24266 よさそうですが、portの操作はシステムコールレベルよりも抽象度が高いため
24267 これも採用しませんでした。結局、新しい名前を採用することにしました。
24268 @c COMMON
24269
24270 @defun copy-port src dst :key (unit 0) (size #f)
24271 @c EN
24272 Copies data from an input port @var{src} to an output port @var{dst},
24273 until eof is read from @var{src}.
24274 @c JP
24275 @var{src}からEOFまでデータを読みだし、@var{dst}へ書き出します。
24276 @c COMMON
24277
24278 @c EN
24279 The keyword argument @var{unit} may be zero, a positive exact integer,
24280 a symbol @code{byte} or a symbol @code{char}, to specify the unit
24281 of copying. If it is an integer, a buffer of the size
24282 (in case of zero, a system default size) is used to copy,
24283 using block I/O. Generally it is the fastest if you copy
24284 between normal files. If @var{unit} is a symbol @code{byte},
24285 the copying is done byte by byte, using C-version of @code{read-byte}
24286 and @code{write-byte}. If @var{unit} is a symbol @code{char},
24287 the copying is done character by character, using C-version of
24288 @code{read-char} and @code{write-char}.
24289 @c JP
24290 キーワード引数@var{unit}は0以上の整数か、シンボル@code{byte}もしくは@code{char}
24291 でなければなりません。これはデータをコピーする単位を指定します。
24292 整数ならば、その大きさ(0の場合はシステム規定の大きさ)のバッファが確保され、
24293 ブロックI/Oを使って転送が行われます。通常のファイルをコピーする場合などはこれが
24294 速いでしょう。もし@var{unit}がシンボル@code{byte}であれば、バイト毎
24295 に読みだし/書き込みが行われます。@var{unit}がシンボル@code{char}であれば、
24296 キャラクタ毎に読みだし/書き込みが行われます。
24297 @c COMMON
24298
24299 @c EN
24300 If nonnegative integer is given to the keyword argument @var{size},
24301 it specifies the maximum amount of data to be copied. If @var{unit}
24302 is a symbol @code{char}, @var{size} specifies the number of characters.
24303 Otherwise, @var{size} specifies the number of bytes.
24304 @c JP
24305 キーワード引数@var{size}に非負の整数が与えられた場合、それはコピーされるデータの
24306 最大量を指定します。@var{unit}がシンボル@code{char}の場合は@var{size}は
24307 コピーされる文字数を、そうでない場合はバイト数を指定します。
24308 @c COMMON
24309
24310 @c EN
24311 Returns number of characters copied when @var{unit} is a symbol
24312 @code{char}. Otherwise, returns number of bytes copied.
24313 @c JP
24314 @var{unit}がシンボル@code{char}の場合はコピーされた文字数を返し、
24315 そうでない場合はコピーされたバイト数を返します。
24316 @c COMMON
24317 @end defun
24318
24319 @node File ports, String ports, Common port operations, Input and output
24320 @subsection File ports
24321 @c NODE ファイルポート
24322
24323 @menu
24324 * Opening file ports::
24325 * Character encoding of file I/O::
24326 * File descriptor ports::
24327 @end menu
24328
24329 @node Opening file ports, Character encoding of file I/O, File ports, File ports
24330 @subsubsection Opening file ports
24331 @c NODE ファイルポートのオープン
24332
24333 @defun open-input-file filename :key if-does-not-exist buffering element-type encoding conversion-buffer-size conversion-illegal-output
24334 @defunx open-output-file filename :key if-does-not-exist if-exists buffering element-type encoding conversion-buffer-size conversion-illegal-output
24335 [R7RS+ file]
24336 @c EN
24337 Opens a file @var{filename} for input or output, and
24338 returns an input or output port associated with it, respectively.
24339
24340 The keyword arguments specify precise behavior.
24341 @c JP
24342 ファイル@var{filename}を入力または出力用にオープンし、
24343 入力ポートまたは出力ポートを作成して返します。
24344
24345 キーワード引数により、動作を細かく指定できます。
24346 @c COMMON
24347
24348 @table @code
24349 @item :if-exists
24350 @c EN
24351 This keyword argument can be specified only for @code{open-output-file}, and
24352 specifies the action when the @var{filename} already exists.
24353 One of the following value can be given.
24354 @c JP
24355 このキーワード引数は@code{open-output-file}のみに指定でき、
24356 @var{filename}が既に存在した場合の動作を指定します。次の値のいずれかを与えることができます。
24357 @c COMMON
24358 @table @code
24359 @item :supersede
24360 @c EN
24361 The existing file is truncated. This is the default behavior.
24362 @c JP
24363 既存のファイルが長さ0に縮められます。これが既定の動作です。
24364 @c COMMON
24365 @item :append
24366 @c EN
24367 The output data will be appended to the existing file.
24368 @c JP
24369 既存のファイルにこれから書き出す内容が追加されます。
24370 @c COMMON
24371 @item :overwrite
24372 @c EN
24373 The output data will overwrite the existing content.
24374 If the output data is shorter than the existing file, the rest of
24375 existing file remains.
24376 @c JP
24377 既存のファイルにこれから書き出す内容が上書きされます。
24378 書き出されるデータが既存のファイルのデータよりも短い場合、
24379 残りの部分はそのまま残されます。
24380 @c COMMON
24381 @item :error
24382 @c EN
24383 An error is signaled.
24384 @c JP
24385 エラーが報告されます。
24386 @c COMMON
24387 @item #f
24388 @c EN
24389 No action is taken, and the function returns @code{#f}.
24390 @c JP
24391 何もせず、@code{#f}を返します。
24392 @c COMMON
24393 @end table
24394
24395 @item :if-does-not-exist
24396 @c EN
24397 This keyword argument specifies the action when @var{filename} does not exist.
24398 @c JP
24399 このキーワード引数は@var{filename}が存在しない場合の動作を指定します。
24400 @c COMMON
24401 @table @code
24402 @item :error
24403 @c EN
24404 An error is signaled. This is the default behavior of
24405 @code{open-input-file}.
24406 @c JP
24407 エラーを報告します。これが@code{open-input-file}の既定の動作です。
24408 @c COMMON
24409 @item :create
24410 @c EN
24411 A file is created. This is the default behavior of @code{open-output-file}.
24412 The check of file existence and creation is done atomically; you can
24413 exclusively create the file by specifying @code{:error} or @code{#f} to
24414 @var{if-exists}, along this option.
24415 You can't specify this value for @code{open-input-file}.
24416 @c JP
24417 ファイルが作成されます。これが@code{open-output-file}の既定の動作です。
24418 ファイルの存在のチェックと作成はアトミックに行われます。
24419 このオプションに加え、@var{if-exists}オプションに@code{:error}か@code{#f}を
24420 指定することで、排他的にファイルを作成することができます。
24421 @code{open-input-file}に対してはこの値を指定することはできません。
24422 @c COMMON
24423 @item #f
24424 @c EN
24425 No action is taken, and the function returns @code{#f}.
24426 @c JP
24427 何もせず、@code{#f}を返します。
24428 @c COMMON
24429 @end table
24430
24431 @item :buffering
24432 @c EN
24433 This argument specifies the buffering mode. The following values are
24434 allowed.
24435 The port's buffering mode can be get/set by @code{port-buffering}.
24436 (@pxref{Common port operations}).
24437 @c JP
24438 この引数はバッファリングモードを指定します。以下の値が設定できます。
24439 ポートのバッファリングモードは手続き@code{port-buffering}
24440 (@ref{Common port operations}参照)によって
24441 読みだし/変更可能です。
24442 @c COMMON
24443 @table @code
24444 @item :full
24445 @c EN
24446 Buffer the data as much as possible. This is the default mode.
24447 @c JP
24448 出来る限りデータをバッファリングします。これがデフォルトのモードです。
24449 @c COMMON
24450 @item :none
24451 @c EN
24452 No buffering is done. Every time the data is written (to an output port)
24453 or read (from an input port), the underlying system call is used.
24454 Process's standard error port is opened in this mode by default.
24455 @c JP
24456 バッファリングを行いません。出力ポートにデータが書き出されるか、
24457 入力ポートからデータが読み込まれる度に、下位にあるシステムコールが呼ばれます。
24458 プロセスの標準エラーポートはこのモードでオープンされています。
24459 @c COMMON
24460 @item :line
24461 @c EN
24462 This is valid only for output ports. The written data is buffered, but
24463 the buffer is flushed whenever a newline character is written.
24464 This is suitable for interactive output port. Process's standard
24465 output port is opened in this mode by default.
24466 (Note that this differs from the line buffering mode of C stdio, which
24467 flushes the buffer as well when input is requested from the same file
24468 descriptor.)
24469 @c JP
24470 このモードは出力ポートにのみ有効です。書き出されたデータはバッファに
24471 貯められますが、改行文字が書かれたらフラッシュされます。
24472 このモードは対話的な出力ポートなどに便利です。
24473 プロセスの標準出力ポートはこのモードでオープンされています。
24474 (これは、Cのstdioライブラリの「ラインバッファリング」とちょっと違うことに
24475 注意してください。stdioでは同じファイルディスクリプタから入力が行われる時も
24476 バッファはフラッシュされますが、Gaucheではそうはなりません)。
24477 @c COMMON
24478 @item :modest
24479 @c EN
24480 This is valid only for input ports. This is almost the same as the mode
24481 @code{:full}, except that @code{read-uvector} may return less data
24482 than requested if the requested amount of data is not immediately available.
24483 (In the @code{:full} mode, @code{read-uvector} waits the entire data to be
24484 read). This is suitable for the port connected to a pipe or network.
24485 @c JP
24486 このモードは入力ポートにのみ有効です。ほとんど@code{:full}バッファリングモードと
24487 同じですが、@code{read-uvector}はポートに要求されたデータより少ないデータしか
24488 無かった場合、要求された量がたまるまで待つのではなく、今あるデータだけを
24489 返します(@code{:full}の場合は@code{read-uvector}はすべてのデータが到着するまで
24490 待ちます)。このモードはポートがパイプやネットワークに接続されている場合に
24491 便利です。
24492 @c COMMON
24493 @end table
24494
24495 @item :element-type
24496 @c EN
24497 This argument specifies the type of the file.
24498 @c JP
24499 この引数はファイルのタイプを指定します。
24500 @c COMMON
24501 @table @code
24502 @item :binary
24503 @c EN
24504 The file is opened in "binary" mode. (This is the default)
24505 @c JP
24506 ファイルはバイナリモードでオープンされます。(これがデフォルトです。)
24507 @c COMMON
24508 @item :character
24509 @c EN
24510 The file is opened in "character" (or "text") mode.
24511 @c JP
24512 ファイルはキャラクタモード(テキストモード)でオープンされます。
24513 @c COMMON
24514 @end table
24515 @c EN
24516 Note: This flag makes difference only on Windows-native platforms,
24517 and only affect the treatment of line terminators. In character
24518 mode, writing @code{#\newline} on the output causes CR + LF characters to be
24519 written, instead of just LF. And reading CR + LF sequence returns
24520 just @code{#\newline}.
24521
24522 On Unix, both mode are the same.
24523
24524 Note that Gauche doesn't distinguish character (textual) port and
24525 binary port. So this flag really matters only on Windows line
24526 terminators.
24527 @c JP
24528 註: このフラグで違いが出るのはWindowsネイティブ版のみです。
24529 キャラクタモードでは、@code{#\newline}文字をを出力するとCR + LFが書き出され、
24530 またCR + LFシーケンスは単一の@code{#\newline}として読まれます。
24531
24532 Unixでは両者に違いはありません。
24533
24534 なお、Gaucheにはテキストポートとバイナリポートの区別はありません。
24535 したがってこのフラグはWindowsの行終端文字の扱いのみのためにあります。
24536 @c COMMON
24537
24538 @item :encoding
24539 @c EN
24540 This argument specifies character encoding of the file. The argument
24541 is a string or a symbol that names a character encoding scheme (CES).
24542
24543 For @code{open-input-file}, it can be a wildcard CES (e.g. @code{*jp})
24544 to guess the file's encoding heuristically
24545 (@pxref{Autodetecting the encoding scheme}),
24546 or @code{#t}, in which case we assume the input file itself has magic
24547 encoding comment and use @code{open-coding-aware-port}
24548 (@pxref{Coding-aware ports}).
24549
24550 If this argument is given, Gauche automatically loads
24551 @code{gauche.charconv} module and converts the input/output characters
24552 as you read to or write from the port.
24553 See @ref{Supported character encoding schemes}, for the details of
24554 character encoding schemes.
24555
24556 If this argument is omitted, the value of the parameter
24557 @code{default-file-encoding} is assumed for the file's character encoding
24558 (@pxref{Character encoding of file I/O}).
24559 @c JP
24560 この引数はファイルの文字エンコーディングを指定します。引数は文字列かシンボルで、
24561 文字エンコーディングスキーム(CES)の名前を渡します。
24562
24563 @code{open-input-file}では、ここにワイルドカードCES (例: @code{*jp}) を
24564 渡して、入力ファイルのエンコーディングを推測させることもできます
24565 (@ref{Autodetecting the encoding scheme}参照)。
24566 また、ここに@code{#t}を渡すと、入力ポートはCoding aware portでラップされます
24567 (@ref{Coding-aware ports}参照)。入力ファイルがエンコーディング指定の
24568 マジックコメントを持っていることが期待できる場合に便利です。
24569
24570 この引数が与えられた場合、Gaucheは自動的に@code{gauche.charconv}モジュールを
24571 ロードし、ポートの入出力時に文字コード変換を行います。
24572 CESについて詳しくは@ref{Supported character encoding schemes}を参照してください。
24573
24574 この引数が省略された場合は、パラメータ@code{default-file-encoding}
24575 の値が指定されたものとみなされます (@ref{Character encoding of file I/O}参照)。
24576 @c COMMON
24577
24578 @item :conversion-buffer-size
24579 @c EN
24580 This argument may be used with the @var{encoding} argument to specify
24581 the buffer size of character encoding conversion. It is passed as
24582 a @var{buffer-size} argument of the conversion port constructors
24583 (@pxref{Conversion ports}).
24584
24585 Usually you don't need to give this argument; but if you need to guess
24586 the input file encoding, larger buffer size may work better since guessing
24587 routine can have more data before deciding the encoding.
24588 @c JP
24589 この引数は、文字エンコーディング変換に使うバッファサイズを指定するために
24590 @var{encoding}引数と共に使うことができます。渡された値はそのまま
24591 文字コード変換ポートのコンストラクタの@var{buffer-size}引数に渡されます
24592 (@ref{Conversion ports}参照)。
24593
24594 この引数を指定する必要は滅多にありませんが、入力ファイルの文字エンコーディングを
24595 推測しなければならない場合、大きめのバッファサイズの方が精度が上がります。
24596 推測ルーチンがより多くのデータを見て文字エンコーディングを決定できるからです。
24597 @c COMMON
24598
24599 @item :conversion-illegal-output
24600 @c EN
24601 This argument may be used with the @var{encoding} argument to specify
24602 the behavior when the source character can't be mapped to the destination
24603 character. It must be either a symbol @code{raise} or a symbol
24604 @code{replace}, and is passed as @var{illegal-output} argument to the
24605 conversion port. @xref{Conversion ports}, for the details.
24606 @c JP
24607 この引数は@var{encode}引数と一緒に使うことで、
24608 文字エンコーディング変換において、元の文字に対応する文字が変換先に無い場合の振る舞いを
24609 指定できます。値はシンボル@code{raise}か@code{replace}でなければならず、
24610 それはそのまま変換ポートの@var{illegal-output}引数に渡されます。
24611 詳しくは@ref{Conversion ports}を参照してください。
24612 @c COMMON
24613 @end table
24614
24615 @c EN
24616 By combination of @var{if-exists} and @var{if-does-not-exist} flags,
24617 you can implement various actions:
24618 @example
24619 (open-output-file "foo" :if-exists :error)
24620 @result{} ;@r{opens "foo" exclusively, or error}
24621
24622 (open-output-file "foo" :if-exists #f)
24623 @result{} ;@r{opens "foo" exclusively, or returns} #f
24624
24625 (open-output-file "foo" :if-exists :append
24626 :if-does-not-exist :error)
24627 @result{} ;@r{opens "foo" for append only if it already exists}
24628 @end example
24629 @c JP
24630 @var{if-exists}と@var{if-does-not-exist}フラグの組合せにより、
24631 色々な動作を実現できます。
24632 @example
24633 (open-output-file "foo" :if-exists :error)
24634 @result{} ;@r{"foo"を排他的にオープンするかエラーを報告する}
24635
24636 (open-output-file "foo" :if-exists #f)
24637 @result{} ;@r{"foo"を排他的にオープンするか}#f@r{を返す}
24638
24639 (open-output-file "foo" :if-exists :append
24640 :if-does-not-exist :error)
24641 @result{} ;@r{"foo"が既に存在する場合に限り、それを追加モードでオープン}
24642 @end example
24643 @c COMMON
24644
24645 @c EN
24646 To check the existence of a file without opening it,
24647 use @code{sys-access} or @code{file-exists?} (@pxref{File stats}).
24648 @c JP
24649 ファイルをオープンせずにその存在をチェックするには、
24650 @code{sys-access}か@code{file-exists?}を使って下さい (@ref{File stats}参照)。
24651 @c COMMON
24652
24653 @c EN
24654 Note for portability: Some Scheme implementations (e.g. STk) allows
24655 you to specify a command to @var{filename} and reads from, or
24656 writes to, the subprocess standard input/output. Some other scripting
24657 languages (e.g. Perl) have similar features. In Gauche,
24658 @code{open-input-file} and @code{open-output-file} strictly operates
24659 on files (what the underlying OS thinks as files).
24660 However, you can use ``process ports'' to invoke
24661 other command in a subprocess and to communicate it.
24662 @xref{Process ports}, for details.
24663 @c JP
24664 移植性に関する註:Schemeシステムによっては、@var{filename}のところに
24665 シェルコマンドを指定して、サブプロセスの標準入出力と通信できるようにするものが
24666 あります。他のスクリプティング言語(例:Perl)にも同様の機能があります。
24667 Gaucheでは、@code{open-input-file}と@code{open-output-file}は
24668 あくまでファイル (OSがファイルとして扱うもの) のみに対して使えます。
24669 サブプロセスと通信するためには、「プロセスポート」という機能が提供されています。
24670 @ref{Process ports}を参照して下さい。
24671 @c COMMON
24672 @end defun
24673
24674 @defun call-with-input-file string proc :key if-does-not-exist buffering element-type encoding conversion-buffer-size
24675 @defunx call-with-output-file string proc :key if-does-not-exist if-exists buffering element-type encoding conversion-buffer-size
24676 [R7RS+ file]
24677 @c EN
24678 Opens a file specified by @var{string} for input/output,
24679 and call @var{proc} with one argument, the file port. When @var{proc}
24680 returns, or an error is signaled from @var{proc} that is not captured
24681 within @var{proc}, the file is closed.
24682 @c JP
24683 @var{string}で示されるファイルを入力または出力用にオープンし、
24684 作成されたポートを引数として手続き@var{proc}を呼び出します。
24685 @var{proc}が正常終了するか、@var{proc}内で捕捉されないエラーが起きた場合に
24686 ファイルはクローズされます。
24687 @c COMMON
24688
24689 @c EN
24690 The keyword arguments have the same meanings of
24691 @code{open-input-file} and @code{open-output-file}'s. Note that
24692 if you specify @code{#f} to @var{if-exists} and/or @var{if-does-not-exist},
24693 @var{proc} may receive @code{#f} instead of a port object when
24694 the file is not opened.
24695 @c JP
24696 キーワード引数は
24697 @code{open-input-file}及び@code{open-output-file}のものと同じ意味を持ちます。
24698 @var{if-exists}や@var{if-does-not-exist}に@code{#f}を指定した場合、
24699 ファイルがオープンされなかった場合は@var{proc}にポートではなく@code{#f}が渡される
24700 ことに注意して下さい。
24701 @c COMMON
24702
24703 @c EN
24704 Returns the value(s) @code{proc} returned.
24705 @c JP
24706 @var{proc}が返す値を返します。
24707 @c COMMON
24708 @end defun
24709
24710 @defun with-input-from-file string thunk :key if-does-not-exist buffering element-type encoding conversion-buffer-size
24711 @defunx with-output-to-file string thunk :key if-does-not-exist if-exists buffering element-type encoding conversion-buffer-size
24712 [R7RS file]
24713 @c EN
24714 Opens a file specified by @var{string} for input or output
24715 and makes the opened port as the current input or output port,
24716 then calls @var{thunk}. The file is closed when @var{thunk}
24717 returns or an error is signaled from @var{thunk} that is not
24718 captured within @var{thunk}.
24719
24720 Returns the value(s) @code{thunk} returns.
24721
24722 The keyword arguments have the same
24723 meanings of @code{open-input-file} and @code{open-output-file}'s,
24724 except that when @code{#f} is given to @var{if-exists} and
24725 @var{if-does-not-exist} and the opening port is failed,
24726 @var{thunk} isn't called at all and @code{#f} is returned
24727 as the result of @code{with-input-from-file} and
24728 @code{with-output-to-file}.
24729 @c JP
24730 @var{string}で示されるファイルを入力または出力用にオープンし、オープンされた
24731 ポートを現在の入力または出力ポートに設定して、@var{thunk}を呼び出します。
24732 @var{thunk}が戻るか、@var{thunk}内で捕捉されないエラーが生じた際にファイルは閉じられます。
24733
24734 @var{thunk}が返す値を返します。
24735
24736 キーワード引数は
24737 @code{open-input-file}及び@code{open-output-file}のものと同じ意味を持ちます。
24738 但し@var{if-exists}や@var{if-does-not-exist}に@code{#f}が指定され、
24739 ファイルがオープンできなかった場合は、@var{thunk}は呼ばれずに
24740 直ちに@code{#f}が返されます。
24741 @c COMMON
24742 @end defun
24743
24744 @c EN
24745 @emph{Notes on semantics of closing file ports:}
24746 R7RS states, in the description of @code{call-with-port} et al.,
24747 that @emph{"If @emph{proc} does not return, then the port will
24748 not be closed automatically unless it is possible
24749 to prove that the port will never again be used for read or write
24750 operation."}
24751 @c JP
24752 @emph{ポートを閉じるセマンティクスについて:}
24753 R7RSは@code{call-with-port}等の説明において、次のように述べています。
24754 「@emph{procが戻って来なかった場合、今後ポートが読み書きに一切使われないことが
24755 証明できない限りは、ポートは自動的には閉じられない}」。
24756 @c COMMON
24757
24758 @c EN
24759 Gauche's implementation slightly misses this criteria; the mere fact
24760 that an uncaptured error is thrown in @var{proc} does not prove
24761 the port will never be used. Nevertheless, it is very difficult
24762 to think the situation that you can do meaningful operation on
24763 the port after such an error is signaled; you'd have no idea
24764 what kind of state the port is in. In practical programs, you
24765 should capture error explicitly inside @var{proc} if you still want
24766 to do some meaningful operation with the port.
24767 @c JP
24768 Gaucheの実装は若干この条件には反しています。捕捉されないエラーが@var{proc}から
24769 発せられたというだけでは、そのポートが今後一切使われないかどうかはわかりません。
24770 しかし実際には、そのようなエラーが発せられた後でポートに対して意味のある操作をするのは
24771 非現実的です。ポートがどのような状態にあるかわからないわけですから。
24772 現実的なプログラムでは、ポートに対して意味のある操作をしつづけたいのなら、
24773 @var{proc}の中で明示的にエラーをハンドルすべきでしょう。
24774 @c COMMON
24775
24776 @c EN
24777 Note that if a continuation captured outside @code{call-with-input-file}
24778 et al. is invoked inside @var{proc}, the port is not closed.
24779 It is possible that the control returns later into the @var{proc},
24780 if a continuation is captured in it (e.g. coroutines).
24781 The low-level exceptions (@pxref{Low-level exception handling mechanism})
24782 also doesn't ensure closing the port.
24783 @c JP
24784 @code{call-with-input-file}の外で捕捉された継続を@var{proc}内で呼んだ場合には
24785 ポートは閉じられないことに注意して下さい。後で@var{proc}へと制御が戻ってくるかも
24786 しれないからです (コルーチン等)。また、
24787 低レベルの例外メカニズム(@ref{Low-level exception handling mechanism}
24788 参照)を利用した場合、エラー時にポートを閉じるのはプログラマの責任になります。
24789 @c COMMON
24790
24791 @node Character encoding of file I/O, File descriptor ports, Opening file ports, File ports
24792 @subsubsection Character encoding of file I/O
24793 @c NODE ファイルI/Oにおける文字エンコーディング
24794
24795 @deffn {Parameter} default-file-encoding
24796 @c EN
24797 A character encoding name assumed when you omit @var{encoding}
24798 keyword arguments in file port opening procedures, such as
24799 @code{open-input-port}, @code{call-with-output-file}, etc.
24800 The default value is @code{utf-8}.
24801 @c JP
24802 ファイルポートをオープンする、@code{open-input-port}や@code{call-with-output-file}
24803 等の手続きに@var{encoding}キーワード引数を指定しなかった場合、
24804 このパラメータの値が文字エンコーディング名として使われます。
24805 デフォルトの値は@code{utf-8}です。
24806 @c COMMON
24807
24808 @c EN
24809 In most circumstances, you don't need to change the value of this parameter.
24810 These days, utf-8 became de facto in data exchange, so
24811 you need to specify @var{encoding} argument explicitly only when you know
24812 you're dealing with non-utf8 data.
24813 @c JP
24814 ほとんどの場合、このパラメータの値を変える必要はないでしょう。
24815 データ交換にはutf-8がデファクトとなった現代では、utf8でないデータを
24816 扱う時のみ@var{encoding}を指定するだけで事足ります。
24817 @c COMMON
24818
24819 @c EN
24820 However, suppose you have exising system that assumes, say, latin-1 encoding,
24821 and you've been using Gauche with @code{none} CES encoding (which means
24822 Gauche just treats an octet as a character).
24823 Gauche uses utf-8 exclusively in its internal encoding since 1.0,
24824 and if you switch to it, you would need to check every file opening
24825 calls to make sure they have @code{:encoding latin-1}. That would be a lot
24826 of work.
24827 @c JP
24828 ただ、例えばこれまでGaucheの内部エンコーディングを@code{none}でコンパイルしていて
24829 (これはGaucheが文字を8ビット固定長で扱うことを意味します)、システムがLatin-1エンコーディング
24830 でデータを扱っていたとしましょう。
24831 Gaucheは1.0から内部エンコーディングをutf-8のみにしたので、
24832 バージョンを上げる際に、
24833 全てのファイルオープン手続きを調べて@code{:encoding latin-1}をつけて回らないとなりません。
24834 それはかなり大きな変更となるでしょう。
24835 @c COMMON
24836
24837 @c EN
24838 You can change this parameter to @code{latin-1} instead, and the exiting
24839 calls work as if @code{:encoding latin-1} is attached unless it already
24840 has explicit @code{:encoding}.
24841 @c JP
24842 そういう場合には、このパラメータを@code{latin1}にセットすることで、
24843 これまで@code{:encoding}がついていなかったファイルオープン手続きを
24844 あたかも@code{:encoding latin-1}が付加されているかのように振る舞わせることができます。
24845 @c COMMON
24846
24847 @c EN
24848 Note that source code is loaded using coding aware ports
24849 (@pxref{Coding-aware ports}), with the default encoding being
24850 Gauche's native encoding. The value of this parameter doesn't have
24851 effect. Use encoding magic comment to specify the encoding of
24852 source code.
24853 @c JP
24854 ソースコードをloadする場合は、内部エンコーディングをデフォルトとする
24855 コーディング認識ポートが使われることに注意してください (@ref{Coding-aware ports}参照)。
24856 内部エンコーディングとソースエンコーディングが異なる場合は、
24857 文字エンコーディングを指定する呪文コメント@code{coding:coding-name}を使ってください。
24858 @c COMMON
24859 @end deffn
24860
24861
24862 @node File descriptor ports, , Character encoding of file I/O, File ports
24863 @subsubsection File descriptor ports
24864 @c NODE ファイルディスクリプタポート
24865
24866 @defun open-input-fd-port fd :key buffering name owner?
24867 @defunx open-output-fd-port fd :key buffering name owner?
24868 @c EN
24869 Creates and returns an input or output port on top of the given
24870 file descriptor. @var{Buffering} specifies the buffering mode
24871 as described in @code{open-input-file} entry above; the default
24872 is @code{:full}. @var{Name} is used for the created port's name
24873 and returned by @code{port-name}.
24874
24875 A boolean flag @code{owner?} specifies whether @var{fd} should be
24876 closed when the port is closed. If it is @code{#f}, closing port
24877 doesn't close @var{fd}. If it s @code{#t}, closing port automatically
24878 closes @code{fd}. It can also be a symbol @code{dup}, in which case
24879 @code{fd} is duplicated (by @code{dup(2)} system call) and the
24880 resulting port owns the new fd which will be closed automatically--but
24881 @var{fd} itself remains open, and can be closed independently.
24882 @c JP
24883 与えられたファイルディスクリプタにアクセスする入力または出力ポートを
24884 作成して返します。@var{buffering} は@code{open-input-file} の項で
24885 説明されたポートのバッファリングモードを指定します。デフォルトは@code{:full}です。
24886 @var{name}は@code{port-name}によって返されるポートの名前を指定します。
24887
24888 @var{owner?} は、このポートを閉じた時に@var{fd}もクローズすべきかどうかを
24889 指定します。@code{#f}ならポートを閉じても@var{fd}はそのままです。
24890 @code{#t}ならポートを閉じた時に@var{fd}も自動的に閉じられます。
24891 また、シンボル@code{dup}を渡すこともできて、その場合は内部で@var{fd}が
24892 @code{dup(2)}システムコールによって複製され、新しいfdをポートが所有します。
24893 新たなfdはポートが閉じると自動的に閉じられますが、@var{fd}自体は閉じられません。
24894 また、@var{fd}をポートとは独立して閉じることができます。
24895 @c COMMON
24896 @end defun
24897
24898 @defun port-fd-dup! toport fromport
24899 @c EN
24900 Interface to the system call @code{dup2(2)}.
24901 Atomically closes the file descriptor associated to @var{toport},
24902 creates a copy of the file descriptor associated to @var{fromport},
24903 and sets the new file descriptor to @var{toport}.
24904 Both @var{toport} and @var{fromport} must be file ports.
24905 Before the original file descriptor of @var{toport} is closed,
24906 any buffered output (when @var{toport} is an output port) is flushed,
24907 and any buffered input (when @var{toport} is an input port) is discarded.
24908
24909 `Copy' means that, even the two file descriptors differ in their values,
24910 they both point to the same system's open file table entry. For example
24911 they share the current file position; after @var{port-fd-dup!},
24912 if you call @code{port-seek} on @var{fromport}, the change is also visible
24913 from @var{toport}, and vice versa. Note that this 'sharing' is in the
24914 system-level; if either @var{toport} or @var{fromport} is buffered,
24915 the buffered contents are not shared.
24916
24917 This procedure is mainly intended for programs that needs to control
24918 open file descriptors explicitly; e.g. a daemon process would want to redirect
24919 its I/O to a harmless device such as @file{/dev/null}, and a shell process
24920 would want to set up file descriptors before executing the child process.
24921 @c JP
24922 システムの@code{dup2(2)}のインタフェースです。
24923 アトミックに@var{toport}のファイルディスクリプタをクローズし、@var{fromport}の
24924 ファイルディスクリプタを複製したものを@var{toport}に設定します。
24925 @var{toport}、@var{fromport}はいずれもファイルポートでなければなりません。
24926
24927 ファイルディスクリプタが「複製」されると、ふたつのディスクリプタ番号が異なっていても
24928 それらはシステムのオープンファイルテーブルの同じエントリを指します。
24929 例えば、現在の(システムレベルでの)ファイル上の読み書き位置は共有されます。
24930 @code{port-fd-dup!}の後で、@code{port-seek}を@var{fromport}に
24931 対して呼び出せば、その変更は@var{toport}の読み書き位置にも影響を与えるでしょうし、
24932 その逆もまたあります。ただし、共有されるのはシステムレベルの情報のみで、
24933 @var{toport}や@var{fromport}がバッファリングされている場合、バッファの内容は
24934 共有されません。
24935
24936 この手続きは、主にファイルディスクリプタを明示的に制御する必要のあるプログラム
24937 のために用意されています。例えばデーモンプロセスがその入出力を@file{/dev/null}などの
24938 無難なデバイスに切り替えたり、シェルプロセスが子プロセスを@code{exec}する前に
24939 そのファイルディスクリプタをセットアップしたりするような場合です。
24940 @c COMMON
24941 @end defun
24942
24943 @node String ports, Coding-aware ports, File ports, Input and output
24944 @subsection String ports
24945 @c NODE 文字列ポート
24946
24947 @c EN
24948 String ports are the ports that you can read from or write to
24949 memory.
24950 @c JP
24951 文字列ポートは、メモリ上のデータと関連付けられたポートです。
24952 @c COMMON
24953
24954 @defun open-input-string string :key name
24955 [R7RS base][SRFI-6]
24956 @c EN
24957 Creates an input string port that has the content @var{string}.
24958 This is a more efficient way to access a string in order
24959 rather than using @code{string-ref} with incremental index.
24960
24961 @example
24962 (define p (open-input-string "foo x"))
24963 (read p) @result{} foo
24964 (read-char p) @result{} #\space
24965 (read-char p) @result{} #\x
24966 (read-char p) @result{} #<eof>
24967 (read-char p) @result{} #<eof>
24968 @end example
24969 @c JP
24970 @var{string}を内容とする入力文字列ポートを作って返します。
24971 文字列に逐次的にアクセスする場合、インデックスをインクリメントしながら
24972 @code{string-ref}を呼び出すより効率の良い方法です。
24973 @example
24974 (define p (open-input-string "文字 列"))
24975 (read p) @result{} 文字
24976 (read-char p) @result{} #\space
24977 (read-char p) @result{} #\列
24978 (read-char p) @result{} #<eof>
24979 (read-char p) @result{} #<eof>
24980 @end example
24981 @c COMMON
24982
24983 @c EN
24984 The @var{name} keyword argument is a Gauche extension.
24985 By default, the created port is named as @code{(input string port)}.
24986 It is mainly used for debugging. You can specify alternative name with
24987 this argument.
24988 As Gauche's convention, file ports has the source file path as its name,
24989 so port names for debugging information should be parenthesized
24990 not to be taken as pathnames.
24991 @c JP
24992 @var{name}キーワード引数はGaucheの拡張です。
24993 デフォルトでは、作られるポートの名前は@code{(input string port)}になります。
24994 ポートの名前は主にデバッグのために使われます。この引数で代わりの名前を指定できます。
24995 Gaucheの慣習として、ファイルポートは元ファイルのパス名を名前に持つので、
24996 ポート名にデバッグ用途の情報を載せる場合はパス名と区別しやすいよう括弧に入れるのが良いでしょう。
24997 @c COMMON
24998
24999 @example
25000 gosh> (open-input-string "")
25001 #<iport (input string port) 0x215c0c0>
25002 gosh> (open-input-string "" :name "(user input)")
25003 #<iport (user input) 0x22a4e40>
25004 @end example
25005 @end defun
25006
25007 @defun get-remaining-input-string port
25008 @c EN
25009 @var{Port} must be an input string port.
25010 Returns the remaining content of the input port.
25011 The internal pointer of @var{port} isn't moved, so the
25012 subsequent read from @var{port} isn't affected.
25013 If @var{port} has already reached to EOF, a null string is returned.
25014 @c JP
25015 @var{port}は入力文字列ポートでなければなりません。
25016 入力ポートに残っている文字列を返します。
25017 @var{port}の内部ポインタは動かされないので、@var{port}に対するreadは
25018 影響を受けません。@var{port}が既にEOFに達していた場合は、空文字列が返されます。
25019 @c COMMON
25020
25021 @example
25022 (define p (open-input-string "abc\ndef"))
25023 (read-line p) @result{} "abc"
25024 (get-remaining-input-string p) @result{} "def"
25025 (read-char p) @result{} #\d
25026 (read-line p) @result{} "ef"
25027 (get-remaining-input-string p) @result{} ""
25028 @end example
25029 @end defun
25030
25031
25032 @defun open-output-string :key name
25033 [R7RS base][SRFI-6]
25034 @c EN
25035 Creates an output string port. Anything written to the
25036 port is accumulated in the buffer, and can be obtained
25037 as a string by @code{get-output-string}.
25038 This is a far more efficient way to construct a string
25039 sequentially than pre-allocate a string and fill it with
25040 @code{string-set!}.
25041 @c JP
25042 出力文字列ポートを作成して返します。このポートに書き出された文字列は
25043 内部のバッファにたくわえられ、@code{get-output-string} で取り出すことが
25044 できます。
25045 これは、順番に文字列を構成する方法として、あらかじめ文字列をアロケートして
25046 @code{string-set!}で埋めて行くよりもずっと効率の良い方法です。
25047 @c COMMON
25048
25049 @c EN
25050 The @var{name} keyword argument is a Gauche extension.
25051 By default, the created port is named as @code{(output string port)}.
25052 It is mainly used for debugging. You can specify alternative name with
25053 this argument.
25054 As Gauche's convention, file ports has the source file path as its name,
25055 so port names for debugging information should be parenthesized
25056 not to be taken as pathnames.
25057 @c JP
25058 @var{name}キーワード引数はGaucheの拡張です。
25059 デフォルトでは、作られるポートの名前は@code{(output string port)}になります。
25060 ポートの名前は主にデバッグのために使われます。この引数で代わりの名前を指定できます。
25061 Gaucheの慣習として、ファイルポートは元ファイルのパス名を名前に持つので、
25062 ポート名にデバッグ用途の情報を載せる場合はパス名と区別しやすいよう括弧に入れるのが良いでしょう。
25063 @c COMMON
25064
25065 @example
25066 gosh> (open-output-string)
25067 #<oport (output string port) 0x22a4c00>
25068 gosh> (open-output-string :name "(temporary output)")
25069 #<oport (temporary output) 0x22a49c0>
25070 @end example
25071 @end defun
25072
25073 @defun get-output-string port
25074 [R7RS base][SRFI-6]
25075 @c EN
25076 Takes an output string port @code{port} and returns a string
25077 that has been accumulated to @code{port} so far.
25078 If a byte data has been written to the port, this function
25079 re-scans the buffer to see if it can consist a complete string;
25080 if not, an incomplete string is returned.
25081 @c JP
25082 出力文字列ポート@code{port}を取り、それまでそのポートに蓄積された
25083 文字列を返します。バイトデータがそのポートに書き出されていた場合、
25084 この手続きはまず内部バッファをスキャンし、結果が完全な文字列で表現できるかどうかを
25085 調べます。もし表現できなければ、不完全な文字列が返されます。
25086 @c COMMON
25087
25088 @c EN
25089 This doesn't affect the @var{port}'s operation, so you can keep
25090 accumulating content to @var{port} after calling @code{get-output-string}.
25091 @c JP
25092 これは@var{port}の操作には影響をあたえません。@code{get-output-string}を
25093 呼んだ後でも、@var{port}に内容を蓄積しつづけることができます。
25094 @c COMMON
25095 @end defun
25096
25097 @defun call-with-input-string string proc
25098 @defunx call-with-output-string proc
25099 @defunx with-input-from-string string thunk
25100 @defunx with-output-to-string thunk
25101 @c EN
25102 These utility functions are trivially defined as follows.
25103 The interface is parallel to the file port version.
25104 @c JP
25105 これらのユーティリティ関数は次に定義されるような動作をします。
25106 インタフェースはファイルポートを扱う類似の関数と揃えてあります。
25107 @c COMMON
25108 @example
25109 (define (call-with-output-string proc)
25110 (let ((out (open-output-string)))
25111 (proc out)
25112 (get-output-string out)))
25113
25114 (define (call-with-input-string str proc)
25115 (let ((in (open-input-string str)))
25116 (proc in)))
25117
25118 (define (with-output-to-string thunk)
25119 (let ((out (open-output-string)))
25120 (with-output-to-port out thunk)
25121 (get-output-string out)))
25122
25123 (define (with-input-from-string str thunk)
25124 (with-input-from-port (open-input-string str) thunk))
25125 @end example
25126 @end defun
25127
25128 @defun call-with-string-io str proc
25129 @defunx with-string-io str thunk
25130 @example
25131 (define (call-with-string-io str proc)
25132 (let ((out (open-output-string))
25133 (in (open-input-string str)))
25134 (proc in out)
25135 (get-output-string out)))
25136
25137 (define (with-string-io str thunk)
25138 (with-output-to-string
25139 (lambda ()
25140 (with-input-from-string str
25141 thunk))))
25142 @end example
25143 @end defun
25144
25145 @defun write-to-string obj :optional writer
25146 @defunx read-from-string string :optional start end
25147 @c EN
25148 These convenience functions cover common idioms using string ports.
25149 @example
25150 (write-to-string obj writer)
25151 @equiv{}
25152 (with-output-to-string (lambda () (writer obj)))
25153
25154 (read-from-string string)
25155 @equiv{}
25156 (with-input-from-string string read)
25157 @end example
25158 The default value of @var{writer} is the procedure @code{write}.
25159 The default values of @var{start} and @var{end} is 0 and
25160 the length of @var{string}.
25161
25162 Portability note: Common Lisp has these functions, with
25163 different optional arguments.
25164 STk has @code{read-from-string} without optional argument.
25165 @c JP
25166 文字列ポートを使う定型句をユーティリティ関数にしました。
25167 @example
25168 (write-to-string obj writer)
25169 @equiv{}
25170 (with-output-to-string (lambda () (writer obj)))
25171
25172 (read-from-string string)
25173 @equiv{}
25174 (with-input-from-string string read)
25175 @end example
25176 @var{writer}の既定値は@code{write}です。@var{start}, @var{end}は
25177 省略されればそれぞれ0と文字列の長さになります。
25178
25179 移植性への註:Common Lispに同名の関数があります。必須引数の動作は同じですが、
25180 省略可能な引数は異なります。
25181 STkには@code{read-from-string}がありますが、省略可能な引数は取りません。
25182 @c COMMON
25183 @end defun
25184
25185 @node Coding-aware ports, Input, String ports, Input and output
25186 @subsection Coding-aware ports
25187 @c NODE コーディング認識ポート
25188
25189 @c EN
25190 A coding-aware port is a special type of procedural input port that
25191 is used by @code{load} to read a program source. The port recognizes
25192 the magic comment to specify the character encoding of the
25193 program source, such as @code{;; -*- coding: utf-8 -*-}, and makes
25194 an appropriate character encoding conversion.
25195 See @ref{Multibyte scripts} for the details of coding magic comment.
25196 @c JP
25197 コーディング認識ポートは特殊な手続的入力ポートで、@code{load}が
25198 プログラムソースコードを読む際に使われています。このポートは
25199 @code{;; -*- coding: utf-8 -*-}のような、プログラムソースの
25200 文字エンコーディングを指定する特殊なコメントを認識し、適切な
25201 文字エンコーディング変換を行います。
25202 特殊なコメントでソースの文字エンコーディングを指定することについては、
25203 @ref{Multibyte scripts}を参照して下さい。
25204 @c COMMON
25205
25206 @defun open-coding-aware-port iport
25207 @c EN
25208 Takes an input port and returns an input coding aware port,
25209 which basically just pass through the data from @var{iport} to
25210 its reader. However, if a magic comment appears within the
25211 first two lines of data from @var{iport}, the coding aware port
25212 applies the necessary character encoding conversion to the rest of the
25213 data as they are read.
25214 @c JP
25215 入力ポートを引数としてとりコーディング認識入力ポートを返します。
25216 基本的には @var{iport} からの入力データをリーダにわたしているだけです。
25217 しかし、@var{iport} からの入力データの最初の2行以内に、特別な呪文コメント
25218 が現れた場合、コーディング認識ポートは、その後に読み込まれるデータについて
25219 必要な文字エンコーディング変換を行います。
25220 @c COMMON
25221
25222 @c EN
25223 The passed port, @var{iport}, is "owned" by the created coding-aware
25224 port. That is, when the coding-aware port is closed, @var{iport} is
25225 also closed. The content read from @var{iport} is buffered in the
25226 coding-aware port, so other code shouldn't read from @var{iport}.
25227 @c JP
25228 引数として渡されたポート、@var{iport} は生成されたコーディング認識
25229 ポートによって所有されます。つまり、コーディング認識ポートがクローズ
25230 されると、@var{iport} もクローズされます。@var{iport} から読み込まれた
25231 内容はコーディング認識ポート内でバッファリングさます、したがって、
25232 別のコードで @var{iport} から読み出しを行うべきではありません。
25233 @c COMMON
25234
25235 @c EN
25236 By default, Gauche's @code{load} uses a coding aware port to read
25237 the program source, so that the coding magic comment works for
25238 the Gauche source programs (see @ref{Loading Scheme file}).
25239 However, since the mechanism itself
25240 is independent from @code{load}, you can use this port for
25241 other purposes; it is particularly useful to write a function
25242 that processes Scheme source programs which may have the coding
25243 magic comment.
25244 @c JP
25245 デフォルトでは、Gauche の @code{load} はプログラムソースを読むのに
25246 コーディング認識ポートを使います。したがって、文字エンコーディングを
25247 示す特別な呪文コメントは、Gauche のソースプログラムでは有効になります
25248 (@ref{Loading Scheme file}参照)。ただし、この機構自身は @code{load} とは
25249 独立しており、このポートを別の目的で利用できます。特にコーディングの
25250 呪文コメントがある Scheme のソースプログラムを処理する関数を書くときに
25251 便利です。
25252 @c COMMON
25253 @end defun
25254
25255 @node Input, Output, Coding-aware ports, Input and output
25256 @subsection Input
25257 @c NODE 入力
25258
25259 @c EN
25260 For the input-related procedures, the optional @var{iport} argument must be
25261 an input port, and when omitted, the current input port is assumed.
25262 @c JP
25263 入力に関する手続きで、省略可能な引数@var{iport}は入力ポートでなければなりません。
25264 省略された場合が現在の入力ポートが使われます。
25265 @c COMMON
25266
25267 @menu
25268 * Reading data::
25269 * Reader lexical mode::
25270 * Read-time constructor::
25271 * Input utility functions::
25272 @end menu
25273
25274 @node Reading data, Reader lexical mode, Input, Input
25275 @subsubsection Reading data
25276 @c NODE データの読み込み
25277
25278 @defun read :optional iport
25279 [R7RS base]
25280 @c EN
25281 Reads an S-expression from @var{iport} and returns it.
25282 Gauche recognizes the lexical structure specified in R7RS,
25283 and some additional lexical structures listed in @ref{Lexical structure}.
25284
25285 If @var{iport} has already reached to the end of file,
25286 an eof object is returned.
25287
25288 The procedure reads up to the last character that consists the S-expression,
25289 and leaves the rest in the port. It's not like CommonLisp's @code{read},
25290 which consumes whitespaces after S-expression by default.
25291 @c JP
25292 @var{iport}からS式をひとつ読み込んで返します。
25293 GaucheはR7RSに定義されている構文要素に加え、@ref{Lexical structure}に
25294 定義されている拡張構文要素を認識します。
25295
25296 @var{iport}が既にEOFに達していた場合は、EOFオブジェクトが返されます。
25297
25298 この手続きはS式を構成する最後の文字までを読み、その後の文字はポートに
25299 残します。これは、S式に続く空白文字も読み込むCommonLispの@code{read}の
25300 振る舞いとは異なります。
25301 @c COMMON
25302 @end defun
25303
25304 @defun read-with-shared-structure :optional iport
25305 @defunx read/ss :optional iport
25306 [SRFI-38]
25307 @c EN
25308 These procedures are defined in SRFI-38 to recognize shared substructure
25309 notation (@code{#n=}, @code{#n#}). Gauche's builtin @code{read} recognizes
25310 the SRFI-38 notation, so these are just synonyms to @code{read}; these
25311 are only provided for SRFI-38 compatibility.
25312 @c JP
25313 これらの手続きは、SRFI-38 で定義されていて、共有構造を表す記法
25314 (@code{#n=}, @code{#n#})を認識できます。Gauche の組み込み @code{read} は
25315 この SRFI-38 の記法を認識します。それゆえ、これらの手続きは、@code{read}
25316 と同じで、SRFI-38 との互換性のために用意されています。
25317 @c COMMON
25318 @end defun
25319
25320 @defun read-char :optional iport
25321 [R7RS base]
25322 @c EN
25323 Reads one character from @var{iport} and returns it.
25324 If @var{iport} has already
25325 reached to the end, returns an eof object.
25326 If the byte stream in @var{iport} doesn't consist a valid character,
25327 the behavior is undefined. (In future, a port will have a option
25328 to deal with invalid characters).
25329 @c JP
25330 @var{iport}から1文字読み込んで返します。
25331 @var{iport}が既にEOFに達していた場合はeofオブジェクトを返します。
25332 @var{iport}にあるバイトストリームが正しい文字を構成しない場合、
25333 ふるまいは未定義です。(将来はポート側に、不正な文字に対する対応を決める
25334 オプションを設ける予定です)。
25335 @c COMMON
25336 @end defun
25337
25338 @defun peek-char :optional iport
25339 [R7RS base]
25340 @c EN
25341 Reads one character in @var{iport} and returns it, keeping the character
25342 in the @var{port}.
25343 If the byte stream in @var{iport} doesn't consist a valid character,
25344 the behavior is undefined. (In future, a port will have a option
25345 to deal with invalid characters).
25346 @c JP
25347 @var{iport}から1文字読み込んで返します。文字はそのまま@var{iport}に留まります。
25348 @var{iport}が既にEOFに達していた場合はeofオブジェクトを返します。
25349 @var{iport}にあるバイトストリームが正しい文字を構成しない場合、
25350 ふるまいは未定義です。(将来はポート側に、不正な文字に対する対応を決める
25351 オプションを設ける予定です)。
25352 @c COMMON
25353 @end defun
25354
25355 @defun read-byte :optional iport
25356 @defunx read-u8 :optional iport
25357 [R7RS base]
25358 @c EN
25359 Reads one byte from an input port @var{iport}, and returns it as an integer
25360 in the range between 0 and 255.
25361 If @var{iport} has already reached EOF, an eof object is returned.
25362
25363 This is traditionally called @code{read-byte}, and
25364 R7RS calls it @code{read-u8}. You can use either.
25365 @c JP
25366 入力ポート@var{iport}から1バイト読み込み、0から255までの整数値として返します。
25367 @var{iport}が既にEOFに達していた場合はeofオブジェクトを返します。
25368
25369 これは伝統的に@code{read-byte}と呼ばれてきましたが、
25370 R7RSでは@code{read-u8}と名づけています。どちらも使えます。
25371 @c COMMON
25372 @end defun
25373
25374 @defun peek-byte :optional iport
25375 @defunx peek-u8 :optional iport
25376 [R7RS base]
25377 @c EN
25378 Peeks one byte at the head of an input port @var{iport}, and returns
25379 it as an integer in the range between 0 and 255.
25380 If @var{iport} has already reached EOF, an eof object is returned.
25381
25382 This is traditionally called @code{peek-byte}, and
25383 R7RS calls it @code{peek-u8}. You can use either.
25384 @c JP
25385 入力ポート@var{iport}の先頭の1バイトを見て、それを0から255までの整数値として返します。
25386 @var{iport}が既にEOFに達していた場合はeofオブジェクトを返します。
25387
25388 これは伝統的に@code{peek-byte}と呼ばれてきましたが、
25389 R7RSでは@code{peek-u8}と名づけています。どちらも使えます。
25390 @c COMMON
25391 @end defun
25392
25393 @defun read-line :optional iport allow-byte-string?
25394 [R7RS base]
25395 @c EN
25396 Reads one line (a sequence of characters terminated by newline or EOF)
25397 and returns a string. The terminating newline is not included.
25398 This function recognizes popular line terminators (LF only, CRLF, and CR only).
25399 If @var{iport} has already reached EOF, an eof object is returned.
25400 @c JP
25401 入力ポートから、行末もしくはEOFまで読み込んで文字列として返します。
25402 よく使われる行末 (LF only, CRLF, and CR only) を認識します。
25403 戻り値にはこれらの行末文字は含まれません。
25404 @var{iport}が既にEOFに達していた場合はeofオブジェクトを返します。
25405 @c COMMON
25406
25407 @c EN
25408 If a byte sequence is read from @var{iport}
25409 which doesn't constitute a valid character in the native encoding,
25410 @code{read-line} signals an error by default. However, if a true value
25411 is given to the argument @var{allow-byte-string?},
25412 @code{read-line} returns a byte string (incomplete string) in such case,
25413 without reporting an error.
25414 It is particularly useful if you read from a source whose
25415 character encoding is not yet known; for example, to read XML document,
25416 you need to check the first line to see if there is a charset parameter
25417 so that you can then use an appropriate character conversion port.
25418 This optional argument is Gauche's extension to R7RS.
25419 @c JP
25420 @var{iport}から、内部文字エンコーディングでは文字を構成し得ないバイトシーケンスが
25421 読まれた場合、デフォルトでは@code{read-line}はエラーを通知します。
25422 しかし、省略可能な引数@var{allow-byte-string?}に真の値が与えられた場合は、
25423 @code{read-line}はエラーを通知せず、かわりにバイト文字列 (不完全な文字列) を
25424 返します。この動作は、特に文字エンコーディングが不明なソースから読み込む際に
25425 便利です。例えばXMLドキュメントを読み込む際、最初の行のcharsetパラメータを
25426 チェックしてから適切な文字エンコーディング変換ポートを使うといった用途などです。
25427 この動作はGauche独自の拡張です。
25428 @c COMMON
25429 @end defun
25430
25431 @defun read-string nchars :optional iport
25432 [R7RS base]
25433 @c EN
25434 Read @var{nchars} characters, or as many characters as available
25435 before EOF, and returns a string that consists of those characters.
25436 If the input has already reached EOF, an eof object is returned.
25437 @c JP
25438 @var{nchars}文字を読み込み、もしくはそれ以前にEOFに達したら読めただけの文字を
25439 使って文字列を作って返します。もし入力が既にEOFに達していた場合は
25440 EOFを返します。
25441 @c COMMON
25442 @end defun
25443
25444 @defun consume-trailing-whitespaces :optional iport
25445 @c EN
25446 Reads and discards consecutive whitespace characters up to (including)
25447 the first EOL, from @var{iport}. If @var{iport} is omitted,
25448 the current input port is used.
25449 @c JP
25450 @var{iport}から、連続する空白文字を、最初の行末文字を読むまで読み込んで捨てます。
25451 @var{iport}が省略された場合は現在の入力ポートが使われます。
25452 @c COMMON
25453
25454 @c EN
25455 This is mainly for interactive REPL when the input is line
25456 buffered. Suppose you're reading user's input using @code{read}.
25457 If the input is line buffered, @code{read} won't see any input until
25458 the user type @code{RET}. It means if the user type
25459 @code{(read-line)RET}, then @code{read} returns @code{(read-line)},
25460 and if you evaluate it immediately, it reads @code{RET}.
25461 @c JP
25462 これは主にラインバッファリングがある入力でインタラクティブなREPLを走らせる
25463 ためのものです。入力を@code{read}で読み込んでいるとしましょう。
25464 入力がラインバッファされていたら、ユーザがRETをタイプしてはじめて@code{read}が
25465 入力を読むことになります。ということは、ユーザが@code{(read-line)RET}とタイプしたなら、
25466 @code{read}は@code{(read-line)}を返し、もしそれを即座にevalするなら、
25467 それは入力に残っているRETを読み込むことになるでしょう。
25468 @c COMMON
25469
25470 @c EN
25471 That is not users typically expect; the user wants to type the
25472 input for @code{read-line}. Hence, it is useful to consume trailing
25473 @code{RET} after reading the user's initial input.
25474 @c JP
25475 これはユーザが通常期待する動作とは異なります。
25476 ユーザは、@code{read-line}が実行された時点で、入力にタイプした行を読んで欲しいと
25477 思うでしょう。したがって、ユーザの最初の入力のあと、バフぁFに残っているRETを含めた
25478 空白文字を捨てておくことが役に立ちます。
25479 @c COMMON
25480 @end defun
25481
25482 @defun read-block nbytes :optional iport
25483 @c EN
25484 This procedure is deprecated - use @code{read-uvector} instead
25485 (@pxref{Uvector block I/O}).
25486 @c JP
25487 この手続きは非推奨になりました。@code{read-uvector}を使ってください
25488 (@ref{Uvector block I/O}参照)。
25489 @c COMMON
25490
25491 @c EN
25492 Reads @var{nbytes} bytes from @var{iport}, and returns an incomplete
25493 string consisted by those bytes. The size of returned string may
25494 shorter than @var{nbytes} when @var{iport} doesn't have enough bytes
25495 to fill.
25496 If @var{nbytes} is zero, a null string is always returned.
25497
25498 If @var{iport} has already reached EOF, an eof object is returned.
25499 @c JP
25500 @var{nbytes}バイトのデータを@var{iport}から読み込み、
25501 不完全な文字列として返します。@var{iport}に十分なデータが無い場合、
25502 返される文字列は@var{nbytes}より短いかもしれません。
25503 @var{nbytes}が0の場合は、常に空文字列が返されます。
25504
25505 @var{iport}が既にEOFに達していた場合はEOFオブジェクトが返されます。
25506 @c COMMON
25507
25508 @c EN
25509 If @var{iport} is a file port, the behavior of @code{read-block}
25510 differs by the buffering mode of the port (@xref{File ports}, for
25511 the detail explanation of buffering modes).
25512 @c JP
25513 @var{iport}がファイルポートだった場合、@code{read-block}は
25514 ポートのバッファリングモードによってふるまいが異なります
25515 (バッファリングモードの詳細については@ref{File ports}を参照して下さい)。
25516 @c COMMON
25517 @itemize @bullet
25518 @item
25519 @c EN
25520 If the buffering mode is @code{:full}, @code{read-block} waits
25521 until @var{nbytes} data is read, except it reads EOF.
25522 @c JP
25523 バッファリングモードが@code{:full}の場合、@code{read-block}は
25524 EOFを読まない限り、@var{nbytes}のデータが読まれるまで待ちます。
25525 @c COMMON
25526 @item
25527 @c EN
25528 If the buffering mode is @code{:modest} or @code{:none}, @code{read-block}
25529 returns shorter string than @var{nbytes} even if it doesn't reach EOF,
25530 but the entire data is not available immediately.
25531 @c JP
25532 バッファリングモードが@code{:modest}か@code{:none}である場合、
25533 @code{read-block}はEOFが読まれなくても、すぐに読めるデータが@var{nbytes}よりも
25534 少ない場合はそのデータだけを返します。
25535 @c COMMON
25536 @end itemize
25537
25538 @c EN
25539 If you want to write a chunk of bytes to a port,
25540 you can use either @code{display} if the data is in string,
25541 or @code{write-uvector} in @code{gauche.uvector} (@pxref{Uvector block I/O})
25542 if the data is in uniform vector.
25543 @c JP
25544 データブロックをポートに書き出すには、データが文字列で表現されている
25545 場合は単純に@code{display}が使えます。データがuniform vectorで表現されている
25546 場合は@code{gauche.uvector}モジュールの@code{write-uvector}が
25547 使えます (@ref{Uvector block I/O}参照)。
25548 @c COMMON
25549 @end defun
25550
25551 @defun eof-object
25552 [R7RS base]
25553 @c EN
25554 Returns an EOF object.
25555 @c JP
25556 EOFオブジェクトを返します。
25557 @c COMMON
25558 @end defun
25559
25560
25561 @defun eof-object? obj
25562 [R7RS base]
25563 @c EN
25564 Returns true if @var{obj} is an EOF object.
25565 @c JP
25566 @var{obj}がEOFオブジェクトなら@code{#t}を返します。
25567 @c COMMON
25568 @end defun
25569
25570 @defun char-ready? :optional port
25571 [R7RS base]
25572 @c EN
25573 If a character is ready to be read from @var{port}, returns @code{#t}.
25574
25575 For now, this procedure actually checks only if next @emph{byte} is
25576 immediately available from @var{port}. If the next byte is a part of
25577 a multibyte character, the attempt to read the whole character may block,
25578 even if @code{char-ready?} returns @code{#t} on the port.
25579 (It is unlikely to happen in usual situation, but theoretically it can.
25580 If you concern, use @code{read-uvector} to read the input as a byte
25581 sequence, then use input string port to read characters.)
25582 @c JP
25583 @var{port}から文字が読み出せる状態ならば@code{#t}を返します。
25584
25585 今のところ、この手続きは@var{port}から少なくとも1バイト読み出せる状態なら@code{#t}
25586 を返します。そのバイトがマルチバイト文字を構成する場合、@code{char-ready?}を返した
25587 ポートから文字全てを読み込もうとすると、ブロックする可能性があります。
25588 (通常の使用状況ではそのようなことは起きないでしょうが、理論的には起こり得ます。
25589 慎重を期したい場合は@code{read-uvector}でバイトシーケンスとして読み込んだ後、
25590 入力文字列ポート等を使って文字毎に読むようにして下さい。)
25591 @c COMMON
25592 @end defun
25593
25594 @defun byte-ready? :optional port
25595 @defunx u8-ready? :optional port
25596 [R7RS base]
25597 @c EN
25598 If one byte (octet) is ready to be read from @var{port}, returns
25599 @code{#t}.
25600
25601 This is traditionally called @code{byte-ready?}, and
25602 R7RS calls it @code{u8-ready?}. You can use either.
25603 @c JP
25604 @var{port}から1バイトをすぐに読み込める状態なら@code{#t}を返します。
25605
25606 これは伝統的に@code{byte-ready?}と呼ばれてきましたが、
25607 R7RSでは@code{u8-ready?}と名づけています。どちらも使えます。
25608 @c COMMON
25609 @end defun
25610
25611 @node Reader lexical mode, Read-time constructor, Reading data, Input
25612 @subsubsection Reader lexical mode
25613 @c NODE リーダー字句モード
25614
25615 @deffn {Parameter} reader-lexical-mode
25616 @c EN
25617 Get/set the reader lexical mode. Changing this parameter
25618 switches behavior of the reader concerning some corner cases
25619 of the lexical syntax, where legacy Gauche syntax and R7RS syntax
25620 aren't compatible.
25621 @c JP
25622 現在のリーダ字句モードを表すパラメータです。
25623 このパラメータの値を変えることにより、旧来のGaucheとR7RSで非互換となる
25624 コーナーケースの字句構文についての解釈を変更できます。
25625 @c COMMON
25626
25627 @c EN
25628 In general, you don't need to change this parameter directly.
25629 The lexical syntax matters at the read-time, while changing this parameter
25630 happens at the execution-time; unless you know the exact timing when
25631 each phase occurs, you might not get what you want.
25632 @c JP
25633 一般的には、このパラメータを直接変える必要のある場合は少ないでしょう。
25634 字句構文は読み込み時に問題となりますが、パラメータの変更は実行時に起こります。
25635 いつ、何が起きるかを正確に把握しているのでない限り、意図したとおりの効果は
25636 得られないかもしれません。
25637 @c COMMON
25638
25639 @c EN
25640 The hash-bang directive @code{#!gauche-legacy} and @code{#!r7rs}
25641 indirectly affects this parameter; the first one sets the reader
25642 mode to @code{legacy}, and the second one to @code{strict-r7}.
25643 @c JP
25644 hash-bang指示子 @code{#!gauche-legacy} および @code{#!r7rs} は
25645 間接的にこのパラメータに影響を与えます。@code{#!gauche-legacy}は
25646 リーダモードを@code{legacy}に、@code{#!r7rs}は@code{strict-r7}に
25647 変更します。
25648 @c COMMON
25649
25650 @c EN
25651 The command-line argument @code{-fwarn-legacy} sets the default
25652 reader mode to @code{warn-legacy}.
25653 @c JP
25654 コマンドライン引数の@code{-fwarn-legacy}はデフォルトのリーダモードを
25655 @code{warn-legacy}にセットします。
25656 @c COMMON
25657
25658 @c EN
25659 Change to this parameter during @code{load} is delimited within that @code{load};
25660 once @code{load} is done, the value of this parameter is reset
25661 to the value when @code{load} is started.
25662 @c JP
25663 @code{load}中にこのパラメータを変更した場合、その効果は@code{load}の期間中に
25664 留まります。その@code{load}が終了した時点で、
25665 @code{load}開始時のリーダモードが復元されます。
25666 @c COMMON
25667
25668 @c EN
25669 The parameter takes one of the following symbols as a value.
25670 @c JP
25671 このパラメータは値として次のシンボルのうちいずれかを取ります。
25672 @c COMMON
25673
25674 @table @code
25675 @item permissive
25676 @c EN
25677 This is the default mode. It tries to find a reasonable
25678 compromise between two syntax.
25679 @c JP
25680 これがデフォルトのモードです。二つの構文の、ほどほどの妥協点を見つけようとします。
25681 @c COMMON
25682
25683 @c EN
25684 In string literals, hex escape sequence
25685 is first interpreted as R7RS lexical syntax. If the syntax doesn't
25686 conform R7RS hex escape, it is interpreted as legacy Gauche hex escape
25687 syntax. For example, @code{"\x30;a"} is read as @code{"0a"}, for
25688 the hex escape sequence including the terminating semicolon is read
25689 as R7RS hex escape sequence. It also reads @code{"\x30a"} as
25690 @code{"0a"}, for the legacy Gauche hex escape always takes two hexadecimal
25691 digits without the terminator. With this mode, you can use R7RS
25692 hex escape syntax for the new code, and yet almost all legacy Gauche
25693 code can be read without a problem.
25694 However, if the legacy code has a semicolon followed by hex escape,
25695 it is interpreted as R7RS syntax and the incompatibility arises.
25696 @c JP
25697 文字列リテラル中の16進数エスケープシーケンスは、まず
25698 R7RSの字句構文で解釈されます。もしそれがR7RSの16進数エスケープシーケンスの
25699 構文に沿っていなかった場合は、旧来のGaucheの構文で解釈されます。
25700 例えば、@code{"\x30;a"} は、セミコロンがR7RSのエスケープシーケンスの終端と
25701 みなされ、@code{"0a"} と読まれます。一方で @code{"\x30a"} も @code{"0a"} と
25702 読まれます。終端のセミコロンが無く、有効なR7RSの構文でないため、
25703 旧来のGaucheのエスケープシーケンスとして2桁固定で解釈されるからです。
25704 このモードでは、新たなコードでR7RSエスケープシーケンスを利用できるうえ、
25705 ほとんどの既存のGaucheコードはそのまま走ります。
25706 しかし、もし既存のGaucheコードで、たまたま2桁の16進数エスケープの直後に
25707 セミコロンがあった場合、それはR7RSとして読まれ、非互換性が生じます。
25708 @c COMMON
25709
25710 @item strict-r7
25711 @c EN
25712 Strict R7RS compatible mode.
25713 When the reader encounters the hash-bang directive @code{#!r7rs},
25714 the rest of file is read with this mode.
25715 @c JP
25716 厳密にR7RS互換なモード。
25717 リーダが、hash-bang指示子@code{#!r7rs}に出会うと、ファイルの残りの部分は
25718 このモードで読まれます。
25719 @c COMMON
25720
25721 @c EN
25722 In this mode, Gauche's extended lexical syntax will raise an error.
25723
25724 Use this mode to ensure the code can be read on other R7RS implementations.
25725 @c JP
25726 このモードでは、Gaucheの拡張字句構文はエラーとなります。
25727
25728 他のR7RS実装でも読めるコードであることを確認したい場合に使ってください。
25729 @c COMMON
25730
25731 @item legacy
25732 @c EN
25733 The reader works as the legacy Gauche (version 0.9.3.3 and before).
25734 When the reader encounters the hash-bang directive @code{#!gauche-legacy},
25735 the rest of file is read with this mode.
25736
25737 This only matters when you want to read two-digit hex escape
25738 followed by semicolon as a character plus a semicolon, e.g.
25739 @code{"\x30;a"} as @code{"0;a"} instead of @code{"0a"}.
25740 We expect such a sequence rarely appears in the code,
25741 but if you dump a data in a string literal format, you may
25742 have such sequence (especially in incomplete string literals).
25743 @c JP
25744 リーダは以前の(0.9.3.3及びそれ以前の)Gaucheと同じように動作します。
25745 リーダがhash-bang指示子@code{#!gauche-legacy}に出会うと、ファイルの残りの部分は
25746 このモードで読まれます。
25747
25748 このモードが必要になるのは、2桁の16進数エスケープの直後にセミコロンが来ているリテラルを、
25749 文字+セミコロンと読みたい場合だけです。例えば
25750 @code{"\x30;a"}を@code{"0a"}でなく@code{"0;a"}と読みたい、等。
25751 こういうケースはコードではほとんど無いと思いますが、
25752 データを文字列リテラルとしてダンプしてある場合、それも不完全な文字列として
25753 ダンプしてある場合に、こういった並びが出現しているかもしれません。
25754 @c COMMON
25755
25756 @item warn-legacy
25757 @c EN
25758 The reader works as the @code{permissive} mode,
25759 but warns if it reads legacy hex-escape syntax.
25760 This mode is default when @code{-fwarn-legacy} command-line
25761 argument is given to @code{gosh}.
25762
25763 This is useful to check if you have any incompatible escape sequence
25764 in your code.
25765 @c JP
25766 リーダは@code{permissive}モードと同様に動作しますが、
25767 旧来の16進数エスケープに出会うと警告を発します。
25768 @code{gosh}に@code{-fwarn-legacy}コマンドライン引数が与えられた場合は
25769 これがデフォルトのモードになります。
25770
25771 コードの中に非互換なエスケープシーケンスが無いかどうか調べるのに役立ちます。
25772 @c COMMON
25773 @end table
25774 @end deffn
25775
25776
25777 @node Read-time constructor, Input utility functions, Reader lexical mode, Input
25778 @subsubsection Read-time constructor
25779 @c NODE 読み込み時コンストラクタ
25780
25781 @c EN
25782 Read-time constructor, defined in SRFI-10, provides an easy way
25783 to create an external representation of user-defined structures.
25784 @c JP
25785 SRFI-10で定義されている読み込み時コンストラクタは、ユーザ定義の構造の
25786 外部表現を作るための簡単な方法を提供します。
25787 @c COMMON
25788
25789 @deftp {Reader Syntax} @code{#,(@var{tag} @var{arg} @dots{})}
25790 @lxindex #,
25791 [SRFI-10]
25792 @c EN
25793 Gauche maintains a global table that associates a @var{tag} (symbol)
25794 to @emph{a constructor procedure}.
25795 @c JP
25796 Gaucheは@var{tag} (シンボル)を@emph{コンストラクタ手続き}に関連付ける
25797 グローバルなテーブルを管理しています。
25798 @c COMMON
25799
25800 @c EN
25801 When the reader encounters this syntax, it reads @var{arg} @dots{},
25802 finds a reader constructor associated with @var{tag}, and
25803 calls the constructor with @var{arg} @dots{} as arguments,
25804 then inserts the value returned by the constructor as the result
25805 of reading the syntax.
25806 @c JP
25807 リーダーがこの構文に出会ったとき、@var{arg} @dots{}を読み込み、
25808 @var{tag}に関連付けられた読み込みコンストラクタを探し、
25809 @var{arg} @dots{}を引数としてそのコンストラクタを呼び出し、
25810 その構文を読み込んだ結果としてそのコンストラクタが返した値を挿入します。
25811 @c COMMON
25812
25813 @c EN
25814 Note that this syntax is processed inside the reader---the
25815 evaluator doesn't see any of @var{arg}s, but only sees the object
25816 the reader returns.
25817 @c JP
25818 この構文はリーダー内部で処理されることに注意して下さい。評価器は
25819 @var{arg}を見ず、リーダーが返したオブジェクトしか見ません。
25820 @c COMMON
25821 @end deftp
25822
25823 @defun define-reader-ctor @var{tag} @var{procedure}
25824 @c EN
25825 [SRFI-10]
25826 Associates a reader constructor @var{procedure} with @var{tag}.
25827
25828 Examples:
25829 @c JP
25830 [SRFI-10]
25831 読み込みコンストラクタ@var{procedure}を@var{tag}に関連付けます。
25832
25833 例:
25834 @c COMMON
25835 @example
25836 (define-reader-ctor 'pi (lambda () (* (atan 1) 4)))
25837
25838 #,(pi) @result{} 3.141592653589793
25839
25840 '(#,(pi)) @result{} (3.141592653589793)
25841
25842 (define-reader-ctor 'hash
25843 (lambda (type . pairs)
25844 (let ((tab (make-hash-table type)))
25845 (for-each (lambda (pair)
25846 (hash-table-put! tab (car pair) (cdr pair)))
25847 pairs)
25848 tab)))
25849
25850 (define table
25851 #,(hash eq? (foo . bar) (duh . dah) (bum . bom)))
25852
25853 table @result{} #<hash-table eq? 0x80f9398>
25854 (hash-table-get table 'duh) @result{} dah
25855 @end example
25856
25857 @c EN
25858 Combined with @code{write-object} method (@pxref{Output}),
25859 it is easy to make a user-defined class written in the form
25860 it can be read back:
25861 @c JP
25862 @code{write-object}メソッド(@ref{Output}参照)と組み合わせて、
25863 読み戻ることが可能なフォームで書かれたユーザ定義のクラスを
25864 作ることが簡単になります。
25865 @c COMMON
25866
25867 @example
25868 (define-class <point> ()
25869 ((x :init-value 0 :init-keyword :x)
25870 (y :init-value 0 :init-keyword :y)))
25871
25872 (define-method write-object ((p <point>) out)
25873 (format out "#,(<point> ~s ~s)" (ref p 'x) (ref p 'y)))
25874
25875 (define-reader-ctor '<point>
25876 (lambda (x y) (make <point> :x x :y y)))
25877 @end example
25878
25879 @end defun
25880
25881 @c EN
25882 @emph{NOTE:} The extent of the effect of @code{define-reader-ctor}
25883 is not specified in SRFI-10, and might pose a compatibility problem
25884 among implementations that support SRFI-10.
25885 (In fact, the very existence of @code{define-reader-ctor} is
25886 up to an implementation choice.)
25887 @c JP
25888 @emph{注意:} @code{define-reader-ctor}の効果の範囲はSRFI-10には
25889 規定されておらず、SRFI-10をサポートする実装においても互換性の問題を
25890 起こすことがあるかもしれません。
25891 (実際に、@code{define-reader-ctor}の存在そのものが実装の選択に
25892 任されています。)
25893 @c COMMON
25894
25895 @c EN
25896 In Gauche, at least for the time being, @code{define-reader-ctor}
25897 take effects as soon as the form is compiled and evaluated. Since
25898 Gauche compiles and evaluates each toplevel form in order, @var{tag}
25899 specified in @code{define-reader-ctor} can be used immediately after that.
25900 However, it doesn't work if the call of @code{define-reader-ctor} and
25901 the use of @var{tag} is enclosed in a @code{begin} form, for the entire
25902 @code{begin} form is compiled at once before being evaluated.
25903 @c JP
25904 Gaucheでは、現時点においては、@code{define-reader-ctor}はそのフォームが
25905 コンパイルされ評価された時点で効力を持ちます。
25906 Gaucheはトップレベルのフォームを順番にコンパイル・評価するので、
25907 @code{define-reader-ctor}で指定された@var{tag}は、その指定の直後から
25908 使えます。
25909 しかし、@code{define-reader-ctor}の呼び出しと@var{tag}の使用が
25910 @code{begin}フォームで囲まれている場合は、@code{begin}フォーム全体は
25911 評価される前に一度にコンパイルされるため、うまく動作しません。
25912 @c COMMON
25913
25914 @c EN
25915 Other implementations may require to read the entire file before
25916 making its @code{define-reader-ctor} call effective. If so, it
25917 effectively prevents one from using @code{define-reader-ctor} and
25918 the defined @var{tag} in the same file. It is desirable to separate
25919 the call of @code{define-reader-ctor} and the use of @var{tag}
25920 in the different files if possible.
25921 @c JP
25922 他の実装では、@code{define-reader-ctor}の呼び出しが効力を持つようにする
25923 前にファイル全体を読み込むことを要求するかも知れません。
25924 その場合は、@code{define-reader-ctor}と定義された@var{tag}の使用を
25925 同じファイルに置く事は実質的に不可能です。
25926 可能ならば、@code{define-reader-ctor}の呼び出しと、@var{tag}の使用は
25927 異なるファイルに分離されることが望まれます。
25928 @c COMMON
25929
25930 @c EN
25931 Another issue about the current @code{define-reader-ctor} is that
25932 it modifies the global table of Gauche system, hence it is not modular.
25933 The code written by different people might use the same tags,
25934 and yield an unexpected result. In future versions, Gauche may
25935 have some way to encapsulate the scope of @var{tag}, although
25936 the author doesn't have clear idea yet.
25937 @c JP
25938 現在の@code{define-reader-ctor}に関するもう1つの問題は、それが
25939 Gaucheシステムのグローバルテーブルを変更してしまうことで、それゆえに
25940 モジュール性が良くありません。
25941 複数人によって書かれたコードは同じタグを使っているかも知れず、
25942 期待されない結果を引き起こすかも知れません。
25943 作者にはまだ明確なアイデアがありませんが、将来のバージョンでは、
25944 Gaucheには@var{tag}のスコープをカプセル化する方法が導入されるかも
25945 しれません。
25946 @c COMMON
25947
25948
25949 @node Input utility functions, , Read-time constructor, Input
25950 @subsubsection Input utility functions
25951 @c NODE 入力ユーティリティ手続き
25952
25953 @defun port->string port
25954 @defunx port->list reader port
25955 @defunx port->string-list port
25956 @defunx port->sexp-list port
25957 @c EN
25958 Generally useful input procedures. The API is taken from
25959 scsh and STk.
25960 @c JP
25961 便利な入力手続きです。APIはScshとSTkから取りました。
25962 @c COMMON
25963
25964 @c EN
25965 @code{port->string} reads @var{port}
25966 until EOF and returns the accumulated data as a string.
25967 @c JP
25968 @code{port->string}は@var{port}をEOFまで読み込み、
25969 読んだものを文字列として返します。
25970 @c COMMON
25971
25972 @c EN
25973 @code{port->list} applies @var{reader} on @var{port} repeatedly, until
25974 @var{reader} returns an EOF, then returns the list of objects
25975 @var{reader} returned.
25976 Note that @var{port} isn't closed.
25977 @c JP
25978 @code{port->list}は手続き@var{reader}を@var{port}に繰り返し適用し、
25979 結果をリストに蓄積します。@var{reader}がEOFを返したら
25980 蓄積されたリストを返します。
25981 @var{port}自体はクローズされないことに注意してください。
25982 @c COMMON
25983
25984 @c EN
25985 @code{port->string-list} is a @code{port->list} specialized
25986 by @code{read-line}, and
25987 @code{port->sexp-list} is a @code{port->list} specialized
25988 by @code{read}.
25989 @c JP
25990 @code{port->string-list}は@code{port->list}を
25991 @code{read-line}で特定化したもので、
25992 @code{port->sexp-list}は@code{port->list}を
25993 @code{read}で特定化したものです。
25994 @c COMMON
25995
25996 @c EN
25997 If the input contains an octet sequence that's not form a valid
25998 character in the Gauche's native character encoding,
25999 @code{port->string} and @code{port->string-list} may return
26000 incomplete string(s).
26001 If you want to deal with binary data, consider using
26002 @code{port->uvector} in @code{gauche.uvector} (@pxref{Uvector block I/O}).
26003 @c JP
26004 もし入力にGaucheの内部エンコーディングにおいて有効な文字をつくらない
26005 バイト列が含まれていた場合、@code{port->string}と@code{port->string-list}
26006 の返り値には不完全な文字列が含まれている可能性があります。
26007 入力をバイナリデータとして扱いたい場合は、
26008 @code{gauche.uvector}の@code{port->uvector}を使って下さい
26009 (@ref{Uvector block I/O}参照)。
26010 @c COMMON
26011 @end defun
26012
26013 @defun port-fold fn knil reader
26014 @defunx port-fold-right fn knil reader
26015 @defunx port-for-each fn reader
26016 @defunx port-map fn reader
26017 @c DEPRECATED
26018 @c EN
26019 Convenient iterators over the input read by @var{reader}.
26020
26021 Since these procedures are not really about ports,
26022 they are superseded by @code{generator-fold},
26023 @code{generator-fold-right}, @code{generator-for-each}
26024 and @code{generator-map}, respectively. @xref{Folding generated values},
26025 for the details.
26026
26027 We provide these only for the backward compatibility.
26028 @c JP
26029 @var{reader}によって読まれる入力に対する便利な繰り返し手続きです。
26030
26031 実際にはこれらの手続きはポートからの入力以外にも使えるため、それぞれ
26032 @code{generator-fold}, @code{generator-fold-right},
26033 @code{generator-for-each}, @code{generator-map}によって置き換えられました。
26034 詳しくは@ref{Folding generated values}を参照してください。
26035
26036 これらの手続きは後方互換性のためだけに提供されています。
26037 @c COMMON
26038 @end defun
26039
26040 @node Output, , Input, Input and output
26041 @subsection Output
26042 @c NODE 出力
26043
26044 @menu
26045 * Layers of output routines::
26046 * Output controls::
26047 * Object output::
26048 * Formatting output::
26049 * Low-level output::
26050 @end menu
26051
26052 @node Layers of output routines, Output controls, Output, Output
26053 @subsubsection Layers of output routines
26054 @c NODE 出力ルーチンの階層
26055
26056 @c EN
26057 Gauche has quite a few output procedures which may confuse newcomers.
26058 The following table will help to understand how to use those procedures:
26059 @c JP
26060 Gaucheにはたくさんの出力手続きがあり、慣れないうちはどれを使えばよいか迷ってしまう
26061 かもしれません。次の表は様々な出力手続きを分類するものです。
26062 @c COMMON
26063
26064 @table @asis
26065 @c EN
26066 @item Object writers
26067 Procedures that write out Scheme objects.
26068 Although there exist more low-level procedures,
26069 these are regarded as a basic layer of output routines,
26070 since it works on a generic Scheme object as a single unit.
26071 They come in two flavors:
26072
26073 @itemize @bullet
26074 @item
26075 Write-family procedures: @code{write}, @code{write-shared}, @code{write-simple}--these are to produce @emph{external representation} of Scheme objects,
26076 which can be generally read back by @code{read} without losing
26077 information as much as possible@footnote{In a sense, this is somewhat similar to
26078 what is called ``serialization'' or ``marshalling'' in other programming
26079 language; you can @code{write} out a generic Scheme object on disk or
26080 to wire, and @code{read} it to get an object equivalent to the original
26081 one. In Lisp-family languages, this is called @emph{read/write invariance}
26082 and is a built-in feature.
26083 Note that some objects do not have this invariance
26084 in nature, so sometimes you need to make your own serializer/marshaller.}.
26085 The external representation of most Scheme objects
26086 are the ones you write literal data in program, so this is the default way
26087 of writing Scheme objects out.
26088 @item
26089 Display-family procedures:
26090 @code{display}, @code{print}, @code{newline}.
26091 These are to produce plain-text output suitable for human readers.
26092 @end itemize
26093 @c JP
26094 @item オブジェクトの出力
26095 Schemeオブジェクトを出力する手続きです。
26096 もっと低レベルの手続きもありますが、一般にはこの層が出力ルーチンの基本であると
26097 みなされています。Schemeのオブジェクト単位で操作をするからです。
26098 この手続き群はさらに次の二つのグループに分かれます。
26099
26100 @itemize @bullet
26101 @item
26102 Write族手続き: @code{write}, @code{write-shared}, @code{write-simple}---これらは、Schemeオブジェクトの@emph{外部表現}を出力します。出力されたものは一般に、
26103 @code{read}を使って、可能な限り情報を失わずに読み戻すことができます@footnote{ある意味、
26104 これは他のプログラミング言語でシリアライズやマーシャライズと呼ばれている操作に
26105 似ています。一般のSchemeオブジェクトをディスクやネットワークに@code{write}して、
26106 それを@code{read}すれば、元のオブジェクトと等価なオブジェクトが得られるわけです。
26107 Lisp族言語では、これは@emph{read/write invariance}と呼ばれ、組み込みの機能と
26108 なっています。但しオブジェクトによってはこの性質を持たないものもあり、
26109 そういうオブジェクトを扱う時は専用のシリアライザを書く必要があります。}。
26110 Schemeオブジェクトの外部表現は、リテラルデータをプログラム中に記述するのと
26111 同じ書き方なので、これがSchemeオブジェクトを出力する際のデフォルトの表現になっています。
26112 @item
26113 Display族手続き: @code{display}, @code{print}, @code{newline}.
26114 これらは人間に読みやすいプレーンテキストな出力を生成します。
26115 @end itemize
26116 @c COMMON
26117
26118 @c EN
26119 @item High-level formatting output
26120 To produce output in specific width, alignment, etc: @code{format}.
26121 This corresponds to C's @code{printf}.
26122 @c JP
26123 @item 高レベル整形出力
26124 出力を指定の桁数に揃えたり、どちらかに寄せたり、といった書式を指定できる手続きが
26125 @code{format}です。Cの@code{printf}のようなものです。
26126 @c COMMON
26127
26128 @c EN
26129 @item Low-level type-specific output
26130 Procedures that deal with raw data.
26131 @itemize @bullet
26132 @item
26133 To output a character or a byte: @code{write-char}, @code{write-byte}.
26134 @item
26135 To output a string or an array of binary data: @code{write-string},
26136 @code{write-uvector}.
26137 @item
26138 To flush the output buffer: @code{flush}, @code{flush-all-ports}.
26139 @end itemize
26140 @c JP
26141 @item 低レベル、特定の型用の出力
26142 「生」のデータを扱う手続きです。
26143 @itemize @bullet
26144 @item
26145 文字毎やバイト毎の出力: @code{write-char}, @code{write-byte}
26146 @item
26147 文字列やバイナリデータの配列の出力: @code{write-string},
26148 @code{write-uvector}
26149 @item
26150 出力バッファのフラッシュ: @code{flush}, @code{flush-all-ports}
26151 @end itemize
26152 @c COMMON
26153 @end table
26154
26155 @node Output controls, Object output, Layers of output routines, Output
26156 @subsubsection Output controls
26157 @c NODE 出力制御
26158
26159 @deftp {Class} <write-controls>
26160 @clindex write-controls
26161 @c EN
26162 You can control several aspects of Lisp structure output via
26163 @code{<write-controls>} object. The object output routines
26164 (e.g. @code{write, display}) and the high-level output routines
26165 (e.g. @code{format}) can take optional write-controls.
26166 @c JP
26167 Lisp構造の出力形式は、
26168 @code{<write-controls>}オブジェクトによって制御することができます。
26169 Lispオブジェクトを出力するルーチン(@code{write, display}等)や、
26170 高レベル出力手続き(@code{format}等)は出力制御オブジェクトを取ることができます。
26171 @c COMMON
26172
26173 @c EN
26174 The following example may give you some ideas on what
26175 write controls can do:
26176 @c JP
26177 以下の例で、出力制御の様子がわかると思います。
26178 @c COMMON
26179
26180 @example
26181 (write '(1 10 100 1000)
26182 (make-write-controls :base 16 :radix #t))
26183 @r{prints} (#x1 #xa #x64 #x3e8)
26184
26185 (write (iota 100)
26186 (make-write-controls :length 5))
26187 @r{prints} (0 1 2 3 4 ...)
26188 @end example
26189
26190 @c EN
26191 The @code{make-write-controls} procedure returns a write-controls object,
26192 which has the following slots (those slot names are taken from Common Lisp's
26193 print control variables):
26194 @c JP
26195 @code{make-write-controls}手続きは出力制御オブジェクトを作って返します。
26196 出力制御オブジェクトは以下のスロットを持ちます
26197 (これらのスロット名はCommon Lispの対応するプリント制御変数から取られました)。
26198 @c COMMON
26199
26200 @defivar <write-controls> length
26201 @c EN
26202 If this slot has a nonnegative integer, it determines the maximum number
26203 of items displayed for lists and vectors (including uniform vectors).
26204 If the sequence has more elements than the limit, an ellipsis is printed
26205 in place. If this slot is @code{#f} (default), sequence will be written
26206 out fully.
26207 @c JP
26208 このスロットが非負整数の場合、それはリストとベクタ(ユニフォームベクタを含む)の
26209 要素が表示される最大数を指定します。もしリストやベクタがその最大数より
26210 多くの要素を持っている場合、残りの要素は表示されず、代わりに
26211 エリプシスが表示されます。このスロットが@code{#f}(デフォルト)であれば、
26212 すべての要素が表示されます。
26213 @c COMMON
26214 @end defivar
26215
26216 @defivar <write-controls> level
26217 @c EN
26218 If this slot has a nonnegative integer, it determines the maximum depth
26219 of the structure (lists and vectors) to be displayed. If the structure
26220 has deeper node, it will be printed as @code{#}.
26221 If this slot is @code{#f} (default), no depth limit is enforced.
26222 @c JP
26223 このスロットが非負整数の場合、それは構造体(リストとベクタ)が表示される
26224 最大の深さを指定します。もし構造体がより深いノードを持っている場合、
26225 そのノードの代わりに@code{#}が表示されます。
26226 このスロットが@code{#f}(デフォルト)であれば、すべての要素が表示されます。
26227 @c COMMON
26228 @end defivar
26229
26230 @defivar <write-controls> base
26231 @c EN
26232 This slot must have an integer between 2 and 36, inclusive, and specifies
26233 the radix used to print exact numbers. The default value is 10.
26234 @c JP
26235 このスロットは2以上36以下の整数でなければならず、
26236 正確な整数を印字する基数を指定します。デフォルトは10です。
26237 @c COMMON
26238 @end defivar
26239
26240 @defivar <write-controls> radix
26241 @c EN
26242 This slot must have a boolean value. If it is true, radix prefix
26243 is always printed before exact numbers. The default value is @code{#f}.
26244 @c JP
26245 このスロットは真偽値を持ちます。真であれば、
26246 正確な整数の前に常に基数プレフィクスが表示されます。
26247 デフォルトは@code{#f}です。
26248 @c COMMON
26249 @end defivar
26250
26251 @defivar <write-controls> pretty
26252 @c EN
26253 If this slot has true value,
26254 @emph{pretty printing} is used, that is, newlines and indentations are
26255 inserted
26256 to show nested data structures fit in the specified width of columns.
26257 @c JP
26258 このスロットが真の値の場合、
26259 指定されたカラム幅内で、改行やインデントを適宜挿入してネストした構造を見やすく表示する、
26260 @emph{プリティプリント}機能を使います。
26261 @c COMMON
26262 @end defivar
26263
26264 @defivar <write-controls> width
26265 @c EN
26266 If this slot has a nonnegative integer, it specifies the display
26267 column width used for pretty printing.
26268 @c JP
26269 このスロットが非負整数の場合、プリティプリントで使われる表示幅を指定します。
26270 @c COMMON
26271 @end defivar
26272
26273 @defivar <write-controls> indent
26274 @c EN
26275 This slot must be a nonnegative exact integer. If this is greater than zero,
26276 and the @code{pretty} slot is true,
26277 that number of whitespaces are written out after the pretty printer emits
26278 a newline. That is, the second and after lines are indented.
26279 If the @code{pretty} slot is false, this slot is ignored and no indentation
26280 is done.
26281
26282 Note that the first line is not indended; the intention is that pretty
26283 printing begins at a certain column, so that no whitespace insetion
26284 is needed for the first line but the rest of lines need to be indented
26285 to align to the beginning of pretty print.
26286 @c JP
26287 このスロットの値は非負の正確な整数でなければなりません。
26288 このスロットの値がゼロより大きく、@code{pretty}スロットが偽でなければ、
26289 プリティプリンタは改行文字を出力した後にこのスロットの数だけ空白文字を出力します。
26290 つまり、2行め以降がインデントされることになります。
26291 @code{pretty}スロットが偽であればこのスロットは無視されインデントも行われません。
26292
26293 最初の行はインデントされないことに注意してください。
26294 想定する使い方は、あるカラムからプリティプリントを開始することです。この場合、
26295 1行目はそのまま出力できますが、2行目以降を1行目と揃うようにインデントする必要があります。
26296 @c COMMON
26297 @end defivar
26298
26299 @defivar <write-controls> string-length
26300 @c EN
26301 This slot must be a nonnegative exact integer or @code{#f}.
26302 If its value is an integer, string literals longer than the value
26303 are truncated during output; an ellipsis is shown after truncated
26304 content, before closing double-quotes.
26305 @c JP
26306 このスロットは非負整数か@code{#f}です。非負整数の場合、その長さ以上の文字列リテラルは
26307 切り詰めて表示されます。このスロットの値ぶんの文字が出力されたのち、
26308 エリプシスとダブルクオートが出力されます。
26309 @c COMMON
26310 @end defivar
26311
26312 @c EN
26313 A write-controls object is immutable. If you need a controls object
26314 with a slight variation of an existing controls object,
26315 use @code{write-controls-copy}.
26316 @c JP
26317 出力制御オブジェクトは変更不可です。もし既に存在する制御オブジェクトを
26318 少し変えたものが欲しければ、@code{write-controls-copy}が使えます。
26319 @c COMMON
26320
26321 @c EN
26322 Note: When we introduced @code{<write-controls>} object in 0.9.5,
26323 we used slot names as @code{print-length}, @code{print-pretty} etc.,
26324 mirroring Common Lisp's special variables. However, the @code{print-} part
26325 is redundant, as it is a part of a class dedicated to print control. So
26326 we changed the slot names as of 0.9.6.
26327 The procedures @code{make-write-controls} and @code{write-controls-copy}
26328 accepts both old and new names for the backward compatibility. The old
26329 code that directly refers to the slots needs to be rewritten (we think
26330 there're a not a lot). We'll drop the old name support in 1.0 release.
26331 @c JP
26332 註: 0.9.5で@code{<write-controls>}オブジェクトを導入した際には、
26333 Common Lispのスペシャル変数の名前をそのまま反映した
26334 @code{print-length}、@code{print-pretty}等をスロット名としていました。
26335 しかし出力制御オブジェクトの一部であることがわかっている以上、@code{print-}の部分は冗長です。
26336 そこで0.9.6からスロット名を変えました。
26337 互換性のために、@code{make-write-controls}と@code{write-controls-copy}は
26338 古いスロット名でのキーワード引数も認識します。
26339 スロットを直接指定してアクセスしているコードは修正の必要があります。
26340 1.0リリース時に古いスロット名のサポートを落とす予定です。
26341 @c COMMON
26342 @end deftp
26343
26344 @defun make-write-controls :key length level base radix pretty width indent string-length
26345 @c EN
26346 Creates and returns a write-controls object.
26347 @c JP
26348 出力制御オブジェクトを作って返します。
26349 @c COMMON
26350 @end defun
26351
26352 @defun write-controls-copy controls :key length level base radix pretty width indent string-length
26353 @c EN
26354 Returns a copy of another write-controls object @var{controls}.
26355 If keyword arguments are given, those values override the
26356 original values.
26357 @c JP
26358 出力制御オブジェクト@var{controls}のコピーを返します。もしキーワード引数が
26359 与えられれば、その要素が置き換えられます。
26360 @c COMMON
26361 @end defun
26362
26363 @c EN
26364 Note: The high-level output procedures can be recursively called
26365 via @code{write-object} method. In that case, the write controls
26366 of the root output call will be automatically inherited to the
26367 recursive output calls to the same port.
26368 @c JP
26369 高レベル出力手続きは@code{write-object}メソッドを経由して再帰的に
26370 呼ばれる可能性があります。その場合、大元の出力手続き呼び出しに渡された
26371 出力制御オブジェクトが、同じポートに対して出力する再帰的に呼ばれる
26372 出力手続きへと自動的に引き継がれます。
26373 @c COMMON
26374
26375 @node Object output, Formatting output, Output controls, Output
26376 @subsubsection Object output
26377 @c NODE オブジェクトの出力
26378
26379 @c EN
26380 For the following procedures, the optional @var{port} argument must be
26381 an output port, and when omitted, the current output port is assumed.
26382 @c JP
26383 以下の手続きで、省略可能な引数@var{port}は出力ポートでなければなりません。
26384 省略された場合が現在の出力ポートが使われます。
26385 @c COMMON
26386
26387 @c EN
26388 Some procedures take @var{port/controls} argument, which can be either
26389 an output port or @code{<write-controls>} object. For example, @code{write}
26390 takes up to two such optional arguments; that is, you can call it
26391 as @code{(write obj)}, @code{(write obj port)},
26392 @code{(write obj controls)}, @code{(write obj port controls)}
26393 or @code{(write obj controls port)}. When omitted, the port is assumed
26394 to be the current output port, and the controls is assumed to be the default
26395 controls.
26396 @c JP
26397 いくつかの手続きは@var{port/controls}引数を取ります。これは、出力ポート
26398 もしくは@code{<write-controls>}オブジェクトでなければなりません。例えば
26399 @code{write}は二つまでそういった引数を取ります。すなわち、@code{write}は
26400 以下のいずれの形式でも呼び出すことができます:
26401 @code{(write obj)}、@code{(write obj port)}、
26402 @code{(write obj controls)}、@code{(write obj port controls)}、
26403 @code{(write obj controls port)}。
26404 省略された場合、ポートは現在の出力ポート、出力制御についてはデフォルトの出力制御が
26405 使われます。
26406 @c COMMON
26407
26408 @defun write obj :optional port/controls1 port/controls2
26409 @defunx write-shared obj :optional port/controls1 port/controls2
26410 @defunx write-simple obj :optional port/controls1 port/controls2
26411 [R7RS+ write]
26412 @c EN
26413 The @code{write}-family procedures are used to write an
26414 external representation of Scheme object,
26415 which can be read back by @code{read} procedure. The three
26416 procedures differ in a way to handle shared or circular structures.
26417 @c JP
26418 @code{write}族の手続きは、Schemeオブジェクトの外部表現を出力します。
26419 外部表現は一般に、@code{read}手続きによって読み戻せば、
26420 元のオブジェクトと同等のオブジェクトとなります。
26421 この3つの手続きの違いは、共有構造および循環構造の扱いにあります。
26422 @c COMMON
26423
26424 @c EN
26425 @code{Write} is circular-safe; that is, it uses datum label notation
26426 (@code{#n=} and @code{#n#}) to show cycles. It does not use datum label
26427 notation for non-circular structures that are merely shared
26428 (see the second example).
26429 @c JP
26430 @code{write}は循環構造に対して安全です。データに循環がある場合は
26431 データラベル記法(@code{#n=}と@code{#n#})を用いてそれを表現します。
26432 循環の無い、単に共有されているだけの構造についてはデータラベル記法を使いません
26433 (二番目の例参照)。
26434 @c COMMON
26435
26436 @example
26437 (let1 x (list 1)
26438 (set-cdr! x x) ; create a cycle
26439 (write x))
26440 @result{} @r{shows} #0=(1 . #0#)
26441
26442 (let1 x (list 1)
26443 (write (list x x)))
26444 @result{} @r{shows} ((1) (1))
26445 @end example
26446
26447 @c EN
26448 @code{Write-shared} is also circular-safe, and it also shows
26449 shared structures using datum labels. Use this if you need
26450 to preserve topology of a graph structure.
26451 @c JP
26452 @code{write-shared}も循環構造に対して安全で、さらに共有構造も
26453 データラベル記法で表示します。グラフ構造のトポロジーを維持する必要がある
26454 場合はこの手続きを使ってください。
26455 @c COMMON
26456
26457 @example
26458 (let1 x (list 1)
26459 (write-shared (list x x)))
26460 @result{} @r{shows} (#0=(1) #0#)
26461 @end example
26462
26463 @c EN
26464 Finally, @code{write-simple} writes out the object recursively
26465 without taking account of shared or circular structures. This is fast,
26466 for it doesn't need to scan the structure before actually writing out.
26467 However, it won't stop when a circular structure is passed.
26468 @c JP
26469 最後に、@code{write-simple}はオブジェクトを、共有構造や循環構造を考慮せずに
26470 再帰的に表示します。これは出力前に共有構造の検出パスを走らせる必要がないので
26471 高速です。しかし、渡されたデータに循環があった場合は出力が止まらなくなります。
26472 @c COMMON
26473
26474 @c EN
26475 When these procedures encounter an object of
26476 a user-defined class, they call the generic function @code{write-object}.
26477 @c JP
26478 これらの手続きが表示中にユーザ定義クラスのオブジェクトに
26479 出会った場合は、ジェネリックファンクション@code{write-object}を呼び出します。
26480 @c COMMON
26481
26482 @c EN
26483 Historical context: @code{Write} has been in Scheme standards, but
26484 handling of circular structures hasn't been specified until R7RS.
26485 In fact, until Gauche 0.9.4,
26486 @code{write} diverged for circular structures.
26487 SRFI-38 introduced the datum-label notation and
26488 @code{write-with-shared-structure} and @code{write/ss} procedures
26489 to produce such notation, and Gauche supported it.
26490 R7RS clarified this issue, and Gauche 0.9.4 followed.
26491 @c JP
26492 歴史的経緯: @code{write}は以前のScheme標準にもありましたが、
26493 循環構造があった場合の振る舞いはR7RSになるまで規定されていませんでした。
26494 実際、Gauche 0.9.4より前の@code{write}は、循環構造を渡されると停止しません。
26495 SRFI-38はデータラベル記法および、それを表示するための
26496 @code{write-with-shared-structure}と@code{write/ss}手続きを導入し、
26497 Gaucheもそれをサポートしていました。
26498 R7RSでこの問題は明確にされ、Gaucheも0.9.4からそれに沿っています。
26499 @c COMMON
26500 @end defun
26501
26502
26503 @defun write-with-shared-structure obj :optional port
26504 @defunx write/ss obj :optional port
26505 @defunx write* obj :optional port
26506 [SRFI-38]
26507 @c EN
26508 These are aliases of @code{write-shared} above.
26509 @c JP
26510 これらは上記の@code{write-shared}の別名です。
26511 @c COMMON
26512
26513 @c EN
26514 Gauche has been used the name @code{write*} for long, which is
26515 taken from STklos. SRFI-38 defines @code{write-with-shared-structure}
26516 and @code{write/ss}. These names are kept for the backward compatibility.
26517 New code should use @code{write-shared}.
26518 @c JP
26519 Gaucheは、STklosから取った@code{write*}という名前を長く使ってきましたが、
26520 SRFI-38によって@code{write-with-shared-structure}と@code{write/ss}が
26521 定義されました。これらの名前は互換性のためだけに残してあります。
26522 新たなコードには@code{write-shared}を使ってください。
26523 @c COMMON
26524 @end defun
26525
26526
26527 @defun display obj :optional port/controls1 port/controls2
26528 [R7RS write]
26529 @c EN
26530 Produces a human-friendly representation of an object @var{obj}
26531 to the output port.
26532
26533 If @var{obj} contains cycles, @code{display} uses datum-label notation.
26534
26535 When @code{display} encounters an object of
26536 a user-defined class, it calls the generic function @code{write-object}.
26537 @c JP
26538 オブジェクト@var{obj}の人に読みやすい表現を、出力ポートに書き出します。
26539
26540 @var{obj}が循環構造を含んでいる場合は、データラベル記法を使って出力します。
26541
26542 @code{display}が表示中にユーザ定義クラスのオブジェクトに
26543 出会った場合は、ジェネリックファンクション@code{write-object}を呼び出します。
26544 @c COMMON
26545
26546 @example
26547 (display "\"Mahalo\", he said.")
26548 @result{} @r{shows} "Mahalo", he said.
26549
26550 (let ((x (list "imua")))
26551 (set-cdr! x x)
26552 (display x))
26553 @result{} @r{shows} #0=(imua . #0#)
26554 @end example
26555 @end defun
26556
26557
26558 @defun print expr @dots{}
26559 @c EN
26560 Displays @var{expr}s (using @code{display}) to the current output port,
26561 then writes a newline.
26562 @c JP
26563 @var{expr} @dots{} を@code{display}を使って現在の出力ポートに表示し、
26564 最後に改行を書き出します。
26565 @c COMMON
26566 @end defun
26567
26568 @defun pprint obj :key port controls width length level newline indent
26569 @c EN
26570 Pretty prints @var{obj} to @var{port}, which is defaulted to the current
26571 output port. The same effect is achieved by passing the @code{write} procedure
26572 a write control with @code{pretty} slot setting to @code{#t}
26573 (in fact, it is how @code{pprint} is implemented), but this procedure
26574 provides more convenient interface when you want to play with the
26575 pretty printer.
26576
26577 By default, @code{pprint} prints a newline after writing @var{obj}.
26578 You can suppress this newline by passing @code{#f} to @var{newline} keyword
26579 argument.
26580
26581 To customize pretty printing, you can pass a write control object
26582 to the @var{controls} keyword argument (the @code{pretty} slot of
26583 @var{controls} is ignored; it'll always printed prettily).
26584 Furthermore, you can override @code{width}, @code{length}, @code{level},
26585 and @code{indent}
26586 slots of @var{controls}. If you omit @var{controls}, a reasonable default
26587 value is assumed.
26588 @xref{Output controls}, for the detail of write controls.
26589 @c JP
26590 @var{obj}を@var{port}に整形出力(prettyprint)します。
26591 @var{port}が省略された場合は現在の出力ポートが使われます。
26592 この手続きと同じ効果は、@code{write}手続きに@code{pretty}スロットを@code{#t}にした
26593 出力制御オブジェクトを渡すことでも得られます
26594 (実際、内部的には@code{pprint}はそうやって@code{write}を呼び出しているだけです)
26595 が、手軽に整形出力を試してみたい場合にこの手続きは便利です。
26596
26597 デフォルトでは、@code{pprint}は@var{obj}を出力した後に改行します。
26598 この動作を抑制するには@var{newline}に@code{#f}を渡してください。
26599
26600 出力の整形をカスタマイズするには、@var{controls}キーワード引数に出力制御オブジェクトを
26601 渡します(渡された制御オブジェクトの@code{pretty}スロットは無視されます;
26602 常に出力は整形されます)。さらに、出力制御オブジェクトの
26603 @code{width}、@code{length}、@code{level}、@code{indent}スロットを、
26604 それぞれのキーワード引数でオーバライドできます。
26605 @var{controls}を省略した場合は適切なデフォルト値が使われます。
26606 出力制御の詳細については@ref{Output controls}を参照してください。
26607 @c COMMON
26608
26609 @example
26610 (pprint (make-list 6 '(gauche droite)))
26611 @result{} @r{prints}
26612 ((gauche droite) (gauche droite) (gauche droite) (gauche droite)
26613 (gauche droite) (gauche droite))
26614
26615 (pprint (make-list 6 '(gauche droite)) :width 20)
26616 @result{} @r{prints}
26617 ((gauche droite)
26618 (gauche droite)
26619 (gauche droite)
26620 (gauche droite)
26621 (gauche droite)
26622 (gauche droite))
26623
26624 (pprint (make-list 6 '(gauche droite)) :length 3)
26625 @result{} @r{prints}
26626 ((gauche droite) (gauche droite) (gauche droite) …)
26627
26628 (pprint (make-list 6 '(gauche droite)) :level 1)
26629 @result{} @r{prints}
26630 (# # # # # #)
26631 @end example
26632 @end defun
26633
26634 @deffn {Method} write-object (obj <object>) port
26635 @c EN
26636 You can customize how the object is printed out by this method.
26637 @c JP
26638 このメソッドをつかって、オブジェクトをどのように印字するかをカスタマイズ
26639 できます。
26640 @c COMMON
26641 @end deffn
26642
26643 @defun newline :optional port
26644 [R7RS base]
26645 @c EN
26646 Writes a newline character to @var{port}.
26647 This is equivalent to @code{(write-char #\newline port)},
26648 @code{(display "\n" port)}. It is kept for a historical reason.
26649 @c JP
26650 @var{port}に改行文字を書き出します。@code{(write-char #\newline port)}や
26651 @code{(display "\n" port)}と書いても同じことですが、歴史的な理由から
26652 残されています。
26653 @c COMMON
26654 @end defun
26655
26656 @defun fresh-line :optional port
26657 @c EN
26658 If the output column is at the beginning of line, do nothing and
26659 returns @code{#f}. Otherwise, writes a newline character and returns @code{#t}.
26660 It is handy when you want to make sure the next output starts
26661 from the beginning of line, but do not want to produce an extra blank line.
26662
26663 This procedure is taken from Common Lisp.
26664 @c JP
26665 出力カラムが行頭であれば何もせず@code{#f}を返します。そうでなければ@code{#\newline}
26666 を出力して@code{#t}を返します。
26667 次の出力を行頭から始めたいけれど、余分な空行は出力したくない、という時に便利です。
26668
26669 この手続きはCommon Lispから取りました。
26670 @c COMMON
26671
26672 @c EN
26673 Not all situations allow this procedure to know the port's output column;
26674 especially, if you mix textual and binary data to output, the column
26675 tracking becomes unreliable. If this procedure can't detrmine the
26676 column position, it emits a newline character.
26677 @c JP
26678 常にポートの出力カラムがわかるとは限りません。特に、テキスト出力とバイナリ出力を
26679 混ぜた場合、出力カラムのトラッキングは信頼できないものとなります。
26680 出力カラムが特定できない場合は、この手続きは改行文字を出力します。
26681 @c COMMON
26682 @end defun
26683
26684
26685
26686 @node Formatting output, Low-level output, Object output, Output
26687 @subsubsection Formatting output
26688 @c NODE フォーマット出力
26689
26690
26691
26692 @defun format [d/c1 [d/c2]] format-string arg @dots{}
26693 [SRFI-28+]
26694 @c EN
26695 Format @var{arg} @dots{} according to @var{format-string}.
26696 This function is a subset of CommonLisp's @code{format} function,
26697 with a bit of extension. It is also a superset of SRFI-28,
26698 Basic format strings.
26699 @c JP
26700 @var{string} の指示に従い、@var{arg} @dots{}をフォーマットします。
26701 この手続きはCommonLispの@code{format}のサブセットに、Gauche独自の拡張を
26702 加えたものです。また、これはSRFI-28 "Basic format strings" のスーパーセットに
26703 なっています。
26704 @c COMMON
26705
26706 @c EN
26707 The procedure has unusual signature. The two optional arguments,
26708 @var{d/c1} and @var{d/c2}, can be an object to specify the destination,
26709 or a @code{<write-controls>} object to tailor
26710 @code{~s} and @code{~a} output
26711 (@pxref{Output controls}).
26712 You can give none, either one of them,
26713 or both, in any order.
26714 @c JP
26715 この手続きは奇妙なシグネチャを持っています。
26716 最初の二つの省略可能引数、@var{d/c1}と@var{d/c2}は、
26717 出力先を指定するオブジェクトか、@code{~s}と@code{~a}の出力形式をカスタマイズする
26718 @code{<write-controls>}オブジェクトです(@ref{Output controls}参照)。
26719 それらをどちらも渡さないことも、どちらかだけを渡すことも、両方渡すこともできます。
26720 両方渡す場合の順番は自由です。
26721 @c COMMON
26722
26723 @c EN
26724 Note: SRFI-28's @code{format} does not take optional arguments before
26725 @var{format-string}
26726 @c JP
26727 註: SRFI-28の@code{format}は@var{format-string}の前に省略可能引数を取りません。
26728 @c COMMON
26729
26730 @c EN
26731 If you give an object to specify destination, it must be either an output
26732 port or a boolean value.
26733 If it is an output port, the
26734 formatted result is written to it; if it is @code{#t},
26735 the result is written to the current output port;
26736 if it is @code{#f}, the formatted result is returned as a string.
26737 @var{Dest} can be omitted, as SRFI-28 @code{format};
26738 it has the same effects as giving @code{#f} to the @var{dest}.
26739 @c JP
26740 出力先を指定するオブジェクトを渡す場合、それは出力ポートか真偽値でなければなりません。
26741 それが出力ポートであれば、フォーマットされた
26742 結果はそのポートに書き出されます。@var{port}が@code{#t}であれば、結果は
26743 現在の出力ポートに書き出されます。@var{port}が@code{#f}であれば、結果は
26744 文字列として@code{format}から返されます。
26745 @var{dest}は省略することもできます。その場合は、@code{dest}に@code{#f}
26746 を指定したのと同じ動作をします(SRFI-28の@code{format})。
26747 @c COMMON
26748
26749 @c EN
26750 @var{string} is a string that contains format directives.
26751 A format directive is a character sequence begins with tilde, `@code{~}',
26752 and ends with some specific characters. A format directive takes
26753 the corresponding @var{arg} and formats it. The rest of string is
26754 copied to the output as is.
26755 @c JP
26756 @var{string}はフォーマット指示子を含んだ文字列です。
26757 フォーマット指示子はチルダ`@code{~}'から始まり、特定の文字で終了する文字の並びで、
26758 それぞれのフォーマット指示子が対応する@var{arg}を取りフォーマットします。
26759 @var{string}内のフォーマット指示子以外の文字列はそのまま出力されます。
26760 @c COMMON
26761
26762 @example
26763 (format #f "the answer is ~s" 42)
26764 @result{} "the answer is 42"
26765 @end example
26766
26767 @c EN
26768 The format directive can take one or more @var{parameters}, separated
26769 by comma characters. A parameter may be an integer or a character;
26770 if it is a character, it should be preceded by a quote character.
26771 Parameter can be omitted, in such case the system default value is
26772 used. The interpretation of the parameters depends on the
26773 format directive.
26774 @c JP
26775 フォーマット指示子は一つ以上のコンマで区切られたパラメータを取ることもできます。
26776 パラメータは整数か文字です。文字の場合、クオート文字に続けてその文字を置きます。
26777 パラメータが省略された場合は既定値が使われます。パラメータの意味はフォーマット指示子毎に
26778 異なります。
26779 @c COMMON
26780
26781 @c EN
26782 Furthermore, a format directive can take two
26783 additional flags: atmark `@code{@@}' and colon `@code{:}'. One or
26784 both of them may modify the behavior of the format directive.
26785 Those flags must be placed immediately before the directive
26786 character.
26787 @c JP
26788 さらに、フォーマット指示子は2種類のフラグ、`@code{@@}' と `@code{:}' を
26789 取ることができます。これらの組合せでフォーマットの動作が変わります。フラグは
26790 (もしあれば)パラメータの後、指示子の文字の直前に置かれなければなりません。
26791 @c COMMON
26792
26793 @c EN
26794 If a character `@code{v}' or `@code{V}' is in the place of the
26795 parameter, the value of the parameter is taken from the format's
26796 argument. The argument must be either an integer, a character, or
26797 @code{#f} (indicating that the parameter is effectively omitted).
26798 @c JP
26799 パラメータの位置に文字 `@code{v}' か `@code{V}' を置くこともできます。
26800 その場合、パラメータの値が引数リストから取られます。対応する引数は整数か
26801 文字、または@code{#f}でなければなりません。@code{#f}の場合はそのパラメータが
26802 省略されたのと同じになります。
26803 @c COMMON
26804
26805 @c EN
26806 Some examples:
26807
26808 @table @code
26809 @item ~10,2s
26810 A format directive @code{~s}, with two parameters, 10 and 2.
26811 @item ~12,,,'*A
26812 A format directive @code{~a}, with 12 for the first parameter and
26813 a character `@code{*}' for the fourth parameter. The second and
26814 third parameters are omitted.
26815 @item ~10@@d
26816 A format directive @code{~d}, with 10 for the first parameter and
26817 `@code{@@}' flag.
26818 @item ~v,vx
26819 A format directive @code{~x}, whose first and second parameter will
26820 be taken from the arguments.
26821 @end table
26822 @c JP
26823 いくつかの例です。
26824
26825 @table @code
26826 @item ~10,2s
26827 パラメータ10と2を伴う、フォーマット指示子@code{~s}。
26828 @item ~12,,,'*A
26829 第1パラメータに数値12、第4パラメータに文字`@code{*}'を取るフォーマット指示子@code{~a}。
26830 第2と第3のパラメータは省略されています。
26831 @item ~10@@d
26832 フォーマット指示子@code{~d}。パラメータ10と`@code{@@}'フラグがついています。
26833 @item ~v,vx
26834 フォーマット指示子@code{~x}。第1パラメータと第2パラメータは引数リストから取られます。
26835 @end table
26836 @c COMMON
26837
26838 @c EN
26839 The following is a complete list of the supported format directives.
26840 Either upper case or lower case character can be used for the format
26841 directive; usually they have no distinction, except noted.
26842 @c JP
26843 以下にサポートされているフォーマット指示子を示します。フォーマット指示子の文字自体は
26844 大文字であっても小文字であっても構いません。特に断りのない限り両者は同じ動作をします。
26845 @c COMMON
26846
26847 @table @asis
26848 @item @b{~A}
26849 @c EN
26850 Parameters: @var{mincol},@var{colinc},@var{minpad},@var{padchar},@var{maxcol}
26851
26852 Ascii output. The corresponding argument is printed by @code{display}.
26853 If an integer @var{mincol} is given, it specifies the minimum number
26854 of characters to be output; if the formatted result is shorter than
26855 @var{mincol}, a whitespace is padded to the right (i.e. the result
26856 is left justified).
26857 @c JP
26858 パラメータ: @var{mincol},@var{colinc},@var{minpad},@var{padchar},@var{maxcol}
26859
26860 ASCII出力。対応する引数が@code{display}を使ってフォーマットされます。
26861 整数が@var{mincol}に与えられた場合、それは出力される最小の文字数を指定します。
26862 引数のフォーマット結果が@var{mincol}より短ければ、空白が右に追加されます(つまり、
26863 左詰めになります)。
26864 @c COMMON
26865
26866 @c EN
26867 The @var{colinc}, @var{minpad} and @var{padchar} parameters
26868 control, if given, further padding. A character @var{padchar} replaces
26869 the padding character for the whitespace. If an integer @var{minpad}
26870 is given and greater than 0, at least @var{minpad} padding character
26871 is used, regardless of the resulting width. If an integer @var{colinc}
26872 is given, the padding character is added (after @var{minpad}) in chunk
26873 of @var{colinc} characters, until the entire width exceeds @var{mincol}.
26874 @c JP
26875 @var{colinc}、@var{minpad}、そして@var{padchar}は更に細かいパディング方法を
26876 指定します。@var{padchar}に文字が与えられた場合、それが空白文字の代わりにパディング文字と
26877 して使われます。@var{minpad}に0以上の整数が与えられた場合、少なくともその数だけの
26878 パディング文字が追加されます。@var{colinc}が指定された場合、
26879 追加されるパディング文字の数が@var{colinc}の倍数に調整されます。
26880 @c COMMON
26881
26882 @c EN
26883 If atmark-flag is given, the format result is right justified, i.e.
26884 padding is added to the left.
26885 @c JP
26886 アトマーク `@code{@@}' フラグが与えられた場合、結果は右詰めになります。
26887 @c COMMON
26888
26889 @c EN
26890 The @var{maxcol} parameter, if given, limits the maximum number of characters
26891 to be written. If the length of formatted string exceeds
26892 @var{maxcol}, only @var{maxcol} characters are written.
26893 If colon-flag is given as well and the length of formatted string
26894 exceeds @var{maxcol}, @var{maxcol} - 4 characters are written and
26895 a string ``@code{ ...}'' is attached after it.
26896 @c JP
26897 @var{maxcol}パラメータは与えられていれば書かれる文字数の上限を指定します。
26898 フォーマット後の文字列の長さが@var{maxcol}を超えた場合、@var{maxcol}文字だけが
26899 書かれます。コロン `@code{:}' フラグが同時に与えられていれば、
26900 @var{maxcol} - 4 文字が書かれた後、文字列``@code{ ...}''が書かれます。
26901 @c COMMON
26902
26903 @example
26904 (format #f "|~a|" "oops")
26905 @result{} "|oops|"
26906 (format #f "|~10a|" "oops")
26907 @result{} "|oops |"
26908 (format #f "|~10@@a|" "oops")
26909 @result{} "| oops|"
26910 (format #f "|~10,,,'*@@a|" "oops")
26911 @result{} "|******oops|"
26912 @c JP
26913 (format #f "|~10,,,'☆a|" "oops")
26914 @result{} "|oops☆☆☆☆☆☆|"
26915 @c COMMON
26916
26917 (format #f "|~,,,,10a|" '(abc def ghi jkl))
26918 @result{} "|(abc def gh|"
26919 (format #f "|~,,,,10:a|" '(abc def ghi jkl))
26920 @result{} "|(abc de ...|"
26921 @end example
26922
26923 @item @b{~S}
26924 @c EN
26925 Parameters: @var{mincol},@var{colinc},@var{minpad},@var{padchar},@var{maxcol}
26926
26927 S-expression output. The corresponding argument is printed
26928 by @code{write}. The semantics of parameters and flags are the same
26929 as @code{~A} directive.
26930 @c JP
26931 パラメータ: @var{mincol},@var{colinc},@var{minpad},@var{padchar},@var{maxcol}
26932
26933 S式出力。対応する引数が@code{write}を使ってフォーマットされます。
26934 パラメータの意味は@code{~A}指示子と同じです。
26935 @c COMMON
26936
26937 @example
26938 (format #f "|~s|" "oops")
26939 @result{} "|\"oops\"|"
26940 (format #f "|~10s|" "oops")
26941 @result{} "|\"oops\" |"
26942 (format #f "|~10@@s|" "oops")
26943 @result{} "| \"oops\"|"
26944 (format #f "|~10,,,'*@@s|" "oops")
26945 @result{} "|****\"oops\"|"
26946 @c JP
26947 (format #f "|~10,,,'★s|" "oops")
26948 @result{} "|\"oops\"★★★★|"
26949 @c COMMON
26950 @end example
26951
26952 @item @b{~W}
26953 @c EN
26954 Parametres: None
26955
26956 Write prettily. Without flags, it just works like @code{~S}. If
26957 a colon flag is given, it works like pretty print, i.e. @code{pretty}
26958 slot of the write context is true. If an atmark flag is given,
26959 it works like @code{length} and @code{level} slots of the write
26960 context is @code{#f}, i.e. temporarily turn off length and level limits.
26961
26962 The indent of pretty print is set at the position where @code{~W} begins,
26963 so that if the output spans multiple lines, the second and following lines
26964 are indented properly.
26965 @c JP
26966 パラメータ: なし
26967
26968 きれいな出力。フラグが無ければ@code{~S}と全く同じですが、
26969 コロンフラグが与えられるとプリティプリントを行います。つまり、
26970 @code{<write-context>}の@code{pretty}スロットが一時的に真になります。
26971 また、アトマークフラグが与えられると、S式の長さ制限および深さ制限を一時的にオフにします。
26972 つまり、@code{<write-context>}の@code{length}と@code{level}スロットを@code{#f}
26973 にします。
26974
26975 プリティプリントのインデントは@code{~W}の出力開始位置にセットされるので、
26976 プリティプリントによって出力が複数行になった場合も開始位置に揃うようにインデントされます。
26977 @c COMMON
26978
26979 @example
26980 (format #t "Result: ~:w\n" (make-list 40 'aaaa))
26981 @result{} @r{prints:}
26982 Result: (aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa
26983 aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa
26984 aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa aaaa)
26985 @end example
26986
26987
26988 @item @b{~C}
26989 @c EN
26990 Parameters: None
26991
26992 Character output. The argument must be a character, or an error is
26993 signaled. If no flags are given, the character is printed with @code{display}.
26994 If atmark-flag is given, the character is printed with @code{write}.
26995 @c JP
26996 パラメータ: なし
26997
26998 文字出力。対応する引数は文字でなければなりません(そうでなければエラーが報告されます)。
26999 フラグが無ければ文字は@code{display}で表示されます。
27000 アトマークフラグが与えられた場合は@code{write}で表示されます。
27001 @c COMMON
27002
27003 @item @b{~D}
27004 @c EN
27005 Parameters: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27006
27007 Decimal output. The argument is formatted as an decimal integer.
27008 If the argument is not an integer, all parameters are ignored
27009 (after processing `@code{v}' parameters) and
27010 it is formatted by @code{~A} directive.
27011 @c JP
27012 パラメータ: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27013
27014 10進出力。対応する引数が10進数表記でフォーマットされます。もし引数が数値でなければ、
27015 全てのパラメータは(`@code{v}'パラメータの処理後に)無視され、
27016 引数は@code{~A}でフォーマットされます。
27017 @c COMMON
27018
27019 @c EN
27020 If an integer parameter @var{mincol} is given, it specifies minimum
27021 width of the formatted result; if the result is shorter than it,
27022 @var{padchar} is padded on the left (i.e. the result is right
27023 justified). The default of @var{padchar} is a whitespace.
27024 @c JP
27025 もし@var{mincol}に整数が与えられたら、それが最小の文字数を指定します。
27026 結果の文字数がそれより少なければ、文字@var{padchar}が左に追加されます(右詰めになります)。
27027 @var{padchar}が省略された場合は空白文字が使われます。
27028 @c COMMON
27029
27030 @example
27031 (format #f "|~d|" 12345)
27032 @result{} "|12345|"
27033 (format #f "|~10d|" 12345)
27034 @result{} "| 12345|"
27035 (format #f "|~10,'0d|" 12345)
27036 @result{} "|0000012345|"
27037 @end example
27038
27039 @c EN
27040 If atmark-flag is given, the sign `@code{+}' is printed for the
27041 positive argument.
27042 @c JP
27043 アトマーク `@code{@@}' フラグが与えられた場合、正の引数に対して `@code{+}' が
27044 先頭につけられます。
27045 @c COMMON
27046
27047 @c EN
27048 If colon-flag is given, every @var{interval}-th digit of
27049 the result is grouped and @var{commachar} is inserted between them.
27050 The default of @var{commachar} is `@code{,}', and the default of
27051 @var{interval} is 3.
27052 @c JP
27053 コロンフラグ `@code{:}' が与えられた場合、結果の文字は@var{interval}文字毎に
27054 まとめられ、間に文字@var{commachar}が挿入されます。デフォルトでは3文字毎にコンマが
27055 挿入されます。
27056 @c COMMON
27057
27058 @example
27059 (format #f "|~:d|" 12345)
27060 @result{} "|12,345|"
27061 (format #f "|~,,'_,4:d|" -12345678)
27062 @result{} "|-1234_5678|"
27063 @end example
27064
27065 @item @b{~B}
27066 @c EN
27067 Parameters: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27068
27069 Binary output. The argument is formatted as a binary integer.
27070 The semantics of parameters and flags are the same as
27071 the @code{~D} directive.
27072 @c JP
27073 パラメータ: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27074
27075 2進出力。対応する引数が2進数の整数としてフォーマットされます。
27076 パラメータの意味は@code{~D}と同じです。
27077 @c COMMON
27078
27079 @item @b{~O}
27080 @c EN
27081 Parameters: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27082
27083 Octal output. The argument is formatted as an octal integer.
27084 The semantics of parameters and flags are the same as
27085 the @code{~D} directive.
27086 @c JP
27087 パラメータ: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27088
27089 8進出力。対応する引数が8進数の整数としてフォーマットされます。
27090 パラメータの意味は@code{~D}と同じです。
27091 @c COMMON
27092
27093 @item @b{~X}
27094 @itemx @b{~x}
27095 @c EN
27096 Parameters: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27097
27098 Hexadecimal output.
27099 The argument is formatted as a hexadecimal integer.
27100 If `@code{X}' is used, upper case alphabets are used for
27101 the digits larger than 10. If `@code{x}' is used, lower case
27102 alphabets are used.
27103 The semantics of parameters and flags are the same as
27104 the @code{~D} directive.
27105 @c JP
27106 パラメータ: @var{mincol},@var{padchar},@var{commachar},@var{interval}
27107
27108 16進出力。対応する引数が16進数の整数としてフォーマットされます。
27109 フォーマット指示文字に `@code{X}' が与えられた場合は `@code{ABCDEF}' が桁文字として
27110 使われ、 `@code{x}' が与えられた場合は `@code{abcdef}' が桁文字として使われます。
27111 パラメータの意味は@code{~D}と同じです。
27112 @c COMMON
27113
27114 @example
27115 (format #f "~8,'0x" 259847592)
27116 @result{} "0f7cf5a8"
27117 (format #f "~8,'0X" 259847592)
27118 @result{} "0F7CF5A8"
27119 @end example
27120
27121 @item @b{~R}
27122 @itemx @b{~r}
27123 @c EN
27124 Parameters: @var{radix},@var{mincol},@var{padchar},@var{commachar},@var{interval}
27125
27126 Radix. If the argument is an exact number,
27127 the directive @code{~@var{n}R} prints out the argument
27128 in radix @var{n}. For example, @var{~10R} is the same as @code{~D}.
27129 The @var{radix} parameter must be between 2 and 36, inclusive.
27130 Other paramters are are the same as @code{~D} directive.
27131
27132 If the argument is other than an exact number, it is formatted
27133 just as @code{~A}.
27134
27135 If uppercase @code{R} is used, uppercase alphabets are used
27136 for base-11 and above. If lowercase @code{r} is used,
27137 lowercase alphabats are used.
27138
27139 If atmark-flag is given, it behaves differently; it prints out the
27140 numeric argument in Roman numerals, e.g. @code{MMXXIII} for 2023.
27141 Adding colon-flag with atmark-flag, it uses a variation of Roman
27142 numerals (@code{IIII} for 4 instead of @code{IV}, for example).
27143 The argument must be a positive exact integer in this case.
27144 Common Lisp only supports up to 4,999 since the Roman numeral 5,000
27145 can't be written in ASCII. Unicode has Roman numeral up to 100,000,
27146 however, so we support up to 499,999.
27147 Again, the distinction of @code{R} and @code{r}
27148 is reflected to the ASCII alphabets used in the output.
27149
27150 If neither @var{radix} nor atmark-flag is given, Common Lisp
27151 prints the number in English. We haven't supported it yet,
27152 and an error is raised.
27153 @c JP
27154 パラメータ: @var{radix},@var{mincol},@var{padchar},@var{commachar},@var{interval}
27155
27156 基数(Radix)。引数が正確数であれば、
27157 @code{~@var{n}R}は引数を基数@var{n}の数値としてフォーマットします。
27158 例えば@code{~10R}は@code{~D}と同じです。
27159 @var{radix}パラメータは2以上36以下でなければなりません。
27160 他のパラメータの意味は@code{~D}と同じです。
27161
27162 引数が正確数以外の場合は、@code{~A}のようにフォーマットします。
27163
27164 大文字@code{R}が使われた場合、11進数以上では大文字アルファベットが使われます。
27165 小文字@code{r}の場合は小文字アルファベットが使われます。
27166
27167 アトマークフラグが与えられた場合は違った動作になります。
27168 引数は正の正確な整数でなければならず、それがローマ数字で表示されます
27169 (例えば2023なら@code{MMXXIII}となります)。
27170 アトマークに加えてコロンフラグも与えられると、4を@code{IV}のかわりに@code{IIII}
27171 と表示する変化形を使います。
27172 ローマ数字の5,000はASCIIでは表せないので、Common Lispはこの機能は
27173 4,999までしかサポートしていません。が、Unicodeにはローマ数字が100,000まで
27174 あるので、Gaucheでは499,999までをサポートします。
27175 @code{R}と@code{r}の区別は出力の大文字小文字に反映されます。
27176
27177 @var{radix}もアトマークフラグも与えられない場合、
27178 Common Lispでは引数の数字を英語表記で出力します。
27179 この機能はまだ実装されておらず、エラーが投げられます。
27180 @c COMMON
27181 @example
27182 (format #f "~36R" 123456789) @result{} "21I3V9"
27183 (format #f "~36r" 123456789) @result{} "21i3v9"
27184 (format #f "~@@R" 1999) @result{} "MCMXCIX"
27185 (format #f "~@@:R" 1999) @result{} "MDCCCCLXXXXVIIII"
27186 (format #f "~@@r" 1999) @result{} "mcmxcix"
27187 (format #f "~@@R" 123456) @result{} "ↈↂↂMMMCDLVI"
27188 @end example
27189
27190
27191 @item @b{~F}
27192 @c EN
27193 Parameters: @var{width},@var{digis},@var{scale},@var{ovfchar},@var{padchar}
27194
27195 Floating-number output.
27196 If the argument is a real number, it is formatted as a decimal floating number.
27197 The @var{width} parameter defines the width of the field; the number is
27198 written out right-justified, with the left room padded with @var{padchar},
27199 whose default is @code{#\space}. When the formatted output can't fit
27200 in @var{width}, @var{ovfchar} is output @var{width} times if it is given,
27201 or the entire output is shown if @var{ovfchar} is omitted.
27202 @c JP
27203 パラメータ: @var{width},@var{digis},@var{scale},@var{ovfchar},@var{padchar}
27204
27205 浮動小数点数出力。
27206 引数が実数ならば、その十進小数表現が出力されます。
27207 @var{width}パラメータは出力幅を指定します。もしフォーマット結果がその幅に足りなければ、
27208 左側に@var{padchar}が詰められます。@var{padchar}のデフォルトは@code{#\space}です。
27209 フォーマット結果が@var{width}を越える場合、@var{ovfchar}が指定されていれば、
27210 @var{width}個の@var{ovfchar}が出力され、指定されていなければ@var{width}を無視して
27211 必要なだけの桁数が出力されます。
27212 @c COMMON
27213
27214 @example
27215 (format "~6f" 3.14) @result{} " 3.14"
27216 (format "~6f" 3.141592) @result{} "3.141592"
27217 (format "~6,,,'#f" 3.141592) @result{} "######"
27218 (format "~6,,,,'*f" 3.14) @result{} "**3.14"
27219 @end example
27220
27221 @c EN
27222 The @var{digits} parameter specifies number of digits shown below the
27223 decimal point. Must be nonnegative integer. When omitted, enough digits
27224 to identify the flonum uniquely is generated (same as using
27225 @code{write} and @code{display}---when you read back the number, you'll
27226 get exactly the same flonum.)
27227 @c JP
27228 @var{digits}パラメータは小数点以下に表示される桁数を指定します。非負整数でなければなりません。
27229 省略された場合は、引数の浮動小数点数を一意に同定できる最小の精度で出力されます
27230 (@code{write}や@code{display}で出力した場合と同じです。その文字列を@code{read}すれば、
27231 全く同じ浮動小数点数が得られます)。
27232 @c COMMON
27233
27234 @example
27235 (format "~6,3f" 3.141592) @result{} " 3.142"
27236 (format "~6,0f" 3.141592) @result{} " 3."
27237 (format "~10,4f" 355/113) @result{} " 3.1416"
27238 (format "~10,4f" 3) @result{} " 3.0000"
27239 @end example
27240
27241 @c EN
27242 If the @var{scale} parameter is given, the argument is multiplied by
27243 @code{(expt 10 scale)} before printing.
27244 @c JP
27245 @var{scale}パラメータが与えられた場合、引数が表示前に@code{(expt 10 scale)}倍
27246 されます。
27247 @c COMMON
27248
27249 @c EN
27250 If the @code{@@} flag is given, plus sign is printed before the non-negative
27251 number.
27252 @c JP
27253 @code{@@}フラグが与えられると、引数が非負の場合にプラス記号が出力されます。
27254 @c COMMON
27255
27256 @example
27257 (format "~8,3@@f" 3.141592) @result{} " +3.142"
27258 @end example
27259
27260 @c EN
27261 When @var{digits} is smaller than the digits required to represent
27262 the flonum unambiguously, we round at @var{digits}+1 position. By default,
27263 it is done based on the value the flonum represents---that is, we choose
27264 the rounded value closer to the actual value of the flonum.
27265 It can sometimes lead to unintuitive results, however. Suppose you want
27266 to round 1.15 at 100ths (that is, round to nearest 10ths). Unlike
27267 elementary math class, it gives you 1.1. That's because the flonum
27268 represented by 1.15 is actually tiny bit smaller than 1.15, so it's closer to
27269 1.1 than 1.2. We show it as 1.15 since no other flonums are closer to
27270 1.15.
27271 @c JP
27272 @var{digits}が浮動小数点数を一意に同定するための桁数に足りない場合は、
27273 小数点以下@var{digits}桁に丸められます。デフォルトでは、この丸めは
27274 浮動小数点数の真の値に基づいて行われます。つまり、真の値に近い方の表現が選ばれます。
27275 これはたまに、非直感的な結果になることがあります。
27276 例えば1.15を1/100の位で丸めて(1/10単位にして)みると、
27277 小学校でやる算数と異なり、1.1が出力されます。
27278 この理由は、1.15と表記される浮動小数点数が実際には1.15よりわずかに小さく、従って
27279 1.1により近いからです。本当は1.15でないものを1.15と表示しているのは、
27280 1.15により近い浮動小数点数が他に無く、1.15が該当する浮動小数点数を一意に同定する
27281 最も短い表現だからです。
27282 @c COMMON
27283
27284 @c EN
27285 But in casual applications, users may perplexed with this behavior.
27286 So we support another rounding mode, which we call notational rounding.
27287 It is based on the notation used for the flonum. In that mode,
27288 rounding 1.15 to nearest 10ths yields 1.2. You can get it by
27289 adding @code{:} flag.
27290 @c JP
27291 しかし日常的なアプリケーションでこういう振る舞いがあると、ユーザが混乱してしまうかもしれません。
27292 そこでもう一つ、表示に基づいた丸め(notational rounding)モードを用意しました。
27293 このモードでは、浮動小数点数の表示に基づいた丸めを行います。従って
27294 1.15を1/100の位で丸めると1.2になります。このモードは@code{:}フラグで指定できます。
27295 @c COMMON
27296
27297 @example
27298 (format "~6,1f" 1.15) @result{} " 1.1"
27299 (format "~6,1:f" 1.15) @result{} " 1.2"
27300 @end example
27301
27302 @item @b{~$}
27303 @c EN
27304 Parameters: @var{digits},@var{idigits},@var{width},@var{padchar}
27305
27306 Floating-point formatting suitable for currency display. The @var{digits}
27307 parameter specifies the number of digits after the decimal point (default 2).
27308 The @var{idigits} parameter specifies the minimum number of digits before
27309 the decimal point (default 1). The @var{width} parameter specifies the
27310 mininum number of characters for the entire display,
27311 and if the number of printed characters are smaller than it,
27312 @var{padchar} is displayed on the left to fill the blank. The default
27313 of @var{width} is 0, and the default of @var{padchar} is @code{#\space}.
27314
27315 If @code{@@} flag is given and the argument is nonnegative, @code{+} is
27316 displayed.
27317
27318 If @code{:} flag is given, the sign is displayed first, before any
27319 padding characters.
27320
27321 If the argument isn't a real number, the object is formatted as if
27322 @code{~wD} directive is given (where @var{w} is @var{width}).
27323
27324 Gauche specific: The number is rounded with notational rounding (see the
27325 description of @code{~F} above for the rounding mode).
27326 @c JP
27327 パラメータ: @var{digits},@var{idigits},@var{width},@var{padchar}
27328
27329 通貨の表示に適した浮動小数点数フォーマット。
27330 @var{digits}は小数点以下に表示される桁数で、デフォルトは2です。
27331 @var{idigits}は小数点より前に表示される最小の桁数で、デフォルトは1です。
27332 @var{width}パラメータは全体の最少文字数を指定し、表示すべき文字がそれより少ない場合は
27333 @var{padchar}が左側に足されます。@var{width}のデフォルトは0、
27334 @var{padchar}のデフォルトは@code{#\space}です。
27335
27336 @code{@@}フラグが与えられた場合、非負の値に@code{+}符号が表示されます。
27337
27338 @code{:}フラグが与えられた場合、符号があればそれはパディングより前に表示されます。
27339
27340 引数が実数でない場合は、あたかも@code{~wD} (@code{w}は@var{width}) が指定
27341 されたかのように表示されます。
27342
27343 Gauche特有の機能として、数値は表示に基づいた丸め(notational rounding)で
27344 丸められます。表示に基づいた丸めについては上の@code{~F}の項の説明を参照してください。
27345 @c COMMON
27346
27347 @example
27348 (map (cut format "~$" <>) '(1.23 4.5 6))
27349 @result{} '("1.23" "4.50" "6.00")
27350 @end example
27351
27352
27353 @item @b{~?}
27354 @c EN
27355 Parameters: None
27356
27357 Recursive formatting. The argument for this directive must be a string
27358 which is interpreted as a format string. The arguments for the given directive
27359 should be given in the next argument, as a list.
27360
27361 @example
27362 (format "~s~?~s" '< "~s ~s" '(a b) '>)
27363 @result{} "<a b>"
27364 @end example
27365
27366 If @code{@@} flag is given, the arguments for the given directive
27367 is taken from the following arguments.
27368
27369 @example
27370 (format "~s~@@?~s" '< "~s ~s" 'a 'b '>)
27371 @result{} "<a b>"
27372 @end example
27373 @c JP
27374 パラメータ: なし
27375
27376 再帰的フォーマッティング。この指示子はまず文字列を引数に取り、それをフォーマット文字列と
27377 解釈します。そしてさらに次の引数(それはリストでなければなりません)を、そのフォーマット文字列
27378 への引数と解釈します。
27379
27380 @example
27381 (format "~s~?~s" '< "~s ~s" '(a b) '>)
27382 @result{} "<a b>"
27383 @end example
27384
27385 @code{@@}フラグが与えられた場合は、最初の引数をフォーマット文字列と解釈した後で、
27386 続く引数を必要なだけそのフォーマット文字列の引数として使います。
27387
27388 @example
27389 (format "~s~@@?~s" '< "~s ~s" 'a 'b '>)
27390 @result{} "<a b>"
27391 @end example
27392 @c COMMON
27393
27394 @item @b{~*}
27395 @c EN
27396 Parameter: @var{count}
27397
27398 Moves the argument counter @var{count} times forward, effectively skips
27399 next @var{count} arguments. The default value of @var{count} is 1,
27400 hence skip the next argument. If a colon-flag is given, moves the argument
27401 counter backwards, e.g. @code{~:*} makes the next directive to process
27402 last argument again. If an atmark-flag is given, @var{count} specifies
27403 absolute position of the arguments, starting from 0.
27404 @c JP
27405 パラメータ: @var{count}
27406
27407 引数のカウンタを@var{count}だけ後方にずらします。つまり、@var{count}個の引数が
27408 無視されることになります。@var{count}のデフォルト値は1です。
27409 コロンフラグが与えられた場合は引数カウンタを前方に動かします。
27410 例えば@code{~:*}は次のディレクティブが直前に使った引数を再び使うようにします。
27411 アトマークフラグが与えられた場合は、@var{count}が引数の絶対位置を示します。
27412 0が最初の引数です。
27413 @c COMMON
27414
27415 @item @b{~P}
27416 @c EN
27417 Parameters: none
27418
27419 Plural. If argument is an exact integer 1, do nothing. Otherwise,
27420 print @code{s}.
27421
27422 If an atmark-flag is given, print @code{y} for the argument 1, and
27423 print @code{ies} for other argument values.
27424
27425 If a colon-flag is given, back up one argument before processing.
27426
27427 Note: 1.0 is regarded as plural.
27428 @c JP
27429 パラメータ: なし
27430
27431 複数形(plural)。引数が正確な1であれば何もせず、そうでなければ@code{s}を出力します。
27432
27433 アトマークフラグが与えられた場合は、引数が正確な1なら@code{y}を、
27434 そうでなければ@code{ies}を出力します。
27435
27436 コロンフラグが与えられた場合は、引数をひとつ戻ってから処理します。
27437
27438 註: 1.0は複数とみなされます。
27439 @c COMMON
27440
27441 @example
27442 (format "~a book~:p, ~a book~:p, ~a pon~:@@p, ~a pon~:@@p" 1 2 1 2)
27443 @result{} "1 book, 2 books, 1 pony, 2 ponies"
27444 @end example
27445
27446
27447 @item @b{~&}
27448 @c EN
27449 Parameter: @var{count}
27450
27451 Fresh line. If the output position is at the beginning of line,
27452 do nothing; otherwise, output @code{#\newline}, just like
27453 @code{fresh-line} procedure (@pxref{Object output}).
27454
27455 If @var{count} is given and greater than 1, output @code{(- count 1)}
27456 newline characters after the fresh line operation. If @var{count} is 0,
27457 do nothing.
27458 @c JP
27459 パラメータ: @var{count}
27460
27461 出力位置が行の頭なら何もせず、そうでなければ@code{#\newline}文字を出力します。
27462 @code{fresh-line}手続きと同じです (@ref{Object output}参照)。
27463
27464 もし@var{count}が与えられて1より大きければ、@code{fresh-line}の後に
27465 @code{(- count 1)}個の@code{#\newline}を出力します。
27466 @var{count}が0なら何もしません。
27467 @c COMMON
27468
27469 @item @b{~~}
27470 @itemx @b{~%}
27471 @itemx @b{~t}
27472 @itemx @b{~|}
27473 @c EN
27474 Parameter: @var{count}
27475
27476 Output a @code{#\~}, @code{#\newline}, @code{#\tab} and @code{#\page},
27477 respectively. If @var{count} is given, output the specified number
27478 of characters.
27479 @c JP
27480 パラメータ: @var{count}
27481
27482 それぞれ、文字@code{#\~}、@code{#\newline}、@code{#\tab}、@code{#\page}を
27483 ひとつ出力します。@var{count}が与えられた場合はその個数出力します。
27484 @c COMMON
27485
27486 @item @b{~} + newline
27487 @c EN
27488 Parameters: none
27489
27490 Ignored newline. As Scheme supports backslash-newline escape in
27491 string literals, this is not necessary, but provided for Common Lisp
27492 compatibility. Without flags, the newline after the tilde, and any
27493 following whitespace characters (@code{char-whitespace?}) are ignored.
27494 With a colon flag, the newline immediately after the tilde is ignored
27495 but the following whitespace characters are preserved. With an atmark
27496 flag, the newline immediately after the tilde is kept
27497 but the following whitespace characters are ignored.
27498 @c JP
27499 パラメータ: なし
27500
27501 改行の無視。Schemeはリテラル文字列の中でバックスラッシュ+改行のエスケープで
27502 無視される改行を入れられるのでこれは必要ないのですが、Common Lispとの互換性のために
27503 サポートされています。
27504 フラグが無ければ、チルドに続く改行文字と、そのあとに続く空白文字(@code{char-whitespace?})
27505 を無視します。コロンフラグが与えられたら、チルドの直後の改行文字だけ無視します。
27506 アトマークフラグが与えられたら、
27507 チルド直後の改行文字は残しますが、その後に続く空白文字は無視します。
27508 @c COMMON
27509
27510 @example
27511 (format "abc~\n def") @result{} "abcdef"
27512 (format "abc~:\n def") @result{} "abc def"
27513 (format "abc~@@\n def") @result{} "abc\ndef"
27514
27515 (format "abc~:\n \ndef") @result{} "abc \ndef"
27516 @end example
27517
27518 @item @b{~[}
27519 @c EN
27520 Parameters: none
27521
27522 Conditional formatting. It can take one of three forms:
27523 @c JP
27524 パラメータ: なし
27525
27526 条件分岐。以下の3つの形をとります。
27527 @c COMMON
27528
27529 @table @asis
27530 @item @b{~[}@i{fmt0}@b{~;}@i{fmt1}@b{~;}...@b{~]}
27531 @c EN
27532 Consume one argument. If it is not an exact integer, an error
27533 is signaled. If it is 0, the format string @i{fmt0} is selected.
27534 If it is 1, @i{fmt1} is selected; and so on. If there's no
27535 corresponding format string, it acts like an empty format string by default.
27536 However, if the last separator is @b{~:;} instead of @b{~;},
27537 the following format string acts as the 'default' format string.
27538 @c JP
27539 引数をひとつ消費します。それが正確な整数でなければエラーが投げられます。
27540 それが0なら@i{fmt0}が、1なら@i{fmt0}が、…という具合に選択されます。
27541 該当するフォーマット文字列が無ければ空のフォーマット文字列として振る舞います。
27542 ただし、最後の区切りを@b{~;}ではなく@b{~:;}にすることで、
27543 それに続くフォーマット文字列を「デフォルト」のフォーマット文字列とすることができます。
27544 @c COMMON
27545
27546 @item @b{~:[}@i{fmt-alternative}@b{~;}@i{fmt-consequence}@b{~]}
27547 @c EN
27548 Consume one argument. If it is @code{#f}, @i{fmt-alternative} is
27549 selected. If it is true, @i{fmt-consequence} is selected.
27550 (Note that it is the reverse of @code{if}. Think false as 0 and true as 1).
27551 @c JP
27552 引数をひとつ消費します。それが偽なら@i{fmt-alternative}が、
27553 真なら@i{fmt-consequence}が選択されます
27554 (@code{if}と順序が逆であることに注意してください。偽を0、真を1と考えると良いでしょう)。
27555 @c COMMON
27556
27557 @item @b{~@@[}@i{fmt-consequence}@b{~]}
27558 @c EN
27559 Peek one argument. If it is @code{#f}, consume it and ignore
27560 @i{fmt-consequence}. If it is true, process @i{fmt-consequence}.
27561 Hence, @i{fmt-consequence} usually contains a directive
27562 to consume one argument.
27563 @c JP
27564 引数を消費せずに調べます。それが偽なら、その引数を消費した上で空のフォーマット文字列として
27565 振る舞います。それが真なら、@i{fmt-consequence}を選択します。
27566 従って、@i{fmt-consequence}は通常、引数をひとつ消費するフォーマット指示子を含みます。
27567 @c COMMON
27568 @end table
27569
27570 @example
27571 (map (cut format "~[zero~;one~;two~]" <>) '(0 1 2 3))
27572 @result{} ("zero" "one" "two" "")
27573 (map (cut format "~[zero~;one~;two~:;other~]" <>) '(0 1 2 3 -1))
27574 @result{} ("zero" "one" "two" "other" "other")
27575 (map (cut format "~:[no~;yes~]" <>) '(#f #t))
27576 @result{} ("no" "yes")
27577 (map (cut format "~@@[I got ~a~]" <>) '(#f rhythm))
27578 @result{} ("" "I got rhythm")
27579 @end example
27580
27581 @end table
27582 @end defun
27583
27584
27585 @node Low-level output, , Formatting output, Output
27586 @subsubsection Low-level output
27587 @c NODE 低レベル出力
27588
27589 @defun write-char char :optional port
27590 [R7RS base]
27591 @c EN
27592 Write a single character @var{char} to the output port @var{port}.
27593 @c JP
27594 文字@var{char}をポートに出力します。
27595 @c COMMON
27596 @end defun
27597
27598 @defun write-byte byte :optional port
27599 @defunx write-u8 byte :optional port
27600 [R7RS base]
27601 @c EN
27602 Write a byte @var{byte} to the port.
27603 @var{byte} must be an exact integer in range between 0 and 255.
27604
27605 This is traditionally called @code{write-byte}, and
27606 R7RS calls it @code{write-u8}. You can use either.
27607 @c JP
27608 出力ポートに1バイトのデータ@var{byte}を書き出します。
27609 @var{byte}は0から255の間の正確な整数でなければなりません。
27610
27611 これは伝統的に@code{write-byte}と呼ばれてきましたが、
27612 R7RSでは@code{write-u8}と名づけています。どちらも使えます。
27613 @c COMMON
27614 @end defun
27615
27616 @defun write-string string :optional oport start end
27617 [R7RS base]
27618 @c EN
27619 If the optional @var{start} and @var{end} arguments are omitted,
27620 it is the same as @code{(display string oport)}. The optional
27621 arguments restricts the range of @var{string} to be written.
27622 @c JP
27623 @var{start}と@var{end}引数が省略された場合は@code{(display string oport)}と
27624 同じです。それらが与えられた場合は、@var{string}中の指定範囲のみが出力されます。
27625 @c COMMON
27626 @end defun
27627
27628
27629 @defun flush :optional port
27630 @defunx flush-all-ports
27631 @c EN
27632 Output the buffered data in @var{port}, or all ports, respectively.
27633
27634 R7RS's @code{flush-output-port} is the same as @code{flush}.
27635 The @code{scheme.base} module defines the name as an alias to
27636 @code{flush} (@pxref{R7RS base library}).
27637
27638 The function "flush" is called in variety of ways on the various
27639 Scheme implementations: @code{force-output} (Scsh, SCM),
27640 @code{flush-output} (Gambit), or @code{flush-output-port} (Bigloo).
27641 The name @code{flush} is taken from STk and STklos.
27642 @c JP
27643 それぞれ、@var{port}、および全てのポートにバッファされているデータを
27644 全て書き出します。
27645
27646 R7RSでは@code{flush}は@code{flush-output-port}と呼ばれています。
27647 Gaucheでは@code{scheme.base}モジュールで@code{flush}の別名として
27648 提供しています(@ref{R7RS base library}参照)。
27649
27650 手続き"flush"はScheme実装によって様々な名前で呼ばれています:
27651 @code{force-output} (Scsh, SCM)、
27652 @code{flush-output} (Gambit)、@code{flush-output-port} (Bigloo) 等。
27653 @code{flush}の名前はSTkとSTklosから取りました。
27654 @c COMMON
27655 @end defun
27656
27657
27658 @c ----------------------------------------------------------------------
27659 @node Loading Programs, Sorting and merging, Input and output, Core library
27660 @section Loading Programs
27661 @c NODE プログラムのロード
27662
27663 @menu
27664 * Loading Scheme file::
27665 * Loading dynamic library::
27666 * Require and provide::
27667 * Autoload::
27668 * Operations on libraries::
27669 @end menu
27670
27671 @node Loading Scheme file, Loading dynamic library, Loading Programs, Loading Programs
27672 @subsection Loading Scheme file
27673 @c NODE Schemeファイルのロード
27674
27675 @defun load file :key paths (error-if-not-found #t) environment ignore-coding
27676 [R7RS+ load]
27677 @c EN
27678 Loads @var{file}, that is, read Scheme expressions in @var{file} and
27679 evaluates them.
27680 An extension ``@code{.scm}'' may be omitted from @var{file}.
27681
27682 If @var{file} doesn't begin with ``/'' or ``./'' or ``../'',
27683 it is searched from the system file search list,
27684 stored in a variable @code{*load-path*}.
27685 Or you can explicitly specify the search path by passing
27686 a list of directory names to the keyword argument @var{paths}.
27687
27688 On success, @code{load} returns the string pathname of the file
27689 actually loaded.
27690 If the specified file is not found, an error is signaled unless
27691 the keyword argument @var{error-if-not-found} is @code{#f}, in
27692 which case @code{load} returns @code{#f}.
27693
27694 By default, @code{load} uses a coding-aware port
27695 (@pxref{Coding-aware ports}) so that the "@code{coding:}" magic
27696 comment at the beginning of the source file is effective.
27697 (See @ref{Multibyte scripts}, for the details of
27698 the coding magic comment). If a true value is given to the
27699 keyword argument @var{ignore-coding}, @code{load} doesn't
27700 create the coding-aware port and directly reads from the
27701 file port.
27702
27703 If a module is given to the keyword argument @var{environment},
27704 @code{load} works as if the given module is selected at the beginning
27705 of the loaded file.
27706
27707 The current module is preserved; even @code{select-module} is
27708 called in @var{file}, the module in which @code{load} is called
27709 is restored afterwards.
27710
27711 Gauche's @code{load} is upper-compatible to R5RS @code{load}, but
27712 R7RS @code{load} differs in optional arguments; @pxref{R7RS load}.
27713
27714 If you want to load a library file, it's better to use `@code{use}'
27715 (@pxref{Defining and selecting modules}), or `@code{require}' described below.
27716 @xref{Compilation}, for difference between @code{load} and @code{require}.
27717 @c JP
27718 @var{file}をロードします。すなわち、@var{file}に書かれたScheme式を順次読み込んで
27719 評価します。@var{file}の拡張子 (``@code{.scm}'') は省略できます。
27720
27721 @var{file}が ``/'', ``./'' または ``../'' で始まっていない場合は、
27722 システムファイルサーチパス (変数@code{*load-path*} に格納されています)
27723 の中から該当ファイルが探されます。あるいは、キーワード引数@var{paths}にディレクトリ名の
27724 リストを渡すことによりサーチパスを指定することもできます。
27725
27726 ロードに成功した場合は、実際にロードされたファイルのパス名が文字列で返されます。
27727 指定ファイルがみつからない場合はエラーとなりますが、もしキーワード引数
27728 @code{error-if-not-found}に@code{#f}が与えられていれば単に@code{load}から
27729 @code{#f}が返されます。
27730
27731 デフォルトでは、@code{load}はコーディング認識ポート(@ref{Coding-aware ports}参照)を
27732 使ってソースファイルを読み込むので、ファイル先頭の"@code{coding:}" コメントによる
27733 文字エンコーディング指定が有効になります。
27734 (codingコメントについては@ref{Multibyte scripts}を参照)。
27735 但し、キーワード引数@var{ignore-coding}に真の値が渡された場合、
27736 @code{load}はcoding-aware portを作成せず、直接ファイルポートから
27737 ソースを読み込みます。
27738
27739 キーワード引数@var{environment}にモジュールが渡された場合は、
27740 あたかもそのモジュールがファイルの先頭でselectされたかのように
27741 @code{load}されます。
27742
27743 カレントモジュールは保存されます。つまり、@var{file}中で@code{select-module}によって
27744 カレントモジュールを変更しても、@code{load}が終わったら@code{load}を読んだ時点の
27745 モジュールに戻ります。
27746
27747 Gaucheの@code{load}はR5RSの@code{load}の上位互換ですが、
27748 R7RSの@code{load}は省略可能引数が異なります。@ref{R7RS load}参照。
27749
27750 ライブラリファイルをロードする場合は、`@code{use}' (@ref{Defining and selecting modules}参照) を
27751 使うか、下に説明する`@code{require}' を使う方が良いでしょう。
27752 @code{load}と@code{require}の違いについては@ref{Compilation}を参照してください。
27753 @c COMMON
27754 @end defun
27755
27756 @defvar *load-path*
27757 @c EN
27758 Keeps a list of directories that are searched by @code{load} and
27759 @code{require}.
27760
27761 If you want to add other directories to the search path,
27762 do not modify this variable directly; use @code{add-load-path},
27763 described below, instead.
27764 @c JP
27765 @code{load}と@code{require}がファイルを探すディレクトリのリストを保持しています。
27766
27767 もしサーチパスにディレクトリを追加したい場合は、この変数を直接変更せずに、下に説明する
27768 @code{add-load-path}を用いて下さい。
27769 @c COMMON
27770 @end defvar
27771
27772 @defspec add-load-path path flag @dots{}
27773 @c EN
27774 Adds a path @var{path} to the library load path list.
27775 @var{Path} must be a literal string, for load paths must be
27776 known at compilation time.
27777 If @var{path} is a relative path, it is resolved relative to
27778 the current working directory, unless @code{:relative} flag is given.
27779 @c JP
27780 パス@var{path}をライブラリロードパスのリストに加えます。
27781 ロードパスはコンパイル時に確定している必要があるので、
27782 @var{path}はリテラル文字列でなければなりません。
27783 @var{path}が相対パスの場合、@code{:relative}フラグが与えられて
27784 いなければ、プロセスの現在のワーキングディレクトリからの相対と解釈されます。
27785 @c COMMON
27786
27787 @c EN
27788 @var{Path} doesn't need to exist; nonexisting paths in load path list
27789 are simply ignored. However, if @var{path} does exist, @code{add-load-path}
27790 searches for architecture-dependent paths; see below.
27791 @c JP
27792 @var{path}は存在する必要はありません。ロードパスに存在しないディレクトリが含まれていても
27793 単に無視されるだけです。ただ、@var{path}が存在する場合、@code{add-load-path}は
27794 アーキテクチャ依存パスも探します。後で詳しく説明します。
27795 @c COMMON
27796
27797 @c EN
27798 Each @var{flag} argument may be one of the followings.
27799 @c JP
27800 以下の値が@var{flag}引数として認識されます。
27801 @c COMMON
27802
27803 @table @code
27804 @item :after
27805 @c EN
27806 Append @var{path} to the end of the current list of load paths.
27807 By default, @var{path} is added in front of the load path list.
27808 @c JP
27809 @var{path}を現在のロードパスリストの末尾に加えます。
27810 デフォルトでは、@var{path}はロードパスリストの先頭に加えられます。
27811 @c COMMON
27812 @item #t
27813 @c EN
27814 The same as @code{:after}. This is for the backward compatibility.
27815 @c JP
27816 @code{:after}と同じです。互換性のために認識されます。
27817 @c COMMON
27818 @item :relative
27819 @c EN
27820 Interpret @var{path} as a relative path to the directory of
27821 the current file, instead of the current working directory.
27822 If the current file can't be determined (e.g. evaluated in REPL, or
27823 the expression is read from a socket), this flag is ignored.
27824 @c JP
27825 @var{path}を、(カレントワーキングディレクトリではなく)
27826 現在ロード中のファイルのあるディレクトリからの相対パスとして
27827 解釈します。現在ロード中のファイルが不明な場合 (REPLから
27828 評価されたり、ソケットから読まれたりしている場合) は、このフラグは無視されます。
27829 @c COMMON
27830 @end table
27831
27832 @c EN
27833 Use this form instead of changing @code{*load-path*} directly.
27834 This form is a special form and recognized by the compiler;
27835 if you change @code{*load-path*}, it is in effect at run time,
27836 and that may be too late for ``use'' or ``require''.
27837 @c JP
27838 ロードパスを変更したい場合、@code{*load-path*}を直接替えずにこのフォームを
27839 使って下さい。このフォームはコンパイル時に解釈されるのに対し、@code{*load-path*}を
27840 書き換えるコードは実行時に解釈されます。``@code{use}'' や ``@code{require}'' は
27841 コンパイル時のロードパスを使うので、@code{*load-path*}への変更は反映されないかもしれません。
27842 @c COMMON
27843
27844 @c EN
27845 Furthermore,
27846 @code{add-load-path} looks for the architecture dependent directories
27847 under the specified path and if it exists, sets up the internal
27848 path list for dynamic loading correctly. Suppose you have
27849 your Scheme module in @code{/home/yours/lib}, and that requires
27850 a dynamic loadable library. You can put the library under
27851 @code{/home/yours/lib/@var{ARCH}/}, where @var{ARCH} is
27852 the value @code{(gauche-architecture)} returns (@pxref{Environment inquiry}).
27853 Then you can have compiled libraries for multiple platforms and
27854 Gauche can still find the right library.
27855 @c JP
27856 更に、@code{add-load-path}は@var{path}の下にアーキテクチャ依存のディレクトリが
27857 ないかどうかを探し、あればそれを内部の共有ライブラリサーチパスに追加します。
27858 例えばあなたが自分のSchemeモジュールを@code{/home/yours/lib}に入れていて、
27859 それが共有ライブラリを必要としていたとします。手続き@code{gauche-architecture}
27860 (@ref{Environment inquiry}参照)が返す値を@var{ARCH}として、
27861 共有ライブラリを@code{/home/yours/lib/@var{ARCH}/}に置いておくと、
27862 共有ライブラリはそこからロードされます。この方法を取ると、複数のプラットフォーム用に
27863 別々にコンパイルされた共有ライブラリを管理することができます。
27864 @c COMMON
27865 @end defspec
27866
27867 @defun load-from-port port
27868 @c EN
27869 Reads Scheme expressions from an input port @var{port} and evaluates
27870 them, until EOF is read.
27871
27872 Note that unless you pass a coding-aware port to @var{port},
27873 the "@code{coding:}" magic comment won't be handled.
27874 @c JP
27875 入力ポート@var{port}から、EOFを読むまで繰り返しScheme式を読み込み評価します。
27876
27877 @var{port}にコーディング認識ポートを渡さない限り、"@code{coding:}"コメント
27878 による文字コード変換は行われないことに注意して下さい。
27879 @c COMMON
27880 @end defun
27881
27882 @defun current-load-port
27883 @defunx current-load-path
27884 @defunx current-load-history
27885 @defunx current-load-next
27886 @c EN
27887 These procedures allows you to query the current context of loading.
27888 They returns the following values when called inside a file being loaded:
27889 @table @code
27890 @item current-load-port
27891 Returns the port object from which this form is being loaded.
27892 @item current-load-path
27893 Returns the pathname of the file from which this form is being loaded.
27894 Note that this may return @code{#f} if the source of @code{load} is
27895 not a file.
27896 @item current-load-history
27897 Returns a list of pairs of a port and a line number (integer),
27898 representing the nesting of loads. Suppose you load
27899 @file{foo.scm}, and from its line 7 it loads @file{bar.scm},
27900 and from its line 18 it loads @file{baz.scm}. If you call
27901 @code{current-load-history} in the file @file{baz.scm}, you'll get
27902 @example
27903 ((#<port "foo.scm"> . 7) (#<port "bar.scm"> . 18))
27904 @end example
27905 @item current-load-next
27906 Returns a list of remaining directories to be searched
27907 at the time this file is found. Suppose the @code{*load-path*}
27908 is @code{("." "../lib" "/home/gauche/lib" "/share/gauche/lib")}
27909 and you load @file{foo.scm}, which happens to be in @file{../lib/}.
27910 Then, inside @file{foo.scm}, @code{current-load-next} returns:
27911 @example
27912 ("/home/gauche/lib" "/share/gauche/lib")
27913 @end example
27914 @end table
27915
27916 When called outside of @code{load}, these procedures returns
27917 @code{#f}, @code{#f}, @code{()} and @code{()}, respectively.
27918 @c JP
27919 これらの手続きによって、現在のロードのコンテクストを知ることができます。
27920 ロードされているファイルの中でこれらの手続きを呼ぶと、次のような値が返されます。
27921 @table @code
27922 @item current-load-port
27923 現在のフォームがロードされている入力ポート。
27924 @item current-load-path
27925 現在のフォームがロードされているファイル。
27926 ロードのソースがファイルでない場合、この値は@code{#f}。
27927 @item current-load-history
27928 入力ポートと行番号のペアのリストで、ロードのネスティングを示したもの。
27929 例えばあなたが@file{foo.scm}をロードし、そのファイルの7行目で
27930 @file{bar.scm}がロードされ、そのファイルの18行目で@file{baz.scm}が
27931 ロードされたとします。@code{current-load-history}を@file{baz.scm}中で
27932 呼ぶと、それは次のような値を返します。
27933 @example
27934 ((#<port "foo.scm"> . 7) (#<port "bar.scm"> . 18))
27935 @end example
27936 @item current-load-next
27937 現在のファイルがロードされた時点での、ファイルサーチパスの残りを返します。
27938 例えば @code{*load-path*} が
27939 @code{("." "../lib" "/home/gauche/lib" "/share/gauche/lib")}で、
27940 あなたが@file{foo.scm}をロードしたところ、それが@file{../lib/}中に見つかったと
27941 しましょう。このとき、@file{foo.scm}中で@code{current-load-next}を呼べば
27942 @example
27943 ("/home/gauche/lib" "/share/gauche/lib")
27944 @end example
27945 が返されます。
27946 @end table
27947
27948 @code{load}されていない状態で呼ばれた時は、これらの手続きはそれぞれ@code{#f}、
27949 @code{#f}、@code{()}、@code{()}を返します。
27950 @c COMMON
27951 @end defun
27952
27953
27954 @node Loading dynamic library, Require and provide, Loading Scheme file, Loading Programs
27955 @subsection Load dynamic library
27956 @c NODE ダイナミックライブラリのロード
27957
27958 @defun dynamic-load file :key init-function
27959 @c EN
27960 Loads and links a dynamic loadable library (shared library) @var{file}.
27961 @var{File} shouldn't contain the suffix (``.so'' on most systems);
27962 @code{dynamic-load} adds it, for it may differ among platforms.
27963
27964 The keyword argument @var{init-function} specifies the initialization
27965 function name of the library in a string. By default, if the file
27966 basename (without extension) is ``foo'', the initialization function
27967 name is ``Scm_Init_foo''.
27968
27969 Usually a dynamic loadable library is provided with wrapping Scheme
27970 module, so the user doesn't have to call this function directly.
27971
27972 There's no way to unload the loaded libraries.
27973 @c JP
27974 ダイナミックローダブルライブラリ(共有ライブラリ)@var{file}をロードしてリンクします。
27975 @var{file}にはサフィックス(``.so'' 等) を含めないで下さい。システムによって
27976 サフィックスは異なるため、@code{dynamic-load}がそれを追加します。
27977
27978 キーワード引数@var{init-function}は共有ライブラリ中の初期化関数の名前を
27979 指定します。デフォルトでは、サフィックスを除くファイル名が ``foo'' の場合、
27980 初期化関数名は ``Scm_Init_foo'' となります。
27981
27982 通常、共有ライブラリはSchemeモジュール中でロードされるので、モジュールユーザが
27983 直接この手続きを呼ぶ必要はほとんどないでしょう。
27984
27985 一度ロードされた共有ライブラリをアンロードすることはできません。
27986 @c COMMON
27987 @end defun
27988
27989
27990 @node Require and provide, Autoload, Loading dynamic library, Loading Programs
27991 @subsection Require and provide
27992 @c NODE requireとprovide
27993
27994 @c EN
27995 @code{Require} and @code{provide} are a traditional Lisp way to ensure
27996 loading a library file only once. If you require a @emph{feature}
27997 for the first time, a library file that provides it is loaded
27998 and the fact that the @emph{feature} is provided is memorized.
27999 Subsequent request of the same feature doesn't need to load the file.
28000 @c JP
28001 @code{require}と@code{provide}は、Lispでライブラリファイルを一度だけ
28002 読み込むことを保証するための伝統的な方法です。
28003 ある@emph{feature}を最初に@code{require}すると、その機能を提供する
28004 ライブラリファイルがロードされ、その機能が提供されたということが記憶されます。
28005 2回め以降のその@emph{feature}のリクエストではファイルはロードされません。
28006 @c COMMON
28007
28008 @c EN
28009 In Gauche, the @code{use} syntax (@pxref{Using modules}) hides
28010 the require mechanism under the hood so you hardly need to see
28011 these forms. These are provided just in case if you want to
28012 do some non-trivial management of libraries and thus want to
28013 bypass Gauche's standard mechanism.
28014 @c JP
28015 Gaucheでは@code{use}構文 (@ref{Using modules}参照) が
28016 requireのメカニズムをボンネットの下に隠してくれるので、
28017 これらの式を直接目にする必要はほとんどありません。
28018 もしあなたがちょっと変わった方式でライブラリを構成したくて、したがって
28019 Gaucheの標準的なメカニズムをバイパスしたい場合に限り、使うようにしてください。
28020 @c COMMON
28021
28022 @defspec require feature
28023 @c EN
28024 If @var{feature} is not loaded, load it. @var{Feature} must be a string,
28025 and it is taken as a file name (without suffix) to be loaded.
28026 This loading takes place at compile time.
28027
28028 If you load SLIB module, @code{require} is extended. @pxref{SLIB} for
28029 details.
28030 @c JP
28031 @var{feature}がまだロードされていなければロードします。@var{feature}は文字列で
28032 なければなりません。それがそのまま(サフィックスを除く)ファイル名としてロードパスから
28033 探されます。@code{require}の解釈はコンパイル時に行われます。
28034
28035 SLIBモジュールをロードすると、@code{require}が拡張されます。詳しくは@ref{SLIB}を
28036 参照して下さい。
28037 @c COMMON
28038
28039 @c EN
28040 If the loaded file does not contain @code{provide} form at all,
28041 the @var{feature} is automatically provided, as if
28042 @code{(provide @var{feature})} is called at the end of the loaded
28043 file. We call this @emph{autoprovide} feature.
28044 @c JP
28045 もしロードされたファイルが@code{provide}フォームを含んでいなかった場合、
28046 あたかもファイルの最後に@code{(provide @var{feature})}があったかのように、
28047 @var{feature}が自動的にprovideされます。これを
28048 @emph{autoprovide}機能と呼んでいます。
28049 @c COMMON
28050
28051 @c EN
28052 Note that @code{require} first sets the current module to
28053 an immutable module called @code{gauche.require-base}
28054 and then load the file. The files
28055 loaded by @code{require} usually have @code{define-module}/@code{select-module}
28056 or @code{define-library} for the first thing, so you rarely notice the
28057 @code{gauche.require-base} module. However, if the loaded file
28058 has toplevel defines or imports (@code{use}'s) without specifying
28059 a module, you'll get an error like the following:
28060 @c JP
28061 @code{require}は、ファイルをロードする前に現在のモジュールを
28062 @code{gauche.require-base}という変更不可なモジュールにセットします。
28063 @code{require}されるファイルは通常、最初に@code{define-module}/@code{select-module}
28064 か@code{define-library}フォームを持つので、この@code{gauche.require-base}モジュール
28065 を目にすることはほとんど無いでしょう。
28066 ただ、もしロードされたファイルがモジュールを指定すること無くトップレベルの
28067 変数を定義したり他のモジュールを@code{import}(@code{use})しようとした場合、
28068 次のようなエラーとなります。
28069 @c COMMON
28070
28071 @example
28072 *** ERROR: Attempted to create a binding (a) in a sealed
28073 module: #<module gauche.require-base>
28074 @end example
28075
28076 @c EN
28077 Rationale: Generally it's difficult to guarantee
28078 when the specified file is loaded by @code{require} (because some other
28079 module may already have required it). If we just used the caller's current
28080 module, there would be a couple of issues: The form @code{define-module} or
28081 @code{define-library} may not be visible from the current module, and
28082 you can't guarantee if the toplevel defines without specifying modules
28083 in the loaded file inserts the caller's current module, since they may
28084 have been loaded into a different module.
28085 It is just a bad idea to insert
28086 toplevel definitions or to import other modules without specifying which
28087 module you put them in. So we made them an error.
28088 @c JP
28089 理由: @code{require}されているファイルがどのタイミングで読まれるかを
28090 正確にコントロールするのは難しいです(他のモジュールが既にrequireしているかも
28091 しれないので)。もし呼び出し側の現在のモジュールをそのまま使った場合、二つの
28092 問題が生じ得ます。(1)呼び出し側の現在のモジュールから、
28093 @code{define-module}や@code{define-library}が見えているとは限りません。
28094 (2)モジュールを指定しないトップレベル定義が呼び出し側の現在のモジュールに
28095 定義を追加することは保証されません(既に別のモジュールへと読みこまれているかもしれません)。
28096 モジュールを指定しないトップレベル定義やimportを持つファイルをrequireすることは、
28097 単に悪いアイディアです。したがってそういう事例はエラーとすることにしました。
28098 @c COMMON
28099 @end defspec
28100
28101 @defun provide feature
28102 @c EN
28103 Adds @var{feature} to the system's provided feature list, so that
28104 the subsequent @code{require} won't load the same file again.
28105 @c JP
28106 @var{feature}をシステムのprovideされたフィーチャーリストに加えます。
28107 以降、@var{feature}が@code{require}されてもファイルはふたたびロードされません。
28108 @c COMMON
28109
28110 @c EN
28111 Because of the autoproviding, i.e. @code{require}
28112 automatically provides the required feature, you hardly need to
28113 use a @code{provide} form explicitly. There are a couple of scenarios that
28114 you may want to use a @code{provide} form:
28115 @c JP
28116 @code{require}が要求された機能を自動的に@code{provide}されたかのように
28117 扱うAutoprovide機能があるために、@code{provide}を明示的に呼ぶ必要は
28118 ほとんど無いでしょう。@var{provide}を使いたいシチュエーションとしては
28119 次のようなものが考えられます。
28120
28121 @c COMMON
28122
28123 @itemize
28124 @item
28125 @c EN
28126 To provide a feature (or features) that is/are different from
28127 the one that caused loading the file.
28128
28129 Suppose feature X supersedes feature Y and providing
28130 compatible APIs of Y but with different implementation.
28131 Once @file{X.scm} is loaded, you don't want @file{Y.scm} to be loaded;
28132 so you want to tell the user that @file{X.scm} also provides the feature Y.
28133 Adding @code{(provide "X")} and @code{(provide "Y")} at the end of
28134 @file{X.scm} accomplish that. (Note: If you add a provide form,
28135 @code{require} no longer autoprovides the feature, so you need
28136 to specify @code{(provide "X")} in @file{X.scm} explicitly to
28137 provide X as well.)
28138
28139 Of course, this doesn't prevent users from loading @file{Y.scm} by
28140 specifying @code{(require "Y")} before @code{(require "X")}.
28141 It should be considered just as a workaround in a production
28142 where other solutions are costly, instead of a permanent solution.
28143 @c JP
28144 そのファイルをロードすることになったfeatureとは異なるfeature (複数可) を
28145 provideしたい場合。
28146
28147 例えばfeature Xがfeature Yを置き換えるものだとします。
28148 XはYのAPIを全て提供しますが、実装は異なります。この場合、
28149 @file{X.scm}が一度ロードされたら、@file{Y.scm}をロードしてほしくないと思うでしょう。
28150 @file{X.scm}に @code{(provide "X")} と @code{(provide "Y")} の両方を
28151 書いておくことで、@file{X.scm}がfeature Yもprovideすると明示すれば、それが実現できます。
28152 (注:@code{provide}が呼ばれると、@code{require}のautoprovide機能は
28153 抑制されるため、@file{X.scm}中で@code{(provide "X")}も指定する必要があります。)
28154
28155 もちろんの方法では、ユーザが @code{(require "Y")} を @code{(require "X")}
28156 より先に書いてしまったら@file{Y.scm}はロードされてしまいます。
28157 この方法は、現場において、永久的な解決が高コストになるような場合のとりあえずの
28158 回避処置と考えるべきでしょう。
28159 @c COMMON
28160
28161 @item
28162 @c EN
28163 To provide no features at all. Passing @code{#f} as @var{feature}
28164 prevents autoproviding by @code{require} without providing any
28165 feature.
28166
28167 This should also be a temporary solution. One possible scenario is
28168 that you are changing @file{X.scm} very frequently during
28169 development and you want @code{(require "X")} always causes loading
28170 the file. Don't forget to remove @code{(provide #f)} when you release
28171 the file, though. Besides, for interactive reloading, consider
28172 using @code{gauche.reload} (@pxref{Reloading modules}) instead.
28173 @c JP
28174 featureを全く@code{provide}しない。
28175 @var{feature}引数に@code{#f}を渡すことで、何のfeatureも@code{provide}することなく
28176 @code{require}によるautoprovidingを抑制できます。
28177
28178 これもまた、何らかの一時的な解決と考えるべきです。たとえば開発中に、
28179 @file{X.scm}を頻繁に変更するために@code{(require "X")}が常に
28180 そのファイルをロードするようにさせたい、といった場合が考えられます。
28181 @file{X.scm}のリリースの前に @code{(provide #f)} を消しておくことを
28182 忘れないように。また、インタラクティブにリロードしたいならば
28183 @code{gauche.reload} (@ref{Reloading modules}参照) を使うことを
28184 おすすめします。
28185 @c COMMON
28186 @end itemize
28187
28188 @end defun
28189
28190 @defun provided? feature
28191 @c EN
28192 Returns @code{#t} if @var{feature} is already provided.
28193 @c JP
28194 @var{feature}が既にprovideされていれば@code{#t}を返します。
28195 @c COMMON
28196 @end defun
28197
28198 @node Autoload, Operations on libraries, Require and provide, Loading Programs
28199 @subsection Autoload
28200
28201 @defmac autoload file/module item @dots{}
28202 @c EN
28203 Sets up @var{item} @dots{} to be autoloaded.
28204 That is, when an @var{item} is referenced for the first time,
28205 @var{file/module} is loaded before the @var{item} is evaluated.
28206 This delays the loading of @var{file/module} until it is needed.
28207 @c JP
28208 @var{item} @dots{} がオートロードされるように設定します。すなわち、
28209 次に@var{item}が参照された時、それが実際に評価される前に@var{file/module}がロード
28210 されるようにします。これによって、必要とされる時まで@var{file/module}のロードを遅らせる
28211 ことができます。
28212 @c COMMON
28213
28214 @c EN
28215 You can specify either a string file name or a symbol module name
28216 to @var{file/module}. If it is a string, the named file is
28217 loaded. If it is a symbol, the named module is loaded (using the
28218 same rule as of @code{use}), then the binding of @var{item} in the
28219 @var{file/module} is imported to the module used the autoload
28220 (@xref{Defining and selecting modules}, for details of @code{use}).
28221 @c JP
28222 引数@var{file/module}には、文字列かシンボルを指定できます。文字列の場合は
28223 そのファイルがロードされます。シンボルの場合、その名のモジュールが(@code{use}と
28224 同じルールで)ロードされ、@var{item}が@var{file/module}から
28225 オートロードを呼び出したモジュールへとインポートされます。
28226 (モジュールの@code{use}の詳細については@ref{Defining and selecting modules}を参照して下さい)。
28227 @c COMMON
28228
28229 @c EN
28230 @var{Item} can be either a variable name (symbol),
28231 or a form @code{(:macro @var{symbol})}. If it is a variable,
28232 the named file/module is loaded when the variable is
28233 about to be evaluated. If it is the latter form,
28234 the named file/module is loaded when a form
28235 @code{(@var{symbol} arg @dots{})} is about to be @emph{compiled},
28236 which enables autoloading macros.
28237 @c JP
28238 @var{item}は変数名(シンボル)か、@code{(:macro @var{symbol})}というフォーム
28239 でなければなりません。変数名の場合は、その変数が評価されようとした時に
28240 指定のファイル/モジュールがロードされます。後者のフォームの場合は、
28241 @code{(@var{symbol} arg @dots{})} というフォームがコンパイルされようとした
28242 時に指定のファイル/モジュールがロードされます。後者はマクロのオートロードになります。
28243 @c COMMON
28244
28245 @c EN
28246 @var{file/module} must define @var{symbol} in it, or an error is signaled
28247 when @var{file/module} is autoloaded.
28248 @c JP
28249 @var{symbol}は@var{file/module}の中で定義されなければなりません。
28250 そうでなければロード時にエラーが報告されます。
28251 @c COMMON
28252
28253 @c EN
28254 The following is an example of autoloading procedures.
28255 @c JP
28256 手続きのオートロードの例を示します。
28257 @c COMMON
28258 @example
28259 (autoload "foo" foo0 foo1)
28260 (autoload "bar" bar0 bar1)
28261
28262 (define (foobar x)
28263 (if (list? x)
28264 (map bar0 x)
28265 (foo0)))
28266
28267 @c EN
28268 (foobar '(1 2)) ; @r{"bar" is loaded at this moment}
28269
28270 (foobar #f) ; @r{"foo" is loaded at this moment}
28271 @c JP
28272 (foobar '(1 2)) ; @r{この時点で "bar" がロードされる}
28273
28274 (foobar #f) ; @r{この時点で "foo" がロードされる}
28275 @c COMMON
28276 @end example
28277
28278 @c EN
28279 Note that if you set to autoload macro, the file/module is loaded
28280 immediately when such form that uses the macro is compiled,
28281 regardless of the piece of
28282 the code is executed or not.
28283 @c JP
28284 マクロのオートロードを設定した場合、指定のファイルまたはモジュールは、
28285 そのマクロを使っているフォームが実行されるされないにかかわらず、
28286 コンパイラがそのフォームを見た時点でロードされることに注意してください。
28287 @c COMMON
28288 @end defmac
28289
28290 @node Operations on libraries, , Autoload, Loading Programs
28291 @subsection Operations on libraries
28292 @c NODE ライブラリの操作
28293
28294 @c EN
28295 There are several procedures you can use to check if
28296 certain libraries and/or modules are installed in the system.
28297
28298 In the following descriptions, @var{pattern} is either a
28299 symbol or a string. If it is a symbol, it specifies
28300 a module name (e.g. @code{foo.bar}). If it is
28301 a string, it specifies a partial pathname of the library
28302 (e.g. @code{"foo/bar"}), which will be searched under
28303 library search paths.
28304 You can also use glob-like metacharacters @code{*} and
28305 @code{?} in @var{pattern}.
28306 @c JP
28307 ある特定のライブラリおよび/あるいはモジュールがシステムにインストールされ
28308 ているかどうかをチェックするための手続きがいくつかあります。
28309
28310 以下の説明の中では、@var{pattern}はシンボルまたは文字列です。シンボル
28311 である場合にはモジュール名(たとえば、@code{foo.bar})を指定します。
28312 文字列である場合にはライブラリの部分パス(たとえば、@code{"foo/bar"})を
28313 指定します。これはライブラリサーチパス以下で検索されます。
28314 @var{pattern}には@code{glob}のメタ文字と同じ意味で @code{*} と @code{?} を
28315 使うこともできます。
28316 @c COMMON
28317
28318 @defun library-fold pattern proc seed :key paths strict? allow-duplicates?
28319 @c EN
28320 A basic iterator for library/module files.
28321 This procedure searches Scheme program files which matches
28322 @var{pattern}, under directories listed in @var{paths}
28323 (the default is the standard file load paths, @code{*load-path*}).
28324 For each matched file, it calls @var{proc} with three arguments:
28325 the matched module or library name, the full path of the program
28326 file, and the state value. @var{Seed} is used as the initial
28327 state value, and the value @var{proc} returns is used as the state
28328 value for the next call of @var{proc}. The value returned from
28329 the last @var{proc} becomes the return value of @code{library-fold}.
28330 @c JP
28331 ライブラリ/モジュールファイルに対する基本イテレータ。この手続きは
28332 @var{pattern} にマッチする Scheme のプログラムファイルを検索します。
28333 検索は @var{paths} (デフォルトは標準のファイルロードパス、
28334 @code{*load-path*})にリストされたディレクトリ以下でおこなわれます。
28335 マッチしたファイル毎に、@var{proc} が、そのマッチしたモジュール名あるいは
28336 ライブラリ名、そのプログラムファイルのフルパス、状態値、の3つの引数を
28337 ともなって呼びだされます。@var{seed}は、初期状態値として使われ、
28338 @var{proc} が返す値は次の @var{proc} の呼出し時に状態値として使われます。
28339 最後の @var{proc} から返された値は @code{library-fold} の値として返ります。
28340 @c COMMON
28341
28342 @c EN
28343
28344 @c JP
28345 @c COMMON
28346
28347 @c EN
28348 If @var{pattern} is a symbol and the keyword argument @var{strict?}
28349 is @code{#t} (which is the default), this procedure calls
28350 @code{library-has-module?} on the files whose name seems to
28351 match the given pattern of module name, in order to find out
28352 the file really implements the module. It can be a time consuming
28353 process if you try to match large number of modules; you can pass
28354 @code{#f} to @var{strict?} to avoid the extra check.
28355 If @var{pattern} is a string, matching is done only for file names
28356 so @var{strict?} is ignored.
28357 @c JP
28358 @var{pattern} がシンボルでかつ、キーワード引数 @var{strict?} が
28359 @code{#t} (デフォルト値)であれば、この手続きは
28360 あたえられたモジュール名のパターンにマッチするようにみえるファイル名に
28361 たいして @code{library-has-module?} を適用して、
28362 本当にそのモジュールを実装しているファイルを見付けます。
28363 大量のモジュールにマッチさせようとすると、時間がかる可能性があります。
28364 @code{#f} を @var{strict?} に渡すことで、余分なチェックを回避できます。
28365 @var{pattern} が文字列だった場合、照合はファイル名に対してのみ行われ、
28366 @var{strict?}は無視されます。
28367 @c COMMON
28368
28369 @c EN
28370 By default, if there are more than one files that have the same name
28371 that matches @var{pattern} in @var{paths}, only the first
28372 one appears in @var{paths} is taken. This gives you
28373 the file you'll get if you use @code{require} or @code{use}
28374 for that library. If you want to iterate all of matching files,
28375 pass @code{#t} to the @var{allow-duplicates?} keyword argument.
28376
28377 Here are some examples (the result may differ in your environment).
28378 @c JP
28379 デフォルトでは、@var{path} 中の @var{pattern} にマッチする同じ名前をもつ
28380 2つ以上のファイルがあるばあい、@var{path} に最初に出現したものだけが
28381 採用されます。そのライブラリに対して、@code{require} あるいは
28382 @code{use} を用いたをつかった場合に得られるのはこのファイルです。
28383 すべてのマッチしたファイルについて反復したければ、@var{allow-duplicates?}
28384 キーワード引数に @code{#t} を渡します。
28385 @c COMMON
28386 @c EN
28387 @example
28388 (library-fold 'srfi.1 acons '())
28389 @result{} ((srfi.1 . "../lib/srfi/1.scm"))
28390
28391 (library-fold "srfi.1" acons '())
28392 @result{} (("srfi.1" . "../lib/srfi/1.scm"))
28393
28394 ;; Note the returned list is in a reverse order of
28395 ;; how @code{acons} is called.
28396 (library-fold 'srfi.1 acons '() :allow-duplicates? #t)
28397 @result{} ((srfi.1 . "/usr/share/gauche-0.98/0.9.13/lib/srfi/1.scm")
28398 (srfi.1 . "../lib/srfi.1.scm"))
28399
28400 ;; Finds available dbm implementations
28401 (library-fold 'dbm.* acons '())
28402 @result{} ((dbm.cdb . "/usr/share/gauche-0.98/0.9.13/lib/dbm/cdb.scm")
28403 (dbm.gdbm . "../lib/dbm/gdbm.scm")
28404 (dbm.ndbm . "../lib/dbm/ndbm.scm")
28405 (dbm.odbm . "../lib/dbm/odbm.scm"))
28406 @end example
28407 @c JP
28408 @example
28409 (library-fold 'srfi.1 acons '())
28410 @result{} ((srfi.1 . "../lib/srfi/1.scm"))
28411
28412 (library-fold "srfi.1" acons '())
28413 @result{} (("srfi.1" . "../lib/srfi/1.scm"))
28414
28415 ;; @code{acons} が呼ばれるのとは逆順のリストが
28416 ;; 返ることに注意してください
28417 (library-fold 'srfi.1 acons '() :allow-duplicates? #t)
28418 @result{} ((srfi.1 . "/usr/share/gauche-0.98/0.9.13/lib/srfi/1.scm")
28419 (srfi.1 . "../lib/srfi.1.scm"))
28420
28421 ;; 利用可能な dbm の実装を見付けます
28422 (library-fold 'dbm.* acons '())
28423 @result{} ((dbm.cdb . "/usr/share/gauche-0.98/0.9.13/lib/dbm/cdb.scm")
28424 (dbm.gdbm . "../lib/dbm/gdbm.scm")
28425 (dbm.ndbm . "../lib/dbm/ndbm.scm")
28426 (dbm.odbm . "../lib/dbm/odbm.scm"))
28427 @end example
28428 @c COMMON
28429 @end defun
28430
28431 @defun library-map pattern proc :key paths allow-duplicates? strict?
28432 @defunx library-for-each pattern proc :key paths allow-duplicates? strict?
28433 @c EN
28434 @code{Map} and @code{for-each} version of iterator over matched
28435 libraries/modules. See @code{library-fold} above for detailed
28436 operation of matching and the meanings of keyword arguments.
28437
28438 @var{Proc} receives two arguments, the matched module/library name
28439 and full path of the file. @code{Library-map} returns a list
28440 of results of @var{proc}. @code{Library-for-each} discards
28441 the results.
28442 @c JP
28443 マッチしたライブラリ/モジュール上のイテレータの @code{map}版および
28444 @code{for-each}版。照合操作とキーワード引数の詳細については上述の
28445 @code{library-fold}を参照してください。
28446
28447 @var{proc}は、マッチしたモジュール/ファイル名と、そのファイルの
28448 フルパスの 2 つの引数をうけとります。@code{library-for-each} は
28449 結果を捨てます。
28450 @c COMMON
28451
28452 @example
28453 (library-map 'srfi.4 list :allow-duplicates? #t)
28454 @result{} ((srfi.4 "../lib/srfi/4.scm")
28455 (srfi.4 "/usr/share/gauche-0.98/0.9.13/lib/srfi/4.scm"))
28456
28457 (library-map 'dbm.* (lambda (m p) m))
28458 @result{} (dbm.odbm dbm.ndbm dbm.gdbm dbm.cdb)
28459 @end example
28460 @end defun
28461
28462 @defun library-exists? mod/path :key paths force-search? strict?
28463 @c EN
28464 Search a library or a module specified by @var{mod/path},
28465 and returns a true value if it finds one. @var{Paths} and @var{strict?}
28466 keyword arguments have the same meaning as @code{library-fold}.
28467
28468 Unlike the iterator procedures above, this procedure first
28469 checks loaded libraries and modules in the calling process,
28470 and returns true if it finds @var{mod/path} in it,
28471 without looking into the filesystem. Passing @code{#t} to
28472 @var{force-search?} keyword arguments skips the checking of
28473 loaded libraries and modules.
28474 @c JP
28475 @var{mod/path} で指定されたライブラリあるいはモジュールを検索し、
28476 もしあれば、真値を返します。キーワード引数 @var{paths} および
28477 @var{strict?} は @code{library-fold} のそれと同じ意味です。
28478
28479 上述のイテレータ手続きとはちがい、この手続きは呼び出しの過程で
28480 最初に既にロードされているライブラリおよびモジュールをチェックします。
28481 もしそのときに @var{mod/path} を見つけたら、真値を返し、ファイル
28482 システムを見にいくことはありません。キーワード引数 @var{force-search?}
28483 に @code{#t} を渡せば、すでにロードされいるライブラリおよびモジュール
28484 のチェックはスキップされます。
28485 @c COMMON
28486 @end defun
28487
28488
28489 @defun library-has-module? path module
28490 @c EN
28491 Returns @code{#t} iff a file specified by @var{path} exists and
28492 appears to implement a module named by @code{module}. @var{path} must be
28493 an actual filename.
28494 @c JP
28495 @var{path} で指定したファイルが存在し、かつ、@code{module} で名指しされた
28496 モジュールが実装されている場合でその場合に限り、@code{#t} を返します。
28497 @var{path} は実際のファイル名でなければなりません。
28498 @c COMMON
28499
28500 @example
28501 (library-has-module? "./test/foo/bar.scm" 'foo.bar)
28502 @result{} #t ;; @r{if ./test/foo/bar.scm implements module foo.bar}.
28503 @end example
28504
28505 @c EN
28506 This procedure assumes a typical layout of the source code
28507 to determine if the given file implements the module, i.e.,
28508 it reads the first form of the code and see if it is a
28509 @code{define-module} form that is defining the given module.
28510 @c JP
28511 この手続きは典型的なソースコードの配置を仮定して、与えられたファイルが
28512 そのモジュールを実装しているかどうかを決定します。すなわち、
28513 まずそのコードのフォームを読み、与えられたモジュールを定義している
28514 @code{define-module} フォームかどうかを見ます。
28515 @c COMMON
28516 @end defun
28517
28518 @c ----------------------------------------------------------------------
28519 @node Sorting and merging, System interface, Loading Programs, Core library
28520 @section Sorting and merging
28521 @c NODE ソートとマージ
28522
28523 @c EN
28524 The interface of sorting and merging API complies SRFI-95, with the
28525 following extensions:
28526 @c JP
28527 ソートとマージのインタフェースはSRFI-95に準拠し、さらに次の点で拡張されています。
28528 @c COMMON
28529
28530 @itemize @bullet
28531 @item
28532 @c EN
28533 You can sort not only lists, vectors and strings, but
28534 any sequence (an instance of @code{<sequence>}).
28535 @c JP
28536 リスト、ベクタ、文字列だけでなく、あらゆるシーケンス
28537 (@code{<sequence>}のインスタンス)をソートできます。
28538 @c COMMON
28539 @item
28540 @c EN
28541 You can use both comparison procedures
28542 and comparators (@pxref{Basic comparators}) to specify the order.
28543 @c JP
28544 順序を指定するのに、比較関数も比較器(@ref{Basic comparators}参照)も
28545 使うことができます。
28546 @c COMMON
28547 @item
28548 @c EN
28549 You can omit comparison procedure; in that case,
28550 elements are compared with @code{default-comparator}.
28551 @c JP
28552 比較関数を省略できます。省略された場合、
28553 要素同士は@code{default-comparator}を使って比較されます。
28554 @c COMMON
28555 @end itemize
28556
28557 @defun sort seq :optional cmp keyfn
28558 @defunx sort! seq :optional cmp keyfn
28559 [SRFI-95+]
28560 @c EN
28561 Sorts elements in a sequence @var{seq}
28562 in ascending order and returns the sorted sequence.
28563 @code{sort!} destructively reuses the original sequence.
28564
28565 You can pass an instance of any @code{<sequence>} as @var{seq};
28566 the same type of sequence will be returned. For @code{sort}, the
28567 sequence type must have builder interface so that @code{sort} can
28568 build a new sequence of the same type (See @ref{Fundamental iterator creators},
28569 for the builder interface).
28570 For @code{sort!}, @var{seq} must be mutable.
28571
28572 The sorting order is specified by @code{cmp}. It must be
28573 either a procedure or a comparator.
28574 If it is a procedure, it
28575 must take two elements of @var{seq}, and returns @code{#t}
28576 if the first argument strictly precedes the second.
28577 If it is a comparator, it must have the comparison procedure.
28578 If omitted, @code{default-comparator} is used.
28579
28580 If the optional argument @var{keyfn} is given, the elements are
28581 first passed to it and the results are used for comparison.
28582 It is guaranteed that @var{keyfn} is called at most once per
28583 element.
28584 @c JP
28585 シーケンス@var{seq}の要素を昇順にソートし、
28586 ソートされたシーケンスを返します。
28587 @code{sort!}は、オリジナルのシーケンスを破壊的に再利用します。
28588
28589 @var{seq}には@code{<sequence>}クラスのインスタンスを渡すことができます。
28590 同じ型のシーケンスが返されます。@code{sort}の場合、
28591 @var{seq}と同じ型のシーケンスを新たに作る必要があるので、
28592 @var{seq}の型はビルダーインタフェースを実装していなければなりません
28593 (ビルダーインタフェースについては@ref{Fundamental iterator creators}を参照)。
28594 @code{sort!}の場合、@var{seq}は変更可能でなければなりません。
28595
28596 ソート順は@code{cmp}で指定されます。これは手続きか比較器でなければなりません。
28597 手続きの場合は、@var{seq}のふたつの要素を
28598 引数に取り、最初の要素が厳密に2番目の要素より先行する場合に
28599 @code{#t}を返します。
28600 比較器の場合は、比較手続きを持つものでなければなりません。
28601 省略された場合は@code{default-comparator}が使われます。
28602
28603 省略可能な手続き引数@var{keyfn}が与えられた場合、
28604 要素はまず@var{keyfn}に渡され、その結果が比較に使われます。
28605 @var{keyfn}は各要素に対してたかだか1回しか呼ばれないことが保証されます。
28606 @c COMMON
28607
28608 @example
28609 (sort '(("Chopin" "Frederic")
28610 ("Liszt" "Franz")
28611 ("Alkan" "Charles-Valentin"))
28612 string<?
28613 car)
28614 @result{} (("Alkan" "Charles-Valentin")
28615 ("Chopin" "Frederic")
28616 ("Liszt" "Franz"))
28617 @end example
28618
28619 @c EN
28620 In the current implementation, quicksort and heapsort
28621 algorithm is used when both @var{cmp} and @var{keyfn} is omitted,
28622 and merge sort algorithm is used otherwise. That is, the sort
28623 is stable if you pass at least @var{cmp} (note that to guarantee
28624 stability, @var{cmp} must return @code{#f} when given identical arguments.)
28625 SRFI-95 requires stability, but also requires @var{cmp} argument,
28626 so those procedures are upper-compatible to SRFI-95.
28627 @c JP
28628 現在の実装では、@var{cmp}が省略された場合は
28629 クィックソートとヒープソートを使い、
28630 @var{cmp}が与えられた場合はマージソートを使っています。
28631 すなわち、少なくとも@var{cmp}を指定すれば、ソートは安定であることが
28632 保証されます (ただし、安定であるためには
28633 @var{cmp}は等しい引数が与えられた時に必ず@code{#f}を返さなければなりません)。
28634 SRFI-95は安定性を要求しますが、同時に@var{cmp}が与えられることも要求するので、
28635 これらの手続きはSRFI-95の上位互換です。
28636 @c COMMON
28637
28638 @c EN
28639 If you want to keep a sorted set of objects to which you
28640 add objects one at at time, you can also use treemaps
28641 (@pxref{Treemaps}). If you only need to find out
28642 a few maximum or minimum elements instead of sorting
28643 all the elements, heaps can be used (@pxref{Heap}).
28644 @c JP
28645 なお、オブジェクトをひとつづつ集合に追加しつつ、常にソートされた
28646 状態に保ちたい場合は、treemapの使用を考えても良いでしょう (@ref{Treemaps}参照)。
28647 また、最大または最小から数要素だけを必要とする場合は、
28648 全ての要素をソートするかわりにヒープが使えます (@ref{Heap}参照)。
28649 @c COMMON
28650 @end defun
28651
28652 @defun sorted? seq :optional cmp keyfn
28653 [SRFI-95+]
28654 @c EN
28655 Returns @code{#t} iff elements in @var{seq} are in sorted order.
28656 You can pass any sequence to @var{seq}.
28657 The optional argument @var{cmp} and @var{keyfn} are the same as
28658 @code{sort}.
28659
28660 In SRFI-95, @var{cmp} can't be omitted.
28661 @c JP
28662 @var{seq}の要素がソートされている時に限り@code{#t}を返します。
28663 @var{seq}にはどんなシーケンスを渡すこともできます。
28664 省略可能引数@var{cmp}と@var{keyfn}の意味は@code{sort}と同じです。
28665
28666 SRFI-95では@var{cmp}は必須になっています。
28667 @c COMMON
28668 @end defun
28669
28670
28671 @defun merge a b :optional cmp keyfn
28672 @defunx merge! a b :optional cmp keyfn
28673 [SRFI-95+]
28674 @c EN
28675 Arguments @var{a} and @var{b} are lists, and their elements are
28676 sorted using a compare function or a comparator @var{cmp}. These procedures
28677 merges two list and returns a list, whose elements are sorted
28678 using @var{cmp}. The destructive version @code{merge!} reuses
28679 cells in @var{a} and @var{b}; the returned list is @code{eq?} to
28680 either @var{a} or @var{b}.
28681
28682 In SRFI-95, @var{cmp} can't be omitted.
28683 @c JP
28684 引数@var{a}と@var{b}はリストで、比較関数または比較器@var{cmp}によって
28685 既にソートされているものとします。これらの手続きは二つのソート済みリストを
28686 マージして、ソートされた一つのリストにします。@code{merge!}は破壊的バージョンで、
28687 @var{a}と@var{b}のセルを再利用します。戻り値は@var{a}か@var{b}に対して@code{eq?}と
28688 なります。
28689
28690 SRFI-95では@var{cmp}は必須になっています。
28691 @c COMMON
28692 @end defun
28693
28694 @c EN
28695 The following procedures are for the backward compatibility. Their
28696 features are already covered by extended @code{sort} and @code{sort!}.
28697 @c JP
28698 以下の手続きは後方互換性のために残されていますが、その機能は
28699 拡張された@code{sort}および@code{sort!}によってカバーされています。
28700 @c COMMON
28701
28702
28703 @defun stable-sort seq :optional cmp keyfn
28704 @defunx stable-sort! seq :optional cmp keyfn
28705 @c EN
28706 Sort a sequence @var{seq}, using stable sort algorithm.
28707 Arguments @var{cmp} and @var{keyfn} are the same as @code{sort}
28708 and @code{sort!}.
28709
28710 In fact, @code{sort} and @code{sort!} now uses stable algorithm
28711 when @var{cmp} is provided, so these procedures are redundant,
28712 unless you want to omit @var{cmp} and yet guarantee stable sort.
28713 @c JP
28714 安定ソートアルゴリズムを使って、シーケンス @var{seq}をソートします。
28715 @var{cmpfn}と@var{keyfn}引数は@code{sort}および@code{sort!}と同じです。
28716
28717 実のところ、現在では@var{sort}と@var{sort!}は@var{cmp}が与えられれば
28718 安定ソートアルゴリズムを使うので、これらの手続きは
28719 どうしても@var{cmp}を省略しつつ安定ソートしたい、という場合でなければ
28720 使う必要はありません。
28721 @c COMMON
28722 @end defun
28723
28724 @defun sort-by seq keyfn :optional cmp
28725 @defunx sort-by! seq keyfn :optional cmp
28726 @defunx stable-sort-by seq keyfn :optional cmp
28727 @defunx stable-sort-by! seq keyfn :optional cmp
28728 @c EN
28729 Variations of sort procedures that takes a key extracting function.
28730 These are redundant now, for @code{sort} etc. takes optional @var{keyfn}.
28731 @c JP
28732 比較のためのキーを取り出す関数を取る、ソート手続きの別バージョンです。
28733 @code{sort}等の手続きが省略可能な@var{keyfn}を取るようになったので、
28734 現在ではこれらの関数は冗長です。
28735 @c COMMON
28736 @end defun
28737
28738
28739 @c ----------------------------------------------------------------------
28740 @node System interface, Development helper API, Sorting and merging, Core library
28741 @section System interface
28742 @c NODE システムインタフェース
28743
28744 @c EN
28745 Gauche supports most of POSIX.1 functions and other system functions
28746 popular among Unix variants as built-in procedures.
28747 @c JP
28748 GaucheはPOSIX.1の多くの関数と、さまざまなUnixで共通して使われているシステム関数へのインタフェースを
28749 組込み手続きとして提供しています。
28750 @c COMMON
28751
28752 @c EN
28753 Lots of Scheme implementations provide some sort of system interface
28754 under various APIs. Some are just called by different names
28755 (e.g, @code{delete-file} or @code{remove-file} or @code{unlink} to delete
28756 a file), some do more abstraction introducing new Scheme objects.
28757 Instead of just picking one of such interfaces, I decided to implement
28758 Gauche's system interface API in two layers; the lower level layer,
28759 described in this section, follows the operating system's API
28760 as close as possible. On top of that, the higher-level APIs are
28761 provided, with considering compatibility to the existing systems.
28762 @c JP
28763 多くのScheme実装はいろいろな形で何らかのシステムインタフェースを提供
28764 しています。名前だけが違うもの(例:@code{delete-file}、@code{remove-file}
28765 、@code{unlink}) もあれば、新しいSchemeオブジェクトを導入して
28766 抽象化を行っているものもあります。Gaucheでは、既存のAPIのどれかを
28767 そのまま真似るのではなく、2つのレイヤを提供することにしました。
28768 この章で述べられる低レベルレイヤは、OSのインタフェースに似せたものを実装します。
28769 その上に、既存のシステムと互換性のある高レベルのインタフェースが実装されます。
28770 @c COMMON
28771
28772 @c EN
28773 The low level system interface has the name @code{sys-}@var{name}
28774 and usually correspond to the system call @var{name}.
28775 I tried to keep the interface similar whenever reasonable.
28776 @c JP
28777 @code{sys-}@var{name}という名前を持つ手続きは、多くの場合、
28778 システムコール@var{name}に対応しています。
28779 可能な限り、インタフェースが似るようにしました。
28780 @c COMMON
28781
28782 @c EN
28783 Gauche restarts a system call after it is interrupted by a signal by default.
28784 See @ref{Signal} for the details.
28785 @c JP
28786 なお、システムコールがシグナルによって割り込まれた場合、
28787 そのシステムコールは原則としてリスタートされます。
28788 詳しくは@ref{Signal}を参照して下さい。
28789 @c COMMON
28790
28791 @c EN
28792 If you are familiar with system programming in C,
28793 see also @ref{C to Scheme mapping}, which shows
28794 correspondence between C standard library functions
28795 and Gauche procedures.
28796 @c JP
28797 Cによるシステムプログラミングに慣れている方は、
28798 @ref{C to Scheme mapping}も参考にして下さい。
28799 Cの標準ライブラリとGaucheの手続きとの対応が示してあります。
28800 @c COMMON
28801
28802 @menu
28803 * Program termination::
28804 * Command-line arguments::
28805 * Environment inquiry::
28806 * Filesystems::
28807 * Unix groups and users::
28808 * Locale::
28809 * Signal::
28810 * System inquiry::
28811 * Time::
28812 * Process management::
28813 * I/O multiplexing::
28814 * Garbage collection::
28815 * Memory mapping::
28816 * Miscellaneous system calls::
28817 @end menu
28818
28819 @node Program termination, Command-line arguments, System interface, System interface
28820 @subsection Program termination
28821 @c NODE プログラムの終了
28822
28823 @c EN
28824 Gauche has a few ways to terminate itself (other than returning
28825 from @code{main}). The @code{exit} procedure is a graceful way
28826 with all proper cleanups. @code{sys-exit} and @code{sys-abort}
28827 may be used in emergency where proper cleanup is impossible.
28828 @c JP
28829 Gaucheは(@code{main}から返る以外に)自分自身を終了させる方法をいくつか
28830 提供しています。@code{exit}手続きが、正しいクリーンアップを行って
28831 優雅に終了する方法です。一方、正しいクリーンアップが不可能な非常事態には
28832 @code{sys-exit}か@code{sys-abort}を使います。
28833 @c COMMON
28834
28835
28836 @defun exit :optional (code 0) (fmtstr #f) args @dots{}
28837 [R7RS+ process-context]
28838 @c EN
28839 Terminates the current process with the exit code @var{code}.
28840 The optional @var{code} argument specifies the exit status; @code{#t}
28841 indicates a success (exit code 0),
28842 @code{#f} indicates a failure (exit code 1),
28843 and an exact integer specifies other exit code (only the lower 8 bits are
28844 used). Any other values of @var{code} makes the exit code to be
28845 70 (@code{EX_SOFTWARE}.
28846 Note that R7RS does not specify how @var{code} is translated to OS's
28847 exit status, except that @code{#t} indicates a success and @code{#f}
28848 indicates a failure. Portable code should only pass @code{#t} or @code{#f}.
28849
28850 When a string is given to @var{fmtstr}, it is passed to
28851 @code{format} (@pxref{Output}), with the rest arguments @var{args},
28852 to produce a message to the standard error port
28853 (@emph{not} the current error port; see @ref{Common port operations}).
28854 @c JP
28855 現在のプロセスを終了し、@var{code}を終了コードにします。
28856 @var{code}が@code{#t}なら成功を意味し、終了コードは0に、
28857 @var{code}が@code{#f}なら失敗を意味し、終了コードは1に、
28858 そして正確な整数の場合はその下位8bitが終了コードとして使われます。
28859 @var{code}がそれ以外のオブジェクトの場合は、
28860 終了コードは70 (@code{EX_SOFTWARE})になります。
28861 (R7RSでは、@code{code}は@code{#t}の時正常終了、@code{#f}のとき異常終了を示す
28862 ということ以外に、具体的にOSレベルのどういった値になるかは規定していません。
28863 ポータブルなコードでは@code{#t}か@code{#f}のみを使うのが良いでしょう。)
28864
28865 @var{fmtstr}文字列が与えられた場合、それは残りの引数@var{args}と
28866 ともに@code{format}に渡され、standard error portにメッセージとして
28867 印字されます (@code{current-error-port}ではありません。
28868 @ref{Common port operations}参照。また、@code{format}については
28869 @ref{Output}参照。)
28870 @c COMMON
28871
28872 @c EN
28873 In fact, the exiting procedure is a bit more complicated.
28874 The precise steps of exiting is as follow.
28875 @c JP
28876 実のところ、プロセス終了の手続きはもう少し複雑です。
28877 正確な段階を次に説明します。
28878 @c COMMON
28879
28880 @enumerate
28881 @item
28882 @c EN
28883 The value of parameter @code{exit-handler} is checked.
28884 If it is not @code{#f}, the value is called as a procedure
28885 with three arguments: @var{code}, @var{fmtstr}, and a list of rest
28886 arguments. It is the default procedure of @code{exit-handler}
28887 that prints out the message to the standard error port.
28888 If an error occurs within exit handler, it is captured and
28889 discarded. Other exceptions are not caught.
28890 @c JP
28891 パラメータ@code{exit-handler}の値がチェックされます。
28892 もしそれが@code{#f}でなければ、それは3引数の手続きとみなされ、
28893 @var{code}、@var{fmtstr}、そして残りの引数のリストを引数として
28894 呼び出されます。実はメッセージを標準エラー出力に出しているのは
28895 デフォルトの@code{exit-handler}です。
28896 終了ハンドラの中でエラーが起きた場合、そのエラーは捕捉され捨てられます。
28897 エラー以外の例外は捕捉されません。
28898 @c COMMON
28899
28900 @item
28901 @c EN
28902 The @var{after} thunks of the active dynamic winds are invoked.
28903 Any exceptions raised in @var{after} thunks are captured and discarded.
28904 @c JP
28905 アクティブな@code{dynamic-wind}の@var{after}サンクが順に呼び出されます。
28906 @var{after}サンク中で発生した例外は捕捉され捨てられます。
28907 @c COMMON
28908
28909 @item
28910 @c EN
28911 The clean-up handlers registered via C API @code{Scm_AddCleanupHandler}
28912 are invoked. These are usually responsible for under-the-hood cleanup
28913 jobs for each application that embeds Gauche. From the Scheme world
28914 there's not much to care.
28915 @c JP
28916 C APIの@code{Scm_AddCleanupHandler}で登録されたクリーンアップハンドラが
28917 呼ばれます。このハンドラは通常、Gaucheを内蔵しているアプリケーション特有の
28918 クリーンアップをするために使われます。Schemeの世界からはあまり気にする必要は
28919 ないでしょう。
28920 @c COMMON
28921
28922 @item
28923 @c EN
28924 The unclosed output buffered ports are flushed.
28925 @c JP
28926 まだ閉じられていない出力ポートのバッファが掃き出されます。
28927 @c COMMON
28928
28929 @item
28930 @c EN
28931 The process exits with an integer derived from @var{code}
28932 as an exit code, via @code{exit(3)}.
28933 @c JP
28934 @code{exit(3)}を呼び、プロセスは@var{code}から導出される整数値を終了コードとして終了します。
28935 @c COMMON
28936 @end enumerate
28937
28938 @c EN
28939 The @code{exit-handler} mechanism allows the application to hook its
28940 exit operation. Note that it is not for simple cleanup jobs;
28941 @code{dynamic-wind}, @code{guard} or @code{unwind-protect} are more appropriate.
28942 @code{exit-handler} is for more specific use just upon application exit.
28943 For example, GUI applications may want to post a dialog
28944 instead of printing to stderr.
28945
28946 For this reason, the library code shouldn't change @code{exit-handler};
28947 only the application knows what to do when it exits.
28948
28949 Another useful case is when you
28950 want to call a third-party code which calls @code{exit} inside. In
28951 that case you may swap the @code{exit-handler} for the one
28952 that raises a non-error exception while calling the third-party code.
28953 Non-error exception isn't caught in @code{exit}, effectively
28954 interrupts the steps explained above. (Yet the @var{after} thunks
28955 of dynamic handlers are processed just like normal exception
28956 handling case.)
28957 Your application code can then capture the exception.
28958 You can use @code{parameterize}
28959 to swap @code{exit-handler} dynamically
28960 and thread-safely (@pxref{Parameters}).
28961 @c JP
28962 @code{exit-handler}のメカニズムはアプリケーションが終了処理をフックすることを
28963 可能にします。ただし、単純なクリーンアップ処理のためのものではありません
28964 (クリーンアップ処理には
28965 @code{dynamic-wind}, @code{guard}あるいは@code{unwind-protect}を使う方が
28966 適切です。)
28967 @code{exit-handler}はもっと「アプリケーションの終了」という特定の事態に
28968 対して何か処理を行いたい場合に使います。
28969 例えばGUIアプリケーションはメッセージを標準エラー出力ではなく
28970 ダイアログとして表示する、というようなことです。
28971
28972 従って、ライブラリコードは@code{exit-handler}に触るべきではありません。
28973 アプリケーションの終了時に何をすべきかを知っているのはアプリケーション自身なのですから。
28974
28975 別の使いどころとしては、サードパーティ製のコードで中で@code{exit}が
28976 呼ばれる可能性のあるものを安全に呼び出したいという場合があります。
28977 そのコードを呼び出している間だけ、@code{exit-handler}を
28978 エラーではない例外を発生させる手続きへと差し替えます。
28979 エラーではない例外は@code{exit}では捕捉されないので、実質的に
28980 上で説明したような終了処理のステップは中断されることになります
28981 (但し、ダイナミックハンドラの@var{after}サンクは通常の例外発生時と
28982 同じように処理されます)。
28983 アプリケーションコードの方でその例外を捕捉してやればよいのです。
28984 @code{parameterize}を使えば@code{exit-handler}を動的に、
28985 かつスレッドセーフに差し替えることが容易になります
28986 (@ref{Parameters}参照)。
28987 @c COMMON
28988
28989 @example
28990 (guard (e [(eq? e 'exit-called) (handle-exit-as-desired)])
28991 (parameterize ((exit-handler (lambda (c f a) (raise 'exit-called))))
28992 (call-third-party-library)))
28993 @end example
28994
28995 @c EN
28996 Generally, calling @code{exit} while other threads are running
28997 should be avoided, since it only rewinds the dynamic handlers active
28998 in the calling threads, and other threads will be killed abruptly.
28999 If you have to do so for some reason,
29000 you may be able to use @code{exit-handler} to tell to other threads
29001 that the application is exiting. (There's no general way, and
29002 Gauche doesn't even have a list of all running threads; it's application's
29003 responsibility).
29004 @c JP
29005 一般的に、他のスレッドが走っている時に@code{exit}を呼ぶことは推奨されません。
29006 @code{exit}手続きは該当スレッド上でアクティブなダイナミックハンドラしか巻き
29007 戻さないので、他のスレッドはいきなり終了させられてしまいます。
29008 しかし@code{exit}を呼ばざるを得ない場合には、
29009 @code{exit-handler}を使って他のスレッドにアプリケーションが終了しつつあることを
29010 伝えられるかもしれません (但しGauche自身は走っているスレッドのリストといった
29011 情報は持っていないので、アプリケーションごとに固有のロジックを実装する必要が
29012 あります。)
29013 @c COMMON
29014
29015 @c EN
29016 Note on design: Some languages integrates exit handling
29017 into exception handling, treating exit as a kind of exception.
29018 It is a tempting idea, so much that we've tried it. It didn't
29019 work out well in Gauche; a big annoyance was that when
29020 an @var{after} thunk raised an exception during
29021 rewinding @code{dynamic-wind}s, it shadowed the original
29022 @emph{exit} exception.
29023 @c JP
29024 設計に関する覚書: 終了を一種の例外とすることで、
29025 終了処理を例外処理と統合している言語もあります。
29026 良いアイディアに思えたので我々もそのような実装を試してみましたが、
29027 Gaucheではうまくいきませんでした。大きな理由のひとつは、
29028 @code{dynamic-wind}の巻き戻し中に@var{after}で例外が
29029 発生すると、その例外がもともとの「終了」例外を隠してしまうことでした。
29030 @c COMMON
29031 @end defun
29032
29033 @deffn {Parameter} exit-handler
29034 @c EN
29035 A parameter that holds an exit handler, a procedure to be called
29036 when @code{exit} is called. It takes three arguments,
29037 the exit code, the format string and the list of arguments for the format
29038 string. See @code{exit} above for the details.
29039
29040 Its value can also be @code{#f}, in that case, no handler will
29041 be called.
29042
29043 The default handler shows the formatted message to
29044 the standard error port.
29045
29046 If the handler raises an error, it is captured and discarded.
29047 If the handler raises other conditions, it won't be captured
29048 and propagate to outer controls.
29049 @c JP
29050 @code{exit}が呼ばれた時に呼び出されるexit handlerを保持するパラメータです。
29051 exit handlerは、終了コード、フォーマット文字列、フォーマット文字列の引数のリスト、
29052 の3つの引数を取る手続きです。上の@code{exit}の項を参照してください。
29053
29054 exit handlerの値は@code{#f}にすることもできます。
29055 その場合はハンドラは呼ばれません。
29056
29057 デフォルトのハンドラは、与えられた引数でフォーマットした文字列を
29058 標準エラー出力に出します。
29059
29060 ハンドラがエラーを投げた場合、それは補足され無視されます。
29061 エラー以外のコンディションを投げた場合は補足されないので、
29062 外側の制御機構に処理が任されます。
29063 @c COMMON
29064 @end deffn
29065
29066 @defun sys-exit code
29067 [POSIX]
29068 @c EN
29069 Terminates the current process with the exit code @var{code}.
29070 If @var{code} is @code{#t}, the exit code is 0;
29071 if it is @code{#f}, the exit code is 1;
29072 if it is an exact integer, its lower 8 bits is used for the
29073 exit code. If @var{code} is any other value,
29074 exit code is 70 (@code{EX_SOFTWARE}).
29075 (This is the same as @code{exit}).
29076
29077 This procedure calls @code{_exit(2)} directly.
29078 No cleanup is done. Unflushed file output is discarded.
29079 @c JP
29080 現在のプロセスを終了し、@var{code}を終了コードにします。
29081 @var{code}が@code{#t}なら終了コードは0、
29082 @code{#f}なら終了コードは1、
29083 そして正確な整数の場合は下位8bitが終了コードとして使われます。
29084 それ以外の値では終了コードは70 (@code{EX_SOFTWARE})になります。
29085 (@code{exit}と同じです)。
29086
29087 この手続きは@code{_exit(2)}を直接コールします。
29088 クリーンアップは一切行われません。
29089 フラッシュされてないファイルバッファの内容は捨てられます。
29090 @c COMMON
29091 @end defun
29092
29093 @defun sys-abort
29094 [POSIX]
29095 @c EN
29096 Calls POSIX abort(). This usually terminates the running process
29097 and dumps core. No cleanup is done.
29098 @c JP
29099 POSIXのabort()を呼びます。通常、現在のプロセスは終了され、コアダンプされます。
29100 クリーンアップは一切行われません。
29101 @c COMMON
29102 @end defun
29103
29104 @node Command-line arguments, Environment inquiry, Program termination, System interface
29105 @subsection Command-line arguments
29106 @c NODE コマンドライン引数
29107
29108 @c EN
29109 The recommended way to get command-line arguments passed to a
29110 Scheme script is the argument to the @code{main} procedure
29111 (@pxref{Writing Scheme scripts}). For the convenience,
29112 there are a few ways to access to the command-line arguments
29113 globally.
29114 @c JP
29115 Schemeスクリプトに渡されたコマンドライン引数を受け取るには、
29116 @var{main}関数の引数を使うのが推奨される方法です
29117 (@pxref{Writing Scheme scripts})。
29118 ただ、簡便のために、どこからでもコマンドライン引数にアクセスできる
29119 インターフェースもいくつか用意してあります。
29120 @c COMMON
29121
29122 @c EN
29123 Note that a Scheme code may not always be called with a command-line
29124 argument---for example, an application-embedded Scheme scriptlet may
29125 not have the concept of command-line at all. That's why the @code{main}
29126 argument is preferred, since it is an explicit interface; if @code{main}
29127 is called, the caller is responsible to pass in something.
29128 @c JP
29129 Schemeコードが実行される時、常にコマンドライン引数が存在するわけではない
29130 ことに注意してください。例えばアプリケーションに埋め込まれたSchemeコード片にとっては、
29131 コマンドライン引数は意味を持ちません。なるべく@code{main}関数の引数を使うべき、
29132 というのはそのためです。@code{main}関数の引数は明示的だからです。
29133 @code{main}が呼ばれたなら、呼び出す側は意識してコマンドライン引数を渡している
29134 わけですから。
29135 @c COMMON
29136
29137 @c EN
29138 That said, here are how to access the command-line arguments:
29139 @c JP
29140 この注意を念頭に置いておいてください。
29141 以下にコマンドライン引数にアクセスする方法を示します。
29142 @c COMMON
29143
29144 @deffn {Parameter} command-line
29145 [R7RS+ process-context][SRFI-193]
29146 @c EN
29147 When called without arguments, it returns a list of command-line arguments,
29148 including the program name in the first element, as a list of strings.
29149 @c JP
29150 引数なしで呼ばれた場合は、コマンドライン引数のリストを文字列のリストとして返します。
29151 最初の要素はプログラム名です。
29152 @c COMMON
29153
29154 @c EN
29155 When Gauche is used as an embedded language, it is application's discretion
29156 to set up this parameter. If the application does nothing, this parameter
29157 will have an empty list. When you use this parameter in the library
29158 you have to deal with that situation.
29159 @c JP
29160 Gaucheが埋め込み言語として使われた場合、このパラメータの値はアプリケーションの
29161 設定に依存します。アプリケーションが何もしていなければ、
29162 このパラメータの値は空リストとなります。ライブラリ中でこのパラメータの値を
29163 使う場合は、その可能性を念頭に置いてください。
29164 @c COMMON
29165
29166 @c EN
29167 When called with one argument, a list of string, it will become the
29168 new value of the parameter. You can use @code{parameterize} to
29169 switch the value of @code{command-line} dynamically
29170 (@pxref{Parameters}). Note that R7RS only defines zero-argument
29171 @code{command-line}.
29172 @c JP
29173 一つの引数で呼び出すこともできます。その場合、引数は文字列のリストでなければなりません。
29174 渡された引数が、新たなパラメータの値となります。
29175 @code{parameterize}を使って@code{command-line}の値を
29176 動的に変えることができます (@ref{Parameters}参照)。
29177 R7RSは、ゼロ引数の@code{command-line}のみ定義しています。
29178 @c COMMON
29179 @end deffn
29180
29181 @deffn {Parameter} script-file
29182 [SRFI-193]
29183 @c EN
29184 While a Scheme program is run as a @emph{script}, this parameter holds
29185 the absolute path of the Scheme source file being run. Run as a script
29186 means either it is passed as the script file to @code{gosh}, or
29187 the file is directly @code{load}ed from the toplevel REPL.
29188
29189 If this function is called from the context outside of script execution,
29190 @code{#f} is returned.
29191 @c JP
29192 Schemeプログラムが@emph{スクリプト}として実行されている期間中、
29193 このパラメータはそのスクリプトの絶対パスを保持しています。
29194 スクリプトとして実行とは、@code{gosh}にスクリプトファイルとして渡されるか、
29195 トップレベルREPLから直接@code{load}される場合です。
29196
29197 この関数がスクリプト実行期間中以外に呼ばれた場合は@code{#f}が返ります。
29198 @c COMMON
29199 @end deffn
29200
29201
29202 @defvar *program-name*
29203 @defvarx *argv*
29204 @c DEPRECATED
29205 @c EN
29206 These variables are bound to the program name and the list of command-line
29207 arguments, respectively. In Gauche scripts that are invoked by @code{gosh}
29208 command, @code{*program-name*} is usually the name of the script, as
29209 given to @code{gosh}. When @code{gosh} is invoked interactively,
29210 @code{*program-name*} contains a zero-length string @code{""},
29211 and @code{*argv*} is an empty list.
29212
29213 These variables exist in @code{user} module.
29214
29215 They are mainly kept for the backward compatibility.
29216 These names are compatible to STk, but other Scheme implementation uses
29217 different conventions. The @code{command-line} parameter above is
29218 preferred.
29219
29220 When Gauche is used as an embedded language, it's the host application's
29221 discretion to set up these variables. Generally, you can't count on
29222 those variables to exist. That's another reason you should avoid
29223 using them.
29224 @c JP
29225 これらの変数はそれぞれ、プログラム名および、コマンドライン引数のリストに束縛されます。
29226 @code{gosh}を使ってGaucheスクリプトを実行しているなら、@code{*program-name*}は
29227 (@code{gosh}に与えられたとおりの) スクリプト名になっています。@code{gosh}が
29228 インタラクティブREPLとして起動された場合は@code{*program-name*}は
29229 空文字列@code{""}で、@code{*argv*}は空リストです。
29230
29231 これらの変数は@code{user}モジュールにあります。
29232
29233 これは主として互換性のためだけに残されています。STkと互換な名前ですが、
29234 他のScheme実装へはポータブルではありません。上の@code{command-line}パラメータの
29235 方がお勧めです。
29236
29237 Gaucheが埋め込み言語として使われている場合、これらの変数を設定するかどうかは
29238 ホストアプリケーションに任されます。一般には、これらの変数が必ず存在している
29239 とは限りません。これもまた、他の方法を使うべき理由です。
29240 @c COMMON
29241 @end defvar
29242
29243
29244 @node Environment inquiry, Filesystems, Command-line arguments, System interface
29245 @subsection Environment inquiry
29246 @c NODE 環境の問い合わせ
29247
29248 @defun sys-getenv name
29249 [POSIX]
29250 @c EN
29251 Returns the value of the environment variable @var{name} as a string,
29252 or @code{#f} if the environment variable is not defined.
29253
29254 For the portable code, you may want to use SRFI-98's
29255 @code{get-environment-variable} (@pxref{Accessing environment variables}),
29256 which is also in R7RS.
29257
29258 Note: Most systems doesn't guarantee thread-safety of @code{getenv} while
29259 environment is being modified; however, Gauche mutexes environment
29260 accessing/mutating APIs internally, so you don't need to worry
29261 about the race condition as far as you use Gauche procedures.
29262 @c JP
29263 環境変数@var{name}の値を文字列で返します。もし@var{name}が定義されていなければ、
29264 @code{#f}が返ります。
29265
29266 ポータブルなコードでは、SRFI-98およびR7RSの@code{get-environment-variable}を
29267 使うのが良いでしょう(@ref{Accessing environment variables}参照)。
29268
29269 註: 多くのシステムでは、環境が変更されている最中の@code{getenv}のスレッド安全性を
29270 保証していませんが、Gaucheは内部的に環境へのアクセスと変更のAPIを排他制御しているので、
29271 Gaucheの手続きを使っている限りにおいてはスレッド安全です。
29272 @c COMMON
29273 @end defun
29274
29275 @defun sys-environ
29276 @c EN
29277 Returns the current environment as a list of strings. Each string
29278 is a form of @code{NAME=VALUE}, where @code{NAME} is the name of
29279 the environment variable and @code{VALUE} is its value. @code{NAME}
29280 never contains a character @code{#\=}. This is useful when you want
29281 to obtain the all environment variables of the current process.
29282 Use @code{sys-getenv} if you want to query a specific environment
29283 variable.
29284 @c JP
29285 現在の環境を文字列のリストとして返します。それぞれの文字列は
29286 @code{NAME=VALUE}というフォーマットになっています。ここで@code{NAME}は
29287 環境変数名、@code{VALUE}はその値です。@code{NAME}が文字@code{#\=}を含
29288 むことはありません。この手続きは現在のプロセスの環境変数をすべて取得し
29289 たい場合に便利です。特定の環境変数の値が欲しい場合には
29290 @code{sys-getenv}を使ってください。
29291 @c COMMON
29292 @end defun
29293
29294 @defun sys-environ->alist :optional envlist
29295 @c EN
29296 A convenience procedure for @code{sys-environ}. When the list of
29297 environment strings (like what @code{sys-environ} returns) is given
29298 to @var{envlist}, this procedure splits name and value of
29299 each environment variable and returns an assoc list.
29300 @c JP
29301 @code{sys-environ}の便利版。環境リスト(@code{sys-environ}が返すような
29302 形式のもの)を@var{envlist}として与えると、この手続きは各環境変数を名前
29303 と値に分けて連想リストにして返します。
29304 @c COMMON
29305
29306 @c EN
29307 When @var{envlist} is omitted, this procedure calls @code{sys-environ}
29308 to get the current environment variables.
29309 @c JP
29310 @var{envlist}を省略すると、この手続きは@code{sys-environ}を呼んで現在
29311 の環境変数を取得します。
29312 @c COMMON
29313
29314 @c EN
29315 For the portable code, you may want to use SRFI-98's
29316 @code{get-environment-variables} (@pxref{Accessing environment variables}),
29317 which is also in R7RS.
29318 @c JP
29319 ポータブルなコードでは、SRFI-98およびR7RSの
29320 @code{get-environment-variables} (@ref{Accessing environment variables}参照),
29321 を使うのが良いでしょう。
29322 @c COMMON
29323
29324 @example
29325 (sys-environ->alist '("A=B" "C=D=E"))
29326 => (("A" . "B") ("C" . "D=E"))
29327 @end example
29328 @end defun
29329
29330
29331 @defun sys-setenv name value :optional overwrite
29332 @defunx sys-putenv name=value
29333 @c EN
29334 @var{sys-setenv} inserts an environment variable @var{name} with
29335 the value @var{value}.
29336 Both @var{name} and @var{value} must be a string.
29337 If the optional argument @var{overwrite} is @code{#f} (default),
29338 the environment is untouched if a variable with @var{name} already
29339 exists. If @var{overwrite} is true, the variable is overwritten.
29340 @c JP
29341 @var{sys-setenv}は環境変数@var{name}とその値@var{value}を
29342 プロセスの実行環境に挿入します。
29343 ただし、省略可能引数@var{overwrite}が@code{#f}(デフォルト値)の場合、
29344 @var{name}が既に存在したら実行環境は変更されません。
29345 @var{overwrite}が真の値であれば、環境変数は上書きされます。
29346 @c COMMON
29347
29348 @c EN
29349 For @code{sys-putenv}, you have to give a single string
29350 with the form of @code{NAME=VALUE}, that is, concatenating @var{name}
29351 and @var{value} with @code{#\=}. If the environment variable with
29352 the same name exists, it will be overwritten.
29353 @c JP
29354 @code{sys-putenv}では、環境変数を名前と値を@code{#\=}でつないだ
29355 @code{NAME=VALUE}という形式で指定します。
29356 同名の環境変数が既に存在する場合は常に上書きされます。
29357 @c COMMON
29358
29359 @c EN
29360 These API reflects POSIX @code{setenv(3)} and @code{putenv(3)}.
29361 However, unlike @code{putenv(3)}, modifying the string passed
29362 to @code{sys-putenv} afterwards won't affect the environment.
29363 @c JP
29364 これらのAPIはPOSIXの@code{setenv(3)}と@code{putenv(3)}のインタフェースを
29365 反映しています。しかし、@code{putenv(3)}と違って
29366 @code{sys-putenv}に渡した文字列はコピーされるので、後でその文字列を
29367 破壊的変更してもプロセスの実行環境に影響はありません。
29368 @c COMMON
29369
29370 @c EN
29371 These procedures are only available when a feature identifier
29372 @code{gauche.sys.setenv} exists. Use @code{cond-expand}
29373 (@pxref{Feature conditional}) to check their availability.
29374 @c JP
29375 これらの手続きは機能識別子@code{gauche.sys.setenv}がある場合のみ使えます。
29376 下の例のように@code{cond-expand}で使えるかどうかチェックしてください
29377 (@ref{Feature conditional}参照)。
29378 @c COMMON
29379
29380 @example
29381 (cond-expand
29382 [gauche.sys.setenv
29383 ... use sys-setenv or sys-putenv ... ]
29384 [else
29385 ... fallback code ...])
29386 @end example
29387
29388 @c EN
29389 These procedures are thread-safe as far as you access and modify
29390 the environment through Gauche API.
29391 @c JP
29392 これらの手続きは、他の方法で環境変数を変更しない限り、スレッドセーフです。
29393 @c COMMON
29394 @end defun
29395
29396 @defun sys-unsetenv name
29397 @defunx sys-clearenv
29398 @c EN
29399 Remove the environment variable with @var{name} (@code{sys-unsetenv}),
29400 or all environment variables. @code{sys-clearenv} is handy
29401 when you need to run subprocess, but you cannot trust the inherited
29402 environment.
29403
29404 These procedures are only available when a feature identifier
29405 @code{gauche.sys.unsetenv} exists. Use @code{cond-expand}
29406 (@pxref{Feature conditional}) to check their availability.
29407 @c JP
29408 @code{sys-unsetenv}は環境変数@var{name}を、また
29409 @code{sys-clearenv}は全ての環境変数をプロセスの実行環境から取り除きます。
29410 @code{sys-clearenv}は、子プロセスを走らせる際に予期せぬ環境変数を
29411 注入されないようにするのに便利です。
29412
29413 これらの手続きは機能識別子@code{gauche.sys.unsetenv}がある場合のみ使えます。
29414 下の例のように@code{cond-expand}で使えるかどうかチェックしてください
29415 (@ref{Feature conditional}参照)。
29416 @c COMMON
29417
29418 @example
29419 (cond-expand
29420 [gauche.sys.unsetenv
29421 ... use sys-unsetenv or sys-clearenv ... ]
29422 [else
29423 ... fallback code ...])
29424 @end example
29425 @end defun
29426
29427
29428 @c EN
29429 SRFI-98 (@pxref{Accessing environment variables}) also defines
29430 a subset of above procedures to access to the environment variables.
29431 Portable programs may want to use them instead.
29432 @c JP
29433 SRFI-98 (@ref{Accessing environment variables}参照) にも、
29434 環境変数を読み出すための、上記の手続きのサブセットにあたるものが
29435 定義されています。ポータブルなコードにしたければそちらも見てみてください。
29436 @c COMMON
29437
29438
29439 @defun gauche-version
29440 @defunx gauche-architecture
29441 @defunx gauche-library-directory
29442 @defunx gauche-architecture-directory
29443 @defunx gauche-site-library-directory
29444 @defunx gauche-site-architecture-directory
29445 @c EN
29446 These functions returns a string that tells information about Gauche
29447 runtime itself.
29448 @c JP
29449 これらの手続きはGaucheランタイムの情報を文字列で返します。
29450 @c COMMON
29451 @end defun
29452
29453 @defun version-alist
29454 [SRFI-176]
29455 @c EN
29456 Returns an alist of various runtime information.
29457 The information is the same as what displayed with @code{gosh -V}.
29458 @c JP
29459 様々なランタイムの情報をalistで返します。
29460 @code{gosh -V}で表示される情報と同じです。
29461 @c COMMON
29462
29463 @c EN
29464 The result is affected by the value of the environemnt variable
29465 @code{GAUCHE_VERSION_INFO_EXCLUSION}. @xref{Environment variables},
29466 for details.
29467 @c JP
29468 結果は環境変数@code{GAUCHE_VERSION_INFO_EXCLUSION}に影響を受けます。
29469 詳しくは@ref{Environment variables}を参照してください。
29470 @c COMMON
29471 @end defun
29472
29473 @defun sys-available-processors
29474 @c EN
29475 Returns the number of available processors on the running platform.
29476 Return value is always a positive exact integer. If Gauche can't
29477 get the information, 1 is returned.
29478
29479 However,
29480 If an environment variable @code{GAUCHE_AVAILABLE_PROCESSORS} is
29481 defined and its value can be interpreted as a positive integer,
29482 then the value is returned regardless of what the hardware/OS tells.
29483 @c JP
29484 現在Gaucheが走っているプラットフォームで使えるプロセッサの個数を返します。
29485 戻り値は常に正の正確な整数です。Gaucheがこの情報を入手できなかった場合は
29486 1が返ります。
29487
29488 但し、もし環境変数@code{GAUCHE_AVAILABLE_PROCESSORS}が定義されていて、
29489 その値が正の整数と解釈できるものだった場合、ハードウェア/OSがどう言おうと
29490 環境変数の値が返されます。
29491 @c COMMON
29492 @end defun
29493
29494 @node Filesystems, Unix groups and users, Environment inquiry, System interface
29495 @subsection Filesystems
29496 @c NODE ファイルシステム
29497
29498 @c EN
29499 System calls that deal with filesystems.
29500 See also @ref{Filesystem utilities}, which defines high-level APIs
29501 on top of the procedures described here.
29502 @c JP
29503 ファイルシステムに関するシステムコール群です。
29504 ここで述べる手続きの上に、より高レベルなAPIがモジュール@code{file.util}として
29505 実装されています。@ref{Filesystem utilities}を参照して下さい。
29506 @c COMMON
29507
29508 @menu
29509 * Directories::
29510 * Directory manipulation::
29511 * Pathnames::
29512 * File stats::
29513 * Other file operations::
29514 @end menu
29515
29516 @node Directories, Directory manipulation, Filesystems, Filesystems
29517 @subsubsection Directories
29518 @c NODE ディレクトリ
29519
29520 @c EN
29521 See also @ref{Directory utilities} for high-level API.
29522 @c JP
29523 高レベルAPIに関しては@ref{Directory utilities}も参照して下さい。
29524 @c COMMON
29525
29526 @defun sys-readdir path
29527 @c EN
29528 @var{path} must be a string that denotes valid pathname of an existing
29529 directory. This function returns a list of strings of the directory
29530 entries. The returned list is not sorted. An error is signaled
29531 if @var{path} doesn't exists or is not a directory.
29532 @c JP
29533 @var{path}は存在するディレクトリを示すパス名でなければなりません。
29534 この手続きはディレクトリの全エントリを文字列のリストとして返します。
29535 リストはソートされません。@var{path}が存在しなかったり、ディレクトリでなかった場合は
29536 エラーとなります。
29537 @c COMMON
29538 @end defun
29539
29540 @defun glob pattern :key separator folder sorter
29541 @defunx sys-glob pattern :key separator folder sorter
29542 @c EN
29543 Provides a traditional Unix glob(3) functionality;
29544 returns a list of pathnames that matches the given @var{pattern}.
29545 @c JP
29546 伝統的なUnixのglob(3)の機能を提供します。この手続きは@var{pattern}とマッ
29547 チするパス名のリストを返します。
29548 @c COMMON
29549
29550 @c EN
29551 This feature used to be a wrapper of system-provided @code{glob} function,
29552 hence it was named @code{sys-glob}. However, as of Gauche version 0.8.12,
29553 it was reimplemented in Scheme on top of other system calls, to overcome
29554 incompatibilities between platforms and for the opportunity to put
29555 more functionalities. So we renamed it @code{glob}.
29556 The old name @code{sys-glob} is kept for compatibility, but new
29557 programs should use @code{glob}.
29558 @c JP
29559 この機能は、かつてはプラットフォームが提供する@code{glob}関数をラップする
29560 もので、@code{sys-glob}という名前でした。しかし、プラットフォーム間の非互
29561 換性を解消し機能の追加を容易にするために、Gauche 0.8.12以降、システムコー
29562 ルの上にSchemeで再実装されています。そのため、@code{glob}と改名してあ
29563 ります。古い方の名前@code{sys-glob}は互換性のために残してありますが、
29564 新たにプログラムを書くときは@code{glob}を使ってください。
29565 @c COMMON
29566
29567 @c EN
29568 The @var{pattern} argument may be a single @emph{glob pattern}, or
29569 a list of glob patterns. If a list is given, pathnames that matches
29570 any one of the pattern are returned. If you're a unix user,
29571 you already know how it works.
29572 @c JP
29573 引数@var{pattern}は単一の@emph{グロブパターン}もしくは、グ
29574 ロブパターンのリストです。リストが渡されたときには、
29575 最低1つのパターンにマッチするパス名がすべて返されます。
29576 Unixのユーザならglobの動作は馴染み深いものでしょう。
29577 @c COMMON
29578
29579 @example
29580 gosh> (glob "*.scm")
29581 ("ext.scm" "test.scm")
29582 gosh> (glob "src/*.[ch]")
29583 ("src/ext.c" "src/ext.h")
29584 gosh> (glob '("*.scm" "src/*.c"))
29585 ("ext.scm" "src/ext.c" "test.scm")
29586 @end example
29587
29588 @c EN
29589 Unlike shell's glob, if there's no matching pathnames, @code{()} is returned.
29590 @c JP
29591 シェルのグロブとはちがって、マッチするパス名がないときは、@code{()}が返ります。
29592 @c COMMON
29593
29594 @c EN
29595 By default, the result is sorted using built-in @code{sort} procedure
29596 (@pxref{Sorting and merging}). You can pass alternative procedure
29597 to @var{sorter} argument; it should be a procedure that takes single
29598 list, and returns a sorted list. It can also be @code{#f}, in which
29599 case the result isn't sorted at all.
29600 @c JP
29601 デフォルトでは、結果は組み込みの@code{sort}手続きによりソートされて返されます
29602 (@ref{Sorting and merging}参照)。@var{sorter}キーワード引数で
29603 代わりのソート手続きを指定できます。@var{sorter}手続きはひとつのリストを受け取り、
29604 それをソートして返します。また、@var{sorter}引数に@code{#f}を渡すと、
29605 結果はソートされずに返されます。
29606 @c COMMON
29607
29608 @c EN
29609 In fact, globbing is a very useful tool to search hierarchical
29610 data structure in general, not limited to the filesystems.
29611 So the @code{glob} function is implemented separately from
29612 the filesystem. Using keyword arguments,
29613 you can glob from any kind of tree data structure.
29614 It is just that their default values are set to look at
29615 the filesystems.
29616 @c JP
29617 グロブはファイルシステムに限らず階層的なデータ構造を検索するのに非常に便利なツールです。
29618 したがって、@code{glob}関数はファイルシステムからは切り離して実装されています。
29619 キーワード引数を使うことで、どのようなツリー状のデータ構造からでもグロブできます。
29620 デフォルト値がファイルシステム用に設定されているにすぎません。
29621 @c COMMON
29622
29623 @c EN
29624 The @var{separator} argument should be a char-set, and used
29625 to split the @var{pattern} into components. Its default is
29626 @code{#[/]}. It is not used to the actual pathnames to match.
29627 @c JP
29628 引数@var{separator}は文字の集合を与えます。これを使って@var{pattern}を
29629 コンポーネントに分割します。デフォルトは@code{#[/]}です。実際のパス名
29630 をマッチさせるのには使われません。
29631 @c COMMON
29632
29633 @c EN
29634 The @var{folder} is a procedure that walks through the data
29635 structure. It is called with five arguments:
29636 @c JP
29637 @var{folder}はデータ構造をトラバースするための手続きです。この手続きは
29638 引数を5つとります。
29639 @c COMMON
29640
29641 @example
29642 (folder @var{proc} @var{seed} @var{parent} @var{regexp} @var{non-leaf?})
29643 @end example
29644
29645 @c EN
29646 @var{proc} is a procedure that takes two arguments. The @var{folder}
29647 should call @var{proc} with every node in the @var{parent} whose
29648 component name matches @var{regexp}, passing around the seed value
29649 just like @code{fold}. It should return the final value returned
29650 by @var{proc}. For example, if @code{cons} is given to @var{proc}
29651 and @code{()} is given to @var{seed}, the return value of the folder
29652 is a list of nodes that matches the @var{regexp}.
29653 @c JP
29654 @var{proc}は引数を2つ取る手続きです。@var{folder}は、@var{parent}内で
29655 コンポーネントとなる名前が@var{regexp}とマッチする各ノードと、
29656 @code{fold}と同様に順に渡されるシード値とで、@var{proc}を呼びます。
29657 @var{folder}は@var{proc}が最後に返した値を返します。たとえば、
29658 @code{cons}が@var{proc}として、@code{()}が@var{seed}として渡されれば、
29659 folder手続きが返す値は@var{regexp}とマッチするノードのリストになります。
29660 @c COMMON
29661
29662 @c EN
29663 The representation of a node is up to the implementation of
29664 @var{folder}. It can be a
29665 pathname, or some sort of objects, or anything. The @code{glob}
29666 procedure does not care what it is; the @code{glob} procedure
29667 merely passes the node to subsequent call to @code{folder} as
29668 @var{parent} argument, or returns a list of nodes as the result.
29669 @c JP
29670 ノードの表現がどうなるかは@var{folder}の実装によります。
29671 パス名であったり、オブジェクトであったりするかもしれません。
29672 @code{glob}手続きはノードの表現については感知しません。
29673 @code{glob}手続きがやることはノードを次に呼ぶ
29674 @code{folder}に@var{parent}引数として渡して、
29675 その結果のノードリストを返すだけです。
29676 @c COMMON
29677
29678 @c EN
29679 The @var{parent} argument is basically a node, and
29680 @var{folder} traverses its children to find the match.
29681 The exception is the initial call of @var{folder}---
29682 at the beginning @code{glob} knows nothing about each node.
29683 When @code{glob} needs to match an absolute path, it
29684 passes @code{#t}, and when @code{glob} needs to match a relative path,
29685 it passes @code{#f}, as the initial @var{parent} value.
29686 @c JP
29687 @var{parent}引数は基本的にはノードで、@var{folder}はその子ノードを
29688 対象にマッチするものを探索します。
29689 例外は最初に@var{folder}が呼ばれる時です。その時点では@code{glob}は
29690 ノードについて何も知らないので、
29691 絶対パスでマッチをかける場合は@code{#t}を、
29692 相対パスでマッチをかける場合は@code{#f}を最初の@var{parent}の値として渡します。
29693 @c COMMON
29694
29695 @c EN
29696 The @var{regexp} argument is used to filter the child nodes.
29697 It should be matched against the component name of the child,
29698 not including its directory names. As a special case, it can
29699 be a symbol @code{dir?}; if that's the case, the folder should
29700 return @var{node} itself, but it may indicate @var{node}
29701 @emph{as a directory}; e.g. if @var{node} is represented as a pathname,
29702 the folder returns a pathname with trailing directory separator.
29703 As special cases,
29704 if @var{node} is a boolean value and @var{regexp} is @code{dir?},
29705 the folder should return the node representing root node or
29706 current node, respectively; e.g. if @var{node} is represented
29707 as a pathname, the folder may return @code{"/"} and @code{"./"}
29708 for those cases.
29709 @c JP
29710 @var{regexp}引数は子ノードをフィルターするのに使い、ディレクトリ名を含
29711 まない、子のコンポーネントである名前に対して照合されるものです。特別な
29712 場合として、シンボル@code{dir?}にすることができます。この場合は、folder
29713 は@var{node}そのものを返し、@var{node}は@emph{ディレクトリ}と見なされ
29714 ます。すなわち、@var{node}がパス名を表わす場合には、folderはディレクト
29715 リ区切り子が最後に付いたパス名を返します。
29716 特別な場合として、@var{node}がブール値でかつ
29717 @var{regexp}が@code{dir?}である場合、folderはルートノードをあらわすノー
29718 ドあるいはカレントノードを返すことになっています。すなわち、@var{node}
29719 はパス名を表す場合、folderは@code{"/"}または@code{"./"}を返します。
29720 @c COMMON
29721
29722 @c EN
29723 The @var{non-leaf} argument is a boolean flag. If it is true,
29724 the filter should omit the leaf nodes from the result (e.g. only
29725 include the directories).
29726 @c JP
29727 @var{non-leaf}引数はブール値フラッグです。真なら、フィルタは結果からリー
29728 フノードをのぞきます(すなわち、ディレクトリだけが含まれるようになり
29729 ます)。
29730 @c COMMON
29731
29732 @c EN
29733 Now, here's the precise spec of glob pattern matching.
29734 @c JP
29735 ここからはグロブパターンマッチングの細かい仕様をみていきます。
29736 @c COMMON
29737
29738 @c EN
29739 Each glob pattern is a string to match pathname-like strings.
29740 @c JP
29741 各グロブパターンはパス名様式文字列にマッチする文字列です。
29742 @c COMMON
29743
29744 @c EN
29745 A pathname-like string is a string consists of one or more
29746 @emph{components}, separated by @emph{separator}s.
29747 The default separator is @code{#[/]}; you can change it
29748 with @var{separator} keyword argument.
29749 A component cannot contain separators, and cannot
29750 be a null string. Consecutive separators are
29751 regarded as a single separator. A pathname-like
29752 string optionally begins with, and/or ends with a separator character.
29753 @c JP
29754 パス名様式文字列は1つ以上の@emph{セパレータ}で区切られた
29755 @emph{コンポーネント}から構成される文字列です。
29756 デフォルトのセパレータは@code{#[/]}です。キーワード引数@var{separator}
29757 を使うとこれを変更できます。コンポーネントにはセパレータを含められませ
29758 ん。また空文字列にすることもできません。連続したセパレータは単一のセパ
29759 レータとみなされます。パス名様式の文字列は状況に応じてセパレータから始
29760 めたり、セパレータで終端したりできます(両方をやるのも可)。
29761 @c COMMON
29762
29763 @c EN
29764 A glob pattern also consists of components and separator
29765 characters. In a component, following characters/syntax have special
29766 meanings.
29767 @c JP
29768 グロブパターンもコンポーネントとセパレータ文字から構成されます。コンポー
29769 ネントにおいては、以下の文字、構文は特別な意味を持ちます。
29770 @c COMMON
29771
29772 @table @code
29773 @item *
29774 @c EN
29775 When it appears at the beginning of a component, it matches
29776 zero or more characters except a period (@code{.}). And it
29777 won't match if the component of the input string begins with
29778 a period.
29779
29780 Otherwise, it matches zero or more sequence of any characters.
29781 @c JP
29782 これがコンポーネントの先頭に表われた場合、0個以上のピリオド(@code{.})
29783 を除く文字にマッチします。入力文字列のコンポーネントがピリオドではじま
29784 るような文字列の場合にはマッチしません。
29785
29786 先頭以外の場所では、0個以上の文字の列にマッチします。
29787 @c COMMON
29788
29789 @item **
29790 @c EN
29791 If a component is just @code{**}, it matches zero or more
29792 number of components that match @code{*}. For example, @code{src/**/*.h}
29793 matches all of the following patterns.
29794 @c JP
29795 コンポーネントが@code{**}だけの場合、これは@code{*}にマッチする0個以上の
29796 コンポーネントにマッチします。例えば@code{src/**/*.h}は
29797 次のようなパターン全てにマッチします。
29798 @c COMMON
29799 @example
29800 src/*.h
29801 src/*/*.h
29802 src/*/*/*.h
29803 src/*/*/*/*.h
29804 ...
29805 @end example
29806
29807 @item ?
29808 @c EN
29809 When it appears at the beginning of a component, it matches
29810 a character except a period (@code{.}). Otherwise, it matches
29811 any single character.
29812 @c JP
29813 コンポーネントの先頭にあらわれた場合、ピリオド(@code{.})以外の一文字に
29814 マッチします。先頭以外の場所では任意の一文字にマッチします。
29815 @c COMMON
29816
29817 @item [@i{chars}]
29818 @c EN
29819 Specifies a character set. Matches any one of the set.
29820 The syntax of @i{chars} is the same as Gauche's character set
29821 syntax (@pxref{Character sets}). For the compatibility of the
29822 traditional glob, the @code{!} character can be used to complement
29823 the character set, e.g. @code{[!abc]} is the same as @code{[^abc]}.
29824 @c JP
29825 文字の集合を指定します。その集合に含まれる文字のどれかにマッチします。
29826 @i{chars}の構文はGaucheの文字集合を表す構文と同じです
29827 (@ref{Character sets}参照)。伝統的なグロブとの互換性のために、@code{!}
29828 文字をつかって、補集合で文字集合を表わすこともできるようになっています。
29829 すなわち、@code{[!abc]}は@code{[^abc]}と同じです。
29830 @c COMMON
29831
29832 @item \
29833 @c EN
29834 Include the next character literally in the pattern. This can be used
29835 to include above special characters in the pattern.
29836 @c JP
29837 次の文字をそのままパターンに含めます。上の特殊文字をそのままパターンに入れたい
29838 時に使えます。
29839 @c COMMON
29840 @end table
29841 @end defun
29842
29843 @defun glob-fold pattern proc seed :key separator folder sorter
29844 @c EN
29845 This is actually a low-level construct of the glob function.
29846 Actually, @var{glob} is simply written like this:
29847 @c JP
29848 これはグロブ関数の低レベル版です。実際@var{glob}は以下のように書いたの
29849 と同じです。
29850 @c COMMON
29851 @example
29852 (define (glob patterns . opts)
29853 (apply glob-fold patterns cons '() opts))
29854 @end example
29855
29856 @c EN
29857 The meaning of @var{pattern}, @var{separator}, @var{folder} and
29858 @var{sorter}
29859 is the same as explained above.
29860 @c JP
29861 @var{pattern}、@var{separator}、@var{folder}および@var{sorter}の意味を前述のものと同
29862 じです。
29863 @c COMMON
29864
29865 @c EN
29866 For each pathname that matches @var{pattern}, @code{glob-fold}
29867 calls @var{proc} with the pathname and a seed value. The initial
29868 seed value is @var{seed}, and the value @var{proc} returns becomes
29869 the next seed value. The result of the last call to @var{proc}
29870 becomes the result of @code{glob-fold}. If there's no matching
29871 pathnames, @var{proc} is never called and @var{seed} is returned.
29872 @c JP
29873 @var{pattern}にパス名ごとに@code{glob-fold}は@var{proc}をパス名とシー
29874 ド値で呼びます。最初のシード値は@var{seed}で、@var{proc}が返す値は次の
29875 シード値になります。最後の@var{proc}の呼び出し結果は@code{glob-fold}の
29876 結果となります。マッチするパス名が存在しないときは、@var{proc}は呼ばれ
29877 ずに、@var{seed}が返ります。
29878 @c COMMON
29879 @end defun
29880
29881 @defun make-glob-fs-fold :key root-path current-path
29882 @c EN
29883 This is a utility function to generate a procedure suitable to
29884 pass the @var{folder} keyword argument of @code{glob-fold} and @code{glob}.
29885 Without arguments, this returns the same procedure which is used
29886 in @code{glob-fold} and @code{glob} by default.
29887 @c JP
29888 これは@code{glob-fold}や@code{glob}の@var{folder}キーワード引数に
29889 渡せる形の手続きを作るユーティリティ手続きです。
29890 引数を渡さなければ、@code{glob-fold}や@code{glob}がデフォルトで使うのと
29891 同じ手続きが返ります。
29892 @c COMMON
29893
29894 @c EN
29895 The keyword arguments @var{root-path} and @var{current-path} specify
29896 the paths where @code{glob-fold} starts to search.
29897 @c JP
29898 キーワード引数@var{root-path}および@var{current-path}はそれぞれ、
29899 @code{glob-fold}が探索を開始するディレクトリを指定します。
29900 @c COMMON
29901
29902 @example
29903 gosh> (glob "/tmp/*.scm")
29904 ("/tmp/x.scm" "/tmp/y.scm")
29905 gosh> (glob "/*.scm"
29906 :folder (make-glob-fs-fold :root-path "/tmp"))
29907 ("/tmp/x.scm" "/tmp/y.scm")
29908 gosh> (glob "*.scm"
29909 :folder (make-glob-fs-fold :current-path "/tmp"))
29910 ("/tmp/x.scm" "/tmp/y.scm")
29911 @end example
29912 @end defun
29913
29914 @c EN
29915 @xref{File stats}, to check if a path is actually a directory.
29916 @c JP
29917 パスがディレクトリかどうかチェックする方法は、@ref{File stats}を参照してください。
29918 @c COMMON
29919
29920 @node Directory manipulation, Pathnames, Directories, Filesystems
29921 @subsubsection Directory manipulation
29922 @c NODE ディレクトリ操作
29923
29924 @defun sys-remove filename
29925 [POSIX]
29926 @c EN
29927 If @var{filename} is a file it is removed.
29928 On some systems this may also work on an empty directory,
29929 but portable scripts shouldn't depend on it.
29930 @c JP
29931 @var{filename}がファイルであればそれを消去します。
29932 システムによっては@var{filename}が空のディレクトリであっても動作しますが、
29933 移植性を気にする場合はその動作に依存しない方が良いでしょう。
29934 @c COMMON
29935 @end defun
29936
29937 @defun sys-rename old new
29938 [POSIX]
29939 @c EN
29940 Renames a file @var{old} to @var{new}. The new name
29941 can be in different directory from the old name, but both paths
29942 must be on the same device.
29943 @c JP
29944 ファイル@var{old}を@var{new}にリネームします。新しい名前は
29945 古い名前と異なるディレクトリにあってもかまいませんが、両者は同じデバイス上に
29946 なければなりません。
29947 @c COMMON
29948 @end defun
29949
29950 @defun sys-tmpnam
29951 [POSIX]
29952 @c EN
29953 Creates a file name which is supposedly unique, and returns it.
29954 This is in POSIX, but its use is discouraged because of potential
29955 security risk. Use @code{sys-mkstemp} below if possible.
29956 @c JP
29957 ユニークなファイル名を作成して返します。この関数はPOSIXに含まれていますが、
29958 セキュリティ上の問題が指摘されており、使わない方が良いとされています。
29959 可能なら下にあげる@code{sys-mkstemp}を使って下さい。
29960 @c COMMON
29961 @end defun
29962
29963 @defun sys-mkstemp template
29964 @c EN
29965 Creates and opens a file that has unique name, and returns two values;
29966 opened port and the created filename. The file is created exclusively,
29967 avoiding race conditions. @var{template} is used as the prefix
29968 of the file. Unlike Unix's mkstemp, you don't need padding characters.
29969 The file is opened for writing, and its permission is set to 600.
29970 @c JP
29971 ユニークな名前を持つファイルを作成してオープンし、オープンされたポートとファイル名の
29972 二つの値を返します。ファイルは排他的に作成されるため、レースコンディションは起こりません。
29973 @var{template}はファイル名のプレフィックスに使われます。Unixのmkstempと違って、
29974 パディングキャラクタをつける必要はありません。ファイルは書き込み用としてオープンされ、
29975 パーミッションは600にセットされます。
29976 @c COMMON
29977 @end defun
29978
29979 @defun sys-mkdtemp template
29980 @c EN
29981 Creates a directory that has unique name, and returns the name.
29982 @var{template} is used as the prefix of the directory. Unlike Unix's
29983 mkdtemp, you don't need padding characters. The directory's
29984 permission is set to 700.
29985 @c JP
29986 ユニークな名前を持つディレクトリを作成し、その名前を返します。
29987 @var{template}はディレクトリ名のプレフィックスに使われます。
29988 Unixのmkdtempと違って、パディングキャラクタをつける必要はありません。
29989 ディレクトリのパーミッションは700にセットされます。
29990 @c COMMON
29991 @end defun
29992
29993 @defun sys-link existing new
29994 [POSIX]
29995 @c EN
29996 Creates a hard link named @var{new} to the existing file @var{existing}.
29997 @c JP
29998 既存のファイル@var{existing}に対し、@var{new}という名のハードリンクを作成します。
29999 @c COMMON
30000 @end defun
30001
30002 @defun sys-unlink pathname
30003 [POSIX]
30004 @c EN
30005 Removes @var{pathname}. It can't be a directory.
30006 Returns @code{#t} if it is successfully removed, or
30007 @code{#f} if @var{pathname} doesn't exist.
30008 An error is signaled otherwise.
30009 @c JP
30010 @var{pathname}で示されるファイルを消去します。
30011 @var{pathname}はディレクトリであってはなりません。
30012 もし消去に成功したら@code{#t}が、@var{pathname}が存在しなければ@code{#f}が返されます。
30013 他の場合はエラーが通知されます。
30014 @c COMMON
30015
30016 @c EN
30017 There are similar procedures, @code{delete-file}/@code{remove-file}
30018 in @code{file.util} module, while they raises an error when the
30019 named pathname doesn't exist (@pxref{File operations}).
30020 @c JP
30021 @code{file.util}モジュールに似た手続き@code{delete-file}/@code{remove-file}が
30022 ありますが、そちらはファイルが存在しない場合にエラーを投げます
30023 (@ref{File operations}参照)。
30024 @c COMMON
30025
30026 @c EN
30027 R7RS defines @code{delete-file}, which you may want to use in portable
30028 programs.
30029 @c JP
30030 R7RSは@code{delete-file}を定義しています。ポータブルなプログラムでは
30031 そちらを使うのが良いでしょう。
30032 @c COMMON
30033 @end defun
30034
30035 @defun sys-symlink existing new
30036 @c EN
30037 Creates a symbolic link named @var{new} to the pathname @var{existing}.
30038 On systems that doesn't support symbolic links,
30039 this function is unbound.
30040 @c JP
30041 @var{existing}を指す@var{new}という名のシンボリックを作成します。
30042 シンボリックリンクをサポートしないシステムでは、この手続きは定義されません。
30043 @c COMMON
30044 @end defun
30045
30046 @defun sys-readlink path
30047 @c EN
30048 If a file specified by @var{path} is a symbolic link, its content is
30049 returned. If @var{path} doesn't exist or is not a symbolic link, an
30050 error is signaled.
30051 On systems that don't support symbolic links,
30052 this function is unbound.
30053 @c JP
30054 @var{path}で示されるファイルがシンボリックリンクならば、それが指すパスを返します。
30055 もし@var{path}が存在しなかったり、シンボリックリンクでなければ、エラーが通知されます。
30056 シンボリックリンクをサポートしないシステムでは、この手続きは定義されません。
30057 @c COMMON
30058 @end defun
30059
30060 @defun sys-mkdir pathname mode
30061 [POSIX]
30062 @c EN
30063 Makes a directory @var{pathname} with mode @var{mode}.
30064 (Note that @var{mode} is masked by the current umask;
30065 see @code{sys-umask} below).
30066 The parent directory of @var{pathname} must exist and be writable
30067 by the process. To create intermediate directories at once, use
30068 @code{make-directory*} in @code{file.util} (@ref{Directory utilities}).
30069 @c JP
30070 ディレクトリ@var{pathname}をモード@var{mode}で作成します。
30071 (@var{mode}はさらにumaskでマスクされることに注意して下さい;下の@code{sys-umask}
30072 参照)。
30073 @var{pathname}の親ディレクトリは存在して、プロセスが書き込めるようになっていなければ
30074 なりません。中間のディレクトリも一度に作成するには、
30075 @code{file.util}の@code{make-directory*}が使えます
30076 (@ref{Directory utilities})。
30077 @c COMMON
30078 @end defun
30079
30080 @defun sys-rmdir pathname
30081 [POSIX]
30082 @c EN
30083 Removes a directory @var{pathname}. The directory must be empty.
30084 To remove a directory with its contents, use @code{remove-directory*}
30085 in @code{file.util} (@ref{Directory utilities}).
30086 @c JP
30087 ディレクトリ@var{pathname}を消去します。ディレクトリは空でなければなりません。
30088 ディレクトリの内容も一緒に消去するには、@code{file.util}の@code{remove-directory*}
30089 が使えます(@ref{Directory utilities})。
30090 @c COMMON
30091 @end defun
30092
30093 @defun sys-umask :optional mode
30094 [POSIX]
30095 @c EN
30096 Sets umask setting to @var{mode}. Returns previous umask setting.
30097 If @var{mode} is omitted or @code{#f}, just returns the current umask without
30098 changing it.
30099 See @code{man umask} for more details.
30100 @c JP
30101 umaskを@var{mode}にセットします。変更される前のumaskを返します。
30102 @var{mode}が省略されるか@code{#f}が渡された場合、
30103 現在のumaskを変更せずにその値を返します。
30104 umaskについては@code{man umask}を参照してください。
30105 @c COMMON
30106 @end defun
30107
30108 @node Pathnames, File stats, Directory manipulation, Filesystems
30109 @subsubsection Pathnames
30110 @c NODE パス名
30111
30112 @c EN
30113 See also @ref{Pathname utilities}, for high-level APIs.
30114 @c JP
30115 高レベルのAPIに関しては@ref{Pathname utilities}も参照して下さい。
30116 @c COMMON
30117
30118 @defun sys-normalize-pathname pathname :key absolute expand canonicalize
30119 @c EN
30120 Converts @var{pathname} according to the way specified by keyword arguments.
30121 More than one keyword argument can be specified.
30122 @c JP
30123 与えられたキーワード引数によって@var{pathname}を以下のように変換します。
30124 キーワード引数は同時に複数指定できます。
30125 @c COMMON
30126 @table @code
30127 @item absolute
30128 @c EN
30129 If this keyword argument is given and true, and @var{pathname} is not
30130 an absolute pathname, it is converted to an absolute pathname by
30131 appending the current working directory in front of @var{pathname}.
30132 @c JP
30133 このキーワード引数に真の値が与えられて、@var{pathname}が絶対パスでない場合、
30134 @var{pathname}の前にプロセスのワーキングディレクトリを足して絶対パスにします。
30135 @c COMMON
30136 @item expand
30137 @c EN
30138 If this keyword argument is given and true, and @var{pathname} begins
30139 with `@code{~}', it is expanded as follows:
30140 @c JP
30141 このキーワード引数に真の値が与えられて、@var{pathname}が`@code{~}' で始まっていた
30142 場合、以下のように展開されます。
30143 @c COMMON
30144 @itemize @bullet
30145 @item
30146 @c EN
30147 If @var{pathname} is consisted entirely by ``@code{~}'', or begins
30148 with ``@code{~/}'', then the character ``@code{~}'' is replaced
30149 for the pathname of the current user's home directory.
30150 @c JP
30151 @var{pathname}が``@code{~}''のみであるか、または``@code{~/}''で始まっている
30152 場合、文字``@code{~}''が現在のプロセスのユーザのホームディレクトリに置き換えられます。
30153 @c COMMON
30154 @item
30155 @c EN
30156 Otherwise, characters following `@code{~}' until either `@code{/}' or
30157 the end of @var{pathname} are taken as a user name, and the user's
30158 home directory is replaced in place of it. If there's no such
30159 user, an error is signaled.
30160 @c JP
30161 上記以外の場合、`@code{~}'以降、`@code{/}'か@var{pathname}の終端までの文字列
30162 がユーザ名とみなされ、そのユーザのホームディレクトリに置換されます。もし該当するユーザが
30163 いなければエラーとなります。
30164 @c COMMON
30165 @end itemize
30166 @item canonicalize
30167 @c EN
30168 Tries to remove pathname components ``@code{.}'' and ``@code{..}''.
30169 The pathname interpretation is done purely in textural level, i.e.
30170 it doesn't access filesystem to see the conversion reflects the
30171 real files. It may be a problem if there's a symbolic links to
30172 other directory in the path.
30173 @c JP
30174 パス名から ``@code{.}'' や ``@code{..}'' を除き、単純化します。
30175 この操作は実際のファイルシステムを参照せずに行われます。元のパス名がディレクトリへの
30176 シンボリックリンクを含んでいた場合、単純化されたパス名は正しくないかもしれません。
30177 @c COMMON
30178 @end table
30179 @end defun
30180
30181 @defun sys-basename pathname
30182 @defunx sys-dirname pathname
30183 @c EN
30184 @code{sys-basename} returns a basename, that is the last component of
30185 @var{pathname}. @code{sys-dirname} returns the components of @var{pathname}
30186 but the last one. If @var{pathname} has a trailing `@code{/}',
30187 it is simply ignored.
30188 @c JP
30189 @code{sys-basename}は与えられたパスのベース名、すなわち最後のコンポーネントを返します。
30190 @code{sys-dirname}は与えられたパスのディレクトリ名、すなわち最後のコンポーネント以外の
30191 コンポーネントを返します。@var{pathname}の末尾が`@code{/}'である場合、その文字は
30192 無視されます。
30193 @c COMMON
30194 @example
30195 (sys-basename "foo/bar/bar.z") @result{} "bar.z"
30196 (sys-basename "coo.scm") @result{} "coo.scm"
30197 (sys-basename "x/y/") @result{} "y"
30198 (sys-dirname "foo/bar/bar.z") @result{} "foo/bar"
30199 (sys-dirname "coo.scm") @result{} "."
30200 (sys-dirname "x/y/") @result{} "x"
30201 @end example
30202 @c EN
30203 These functions doesn't check if @var{pathname} really exists.
30204 @c JP
30205 この手続きは@var{pathname}が存在するかどうかはチェックしません。
30206 @c COMMON
30207
30208 @c EN
30209 Some boundary cases:
30210 @c JP
30211 特殊なケース:
30212 @c COMMON
30213 @example
30214 (sys-basename "") @result{} ""
30215 (sys-dirname "") @result{} "."
30216
30217 (sys-basename "/") @result{} ""
30218 (sys-dirname "/") @result{} "/"
30219 @end example
30220 @c EN
30221 Note: The above behavior is the same as Perl's @code{basename} and
30222 @code{dirname}. On some systems, the command @code{basename}
30223 may return @code{"/"} for the argument @code{"/"}, and
30224 @code{"."} for the argument @code{"."}.
30225 @c JP
30226 註:このふるまいはPerlの@code{basename}および@code{dirname}と同様です。
30227 システムによっては、コマンドの@code{basename}は@code{"/"}に対して@code{"/"}を、
30228 @code{"."}に対して@code{"."}を返すものがあります。
30229 @c COMMON
30230 @end defun
30231
30232 @defun sys-realpath pathname
30233 @c EN
30234 @code{sys-realpath} returns an absolute pathname of @var{pathname}
30235 that does not include ``@code{.}'', ``@code{..}'' or symbolic links.
30236 If @var{pathname} does not exist, it includes a dangling symbolic
30237 link, or the caller doesn't have enough permission to access to
30238 the path, an error is signaled.
30239 @c JP
30240 @code{sys-realpath}は``@code{.}'', ``@code{..}''およびシンボリックリン
30241 クを含まない@var{pathname}の絶対パスを返します。@var{pathname}自体が存在しなかったり、
30242 存在しないパスを指すシンボリックリンクが含まれていたり、関連するパスへのアクセス権限が
30243 不足している場合はエラーが通知されます。
30244 @c COMMON
30245
30246 @c EN
30247 Note: the POSIX @code{realpath(3)} function is known to be unsafe, so
30248 Gauche avoids using it and implements @code{sys-realpath} in its own.
30249 @c JP
30250 注:POSIXの@code{realpath(3)}は安全でない場合があるので、
30251 Gaucheは内部でCランタイムの@code{realpath}を呼ばずに、
30252 独自に@code{sys-realpath}の機能を実装しています。
30253 @c COMMON
30254 @end defun
30255
30256 @defun sys-tmpdir
30257 @c EN
30258 Returns the default directory name suitable to put temporary files.
30259
30260 On Unix-like systems, the environment variable @code{TMPDIR} and @code{TMP}
30261 are first checked, then falls back to @code{/tmp}.
30262
30263 On Windows-native systems, it uses @code{GetTempPath} Windows API.
30264 It checks environment variables @code{TMP}, @code{TEMP}, and
30265 @code{USERPROFILE} in this order, and falls back to Windows system
30266 directory.
30267
30268 On both platforms, the returned pathname may not exist, or
30269 may not be writable by the calling process.
30270
30271 In general, user programs and libraries are recommended to use
30272 @code{temporary-directory} (@pxref{Directory utilities}) instead;
30273 @code{sys-tmpdir} should be used only
30274 if you now the raw value the platform provides.
30275 @c JP
30276 一時ファイルを置くためのデフォルトのディレクトリ名を返します。
30277
30278 Unix系システムでは、環境変数@code{TMPDIR}と@code{TMP}がこの順でチェックされ、
30279 フォールバックとして@code{/tmp}が返されます。
30280
30281 Windowsネイティブの環境では、@code{GetTempPath} Windows APIを呼びます。
30282 これは環境変数@code{TMP}、@code{TEMP}、@code{USERPROFILE}を順に調べ、
30283 いずれも定義されていなければWindowsシステムディレクトリを返します。
30284
30285 いずれのプラットフォームでも、返されたパス名は存在しないかもしれず、
30286 また書き込み可能ではないかもしれないことに注意してください。
30287
30288 一般的に、ユーザプログラムやライブラリは@code{temporary-directory}
30289 (@ref{Directory utilities}参照) の方を利用するのが良いでしょう。
30290 @code{sys-tmpdir}はプラットフォームが推奨する生の値を知りたい場合に
30291 限り使ってください。
30292 @c COMMON
30293 @end defun
30294
30295 @node File stats, Other file operations, Pathnames, Filesystems
30296 @subsubsection File stats
30297 @c NODE ファイルの状態
30298
30299 @c EN
30300 See also @ref{File attribute utilities}, for high-level APIs.
30301 @c JP
30302 高レベルのAPIに関しては@ref{File attribute utilities}も参照して下さい。
30303 @c COMMON
30304
30305 @defun file-exists? path
30306 [R7RS file]
30307 @c EN
30308 Returns true if @var{path} exists.
30309 @c JP
30310 @var{path}が存在していれば@code{#t}を返します。
30311 @c COMMON
30312 @end defun
30313
30314 @defun file-is-regular? path
30315 @defunx file-is-directory? path
30316 @c EN
30317 Returns true if @var{path} is a regular file, or is a directory,
30318 respectively. They return false if @var{path} doesn't
30319 exist at all.
30320 @c JP
30321 それぞれ、@var{path}が存在するか、存在してそれがレギュラーファイルであるか、
30322 存在してそれがディレクトリであれば@code{#t}を返します。
30323 @c COMMON
30324 @end defun
30325
30326 @deftp {Builtin Class} <sys-stat>
30327 @clindex sys-stat
30328 @c EN
30329 An object that represents @code{struct stat}, attributes of an
30330 entry in the filesystem. It has the following read-only slots.
30331 @c JP
30332 ファイルシステム内のエントリの属性を表す、@code{struct stat}のラッパー
30333 オブジェクトです。以下に示す読みだし専用のスロットを持ちます。
30334 @c COMMON
30335
30336 @defivar <sys-stat> type
30337 @c EN
30338 A symbol represents the type of the file.
30339 @c JP
30340 ファイルのタイプを示すシンボルです。
30341 @c COMMON
30342 @c EN
30343 @multitable {aaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}
30344 @item @code{regular} @tab a regular file
30345 @item @code{directory} @tab a directory
30346 @item @code{character} @tab a character device
30347 @item @code{block} @tab a block device
30348 @item @code{fifo} @tab a fifo
30349 @item @code{symlink} @tab a symbolic link
30350 @item @code{socket} @tab a socket
30351 @end multitable
30352 @c JP
30353 @multitable {aaaaaaaaaaaaaaa} {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}
30354 @item @code{regular} @tab 通常のファイル
30355 @item @code{directory} @tab ディレクトリ
30356 @item @code{character} @tab キャラクタデバイス
30357 @item @code{block} @tab ブロックデバイス
30358 @item @code{fifo} @tab FIFO
30359 @item @code{symlink} @tab シンボリックリンク
30360 @item @code{socket} @tab ソケット
30361 @end multitable
30362 @c COMMON
30363 @c EN
30364 If the file type is none of the above, @code{#f} is returned.
30365 @c JP
30366 以上のどれにも当てはまらない場合は@code{#f}が返されます。
30367 @c COMMON
30368
30369 @c EN
30370 Note: Some operating systems don't have the @code{socket} file type
30371 and returns @code{fifo} for socket files. Portable programs should
30372 check both possibilities to see if the given file is a socket.
30373 @c JP
30374 注:いくつかのオペレーティングシステムでは@code{socket}ファイルタイプを
30375 @code{fifo}と区別せず、どちらに対しても@code{fifo}を返します。
30376 ポータブルなプログラムを書くときは注意して下さい。
30377 @c COMMON
30378 @end defivar
30379
30380 @defivar <sys-stat> perm
30381 @c EN
30382 An exact integer for permission bits of @code{struct stat}.
30383 It is the same as lower 9-bits of "mode" slot; provided for the convenience.
30384 @c JP
30385 パーミッションビットマスク。"mode"スロットの下位9ビットと同じですが、
30386 便利なので独立したスロットとして提供されます。
30387 @c COMMON
30388 @end defivar
30389
30390 @defivar <sys-stat> mode
30391 @defivarx <sys-stat> ino
30392 @defivarx <sys-stat> dev
30393 @defivarx <sys-stat> rdev
30394 @defivarx <sys-stat> nlink
30395 @defivarx <sys-stat> uid
30396 @defivarx <sys-stat> gid
30397 @defivarx <sys-stat> size
30398 @c EN
30399 An exact integer for those information of @code{struct stat}.
30400 @c JP
30401 @code{struct stat}の該当するフィールドの値。正確な整数です。
30402 @c COMMON
30403 @end defivar
30404
30405 @defivar <sys-stat> atime
30406 @defivarx <sys-stat> mtime
30407 @defivarx <sys-stat> ctime
30408 @c EN
30409 A number of seconds since Unix Epoch for those information of @code{struct stat}.
30410 @c JP
30411 @code{struct stat}の該当するフィールドの値を、Unix Epochからの秒数で。
30412 @c COMMON
30413 @end defivar
30414
30415 @defivar <sys-stat> atim
30416 @defivarx <sys-stat> mtim
30417 @defivarx <sys-stat> ctim
30418 @c EN
30419 Timestamps represented in @code{<time>} object (@pxref{Time}).
30420 If the system supports it, this allows up to nanosecond precision.
30421 @c JP
30422 @code{<time>}オブジェクトで表されたタイムスタンプ (@ref{Time}参照)。
30423 システムがサポートしていれば、ナノ秒単位のタイムスタンプを得ることができます。
30424 @c COMMON
30425 @end defivar
30426
30427 @end deftp
30428
30429 @defun sys-stat path
30430 @defunx sys-fstat port-or-fd
30431 [POSIX]
30432 @c EN
30433 Returns a @code{<sys-stat>} object of @var{path}, or
30434 the underlying file of @var{port-or-fd}, which
30435 may be a port or a positive exact integer file descriptor, respectively.
30436
30437 If @var{path} is a symbolic link, a stat of the file the link points
30438 to is returned from @code{sys-stat}.
30439
30440 If @var{port-or-fd} is not associated to a file, @code{sys-fstat} returns
30441 @code{#f}.
30442 @c JP
30443 与えられたパス名@var{path}、またはポートかファイルディスクリプタ
30444 @var{port-or-fd}で示されるファイルの情報を@code{<sys-stat>}オブジェクトで
30445 返します。
30446
30447 @code{sys-stat}は、@var{path}がシンボリックリンクであった場合は
30448 リンクの指す先のファイルに関する情報を返します。
30449
30450 @code{sys-fstat}は、@var{port-or-fd}がファイルに関係ないポートであった
30451 場合は@code{#f}を返します。
30452 @c COMMON
30453 @end defun
30454
30455 @defun sys-lstat path
30456 @c EN
30457 Like @code{sys-stat}, but it returns a stat of a symbolic link
30458 if @var{path} is a symbolic link.
30459 @c JP
30460 @code{sys-stat}と同じですが、@var{path}がシンボリックリンクであった
30461 場合はリンクそのものの情報を返します。
30462 @c COMMON
30463 @end defun
30464
30465 @example
30466 gosh> (describe (sys-stat "gauche.h"))
30467 #<<sys-stat> 0x815af70> is an instance of class <sys-stat>
30468 slots:
30469 type : regular
30470 perm : 420
30471 mode : 33188
30472 ino : 845140
30473 dev : 774
30474 rdev : 0
30475 nlink : 1
30476 uid : 400
30477 gid : 100
30478 size : 79549
30479 atime : 1020155914
30480 mtime : 1020152005
30481 ctime : 1020152005
30482 @end example
30483
30484 @defun sys-stat->mode stat
30485 @defunx sys-stat->ino stat
30486 @defunx sys-stat->dev stat
30487 @defunx sys-stat->rdev stat
30488 @defunx sys-stat->nlink stat
30489 @defunx sys-stat->size stat
30490 @defunx sys-stat->uid stat
30491 @defunx sys-stat->gid stat
30492 @defunx sys-stat->atime stat
30493 @defunx sys-stat->mtime stat
30494 @defunx sys-stat->ctime stat
30495 @defunx sys-stat->file-type stat
30496 @c DEPRECATED
30497 @c EN
30498 Use @code{slot-ref} to access information of @code{<sys-stat>} object.
30499 @c JP
30500 @code{<sys-stat>}オブジェクトの情報にアクセスするには@code{slot-ref}を
30501 使って下さい。
30502 @c COMMON
30503 @end defun
30504
30505 @defun sys-access pathname amode
30506 [POSIX]
30507 @c EN
30508 Returns a boolean value of indicating whether access of @var{pathname}
30509 is allowed in @var{amode}. This procedure signals an error
30510 if used in a suid/sgid program (see the note below).
30511 @var{amode} can be a combinations (logical or) of
30512 following predefined flags.
30513 @c JP
30514 @var{pathname}へのアクセスが
30515 @var{mode}に示されるモードで許可されているかどうかを示す真偽値を返します。
30516 この手続きは、suid/sgidプログラムで使われるとエラーとなります(下記註参照)。
30517 @var{mode}は以下に示す定数のコンビネーション(logical or)です。
30518 @c COMMON
30519 @table @code
30520 @item R_OK
30521 @vindex R_OK
30522 @c EN
30523 Checks whether @var{pathname} is readable by the current user.
30524 @c JP
30525 @var{pathname}をカレントユーザが読み出し可能かどうか
30526 @c COMMON
30527 @item W_OK
30528 @vindex W_OK
30529 @c EN
30530 Checks whether @var{pathname} is writable by the current user.
30531 @c JP
30532 @var{pathname}へカレントユーザが書き込み可能かどうか
30533 @c COMMON
30534 @item X_OK
30535 @vindex X_OK
30536 @c EN
30537 Checks whether @var{pathname} is executable (or searchable in case
30538 @var{pathname} is a directory) by the current user.
30539 @c JP
30540 @var{pathname}をカレントユーザが実行可能かどうか(@var{pathname}が
30541 ディレクトリの場合はサーチ可能かどうか)
30542 @c COMMON
30543 @item F_OK
30544 @vindex F_OK
30545 @c EN
30546 Checks whether @var{pathname} exists or not, regardless of
30547 the access permissions of @var{pathname}. (But you need to have
30548 access permissions of the directories containing @var{pathname}).
30549 @c JP
30550 @var{pathname}のパーミッションフラグにかかわらず、@var{pathname}が
30551 存在するかどうか (但し@var{pathname}があるディレクトリの読みだし許可は必要)。
30552 @c COMMON
30553 @end table
30554
30555 @c EN
30556 @emph{Note:} Access(2) is known to be a security hole if used
30557 in suid/sgid program to check the real user's privilege of
30558 accessing the file.
30559 @c JP
30560 @emph{註:} access(2)は、suid/sgidプログラム中で
30561 実ユーザの権限を確かめるために使われた場合、セキュリティホールと
30562 なります。
30563 @c COMMON
30564 @end defun
30565
30566 @defun sys-chmod path mode
30567 @defunx sys-fchmod port-or-fd mode
30568 @c EN
30569 Change the mode of the file named @var{path} or an opened
30570 file specified by @var{port-or-fd} to @var{mode}.
30571 @var{mode} must be a small positive integer whose lower 9 bits
30572 specifies POSIX style permission.
30573 @c JP
30574 名前@var{path}を持つ、もしくは@var{port-or-fd}で指定される
30575 ファイルのパーミッションビットを@var{mode}に変更します。
30576 @var{mode}は小さな正の正確な整数で、POSIXスタイルのパーミッションビットマスク
30577 でなければなりません。
30578 @c COMMON
30579 @end defun
30580
30581 @defun sys-chown path owner-id group-id
30582 @c EN
30583 Change the owner and/or group of the file named @var{path}
30584 to @var{owner-id} and @var{group-id} respectively.
30585 @var{owner-id} and @var{group-id} must be an exact integer.
30586 If either of them is -1, the corresponding ownership is not changed.
30587 @c JP
30588 ファイル@var{path}のオーナーとグループを@var{owner-id}と@var{group-id}
30589 で示されるものに変更します。@var{owner-id}と@var{group-id}は正確な整数で
30590 なければなりません。どちらかに-1が渡された場合は、対応する情報は変更されません。
30591 @c COMMON
30592 @end defun
30593
30594 @defun sys-utime path :optional atime mtime
30595 @c EN
30596 Change the file's access time and modification time to @var{atime}
30597 and @var{mtime}, respectively. The arguments can be either @code{#f}
30598 (indicating the current time), @code{#t} (do not change),
30599 a real numebr (number of seconds from Epoch),
30600 or @code{<time>} object (@xref{Time}).
30601
30602 See also @code{touch-file} (@pxref{File operations}).
30603 @c JP
30604 ファイルのアクセスタイムと変更タイムを@var{atime}と@var{mtime}が示す
30605 値にセットします。@var{atime}/@var{mtime}引数に許されるのは、
30606 @code{#f} (現在の時刻)、@code{#t} (変更なし)、
30607 実数 (Epochからの秒数)、あるいは@code{<time>}インスタンスです
30608 (@ref{Time}参照)。
30609
30610 @ref{File operations}の@code{touch-file}も参照して下さい。
30611 @c COMMON
30612 @end defun
30613
30614 @node Other file operations, , File stats, Filesystems
30615 @subsubsection Other file operations
30616 @c NODE 他のファイル操作
30617
30618 @defun sys-chdir dir
30619 [POSIX]
30620 @c EN
30621 An interface to @code{chdir(2)}.
30622 See also @code{current-directory} (@pxref{Directory utilities}).
30623 @c JP
30624 @code{chdir(2)}へのインタフェースです。
30625 @code{current-directory}(@ref{Directory utilities})も参照して下さい。
30626 @c COMMON
30627 @end defun
30628
30629 @defun sys-pipe :key (buffering :line)
30630 @c EN
30631 [POSIX] Creates a pipe, and returns two ports.
30632 The first returned port is an input port and the second is an output port.
30633 The data put to the output port can be read from the input port.
30634 @c JP
30635 [POSIX] パイプを作り、ポートを2つ返します。
30636 最初に返されるポートは入力ポートで、2番目に返されるポートは出力ポートです。
30637 出力ポートへ書き出したデータは、入力ポートから読み込めます。
30638 @c COMMON
30639
30640 @c EN
30641 @var{Buffering} can be @code{:full}, @code{:line} or @code{:none},
30642 and specifies the buffering mode of the ports opened on the pipe.
30643 @xref{File ports}, for details of the buffering mode.
30644 The default mode is sufficient for typical cases.
30645 @c JP
30646 @var{buffering}は@code{:full}、@code{:line}、@code{:none}のいずれかで、
30647 パイプ上に開かれたポートのバッファリングモードを指定します。
30648 バッファリングモードの詳細については、@ref{File ports}を参照して下さい。
30649 通常のケースでは、デフォルトのモードで間に合うでしょう。
30650 @c COMMON
30651
30652 @example
30653 (receive (in out) (sys-pipe)
30654 (display "abc\n" out)
30655 (flush out)
30656 (read-line in)) @result{} "abc"
30657 @end example
30658
30659 @c EN
30660 Note: the returned value is changed from version 0.3.15, in which
30661 @code{sys-pipe} returned a list of two ports.
30662 @c JP
30663 注意: 戻り値はバージョン0.3.15から変更されています。それまでは、
30664 @code{sys-pipe}は2つのポートのリストを返します。
30665 @c COMMON
30666 @end defun
30667
30668 @defun sys-mkfifo path mode
30669 @c EN
30670 [POSIX] creates a fifo (named pipe) with a name @var{path} and mode
30671 @var{mode}. @var{Mode} must be a positive exact integer to represent
30672 the file mode.
30673 @c JP
30674 [POSIX] 名前が@var{path}でモードが@var{mode}のFIFO(名前付きパイプ)を
30675 作ります。@var{mode}はファイルのモードを表す正の正確整数でなければ
30676 なりません。
30677 @c COMMON
30678 @end defun
30679
30680 @defun sys-isatty port-or-fd
30681 @c EN
30682 [POSIX] @var{port-or-fd} may be a port or an integer file descriptor.
30683 Returns @code{#t} if the port is connected to the console, @code{#f}
30684 otherwise.
30685 @c JP
30686 [POSIX] @var{port-or-fd}はポートか整数のファイルディスクリプタです。
30687 ポートがコンソールに接続されていれば@code{#t}を、そうでなければ@code{#f}を
30688 返します。
30689 @c COMMON
30690 @end defun
30691
30692 @defun sys-ttyname port-or-fd
30693 @c EN
30694 [POSIX] @var{port-or-fd} may be a port or an integer file descriptor.
30695 Returns the name of the terminal connected to the port,
30696 or @code{#f} if the port is not connected to a terminal.
30697 @c JP
30698 [POSIX] @var{port-or-fd}はポートか整数のファイルディスクリプタです。
30699 ポートに接続された端末の名前か、ポートが端末に接続されていなければ
30700 @code{#f}を返します。
30701 @c COMMON
30702 @end defun
30703
30704 @defun sys-truncate path length
30705 @defunx sys-ftruncate port-or-fd length
30706 [POSIX]
30707 @c EN
30708 Truncates a regular file named by @var{path} or referenced by @var{port-or-fd}
30709 to a size of @var{length} bytes.
30710 If the file is larger than @var{length} bytes, the extra data is discarded.
30711 If the file is smaller than that, zero is padded.
30712 @c JP
30713 @var{path}あるいは@var{port-or-fd}によって指定される通常ファイルの長さを
30714 @var{length}にします。
30715 ファイルが@var{length}より長かった場合、余分なデータは捨てられます。
30716 ファイルが@var{length}より短かった場合、残りの部分にはゼロが詰められます。
30717 @c COMMON
30718 @end defun
30719
30720 @node Unix groups and users, Locale, Filesystems, System interface
30721 @subsection Unix groups and users
30722 @c NODE Unixのグループとユーザ
30723
30724 @subsubheading Unix groups
30725
30726 @deftp {Builtin Class} <sys-group>
30727 @clindex sys-group
30728 @c EN
30729 Unix group information. Has following slots.
30730 @c JP
30731 Unixのグループの情報です。以下のスロットを持ちます。
30732 @c COMMON
30733
30734 @defivar <sys-group> name
30735 @c EN
30736 Group name.
30737 @c JP
30738 グループ名。
30739 @c COMMON
30740 @end defivar
30741
30742 @defivar <sys-group> gid
30743 @c EN
30744 Group id.
30745 @c JP
30746 グループID
30747 @c COMMON
30748 @end defivar
30749
30750 @defivar <sys-group> passwd
30751 @c EN
30752 Group password.
30753 @c JP
30754 グループパスワード。
30755 @c COMMON
30756 @end defivar
30757
30758 @defivar <sys-group> mem
30759 @c EN
30760 List of user names who are in this group.
30761 @c JP
30762 このグループに属するユーザ名のリスト。
30763 @c COMMON
30764 @end defivar
30765
30766 @end deftp
30767
30768 @defun sys-getgrgid gid
30769 @defunx sys-getgrnam name
30770 [POSIX]
30771 @c EN
30772 Returns @code{<sys-group>} object from an integer group id @var{gid}
30773 or a group name @var{name}, respectively.
30774 If the specified group doesn't exist, @code{#f} is returned.
30775 @c JP
30776 グループID@var{gid}もしくはグループ名@var{name}で示されるグループの情報を
30777 @code{<sys-group>}で返します。該当するグループが存在しない場合は
30778 @code{#f}が返されます。
30779 @c COMMON
30780 @end defun
30781
30782 @defun sys-gid->group-name gid
30783 @defunx sys-group-name->gid name
30784 @c EN
30785 Convenience function to convert between group id and group name.
30786 @c JP
30787 グループIDとグループ名を相互変換する便利な手続きです。
30788 @c COMMON
30789 @end defun
30790
30791 @subsubheading Unix users
30792
30793 @deftp {Builtin Class} <sys-passwd>
30794 @clindex sys-passwd
30795 @c EN
30796 Unix user information. Has following slots.
30797 @c JP
30798 Unixのユーザの情報です。以下のスロットを持ちます。
30799 @c COMMON
30800
30801 @defivar <sys-passwd> name
30802 @c EN
30803 User name.
30804 @c JP
30805 ユーザ名。
30806 @c COMMON
30807 @end defivar
30808
30809 @defivar <sys-passwd> uid
30810 @c EN
30811 User ID.
30812 @c JP
30813 ユーザID
30814 @c COMMON
30815 @end defivar
30816
30817 @defivar <sys-passwd> gid
30818 @c EN
30819 User's primary group id.
30820 @c JP
30821 ユーザのプライマリグループID。
30822 @c COMMON
30823 @end defivar
30824
30825 @defivar <sys-passwd> passwd
30826 @c EN
30827 User's (encrypted) password. If the system uses the shadow password file,
30828 you just get obscure string like "x".
30829 @c JP
30830 ユーザの(暗号化された)パスワード。システムがシャドウパスワードファイルを
30831 使っている場合は、 "x" のような無意味な文字列が入っています。
30832 @c COMMON
30833 @end defivar
30834
30835 @defivar <sys-passwd> gecos
30836 @c EN
30837 Gecos field.
30838 @c JP
30839 Gecosフィールド。
30840 @c COMMON
30841 @end defivar
30842
30843 @defivar <sys-passwd> dir
30844 @c EN
30845 User's home directory.
30846 @c JP
30847 ユーザのホームディレクトリ。
30848 @c COMMON
30849 @end defivar
30850
30851 @defivar <sys-passwd> shell
30852 @c EN
30853 User's login shell.
30854 @c JP
30855 ユーザのログインシェル。
30856 @c COMMON
30857 @end defivar
30858
30859 @defivar <sys-passwd> class
30860 @c EN
30861 User's class (only available on some systems).
30862 @c JP
30863 ユーザのクラス。(特定のシステムでのみ有効)。
30864 @c COMMON
30865 @end defivar
30866
30867 @end deftp
30868
30869 @defun sys-getpwuid uid
30870 @defunx sys-getpwnam name
30871 [POSIX]
30872 @c EN
30873 Returns @code{<sys-passwd>} object from an integer user id @var{uid}
30874 or a user name @var{name}, respectively.
30875 If the specified user doesn't exist, @code{#f} is returned.
30876 @c JP
30877 ユーザID@var{uid}もしくはユーザ名@var{name}で示されるユーザの情報を
30878 @code{<sys-passwd>}で返します。該当するユーザが存在しない場合は
30879 @code{#f}が返されます。
30880 @c COMMON
30881 @end defun
30882
30883 @defun sys-uid->user-name uid
30884 @defunx sys-user-name->uid name
30885 @c EN
30886 Convenience functions to convert between user id and user name.
30887 @c JP
30888 ユーザIDとユーザ名を相互変換する便利な手続きです。
30889 @c COMMON
30890 @end defun
30891
30892
30893 @subsubheading Password encryption
30894
30895 @defun sys-crypt key salt
30896 @c EN
30897 This is the interface to @code{crypt(3)}. @var{Key} and @var{salt}
30898 must be a string, and an encrypted string is returned.
30899 On systems where @code{crypt(3)} is not available, call to this
30900 function signals an error.
30901
30902 This routine is only for the code that needs to check password
30903 against the system's password database.
30904 If you are building user database on your own, you @emph{must} use
30905 @code{crypt.bcrypt} module (@pxref{Password hashing}) instead of
30906 this routine.
30907 @c JP
30908 これは、@code{crypt(3)}へのインターフェースです。@var{key}と@var{salt}は
30909 文字列でなければならず、暗号化された文字列が返されます。
30910 @code{crypt(3)}が利用できないシステムでこの関数を呼ぶとエラーが通知されます。
30911
30912 このルーチンは、システムのパスワードデータベースを使ってパスワードチェックを
30913 しなければならない時以外に使うべきではありません。独自のパスワードデータベースを
30914 新たに作る場合は、@code{crypt.bcrypt}モジュール(@ref{Password hashing})を
30915 使ってください。
30916 @c COMMON
30917 @end defun
30918
30919 @node Locale, Signal, Unix groups and users, System interface
30920 @subsection Locale
30921 @c NODE ロケール
30922
30923 @defun sys-setlocale category locale
30924 [POSIX]
30925 @c EN
30926 Sets/gets the locale of the category @var{category} to the locale @var{locale}.
30927 @var{category} must be an exact integer; the following pre-defined
30928 variables are available. @var{locale} must be a string locale name,
30929 or @code{#f} if you're merely querying the current locale.
30930
30931 Returns the locale name on success, or @code{#f} if the system
30932 couldn't change the locale. If you pass @code{#f} to the @var{locale},
30933 it returns the current locale name without changing it.
30934 @c JP
30935 カテゴリー@var{category}のロケールを@var{locale}にセットします。
30936 @var{category}は整数でなければなりません;以下の変数が@var{category}の
30937 ために定義されています。@var{locale}はロケールを表す文字列か@code{#f}です。
30938
30939 成功した場合は新しいロケール名を、ロケールが変更できなかった場合は@code{#f}を
30940 返します。@var{locale}に@code{#f}を渡した場合は、ロケールの変更はせずに
30941 単に現在のロケールの値を文字列で返します。
30942 @c COMMON
30943 @end defun
30944
30945 @defvar LC_ALL
30946 @defvarx LC_COLLATE
30947 @defvarx LC_CTYPE
30948 @defvarx LC_MONETARY
30949 @defvarx LC_NUMERIC
30950 @defvarx LC_TIME
30951 @c EN
30952 Predefined variables for possible @var{category} value of
30953 @code{sys-setlocale}.
30954 @c JP
30955 @code{sys-setlocale}の@var{category}に渡せる数値を定義しています。
30956 @c COMMON
30957 @end defvar
30958
30959 @defun sys-localeconv
30960 [POSIX]
30961 @c EN
30962 Returns an assoc list of various information for formatting numbers
30963 in the current locale.
30964 @c JP
30965 現在のロケールで数値をフォーマットする際に必要な様々な情報をassoc listに
30966 して返します。
30967 @c COMMON
30968 @end defun
30969
30970 @c EN
30971 An example session. It may differ on your system settings.
30972 @c JP
30973 例を示します。あなたのシステム設定によっては異なる結果になるかもしれません。
30974 @c COMMON
30975 @example
30976 (sys-localeconv)
30977 @result{}
30978 ((decimal_point . ".") (thousands_sep . "")
30979 (grouping . "") (int_curr_symbol . "")
30980 (currency_symbol . "") (mon_decimal_point . "")
30981 (mon_thousands_sep . "") (mon_grouping . "")
30982 (positive_sign . "") (negative_sign . "")
30983 (int_frac_digits . 127) (frac_digits . 127)
30984 (p_cs_precedes . #t) (p_sep_by_space . #t)
30985 (n_cs_precedes . #t) (n_sep_by_space . #t)
30986 (p_sign_posn . 127) (n_sign_posn . 127))
30987
30988 (sys-setlocale LC_ALL "fr_FR")
30989 @result{} "fr_FR"
30990
30991 (sys-localeconv)
30992 @result{}
30993 ((decimal_point . ",") (thousands_sep . "")
30994 (grouping . "") (int_curr_symbol . "FRF ")
30995 (currency_symbol . "F") (mon_decimal_point . ",")
30996 (mon_thousands_sep . " ") (mon_grouping . "\x03\x03")
30997 (positive_sign . "") (negative_sign . "-")
30998 (int_frac_digits . 2) (frac_digits . 2)
30999 (p_cs_precedes . #f) (p_sep_by_space . #t)
31000 (n_cs_precedes . #f) (n_sep_by_space . #t)
31001 (p_sign_posn . 1) (n_sign_posn . 1))
31002 @end example
31003
31004 @node Signal, System inquiry, Locale, System interface
31005 @subsection Signal
31006 @c NODE シグナル
31007
31008 @c EN
31009 Gauche can send out operating system's signals to the other processes
31010 (including itself) and can handle the incoming signals.
31011 @c JP
31012 Gaucheでは、OSのシグナルを自分自身や他のプロセスに送ったり、
31013 送られたシグナルを処理することができます。
31014 @c COMMON
31015
31016 @c EN
31017 In multithread environment, all threads share the signal
31018 handlers, and each thread has its own signal mask.
31019 See @ref{Signals and threads}, for details.
31020 @c JP
31021 マルチスレッド環境では、全てのスレッドがシグナルハンドラを共有し、
31022 各スレッドが独自のシグナルマスクを持ちます。
31023 詳しくは@ref{Signals and threads}を参照して下さい。
31024 @c COMMON
31025
31026 @c EN
31027 When a system call is interrupted by a signal,
31028 and a programmer defines a handler for the signal that doesn't transfer
31029 control to other context, the system call is restarted after
31030 the handler returns by default.
31031 @c JP
31032 システムコールがシグナルによって割り込まれ、
31033 プログラマがシグナルハンドラをセットしており、そのハンドラが別コンテキストに
31034 制御を移さずに戻った場合、そのシステムコールは原則としてハンドラからの復帰後に
31035 リスタートされます。
31036 @c COMMON
31037
31038 @c EN
31039 Here are some calls that are not simply restarted by signal interruption.
31040 @c JP
31041 シグナル割り込みによって単純にリスタートされないものは次の通りです。
31042 @c COMMON
31043
31044 @table @code
31045 @item close
31046 @c EN
31047 This may be called through @code{sys-close}, @code{close-port}, or even
31048 implicitly when the underlying file is closed. When a signal interrupts
31049 this call, the passed fd is no longer in use. Simply restarting it can
31050 be a race if another thread just grabs the fd.
31051 @c JP
31052 これは@code{sys-close}や@code{close-port}、さらには低層のファイルが自動的に
31053 クローズされる場合に呼ばれます。シグナルがこのシステムコールを中断して@code{EINTR}が
31054 返った時点で、渡されたファイルディスクリプタは無効になっており、もし他のスレッドがその
31055 ディスクリプタを直後に再利用していたら、リスタートするのは競合を引き起こします。
31056 @c COMMON
31057
31058 @item dup2
31059 @c EN
31060 This is called via @code{port-fd-dup!}. When @code{dup2} returns
31061 @code{EINTR}, the @var{newfd} is no longer in use and some other thread
31062 may grab it before restarting it.
31063 @c JP
31064 このコールは@code{port-fd-dup!}から呼ばれます。@code{dup2}が@code{EINTR}を
31065 返した時、@var{newfd}は使われない状態になっており、他のスレッドが直後にそれを使う
31066 可能性があるのでリスタートは危険です。
31067 @c COMMON
31068
31069 @item sleep
31070 @itemx nanosleep
31071 @c EN
31072 These calls tells the remaining time when they are interrupted.
31073 We restart them with that remaining time, not the original argument,
31074 so that the total sleep time would be close to what was given originally.
31075 @c JP
31076 これらのコールは中断された場合に残りの時間を教えてくれます。
31077 Gaucheではリスタート時に元の引数でなく残りの時間を渡すので、スリープする全体の時間は
31078 おおよそ最初に与えられた時間となります。
31079 @c COMMON
31080 @end table
31081
31082 @c EN
31083 On Windows native platforms, signals don't work except
31084 some limited support of @code{sys-kill}.
31085 @c JP
31086 Windowsネイティブ環境では、@code{sys-kill}の限定的なサポートを
31087 除いてシグナルは動作しません。
31088 @c COMMON
31089
31090 @menu
31091 * Signals and signal sets::
31092 * Sending signals::
31093 * Handling signals::
31094 * Masking and waiting signals::
31095 * Signals and threads::
31096 @end menu
31097
31098 @node Signals and signal sets, Sending signals, Signal, Signal
31099 @subsubsection Signals and signal sets
31100 @c NODE シグナルとシグナルセット
31101
31102 @c EN
31103 Each signal is referred by its signal number (a small integer)
31104 defined on the underlying operating system.
31105 Variables are pre-defined to the system's signal number.
31106 System's signal numbers may be architecture dependent, so you should
31107 use those variables rather than using literal integers.
31108 @c JP
31109 シグナルはオペレーティングシステムで定義された小さな整数値で表現されます。
31110 システムのシグナル番号に束縛された変数が定義されています。
31111 システムのシグナル番号はアーキテクチャによって異なるので、
31112 なるべく変数を利用するようにして下さい。
31113 @c COMMON
31114
31115 @defvar SIGABRT
31116 @defvarx SIGALRM
31117 @defvarx SIGCHLD
31118 @defvarx SIGCONT
31119 @defvarx SIGFPE
31120 @defvarx SIGHUP
31121 @defvarx SIGILL
31122 @defvarx SIGINT
31123 @defvarx SIGKILL
31124 @defvarx SIGPIPE
31125 @defvarx SIGQUIT
31126 @defvarx SIGSEGV
31127 @defvarx SIGSTOP
31128 @defvarx SIGTERM
31129 @defvarx SIGTSTP
31130 @defvarx SIGTTIN
31131 @defvarx SIGTTOU
31132 @defvarx SIGUSR1
31133 @defvarx SIGUSR2
31134 @c EN
31135 These variables are bound to the signal numbers of POSIX signals.
31136 @c JP
31137 これらの変数はPOSIXで定義された対応するシグナルの番号に束縛されています。
31138 @c COMMON
31139 @end defvar
31140
31141 @defvar SIGTRAP
31142 @defvarx SIGIOT
31143 @defvarx SIGBUS
31144 @defvarx SIGSTKFLT
31145 @defvarx SIGURG
31146 @defvarx SIGXCPU
31147 @defvarx SIGXFSZ
31148 @defvarx SIGVTALRM
31149 @defvarx SIGPROF
31150 @defvarx SIGWINCH
31151 @defvarx SIGPOLL
31152 @defvarx SIGIO
31153 @defvarx SIGPWR
31154 @c EN
31155 These variables are bound to the signal numbers of system-dependent
31156 signals. Not all of them may be defined on some systems.
31157 @c JP
31158 これらの変数はシステム依存のシグナル番号に束縛されています。
31159 全てのシステムで全てのシグナルがサポートされているわけではありません。
31160 @c COMMON
31161
31162 @c EN
31163 For portable code, you can use SRFI-238's codeset (@pxref{Codesets}).
31164 @c JP
31165 ポータブルなコードには、SRFI-238のコードセットを使うこともできます
31166 (@ref{Codesets}参照)。
31167 @c COMMON
31168 @end defvar
31169
31170 @c EN
31171 Besides each signal numbers, you can refer to a set of signals
31172 using a @code{<sys-sigset>} object.
31173 It can be used to manipulate the signal mask, and to install a signal
31174 handler to a set of signals at once.
31175 @c JP
31176 それぞれのシグナル番号の他に、@code{<sys-sigset>}オブジェクトを使って
31177 シグナルの集合を扱うことができます。シグナルの集合はシグナルマスクを操作したり、
31178 ひとつのシグナルハンドラを多数のシグナルに同時に設定したりする際に使えます。
31179 @c COMMON
31180
31181 @defun sys-strsignal signum
31182 [POSIX]
31183 @c EN
31184 Interface to @code{strsignal(3)}. The argument must be an exact
31185 integer.
31186
31187 Returns the system message associated with the signal with the number
31188 @var{signum}, as a string.
31189 if no such message is available, or @var{signum} is not a valid signal number,
31190 this function may return @code{#f} or some generic message provided
31191 by the system.
31192 @c JP
31193 @code{strsignal(3)}へのインタフェースです。引数は正確な整数でなければなりません。
31194
31195 シグナル番号@var{signum}のシグナルに結びつけられたメッセージを文字列で返します。
31196 もしメッセージが無かったり、@var{signum}が有効なシグナル番号でなかったら、
31197 この関数は@code{#f}を返すか、システムが提供する一般的なメッセージを返します。
31198 @c COMMON
31199
31200 @c EN
31201 For portable code, you can use SRFI-238's codeset (@pxref{Codesets}).
31202 @c JP
31203 ポータブルなコードには、SRFI-238のコードセットを使うこともできます
31204 (@ref{Codesets}参照)。
31205 @c COMMON
31206 @end defun
31207
31208
31209 @deftp {Class} <sys-sigset>
31210 @clindex sys-sigset
31211 @c EN
31212 A set of signals. An empty sigset can be created by
31213 @c JP
31214 シグナルの集合を表します。空のシグナルの集合は次の式で作成できます:
31215 @c COMMON
31216 @example
31217 (make <sys-sigset>) @result{} #<sys-sigset []>
31218 @end example
31219 @end deftp
31220
31221 @defun sys-sigset signal @dots{}
31222 @c EN
31223 Creates and returns an instance of @code{<sys-sigset>}
31224 with members @var{signal} @dots{}. Each @var{signal}
31225 may be either a signal number, another @code{<sys-sigset>}
31226 object, or @code{#t} for all available signals.
31227 @c JP
31228 @var{signal} @dots{}をメンバーとする@code{<sys-sigset>}の
31229 インスタンスを作成して返します。
31230 各@var{signal}にはシグナル番号、他の@code{<sys-sigset>}オブジェクト、あるいは
31231 @code{#t}を渡すことができます。@code{#t}を渡した場合は全てのシグナルが
31232 対象となります。
31233 @c COMMON
31234
31235 @example
31236 (sys-sigset SIGHUP SIGINT) @result{} #<sys-sigset [HUP|INT]>
31237 @end example
31238 @end defun
31239
31240 @defun sys-sigset-add! sigset signal @dots{}
31241 @defunx sys-sigset-delete! sigset signal @dots{}
31242 @c EN
31243 @var{Sigset} must be a @code{<sys-sigset>} object.
31244 Those procedures adds and removes the specified signals from
31245 @var{sigset} respectively, and returns the result. @var{sigset} itself
31246 is also modified.
31247
31248 @var{signal} may be either a signal number, another @code{<sys-sigset>}
31249 object, or @code{#t} for all available signals.
31250 @c JP
31251 @var{sigset}は@code{<sys-sigset>}オブジェクトでなければなりません。
31252 これらの手続きは@var{sigset}に指定されたシグナルを追加、
31253 もしくは@var{sigset}から指定されたシグナルを削除します。
31254 変更された@var{sigset}が返されます。
31255
31256 @var{signal}にはシグナル番号、他の@code{<sys-sigset>}オブジェクト、あるいは
31257 @code{#t}を渡すことができます。@code{#t}を渡した場合は全てのシグナルが
31258 対象となります。
31259 @c COMMON
31260 @end defun
31261
31262 @defun sys-sigset-fill! sigset
31263 @defunx sys-sigset-empty! sigset
31264 @c EN
31265 Fills @var{sigset} by all available signals, or empties @var{sigset}.
31266 @c JP
31267 システムで定義された全てのシグナルを@var{sigset}にセット、
31268 もしくは@var{sigset}を空にします。
31269 @c COMMON
31270 @end defun
31271
31272 @defun sys-signal-name signal
31273 @c EN
31274 Returns the human-readable name of the given signal number.
31275 (Note that signal numbers are system-dependent.)
31276 @c JP
31277 シグナル番号の名前を返します。(シグナル番号はシステムに依存します)。
31278 @c COMMON
31279
31280 @c EN
31281 For portable code, you can use SRFI-238's codeset (@pxref{Codesets}).
31282 @c JP
31283 ポータブルなコードには、SRFI-238のコードセットを使うこともできます
31284 (@ref{Codesets}参照)。
31285 @c COMMON
31286
31287 @example
31288 (sys-signal-name 2) @result{} "SIGINT"
31289 @end example
31290 @end defun
31291
31292 @node Sending signals, Handling signals, Signals and signal sets, Signal
31293 @subsubsection Sending signals
31294 @c NODE シグナルの送出
31295
31296 @c EN
31297 To send a signal, you can use @code{sys-kill} which works like
31298 @code{kill(2)}.
31299 @c JP
31300 シグナルを送るには、@code{sys-kill}を使うことができます。
31301 これはシステムの@code{kill(2)}のように動作します。
31302 @c COMMON
31303
31304 @defun sys-kill pid sig
31305 [POSIX]
31306 @c EN
31307 Sends a signal @var{sig} to the specified process(es). @var{Sig}
31308 must be a positive exact integer. @var{pid} is an exact integer and
31309 specifies the target process(es):
31310 @c JP
31311 シグナル@var{sig}を指定されたプロセス(群)に送ります。
31312 @var{sig}は正確な正整数でなければなりません。@var{pid}は正確な整数でなければ
31313 ならず、次のルールで対象となるプロセスを指定します。
31314 @c COMMON
31315 @itemize @bullet
31316 @item
31317 @c EN
31318 If @var{pid} is positive, it is the target process id.
31319 @c JP
31320 @var{pid}が正ならば、それがそのまま対象となるプロセスIDです。
31321 @c COMMON
31322 @item
31323 @c EN
31324 If @var{pid} is zero, the signal is sent to every process in the process
31325 group of the current process.
31326 @c JP
31327 @var{pid}がゼロならば、シグナルは現在のプロセスのプロセスグループ内の全ての
31328 プロセスに送られます。
31329 @c COMMON
31330 @item
31331 @c EN
31332 If @var{pid} is less than -1, the signal is sent to every process in
31333 the process group @var{-pid}.
31334 @c JP
31335 @var{pid}が-1より小さければ、シグナルはプロセスグループIDが@var{-pid}である
31336 全てのプロセスに送られます。
31337 @c COMMON
31338 @end itemize
31339
31340 @c EN
31341 On Windows native platforms, @code{sys-kill} may take positive integer
31342 or a process handle (@code{<win:handle>} instance) as @var{pid}.
31343 Only @code{SIGKILL}, @code{SIGINT} and @code{SIGABRT} are allowed
31344 as @var{sig}; Gauche uses @code{TerminateProcess} to terminate
31345 the target process for @code{SIGKILL},
31346 and sends the target process
31347 @code{CTRL_C_EVENT} and @code{CTRL_BREAK_EVENT} for
31348 @code{SIGINT} and @code{SIGABRT}, respectively.
31349 @c JP
31350 Windowsネイティブ環境では、@code{sys-kill}は@var{pid}に正整数か
31351 プロセスハンドル(@code{<win:handle>}のインスタンス)を取ります。
31352 @var{sig}がサポートするのは@code{SIGKILL}、@code{SIGINT}、@code{SIGABRT}
31353 のみです。@code{SIGKILL}に対しては@code{TerminateProcess}を使って
31354 対象プロセスを終了させます。@code{SIGINT}と@code{SIGABRT}に対しては
31355 対象プロセスにそれぞれ@code{CTRL_C_EVENT}と@code{CTRL_BREAK_EVENT}を
31356 送ります。
31357 @c COMMON
31358 @end defun
31359
31360 @c EN
31361 There's no Scheme equivalence for @code{raise()}, but you can use
31362 @code{(sys-kill (sys-getpid) @var{sig})}.
31363 @c JP
31364 POSIXの@code{raise()}に対応するScheme関数はありませんが、
31365 @code{(sys-kill (sys-getpid) @var{sig})} で同じことができます。
31366 @c COMMON
31367
31368 @node Handling signals, Masking and waiting signals, Sending signals, Signal
31369 @subsubsection Handling signals
31370 @c NODE シグナルの処理
31371
31372 @c EN
31373 You can register signal handling procedures in Scheme.
31374 (In multithread environment, signal handlers are shared by all
31375 threads; see @ref{Signals and threads} for details).
31376 @c JP
31377 Schemeでシグナルを処理する手続きを登録できます。
31378 (マルチスレッド環境では、シグナルハンドラの設定は全てのスレッドで共有されます。
31379 @ref{Signals and threads}を参照して下さい)。
31380 @c COMMON
31381
31382 @c EN
31383 When a signal is delivered to the Scheme process, the VM just records it
31384 and processes it later at a 'safe point' where the state of VM is consistent.
31385 We call the signal is @emph{pending} when it is registered by the VM
31386 but not processed yet.
31387 @c JP
31388 シグナルがSchemeプロセスに送られると、VMはそれを記録し、
31389 VMの状態が一貫している「安全なポイント」に達した時に処理します。
31390 シグナルがVMに記録され、しかしまだ処理されていない状態を、
31391 シグナルが保留されていると呼ぶことにします。
31392 @c COMMON
31393
31394 @c EN
31395 (Note that this makes handling of some signals such as @code{SIGILL}
31396 useless, for the process can't continue sensible execution after
31397 recording the signal).
31398 @c JP
31399 (このメカニズムのため、@code{SIGILL}のようなシグナルはSchemeレベルでは
31400 処理できません。そのシグナルを記録した後でプロセスが意味のある処理を続行できない
31401 からです)。
31402 @c COMMON
31403
31404 @c EN
31405 If the same signal is delivered more than once before VM processes
31406 the first one, the second one and later have no effect. (This is consistent
31407 to the traditional Unix signal model.) In other words,
31408 for each VM loop a signal handler can be invoked at most once per
31409 each signal.
31410 @c JP
31411 VMがシグナルを処理する前に同じシグナルが到着した場合、後に到着した方の
31412 シグナルは無効になります。(これは伝統的なUnixのシグナル処理と同様です)。
31413 言い替えれば、各VM loop毎に、シグナルハンドラは各シグナルについて
31414 たかだか1回しか呼ばれません。
31415 @c COMMON
31416
31417 @c EN
31418 When too many signals of the same kind are pending,
31419 Gauche assumes something has
31420 gone wrong (e.g. infinite loop inside C-routine) and aborts the
31421 process. The default of this limit is set rather low (3), to allow
31422 unresponsive interactive script to be terminated by typing Ctrl-C
31423 three times. Note that the counter is individual for each signal;
31424 Gauche won't abort if one @code{SIGHUP} and two @code{SIGINT}s are
31425 pending, for example. You can change this limit by
31426 @code{set-signal-pending-limit} described below.
31427 @c JP
31428 同じシグナルがたくさん保留された状態になった場合、
31429 Gaucheは異常事態が起きたとみなし (例えばCルーチンで無限ループに
31430 入った等)、プロセスをabortします。デフォルトではこの限界は
31431 かなり低い値(3)に設定されています。これは、インタラクティブスクリプトが
31432 反応しなくなった場合にCtrl-Cを3回打てば強制終了できる、という場合を
31433 想定しているためです。この限界を調べるカウンタはシグナル毎にあるので、
31434 例えば@code{SIGHUP}がひとつ、@code{SIGINT}がふたつ保留になった、
31435 といった場合はabortしません。この限界は下で述べる@code{set-signal-pending-limit}
31436 で変更することができます。
31437 @c COMMON
31438
31439 @c EN
31440 When you're using the @code{gosh} interpreter, the default
31441 behavior for each signal is as in the following table.
31442 @c JP
31443 @code{gosh}インタプリタを使っている場合、デフォルトでのシグナルの処理は
31444 次のように設定されています。
31445 @c COMMON
31446
31447 @table @code
31448 @item SIGABRT, SIGILL, SIGKILL, SIGSTOP, SIGSEGV, SIGBUS
31449 @c EN
31450 Cannot be handled in Scheme. @code{Gosh} follows the system's
31451 default behavior.
31452 @c JP
31453 Schemeでは処理できません。@code{gosh}ではこれらのシグナルを受けると
31454 システムのデフォルトの動作をします。
31455 @c COMMON
31456 @item SIGCHLD, SIGTSTP, SIGTTIN, SIGTTOU, SIGWINCH
31457 @c EN
31458 No signal handles are installed for these signals by @code{gosh},
31459 so the process follows the system's default behavior.
31460 A Scheme programs can install its own signal handler if necessary.
31461 @c JP
31462 @code{gosh}は初期状態ではこれらのシグナルのハンドラを設定せず、
31463 システムのデフォルトの振るまいに任せます。Schemeプログラムは必要ならば
31464 これらのシグナルのハンドラを設定できます。
31465 @c COMMON
31466 @item SIGCONT
31467 @c EN
31468 If @code{gosh} is running with input editing mode, a signal handler
31469 is installed to restore terminal status. Otherwise, no signal
31470 handler is installed by default, and a Scheme program can
31471 install its own signal handler if necessary.
31472 @c JP
31473 @code{gosh}が入力編集モードで起動している場合は、端末状態を回復する
31474 シグナルハンドラが設定されています。それ以外の場合はシグナルハンドラは
31475 設定されず、Schemeプログラムは必要ならば独自のハンドラを設定できます。
31476 @c COMMON
31477 @item SIGHUP, SIGQUIT, SIGTERM
31478 @c EN
31479 @code{Gosh} installs a signal handler for these signals
31480 that exits from the application with code 0.
31481 @c JP
31482 @code{gosh}はこれらのシグナルに対して、終了コード0でアプリケーションを
31483 終了するシグナルハンドラをセットします。
31484 @c COMMON
31485 @item SIGPIPE
31486 @c EN
31487 @code{Gosh} installs a signal handler that does nothing---that is,
31488 this signal is effectively ignored by default.
31489
31490 It is a design choice. Since Gauche delays actual handling
31491 of signals, @code{SIGPIPE} would be handled after the system call
31492 that tries to write to a broken pipe returns with @code{EPIPE}.
31493 That makes the signal a lot less useful, for we can handle the
31494 situation with error handlers for @code{<system-error>} with @code{EPIPE}.
31495
31496 The default Unix behavior of @code{SIGPIPE} is to terminate
31497 the process. It is useful for the traditional command-line tools
31498 that are often piped together---if one of downstream commands fails,
31499 the upstream process receives @code{SIGPIPE} and the entire
31500 command chain is shut down without a fuss. The signal is, however, rather an
31501 annoyance for other types of output such as sockets.
31502
31503 Gauche does support this ``exit when pipe gets stuck'' convention
31504 by ports. A port can be configured as @emph{sigpipe sensitive};
31505 if writing to that port caused @code{EPIPE}, it terminates the
31506 process. By default, standard output and standard error output
31507 are configured in that way.
31508 @c TODO: In the port section, explain how to configure so.
31509 @c JP
31510 @code{Gosh}は何もしないシグナルハンドラを設定します。
31511 つまり、事実上このシグナルはデフォルトで無視されます。
31512
31513 この設計の意図は次のとおりです。Gaucheはシグナルの処理を安全な
31514 ポイントまで遅延するため、@code{SIGPIPE}はそれを発生させた
31515 システムコールが@code{EPIPE}を返した後で処理されることになります。
31516 この事実によって、@code{SIGPIPE}を処理する必要性は大きく低下します。
31517 書き出した先のパイプが壊れていた場合には@code{EPIPE}の@code{<system-error>}
31518 をハンドルすれば良いからです。
31519
31520 Unixのデフォルトの@code{SIGPIPE}処理は、プロセスを終了させます。
31521 これは伝統的な、パイプでつないでゆくコマンドラインツールにとっては
31522 便利な振る舞いです。下流のコマンドが失敗した場合、上流のコマンドは
31523 @code{SIGPIPE}を受け取るので、つながれたすべてのコマンドが
31524 静かに終了するからです。
31525 けれども、ソケットなど他の種類の出力に対しては、このシグナルは
31526 しばしば邪魔になります。
31527
31528 Gaucheは、この「パイプが詰まったら終了する」という慣習を、
31529 ポートによってサポートします。ポートを「SIGPIPEを感知する」モード
31530 にセットすることができます。そのようなポートへの書き込みが
31531 @code{EPIPE}を発生させる状況になったら、プロセスが終了します。
31532 デフォルトでは、標準出力および標準エラー出力のポートが
31533 このモードになっています。
31534 @c COMMON
31535 @item SIGPWR, SIGXCPU, SIGUSR1, SIGUSR2
31536 @c EN
31537 On Linux platforms with thread support, these signals are used
31538 by the system and not available for Scheme. On other systems,
31539 these signals behaves the same as described below.
31540 @c JP
31541 Linuxプラットフォームでスレッドを使用している場合は、
31542 これらのシグナルはシステムで使用されるため、Schemeからは使用できません。
31543 他のシステムではこれらのシグナルは下記の「他のシグナル」と同じ動作と
31544 なります。
31545 @c COMMON
31546 @c EN
31547 @item other signals
31548 @code{Gosh} installs the default signal handler, which raises
31549 @code{<unhandled-signal-error>} condition (see @ref{Conditions}).
31550 Scheme programs can override it by its own signal handler.
31551 @c JP
31552 @item 他のシグナル
31553 @code{gosh}はデフォルトのシグナルハンドラを設定します。
31554 デフォルトのシグナルハンドラは@code{<unhandled-signal-error>}コンディションを
31555 通知します(@ref{Conditions}参照)。
31556 Schemeプログラムはシグナル毎に独自のハンドラを設定することが可能です。
31557 @c COMMON
31558 @end table
31559
31560 @c EN
31561 If you're using Gauche embedded in some other application,
31562 it may redefine the default behavior.
31563 @c JP
31564 @code{gosh}でなく、他のアプリケーションに埋め込まれたGaucheを使っている場合、
31565 Schemeレベルでのシグナルの使用をアプリケーションが制限している場合があります。
31566 @c COMMON
31567
31568 @c EN
31569 Use the following procedures to get/set signal handlers from Scheme.
31570 @c JP
31571 Schemeからシグナルハンドラを設定するには以下の手続きを使って下さい。
31572 @c COMMON
31573
31574 @defun set-signal-handler! signals handler :optional sigmask
31575 @c EN
31576 @var{Signals} may be a single signal number or a @code{<sys-sigset>}
31577 object, and @var{handler} should be either @code{#t}, @code{#f},
31578 @code{#<undef>}, or a procedure that takes one argument.
31579 If @var{handler} is a procedure, it will be called when the process
31580 receives one of specified signal(s), with the received signal
31581 number as an argument.
31582
31583 By default, the signals in @var{signals} are blocked
31584 (in addition to the signal mask in effect at that time) during
31585 @var{handler} is executed, so that @var{handler} won't be
31586 reentered by the same signal(s). You can provide
31587 a @code{<sys-sigset>} object to the @var{sigmask} arg
31588 to specify the signals to be blocked explicitly.
31589 Note that the signal mask
31590 is per-thread; if more than one thread unblocks a signal, the handler
31591 may still be invoked during execution of the handler (in other thread)
31592 even if you specify @var{sigmask}. You have to set the threads'
31593 signal mask properly to avoid such situation.
31594
31595 It is safe to do anything in @var{handler}, including throwing
31596 an error or invoking continuation captured elsewhere. (However,
31597 continuations captured inside @var{handler} will be invalid
31598 once you return from @var{handler}).
31599 @c JP
31600 @var{signals}はシグナル番号か@code{<sys-sigset>}オブジェクト、
31601 @var{handler}は@code{#t}、@code{#f}、@code{#<undef>}、
31602 一つの引数を取る手続きのいずれかでなければなりません。
31603 @var{handler}が手続きの場合、プロセスが指定されたシグナル(のうちのいずれか)を
31604 受けた時に、そのシグナル番号を引数として@var{handler}が呼ばれます。
31605
31606 デフォルトでは、@var{handler}は、@var{signals}に含まれる
31607 シグナルが(その時点で有効なシグナルマスクに加えて)ブロックされた状態で
31608 実行されます。オプショナルな@var{sigmask}引数に
31609 @code{<sys-sigset>}オブジェクトを渡すことで、
31610 ブロックすべきシグナルを明示することもできます。
31611 ただ、シグナルマスクはスレッド毎であることに注意して下さい。
31612 もし複数のスレッドがあるシグナルをブロックしていない場合、例え@var{sigmask}
31613 を指定していたとしても、ひとつのスレッドで@var{handler}を実行中に
31614 別のスレッドで並行して@var{handler}が呼ばれる可能性はあります。
31615 各スレッドのシグナルマスクを適切に設定することでそのようなケースを
31616 避けるようにして下さい。
31617
31618 @var{handler}の中でできる操作にはほとんど制限がありません。
31619 @var{handler}からエラーを投げたり、他の場所で補捉された継続を呼ぶことも
31620 できます。但し、@var{handler}内で補捉した継続は@var{handler}から
31621 戻った時点で無効になります。
31622 @c COMMON
31623
31624 @c EN
31625 If @var{handler} is @code{#t}, the operating system's default
31626 behavior is set to the specified signal(s). If @var{handler}
31627 is @code{#f}, the specified signals(s) will be ignored.
31628 @c JP
31629 @var{handler}が@code{#t}の場合、指定されたシグナルにはオペレーティングシステムの
31630 デフォルトの振るまいが設定されます。
31631 @var{handler}が@code{#f}の場合、指定されたシグナルは無視されます。
31632 @c COMMON
31633
31634 @c EN
31635 If @var{handler} is @code{#<undef>} (@pxref{Undefined values}),
31636 it indicates Gauche to leave the current OS's signal handler as it is.
31637 This value isn't as much use in @code{set-signal-handler!} as
31638 in @code{get-signal-handler}: If @code{#<undef>} is passed
31639 to @code{set-signal-handler!}, it immediately returns without
31640 modifying anything. However, if you get @code{#<undef>}
31641 from @code{get-signal-handler}, you can know that the
31642 signal handler behavior hasn't been modified by Gauche.
31643 (Note that once Gauche ever installs a signal handler,
31644 there is no way to revert back to make @code{get-signal-handler}
31645 return @code{#<undef>}).
31646 @c JP
31647 @var{handler}が@code{#<undef>}
31648 (@ref{Undefined values}参照) であった場合は、
31649 Gaucheはその時点のOSレベルのシグナルハンドラを変更しません。
31650 この引数は@code{set-signal-handler!}に対してはあまり
31651 意味を持ちません; 何もせずに返るだけだからです。
31652 しかし、@code{get-signal-handler}で@code{#<undef>}が
31653 返った場合、Gaucheがそのシグナルハンドラを一度もいじっていないことを
31654 示します。
31655 (一度でもGaucheがシグナルハンドラをインストールした場合、
31656 @code{get-signal-handler}が@code{#<undef>}を再び
31657 返すことはありません。)
31658 @c COMMON
31659
31660 @c EN
31661 Note that signal handler setting is shared among threads in
31662 multithread environment. The handler is called from the thread
31663 which is received the signal. See @ref{Signals and threads}
31664 for details.
31665 @c JP
31666 マルチスレッドプログラムでは、
31667 シグナルハンドラの設定はスレッド間で共有されることに注意して下さい。
31668 ハンドラはシグナルを受けたスレッドで実行されます。
31669 詳しくは@ref{Signals and threads}を参照して下さい。
31670 @c COMMON
31671 @end defun
31672
31673 @defun get-signal-handler signum
31674 @defunx get-signal-handler-mask signum
31675 @c EN
31676 Returns the handler setting, or signal mask setting, of a signal @var{signum},
31677 respectively. See @code{set-signal-handler!} for the meaning of
31678 the return value of @code{get-signal-handler}.
31679 @c JP
31680 シグナル@var{signum}に設定されたハンドラもしくはシグナルマスクを
31681 それぞれ返します。@code{get-signal-handler}が返す値の意味については
31682 @code{set-signal-handler!}を参照してください。
31683 @c COMMON
31684 @end defun
31685
31686 @defun get-signal-handlers
31687 @c EN
31688 Returns an associative list of all signal handler settings.
31689 Car of each element of returned list is a @code{<sys-sigset>} object,
31690 and cdr of it is the handler (a procedure or a boolean value)
31691 of the signals in the set.
31692 @c JP
31693 現在の全てのシグナルハンドラの設定を連想リストにして返します。
31694 返されるリストの各要素のcarには@code{<sys-sigset>}オブジェクトが、
31695 cdrにはそれらのシグナルに対応するハンドラ(手続きもしくはブール値)がセットされて
31696 います。
31697 @c COMMON
31698 @end defun
31699
31700 @defun get-signal-pending-limit
31701 @defunx set-signal-pending-limit limit
31702 @c EN
31703 Gets/sets the maximum number of pending signals per each signal type.
31704 If the number of pending signals exceeds this limit, Gauche aborts
31705 the process. See the explanation at the beginning of this section
31706 for the details. @var{Limit} must be a nonnegative exact integer.
31707 In the current implementation the maximum number of @var{limit} is 255.
31708 Setting limit to zero makes the number of pending signals unlimited.
31709 @c JP
31710 それぞれ、同一のシグナルをいくつまで保留することを許すかの現在の限界値を
31711 読み出し、また設定します。
31712 同一のシグナルが限界値を越える回数、処理されないまま保留された場合、
31713 Gaucheはプロセスを強制終了します。本節の冒頭の説明を参照してください。
31714 @var{limit}は非負の正確な整数でなければなりません。
31715 現在の実装では、@var{limit}に設定できる最大値は255です。
31716 また、@var{limit}に0を設定すると、無制限にシグナルを保留できるようになります。
31717 @c COMMON
31718 @end defun
31719
31720
31721 @defmac with-signal-handlers (handler-clause @dots{}) thunk
31722 @c EN
31723 A convenience macro to install signal handlers temporarily
31724 during execution of @var{thunk}.
31725 (Note: though this is convenient, this has certain dangerous
31726 properties described below. Use with caution.)
31727 @c JP
31728 @var{thunk}の実行中だけシグナルハンドラを一時的に設定する便利なマクロです
31729 (このマクロは便利ですが下に述べるような多少危険な性質もあるので、
31730 注意して使って下さい)。
31731 @c COMMON
31732
31733 @c EN
31734 Each @var{Handler-clause} may be one of the following forms.
31735 @table @code
31736 @item (@var{signals} @var{expr} @dots{})
31737 @var{Signals} must be an expression that will yield either a signal,
31738 a list of signals, or a @code{<sys-sigset>} object.
31739 Installs a signal handler for @var{signals} that evaluates
31740 @var{expr} @dots{} when one of the signals in @var{signals} is delivered.
31741
31742 @item (@var{signals} => @var{handler})
31743 This form sets the handler of @var{signals} to @var{handler},
31744 where @var{handler} should be either @code{#t}, @code{#f}
31745 or a procedure that takes one argument.
31746
31747 If @var{handler} is a procedure, it will be called when the process
31748 receives one of specified signal(s), with the received signal
31749 number as an argument.
31750 If @var{handler} is @code{#t}, the operating system's default
31751 behavior is set to the specified signal(s). If @var{handler}
31752 is @code{#f}, the specified signals(s) will be ignored.
31753 @end table
31754 @c JP
31755 @var{handler-clause}は以下のいずれかの形式です
31756 @table @code
31757 @item (@var{signals} @var{expr} @dots{})
31758 @var{signals}は、評価された時に単独のシグナル番号、シグナル番号のリスト、
31759 あるいは@code{<sys-sigset>}オブジェクトを生成する式でなければなりません。
31760 @var{signals}に含まれるシグナルを受け取った時に、@var{expr} @dots{}を
31761 評価するようなハンドラを設定します。
31762
31763 @item (@var{signals} => @var{handler})
31764 @var{signals}は上と同じです。@var{signals}に含まれるシグナルに
31765 対して、処理@var{handler}を設定します。
31766
31767 @var{handler}は@code{#t}、@code{#f}、一つの引数を取る手続きのいずれか
31768 でなければなりません。
31769 @var{handler}が手続きの場合、プロセスが指定されたシグナル(のうちのいずれか)を
31770 受けた時に、そのシグナル番号を引数として@var{handler}が呼ばれます。
31771 @var{handler}が@code{#t}の場合、指定されたシグナルにはオペレーティングシステムの
31772 デフォルトの振るまいが設定されます。
31773 @var{handler}が@code{#f}の場合、指定されたシグナルは無視されます。
31774 @end table
31775 @c COMMON
31776
31777 @c EN
31778 When the control exits from @var{thunk}, the signal handler setting
31779 before @code{with-signal-handlers} are recovered.
31780 @c JP
31781 @var{thunk}から制御が抜けた時に、@code{with-signal-handlers}が呼ばれた時点での
31782 シグナルハンドラが再設定されます。
31783 @c COMMON
31784
31785 @c EN
31786 @emph{CAVEAT:} If you're setting more than one signal handlers,
31787 they are installed in serial. If a signal is delivered before
31788 all the handlers are installed, the signal handler state may be
31789 left inconsistent. Also note that the handler setting is a global state;
31790 you can't set "thread local" handler by @code{with-signal-handlers},
31791 although the form may be misleading.
31792 @c JP
31793 @emph{注意:} このフォームで一つ以上のシグナルハンドラを設定する場合、
31794 それらは順にシステムに設定されます。全てのハンドラの設定が終る前に
31795 シグナルが届いた場合、シグナルハンドラの設定や再設定が不完全なままになる
31796 かもしれません。また、シグナルハンドラはグローバルな設定であり、
31797 「スレッドローカル」なハンドラを設定することはできませんが、
31798 @code{with-signal-handlers}の形式はそれを誤解させるかもしれません。
31799 @c COMMON
31800 @end defmac
31801
31802 @node Masking and waiting signals, Signals and threads, Handling signals, Signal
31803 @subsubsection Masking and waiting signals
31804 @c NODE シグナルのマスクと待機
31805
31806 @c EN
31807 A Scheme program can set a signal mask, which is a set of signals
31808 to be blocked from delivery. If a signal is delivered
31809 which is completely blocked in the process, the signal becomes
31810 "pending". The pending signal may be delivered once the signal
31811 mask is changed not to block the specified signal.
31812 (However, it depends on the operating system whether the pending
31813 signals are queued or not.)
31814 @c JP
31815 Schemeプログラムで、送出がブロックされるシグナルの集合であるシグナルマスク
31816 をセットできます。プロセスで完全にブロックされるシグナルが送出されると、
31817 そのシグナルは``保留''となります。保留されたシグナルは、指定されたシグナルを
31818 ブロックしないようにシグナルマスクが変更されると送出されるかもしれません。
31819 (しかし、保留されたシグナルがキューに入れられるかどうかはオペレーティング
31820 システムに依存します。)
31821 @c COMMON
31822
31823 @c EN
31824 In multithread environment, each thread has its own signal mask.
31825 @c JP
31826 マルチスレッドの環境では、スレッド毎に独自のシグナルマスクを持ちます。
31827 @c COMMON
31828
31829 @defun sys-sigmask how mask
31830 @c EN
31831 Modifies the current thread's signal mask, and returns the previous
31832 signal mask. @var{Mask} should be a @code{<sys-sigset>} object
31833 to specify the new mask, or @code{#f} if you just want to query
31834 the current mask without modifying one.
31835
31836 If you give @code{<sys-sigset>} object to @var{mask},
31837 @var{how} argument should be one of the following
31838 integer constants:
31839 @c JP
31840 現在のスレッドのシグナルマスクを変更し、以前のシグナルマスクを返します。
31841 @var{mask}には新しいマスクを指定する@code{<sys-sigset>}オブジェクトか、
31842 あるいはマスクを変更せず現在のマスクを得るだけなら@code{#f}を渡します。
31843
31844 @var{mask}に@code{<sys-sigset>}オブジェクトを渡した場合、
31845 引数@var{how}は以下の整数定数のうちの1つでなければなりません。
31846 @c COMMON
31847 @table @code
31848 @item SIG_SETMASK
31849 @c EN
31850 Sets @var{mask} as the thread's signal mask.
31851 @c JP
31852 @var{mask}をそのスレッドのシグナルマスクとしてセットします。
31853 @c COMMON
31854 @item SIG_BLOCK
31855 @c EN
31856 Adds signals in @var{mask} to the thread's signal mask.
31857 @c JP
31858 そのスレッドのシグナルマスクに@var{mask}にあるシグナルを追加します。
31859 @c COMMON
31860 @item SIG_UNBLOCK
31861 @c EN
31862 Removes signals in @var{mask} from the thread's signal mask.
31863 @c JP
31864 そのスレッドのシグナルマスクから@var{mask}にあるシグナルを削除します。
31865 @c COMMON
31866 @end table
31867 @end defun
31868
31869 @defun sys-sigsuspend mask
31870 @c EN
31871 Atomically sets thread's signal mask to @var{mask} and
31872 suspends the calling thread. When a signal that is not blocked
31873 and has a signal handler installed is delivered, the associated
31874 handler is called, then @code{sys-sigsuspend} returns.
31875 @c JP
31876 アトミックに、スレッドのシグナルマスクを@var{mask}にセットし、
31877 呼び出しているスレッドを一時停止します。ブロックされておらずシグナル
31878 ハンドラがインストールされているシグナルが送出されると、関連
31879 付けられたハンドラが呼ばれ、@code{sys-sigsuspend}は戻ります。
31880 @c COMMON
31881 @end defun
31882
31883 @defun sys-sigwait mask
31884 [POSIX]
31885 @c EN
31886 @var{Mask} must be a @code{<sys-sigset>} object.
31887 If any of signals in @var{mask} is/are pending in the OS,
31888 atomically clears one of them and returns the signal number
31889 of the cleared one. If there's no signal in @var{mask}
31890 pending, @code{sys-sigwait} blocks until any of the signals
31891 in @var{mask} arrives.
31892
31893 You have to block all signals in @var{mask} in all threads
31894 before calling @code{sys-sigwait}. If there's a thread
31895 that doesn't block the signals, the behavior of
31896 @code{sys-sigwait} is undefined.
31897
31898 Note: @code{Sys-sigwait} uses system's @code{sigwait} function,
31899 whose behavior is not defined if there's a signal
31900 handler on the signals it waits. To avoid complication,
31901 @code{sys-sigwait} resets the handlers set to the signals
31902 included in @var{mask} before calling @code{sigwait} to @code{SIG_DFL},
31903 and restores them after @code{sigwait} returns. If another thread
31904 changes signal handlers while @code{sys-sigwait} is waiting,
31905 the behavior is undefined; you shouldn't do that.
31906 @c JP
31907 @var{mask}は@code{<sys-sigset>}オブジェクトでなければなりません。
31908 アトミックに、保留されたシグナルから@var{mask}にあるシグナルの1つを
31909 クリアし、クリアしたシグナルの番号を返します。@var{mask}にある
31910 シグナルが1つも保留されていなければ、@code{sys-sigwait}はシグナルが
31911 届くまでブロックします。
31912
31913 @code{sys-sigwait}を呼ぶ前に、@var{mask}にある全てのシグナルを、
31914 全スレッドからブロックしておく必要があります。シグナルをブロックして
31915 いないスレッドがある場合、@code{sys-sigwait}の動作は未定義です。
31916
31917 註:@code{sys-sigwait}はシステムの@code{sigwait}関数を呼び出しますが、
31918 この関数は待つべきシグナルにシグナルハンドラが設定されていた場合の
31919 振る舞いが未定義となっています。困ったことになるのを避けるために、
31920 @code{sys-sigwait}はまず@var{mask}に含まれるシグナルに
31921 ハンドラが設定されていたらそれを@code{SIG_DFL}にリセットしてから
31922 @code{sigwait}を呼び出し、それが戻った後でハンドラを元に戻します。
31923 @code{sys-sigwait}が待っている間に他のスレッドでシグナルハンドラを
31924 変更してはいけません。そうした場合の動作は不定です。
31925 @c COMMON
31926 @end defun
31927
31928 @node Signals and threads, , Masking and waiting signals, Signal
31929 @subsubsection Signals and threads
31930 @c NODE シグナルとスレッド
31931
31932 @c EN
31933 The semantics of signals looks a bit complicated in the multithread
31934 environment. Nevertheless, it is pretty comprehensible once
31935 you remember a small number of rules. Besides,
31936 Gauche sets up the default behavior easy to use,
31937 while allowing programmers to do tricky stuff.
31938 @c JP
31939 シグナルのセマンティクスはマルチスレッド環境では少々複雑に見えます。
31940 しかし、いくつかのルールを覚えてしまえば、とても理解しやすいものでも
31941 あります。さらにGaucheでは、プログラマの簡単に使えるようにデフォルトの
31942 振る舞いをセットアップしています。
31943 @c COMMON
31944
31945 @c EN
31946 If you don't want to be bothered by the details, just remember
31947 one thing, with one sidenote.
31948 @strong{By default}, signals are handled by the
31949 primordial (main) thread. However, if the main thread
31950 is suspended on mutex or condition variable,
31951 the signal may not be handled at all, so be careful.
31952 @c JP
31953 細かいことは知りたくないという場合は、
31954 次の1つのことだけを覚えておいて下さい。
31955 @strong{デフォルトでは}、シグナルはメインスレッドで処理されます。
31956 しかし、メインスレッドがmutexや条件変数で一時停止している場合は、
31957 シグナルは全く処理されないので注意が必要です。
31958 @c COMMON
31959
31960 @c EN
31961 Now, if you are curious about the details, here are the rules:
31962 @c JP
31963 詳細に興味がある場合は、ここにルールがあります。
31964 @c COMMON
31965 @itemize @bullet
31966 @item
31967 @c EN
31968 The signal handler setting is shared by all threads.
31969 @c JP
31970 シグナルハンドラのセッティングは、全てのスレッドで共有されます。
31971 @c COMMON
31972 @item
31973 @c EN
31974 The signal mask is thread-specific.
31975 @c JP
31976 シグナルマスクはスレッド固有です。
31977 @c COMMON
31978 @item
31979 @c EN
31980 If a process receives an asynchronous signal (think it as a signal
31981 delivered from other processes), one thread is chosen, out of
31982 threads which don't block that signal.
31983 @c JP
31984 プロセスが非同期のシグナルを受け取ったら(他のプロセスからシグナルが
31985 送出されたと考えて下さい)、そのシグナルをブロックしていないスレッドの
31986 うちから任意の1つのスレッドが選ばれます。
31987 @c COMMON
31988 @item
31989 @c EN
31990 The signal handler is run on the chosen thread.
31991 However, if the chosen thread is waiting for acquiring a mutex lock
31992 or a condition variable, the handling of signal will be delayed
31993 until the thread is restarted. Signal delivery itself doesn't
31994 restart the thread.
31995 @c JP
31996 シグナルハンドラは選択されたスレッドにおいて実行されます。
31997 しかし、選択されたスレッドがmutexのロックの獲得や条件変数を待っている
31998 場合は、シグナルの処理はそのスレッドが再開するまで遅延されます。
31999 シグナルの送出自体はスレッドを再開しません。
32000 @c COMMON
32001 @end itemize
32002
32003 @c EN
32004 Now, these rules have several implications.
32005 @c JP
32006 これらのルールにはいくつかの暗黙の了解があります。
32007 @c COMMON
32008
32009 @c EN
32010 If there are more than one thread that don't block a particular
32011 signal, you can't know which thread receives the signal.
32012 Such a situation is much less useful in Gauche than C programs
32013 because of the fact that the signal handling can be delayed indefinitely
32014 if the receiver thread is waiting on mutex or condition variable.
32015 So, it is recommended to make sure, for each signal, there is only one
32016 thread that can receive it.
32017 @c JP
32018 特定のシグナルをブロックしないスレッドが1つ以上ある場合、
32019 どのスレッドがそのシグナルを受け取るかを知る術はありません。
32020 そのような状況は、GaucheにおいてはCプログラムよりもさらに不便です。
32021 なぜなら、受信側のスレッドがmutexや条件変数で待機している場合、
32022 シグナル処理は無期限に遅延されうるからです。
32023 したがって、それぞれのシグナルについて、それを受け取ることのできるスレッドが
32024 常にただの1つしかないようにすることを推奨します。
32025 @c COMMON
32026
32027 @c EN
32028 In Gauche, all threads created by @code{make-thread}
32029 (@pxref{Thread procedures}) blocks all the signals by default
32030 (except the reserved ones). This lets all the signals
32031 to be directed to the primordial (main) thread.
32032 @c JP
32033 Gaucheでは、@code{make-thread}(@ref{Thread procedures}参照)
32034 で作られた全てのスレッドは、デフォルトで全てのシグナル(予約済みを除く)
32035 をブロックします。これは、全てのシグナルがメインスレッドへ
32036 送られるということです。
32037 @c COMMON
32038
32039 @c EN
32040 Another strategy is to create a thread dedicated for handling
32041 signals. To do so, you have to block the signals in the
32042 primordial thread, then create the signal-handling thread,
32043 and within that thread you unblock all the signals.
32044 Such a thread can just loop on @code{sys-pause}.
32045 @c JP
32046 もう1つの戦略は、シグナル処理のみを行うスレッドを作る方法です。
32047
32048 もしシステムが@code{sys-sigwait}をサポートしていれば、ハンドル
32049 したい全てのシグナルを全てのスレッドでブロックしておき、シグナル
32050 処理専用のスレッドで@code{sys-sigwait}を呼び出してシグナルの
32051 受信を待つことができます。@code{sys-sigwait}の返り値がシグナル番号
32052 なので、その値でディスパッチしてください。この方法ではシグナル
32053 ハンドラが呼び出されることはありません。
32054
32055 @code{sys-sigwait}を使わないのであれば、メインスレッドでシグナルを
32056 ブロックして、シグナル処理専用スレッドを作り、そのスレッドで全ての
32057 シグナルを受け付けることができます。そのようなスレッドは@code{sys-pause}
32058 で単にループしていれば良いでしょう。@code{sys-pause}がシグナルで中断
32059 されると、シグナルハンドラがシグナル処理専用スレッドで呼び出されます。
32060 @c COMMON
32061
32062 @example
32063 (thread-start!
32064 (make-thread
32065 (lambda ()
32066 (sys-sigmask SIG_SETMASK (make <sys-sigset>)) ;;empty mask
32067 (let loop () (sys-pause) (loop)))))
32068 @end example
32069
32070 @c EN
32071 Complicated application may want to control per-thread signal
32072 handling precisely. You can do so, just make sure that
32073 at any moment only the designated thread unblocks the desired
32074 signal.
32075 @c JP
32076 複雑なアプリケーションでは、正確にスレッド毎のシグナル処理を
32077 制御したいかもしれません。それは、いつでも、指定されたスレッドのみが
32078 望むシグナルをブロックしないようにすれば、可能です。
32079 @c COMMON
32080
32081 @node System inquiry, Time, Signal, System interface
32082 @subsection System inquiry
32083 @c NODE システムへの問い合わせ
32084
32085 @defun sys-uname
32086 @c EN
32087 [POSIX] Returns a list of five elements,
32088 @code{(@var{sysname} @var{nodename} @var{release} @var{version} @var{machine})}.
32089 @c JP
32090 [POSIX] 次の5要素のリストを返します。
32091 @code{(@var{sysname} @var{nodename} @var{release} @var{version} @var{machine})}。
32092 @c COMMON
32093 @end defun
32094
32095 @defun sys-gethostname
32096 @c EN
32097 Returns the host name. If the system doesn't have gethostname(),
32098 the second element of the list returned by @code{sys-uname} is used.
32099 @c JP
32100 ホスト名を返します。システムでgethostname()が使えない場合、
32101 @code{sys-uname}が返すリストの2番目の要素が使われます。
32102 @c COMMON
32103 @end defun
32104
32105 @defun sys-getdomainname
32106 @c EN
32107 Returns the domain name. If the system doesn't have getdomainname(),
32108 @code{"localdomain"} is returned.
32109 @c JP
32110 ドメイン名を返します。システムでgetdomainname()が使えない場合、
32111 @code{"localdomain"}が返されます。
32112 @c COMMON
32113 @end defun
32114
32115 @defun sys-getcwd
32116 @c EN
32117 [POSIX] Returns the current working directory by a string.
32118 If the current working directory couldn't be obtained from the system,
32119 an error is signaled. See also @code{sys-chdir}
32120 (@pxref{Other file operations}), @code{current-directory}
32121 (@pxref{Directory utilities}).
32122 @c JP
32123 [POSIX] 現在の作業ディレクトリを文字列で返します。
32124 システムから現在の作業ディレクトリが得られない場合は、エラーが通知されます。
32125 @code{sys-chdir}(@ref{Other file operations}参照)、@code{current-directory}
32126 (@ref{Directory utilities}参照)も参照して下さい。
32127 @c COMMON
32128 @end defun
32129
32130 @defun sys-getgid
32131 @defunx sys-getegid
32132 @c EN
32133 [POSIX] Returns integer value of real and effective group id of the
32134 current process, respectively.
32135 Use @code{sys-gid->group-name} or @code{sys-getgrgid} to obtain
32136 the group's name and other information associated to the returned
32137 group id (@pxref{Unix groups and users}).
32138 @c JP
32139 [POSIX] 現在のプロセスの実グループIDと実効グループIDをそれぞれ整数で返します。
32140 返されたグループIDからグループ名その他の情報を得るには
32141 @code{sys-gid->group-name}や@code{sys-getgrgid}を使って下さい
32142 (@ref{Unix groups and users}参照)。
32143 @c COMMON
32144 @end defun
32145
32146 @defun sys-setgid gid
32147 @c EN
32148 [POSIX] Sets the effective group id of the current process.
32149 @c JP
32150 [POSIX] 現在のプロセスの実効グループIDをセットします。
32151 @c COMMON
32152 @end defun
32153
32154 @defun sys-getuid
32155 @defunx sys-geteuid
32156 [POSIX]
32157 @c EN
32158 Returns integer value of real and effective user id of the
32159 current process, respectively.
32160 Use @code{sys-uid->user-name} or @code{sys-getpwuid} to obtain
32161 the user's name and other information associated to the returned
32162 user id (@pxref{Unix groups and users}).
32163 @c JP
32164 現在のプロセスの実ユーザIDと実効ユーザIDをそれぞれ整数で返します。
32165 返されたユーザIDからユーザ名その他の情報を得るには
32166 @code{sys-uid->user-name}や@code{sys-getpwuid}を使って下さい
32167 (@ref{Unix groups and users}参照)。
32168 @c COMMON
32169 @end defun
32170
32171 @defun sys-setuid uid
32172 [POSIX]
32173 @c EN
32174 Sets the effective user id of the current process.
32175 @c JP
32176 現在のプロセスの実効ユーザIDをセットします。
32177 @c COMMON
32178 @end defun
32179
32180 @defun sys-setugid?
32181 @c EN
32182 Returns true iff the process is running with suid/sgid-ed (that is,
32183 the program's suid and/or sgid bit is set.)
32184
32185 Note: If the platform has @code{issetugid()} call, we use it.
32186 Otherwise, we remember whether the real (user|group) id and the
32187 effective (user|group) id differ or not at the initialization time.
32188 (In the latter case, we can't detect the case that the process
32189 changes [e]uid/[e]gid before initializing Gauche; keep it in mind if
32190 libgauche is used as an embedded Scheme engine).
32191 @c JP
32192 プロセスがsuid/sgidされていたら@code{#t}を、そうでなければ@code{#f}を返します。
32193
32194 註:プラットフォームが@code{issetugid()}を持っていればそれを呼びます。
32195 そうでない場合は、初期化時に実uid/gidと実効uid/gidが異なるかどうかを
32196 記録しています。(後者の場合、Gaucheが組み込みSchemeエンジンとして使われていて、
32197 プロセスがGauche初期化前に[e]uid/[e]gidを変更していたケースは検出できないことに
32198 留意してください)。
32199 @c COMMON
32200 @end defun
32201
32202 @defun sys-getgroups
32203 @c EN
32204 [POSIX] Returns a list of integer ids of supplementary groups.
32205 @c JP
32206 [POSIX] 補助的なグループのIDの整数のリストを返します。
32207 @c COMMON
32208 @end defun
32209
32210 @defun sys-setgroups gids
32211 @c EN
32212 Sets the current process's groups to the given
32213 list of integer group ids.
32214 The caller must have the appropriate privilege.
32215
32216 This procedure is only available when the feature id
32217 @code{gauche.sys.setgroups} exists. Use @code{cond-expand} for
32218 the portable program:
32219 @c JP
32220 現在のプロセスのグループIDのリストを、
32221 引数@var{gids}で与えたグループIDのリストに置き換えます。
32222 呼び出すプロセスは適切な特権を持っていなければなりません。
32223
32224 この手続きは、機能識別子@code{gauche.sys.setgroups}があるときのみ
32225 使えます。ポータブルなコードでは@code{cond-expand}を用いてください。
32226 @c COMMON
32227
32228 @example
32229 (cond-expand
32230 [gauche.sys.setgroups (sys-setgroups '(0 1))]
32231 [else])
32232 @end example
32233 @end defun
32234
32235 @defun sys-getlogin
32236 @c EN
32237 [POSIX] Returns a string of the name of the user logged in on the
32238 controlling terminal of the current process.
32239 If the system can't determine the information, @code{#f} is returned.
32240 @c JP
32241 [POSIX] 現在のプロセスの制御端末にログインしているユーザの名前を文字列で
32242 返します。システムがその情報を決定できない場合、@code{#f}が返されます。
32243 @c COMMON
32244 @end defun
32245
32246 @defun sys-getpgrp
32247 @c EN
32248 [POSIX] Returns a process group id of the current process.
32249 @c JP
32250 [POSIX] 現在のプロセスのプロセスグループIDを返します。
32251 @c COMMON
32252 @end defun
32253
32254 @c @defun sys-setpgrp
32255 @c Sets the process group id of the current process to the current
32256 @c process id. Equivalent to @code{sys-setpgid(0, 0)}.
32257 @c @end defun
32258
32259 @defun sys-getpgid pid
32260 @c EN
32261 Returns a process group id of the process specified by @var{pid}.
32262 If @var{pid} is zero, the current process is used.
32263 @c JP
32264 @var{pid}で指定されたプロセスのプロセスグループIDを返します。
32265 @var{pid}が0の場合、現在のプロセスが使われます。
32266 @c COMMON
32267
32268 @c EN
32269 Note that @code{getpgid()} call is not in POSIX. If the system
32270 doesn't have @code{getpgid()}, @code{sys-getpgid} still works if
32271 @var{pid} is zero (it just calls @code{sys-getpgrp}), but signals
32272 an error if @var{pid} is not zero.
32273 @c JP
32274 @code{getpgid()}はPOSIXではないことに注意して下さい。
32275 システムに@code{getpgid()}がない場合、@var{pid}が0ならば
32276 @code{sys-getpgid}がまだ動作しますが(それは単に@code{sys-getpgrp}を呼びます)
32277 、@var{pid}が0でない場合はエラーが通知されます。
32278 @c COMMON
32279 @end defun
32280
32281 @defun sys-setpgid pid pgid
32282 @c EN
32283 [POSIX] Sets the process group id of the process @var{pid} to @var{pgid}.
32284 If @var{pid} is zero, the process ID of the
32285 current process is used. If @var{pgid} is zero, the process ID
32286 of the process specified by @code{pid} is used. (Hence
32287 @code{sys-setpgid(0, 0)} sets the process group id of the
32288 current process to the current process id).
32289 @c JP
32290 [POSIX] プロセス@var{pid}のプロセスグループIDを@var{pgid}にセットします。
32291 @var{pid}が0ならば、現在のプロセスのプロセスIDが使われます。
32292 @var{pgid}が0ならば、@code{pid}で指定されたプロセスのプロセスIDが
32293 使われます。
32294 (したがって、@code{sys-getpgid(0, 0)}は、現在のプロセスのプロセス
32295 グループIDを現在のプロセスIDにセットします。)
32296 @c COMMON
32297 @end defun
32298
32299 @defun sys-setsid
32300 @c EN
32301 [POSIX] Creates a new session if the calling process is
32302 not a process group leader.
32303 @c JP
32304 [POSIX] 呼んでいるプロセスがプロセスグループリーダでなければ、
32305 新しいセッションを作ります。
32306 @c COMMON
32307 @end defun
32308
32309 @defun sys-getpid
32310 @defunx sys-getppid
32311 @c EN
32312 [POSIX] Returns the current process id and the parent process id,
32313 respectively.
32314 @c JP
32315 [POSIX] 現在のプロセスIDと親プロセスのIDをそれぞれ返します。
32316 @c COMMON
32317 @end defun
32318
32319 @defun sys-times
32320 [POSIX]
32321 @end defun
32322
32323 @defun sys-ctermid
32324 @c EN
32325 [POSIX] Returns the name of the controlling terminal of the process.
32326 This may be just a @code{"/dev/tty"}. See also @code{sys-ttyname}.
32327 @c JP
32328 [POSIX] プロセスの制御端末の名前を返します。
32329 これは単に@code{``/dev/tty''}かもしれません。@code{sys-ttyname}も参照して下さい。
32330 @c COMMON
32331 @end defun
32332
32333 @defun sys-getrlimit resource
32334 @defunx sys-setrlimit resource current :optional maximum
32335 [POSIX]
32336 @c EN
32337 Get and set resource limits respectively.
32338 @var{Resource} is an integer constant to specify the resource
32339 of concern. The following constants are defined.
32340 (The constants marked as bsd and/or linux indicates that they
32341 are not defined in POSIX but defined in BSD and/or Linux.
32342 Other systems may or may not have them. Consult @code{getrlimit}
32343 manpage of your system for the details.)
32344 @c JP
32345 プロセスのリソースリミットを取得あるいは設定します。
32346 @var{resource}はリソースの種類を指定する整数値です。
32347 以下にリストする定数が定義されています。
32348 (@code{bsd}、@code{linux}とマークされている値は、POSIXでは
32349 定義されていないけれどBSDもしくはLinuxで定義されていることを示します。
32350 他のプラットフォームでそれらが定義されているかどうかは、
32351 該当システムの@code{getrlimit}のマニュアルを参照してください。)
32352
32353 @c COMMON
32354
32355 @example
32356 RLIMIT_AS RLIMIT_CORE
32357 RLIMIT_CPU RLIMIT_DATA
32358 RLIMIT_FSIZE RLIMIT_LOCKS
32359 RLIMIT_MEMLOCK (bsd/linux) RLIMIT_MSGQUEUE (linux)
32360 RLIMIT_NICE (linux) RLIMIT_NOFILE
32361 RLIMIT_NPROC (bsd/linux) RLIMIT_RSS (bsd/linux)
32362 RLIMIT_RTPRIO (linux) RLIMIT_SIGPENDING (linux)
32363 RLIMIT_SBSIZE RLIMIT_STACK
32364 RLIMIT_OFILE
32365 @end example
32366 @end defun
32367
32368 @defun sys-nice inc
32369 [POSIX]
32370 @c EN
32371 Adds @var{inc}, which must be an exact integer, to the current process's
32372 nice value. Only the root user can specify negative @var{inc} value.
32373 Returns the new nice value.
32374 @c JP
32375 現在のプロセスのnice値に@var{inc}を加算します。@var{inc}は正確な整数でなければなりません。
32376 ルートユーザのみが@var{inc}に負の値を指定できます。
32377 新たなnice値を返します。
32378 @c COMMON
32379 @end defun
32380
32381 @defun sys-strerror errno
32382 @c EN
32383 @var{Errno} must be an exact nonnegative integer representing
32384 a system error number. This function returns a string describing
32385 the error.
32386 @c JP
32387 @var{errno}はシステムエラー番号を表現する非負正確整数でなければなりま
32388 せん。この関数はエラーを説明する文字列を返します。
32389 @c COMMON
32390
32391 @c EN
32392 For portable code, you can use SRFI-238's codeset (@pxref{Codesets}).
32393 @c JP
32394 ポータブルなコードには、SRFI-238のコードセットを使うこともできます
32395 (@ref{Codesets}参照)。
32396 @c COMMON
32397
32398 @c EN
32399 To represent @var{errno}, the following constants are defined.
32400 Each constant is bound to an exact integer representing the system's
32401 error number. Note that the actual value may differ among systems,
32402 and some of these constants may not be defined on some systems.
32403 @c JP
32404 @var{errno}を表現するのに、以下の定義済み定数が使えます。各定数はシス
32405 テムエラーを表現する非負正確整数に束縛されています。実際の値はシステム
32406 ごとに違い、またシステムによっては定義されていない定数があるということ
32407 に注意してください。
32408 @c COMMON
32409
32410 @example
32411 E2BIG EHOSTDOWN ENETDOWN ENXIO
32412 EACCES EHOSTUNREACH ENETRESET EOPNOTSUPP
32413 EADDRINUSE EIDRM ENETUNREACH EOVERFLOW
32414 EADDRNOTAVAIL EILSEQ ENFILE EPERM
32415 EADV EINPROGRESS ENOANO EPFNOSUPPORT
32416 EAFNOSUPPORT EINTR ENOBUFS EPIPE
32417 EAGAIN EINVAL ENOCSI EPROTO
32418 EALREADY EIO ENODATA EPROTONOSUPPORT
32419 EBADE EISCONN ENODEV EPROTOTYPE
32420 EBADF EISDIR ENOENT ERANGE
32421 EBADFD EISNAM ENOEXEC EREMCHG
32422 EBADMSG EKEYEXPIRED ENOKEY EREMOTE
32423 EBADR EKEYREJECTED ENOLCK EREMOTEIO
32424 EBADRQC EKEYREVOKED ENOLINK ERESTART
32425 EBADSLT EL2HLT ENOMEDIUM EROFS
32426 EBFONT EL2NSYNC ENOMEM ESHUTDOWN
32427 EBUSY EL3HLT ENOMSG ESOCKTNOSUPPORT
32428 ECANCELED EL3RST ENONET ESPIPE
32429 ECHILD ELIBACC ENOPKG ESRCH
32430 ECHRNG ELIBBAD ENOPROTOOPT ESRMNT
32431 ECOMM ELIBEXEC ENOSPC ESTALE
32432 ECONNABORTED ELIBMAX ENOSR ESTRPIPE
32433 ECONNREFUSED ELIBSCN ENOSTR ETIME
32434 ECONNRESET ELNRNG ENOSYS ETIMEDOUT
32435 EDEADLK ELOOP ENOTBLK ETOOMANYREFS
32436 EDEADLOCK EMEDIUMTYPE ENOTCONN ETXTBSY
32437 EDESTADDRREQ EMFILE ENOTDIR EUCLEAN
32438 EDOM EMLINK ENOTEMPTY EUNATCH
32439 EDOTDOT EMSGSIZE ENOTNAM EUSERS
32440 EDQUOT EMULTIHOP ENOTSOCK EWOULDBLOCK
32441 EEXIST ENAMETOOLONG ENOTTY EXDEV
32442 EFAULT ENAVAIL ENOTUNIQ EXFULL
32443 EFBIG
32444 @end example
32445 @end defun
32446
32447 @defun sys-errno->symbol k
32448 @defunx sys-symbol->errno symbol
32449 @c EN
32450 These procedures convert between integer error number and the symbol
32451 of its unix name (e.g. @code{EINTR}).
32452
32453 If the given error number or name isn't available on the running
32454 platform, those procedures return @code{#f}. See @code{sys-strerror}
32455 above for potentially available error names.
32456
32457 Valid error names and their actual values differ among platforms.
32458 These procedures make it easy to write portable meta-code that deal
32459 with system errors.
32460
32461 @c TODO: Note about Windows platforms.
32462 @c JP
32463 これらの手続きは、整数のエラー番号と、Unixでのエラー名を表すシンボル(例:@code{EINTR})とを
32464 相互に変換します。
32465
32466 与えられたエラー番号もしくはエラー名が実行中のプラットフォームで有効でない場合は
32467 @code{#f}が返されます。使えるかもしれないエラー名については上の@code{sys-strerror}
32468 の項を参照してください。
32469
32470 有効なエラー名およびその整数値はプラットフォーム毎に異なります。
32471 これらの手続きは、システムエラーを扱うメタなコードをポータブルに書く時に役立つでしょう。
32472 @c COMMON
32473
32474 @c EN
32475 For portable code, you can use SRFI-238's codeset (@pxref{Codesets}).
32476 @c JP
32477 ポータブルなコードには、SRFI-238のコードセットを使うこともできます
32478 (@ref{Codesets}参照)。
32479 @c COMMON
32480 @end defun
32481
32482 @node Time, Process management, System inquiry, System interface
32483 @subsection Time
32484 @c NODE 時間
32485
32486 @c EN
32487 Gauche has two representations of time, one is compatible to POSIX API,
32488 and the other is compatible to SRFI-18, SRFI-19 and SRFI-21.
32489 Most procedures accept both representations; if not, the representation
32490 the procedure accepts is indicated as either 'POSIX time' or 'SRFI time'.
32491 @c JP
32492 Gaucheでは時間は2種類の表現を持ちます。ひとつはPOSIX APIとコンパチブルな
32493 表現で、もう一つはSRFI-18、SRFI-19、SRFI-21とコンパチブルな表現です。
32494 多くの手続きはどちらの表現も理解しますが、そうでない場合は
32495 適用可能な表現を'POSIX time'または'SRFI time'と表記します。
32496 @c COMMON
32497
32498 @c EN
32499 POSIX time is represented by a real number which is a number of seconds
32500 since Unix Epoch (Jan 1, 1970, 0:00:00GMT).
32501 Procedure @code{sys-time}, which corresponds to POSIX @code{time(2)},
32502 returns this time representation.
32503 @c JP
32504 POSIX timeは実数で、Unix Epoch(Jan 1, 1970, 0:00:00GMT)からの秒数で
32505 表現されます。POSIXの@code{time(2)}に対応する@code{sys-time}手続きは
32506 この表現を返します。
32507 @c COMMON
32508
32509 @c EN
32510 SRFI-compatible time is represented by an object of @code{<time>} class,
32511 which keeps seconds and nanoseconds, as well as the type of the time
32512 (UTC, TAI, duration, process time, etc).
32513 @code{Current-time} returns this representation.
32514 @c JP
32515 SRFI互換の時間は@code{<time>}クラスのインスタンスとして表現され、
32516 秒、およびナノ秒のスロットを持ちます。
32517 また、時間の種別(UTC、TAI、期間、プロセス時間、他)も保持しています。
32518 @code{Current-time}はこの表現を返します。
32519 @c COMMON
32520
32521 @subsubheading POSIX time
32522
32523 @defun sys-time
32524 @c EN
32525 [POSIX] Returns the current time in POSIX time
32526 (the time since Epoch (00:00:00 UTC, January 1, 1970),
32527 measured in seconds). It may be a non-integral number, depending on
32528 the architecture.
32529
32530 Note that POSIX's definition of ``seconds since the Epoch'' doesn't
32531 take leap seconds into account.
32532 @c JP
32533 [POSIX] 現在の時間を POSIX 時間(エポック(00:00:00 UTC, January 1, 1970)
32534 からの秒数)で返します。マシンのアーキテクチャによっては、非正確数で
32535 あるかもしれません。
32536 @c COMMON
32537 @end defun
32538
32539 @defun sys-gettimeofday
32540 @c EN
32541 Returns two values. The first value is a number of seconds,
32542 and the second value is a fraction in a number of microseconds,
32543 since 1970/1/1 0:00:00 UTC. If the system doesn't have
32544 @code{gettimeofday} call, this function calls @code{time()};
32545 in that case, microseconds portion is always zero.
32546 @c JP
32547 2つの値を返します。1970/1/1 0:00:00 UTC を基準として、
32548 1つ目の値は秒数、2つ目の値は端数をマイクロ秒で表したものです。
32549 システムが @code{gettimeofday} 呼び出しをサポートしていない場合、
32550 この手続きは @code{time()} を呼び出し、その場合はマイクロ秒の
32551 部分はいつも 0 です。
32552 @c COMMON
32553 @end defun
32554
32555 @deftp {Builtin Class} <sys-tm>
32556 @clindex sys-tm
32557 @c EN
32558 Represents @code{struct tm}, a calendar date. It has the following slots.
32559 @c JP
32560 カレンダーである、@code{struct tm} を表します。以下のスロットを持ちます。
32561 @c COMMON
32562 @defivar <sys-tm> sec
32563 @c EN
32564 Seconds. 0-61.
32565 @c JP
32566 秒。0-61。
32567 @c COMMON
32568 @end defivar
32569 @defivar <sys-tm> min
32570 @c EN
32571 Minutes. 0-59.
32572 @c JP
32573 分。0-59。
32574 @c COMMON
32575 @end defivar
32576 @defivar <sys-tm> hour
32577 @c EN
32578 Hours. 0-23.
32579 @c JP
32580 時。0-23。
32581 @c COMMON
32582 @end defivar
32583 @defivar <sys-tm> mday
32584 @c EN
32585 Day of the month, counting from 1. 1-31.
32586 @c JP
32587 月の日。1 から数える。1-31。
32588 @c COMMON
32589 @end defivar
32590 @defivar <sys-tm> mon
32591 @c EN
32592 Month, counting from 0. 0-11.
32593 @c JP
32594 月。0 から数える。0-11。
32595 @c COMMON
32596 @end defivar
32597 @defivar <sys-tm> year
32598 @c EN
32599 Years since 1900, e.g. 102 for the year 2002.
32600 @c JP
32601 1900年からの年数。例えば、102 なら 2002年。
32602 @c COMMON
32603 @end defivar
32604 @defivar <sys-tm> wday
32605 @c EN
32606 Day of the week. Sunday = 0 .. Saturday = 6.
32607 @c JP
32608 曜日。日曜は 0 .. 土曜は 6。
32609 @c COMMON
32610 @end defivar
32611 @defivar <sys-tm> yday
32612 @c EN
32613 Day of the year. January 1 = 0 .. December 31 = 364 or 365.
32614 @c JP
32615 1年の中での日数。1月1日は 0 .. 12月31日は 364 か 365。
32616 @c COMMON
32617 @end defivar
32618 @defivar <sys-tm> isdst
32619 @c EN
32620 A flag that indicates if the daylight saving time is in effect.
32621 Positive if DST is in effect, zero if not, or negative if unknown.
32622 @c JP
32623 夏時間が有効であるかどうかを指定するフラグ。有効なら正の数、無効なら 0、
32624 分からなければ負の数。
32625 @c COMMON
32626 @end defivar
32627 @end deftp
32628
32629 @defun sys-gmtime time
32630 @defunx sys-localtime time
32631 @c EN
32632 [POSIX] Converts @var{time} to @code{<sys-tm>} object, represented in GMT
32633 or local timezone, respectively. @var{Time} can be either POSIX-time or
32634 SRFI-time.
32635 @c JP
32636 [POSIX] @var{time} を @code{<sys-tm>} オブジェクトに変換します。
32637 標準時での表現かローカルタイムゾーンでの表現かで使い分けます。
32638 @var{Time} は POSIX 時間か SRFI 時間です。
32639 @c COMMON
32640 @end defun
32641
32642 @defun sys-ctime time
32643 @c EN
32644 [POSIX] Converts @var{time} to it string representation, using POSIX ctime().
32645 @var{Time} can be either POSIX-time or SRFI-time.
32646 @c JP
32647 [POSIX] @var{time} を POSIX の ctime() を使って文字列表現に変換します。
32648 @var{Time} は POSIX 時間か SRFI 時間です。
32649 @c COMMON
32650 @end defun
32651
32652 @defun sys-difftime time1 time0
32653 @c EN
32654 [POSIX] Returns the difference of two times in the real number of seconds.
32655 @var{Time0} and @var{time1} can be either POSIX-time or SRFI-time.
32656 @c JP
32657 [POSIX] 2つの時間の差を、秒の実数で返します。@var{Time0} と@var{time1} は
32658 POSIX 時間か SRFI 時間です。
32659 @c COMMON
32660 @end defun
32661
32662 @defun sys-asctime tm
32663 @c EN
32664 [POSIX] Converts @code{<sys-tm>} object @var{tm} to a string representation.
32665 @c JP
32666 [POSIX] @code{<sys-tm>} オブジェクトである @var{tm} を文字列表現に変換します。
32667 @c COMMON
32668 @end defun
32669
32670 @defun sys-strftime format tm
32671 @c EN
32672 [POSIX] Converts @code{<sys-tm>} object @var{tm} to a string representation,
32673 according to a format string @var{format}.
32674 See your system's manual entry of @code{strftime} for the
32675 supported @var{format}.
32676
32677 It may return an empty string if the formatting results in an unusually
32678 lengthy string.
32679 @c JP
32680 [POSIX] @code{<sys-tm>} オブジェクトである @var{tm} を、フォーマット文字列
32681 @var{format} に従って文字列表現に変換します。
32682 @var{format}の書き方はシステムの@code{strftime}のマニュアルエントリを参照してください。
32683
32684 フォーマット結果が異常に長い文字列になる場合は、空文字列が返されることがあります。
32685 @c COMMON
32686 @end defun
32687
32688 @defun sys-mktime tm
32689 @c EN
32690 [POSIX] Converts @code{<sys-tm>} object @var{tm}, expressed as local time,
32691 to the POSIX-time (number of seconds since Epoch).
32692 @c JP
32693 [POSIX] ローカルタイムとして表現された @code{<sys-tm>} オブジェクトである
32694 @var{tm} を POSIX 時間(エポックからの秒数)に変換します。
32695 @c COMMON
32696 @end defun
32697
32698 @defun sys-tm->alist tm
32699 @c DEPRECATED
32700 @end defun
32701
32702
32703 @subsubheading SRFI time
32704
32705 @deftp {Builtin Class} <time>
32706 @clindex time
32707 @c EN
32708 The @code{<time>} object also represents a point of time.
32709 @c JP
32710 ある時刻を表す@code{<time>}オブジェクトです。
32711 @c COMMON
32712
32713 @clindex time
32714 @defivar <time> type
32715 @c EN
32716 Indicates time type. @code{time-utc} is the default, and that
32717 represents the number of seconds since Unix Epoch.
32718 SRFI-19 (@pxref{Time data types and procedures}) adds more types.
32719 @c JP
32720 timeの型を表します。デフォルトは@code{time-utc}で、Unixエポックからの
32721 秒数を表します。SRFI-19(@ref{Time data types and procedures}参照)
32722 ではさらに型が追加されています。
32723 @c COMMON
32724 @end defivar
32725 @defivar <time> second
32726 @c EN
32727 Second part of the time.
32728 @c JP
32729 timeの秒の部分です。
32730 @c COMMON
32731 @end defivar
32732 @defivar <time> nanosecond
32733 @c EN
32734 Nanosecond part of the time.
32735 @c JP
32736 timeのナノ秒の部分です。
32737 @c COMMON
32738 @end defivar
32739 @end deftp
32740
32741 @defun current-time
32742 @c EN
32743 [SRFI-18][SRFI-21]
32744 Returns the @code{<time>} object representing the current time in
32745 @code{time-utc}. @xref{Time data types and procedures}, for
32746 it redefines @code{current-time} to allow optional argument to
32747 specify time type.
32748 @c JP
32749 [SRFI-18][SRFI-21]
32750 現在の時間を@code{time-utc}で表す@code{<time>}オブジェクトを返します。
32751 @ref{Time data types and procedures}では、@code{current-time}が再定義され、
32752 timeの型を指定するオプショナル引数を受け付けるようにされています。
32753 @c COMMON
32754 @end defun
32755
32756 @defun time? obj
32757 [SRFI-18][SRFI-19][SRFI-21]
32758 @c EN
32759 Returns @code{#t} if @var{obj} is a time object.
32760 @c JP
32761 @var{obj}がtimeオブジェクトなら@code{#t}を返します。
32762 @c COMMON
32763 @end defun
32764
32765 @defun absolute-time obj :optional current-time
32766 @c EN
32767 The argument must be either a @code{<time>} object, a real number,
32768 or @code{#f}. If it is an absolute @code{<time>} object, it specifies
32769 an absolute point of time. If it is a @code{<time>} object of
32770 @code{time-duration} type, it is taken as a relative tiem from the current time.
32771 If it is a real number, it specifies
32772 the number of seconds from the current time.
32773
32774 This procedure returns @code{#f} if the argument is @code{#f},
32775 and a UTC @code{<time>} object for an absolute point of time otherwise.
32776
32777 Most procedures that takes `timeout' argument accepts @code{<time} object,
32778 real number or @code{#f}. This procedure is useful to process
32779 such argument in the same way.
32780 @c JP
32781 引数は@code{<time>}オブジェクト、実数、もしくは@code{#f}でなければなりません。
32782 絶対時刻を表す@code{<time>}オブジェクトの場合は絶対時刻を、
32783 @code{time-duration}型の@code{<time>}オブジェクトの場合は現在時刻からの相対時間を、
32784 実数の場合は現在時刻からの相対秒数を示します。
32785
32786 この手続きは、引数が@code{#f}なら@code{#f}を、そうでなければ
32787 絶対時刻に変換したUTC @code{<time>}オブジェクトを返します。
32788
32789 timeout引数を取る多くの手続きが、同じ形式の引数を取ります。
32790 この手続きはそれらと同様に時刻を扱うのに便利です。
32791 @c COMMON
32792
32793 @c EN
32794 The optional @var{current-time} is, if provided, must be an
32795 absolute @code{<time>} object or @code{#f}. If it is a @code{<time>}
32796 object, it is used as the current time instead of the actual current time.
32797 @c JP
32798 省略可能な@var{current-time}オブジェクトは、もし与えられたなら
32799 絶対時刻の@code{<time>}オブジェクトか@code{#f}でなければなりません。
32800 @code{<time>}オブジェクトの場合は、実際の現在時刻のかわりに
32801 それが現在時刻として使われます。
32802 @c COMMON
32803 @end defun
32804
32805 @defun seconds+ time x
32806 [SRFI-226+]
32807 @c EN
32808 Returns a time object that is @var{x} seconds after the given @var{time}.
32809 The type of returned time object is the same as @var{time}.
32810 The argument @var{x} must be a finite real number. If it is negative,
32811 returnd time is before the given time.
32812
32813 This procedure is mainly to write code compatibe to SRFI-226.
32814 For Gauche-specific code, you can use @code{absolute-time} above.
32815
32816 @xref{SRFI-19 Time procedures}, for another way to compute with time
32817 difference by @code{add-duration}/@code{subtract-duration}.
32818 @c JP
32819 与えられた@var{time}より@var{x}秒後を表すtimeオブジェクトを作って返します。
32820 返されるtimeオブジェクトの型は@var{time}と同じです。
32821 @var{x}は有限の実数です。@var{x}が負の場合は、与えられた時間より前の時間が返ります。
32822
32823 この手続きはSRFI-226準拠のコードを書くために用意されています。
32824 Gauche専用のコードなら上の@code{absolute-time}も使えます。
32825
32826 時間の計算には、SRFI-19の@code{add-duration}/@code{subtract-duration}
32827 も使えます。@ref{SRFI-19 Time procedures}を参照してください。
32828 @c COMMON
32829 @end defun
32830
32831
32832 @defun time->seconds time
32833 @defunx seconds->time seconds
32834 [SRFI-18][SRFI-21]
32835 @c EN
32836 Converts between time object and the number of seconds (POSIX-time).
32837 @var{Time} argument of @code{time->seconds} has to be a @code{<time>} object.
32838 @c JP
32839 timeオブジェクトと秒数(POSIX時間)を変換します。
32840 @code{time->seconds}の引数@var{time}は、@code{<time>}オブジェクトで
32841 なければなりません。
32842 @c COMMON
32843 @end defun
32844
32845
32846 @node Process management, I/O multiplexing, Time, System interface
32847 @subsection Process management
32848 @c NODE プロセス管理
32849
32850 @c EN
32851 The following procedures provide pretty raw, direct interface
32852 to the system calls.
32853 See also @ref{High-level process interface}, which provides
32854 more convenient process handling on top of these primitives.
32855 @c JP
32856 以下の手続きは、システムコールに対する直接的なインタフェースを提供します。
32857 @ref{High-level process interface}も合わせて参照して下さい。
32858 より高レベルの便利な手続きが定義されています。
32859 @c COMMON
32860
32861 @subsubheading Fork and exec
32862
32863 @defun sys-system command
32864 @c EN
32865 [POSIX]
32866 Runs @var{command}, which must be a string, in a subprocess.
32867 @var{command} is usually passed
32868 to @code{sh}, so the shell metacharacters are interpreted.
32869 @c JP
32870 [POSIX]
32871 サブプロセスで文字列@var{command}を実行します。@var{command}は通常、
32872 @code{sh}へ渡されるので、シェルのメタキャラクタは解釈されます。
32873 @c COMMON
32874
32875 @c EN
32876 If the operating system fails to spawn a subshell, a @code{<system-error>}
32877 is thrown. Otherwise, it waits until the subshell terminates, and
32878 the integer termination status of the subshell is
32879 returned.
32880 @c JP
32881 OSがサブシェル実行に失敗した場合は、@code{<system-error>}エラーが投げられます。
32882 そうでなければ、この手続きはサブシェルが終了するまで待ち、サブシェルの
32883 終了ステータス(termination status)を整数で返します。
32884 @c COMMON
32885
32886 @c EN
32887 The termination status must be interpreted as the same way as
32888 the return value of @code{sys-wait}, described below. For example,
32889 if you want to get exit status, you have to test the result with
32890 @code{sys-wait-exited?}, then apply @code{sys-wait-exit-status}.
32891 @c JP
32892 終了ステータスは@code{sys-wait}の戻り値と同じように解釈できます。
32893 例えば、exit statusを取るにはまず戻り値を@code{sys-wait-exited?}で検査して、
32894 それから@code{sys-wait-exit-status}を適用します。
32895 @c COMMON
32896
32897 @c EN
32898 In general, analyzing the result of @code{sys-system} properly is cumbersome,
32899 for nonzero code may indicate subshell's abnormal exit or signalled status
32900 or the command's abnormal exit or signalled status.
32901 We recommend to use @code{do-process} etc. of @code{gauche.process}
32902 module if you need to handle subprocess' exit status
32903 (@pxref{High-level process interface}).
32904 @c JP
32905 一般的に、@code{sys-system}の戻り値をきちんと解析するのは面倒です。
32906 というのも、ゼロでない場合、それはサブシェル本体の異常終了もしくはシグナルによる終了
32907 を表しているかもしれないし、@var{command}の異常終了もしくはシグナルによる終了
32908 を表しているかもしれないからです。
32909 サブプロセスの終了コードを精査する必要がある場合は、
32910 @code{gauche.process}モジュールの@code{do-process}等を使うことを推奨します
32911 (@ref{High-level process interface}参照)。
32912 @c COMMON
32913
32914 @c EN
32915 On Windows native platforms this will pass the argument to @code{cmd.exe}.
32916 We strongly discourage invoking @code{cmd.exe} with externally
32917 supplied arguments, since it is impossible to safely escape
32918 arbitrary string for @code{cmd.exe} arguments on Windows.
32919 @c JP
32920 Windowsネイティブな環境では、引数は@code{cmd.exe}に渡されます。
32921 外部から供給された文字列を引数にして@code{cmd.exe}を呼び出すことは
32922 避けてください。Windowsの@code{cmd.exe}に渡す任意の文字列を安全にエスケープすることは
32923 事実上不可能です。
32924 @c COMMON
32925 @end defun
32926
32927 @defun sys-fork
32928 @c EN
32929 [POSIX]
32930 Fork the current process. Returns 0 if you're in the child process,
32931 and a child process' pid if you're in the parent process.
32932 All the opened file descriptors are shared between the parent and
32933 the child. See @code{fork(2)} of your system for details.
32934 @c JP
32935 [POSIX]
32936 現在のプロセスをフォークします。子プロセスにいるならば0が返り、
32937 親プロセスにいるならば子プロセスのプロセスIDが返ります。
32938 全ての開かれているファイルディスクリプタは、親プロセスと子プロセスで
32939 共有されます。詳細は、システムの@code{fork(2)}を参照して下さい。
32940 @c COMMON
32941
32942 @c EN
32943 If the child process runs some Scheme code and exits instead of
32944 calling @code{sys-exec}, it should call @code{sys-exit}
32945 instead of @code{exit} to terminate itself.
32946 Normal exit call tries to flush the file
32947 buffers, and on some OS it messes up the parent's file buffers.
32948 @c JP
32949 子プロセスが@code{sys-exec}を呼ぶ代わりにSchemeコードを実行して
32950 終了する場合は、@code{exit}ではなく@code{sys-exit}を呼ぶ必要があります。
32951 通常のexitの呼び出しはファイルバッファのフラッシュを試み、
32952 OSによっては親のファイルバッファを混乱させるでしょう。
32953 @c COMMON
32954
32955 @c EN
32956 It should be noted that @code{sys-fork} is not safe when
32957 multiple threads are running. Because @code{fork(2)} copies
32958 the process' memory image which includes any mutex state,
32959 a mutex which is locked by another thread at the time of @code{sys-fork}
32960 remains locked in the child process, nevertheless the child process
32961 doesn't have the thread that unlock it!
32962 (This applies to the internal mutexes as well, so even you don't
32963 use Scheme mutex explicitly, this situation can always happen.)
32964
32965 If what you want is to spawn another program in a multi-threaded application,
32966 use @code{sys-fork-and-exec} explained below.
32967 If you absolutely need to run Scheme code in the
32968 child process, a typical technique is that you fork a manager process
32969 at the beginning of application, and whenever you need a new process
32970 you ask the manager process to fork one for you.
32971 @c JP
32972 @code{sys-fork}は複数のスレッドが走っている時には安全ではないことに
32973 注意してください。@code{fork(2)}システムコールはプロセスのメモリイメージを
32974 複製しますが、それには他のスレッドでロックされているmutexも含まれます。
32975 もし@code{sys-fork}の瞬間に他のスレッドが何かをロックしていたとすれば、
32976 子プロセスでもその資源はロックされたままになりますが、
32977 その時子プロセスはもはやその資源をアンロックするスレッドを持っていません。
32978 (これは内部で使っているmutexにも起こり得るため、Schemeレベルでmutexを
32979 全く使っていないとしても防ぐことはできません)。
32980
32981 やりたいことが、マルチスレッドアプリケーションで別プログラムをspawnする
32982 ことであるなら、下に説明する@code{sys-fork-and-exec}を使ってください。
32983 どうしても別プロセスでSchemeコードを走らせたいのなら、よくある方法は、
32984 アプリケーションの起動後すぐにマネージャプロセスとなる子プロセスをfork
32985 しておき、新たなプロセスが欲しくなったらそのマネージャプロセスに
32986 forkを依頼するという方法です。
32987 @c COMMON
32988
32989 @c EN
32990 This procedure is not available on Windows native platforms.
32991 @c JP
32992 Windowsネイティブな環境ではこの手続きは使えません。
32993 @c COMMON
32994 @end defun
32995
32996 @defun sys-exec command args :key directory iomap sigmask environment
32997 @c EN
32998 [POSIX+]
32999 Execute @var{command} with @var{args}, a list of arguments.
33000 The current process image is replaced by @var{command},
33001 so this function never returns.
33002 @c JP
33003 [POSIX+]
33004 @var{command}を引数のリストである@var{args}を伴って実行します。
33005 現在のプロセスイメージは@var{command}に置き換えられるので、
33006 この関数は戻りません。
33007 @c COMMON
33008
33009 @c EN
33010 All elements of @var{args} must be strings. The first element of
33011 @var{args} is used as @code{argv[0]}, i.e. the program name.
33012 @c JP
33013 @var{args}の全ての要素は文字列でなければなりません。
33014 @var{args}の最初の要素は、@code{argv[0]}、すなわちプログラム名として
33015 使われます。
33016 @c COMMON
33017
33018 @c EN
33019 (NB: On Windows, you can invoke batch files (@file{*.bat}, @file{*.cmd})
33020 using @code{sys-exec} and @code{sys-fork-and-exec}, but you can't
33021 use characters @code{()%!^<>&|"} within the command-line arguments,
33022 since there's no comprehensive way to escape them safely.
33023 You can pass them if you directly invoke an executable file.)
33024 @c JP
33025 (註: Windowsでは、@code{sys-exec}と@code{sys-fork-and-exec}で
33026 バッチファイル(@file{*.bat}, @file{*.cmd})を起動することもできます。
33027 ただその場合、コマンドライン引数に文字@code{()%!^<>&|"}のいずれかを含めることは
33028 できません。これらの文字を安全にエスケープする包括的な方法が無いからです。
33029 実行可能ファイルを直接指定する場合はこの制限はありません。)
33030 @c COMMON
33031
33032 @c EN
33033 The keyword argument @var{directory} must be a string of a
33034 directory name or @code{#f}.
33035 If it is a string, @code{sys-exec} change current working directory
33036 there before executing the program.
33037 @c JP
33038 キーワード引数@var{directory}は文字列によるディレクトリ名
33039 か@code{#f}でなければなりません。
33040 文字列だった場合、@code{sys-exec}はプログラムを実行する前に
33041 カレントワーキングディレクトリを指定ディレクトリに移動します。
33042 @c COMMON
33043
33044 @c EN
33045 The @var{iomap} keyword argument, when provided, specifies how the
33046 open file descriptors are treated. It must be the following format:
33047 @c JP
33048 キーワード引数の@var{iomap}は、与えられた場合は、開かれている
33049 ファイルディスクリプタがどのように扱われるかを指定します。
33050 この引数は以下のフォーマットでなければなりません。
33051 @c COMMON
33052 @example
33053 ((@i{to-fd} . @i{from-port-or-fd}) @dots{})
33054 @end example
33055 @c EN
33056 @i{To-fd} must be an integer,
33057 and @i{from-port-or-fd} must be an integer file descriptor or a port.
33058 Each element of the list makes the file descriptor of @i{from-port-or-fd}
33059 of the current process be mapped to the file descriptor @i{to-fd}
33060 in the executed process.
33061 @c JP
33062 @i{to-fd}は整数でなければならず、@i{from-port-or-fd}は整数のファイル
33063 ディスクリプタかポートでなければなりません。
33064 リストのそれぞれの要素は、現在のプロセスの@i{from-port-or-fd}の
33065 ファイルディスクリプタを、実行されているプロセスのファイルディスクリプタ
33066 @i{to-fd}にマップさせます。
33067 @c COMMON
33068
33069 @c EN
33070 If @var{iomap} is provided,
33071 any file descriptors other than specified in the iomap list will be closed
33072 before @code{exec()}. Otherwise, all file descriptors in the current
33073 process remain open.
33074 @c JP
33075 @var{iomap}が与えられると、iomapリストで指定されていないいかなるファイル
33076 ディスクリプタも@code{exec()}の前に閉じられます。さもなければ、現在のプロセスの
33077 全てのファイルディスクリプタは開かれたままになります。
33078 @c COMMON
33079
33080 @example
33081 (sys-exec "ls" '("ls" "-l")) @result{} ;; ls is executed.
33082
33083 (let ((out (open-output-file "ls.out")))
33084 (sys-exec "ls" '("ls" "-l") :iomap `((2 . 1) (1 . ,out)))
33085 @result{}
33086 ;; ls is executed, with its stderr redirected
33087 ;; to the current process's stdout, and its
33088 ;; stdout redirected to the file "ls.out".
33089 @end example
33090
33091 @c EN
33092 The @var{sigmask} keyword argument can be an instance of @code{<sys-sigset>}
33093 or @code{#f} (@xref{Signal}, for the details of signal masks).
33094 If it is an instance of @code{<sys-sigset>}, the signal mask of calling
33095 thread is replaced by it just before @code{exec(2)} is called.
33096 It is useful, for example, to run an external program from a thread where
33097 all signals are blocked (which is the default; see @ref{Signals and threads}).
33098 Without setting @var{sigmask}, the @code{exec}ed process inherits
33099 calling thread's signal mask and become a process that blocks all signals,
33100 which is not very convenient in most cases.
33101 @c JP
33102 @var{sigmask}キーワード引数には、@code{<sys-sigset>}のインスタンスか
33103 @code{#f}を渡すことができます (シグナルマスクについては@ref{Signal}を
33104 参照して下さい)。@code{<sys-sigset>}のインスタンスを渡した場合、
33105 この関数を呼び出したスレッドのシグナルマスクが、@code{exec(2)}を呼ぶ
33106 直前にそれによって置き換えられます。
33107 これは、全てのシグナルをブロックしているスレッドから外部プログラムを走らせる
33108 ような場合に便利です (@ref{Signals and threads}で述べるように、
33109 新たなスレッドは全てのシグナルをデフォルトでブロックします)。
33110 このような場合に@var{sigmask}を設定しないと、@code{exec}されたプロセスは
33111 スレッドのシグナルマスクを継承し、ほとんどのシグナルを受け付けないプロセスと
33112 なってしまうからです。通常、それはあまり便利ではありません。
33113 @c COMMON
33114
33115 @c EN
33116 Finally, @var{environment} keyword argument specifies
33117 the environment where the new process sees.
33118 If it is @code{#f} (default), the new process sees the same enviornment
33119 of the caller process.
33120 Otherwise, it must be a list of strings.
33121 Each string must be a form of @code{"NAME=VALUE"}, where @var{NAME}
33122 is the name of envionemnt variable, and @var{VALUE} is its value.
33123 Environment variable's name cannot contain @code{=}, while its value can.
33124 This format is compatible with what @code{sys-environ} returns
33125 (@pxref{Environment inquiry}),
33126 so that you can get the current enviornment with @code{sys-environ},
33127 add/remove/modify some of its entries, and pass it to this argument.
33128 @c JP
33129 最後に、@var{environment}キーワード引数は新たなプロセスから見える環境を指定します。
33130 デフォルト値は@code{#f}で、その場合は新たなプロセスは現在のプロセスの環境を引き継ぎます。
33131 そうでなければ、引数は文字列のリストでなければならず、
33132 各文字列は@code{"NAME=VALUE"}の形式でなければなりません。
33133 @var{NAME}が環境変数の名前を、@var{VALUE}がその値を示します。
33134 @var{NAME}は@code{=}を含むことはできませんが、@var{VALUE}に@code{=}を含めることは
33135 できます。
33136 この形式は@code{sys-environ}が返す形式と互換です
33137 (@ref{Environment inquiry}参照)。
33138 したがって、@code{sys-environ}で取得した環境にエントリを追加したり、
33139 そこからエントリを削除したりしてこの引数に渡すことができます。
33140 @c COMMON
33141
33142 @c EN
33143 When @code{sys-exec}
33144 encounters an error, most of the time it raises an error condition.
33145 Once the file descriptors are permuted, however, it would be impractical
33146 to handle errors in reasonable way (you don't even know stderr is still
33147 available!), so Gauche simply exits on the error.
33148 @c JP
33149 @code{sys-exec}がエラーに遭遇すると、たいていの場合エラー条件を投げます。
33150 しかし一旦ファイルディスクリプタの順番が変えられると、合理的な方法でエラーを処理する
33151 ことは実行不可能です(標準エラーがまだ有効かどうかさえ知る術がありません)。
33152 したがって、その場合はGaucheはエラー時には単に終了するだけです。
33153 @c COMMON
33154
33155 @c EN
33156 On Windows native platforms, only redirections of stdin, stdout and stderr
33157 are handled. Singal mask is ignored, for Windows doesn't have
33158 signals as the means of interprocess communication.
33159 @c JP
33160 Windowsネイティブ環境では、標準入力、標準出力、標準エラー出力に
33161 関するリダイレクションのみが処理されます。Windowsはプロセス間通信としての
33162 シグナルをサポートしないので、シグナルマスクは無視されます。
33163 @c COMMON
33164 @end defun
33165
33166 @defun sys-fork-and-exec command args :key directory iomap sigmask detached environment
33167 @c EN
33168 Like @code{sys-exec}, but executes @code{fork(2)} just before
33169 remapping I/O, altering signal mask and call @code{execvp(2)}.
33170 Returns child's process id. The meanings of arguments are
33171 the same as @code{sys-exec}.
33172
33173 It is strongly recommended to use this procedure instead of
33174 @code{sys-fork} and @code{sys-exec} combination when you need
33175 to spawn another program while other threads are running.
33176 No memory allocation nor lock acquisition is done between
33177 @code{fork(2)} and @code{execvp(2)},
33178 so it's pretty safe in the multithreaded environment.
33179 @c JP
33180 @code{sys-exec}と同じですが、ファイルディスクリプタとシグナルマスクを変更して
33181 @code{execvp(2)}を実行する直前に、@code{fork(2)}を実行します。
33182 子プロセスのプロセスidを返します。引数の意味は@code{sys-exec}と同じです。
33183
33184 他のスレッドが走っている環境下で別プログラムをspawnしたい場合は、
33185 @code{sys-fork}と@code{sys-exec}を別々に使うのではなく、
33186 この手続きを使ってください。
33187 この手続き中では、@code{fork(2)}と@code{execvp(2)}の間で
33188 メモリアロケーションもロックの獲得も行われないため、
33189 マルチスレッド環境で実行しても安全になっています。
33190 @c COMMON
33191
33192 @c EN
33193 On Windows native platforms, this procedure returns a
33194 Windows handle object (@code{<win:handle>}) of the created
33195 process instead of an integer process ID. See below for
33196 Windows process handle specific API.
33197
33198 Like @code{sys-exec}, only redirections of stdin, stdout and stderr
33199 are handled on Windows native platforms.
33200 @c JP
33201 Windowsネイティブ環境では、この手続きはプロセスIDではなく
33202 作られたプロセスに対するWindowsのハンドルオブジェクト
33203 (@code{<win:handle>}) を返します。Windowsプロセスハンドル
33204 特有の手続きについては後に述べます。
33205
33206 また、@code{sys-exec}同様、Windowsネイティブ環境では、標準入力、標準出力、標準エラー出力に
33207 関するリダイレクションのみが処理されます。
33208 @c COMMON
33209
33210 @c EN
33211 When a true value is given to the @var{detached} keyword argument,
33212 the executed process is detached from the current process group
33213 and belongs to its own group.
33214 That is, it won't be affected to the signal sent to the process group
33215 the caller process currently belongs to.
33216 It is a part of the common idioms to start a daemon process.
33217
33218 On Unix platforms, besides the executed process gets its own session
33219 by @code{setsid(2)}, it performs extra @code{fork(2)} to make its
33220 parent be the @code{init} process (pid=1).
33221 (Note: It means the running process is actually a grandchild of the
33222 calling process, although that relationship isn't preserved.
33223 The returned pid is the running process's one,
33224 not the intermediate process that exits immediately.)
33225
33226 On Windows native platforms,
33227 this flag causes the new process to be
33228 created with the @code{CREATE_NEW_PROCESS_GROUP} creation flag.
33229 @c JP
33230 @var{detached}キーワード引数に真の値が与えられた場合、
33231 実行されるプロセスは現在のプロセスグループからは切り離されます。
33232 つまり、現在のプロセスグループに送られるシグナルを、新しいプロセスは受け取りません。
33233 この動作はデーモンプロセスを作る際の標準的な手順のひとつです。
33234
33235 Unixでは、実行されるプロセスが@code{setsid(2)}を呼んで
33236 独自のセッションを作るだけでなく、余分な@code{fork(2)}
33237 を実行することで親を@code{init}プロセス (pid=1) に切り替えます。
33238 (つまり、実行されるプロセスは実は呼び出すプロセスの孫にあたります。
33239 親子関係はなくなりますが。返されるpidは実際に走っているこのプロセスのもので、
33240 すぐに終了する中間プロセスのものではありません。)
33241
33242 Windowsネイティブ環境では、このフラグがあると
33243 プロセス作成時に@code{CREATE_NEW_PROCESS_GROUP}フラグが使われます。
33244 @c COMMON
33245 @end defun
33246
33247 @subsubheading Wait
33248
33249 @defun sys-wait
33250 @c EN
33251 [POSIX] Calls system's @code{wait(2)}. The process suspends its execution
33252 until one of the child terminates. Returns two exact integer values,
33253 the first one is the child's process id, and the second is a status code.
33254 The status code can be interpreted by the following functions.
33255 @c JP
33256 [POSIX] システムの@code{wait(2)}を呼びます。プロセスは、子プロセスの1つが
33257 終了するまでその実行を一時停止します。2つの正確整数、1つ目は子プロセスのID、
33258 2つ目はステータスコードを返します。ステータスコードは以下の関数によって
33259 解釈できます。
33260 @c COMMON
33261 @end defun
33262
33263 @defun sys-waitpid pid :key nohang untraced
33264 @c EN
33265 [POSIX] This is an interface to @code{waitpid(3)}, an extended version of
33266 wait.
33267 @c JP
33268 [POSIX] これは、waitの拡張バージョンである、@code{waitpid(3)}への
33269 インターフェースです。
33270 @c COMMON
33271
33272 @c EN
33273 @var{pid} is an exact integer specifying which child(ren) to be waited.
33274 If it is a positive integer,
33275 it waits for that specific child. If it is zero, it waits for any
33276 member of this process group. If it is -1, it waits for any child process.
33277 If it is less than -1, it waits for any child process whose process group
33278 id is equal to the absolute value of @var{pid}.
33279 @c JP
33280 @var{pid}は、待つべき子プロセスを指定する正確な整数です。正の整数ならば、
33281 特定の子プロセスを待ちます。0ならば、このプロセスグループのいずれかの
33282 メンバを待ちます。-1ならば、いずれかの子プロセスを待ちます。
33283 -1よりも小さければ、プロセスグループIDが@var{pid}の絶対値と等しいいずれかの
33284 子プロセスを待ちます。
33285 @c COMMON
33286
33287 @c EN
33288 If there's no child process to wait, or a specific @var{pid} is
33289 given but it's not a child process of the current process,
33290 an error (@code{<system-error>}, @code{ECHILD}) is signaled.
33291 @c JP
33292 待つべき子プロセスが存在しない場合や、@var{pid}に具体的なプロセスIDが
33293 与えられたがそれが現在のプロセスの子プロセスでない場合は
33294 エラー(@code{<system-error>}, @code{ECHILD})となります。
33295 @c COMMON
33296
33297
33298 @c EN
33299 The calling process suspends until one of those child process is terminated,
33300 unless true is specified to the keyword argument @var{nohang}.
33301 @c JP
33302 キーワード引数@var{nohang}に真値が指定されていなければ、
33303 呼んでいるプロセスは、それらの子プロセスのうちの1つが終了するまで一時停止します。
33304 @c COMMON
33305
33306 @c EN
33307 If true is specified to the keyword argument @var{untraced},
33308 the status of stopped child process can be also returned.
33309 @c JP
33310 キーワード引数@var{untraced}に真値が指定されていれば、
33311 停止した子プロセスのステータスも返ります。
33312 @c COMMON
33313
33314 @c EN
33315 The return values are two exact integers, the first one is the child
33316 process id, and the second is a status code. If @var{nohang} is true and
33317 no child process status is available, the first value is zero.
33318 @c JP
33319 戻り値は2つの正確整数で、1つ目は子プロセスのID、2つ目はステータスコードです。
33320 @var{nohang}が真で子プロセスのステータスが利用できない場合は、1つ目の値は0です。
33321 @c COMMON
33322
33323 @c EN
33324 On Windows native platforms, this procedure may also accept
33325 a Windows process handle (@code{<win:handle>}) object as @var{pid} to
33326 wait the specific process. You can pass @code{-1} as @var{pid}
33327 to wait for any children, but you cannot wait for a specific
33328 process group.
33329 @c JP
33330 Windowsネイティブ環境では、この関数は@var{pid}にWindowsプロセスハンドル
33331 (@code{<win:handle>})オブジェクトを受け取ることもできます。
33332 その場合はそのハンドルの指すプロセスの終了を待ちます。
33333 また、@code{-1}を渡していずれかの子プロセスの終了を待つこともできますが、
33334 特定のプロセスグループの中の子プロセスを待つことはできません。
33335 @c COMMON
33336 @end defun
33337
33338 @defun sys-wait-exited? status
33339 @defunx sys-wait-exit-status status
33340 @c EN
33341 [POSIX]
33342 The argument is an exit status returned as a second value
33343 from @code{sys-wait} or @code{sys-waitpid}.
33344 @code{sys-wait-exited?} returns @code{#t} if the child process is
33345 terminated normally. @code{sys-wait-exit-status} returns the exit
33346 code the child process passed to @code{exit(2)}, or the return value
33347 of @code{main()}.
33348 @c JP
33349 [POSIX]
33350 引数は@code{sys-wait}か@code{sys-waitpid}の2番目の値として返される
33351 終了ステータスです。子プロセスが正常終了したら、@code{sys-wait-exited?}は
33352 @code{#t}を返します。@code{sys-wait-exit-status}は、子プロセスが
33353 @code{exit(2)}に渡した終了コードか、@code{main()}の戻り値を返します。
33354 @c COMMON
33355 @end defun
33356
33357 @defun sys-wait-signaled? status
33358 @defunx sys-wait-termsig status
33359 @c EN
33360 [POSIX]
33361 The argument is an exit status returned as a second value
33362 from @code{sys-wait} or @code{sys-waitpid}.
33363 @code{sys-wait-signaled?} returns @code{#t} if the child process
33364 is terminated by an uncaught signal.
33365 @code{sys-wait-termsig} returns the signal number that terminated the child.
33366 @c JP
33367 [POSIX]
33368 引数は、@code{sys-wait}か@code{sys-waitpid}の2つ目の戻り値である終了ステータスです。
33369 子プロセスが捕捉されないシグナルで終了した場合は、@code{sys-wait-signaled?}は
33370 @code{#t}を返します。
33371 @code{sys-wait-termsig}は、子プロセスを終了したシグナルの番号を返します。
33372 @c COMMON
33373 @end defun
33374
33375 @defun sys-wait-stopped? status
33376 @defunx sys-wait-stopsig status
33377 @c EN
33378 [POSIX]
33379 The argument is an exit status returned as a second value
33380 from @code{sys-waitpid}.
33381 @code{sys-wait-stopped?} returns @code{#t} if the child process is
33382 stopped. This status can be caught only by @code{sys-waitpid} with
33383 true @var{untraced} argument. @code{sys-wait-stopsig} returns the
33384 signum number that stopped the child.
33385 @c JP
33386 [POSIX]
33387 引数は、@code{sys-waitpid}の2つ目の戻り値である終了ステータスです。
33388 子プロセスが停止されれば、@code{sys-wait-stopped?}は@code{#t}を
33389 返します。このステータスは、@code{sys-waitpid}が@var{untraced}引数に
33390 真値を持っている場合にのみ捕捉されます。@code{sys-wait-stopsig}は
33391 子プロセスを停止させたシグナルの番号を返します。
33392 @c COMMON
33393 @end defun
33394
33395 @c EN
33396 On Windows native platforms, exit code is not structured as on Unix.
33397 You cannot distinguish a process being exited voluntarily or
33398 by forced termination. Gauche uses exit code @code{#xff09} to
33399 terminate other process with @code{sys-kill},
33400 and the above @code{sys-wait-*} procedures are adjusted accordingly,
33401 so that @code{sys-wait-signaled?} can likely to be used to check
33402 whether if the child process is terminated by Gauche.
33403 (@xref{Signal}, for the details of signal support on Windows.)
33404 @code{Sys-wait-stopped?} never returns true
33405 on Windows native platforms (yet).
33406 @c JP
33407 Windowsネイティブ環境では、終了コードはUnixのように構造化されておらず、
33408 プロセスが自発的に終了したか強制的に終了させられたかを判断する一般的な方法は
33409 ありません。Gauche自身は他のプロセスを@code{sys-kill}で
33410 終了させる場合に終了コード@code{#xff09}を送り、上の@code{sys-wait-*}
33411 手続きもそれに合わせてあります。従ってGaucheによって終了させられたプロセスでは
33412 @code{sys-wait-signaled?}でそのことを検出できる可能性が高いでしょう。
33413 (Windows上のシグナルのサポートについては@ref{Signal}を参照してください。)
33414 Windowsネイティブ環境では、@code{sys-wait-stopped?}が真を返すことは
33415 (今のところ)ありません。
33416 @c COMMON
33417
33418 @c EN
33419 @subsubheading Windows specific utilities
33420 @c JP
33421 @subsubheading Windows特有のユーティリティ
33422 @c COMMON
33423
33424 @c EN
33425 The following procedures are to access Windows process handle.
33426 They are only available on Windows native platforms.
33427 @c JP
33428 以下の手続きはWindowsのプロセスハンドルにアクセスするものです。
33429 Windowsネイティブ環境でのみ提供されます。
33430 @c COMMON
33431
33432 @defun sys-win-process? obj
33433 [Windows]
33434 @c EN
33435 Returns @code{#t} iff @var{obj} is a Windows process handle object.
33436 @c JP
33437 @var{obj}がWindowsプロセスハンドルの場合に@code{#t}を、それ以外では@code{#f}を
33438 返します。
33439 @c COMMON
33440 @end defun
33441
33442 @defun sys-win-process-pid handle
33443 [Windows]
33444 @c EN
33445 Returns an integer PID of the process represented by
33446 a Windows process handle @var{handle}. An error is signaled
33447 if @var{handle} is not a valid Windows process handle.
33448
33449 Note that the API to get a pid from a process handle is only
33450 provided on or after Windows XP SP1. If you call this
33451 procedure on Windows version before that, @code{-1} will be
33452 returned.
33453 @c JP
33454 Windowsプロセスハンドル@var{handle}が示すプロセスの、整数のpid値を
33455 返します。@var{handle}が有効なWindowsプロセスハンドルでない場合はエラーが
33456 通知されっす。
33457
33458 プロセスハンドルからプロセスIDを得るAPIはWindows XP SP1から提供されるように
33459 なりました。それ以前のWindowsでこの手続きを呼ぶと@code{-1}が返されます。
33460 @c COMMON
33461 @end defun
33462
33463
33464 @node I/O multiplexing, Garbage collection, Process management, System interface
33465 @subsection I/O multiplexing
33466 @c NODE I/Oの多重化
33467
33468 @c EN
33469 The interface functions for @code{select(2)}.
33470 The higher level interface is provided on top of these
33471 primitives; see @ref{Simple dispatcher}.
33472 @c JP
33473 @code{select(2)}へのインターフェース関数です。
33474 これらのプリミティブの上に構築された高次元のインターフェースが
33475 提供されています。@ref{Simple dispatcher}を
33476 参照して下さい。
33477 @c COMMON
33478
33479 @deftp {Builtin Class} <sys-fdset>
33480 @clindex sys-fdset
33481 @c EN
33482 Represents @code{fd_set}, a set of file descriptors. You can make
33483 an empty file descriptor set by make method:
33484 @c JP
33485 ファイルディスクリプタの集合である@code{fd_set}を表します。
33486 makeメソッドによって、空のファイルディスクリプタの集合を作れます。
33487 @c COMMON
33488 @example
33489 (make <sys-fdset>)
33490 @end example
33491 @end deftp
33492
33493 @defun sys-fdset elt @dots{}
33494 @c EN
33495 Creates a new @code{<sys-fdset>} instance with file descriptors
33496 specified by @var{elt} @dots{}. Each @var{elt} can be an
33497 integer file descriptor, a port, or a @code{<sys-fdset>} instance.
33498 In the last case, the descriptors in the given fdset is copied
33499 to the new fdset.
33500 @c JP
33501 @var{elt} @dots{}で指定されたファイルディスクリプタを持つ
33502 新たな@code{<sys-fdset>}のインスタンスを作成して返します。
33503 各@var{elt}は、ファイルディスクリプタを指定する整数、ポート、
33504 もしくは@code{<sys-fdset>}のインスタンスでなければなりません。
33505 最後の場合は、与えられたfdsetに含まれるディスクリプタが
33506 新たなfdsetにコピーされます。
33507 @c COMMON
33508 @end defun
33509
33510 @defun sys-fdset-ref fdset port-or-fd
33511 @defunx sys-fdset-set! fdset port-or-fd flag
33512 @c EN
33513 Gets and sets specific file descriptor bit of @var{fdset}.
33514 @var{port-or-fd} may be a port or an integer file descriptor.
33515 If @var{port-or-fd} is a port that doesn't have associated file descriptor,
33516 @code{sys-fdset-ref} returns @code{#f}, and @code{sys-fdset-set!} doesn't
33517 modify @var{fdset}. @var{flag} must be a boolean value.
33518 @c JP
33519 @var{fdset}の特定のファイルディスクリプタビットを取得・セットできます。
33520 @var{port-or-fd}は関連付けられたファイルディスクリプタを持っていないポートで、
33521 @code{sys-fdset-ref}は@code{#f}を返し、@code{sys-fdset-set!}は@var{fdset}を
33522 変更しません。@var{flag}は真偽値でなければなりません。
33523 @c COMMON
33524
33525 @c EN
33526 You can use generic setter of @code{sys-fdset-ref} as this:
33527 @c JP
33528 下記のように、@code{sys-fdset-ref}のジェネリックなセッタが使えます。
33529 @c COMMON
33530 @example
33531 (set! (sys-fdset-ref fdset port-or-fd) flag)
33532 @equiv{} (sys-fdset-set! fdset port-or-fd flag)
33533 @end example
33534 @end defun
33535
33536 @defun sys-fdset-copy! dest-fdset src-fdset
33537 @c EN
33538 Copies the content of @var{src-fdset} into @var{dest-fdset}.
33539 Returns @var{dest-fdset}.
33540 @c JP
33541 @var{src-fdset}の内容を@var{dest-fdset}にコピーします。
33542 @var{dest-fdset}を返します。
33543 @c COMMON
33544 @end defun
33545
33546 @defun sys-fdset-clear! fdset
33547 @c EN
33548 Empties and returns @var{fdset}.
33549 @c JP
33550 @var{fdset}の内容をクリアし、それ自身を返します。
33551 @c COMMON
33552 @end defun
33553
33554 @defun sys-fdset->list fdset
33555 @defunx list->sys-fdset fds
33556 @c EN
33557 Converts an fdset to a list of integer file descriptors and vice versa.
33558 In fact, @code{list->sys-fdset} works just like
33559 @code{(lambda (fds) (apply sys-fdset fds))}, so it accepts ports
33560 and other fdsets as well as integer file descriptors.
33561 @c JP
33562 fdsetを整数のファイルディスクリプタのリストに変換し、またその逆を行います。
33563 実際は、@code{list->sys-fdset}は
33564 @code{(lambda (fds) (apply sys-fdset fds))} のように動作するため、
33565 整数のファイルディスクリプタ以外にポートや他のfdsetを与えることもできます。
33566 @c COMMON
33567 @end defun
33568
33569 @defun sys-fdset-max-fd fdset
33570 @c EN
33571 Returns the maximum file descriptor number in @var{fdset}.
33572 @c JP
33573 @var{fdset}にある最大のファイルディスクリプタ番号を返します。
33574 @c COMMON
33575 @end defun
33576
33577 @defun sys-select readfds writefds exceptfds :optional timeout
33578 @defunx sys-select! readfds writefds exceptfds :optional timeout
33579 @c EN
33580 Waits for a set of file descriptors to change status.
33581 @var{readfds}, @var{writefds}, and @var{exceptfds} are @code{<fdset>}
33582 objects to represent a set of file descriptors to watch.
33583 File descriptors in @var{readfds} are watched to see if characters
33584 are ready to be read. File descriptors in @var{writefds} are
33585 watched if writing to them is ok. File descriptors in @var{exceptfds}
33586 are watched for exceptions. You can pass @code{#f} to one or more
33587 of those arguments if you don't care about watching the condition.
33588 @c JP
33589 ステータスを変更するためにファイルディスクリプタの集合を待ちます。
33590 @var{readfds}、@var{writefds}、@var{exceptfds}は、注目するファイル
33591 ディスクリプタの集合を表す@code{<fdset>}オブジェクトです。
33592 @var{readfds}にあるファイルディスクリプタは、文字を読み込む準備が
33593 出来たかどうかを検査するために監視されています。
33594 @var{writefds}にあるファイルディスクリプタはそこへ書き込むことができる
33595 ようになったか監視されています。@var{exceptfds}にあるファイルディスクリプタは
33596 例外のために監視されています。条件を監視する必要がない場合は、これらの引数の
33597 1つ以上に@code{#f}を渡すことができます。
33598 @c COMMON
33599
33600 @c EN
33601 @var{timeout} specifies maximum time @code{sys-select} waits for
33602 the condition change. It can be a real number, for number of microseconds,
33603 or a list of two integers, the first is the number of seconds and
33604 the second is the number of microseconds. If you pass @code{#f},
33605 @code{sys-select} waits indefinitely.
33606 @c JP
33607 @var{timeout}は@code{sys-select}が条件の変更を待つ最大の時間を指定します。
33608 それは、マイクロ秒を表す実数か、1つ目が秒数で2つ目がマイクロ秒である
33609 2つの整数からなるリストです。@code{#f}を渡すと、@code{sys-select}は
33610 永久に待ちます。
33611 @c COMMON
33612
33613 @c EN
33614 @code{sys-select} returns four values. The first value is a number
33615 of descriptors it detected status change. It may be zero if
33616 timeout expired. The second, third and fourth values are @code{<fdset>}
33617 object that contains a set of descriptors that changed status
33618 for reading, writing, and exception, respectively.
33619 If you passed @code{#f} to one or more of @var{readfds},
33620 @var{writefds} and @var{exceptfds}, the corresponding return value
33621 is @code{#f}.
33622 @c JP
33623 @code{sys-select}は4つの値を返します。1つ目の値は、ステータスの変更を
33624 検知したディスクリプタの数です。timeoutが経過したら0になるでしょう。
33625 2、3、4番目の値は、それぞれ読み込み、書き出し、例外のステータスを変更
33626 するディスクリプタの集合を含む@code{<fdset>}オブジェクトです。
33627 @var{readfds}、@var{writefds}、@var{exceptfds}のうちの1つ以上に@code{#f}を
33628 渡すと、対応する戻り値は@code{#f}になります。
33629 @c COMMON
33630
33631 @c EN
33632 @code{sys-select!} variant works the same as @code{sys-select}, except
33633 it modifies the passed @code{<fdset>} arguments.
33634 @code{sys-select} creates new @code{<fdset>} objects and
33635 doesn't modify its arguments.
33636 @c JP
33637 @code{sys-select!}の仲間は、それが渡された引数@code{<fdset>}を変更することを
33638 除けば、@code{sys-select}と同じように動作します。
33639 @code{sys-select}は、新しい@code{<fdset>}オブジェクトを作り、その
33640 引数を変更しません。
33641 @c COMMON
33642 @end defun
33643
33644
33645 @node Garbage collection, Memory mapping, I/O multiplexing, System interface
33646 @subsection Garbage collection
33647 @c NODE ガベージコレクション
33648
33649 @c EN
33650 The garbage collector runs implicitly whenever it is necessary,
33651 and you don't usually need to worry about it. However, in case
33652 if you do need to worry, here are a few procedures you can use.
33653 @c JP
33654 ガベージコレクタは必要になった時に自動的に走るので、普段気にする必要はないでしょう。
33655 けれどももし気にする必要が出てきた時は、いくつか使える手続きがあります。
33656 @c COMMON
33657
33658 @defun gc
33659 @c EN
33660 Trigger a full GC. It may be useful if you want to reduce
33661 interference of GC in certain parts of code by calling this
33662 immediately before that.
33663 @c JP
33664 フルGCを起動します。GCの影響をなるべく排除したいコードがある場合、
33665 その直前にこの手続きを呼ぶことで影響を減らせるかもしれません。
33666 @c COMMON
33667 @end defun
33668
33669 @defun gc-stat
33670 @c EN
33671 Returns a list of lists, each inner list contains a keyword and
33672 related statistics. Current statistics include @code{:total-heap-size},
33673 @code{:free-bytes}, @code{:bytes-since-gc} and @code{:total-bytes}.
33674 @c JP
33675 GCに関する統計情報を返します。返り値はリストのリストで、
33676 内側のリストはキーワードと対応する数値からなります。
33677 現在、返されるキーワードは
33678 @code{:total-heap-size}、
33679 @code{:free-bytes}、@code{:bytes-since-gc}、@code{:total-bytes}です。
33680 @c COMMON
33681 @end defun
33682
33683 @node Memory mapping, Miscellaneous system calls, Garbage collection, System interface
33684 @subsection Memory mapping
33685 @c NODE メモリマッピング
33686
33687 @deftp {Class} <memory-region>
33688 @c EN
33689 An object representing a mapped memory pages. It is returned
33690 from @code{sys-mmap}, and can be passed to @code{make-view-uvector}
33691 to access. It has the following read-only slots.
33692 @c JP
33693 マップされたメモリ領域を表すオブジェクトです。@code{sys-mmap}によって返され、
33694 @code{make-view-uvector}に渡してアクセスできます。以下の読み取り専用スロットを
33695 持っています。
33696 @c COMMON
33697
33698 @defivar {<memory-region>} address
33699 @c EN
33700 The address of the mapping. Not useful in the Scheme world, but
33701 you may need to pass this to foreign functions.
33702 @c JP
33703 マッピングされたアドレス。Schemeの世界では意味がありませんが、
33704 外部関数に渡すことはできます。
33705 @c COMMON
33706 @end defivar
33707
33708 @defivar {<memory-region>} size
33709 @c EN
33710 The size of the mapping, in bytes.
33711 @c JP
33712 マッピングの大きさをバイト数で。
33713 @c COMMON
33714 @end defivar
33715
33716 @defivar {<memory-region>} protection
33717 @c EN
33718 The bitmask represents memory protection. It is a bitwise OR of integer
33719 constants
33720 @code{PROT_READ}, @code{PROT_WRITE}, @code{PROT_EXEC} and @code{PROT_NONE}.
33721 See @code{sys-mmap} below for thedetails.
33722 @c JP
33723 メモリ保護属性のビットマスク。整数定数
33724 @code{PROT_READ}、@code{PROT_WRITE}、@code{PROT_EXEC}、@code{PROT_NONE}
33725 の組み合わせのbitwise orです。詳しくは下の@code{sys-mmap}を参照。
33726 @c COMMON
33727 @end defivar
33728
33729 @defivar {<memory-region>} flags
33730 @c EN
33731 the flags passed to the @code{sys-mmap}. See @code{sys-mmap} below
33732 for the details.
33733 @c JP
33734 @code{sys-mmap}に渡されたフラグ。下の@code{sys-mmap}を参照。
33735 @c COMMON
33736 @end defivar
33737 @end deftp
33738
33739 @defun sys-mmap port prot flags size :optional offset
33740 [POSIX]
33741 @c EN
33742 Maps files into memory using @code{mmap(2)} (or
33743 @code{MapViewOfFileEx} on Windows). Returns
33744 a @code{<memory-region>} object, which can be accessed
33745 via @code{make-view-uvector}.
33746 @c JP
33747 @code{mmap(2)} (Windowsでは@code{MapViewOfFileEx}) を使って
33748 ファイルをメモリにマップします。マップされたメモリは
33749 @code{<memory-region>}オブジェクトとして返され、
33750 @code{make-view-uvector}でアクセスできます。
33751 @c COMMON
33752
33753 @c EN
33754 The @var{port} argument must be either a port or @code{#f}.
33755 If it is a port, it must have underlying file. If it is @code{#f},
33756 the mapping becomes ``anonymous'' (not backed with a file); in that
33757 case, @code{MAP_ANONYMOUS} flag must also be specified in @var{flags}.
33758 @c JP
33759 @var{port}引数はポートか@code{#f}でなければならず、ポートの場合は
33760 ファイルと結びつけられていなければなりません。この引数が@code{#f}の場合は、
33761 ファイルの裏打ちがない「匿名の」メモリ領域がマップされます。この場合、
33762 @var{flags}引数に@code{MAP_ANONYMOUS}が指定されていなければなりません。
33763 @c COMMON
33764
33765 @c EN
33766 The @var{prot} argument specifies the protection bits of the
33767 memory region; it must be an integer created by bitwise-OR
33768 of the following constants:
33769 @c JP
33770 @var{port}引数はメモリ領域の保護属性を指定します。以下の定数のbitwise or
33771 でなければなりません。
33772 @c COMMON
33773 @table @code
33774 @item PROT_EXEC
33775 @c EN
33776 The mapped pages may be executed.
33777 @c JP
33778 メモリページに実行可能属性を付加。
33779 @c COMMON
33780 @item PROT_READ
33781 @c EN
33782 The mapped pages may be read.
33783 @c JP
33784 メモリページに読み取り可能属性を付加。
33785 @c COMMON
33786 @item PROT_WRITE
33787 @c EN
33788 The mapped pages may be written.
33789 @c JP
33790 メモリページに書き込み可能属性を付加。
33791 @c COMMON
33792 @item PROT_NONE
33793 @c EN
33794 Pages may not be accessed.
33795 @c JP
33796 ページにはアクセスできない。
33797 @c COMMON
33798 @end table
33799
33800 @c EN
33801 The @var{flags} argument must be an integer created by bitwise-OR
33802 of the following constants:
33803 @c JP
33804 @var{flags}引数は、以下の定数のbitwise orでなければなりません。
33805 @c COMMON
33806 @table @code
33807 @item MAP_SHARED
33808 @c EN
33809 The mapping is shared among processes. If you update the mapped
33810 pages, other processes mapping the same region can see it, too.
33811 @c JP
33812 マッピングはプロセス間で共有される。マップされたページを変更した場合、
33813 その変更は同じ領域をマップしている他のプロセスからも見える。
33814 @c COMMON
33815 @item MAP_PRIVATE
33816 @c EN
33817 The mapping is private to this process. If you update the mapped
33818 pages, it stays in the process and is not visible from outside.
33819 @c JP
33820 マッピングはプロセスだけに止まる。マップされたページを変更しても、
33821 それは外からは見えない。
33822 @c COMMON
33823 @item MAP_ANONYMOUS
33824 @c EN
33825 The pages don't have a backing file.
33826 @c JP
33827 マップされたページはファイルに結びつけられない。
33828 @c COMMON
33829 @end table
33830
33831 @c EN
33832 The @var{size} argument must be a positive exact integer, and the
33833 @var{offset} argument must be a non-negative exact integer. They specify
33834 the region of the file to be mapped; @var{size} bytes starting
33835 from @var{offset} bytes. The @var{offset} must be a multiple of
33836 the page size. If @var{offfset} is omitted, 0 is assumed.
33837 If you're mapping non-file-backed memory (when @var{port} is @code{#f}),
33838 @var{offset} is ignored.
33839 @c JP
33840 @var{size}は正の正確な整数、@var{offset}は非負の正確な整数でなければなりません。
33841 それらはファイル中のマップすべき領域を指定します。@var{offset}バイト目から始まる、
33842 @var{size}バイトの領域です。@var{offset}はページサイズの倍数でなければならず、
33843 省略された場合は0となります。マッピングがファイルと結びつけられていない場合
33844 (@var{port}が@code{#f}の場合)、@var{offset}は無視されます。
33845 @c COMMON
33846
33847 @c EN
33848 You don't need to @code{unmap} the mapped pages explicitly; when the created
33849 @code{<memory-region>} object is garbage collected, the memory
33850 is unmapped.
33851 @c JP
33852 マップされたメモリを陽に@code{unmap}する必要はありません。
33853 @code{<memory-region>}オブジェクトがガベージコレクトされる時に、メモリはunmapされます。
33854 @c COMMON
33855 @end defun
33856
33857 @defun make-view-uvector mem class length :optional offset immutable?
33858 @c EN
33859 This procedure creates a uniform vector that works as a ``window''
33860 to the memory region @var{mem}, which must be
33861 a @code{<memory-region>} object. If the underlying memory content
33862 changes, it is visible through the uvector. If the memory region is
33863 writeble and you mutate the uvector, it is reflected to the underlying
33864 memory region.
33865 @c JP
33866 この手続きはメモリ領域@var{mem}の「窓」になるユニフォームベクタを作って返します。
33867 @var{mem}は@code{<memory-region>}オブジェクトでなければなりません。
33868 マップされているメモリ領域に変化があれば、uvectorの内容も変化します。
33869 メモリが書き込み可能でマップされていれば、uvectorを変更するとそれが
33870 メモリにも反映されます。
33871 @c COMMON
33872
33873 @c EN
33874 The @var{class} argument must be one of the uniform vector class
33875 (e.g. @code{<u8vector>}), and @var{length} is the length of the
33876 uvector to be created. The length is the number of elements,
33877 not the number of bytes. The memory is accessed with the native
33878 endianness. @var{Length} can be @code{#f}, in that case up to the end of the
33879 memory region is used.
33880 @c JP
33881 @var{class}はユニフォームベクタのクラスでなければなりません (例: @code{<u8vector>})。
33882 @var{length}は作られるユニフォームベクタの長さ(要素数)です。
33883 メモリはネイティブバイトオーダーでアクセスされます。@var{length}は@code{#f}でも良く、
33884 その場合はメモリ領域の最後までが使われます。
33885 @c COMMON
33886
33887 @c EN
33888 The @var{offset} argument specifies the offset from the beginning of
33889 memory region, in number of @emph{bytes}. It must be a multiple
33890 of the uvector's element size.
33891 @c JP
33892 @var{offset}引数はメモリ領域先頭からのオフセットをバイト数で指定します。
33893 これはユニフォームベクタの要素サイズの倍数でなければなりません。
33894 @c COMMON
33895
33896 @c EN
33897 If the memory region is read-only (i.e. it is mapped without @code{PROT_WRITE}),
33898 the resulting uvector is immutable. Otherwise, it is mutable by default,
33899 but ynou can give a true value to @var{immutable?} argument to create
33900 an immutable uvector.
33901 @c JP
33902 メモリ領域が読み出し専用であれば(つまり、@code{PROT_WRITE}属性なしでマップされていれば)、
33903 返されるユニフォームベクタは変更不可になります。そうでなければデフォルトで変更可能な
33904 ユニフォームベクタが返されますが、@var{immutable?}引数に真の値を与えることで、
33905 変更不可なユニフォームベクタを得ることもできます。
33906 @c COMMON
33907
33908 @c EN
33909 The memory region isn't garbage collected as long as there're uvectors
33910 that referencing the region.
33911 @c JP
33912 メモリ領域は、それを参照しているユニフォームベクタが生きている限りは
33913 ガベージコレクトされません。
33914 @c COMMON
33915 @end defun
33916
33917
33918 @node Miscellaneous system calls, , Memory mapping, System interface
33919 @subsection Miscellaneous system calls
33920 @c NODE その他のシステムコール
33921
33922 @defun sys-pause
33923 @c EN
33924 [POSIX]
33925 Suspends the process until it receives a signal whose
33926 action is to either execute a signal-catching function or to terminate
33927 the process. This function only returns when the signal-catching
33928 function returns. The returned value is undefined.
33929 @c JP
33930 [POSIX]
33931 シグナルキャッチ関数の実行かプロセスの終了を指示するシグナルを
33932 受け取るまでプロセスを一時停止します。この関数は、シグナルキャッチ関数が
33933 戻ったときにのみ戻ります。戻り値は未定義です。
33934 @c COMMON
33935
33936 @c EN
33937 Note that just calling @code{pause()} doesn't suffice the above semantics
33938 in Scheme-level. Internally this procedure calls @code{sigsuspend()}
33939 with the current signal mask.
33940 @c JP
33941 Schemeレベルでは、@code{pause()}を呼ぶだけでは上記のセマンティクスを
33942 満足しません。内部的にこの手続きは現在のシグナルマスクを伴って、
33943 @code{sigsuspend()}を呼びます。
33944 @c COMMON
33945 @end defun
33946
33947 @defun sys-alarm seconds
33948 @c EN
33949 [POSIX] Arranges a SIGALRM signal to be delivered after @var{seconds}.
33950 The previous settings of the alarm clock is canceled. Passing zero
33951 to @var{seconds} doesn't schedule new alarm.
33952 Returns the number of seconds remaining until previously scheduled
33953 alarm was due to be delivered (or zero if no alarm is active).
33954 @c JP
33955 [POSIX] SIGALRMシグナルが@var{seconds}秒後に送出されるように準備します。
33956 以前のアラームクロックのセッティングはキャンセルされます。
33957 @var{seconds}に0を渡すと、新しいアラームをスケジューリングしません。
33958 以前にスケジューリングされていたアラームが送出されるまでの残り時間を
33959 秒数で返します(アラームがアクティブでない場合は0を返します)。
33960 @c COMMON
33961 @end defun
33962
33963 @defun sys-sleep seconds :optional (no-retry #f)
33964 [POSIX]
33965 @c EN
33966 Suspends the calling thread until the specified number of seconds elapses.
33967
33968 Note that libc's @code{sleep(3)} could return before the specified interval
33969 if the calling thread receives a signal; in that case,
33970 @code{sys-sleep} automatically restarts @code{sleep(3)} again with
33971 remaining time interval
33972 (after invoking Scheme signal handlers if there's any) by default.
33973 So you can count on the thread does sleep at least the specified
33974 amount of time.
33975
33976 If you do want @code{sys-sleep} to return prematurely upon receiving
33977 a signal, you can give a true value to an optional argument @var{no-retry}.
33978
33979 The reason that we retries by default is that Gauche's GC may use
33980 signals to synchronize between threads. If GC is invoked by one thread
33981 While another thread is sleeping on @code{sleep(3)}, it may return
33982 prematurely. It could happen often if other threads allocate a lot,
33983 which could make @code{sys-sleep} unreliable.
33984
33985 Returns zero if it sleeps well (which is always the case if @var{no-retry}
33986 is false), or the number of unslept seconds if it is woke up by a signal.
33987 @c JP
33988 指定された秒数が経過するまで、呼び出したスレッドを一時停止します。
33989
33990 libcの@code{sleep(3)}は、シグナルを受けると指定時間経過前であっても
33991 戻ってきます。その場合@code{sys-sleep}はデフォルトで、(Schemeのシグナルハンドラが
33992 あればそれを呼び出した後)残り時間を引数にして再び@code{sleep(3)}を呼び出します。
33993 従って@code{sys-sleep}を呼び出したスレッドは、少なくとも指定した時間、
33994 眠れることが保証されます。
33995
33996 もし@code{sys-sleep}がシグナルを受けた場合にすぐ戻ってきてほしければ、
33997 省略可能引数@code{no-retry}に真の値を渡してください。
33998
33999 デフォルトで@code{sleep(3)}を再呼び出しする理由は、GaucheのGCが
34000 スレッド間同期にシグナルを使う場合があるからです。
34001 もし一つのスレッドが@code{sys-sleep}で待っている間にもうひとつのスレッドが
34002 GCをトリガすると、@code{sys-sleep}が時間経過前に戻ってくる可能性があります。
34003 他のスレッドがたくさんアロケートする場合、@code{sys-sleep}はすぐに
34004 戻ってきてしまい、信頼できなくなるかもしれません。
34005
34006 指定時間が満了した場合(@var{no-retry}が偽であれば常にそうです)、
34007 @code{sys-sleep}は0を返し、
34008 シグナルによって一時停止が解除された場合は、満了までの秒数を返します。
34009 @c COMMON
34010
34011 @c EN
34012 To be portable across POSIX implementation, keep @var{seconds} less than
34013 65536.
34014 @c JP
34015 POSIX実装間でポータブルにするためには、@var{seconds}を65536より小さく保って
34016 下さい。
34017 @c COMMON
34018
34019 @c EN
34020 Some systems may be using @code{alarm(2)} to implement @code{sleep(3)},
34021 so you shouldn't mix @code{sys-sleep} and @code{sys-alarm}.
34022 @c JP
34023 システムによっては@code{sleep(3)}の実装に@code{alarm(2)}を用いている可能性があるので、
34024 @code{sys-sleep}と@code{sys-alarm}を混ぜて使うことはおすすめしません。
34025 @c COMMON
34026 @end defun
34027
34028 @defun sys-nanosleep nanoseconds :optional (no-retry #f)
34029 [POSIX]
34030 @c EN
34031 Suspends the calling thread until the specified number of nanoseconds elapses.
34032 The argument @var{nanoseconds} can be
34033 a @code{<time>} object (@pxref{Time}), or a real number.
34034
34035 The system's @code{nanosleep(2)} could return before the specified interval
34036 if the calling thread receives a signal; in that case,
34037 @code{sys-nanosleep} automatically restarts @code{nanosleep(2)} again with
34038 remaining time interval
34039 (after invoking Scheme signal handlers if there's any) by default.
34040 So you can count on the thread does sleep at least the specified
34041 amount of time.
34042
34043 The reason that we retries by default is that Gauche's GC may use
34044 signals to synchronize between threads. If GC is invoked by one thread
34045 while another thread is sleeping on @code{nanosleep(2)}, it may return
34046 prematurely. It could happen often if other threads allocate a lot,
34047 which could make @code{sys-nanosleep} unreliable.
34048
34049 Returns @code{#f} if @var{nanoseconds} elapsed (which is always
34050 the case if @code{no-retry} is @code{#f}),
34051 or a @code{<time>}
34052 object that indicates the remaining time if @code{sys-nanosleep}
34053 is interrupted by a signal.
34054 @c JP
34055 指定されたナノ秒が経過するまで、呼び出したスレッドを一時停止します。
34056 引数@var{nanoseconds}は@code{<time>}オブジェクト(@ref{Time}参照)か
34057 実数です。
34058
34059 システムの@code{nanosleep(2)}は、シグナルを受けると指定時間経過前であっても
34060 戻ってきますが、@code{sys-nanosleep}はデフォルトで、(Schemeのシグナルハンドラが
34061 あればそれを呼び出した後)残り時間を引数にして再び@code{nanosleep(2)}を呼び出します。
34062 従って@code{sys-nanosleep}を呼び出したスレッドは、少なくとも指定した時間、
34063 眠れることが保証されます。
34064
34065 もし@code{sys-nanosleep}がシグナルを受けた場合にすぐ戻ってきてほしければ、
34066 省略可能引数@code{no-retry}に真の値を渡してください。
34067
34068 デフォルトで@code{nanosleep(2)}を再呼び出しする理由は、GaucheのGCが
34069 スレッド間同期にシグナルを使う場合があるからです。
34070 もし一つのスレッドが@code{sys-nanosleep}で待っている間にもうひとつのスレッドが
34071 GCをトリガすると、@code{sys-nanosleep}が時間経過前に戻ってくる可能性があります。
34072 他のスレッドがたくさんアロケートする場合、@code{sys-nanosleep}はすぐに
34073 戻ってきてしまい、信頼できなくなるかもしれません。
34074
34075 @var{nanoseconds}が経過した場合の返り値は@code{#f}です。
34076 @code{no-retry}が偽であれば常にそうなります。
34077 @code{sys-nanosleep}がシグナルによって割り込まれた場合は、
34078 残りの時間を表す@code{<time>}オブジェクトを返します。
34079 @c COMMON
34080
34081 @example
34082 ;@r{wait for 0.5 sec}
34083 (sys-nanosleep 500000000)
34084
34085 ;@r{wait for 1.3 sec}
34086 (sys-nanosleep (make <time> :second 1 :nanosecond 300000000))
34087 @end example
34088
34089 @c EN
34090 Note: On Windows native platforms, this function is emulated using
34091 @code{Sleep}. The argument is rounded up to millisecond resolution,
34092 and it won't be interrupted by a signal.
34093 @c JP
34094 Windowsネイティブ環境では、この関数は@code{Sleep}によってエミュレートされます。
34095 引数はミリ秒の単位に切り上げられます。またシグナルによって中断されることはありません。
34096 @c COMMON
34097 @end defun
34098
34099 @defun sys-random
34100 @defunx sys-srandom seed
34101 @c EN
34102 A pseudo random number generator.
34103 @code{sys-random} returns a random number between 0 and a positive
34104 integer @var{rand_max}, inclusive. This is a straightforward
34105 interface to @code{random(3)}. If the underlying system doesn't have
34106 @code{random(3)}, @code{lrand48(3)} is used.
34107 @c JP
34108 擬似的な乱数ジェネレータです。
34109 @code{sys-random}は0から@var{rand_max}(それ自体を含む)までの間で乱数を
34110 返します。これは@code{random(3)}への直接的なインターフェースです。
34111 システムに@code{random(3)}がない場合、@code{lrand48(3)}が使われます。
34112 @c COMMON
34113
34114 @c EN
34115 @code{sys-srandom} sets the seed of the random number generator.
34116 It uses either @code{srandom(3)} or @code{srand48(3)}, depending on
34117 the system.
34118 @c JP
34119 @code{sys-srandom}は乱数ジェネレータの種をセットします。
34120 システムによって、@code{srandom(3)}か@code{srand48(3)}を使います。
34121 @c COMMON
34122
34123 @c EN
34124 The intention of these functions are to provide an off-the-stock handy
34125 random number generator (RNG) for applications that doesn't
34126 sensitive to the quality and/or speed of RNG. For serious statistics
34127 analysis, use Mersenne Twister RNG in @code{math.mt-random}
34128 module (@pxref{Mersenne-Twister random number generator}).
34129 @c JP
34130 これらの関数の意図は、乱数ジェネレータ(RNG; random number generator)の
34131 品質や速度を気にしないアプリケーションに、簡便なRNGを提供することです。
34132 本格的な統計分析には、@code{math.mt-random}モジュールのMersenne Twister RNGを
34133 使って下さい(@ref{Mersenne-Twister random number generator}参照)。
34134 @c COMMON
34135 @end defun
34136
34137 @defvar RAND_MAX
34138 @c EN
34139 Bound to a positive integer that @code{sys-random} may return.
34140 @c JP
34141 @code{sys-random}が返す正の整数に束縛されます。
34142 @c COMMON
34143 @end defvar
34144
34145 @defun sys-get-osfhandle port-or-fd
34146 [Windows]
34147 @c EN
34148 This procedure is only available on Windows native platforms.
34149 Returns a Windows file handle associated to the given port or
34150 integer file descriptor. Throws an error if the given argument
34151 does not have associated file handle.
34152 @c JP
34153 この手続きはWindowsネイティブ版だけにあります。
34154 与えられたポートまたは整数のファイルディスクリプタに対応する
34155 Windowsファイルハンドルを返します。引数がファイルハンドルに
34156 対応していなかった場合はエラーが投げられます。
34157 @c COMMON
34158 @end defun
34159
34160
34161 @c ----------------------------------------------------------------------
34162 @node Development helper API, , System interface, Core library
34163 @section Development helper API
34164 @c NODE 開発補助API
34165
34166 @c EN
34167 Gauche has some basic built-in APIs to help developers
34168 to analyze the program.
34169 @c JP
34170 Gauche には開発者がプログラムを解析するための基本的な組込みAPIがあります。
34171 @c COMMON
34172
34173 @menu
34174 * Debugging aid::
34175 * Profiler API::
34176 @end menu
34177
34178 @node Debugging aid, Profiler API, Development helper API, Development helper API
34179 @subsection Debugging aid
34180 @c NODE デバッグ補助
34181
34182 @defmac debug-print expr
34183 @c EN
34184 This macro prints @var{expr} in a source form, then evaluates it,
34185 then prints out the result(s), and returns them.
34186 @c JP
34187 このマクロは@var{expr}をそのフォームのまま印字してから、その式を評価し、
34188 評価の結果を印字し、その値を返します。
34189 @c COMMON
34190
34191 @c EN
34192 The output goes to the current trace port
34193 (@pxref{Common port operations}).
34194 @c JP
34195 出力は現在のトレース出力ポート (@code{current-trace-port})
34196 に行きます (@ref{Common port operations}参照)。
34197 @c COMMON
34198
34199 @c EN
34200 The special reader syntax @code{#?=@var{expr}} is expanded into
34201 @code{(debug-print @var{expr})}. See @ref{Debugging}, for the
34202 details.
34203 @c JP
34204 特殊リーダー構文 @code{#?=@var{expr}} は
34205 @code{(debug-print @var{expr})} に展開されます。
34206 詳細については @ref{Debugging} を参照してください。
34207 @c COMMON
34208 @end defmac
34209
34210 @deffn {Parameter} debug-print-width
34211 @c EN
34212 This parameter specifies the maximum width of information to be
34213 printed by @code{debug-print}. If the information takes more
34214 columns than the value of this parameter, it is truncated.
34215 @c JP
34216 このパラメータは@code{debug-print}が印字する情報の最大幅を指定するもの
34217 です。このパラメータが保持する値よりも大きいカラム数の情報は丸められま
34218 す。
34219 @c COMMON
34220
34221 @c EN
34222 To show all the information, set @code{#f} to this parameter.
34223 @c JP
34224 すべての情報を表示したければ、このパラメータに@code{#f}を設定してくだ
34225 さい。
34226 @c COMMON
34227 @end deffn
34228
34229 @defmac debug-funcall (proc arg @dots{})
34230 @c EN
34231 This macro prints the value of @var{arg}s right before calling
34232 @var{proc} and the result(s) of the call afterwards.
34233 @c JP
34234 このマクロは@var{proc}を呼び出す直前に全ての@var{arg}の値を表示し、
34235 そして@var{proc}の呼び出し後に全ての戻り値を表示します。
34236 @c COMMON
34237
34238 @c EN
34239 The output goes to the current trace port
34240 (@pxref{Common port operations}).
34241 @c JP
34242 出力は現在のトレース出力ポート (@code{current-trace-port})
34243 に行きます (@ref{Common port operations}参照)。
34244 @c COMMON
34245
34246 @c EN
34247 The special reader syntax @code{#?,@var{expr}} is expanded into
34248 @code{(debug-funcall @var{expr})}. See @ref{Debugging}, for the
34249 details.
34250 @c JP
34251 特別なリーダ構文 @code{#?,@var{expr}} は @code{(debug-funcall @var{expr})}
34252 に展開されます。詳しくは @ref{Debugging} を参照してください。
34253 @c COMMON
34254 @end defmac
34255
34256 @defmac debug-print-conditionally test expr
34257 @defmacx debug-funcall-conditionally test (proc arg @dots{})
34258 @c EN
34259 Works like @code{debug-print} and @code{debug-funcall}, but
34260 prints out the debug info ony when @var{test} evaluates to true.
34261
34262 These are functionally equivalent to the following code:
34263 @c JP
34264 @code{debug-print}および@code{debug-funcall}のように動作しますが、
34265 @var{test}が真の値に評価された時のみデバッグ出力を表示します。
34266
34267 これらは次のコードと機能的には同じです。
34268 @c COMMON
34269
34270 @example
34271 (if test
34272 (debug-print expr)
34273 expr)
34274
34275 (if test
34276 (debug-funcall (proc arg @dots{}))
34277 (proc arg @dots{}))
34278 @end example
34279
34280 @c EN
34281 The special reader syntax @code{#??=@var{test} @var{expr}} and
34282 @code{#??,@var{test} @var{expr}} are expanded into
34283 @code{(debug-print-conditionally @var{test} @var{expr})} and
34284 @code{(debug-funcall-conditionally @var{test} @var{expr})}, respectively.
34285 See @ref{Debugging}, for the details.
34286 @c JP
34287 特別なリーダ構文 @code{#??=@var{test} @var{expr}} および
34288 @code{#??,@var{test} @var{expr}} はそれぞれ
34289 @code{(debug-print-conditionally @var{test} @var{expr})} と
34290 @code{(debug-funcall-conditionally @var{test} @var{expr})} に展開されます。
34291 詳しくは @ref{Debugging} を参照してください。
34292 @c COMMON
34293 @end defmac
34294
34295 @defun debug-source-info obj
34296 @c EN
34297 Retrieves source information attached to @var{obj}.
34298 The source information is returned as a list of source file name
34299 and an integer line number. If no source information is available
34300 in @var{obj}, @code{#f} is returned.
34301 @c JP
34302 @var{obj}に付加されているソースコード情報を検索します。ソースコード情
34303 報とはソースコードファイル名と行番号のリストです。@var{obj}にソースコー
34304 ド情報が付加されていなければ、@code{#f}が返されます。
34305 @c COMMON
34306 @end defun
34307
34308 @defun source-code closure
34309 @c EN
34310 Returns the source code of @var{closure}, if available.
34311 Otherwise, @code{#f} is returned.
34312
34313 Currently, only the code that's directly read from Scheme source
34314 is available; if the Scheme code is precompiled, the source code
34315 isn't saved. It may be changed in future.
34316 @c JP
34317 @var{closure}のソースコードが取り出せればそれを返します。そうでなければ
34318 @code{#f}を返します。
34319
34320 現在、Schemeソースから直接読み込まれた場合のみ、ソースコードが取り出せます。
34321 プリコンパイルされたSchemeコードではソースコードは保存されません。
34322 将来は変更されるかもしれません。
34323 @c COMMON
34324 @end defun
34325
34326 @defun source-location procedure
34327 @c EN
34328 Returns the location (a list of filename and line number) where @var{procedure}
34329 is defined, if available. Otherwise, @code{#f} is returned.
34330 @c JP
34331 @var{procedure}が定義された場所(ファイル名と行番号)がわかればそれをリストにして
34332 返します。わからなければ@code{#f}が返ります。
34333 @c COMMON
34334
34335 @example
34336 gosh> (use rfc.http)
34337 gosh> (source-location http-get)
34338 ("/usr/share/gauche-0.9/0.9.5/lib/rfc/http.scm" 443)
34339 @end example
34340
34341 @c EN
34342 If @var{procedure} is a subr or a precompiled closure, the filename
34343 may not be a complete pathname.
34344 @c JP
34345 @var{procedure}がsubrやプリコンパイルされた手続きの場合、
34346 ファイル名は完全なパスではないかもしれません。
34347 @c COMMON
34348
34349 @example
34350 gosh> (source-location cons)
34351 ("liblist.scm" 46)
34352 @end example
34353 @end defun
34354
34355 @defun disasm closure
34356 @c EN
34357 Disassemble the compiled body of @var{closure} and print it.
34358 It may not be very useful unless you're tracking a compiler bug,
34359 or trying to tune the program to its limit.
34360 @c JP
34361 コンパイル済の@var{closure}の本体部分をディスアセンブルして印字します。
34362 これはコンパイラのバグをなんとかしようという場合か、限界まで
34363 チューンしようとしないかぎりは役には立たないでしょう。
34364 @c COMMON
34365
34366 @c EN
34367 If you're reading the disassembler output, keep in mind that
34368 the compiled code vector may have some dead code; they are produced
34369 by the jump optimization, but the compiler doesn't bother to eliminate
34370 them.
34371 @c JP
34372 このディスアセンブラの出力結果を読む場合には、コンパイルされたコードに
34373 はデッドコードが含まれている可能性があることを心してください。デッドコー
34374 ドはジャンプ最適化によって生成されるのですが、コンパイラはこれをわざわ
34375 ざ除去することはしていません。
34376 @c COMMON
34377 @end defun
34378
34379 @defun debug-label obj
34380 @c EN
34381 This returns a string that is quasi-unique to an object @var{obj}.
34382 ``Quasi-unique'' means the label is unique to the @var{obj}---
34383 the same (@code{eq?}) objs returns the same string, and
34384 if two objs return different string they aren't @code{eq?} to each other---
34385 @emph{until next GC occurs}.
34386
34387 This is mostly for printing out anonymous objects that doesn't
34388 have any other good way to distinguish each other.
34389 Note that uniqueness isn't guaranteed
34390 across GCs, you shouldn't use the returned value as the key to identify
34391 the objects.
34392 @c JP
34393 この手続きは、@var{obj}についてほぼユニークな文字列を返します。
34394 「ほぼ」ユニークというのは、
34395 @emph{次のGCが起きるまでは}、オブジェクトが同じ文字列を返したら@code{eq?}であり、
34396 また@code{eq?}でないオブジェクト同士は異なる文字列を返すということです。
34397
34398 この文字列は、他に区別の手段がないような無名オブジェクトを印字する時に
34399 使われることを想定しています。GCをまたいだ唯一性は保証されないので、
34400 この手続きが返す文字列をオブジェクトを同定するキーとして使ってはいけません。
34401 @c COMMON
34402 @end defun
34403
34404
34405 @node Profiler API, , Debugging aid, Development helper API
34406 @subsection Profiler API
34407 @c NODE プロファイラAPI
34408
34409 @c EN
34410 These are the functions to control Gauche's built-in profiler.
34411 See @ref{Using profiler} for the explanation of the profiler.
34412 @c JP
34413 ここに挙げている関数は、Gauche の組込みプロファイラを制御するためのも
34414 のです。プロファイラの説明については @ref{Using profiler} を参照してく
34415 ださい。
34416 @c COMMON
34417
34418 @c EN
34419 Note that the profiler isn't guaranteed to work correctly yet in
34420 multi-threaded program, since the interaction between @code{setitimer}
34421 and threads are platform-dependent.
34422 @c JP
34423 注意:現時点ではプロファイラはマルチスレッドプログラムでは正しく動作する
34424 保証はありません。@code{setitimer}とスレッドの相互作用が
34425 プラットフォーム依存だからです。
34426 @c COMMON
34427
34428 @defun profiler-start
34429 @c EN
34430 Starts the sampling profiler. If the profiler is already started,
34431 nothing is done.
34432 @c JP
34433 標本化プロファイラを始動します。プロファイラが既に始動しいる場合
34434 には何もしません。
34435 @c COMMON
34436 @end defun
34437
34438 @defun profiler-stop
34439 @c EN
34440 Stop the sampling profiler, and save the sampled data into
34441 the internal structure. If there are already saved sampled data,
34442 the newly obtained data is added to it.
34443 If the profiler isn't running, nothing is done.
34444 @c JP
34445 標本化プロファイラを停止し、標本データを内部データ構
34446 造に保存します。既に標本データが保存されていた場合には、新
34447 しく収集された標本データがその後に追加されます。もしプロファイラが動いてい
34448 なかった場合には何もしません。
34449 @c COMMON
34450 @end defun
34451
34452 @defun profiler-reset
34453 @c EN
34454 Stop the profiler if it is running. Then discard the
34455 saved sampled data.
34456 @c JP
34457 もしプロファイラが動いていればそれを停止し、保存されていた標本データ
34458 を破棄します。
34459
34460 @c COMMON
34461 @end defun
34462
34463 @defun profiler-show :key sort-by max-rows
34464 @c EN
34465 Show the saved sampled data.
34466 @c JP
34467 格納されている標本データを表示します。
34468 @c COMMON
34469
34470 @c EN
34471 The keyword argument @var{sort-by} may be one of the symbols
34472 @code{time}, @code{count}, or @code{time-per-call}, to specify
34473 how the result should be sorted. The default is @code{time}.
34474 @c JP
34475 キーワード引数 @var{sort-by} は指定する場合は、@code{time}、
34476 @code{count} または @code{time-per-call} のどれかひとつです。
34477 これで結果の整列順を指定します。デフォルトでは @code{time}です。
34478 @c COMMON
34479
34480 @c EN
34481 The keyword argument @var{max-rows} specifies the max number of
34482 rows to be shown. If it is @code{#f}, all the data is shown.
34483 @c JP
34484 キーワード引数 @var{max-rows} では結果を表示する最大行数を指定します。
34485 この値が @code{#f} であればすべてのデータが表示されます。
34486 @c COMMON
34487 @end defun
34488
34489 @defun with-profiler thunk
34490 @c EN
34491 A convenience procedure.
34492 Call @var{thunk} with the sampling profiler running,
34493 and show the result to the current output port afterwards.
34494 Returns value(s) thunk yields.
34495 The profiler is reset after the result is shown.
34496
34497 You can't nest this construct; the innermost @code{with-profiler}
34498 will reset the profiler, invalidates any outer @code{with-profiler}.
34499 @c JP
34500 手軽にプロファイリングするための手続きです。
34501 プロファイラをonにして@var{thunk}を呼び出し、結果をcurrent output port
34502 に出力します。@var{thunk}の戻り値が式の戻り値となります。
34503 結果表示後、プロファイラはリセットされます。
34504
34505 この手続きをネストすることはできません。最も内側の@code{with-profiler}が
34506 結果をリセットしてしまうので、外側の@code{with-profiler}に全ての情報が渡らないからです。
34507 @c COMMON
34508 @end defun
34509
34510
34511
34512 @c Local variables:
34513 @c mode: texinfo
34514 @c coding: utf-8
34515 @c end: