Add SCM_INUM1 to numbers.h, and make use of it and SCM_INUM0 in numbers.c
[bpt/guile.git] / doc / ref / api-data.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @node Simple Data Types
8 @section Simple Generic Data Types
9
10 This chapter describes those of Guile's simple data types which are
11 primarily used for their role as items of generic data. By
12 @dfn{simple} we mean data types that are not primarily used as
13 containers to hold other data --- i.e.@: pairs, lists, vectors and so on.
14 For the documentation of such @dfn{compound} data types, see
15 @ref{Compound Data Types}.
16
17 @c One of the great strengths of Scheme is that there is no straightforward
18 @c distinction between ``data'' and ``functionality''. For example,
19 @c Guile's support for dynamic linking could be described:
20
21 @c @itemize @bullet
22 @c @item
23 @c either in a ``data-centric'' way, as the behaviour and properties of the
24 @c ``dynamically linked object'' data type, and the operations that may be
25 @c applied to instances of this type
26
27 @c @item
28 @c or in a ``functionality-centric'' way, as the set of procedures that
29 @c constitute Guile's support for dynamic linking, in the context of the
30 @c module system.
31 @c @end itemize
32
33 @c The contents of this chapter are, therefore, a matter of judgment. By
34 @c @dfn{generic}, we mean to select those data types whose typical use as
35 @c @emph{data} in a wide variety of programming contexts is more important
36 @c than their use in the implementation of a particular piece of
37 @c @emph{functionality}. The last section of this chapter provides
38 @c references for all the data types that are documented not here but in a
39 @c ``functionality-centric'' way elsewhere in the manual.
40
41 @menu
42 * Booleans:: True/false values.
43 * Numbers:: Numerical data types.
44 * Characters:: Single characters.
45 * Character Sets:: Sets of characters.
46 * Strings:: Sequences of characters.
47 * Bytevectors:: Sequences of bytes.
48 * Symbols:: Symbols.
49 * Keywords:: Self-quoting, customizable display keywords.
50 * Other Types:: "Functionality-centric" data types.
51 @end menu
52
53
54 @node Booleans
55 @subsection Booleans
56 @tpindex Booleans
57
58 The two boolean values are @code{#t} for true and @code{#f} for false.
59
60 Boolean values are returned by predicate procedures, such as the general
61 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
62 (@pxref{Equality}) and numerical and string comparison operators like
63 @code{string=?} (@pxref{String Comparison}) and @code{<=}
64 (@pxref{Comparison}).
65
66 @lisp
67 (<= 3 8)
68 @result{} #t
69
70 (<= 3 -3)
71 @result{} #f
72
73 (equal? "house" "houses")
74 @result{} #f
75
76 (eq? #f #f)
77 @result{}
78 #t
79 @end lisp
80
81 In test condition contexts like @code{if} and @code{cond} (@pxref{if
82 cond case}), where a group of subexpressions will be evaluated only if a
83 @var{condition} expression evaluates to ``true'', ``true'' means any
84 value at all except @code{#f}.
85
86 @lisp
87 (if #t "yes" "no")
88 @result{} "yes"
89
90 (if 0 "yes" "no")
91 @result{} "yes"
92
93 (if #f "yes" "no")
94 @result{} "no"
95 @end lisp
96
97 A result of this asymmetry is that typical Scheme source code more often
98 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
99 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
100 not necessary to represent an @code{if} or @code{cond} true value.
101
102 It is important to note that @code{#f} is @strong{not} equivalent to any
103 other Scheme value. In particular, @code{#f} is not the same as the
104 number 0 (like in C and C++), and not the same as the ``empty list''
105 (like in some Lisp dialects).
106
107 In C, the two Scheme boolean values are available as the two constants
108 @code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
109 Care must be taken with the false value @code{SCM_BOOL_F}: it is not
110 false when used in C conditionals. In order to test for it, use
111 @code{scm_is_false} or @code{scm_is_true}.
112
113 @rnindex not
114 @deffn {Scheme Procedure} not x
115 @deffnx {C Function} scm_not (x)
116 Return @code{#t} if @var{x} is @code{#f}, else return @code{#f}.
117 @end deffn
118
119 @rnindex boolean?
120 @deffn {Scheme Procedure} boolean? obj
121 @deffnx {C Function} scm_boolean_p (obj)
122 Return @code{#t} if @var{obj} is either @code{#t} or @code{#f}, else
123 return @code{#f}.
124 @end deffn
125
126 @deftypevr {C Macro} SCM SCM_BOOL_T
127 The @code{SCM} representation of the Scheme object @code{#t}.
128 @end deftypevr
129
130 @deftypevr {C Macro} SCM SCM_BOOL_F
131 The @code{SCM} representation of the Scheme object @code{#f}.
132 @end deftypevr
133
134 @deftypefn {C Function} int scm_is_true (SCM obj)
135 Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
136 @end deftypefn
137
138 @deftypefn {C Function} int scm_is_false (SCM obj)
139 Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
140 @end deftypefn
141
142 @deftypefn {C Function} int scm_is_bool (SCM obj)
143 Return @code{1} if @var{obj} is either @code{#t} or @code{#f}, else
144 return @code{0}.
145 @end deftypefn
146
147 @deftypefn {C Function} SCM scm_from_bool (int val)
148 Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
149 @end deftypefn
150
151 @deftypefn {C Function} int scm_to_bool (SCM val)
152 Return @code{1} if @var{val} is @code{SCM_BOOL_T}, return @code{0}
153 when @var{val} is @code{SCM_BOOL_F}, else signal a `wrong type' error.
154
155 You should probably use @code{scm_is_true} instead of this function
156 when you just want to test a @code{SCM} value for trueness.
157 @end deftypefn
158
159 @node Numbers
160 @subsection Numerical data types
161 @tpindex Numbers
162
163 Guile supports a rich ``tower'' of numerical types --- integer,
164 rational, real and complex --- and provides an extensive set of
165 mathematical and scientific functions for operating on numerical
166 data. This section of the manual documents those types and functions.
167
168 You may also find it illuminating to read R5RS's presentation of numbers
169 in Scheme, which is particularly clear and accessible: see
170 @ref{Numbers,,,r5rs,R5RS}.
171
172 @menu
173 * Numerical Tower:: Scheme's numerical "tower".
174 * Integers:: Whole numbers.
175 * Reals and Rationals:: Real and rational numbers.
176 * Complex Numbers:: Complex numbers.
177 * Exactness:: Exactness and inexactness.
178 * Number Syntax:: Read syntax for numerical data.
179 * Integer Operations:: Operations on integer values.
180 * Comparison:: Comparison predicates.
181 * Conversion:: Converting numbers to and from strings.
182 * Complex:: Complex number operations.
183 * Arithmetic:: Arithmetic functions.
184 * Scientific:: Scientific functions.
185 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
186 * Random:: Random number generation.
187 @end menu
188
189
190 @node Numerical Tower
191 @subsubsection Scheme's Numerical ``Tower''
192 @rnindex number?
193
194 Scheme's numerical ``tower'' consists of the following categories of
195 numbers:
196
197 @table @dfn
198 @item integers
199 Whole numbers, positive or negative; e.g.@: --5, 0, 18.
200
201 @item rationals
202 The set of numbers that can be expressed as @math{@var{p}/@var{q}}
203 where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
204 pi (an irrational number) doesn't. These include integers
205 (@math{@var{n}/1}).
206
207 @item real numbers
208 The set of numbers that describes all possible positions along a
209 one-dimensional line. This includes rationals as well as irrational
210 numbers.
211
212 @item complex numbers
213 The set of numbers that describes all possible positions in a two
214 dimensional space. This includes real as well as imaginary numbers
215 (@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
216 @var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
217 @minus{}1.)
218 @end table
219
220 It is called a tower because each category ``sits on'' the one that
221 follows it, in the sense that every integer is also a rational, every
222 rational is also real, and every real number is also a complex number
223 (but with zero imaginary part).
224
225 In addition to the classification into integers, rationals, reals and
226 complex numbers, Scheme also distinguishes between whether a number is
227 represented exactly or not. For example, the result of
228 @m{2\sin(\pi/4),2*sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)}, but Guile
229 can represent neither @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
230 Instead, it stores an inexact approximation, using the C type
231 @code{double}.
232
233 Guile can represent exact rationals of any magnitude, inexact
234 rationals that fit into a C @code{double}, and inexact complex numbers
235 with @code{double} real and imaginary parts.
236
237 The @code{number?} predicate may be applied to any Scheme value to
238 discover whether the value is any of the supported numerical types.
239
240 @deffn {Scheme Procedure} number? obj
241 @deffnx {C Function} scm_number_p (obj)
242 Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
243 @end deffn
244
245 For example:
246
247 @lisp
248 (number? 3)
249 @result{} #t
250
251 (number? "hello there!")
252 @result{} #f
253
254 (define pi 3.141592654)
255 (number? pi)
256 @result{} #t
257 @end lisp
258
259 @deftypefn {C Function} int scm_is_number (SCM obj)
260 This is equivalent to @code{scm_is_true (scm_number_p (obj))}.
261 @end deftypefn
262
263 The next few subsections document each of Guile's numerical data types
264 in detail.
265
266 @node Integers
267 @subsubsection Integers
268
269 @tpindex Integer numbers
270
271 @rnindex integer?
272
273 Integers are whole numbers, that is numbers with no fractional part,
274 such as 2, 83, and @minus{}3789.
275
276 Integers in Guile can be arbitrarily big, as shown by the following
277 example.
278
279 @lisp
280 (define (factorial n)
281 (let loop ((n n) (product 1))
282 (if (= n 0)
283 product
284 (loop (- n 1) (* product n)))))
285
286 (factorial 3)
287 @result{} 6
288
289 (factorial 20)
290 @result{} 2432902008176640000
291
292 (- (factorial 45))
293 @result{} -119622220865480194561963161495657715064383733760000000000
294 @end lisp
295
296 Readers whose background is in programming languages where integers are
297 limited by the need to fit into just 4 or 8 bytes of memory may find
298 this surprising, or suspect that Guile's representation of integers is
299 inefficient. In fact, Guile achieves a near optimal balance of
300 convenience and efficiency by using the host computer's native
301 representation of integers where possible, and a more general
302 representation where the required number does not fit in the native
303 form. Conversion between these two representations is automatic and
304 completely invisible to the Scheme level programmer.
305
306 C has a host of different integer types, and Guile offers a host of
307 functions to convert between them and the @code{SCM} representation.
308 For example, a C @code{int} can be handled with @code{scm_to_int} and
309 @code{scm_from_int}. Guile also defines a few C integer types of its
310 own, to help with differences between systems.
311
312 C integer types that are not covered can be handled with the generic
313 @code{scm_to_signed_integer} and @code{scm_from_signed_integer} for
314 signed types, or with @code{scm_to_unsigned_integer} and
315 @code{scm_from_unsigned_integer} for unsigned types.
316
317 Scheme integers can be exact and inexact. For example, a number
318 written as @code{3.0} with an explicit decimal-point is inexact, but
319 it is also an integer. The functions @code{integer?} and
320 @code{scm_is_integer} report true for such a number, but the functions
321 @code{scm_is_signed_integer} and @code{scm_is_unsigned_integer} only
322 allow exact integers and thus report false. Likewise, the conversion
323 functions like @code{scm_to_signed_integer} only accept exact
324 integers.
325
326 The motivation for this behavior is that the inexactness of a number
327 should not be lost silently. If you want to allow inexact integers,
328 you can explicitly insert a call to @code{inexact->exact} or to its C
329 equivalent @code{scm_inexact_to_exact}. (Only inexact integers will
330 be converted by this call into exact integers; inexact non-integers
331 will become exact fractions.)
332
333 @deffn {Scheme Procedure} integer? x
334 @deffnx {C Function} scm_integer_p (x)
335 Return @code{#t} if @var{x} is an exact or inexact integer number, else
336 @code{#f}.
337
338 @lisp
339 (integer? 487)
340 @result{} #t
341
342 (integer? 3.0)
343 @result{} #t
344
345 (integer? -3.4)
346 @result{} #f
347
348 (integer? +inf.0)
349 @result{} #t
350 @end lisp
351 @end deffn
352
353 @deftypefn {C Function} int scm_is_integer (SCM x)
354 This is equivalent to @code{scm_is_true (scm_integer_p (x))}.
355 @end deftypefn
356
357 @defvr {C Type} scm_t_int8
358 @defvrx {C Type} scm_t_uint8
359 @defvrx {C Type} scm_t_int16
360 @defvrx {C Type} scm_t_uint16
361 @defvrx {C Type} scm_t_int32
362 @defvrx {C Type} scm_t_uint32
363 @defvrx {C Type} scm_t_int64
364 @defvrx {C Type} scm_t_uint64
365 @defvrx {C Type} scm_t_intmax
366 @defvrx {C Type} scm_t_uintmax
367 The C types are equivalent to the corresponding ISO C types but are
368 defined on all platforms, with the exception of @code{scm_t_int64} and
369 @code{scm_t_uint64}, which are only defined when a 64-bit type is
370 available. For example, @code{scm_t_int8} is equivalent to
371 @code{int8_t}.
372
373 You can regard these definitions as a stop-gap measure until all
374 platforms provide these types. If you know that all the platforms
375 that you are interested in already provide these types, it is better
376 to use them directly instead of the types provided by Guile.
377 @end defvr
378
379 @deftypefn {C Function} int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
380 @deftypefnx {C Function} int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
381 Return @code{1} when @var{x} represents an exact integer that is
382 between @var{min} and @var{max}, inclusive.
383
384 These functions can be used to check whether a @code{SCM} value will
385 fit into a given range, such as the range of a given C integer type.
386 If you just want to convert a @code{SCM} value to a given C integer
387 type, use one of the conversion functions directly.
388 @end deftypefn
389
390 @deftypefn {C Function} scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
391 @deftypefnx {C Function} scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
392 When @var{x} represents an exact integer that is between @var{min} and
393 @var{max} inclusive, return that integer. Else signal an error,
394 either a `wrong-type' error when @var{x} is not an exact integer, or
395 an `out-of-range' error when it doesn't fit the given range.
396 @end deftypefn
397
398 @deftypefn {C Function} SCM scm_from_signed_integer (scm_t_intmax x)
399 @deftypefnx {C Function} SCM scm_from_unsigned_integer (scm_t_uintmax x)
400 Return the @code{SCM} value that represents the integer @var{x}. This
401 function will always succeed and will always return an exact number.
402 @end deftypefn
403
404 @deftypefn {C Function} char scm_to_char (SCM x)
405 @deftypefnx {C Function} {signed char} scm_to_schar (SCM x)
406 @deftypefnx {C Function} {unsigned char} scm_to_uchar (SCM x)
407 @deftypefnx {C Function} short scm_to_short (SCM x)
408 @deftypefnx {C Function} {unsigned short} scm_to_ushort (SCM x)
409 @deftypefnx {C Function} int scm_to_int (SCM x)
410 @deftypefnx {C Function} {unsigned int} scm_to_uint (SCM x)
411 @deftypefnx {C Function} long scm_to_long (SCM x)
412 @deftypefnx {C Function} {unsigned long} scm_to_ulong (SCM x)
413 @deftypefnx {C Function} {long long} scm_to_long_long (SCM x)
414 @deftypefnx {C Function} {unsigned long long} scm_to_ulong_long (SCM x)
415 @deftypefnx {C Function} size_t scm_to_size_t (SCM x)
416 @deftypefnx {C Function} ssize_t scm_to_ssize_t (SCM x)
417 @deftypefnx {C Function} scm_t_int8 scm_to_int8 (SCM x)
418 @deftypefnx {C Function} scm_t_uint8 scm_to_uint8 (SCM x)
419 @deftypefnx {C Function} scm_t_int16 scm_to_int16 (SCM x)
420 @deftypefnx {C Function} scm_t_uint16 scm_to_uint16 (SCM x)
421 @deftypefnx {C Function} scm_t_int32 scm_to_int32 (SCM x)
422 @deftypefnx {C Function} scm_t_uint32 scm_to_uint32 (SCM x)
423 @deftypefnx {C Function} scm_t_int64 scm_to_int64 (SCM x)
424 @deftypefnx {C Function} scm_t_uint64 scm_to_uint64 (SCM x)
425 @deftypefnx {C Function} scm_t_intmax scm_to_intmax (SCM x)
426 @deftypefnx {C Function} scm_t_uintmax scm_to_uintmax (SCM x)
427 When @var{x} represents an exact integer that fits into the indicated
428 C type, return that integer. Else signal an error, either a
429 `wrong-type' error when @var{x} is not an exact integer, or an
430 `out-of-range' error when it doesn't fit the given range.
431
432 The functions @code{scm_to_long_long}, @code{scm_to_ulong_long},
433 @code{scm_to_int64}, and @code{scm_to_uint64} are only available when
434 the corresponding types are.
435 @end deftypefn
436
437 @deftypefn {C Function} SCM scm_from_char (char x)
438 @deftypefnx {C Function} SCM scm_from_schar (signed char x)
439 @deftypefnx {C Function} SCM scm_from_uchar (unsigned char x)
440 @deftypefnx {C Function} SCM scm_from_short (short x)
441 @deftypefnx {C Function} SCM scm_from_ushort (unsigned short x)
442 @deftypefnx {C Function} SCM scm_from_int (int x)
443 @deftypefnx {C Function} SCM scm_from_uint (unsigned int x)
444 @deftypefnx {C Function} SCM scm_from_long (long x)
445 @deftypefnx {C Function} SCM scm_from_ulong (unsigned long x)
446 @deftypefnx {C Function} SCM scm_from_long_long (long long x)
447 @deftypefnx {C Function} SCM scm_from_ulong_long (unsigned long long x)
448 @deftypefnx {C Function} SCM scm_from_size_t (size_t x)
449 @deftypefnx {C Function} SCM scm_from_ssize_t (ssize_t x)
450 @deftypefnx {C Function} SCM scm_from_int8 (scm_t_int8 x)
451 @deftypefnx {C Function} SCM scm_from_uint8 (scm_t_uint8 x)
452 @deftypefnx {C Function} SCM scm_from_int16 (scm_t_int16 x)
453 @deftypefnx {C Function} SCM scm_from_uint16 (scm_t_uint16 x)
454 @deftypefnx {C Function} SCM scm_from_int32 (scm_t_int32 x)
455 @deftypefnx {C Function} SCM scm_from_uint32 (scm_t_uint32 x)
456 @deftypefnx {C Function} SCM scm_from_int64 (scm_t_int64 x)
457 @deftypefnx {C Function} SCM scm_from_uint64 (scm_t_uint64 x)
458 @deftypefnx {C Function} SCM scm_from_intmax (scm_t_intmax x)
459 @deftypefnx {C Function} SCM scm_from_uintmax (scm_t_uintmax x)
460 Return the @code{SCM} value that represents the integer @var{x}.
461 These functions will always succeed and will always return an exact
462 number.
463 @end deftypefn
464
465 @deftypefn {C Function} void scm_to_mpz (SCM val, mpz_t rop)
466 Assign @var{val} to the multiple precision integer @var{rop}.
467 @var{val} must be an exact integer, otherwise an error will be
468 signalled. @var{rop} must have been initialized with @code{mpz_init}
469 before this function is called. When @var{rop} is no longer needed
470 the occupied space must be freed with @code{mpz_clear}.
471 @xref{Initializing Integers,,, gmp, GNU MP Manual}, for details.
472 @end deftypefn
473
474 @deftypefn {C Function} SCM scm_from_mpz (mpz_t val)
475 Return the @code{SCM} value that represents @var{val}.
476 @end deftypefn
477
478 @node Reals and Rationals
479 @subsubsection Real and Rational Numbers
480 @tpindex Real numbers
481 @tpindex Rational numbers
482
483 @rnindex real?
484 @rnindex rational?
485
486 Mathematically, the real numbers are the set of numbers that describe
487 all possible points along a continuous, infinite, one-dimensional line.
488 The rational numbers are the set of all numbers that can be written as
489 fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
490 All rational numbers are also real, but there are real numbers that
491 are not rational, for example @m{\sqrt2, the square root of 2}, and
492 @m{\pi,pi}.
493
494 Guile can represent both exact and inexact rational numbers, but it
495 can not represent irrational numbers. Exact rationals are represented
496 by storing the numerator and denominator as two exact integers.
497 Inexact rationals are stored as floating point numbers using the C
498 type @code{double}.
499
500 Exact rationals are written as a fraction of integers. There must be
501 no whitespace around the slash:
502
503 @lisp
504 1/2
505 -22/7
506 @end lisp
507
508 Even though the actual encoding of inexact rationals is in binary, it
509 may be helpful to think of it as a decimal number with a limited
510 number of significant figures and a decimal point somewhere, since
511 this corresponds to the standard notation for non-whole numbers. For
512 example:
513
514 @lisp
515 0.34
516 -0.00000142857931198
517 -5648394822220000000000.0
518 4.0
519 @end lisp
520
521 The limited precision of Guile's encoding means that any ``real'' number
522 in Guile can be written in a rational form, by multiplying and then dividing
523 by sufficient powers of 10 (or in fact, 2). For example,
524 @samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
525 100000000000000000. In Guile's current incarnation, therefore, the
526 @code{rational?} and @code{real?} predicates are equivalent.
527
528
529 Dividing by an exact zero leads to a error message, as one might
530 expect. However, dividing by an inexact zero does not produce an
531 error. Instead, the result of the division is either plus or minus
532 infinity, depending on the sign of the divided number.
533
534 The infinities are written @samp{+inf.0} and @samp{-inf.0},
535 respectively. This syntax is also recognized by @code{read} as an
536 extension to the usual Scheme syntax. The infinities are considered to
537 be inexact, non-integer values.
538
539 Dividing zero by zero yields something that is not a number at all:
540 @samp{+nan.0}. This is the special `not a number' value.
541
542 On platforms that follow @acronym{IEEE} 754 for their floating point
543 arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
544 are implemented using the corresponding @acronym{IEEE} 754 values.
545 They behave in arithmetic operations like @acronym{IEEE} 754 describes
546 it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
547
548 While @samp{+nan.0} is not @code{=} to itself, it is @code{eqv?} to
549 itself.
550
551 To test for the special values, use the functions @code{inf?} and
552 @code{nan?}.
553
554 @deffn {Scheme Procedure} real? obj
555 @deffnx {C Function} scm_real_p (obj)
556 Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
557 that the sets of integer and rational values form subsets of the set
558 of real numbers, so the predicate will also be fulfilled if @var{obj}
559 is an integer number or a rational number.
560 @end deffn
561
562 @deffn {Scheme Procedure} rational? x
563 @deffnx {C Function} scm_rational_p (x)
564 Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
565 Note that the set of integer values forms a subset of the set of
566 rational numbers, i. e. the predicate will also be fulfilled if
567 @var{x} is an integer number.
568
569 Since Guile can not represent irrational numbers, every number
570 satisfying @code{real?} also satisfies @code{rational?} in Guile.
571 @end deffn
572
573 @deffn {Scheme Procedure} rationalize x eps
574 @deffnx {C Function} scm_rationalize (x, eps)
575 Returns the @emph{simplest} rational number differing
576 from @var{x} by no more than @var{eps}.
577
578 As required by @acronym{R5RS}, @code{rationalize} only returns an
579 exact result when both its arguments are exact. Thus, you might need
580 to use @code{inexact->exact} on the arguments.
581
582 @lisp
583 (rationalize (inexact->exact 1.2) 1/100)
584 @result{} 6/5
585 @end lisp
586
587 @end deffn
588
589 @deffn {Scheme Procedure} inf? x
590 @deffnx {C Function} scm_inf_p (x)
591 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
592 @code{#f} otherwise.
593 @end deffn
594
595 @deffn {Scheme Procedure} nan? x
596 @deffnx {C Function} scm_nan_p (x)
597 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
598 @end deffn
599
600 @deffn {Scheme Procedure} nan
601 @deffnx {C Function} scm_nan ()
602 Return NaN.
603 @end deffn
604
605 @deffn {Scheme Procedure} inf
606 @deffnx {C Function} scm_inf ()
607 Return Inf.
608 @end deffn
609
610 @deffn {Scheme Procedure} numerator x
611 @deffnx {C Function} scm_numerator (x)
612 Return the numerator of the rational number @var{x}.
613 @end deffn
614
615 @deffn {Scheme Procedure} denominator x
616 @deffnx {C Function} scm_denominator (x)
617 Return the denominator of the rational number @var{x}.
618 @end deffn
619
620 @deftypefn {C Function} int scm_is_real (SCM val)
621 @deftypefnx {C Function} int scm_is_rational (SCM val)
622 Equivalent to @code{scm_is_true (scm_real_p (val))} and
623 @code{scm_is_true (scm_rational_p (val))}, respectively.
624 @end deftypefn
625
626 @deftypefn {C Function} double scm_to_double (SCM val)
627 Returns the number closest to @var{val} that is representable as a
628 @code{double}. Returns infinity for a @var{val} that is too large in
629 magnitude. The argument @var{val} must be a real number.
630 @end deftypefn
631
632 @deftypefn {C Function} SCM scm_from_double (double val)
633 Return the @code{SCM} value that represents @var{val}. The returned
634 value is inexact according to the predicate @code{inexact?}, but it
635 will be exactly equal to @var{val}.
636 @end deftypefn
637
638 @node Complex Numbers
639 @subsubsection Complex Numbers
640 @tpindex Complex numbers
641
642 @rnindex complex?
643
644 Complex numbers are the set of numbers that describe all possible points
645 in a two-dimensional space. The two coordinates of a particular point
646 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
647 the complex number that describes that point.
648
649 In Guile, complex numbers are written in rectangular form as the sum of
650 their real and imaginary parts, using the symbol @code{i} to indicate
651 the imaginary part.
652
653 @lisp
654 3+4i
655 @result{}
656 3.0+4.0i
657
658 (* 3-8i 2.3+0.3i)
659 @result{}
660 9.3-17.5i
661 @end lisp
662
663 @cindex polar form
664 @noindent
665 Polar form can also be used, with an @samp{@@} between magnitude and
666 angle,
667
668 @lisp
669 1@@3.141592 @result{} -1.0 (approx)
670 -1@@1.57079 @result{} 0.0-1.0i (approx)
671 @end lisp
672
673 Guile represents a complex number with a non-zero imaginary part as a
674 pair of inexact rationals, so the real and imaginary parts of a
675 complex number have the same properties of inexactness and limited
676 precision as single inexact rational numbers. Guile can not represent
677 exact complex numbers with non-zero imaginary parts.
678
679 @deffn {Scheme Procedure} complex? z
680 @deffnx {C Function} scm_complex_p (z)
681 Return @code{#t} if @var{x} is a complex number, @code{#f}
682 otherwise. Note that the sets of real, rational and integer
683 values form subsets of the set of complex numbers, i. e. the
684 predicate will also be fulfilled if @var{x} is a real,
685 rational or integer number.
686 @end deffn
687
688 @deftypefn {C Function} int scm_is_complex (SCM val)
689 Equivalent to @code{scm_is_true (scm_complex_p (val))}.
690 @end deftypefn
691
692 @node Exactness
693 @subsubsection Exact and Inexact Numbers
694 @tpindex Exact numbers
695 @tpindex Inexact numbers
696
697 @rnindex exact?
698 @rnindex inexact?
699 @rnindex exact->inexact
700 @rnindex inexact->exact
701
702 R5RS requires that a calculation involving inexact numbers always
703 produces an inexact result. To meet this requirement, Guile
704 distinguishes between an exact integer value such as @samp{5} and the
705 corresponding inexact real value which, to the limited precision
706 available, has no fractional part, and is printed as @samp{5.0}. Guile
707 will only convert the latter value to the former when forced to do so by
708 an invocation of the @code{inexact->exact} procedure.
709
710 @deffn {Scheme Procedure} exact? z
711 @deffnx {C Function} scm_exact_p (z)
712 Return @code{#t} if the number @var{z} is exact, @code{#f}
713 otherwise.
714
715 @lisp
716 (exact? 2)
717 @result{} #t
718
719 (exact? 0.5)
720 @result{} #f
721
722 (exact? (/ 2))
723 @result{} #t
724 @end lisp
725
726 @end deffn
727
728 @deffn {Scheme Procedure} inexact? z
729 @deffnx {C Function} scm_inexact_p (z)
730 Return @code{#t} if the number @var{z} is inexact, @code{#f}
731 else.
732 @end deffn
733
734 @deffn {Scheme Procedure} inexact->exact z
735 @deffnx {C Function} scm_inexact_to_exact (z)
736 Return an exact number that is numerically closest to @var{z}, when
737 there is one. For inexact rationals, Guile returns the exact rational
738 that is numerically equal to the inexact rational. Inexact complex
739 numbers with a non-zero imaginary part can not be made exact.
740
741 @lisp
742 (inexact->exact 0.5)
743 @result{} 1/2
744 @end lisp
745
746 The following happens because 12/10 is not exactly representable as a
747 @code{double} (on most platforms). However, when reading a decimal
748 number that has been marked exact with the ``#e'' prefix, Guile is
749 able to represent it correctly.
750
751 @lisp
752 (inexact->exact 1.2)
753 @result{} 5404319552844595/4503599627370496
754
755 #e1.2
756 @result{} 6/5
757 @end lisp
758
759 @end deffn
760
761 @c begin (texi-doc-string "guile" "exact->inexact")
762 @deffn {Scheme Procedure} exact->inexact z
763 @deffnx {C Function} scm_exact_to_inexact (z)
764 Convert the number @var{z} to its inexact representation.
765 @end deffn
766
767
768 @node Number Syntax
769 @subsubsection Read Syntax for Numerical Data
770
771 The read syntax for integers is a string of digits, optionally
772 preceded by a minus or plus character, a code indicating the
773 base in which the integer is encoded, and a code indicating whether
774 the number is exact or inexact. The supported base codes are:
775
776 @table @code
777 @item #b
778 @itemx #B
779 the integer is written in binary (base 2)
780
781 @item #o
782 @itemx #O
783 the integer is written in octal (base 8)
784
785 @item #d
786 @itemx #D
787 the integer is written in decimal (base 10)
788
789 @item #x
790 @itemx #X
791 the integer is written in hexadecimal (base 16)
792 @end table
793
794 If the base code is omitted, the integer is assumed to be decimal. The
795 following examples show how these base codes are used.
796
797 @lisp
798 -13
799 @result{} -13
800
801 #d-13
802 @result{} -13
803
804 #x-13
805 @result{} -19
806
807 #b+1101
808 @result{} 13
809
810 #o377
811 @result{} 255
812 @end lisp
813
814 The codes for indicating exactness (which can, incidentally, be applied
815 to all numerical values) are:
816
817 @table @code
818 @item #e
819 @itemx #E
820 the number is exact
821
822 @item #i
823 @itemx #I
824 the number is inexact.
825 @end table
826
827 If the exactness indicator is omitted, the number is exact unless it
828 contains a radix point. Since Guile can not represent exact complex
829 numbers, an error is signalled when asking for them.
830
831 @lisp
832 (exact? 1.2)
833 @result{} #f
834
835 (exact? #e1.2)
836 @result{} #t
837
838 (exact? #e+1i)
839 ERROR: Wrong type argument
840 @end lisp
841
842 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
843 plus and minus infinity, respectively. The value must be written
844 exactly as shown, that is, they always must have a sign and exactly
845 one zero digit after the decimal point. It also understands
846 @samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
847 The sign is ignored for `not-a-number' and the value is always printed
848 as @samp{+nan.0}.
849
850 @node Integer Operations
851 @subsubsection Operations on Integer Values
852 @rnindex odd?
853 @rnindex even?
854 @rnindex quotient
855 @rnindex remainder
856 @rnindex modulo
857 @rnindex gcd
858 @rnindex lcm
859
860 @deffn {Scheme Procedure} odd? n
861 @deffnx {C Function} scm_odd_p (n)
862 Return @code{#t} if @var{n} is an odd number, @code{#f}
863 otherwise.
864 @end deffn
865
866 @deffn {Scheme Procedure} even? n
867 @deffnx {C Function} scm_even_p (n)
868 Return @code{#t} if @var{n} is an even number, @code{#f}
869 otherwise.
870 @end deffn
871
872 @c begin (texi-doc-string "guile" "quotient")
873 @c begin (texi-doc-string "guile" "remainder")
874 @deffn {Scheme Procedure} quotient n d
875 @deffnx {Scheme Procedure} remainder n d
876 @deffnx {C Function} scm_quotient (n, d)
877 @deffnx {C Function} scm_remainder (n, d)
878 Return the quotient or remainder from @var{n} divided by @var{d}. The
879 quotient is rounded towards zero, and the remainder will have the same
880 sign as @var{n}. In all cases quotient and remainder satisfy
881 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
882
883 @lisp
884 (remainder 13 4) @result{} 1
885 (remainder -13 4) @result{} -1
886 @end lisp
887 @end deffn
888
889 @c begin (texi-doc-string "guile" "modulo")
890 @deffn {Scheme Procedure} modulo n d
891 @deffnx {C Function} scm_modulo (n, d)
892 Return the remainder from @var{n} divided by @var{d}, with the same
893 sign as @var{d}.
894
895 @lisp
896 (modulo 13 4) @result{} 1
897 (modulo -13 4) @result{} 3
898 (modulo 13 -4) @result{} -3
899 (modulo -13 -4) @result{} -1
900 @end lisp
901 @end deffn
902
903 @c begin (texi-doc-string "guile" "gcd")
904 @deffn {Scheme Procedure} gcd x@dots{}
905 @deffnx {C Function} scm_gcd (x, y)
906 Return the greatest common divisor of all arguments.
907 If called without arguments, 0 is returned.
908
909 The C function @code{scm_gcd} always takes two arguments, while the
910 Scheme function can take an arbitrary number.
911 @end deffn
912
913 @c begin (texi-doc-string "guile" "lcm")
914 @deffn {Scheme Procedure} lcm x@dots{}
915 @deffnx {C Function} scm_lcm (x, y)
916 Return the least common multiple of the arguments.
917 If called without arguments, 1 is returned.
918
919 The C function @code{scm_lcm} always takes two arguments, while the
920 Scheme function can take an arbitrary number.
921 @end deffn
922
923 @deffn {Scheme Procedure} modulo-expt n k m
924 @deffnx {C Function} scm_modulo_expt (n, k, m)
925 Return @var{n} raised to the integer exponent
926 @var{k}, modulo @var{m}.
927
928 @lisp
929 (modulo-expt 2 3 5)
930 @result{} 3
931 @end lisp
932 @end deffn
933
934 @node Comparison
935 @subsubsection Comparison Predicates
936 @rnindex zero?
937 @rnindex positive?
938 @rnindex negative?
939
940 The C comparison functions below always takes two arguments, while the
941 Scheme functions can take an arbitrary number. Also keep in mind that
942 the C functions return one of the Scheme boolean values
943 @code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
944 is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
945 y))} when testing the two Scheme numbers @code{x} and @code{y} for
946 equality, for example.
947
948 @c begin (texi-doc-string "guile" "=")
949 @deffn {Scheme Procedure} =
950 @deffnx {C Function} scm_num_eq_p (x, y)
951 Return @code{#t} if all parameters are numerically equal.
952 @end deffn
953
954 @c begin (texi-doc-string "guile" "<")
955 @deffn {Scheme Procedure} <
956 @deffnx {C Function} scm_less_p (x, y)
957 Return @code{#t} if the list of parameters is monotonically
958 increasing.
959 @end deffn
960
961 @c begin (texi-doc-string "guile" ">")
962 @deffn {Scheme Procedure} >
963 @deffnx {C Function} scm_gr_p (x, y)
964 Return @code{#t} if the list of parameters is monotonically
965 decreasing.
966 @end deffn
967
968 @c begin (texi-doc-string "guile" "<=")
969 @deffn {Scheme Procedure} <=
970 @deffnx {C Function} scm_leq_p (x, y)
971 Return @code{#t} if the list of parameters is monotonically
972 non-decreasing.
973 @end deffn
974
975 @c begin (texi-doc-string "guile" ">=")
976 @deffn {Scheme Procedure} >=
977 @deffnx {C Function} scm_geq_p (x, y)
978 Return @code{#t} if the list of parameters is monotonically
979 non-increasing.
980 @end deffn
981
982 @c begin (texi-doc-string "guile" "zero?")
983 @deffn {Scheme Procedure} zero? z
984 @deffnx {C Function} scm_zero_p (z)
985 Return @code{#t} if @var{z} is an exact or inexact number equal to
986 zero.
987 @end deffn
988
989 @c begin (texi-doc-string "guile" "positive?")
990 @deffn {Scheme Procedure} positive? x
991 @deffnx {C Function} scm_positive_p (x)
992 Return @code{#t} if @var{x} is an exact or inexact number greater than
993 zero.
994 @end deffn
995
996 @c begin (texi-doc-string "guile" "negative?")
997 @deffn {Scheme Procedure} negative? x
998 @deffnx {C Function} scm_negative_p (x)
999 Return @code{#t} if @var{x} is an exact or inexact number less than
1000 zero.
1001 @end deffn
1002
1003
1004 @node Conversion
1005 @subsubsection Converting Numbers To and From Strings
1006 @rnindex number->string
1007 @rnindex string->number
1008
1009 The following procedures read and write numbers according to their
1010 external representation as defined by R5RS (@pxref{Lexical structure,
1011 R5RS Lexical Structure,, r5rs, The Revised^5 Report on the Algorithmic
1012 Language Scheme}). @xref{Number Input and Output, the @code{(ice-9
1013 i18n)} module}, for locale-dependent number parsing.
1014
1015 @deffn {Scheme Procedure} number->string n [radix]
1016 @deffnx {C Function} scm_number_to_string (n, radix)
1017 Return a string holding the external representation of the
1018 number @var{n} in the given @var{radix}. If @var{n} is
1019 inexact, a radix of 10 will be used.
1020 @end deffn
1021
1022 @deffn {Scheme Procedure} string->number string [radix]
1023 @deffnx {C Function} scm_string_to_number (string, radix)
1024 Return a number of the maximally precise representation
1025 expressed by the given @var{string}. @var{radix} must be an
1026 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
1027 is a default radix that may be overridden by an explicit radix
1028 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1029 supplied, then the default radix is 10. If string is not a
1030 syntactically valid notation for a number, then
1031 @code{string->number} returns @code{#f}.
1032 @end deffn
1033
1034 @deftypefn {C Function} SCM scm_c_locale_stringn_to_number (const char *string, size_t len, unsigned radix)
1035 As per @code{string->number} above, but taking a C string, as pointer
1036 and length. The string characters should be in the current locale
1037 encoding (@code{locale} in the name refers only to that, there's no
1038 locale-dependent parsing).
1039 @end deftypefn
1040
1041
1042 @node Complex
1043 @subsubsection Complex Number Operations
1044 @rnindex make-rectangular
1045 @rnindex make-polar
1046 @rnindex real-part
1047 @rnindex imag-part
1048 @rnindex magnitude
1049 @rnindex angle
1050
1051 @deffn {Scheme Procedure} make-rectangular real_part imaginary_part
1052 @deffnx {C Function} scm_make_rectangular (real_part, imaginary_part)
1053 Return a complex number constructed of the given @var{real-part} and @var{imaginary-part} parts.
1054 @end deffn
1055
1056 @deffn {Scheme Procedure} make-polar x y
1057 @deffnx {C Function} scm_make_polar (x, y)
1058 @cindex polar form
1059 Return the complex number @var{x} * e^(i * @var{y}).
1060 @end deffn
1061
1062 @c begin (texi-doc-string "guile" "real-part")
1063 @deffn {Scheme Procedure} real-part z
1064 @deffnx {C Function} scm_real_part (z)
1065 Return the real part of the number @var{z}.
1066 @end deffn
1067
1068 @c begin (texi-doc-string "guile" "imag-part")
1069 @deffn {Scheme Procedure} imag-part z
1070 @deffnx {C Function} scm_imag_part (z)
1071 Return the imaginary part of the number @var{z}.
1072 @end deffn
1073
1074 @c begin (texi-doc-string "guile" "magnitude")
1075 @deffn {Scheme Procedure} magnitude z
1076 @deffnx {C Function} scm_magnitude (z)
1077 Return the magnitude of the number @var{z}. This is the same as
1078 @code{abs} for real arguments, but also allows complex numbers.
1079 @end deffn
1080
1081 @c begin (texi-doc-string "guile" "angle")
1082 @deffn {Scheme Procedure} angle z
1083 @deffnx {C Function} scm_angle (z)
1084 Return the angle of the complex number @var{z}.
1085 @end deffn
1086
1087 @deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1088 @deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1089 Like @code{scm_make_rectangular} or @code{scm_make_polar},
1090 respectively, but these functions take @code{double}s as their
1091 arguments.
1092 @end deftypefn
1093
1094 @deftypefn {C Function} double scm_c_real_part (z)
1095 @deftypefnx {C Function} double scm_c_imag_part (z)
1096 Returns the real or imaginary part of @var{z} as a @code{double}.
1097 @end deftypefn
1098
1099 @deftypefn {C Function} double scm_c_magnitude (z)
1100 @deftypefnx {C Function} double scm_c_angle (z)
1101 Returns the magnitude or angle of @var{z} as a @code{double}.
1102 @end deftypefn
1103
1104
1105 @node Arithmetic
1106 @subsubsection Arithmetic Functions
1107 @rnindex max
1108 @rnindex min
1109 @rnindex +
1110 @rnindex *
1111 @rnindex -
1112 @rnindex /
1113 @findex 1+
1114 @findex 1-
1115 @rnindex abs
1116 @rnindex floor
1117 @rnindex ceiling
1118 @rnindex truncate
1119 @rnindex round
1120
1121 The C arithmetic functions below always takes two arguments, while the
1122 Scheme functions can take an arbitrary number. When you need to
1123 invoke them with just one argument, for example to compute the
1124 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1125 one: @code{scm_difference (x, SCM_UNDEFINED)}.
1126
1127 @c begin (texi-doc-string "guile" "+")
1128 @deffn {Scheme Procedure} + z1 @dots{}
1129 @deffnx {C Function} scm_sum (z1, z2)
1130 Return the sum of all parameter values. Return 0 if called without any
1131 parameters.
1132 @end deffn
1133
1134 @c begin (texi-doc-string "guile" "-")
1135 @deffn {Scheme Procedure} - z1 z2 @dots{}
1136 @deffnx {C Function} scm_difference (z1, z2)
1137 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1138 the sum of all but the first argument are subtracted from the first
1139 argument.
1140 @end deffn
1141
1142 @c begin (texi-doc-string "guile" "*")
1143 @deffn {Scheme Procedure} * z1 @dots{}
1144 @deffnx {C Function} scm_product (z1, z2)
1145 Return the product of all arguments. If called without arguments, 1 is
1146 returned.
1147 @end deffn
1148
1149 @c begin (texi-doc-string "guile" "/")
1150 @deffn {Scheme Procedure} / z1 z2 @dots{}
1151 @deffnx {C Function} scm_divide (z1, z2)
1152 Divide the first argument by the product of the remaining arguments. If
1153 called with one argument @var{z1}, 1/@var{z1} is returned.
1154 @end deffn
1155
1156 @deffn {Scheme Procedure} 1+ z
1157 @deffnx {C Function} scm_oneplus (z)
1158 Return @math{@var{z} + 1}.
1159 @end deffn
1160
1161 @deffn {Scheme Procedure} 1- z
1162 @deffnx {C function} scm_oneminus (z)
1163 Return @math{@var{z} - 1}.
1164 @end deffn
1165
1166 @c begin (texi-doc-string "guile" "abs")
1167 @deffn {Scheme Procedure} abs x
1168 @deffnx {C Function} scm_abs (x)
1169 Return the absolute value of @var{x}.
1170
1171 @var{x} must be a number with zero imaginary part. To calculate the
1172 magnitude of a complex number, use @code{magnitude} instead.
1173 @end deffn
1174
1175 @c begin (texi-doc-string "guile" "max")
1176 @deffn {Scheme Procedure} max x1 x2 @dots{}
1177 @deffnx {C Function} scm_max (x1, x2)
1178 Return the maximum of all parameter values.
1179 @end deffn
1180
1181 @c begin (texi-doc-string "guile" "min")
1182 @deffn {Scheme Procedure} min x1 x2 @dots{}
1183 @deffnx {C Function} scm_min (x1, x2)
1184 Return the minimum of all parameter values.
1185 @end deffn
1186
1187 @c begin (texi-doc-string "guile" "truncate")
1188 @deffn {Scheme Procedure} truncate x
1189 @deffnx {C Function} scm_truncate_number (x)
1190 Round the inexact number @var{x} towards zero.
1191 @end deffn
1192
1193 @c begin (texi-doc-string "guile" "round")
1194 @deffn {Scheme Procedure} round x
1195 @deffnx {C Function} scm_round_number (x)
1196 Round the inexact number @var{x} to the nearest integer. When exactly
1197 halfway between two integers, round to the even one.
1198 @end deffn
1199
1200 @c begin (texi-doc-string "guile" "floor")
1201 @deffn {Scheme Procedure} floor x
1202 @deffnx {C Function} scm_floor (x)
1203 Round the number @var{x} towards minus infinity.
1204 @end deffn
1205
1206 @c begin (texi-doc-string "guile" "ceiling")
1207 @deffn {Scheme Procedure} ceiling x
1208 @deffnx {C Function} scm_ceiling (x)
1209 Round the number @var{x} towards infinity.
1210 @end deffn
1211
1212 @deftypefn {C Function} double scm_c_truncate (double x)
1213 @deftypefnx {C Function} double scm_c_round (double x)
1214 Like @code{scm_truncate_number} or @code{scm_round_number},
1215 respectively, but these functions take and return @code{double}
1216 values.
1217 @end deftypefn
1218
1219 @node Scientific
1220 @subsubsection Scientific Functions
1221
1222 The following procedures accept any kind of number as arguments,
1223 including complex numbers.
1224
1225 @rnindex sqrt
1226 @c begin (texi-doc-string "guile" "sqrt")
1227 @deffn {Scheme Procedure} sqrt z
1228 Return the square root of @var{z}. Of the two possible roots
1229 (positive and negative), the one with the a positive real part is
1230 returned, or if that's zero then a positive imaginary part. Thus,
1231
1232 @example
1233 (sqrt 9.0) @result{} 3.0
1234 (sqrt -9.0) @result{} 0.0+3.0i
1235 (sqrt 1.0+1.0i) @result{} 1.09868411346781+0.455089860562227i
1236 (sqrt -1.0-1.0i) @result{} 0.455089860562227-1.09868411346781i
1237 @end example
1238 @end deffn
1239
1240 @rnindex expt
1241 @c begin (texi-doc-string "guile" "expt")
1242 @deffn {Scheme Procedure} expt z1 z2
1243 Return @var{z1} raised to the power of @var{z2}.
1244 @end deffn
1245
1246 @rnindex sin
1247 @c begin (texi-doc-string "guile" "sin")
1248 @deffn {Scheme Procedure} sin z
1249 Return the sine of @var{z}.
1250 @end deffn
1251
1252 @rnindex cos
1253 @c begin (texi-doc-string "guile" "cos")
1254 @deffn {Scheme Procedure} cos z
1255 Return the cosine of @var{z}.
1256 @end deffn
1257
1258 @rnindex tan
1259 @c begin (texi-doc-string "guile" "tan")
1260 @deffn {Scheme Procedure} tan z
1261 Return the tangent of @var{z}.
1262 @end deffn
1263
1264 @rnindex asin
1265 @c begin (texi-doc-string "guile" "asin")
1266 @deffn {Scheme Procedure} asin z
1267 Return the arcsine of @var{z}.
1268 @end deffn
1269
1270 @rnindex acos
1271 @c begin (texi-doc-string "guile" "acos")
1272 @deffn {Scheme Procedure} acos z
1273 Return the arccosine of @var{z}.
1274 @end deffn
1275
1276 @rnindex atan
1277 @c begin (texi-doc-string "guile" "atan")
1278 @deffn {Scheme Procedure} atan z
1279 @deffnx {Scheme Procedure} atan y x
1280 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1281 @end deffn
1282
1283 @rnindex exp
1284 @c begin (texi-doc-string "guile" "exp")
1285 @deffn {Scheme Procedure} exp z
1286 Return e to the power of @var{z}, where e is the base of natural
1287 logarithms (2.71828@dots{}).
1288 @end deffn
1289
1290 @rnindex log
1291 @c begin (texi-doc-string "guile" "log")
1292 @deffn {Scheme Procedure} log z
1293 Return the natural logarithm of @var{z}.
1294 @end deffn
1295
1296 @c begin (texi-doc-string "guile" "log10")
1297 @deffn {Scheme Procedure} log10 z
1298 Return the base 10 logarithm of @var{z}.
1299 @end deffn
1300
1301 @c begin (texi-doc-string "guile" "sinh")
1302 @deffn {Scheme Procedure} sinh z
1303 Return the hyperbolic sine of @var{z}.
1304 @end deffn
1305
1306 @c begin (texi-doc-string "guile" "cosh")
1307 @deffn {Scheme Procedure} cosh z
1308 Return the hyperbolic cosine of @var{z}.
1309 @end deffn
1310
1311 @c begin (texi-doc-string "guile" "tanh")
1312 @deffn {Scheme Procedure} tanh z
1313 Return the hyperbolic tangent of @var{z}.
1314 @end deffn
1315
1316 @c begin (texi-doc-string "guile" "asinh")
1317 @deffn {Scheme Procedure} asinh z
1318 Return the hyperbolic arcsine of @var{z}.
1319 @end deffn
1320
1321 @c begin (texi-doc-string "guile" "acosh")
1322 @deffn {Scheme Procedure} acosh z
1323 Return the hyperbolic arccosine of @var{z}.
1324 @end deffn
1325
1326 @c begin (texi-doc-string "guile" "atanh")
1327 @deffn {Scheme Procedure} atanh z
1328 Return the hyperbolic arctangent of @var{z}.
1329 @end deffn
1330
1331
1332 @node Bitwise Operations
1333 @subsubsection Bitwise Operations
1334
1335 For the following bitwise functions, negative numbers are treated as
1336 infinite precision twos-complements. For instance @math{-6} is bits
1337 @math{@dots{}111010}, with infinitely many ones on the left. It can
1338 be seen that adding 6 (binary 110) to such a bit pattern gives all
1339 zeros.
1340
1341 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1342 @deffnx {C Function} scm_logand (n1, n2)
1343 Return the bitwise @sc{and} of the integer arguments.
1344
1345 @lisp
1346 (logand) @result{} -1
1347 (logand 7) @result{} 7
1348 (logand #b111 #b011 #b001) @result{} 1
1349 @end lisp
1350 @end deffn
1351
1352 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1353 @deffnx {C Function} scm_logior (n1, n2)
1354 Return the bitwise @sc{or} of the integer arguments.
1355
1356 @lisp
1357 (logior) @result{} 0
1358 (logior 7) @result{} 7
1359 (logior #b000 #b001 #b011) @result{} 3
1360 @end lisp
1361 @end deffn
1362
1363 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1364 @deffnx {C Function} scm_loxor (n1, n2)
1365 Return the bitwise @sc{xor} of the integer arguments. A bit is
1366 set in the result if it is set in an odd number of arguments.
1367
1368 @lisp
1369 (logxor) @result{} 0
1370 (logxor 7) @result{} 7
1371 (logxor #b000 #b001 #b011) @result{} 2
1372 (logxor #b000 #b001 #b011 #b011) @result{} 1
1373 @end lisp
1374 @end deffn
1375
1376 @deffn {Scheme Procedure} lognot n
1377 @deffnx {C Function} scm_lognot (n)
1378 Return the integer which is the ones-complement of the integer
1379 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1380
1381 @lisp
1382 (number->string (lognot #b10000000) 2)
1383 @result{} "-10000001"
1384 (number->string (lognot #b0) 2)
1385 @result{} "-1"
1386 @end lisp
1387 @end deffn
1388
1389 @deffn {Scheme Procedure} logtest j k
1390 @deffnx {C Function} scm_logtest (j, k)
1391 Test whether @var{j} and @var{k} have any 1 bits in common. This is
1392 equivalent to @code{(not (zero? (logand j k)))}, but without actually
1393 calculating the @code{logand}, just testing for non-zero.
1394
1395 @lisp
1396 (logtest #b0100 #b1011) @result{} #f
1397 (logtest #b0100 #b0111) @result{} #t
1398 @end lisp
1399 @end deffn
1400
1401 @deffn {Scheme Procedure} logbit? index j
1402 @deffnx {C Function} scm_logbit_p (index, j)
1403 Test whether bit number @var{index} in @var{j} is set. @var{index}
1404 starts from 0 for the least significant bit.
1405
1406 @lisp
1407 (logbit? 0 #b1101) @result{} #t
1408 (logbit? 1 #b1101) @result{} #f
1409 (logbit? 2 #b1101) @result{} #t
1410 (logbit? 3 #b1101) @result{} #t
1411 (logbit? 4 #b1101) @result{} #f
1412 @end lisp
1413 @end deffn
1414
1415 @deffn {Scheme Procedure} ash n cnt
1416 @deffnx {C Function} scm_ash (n, cnt)
1417 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1418 @var{cnt} is negative. This is an ``arithmetic'' shift.
1419
1420 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1421 when @var{cnt} is negative it's a division, rounded towards negative
1422 infinity. (Note that this is not the same rounding as @code{quotient}
1423 does.)
1424
1425 With @var{n} viewed as an infinite precision twos complement,
1426 @code{ash} means a left shift introducing zero bits, or a right shift
1427 dropping bits.
1428
1429 @lisp
1430 (number->string (ash #b1 3) 2) @result{} "1000"
1431 (number->string (ash #b1010 -1) 2) @result{} "101"
1432
1433 ;; -23 is bits ...11101001, -6 is bits ...111010
1434 (ash -23 -2) @result{} -6
1435 @end lisp
1436 @end deffn
1437
1438 @deffn {Scheme Procedure} logcount n
1439 @deffnx {C Function} scm_logcount (n)
1440 Return the number of bits in integer @var{n}. If @var{n} is
1441 positive, the 1-bits in its binary representation are counted.
1442 If negative, the 0-bits in its two's-complement binary
1443 representation are counted. If zero, 0 is returned.
1444
1445 @lisp
1446 (logcount #b10101010)
1447 @result{} 4
1448 (logcount 0)
1449 @result{} 0
1450 (logcount -2)
1451 @result{} 1
1452 @end lisp
1453 @end deffn
1454
1455 @deffn {Scheme Procedure} integer-length n
1456 @deffnx {C Function} scm_integer_length (n)
1457 Return the number of bits necessary to represent @var{n}.
1458
1459 For positive @var{n} this is how many bits to the most significant one
1460 bit. For negative @var{n} it's how many bits to the most significant
1461 zero bit in twos complement form.
1462
1463 @lisp
1464 (integer-length #b10101010) @result{} 8
1465 (integer-length #b1111) @result{} 4
1466 (integer-length 0) @result{} 0
1467 (integer-length -1) @result{} 0
1468 (integer-length -256) @result{} 8
1469 (integer-length -257) @result{} 9
1470 @end lisp
1471 @end deffn
1472
1473 @deffn {Scheme Procedure} integer-expt n k
1474 @deffnx {C Function} scm_integer_expt (n, k)
1475 Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1476 integer, @var{n} can be any number.
1477
1478 Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1479 in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1480 @math{0^0} is 1.
1481
1482 @lisp
1483 (integer-expt 2 5) @result{} 32
1484 (integer-expt -3 3) @result{} -27
1485 (integer-expt 5 -3) @result{} 1/125
1486 (integer-expt 0 0) @result{} 1
1487 @end lisp
1488 @end deffn
1489
1490 @deffn {Scheme Procedure} bit-extract n start end
1491 @deffnx {C Function} scm_bit_extract (n, start, end)
1492 Return the integer composed of the @var{start} (inclusive)
1493 through @var{end} (exclusive) bits of @var{n}. The
1494 @var{start}th bit becomes the 0-th bit in the result.
1495
1496 @lisp
1497 (number->string (bit-extract #b1101101010 0 4) 2)
1498 @result{} "1010"
1499 (number->string (bit-extract #b1101101010 4 9) 2)
1500 @result{} "10110"
1501 @end lisp
1502 @end deffn
1503
1504
1505 @node Random
1506 @subsubsection Random Number Generation
1507
1508 Pseudo-random numbers are generated from a random state object, which
1509 can be created with @code{seed->random-state} or
1510 @code{datum->random-state}. An external representation (i.e. one
1511 which can written with @code{write} and read with @code{read}) of a
1512 random state object can be obtained via
1513 @code{random-state->datum}. The @var{state} parameter to the
1514 various functions below is optional, it defaults to the state object
1515 in the @code{*random-state*} variable.
1516
1517 @deffn {Scheme Procedure} copy-random-state [state]
1518 @deffnx {C Function} scm_copy_random_state (state)
1519 Return a copy of the random state @var{state}.
1520 @end deffn
1521
1522 @deffn {Scheme Procedure} random n [state]
1523 @deffnx {C Function} scm_random (n, state)
1524 Return a number in [0, @var{n}).
1525
1526 Accepts a positive integer or real n and returns a
1527 number of the same type between zero (inclusive) and
1528 @var{n} (exclusive). The values returned have a uniform
1529 distribution.
1530 @end deffn
1531
1532 @deffn {Scheme Procedure} random:exp [state]
1533 @deffnx {C Function} scm_random_exp (state)
1534 Return an inexact real in an exponential distribution with mean
1535 1. For an exponential distribution with mean @var{u} use @code{(*
1536 @var{u} (random:exp))}.
1537 @end deffn
1538
1539 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1540 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1541 Fills @var{vect} with inexact real random numbers the sum of whose
1542 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1543 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1544 the coordinates are uniformly distributed over the surface of the unit
1545 n-sphere.
1546 @end deffn
1547
1548 @deffn {Scheme Procedure} random:normal [state]
1549 @deffnx {C Function} scm_random_normal (state)
1550 Return an inexact real in a normal distribution. The distribution
1551 used has mean 0 and standard deviation 1. For a normal distribution
1552 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1553 (* @var{d} (random:normal)))}.
1554 @end deffn
1555
1556 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1557 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1558 Fills @var{vect} with inexact real random numbers that are
1559 independent and standard normally distributed
1560 (i.e., with mean 0 and variance 1).
1561 @end deffn
1562
1563 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1564 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1565 Fills @var{vect} with inexact real random numbers the sum of whose
1566 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1567 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1568 the coordinates are uniformly distributed within the unit
1569 @var{n}-sphere.
1570 @c FIXME: What does this mean, particularly the n-sphere part?
1571 @end deffn
1572
1573 @deffn {Scheme Procedure} random:uniform [state]
1574 @deffnx {C Function} scm_random_uniform (state)
1575 Return a uniformly distributed inexact real random number in
1576 [0,1).
1577 @end deffn
1578
1579 @deffn {Scheme Procedure} seed->random-state seed
1580 @deffnx {C Function} scm_seed_to_random_state (seed)
1581 Return a new random state using @var{seed}.
1582 @end deffn
1583
1584 @deffn {Scheme Procedure} datum->random-state datum
1585 @deffnx {C Function} scm_datum_to_random_state (datum)
1586 Return a new random state from @var{datum}, which should have been
1587 obtained by @code{random-state->datum}.
1588 @end deffn
1589
1590 @deffn {Scheme Procedure} random-state->datum state
1591 @deffnx {C Function} scm_random_state_to_datum (state)
1592 Return a datum representation of @var{state} that may be written out and
1593 read back with the Scheme reader.
1594 @end deffn
1595
1596 @defvar *random-state*
1597 The global random state used by the above functions when the
1598 @var{state} parameter is not given.
1599 @end defvar
1600
1601 Note that the initial value of @code{*random-state*} is the same every
1602 time Guile starts up. Therefore, if you don't pass a @var{state}
1603 parameter to the above procedures, and you don't set
1604 @code{*random-state*} to @code{(seed->random-state your-seed)}, where
1605 @code{your-seed} is something that @emph{isn't} the same every time,
1606 you'll get the same sequence of ``random'' numbers on every run.
1607
1608 For example, unless the relevant source code has changed, @code{(map
1609 random (cdr (iota 30)))}, if the first use of random numbers since
1610 Guile started up, will always give:
1611
1612 @lisp
1613 (map random (cdr (iota 19)))
1614 @result{}
1615 (0 1 1 2 2 2 1 2 6 7 10 0 5 3 12 5 5 12)
1616 @end lisp
1617
1618 To use the time of day as the random seed, you can use code like this:
1619
1620 @lisp
1621 (let ((time (gettimeofday)))
1622 (set! *random-state*
1623 (seed->random-state (+ (car time)
1624 (cdr time)))))
1625 @end lisp
1626
1627 @noindent
1628 And then (depending on the time of day, of course):
1629
1630 @lisp
1631 (map random (cdr (iota 19)))
1632 @result{}
1633 (0 0 1 0 2 4 5 4 5 5 9 3 10 1 8 3 14 17)
1634 @end lisp
1635
1636 For security applications, such as password generation, you should use
1637 more bits of seed. Otherwise an open source password generator could
1638 be attacked by guessing the seed@dots{} but that's a subject for
1639 another manual.
1640
1641
1642 @node Characters
1643 @subsection Characters
1644 @tpindex Characters
1645
1646 In Scheme, there is a data type to describe a single character.
1647
1648 Defining what exactly a character @emph{is} can be more complicated
1649 than it seems. Guile follows the advice of R6RS and uses The Unicode
1650 Standard to help define what a character is. So, for Guile, a
1651 character is anything in the Unicode Character Database.
1652
1653 @cindex code point
1654 @cindex Unicode code point
1655
1656 The Unicode Character Database is basically a table of characters
1657 indexed using integers called 'code points'. Valid code points are in
1658 the ranges 0 to @code{#xD7FF} inclusive or @code{#xE000} to
1659 @code{#x10FFFF} inclusive, which is about 1.1 million code points.
1660
1661 @cindex designated code point
1662 @cindex code point, designated
1663
1664 Any code point that has been assigned to a character or that has
1665 otherwise been given a meaning by Unicode is called a 'designated code
1666 point'. Most of the designated code points, about 200,000 of them,
1667 indicate characters, accents or other combining marks that modify
1668 other characters, symbols, whitespace, and control characters. Some
1669 are not characters but indicators that suggest how to format or
1670 display neighboring characters.
1671
1672 @cindex reserved code point
1673 @cindex code point, reserved
1674
1675 If a code point is not a designated code point -- if it has not been
1676 assigned to a character by The Unicode Standard -- it is a 'reserved
1677 code point', meaning that they are reserved for future use. Most of
1678 the code points, about 800,000, are 'reserved code points'.
1679
1680 By convention, a Unicode code point is written as
1681 ``U+XXXX'' where ``XXXX'' is a hexadecimal number. Please note that
1682 this convenient notation is not valid code. Guile does not interpret
1683 ``U+XXXX'' as a character.
1684
1685 In Scheme, a character literal is written as @code{#\@var{name}} where
1686 @var{name} is the name of the character that you want. Printable
1687 characters have their usual single character name; for example,
1688 @code{#\a} is a lower case @code{a}.
1689
1690 Some of the code points are 'combining characters' that are not meant
1691 to be printed by themselves but are instead meant to modify the
1692 appearance of the previous character. For combining characters, an
1693 alternate form of the character literal is @code{#\} followed by
1694 U+25CC (a small, dotted circle), followed by the combining character.
1695 This allows the combining character to be drawn on the circle, not on
1696 the backslash of @code{#\}.
1697
1698 Many of the non-printing characters, such as whitespace characters and
1699 control characters, also have names.
1700
1701 The most commonly used non-printing characters have long character
1702 names, described in the table below.
1703
1704 @multitable {@code{#\backspace}} {Preferred}
1705 @item Character Name @tab Codepoint
1706 @item @code{#\nul} @tab U+0000
1707 @item @code{#\alarm} @tab u+0007
1708 @item @code{#\backspace} @tab U+0008
1709 @item @code{#\tab} @tab U+0009
1710 @item @code{#\linefeed} @tab U+000A
1711 @item @code{#\newline} @tab U+000A
1712 @item @code{#\vtab} @tab U+000B
1713 @item @code{#\page} @tab U+000C
1714 @item @code{#\return} @tab U+000D
1715 @item @code{#\esc} @tab U+001B
1716 @item @code{#\space} @tab U+0020
1717 @item @code{#\delete} @tab U+007F
1718 @end multitable
1719
1720 There are also short names for all of the ``C0 control characters''
1721 (those with code points below 32). The following table lists the short
1722 name for each character.
1723
1724 @multitable @columnfractions .25 .25 .25 .25
1725 @item 0 = @code{#\nul}
1726 @tab 1 = @code{#\soh}
1727 @tab 2 = @code{#\stx}
1728 @tab 3 = @code{#\etx}
1729 @item 4 = @code{#\eot}
1730 @tab 5 = @code{#\enq}
1731 @tab 6 = @code{#\ack}
1732 @tab 7 = @code{#\bel}
1733 @item 8 = @code{#\bs}
1734 @tab 9 = @code{#\ht}
1735 @tab 10 = @code{#\lf}
1736 @tab 11 = @code{#\vt}
1737 @item 12 = @code{#\ff}
1738 @tab 13 = @code{#\cr}
1739 @tab 14 = @code{#\so}
1740 @tab 15 = @code{#\si}
1741 @item 16 = @code{#\dle}
1742 @tab 17 = @code{#\dc1}
1743 @tab 18 = @code{#\dc2}
1744 @tab 19 = @code{#\dc3}
1745 @item 20 = @code{#\dc4}
1746 @tab 21 = @code{#\nak}
1747 @tab 22 = @code{#\syn}
1748 @tab 23 = @code{#\etb}
1749 @item 24 = @code{#\can}
1750 @tab 25 = @code{#\em}
1751 @tab 26 = @code{#\sub}
1752 @tab 27 = @code{#\esc}
1753 @item 28 = @code{#\fs}
1754 @tab 29 = @code{#\gs}
1755 @tab 30 = @code{#\rs}
1756 @tab 31 = @code{#\us}
1757 @item 32 = @code{#\sp}
1758 @end multitable
1759
1760 The short name for the ``delete'' character (code point U+007F) is
1761 @code{#\del}.
1762
1763 There are also a few alternative names left over for compatibility with
1764 previous versions of Guile.
1765
1766 @multitable {@code{#\backspace}} {Preferred}
1767 @item Alternate @tab Standard
1768 @item @code{#\nl} @tab @code{#\newline}
1769 @item @code{#\np} @tab @code{#\page}
1770 @item @code{#\null} @tab @code{#\nul}
1771 @end multitable
1772
1773 Characters may also be written using their code point values. They can
1774 be written with as an octal number, such as @code{#\10} for
1775 @code{#\bs} or @code{#\177} for @code{#\del}.
1776
1777 If one prefers hex to octal, there is an additional syntax for character
1778 escapes: @code{#\xHHHH} -- the letter 'x' followed by a hexadecimal
1779 number of one to eight digits.
1780
1781 @rnindex char?
1782 @deffn {Scheme Procedure} char? x
1783 @deffnx {C Function} scm_char_p (x)
1784 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1785 @end deffn
1786
1787 Fundamentally, the character comparison operations below are
1788 numeric comparisons of the character's code points.
1789
1790 @rnindex char=?
1791 @deffn {Scheme Procedure} char=? x y
1792 Return @code{#t} iff code point of @var{x} is equal to the code point
1793 of @var{y}, else @code{#f}.
1794 @end deffn
1795
1796 @rnindex char<?
1797 @deffn {Scheme Procedure} char<? x y
1798 Return @code{#t} iff the code point of @var{x} is less than the code
1799 point of @var{y}, else @code{#f}.
1800 @end deffn
1801
1802 @rnindex char<=?
1803 @deffn {Scheme Procedure} char<=? x y
1804 Return @code{#t} iff the code point of @var{x} is less than or equal
1805 to the code point of @var{y}, else @code{#f}.
1806 @end deffn
1807
1808 @rnindex char>?
1809 @deffn {Scheme Procedure} char>? x y
1810 Return @code{#t} iff the code point of @var{x} is greater than the
1811 code point of @var{y}, else @code{#f}.
1812 @end deffn
1813
1814 @rnindex char>=?
1815 @deffn {Scheme Procedure} char>=? x y
1816 Return @code{#t} iff the code point of @var{x} is greater than or
1817 equal to the code point of @var{y}, else @code{#f}.
1818 @end deffn
1819
1820 @cindex case folding
1821
1822 Case-insensitive character comparisons use @emph{Unicode case
1823 folding}. In case folding comparisons, if a character is lowercase
1824 and has an uppercase form that can be expressed as a single character,
1825 it is converted to uppercase before comparison. All other characters
1826 undergo no conversion before the comparison occurs. This includes the
1827 German sharp S (Eszett) which is not uppercased before conversion
1828 because its uppercase form has two characters. Unicode case folding
1829 is language independent: it uses rules that are generally true, but,
1830 it cannot cover all cases for all languages.
1831
1832 @rnindex char-ci=?
1833 @deffn {Scheme Procedure} char-ci=? x y
1834 Return @code{#t} iff the case-folded code point of @var{x} is the same
1835 as the case-folded code point of @var{y}, else @code{#f}.
1836 @end deffn
1837
1838 @rnindex char-ci<?
1839 @deffn {Scheme Procedure} char-ci<? x y
1840 Return @code{#t} iff the case-folded code point of @var{x} is less
1841 than the case-folded code point of @var{y}, else @code{#f}.
1842 @end deffn
1843
1844 @rnindex char-ci<=?
1845 @deffn {Scheme Procedure} char-ci<=? x y
1846 Return @code{#t} iff the case-folded code point of @var{x} is less
1847 than or equal to the case-folded code point of @var{y}, else
1848 @code{#f}.
1849 @end deffn
1850
1851 @rnindex char-ci>?
1852 @deffn {Scheme Procedure} char-ci>? x y
1853 Return @code{#t} iff the case-folded code point of @var{x} is greater
1854 than the case-folded code point of @var{y}, else @code{#f}.
1855 @end deffn
1856
1857 @rnindex char-ci>=?
1858 @deffn {Scheme Procedure} char-ci>=? x y
1859 Return @code{#t} iff the case-folded code point of @var{x} is greater
1860 than or equal to the case-folded code point of @var{y}, else
1861 @code{#f}.
1862 @end deffn
1863
1864 @rnindex char-alphabetic?
1865 @deffn {Scheme Procedure} char-alphabetic? chr
1866 @deffnx {C Function} scm_char_alphabetic_p (chr)
1867 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1868 @end deffn
1869
1870 @rnindex char-numeric?
1871 @deffn {Scheme Procedure} char-numeric? chr
1872 @deffnx {C Function} scm_char_numeric_p (chr)
1873 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1874 @end deffn
1875
1876 @rnindex char-whitespace?
1877 @deffn {Scheme Procedure} char-whitespace? chr
1878 @deffnx {C Function} scm_char_whitespace_p (chr)
1879 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1880 @end deffn
1881
1882 @rnindex char-upper-case?
1883 @deffn {Scheme Procedure} char-upper-case? chr
1884 @deffnx {C Function} scm_char_upper_case_p (chr)
1885 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1886 @end deffn
1887
1888 @rnindex char-lower-case?
1889 @deffn {Scheme Procedure} char-lower-case? chr
1890 @deffnx {C Function} scm_char_lower_case_p (chr)
1891 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1892 @end deffn
1893
1894 @deffn {Scheme Procedure} char-is-both? chr
1895 @deffnx {C Function} scm_char_is_both_p (chr)
1896 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1897 @code{#f}.
1898 @end deffn
1899
1900 @deffn {Scheme Procedure} char-general-category chr
1901 @deffnx {C Function} scm_char_general_category (chr)
1902 Return a symbol giving the two-letter name of the Unicode general
1903 category assigned to @var{chr} or @code{#f} if no named category is
1904 assigned. The following table provides a list of category names along
1905 with their meanings.
1906
1907 @multitable @columnfractions .1 .4 .1 .4
1908 @item Lu
1909 @tab Uppercase letter
1910 @tab Pf
1911 @tab Final quote punctuation
1912 @item Ll
1913 @tab Lowercase letter
1914 @tab Po
1915 @tab Other punctuation
1916 @item Lt
1917 @tab Titlecase letter
1918 @tab Sm
1919 @tab Math symbol
1920 @item Lm
1921 @tab Modifier letter
1922 @tab Sc
1923 @tab Currency symbol
1924 @item Lo
1925 @tab Other letter
1926 @tab Sk
1927 @tab Modifier symbol
1928 @item Mn
1929 @tab Non-spacing mark
1930 @tab So
1931 @tab Other symbol
1932 @item Mc
1933 @tab Combining spacing mark
1934 @tab Zs
1935 @tab Space separator
1936 @item Me
1937 @tab Enclosing mark
1938 @tab Zl
1939 @tab Line separator
1940 @item Nd
1941 @tab Decimal digit number
1942 @tab Zp
1943 @tab Paragraph separator
1944 @item Nl
1945 @tab Letter number
1946 @tab Cc
1947 @tab Control
1948 @item No
1949 @tab Other number
1950 @tab Cf
1951 @tab Format
1952 @item Pc
1953 @tab Connector punctuation
1954 @tab Cs
1955 @tab Surrogate
1956 @item Pd
1957 @tab Dash punctuation
1958 @tab Co
1959 @tab Private use
1960 @item Ps
1961 @tab Open punctuation
1962 @tab Cn
1963 @tab Unassigned
1964 @item Pe
1965 @tab Close punctuation
1966 @tab
1967 @tab
1968 @item Pi
1969 @tab Initial quote punctuation
1970 @tab
1971 @tab
1972 @end multitable
1973 @end deffn
1974
1975 @rnindex char->integer
1976 @deffn {Scheme Procedure} char->integer chr
1977 @deffnx {C Function} scm_char_to_integer (chr)
1978 Return the code point of @var{chr}.
1979 @end deffn
1980
1981 @rnindex integer->char
1982 @deffn {Scheme Procedure} integer->char n
1983 @deffnx {C Function} scm_integer_to_char (n)
1984 Return the character that has code point @var{n}. The integer @var{n}
1985 must be a valid code point. Valid code points are in the ranges 0 to
1986 @code{#xD7FF} inclusive or @code{#xE000} to @code{#x10FFFF} inclusive.
1987 @end deffn
1988
1989 @rnindex char-upcase
1990 @deffn {Scheme Procedure} char-upcase chr
1991 @deffnx {C Function} scm_char_upcase (chr)
1992 Return the uppercase character version of @var{chr}.
1993 @end deffn
1994
1995 @rnindex char-downcase
1996 @deffn {Scheme Procedure} char-downcase chr
1997 @deffnx {C Function} scm_char_downcase (chr)
1998 Return the lowercase character version of @var{chr}.
1999 @end deffn
2000
2001 @rnindex char-titlecase
2002 @deffn {Scheme Procedure} char-titlecase chr
2003 @deffnx {C Function} scm_char_titlecase (chr)
2004 Return the titlecase character version of @var{chr} if one exists;
2005 otherwise return the uppercase version.
2006
2007 For most characters these will be the same, but the Unicode Standard
2008 includes certain digraph compatibility characters, such as @code{U+01F3}
2009 ``dz'', for which the uppercase and titlecase characters are different
2010 (@code{U+01F1} ``DZ'' and @code{U+01F2} ``Dz'' in this case,
2011 respectively).
2012 @end deffn
2013
2014 @tindex scm_t_wchar
2015 @deftypefn {C Function} scm_t_wchar scm_c_upcase (scm_t_wchar @var{c})
2016 @deftypefnx {C Function} scm_t_wchar scm_c_downcase (scm_t_wchar @var{c})
2017 @deftypefnx {C Function} scm_t_wchar scm_c_titlecase (scm_t_wchar @var{c})
2018
2019 These C functions take an integer representation of a Unicode
2020 codepoint and return the codepoint corresponding to its uppercase,
2021 lowercase, and titlecase forms respectively. The type
2022 @code{scm_t_wchar} is a signed, 32-bit integer.
2023 @end deftypefn
2024
2025 @node Character Sets
2026 @subsection Character Sets
2027
2028 The features described in this section correspond directly to SRFI-14.
2029
2030 The data type @dfn{charset} implements sets of characters
2031 (@pxref{Characters}). Because the internal representation of
2032 character sets is not visible to the user, a lot of procedures for
2033 handling them are provided.
2034
2035 Character sets can be created, extended, tested for the membership of a
2036 characters and be compared to other character sets.
2037
2038 @menu
2039 * Character Set Predicates/Comparison::
2040 * Iterating Over Character Sets:: Enumerate charset elements.
2041 * Creating Character Sets:: Making new charsets.
2042 * Querying Character Sets:: Test charsets for membership etc.
2043 * Character-Set Algebra:: Calculating new charsets.
2044 * Standard Character Sets:: Variables containing predefined charsets.
2045 @end menu
2046
2047 @node Character Set Predicates/Comparison
2048 @subsubsection Character Set Predicates/Comparison
2049
2050 Use these procedures for testing whether an object is a character set,
2051 or whether several character sets are equal or subsets of each other.
2052 @code{char-set-hash} can be used for calculating a hash value, maybe for
2053 usage in fast lookup procedures.
2054
2055 @deffn {Scheme Procedure} char-set? obj
2056 @deffnx {C Function} scm_char_set_p (obj)
2057 Return @code{#t} if @var{obj} is a character set, @code{#f}
2058 otherwise.
2059 @end deffn
2060
2061 @deffn {Scheme Procedure} char-set= . char_sets
2062 @deffnx {C Function} scm_char_set_eq (char_sets)
2063 Return @code{#t} if all given character sets are equal.
2064 @end deffn
2065
2066 @deffn {Scheme Procedure} char-set<= . char_sets
2067 @deffnx {C Function} scm_char_set_leq (char_sets)
2068 Return @code{#t} if every character set @var{cs}i is a subset
2069 of character set @var{cs}i+1.
2070 @end deffn
2071
2072 @deffn {Scheme Procedure} char-set-hash cs [bound]
2073 @deffnx {C Function} scm_char_set_hash (cs, bound)
2074 Compute a hash value for the character set @var{cs}. If
2075 @var{bound} is given and non-zero, it restricts the
2076 returned value to the range 0 @dots{} @var{bound - 1}.
2077 @end deffn
2078
2079 @c ===================================================================
2080
2081 @node Iterating Over Character Sets
2082 @subsubsection Iterating Over Character Sets
2083
2084 Character set cursors are a means for iterating over the members of a
2085 character sets. After creating a character set cursor with
2086 @code{char-set-cursor}, a cursor can be dereferenced with
2087 @code{char-set-ref}, advanced to the next member with
2088 @code{char-set-cursor-next}. Whether a cursor has passed past the last
2089 element of the set can be checked with @code{end-of-char-set?}.
2090
2091 Additionally, mapping and (un-)folding procedures for character sets are
2092 provided.
2093
2094 @deffn {Scheme Procedure} char-set-cursor cs
2095 @deffnx {C Function} scm_char_set_cursor (cs)
2096 Return a cursor into the character set @var{cs}.
2097 @end deffn
2098
2099 @deffn {Scheme Procedure} char-set-ref cs cursor
2100 @deffnx {C Function} scm_char_set_ref (cs, cursor)
2101 Return the character at the current cursor position
2102 @var{cursor} in the character set @var{cs}. It is an error to
2103 pass a cursor for which @code{end-of-char-set?} returns true.
2104 @end deffn
2105
2106 @deffn {Scheme Procedure} char-set-cursor-next cs cursor
2107 @deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
2108 Advance the character set cursor @var{cursor} to the next
2109 character in the character set @var{cs}. It is an error if the
2110 cursor given satisfies @code{end-of-char-set?}.
2111 @end deffn
2112
2113 @deffn {Scheme Procedure} end-of-char-set? cursor
2114 @deffnx {C Function} scm_end_of_char_set_p (cursor)
2115 Return @code{#t} if @var{cursor} has reached the end of a
2116 character set, @code{#f} otherwise.
2117 @end deffn
2118
2119 @deffn {Scheme Procedure} char-set-fold kons knil cs
2120 @deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2121 Fold the procedure @var{kons} over the character set @var{cs},
2122 initializing it with @var{knil}.
2123 @end deffn
2124
2125 @deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2126 @deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2127 This is a fundamental constructor for character sets.
2128 @itemize @bullet
2129 @item @var{g} is used to generate a series of ``seed'' values
2130 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2131 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2132 @item @var{p} tells us when to stop -- when it returns true
2133 when applied to one of the seed values.
2134 @item @var{f} maps each seed value to a character. These
2135 characters are added to the base character set @var{base_cs} to
2136 form the result; @var{base_cs} defaults to the empty set.
2137 @end itemize
2138 @end deffn
2139
2140 @deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2141 @deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2142 This is a fundamental constructor for character sets.
2143 @itemize @bullet
2144 @item @var{g} is used to generate a series of ``seed'' values
2145 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2146 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2147 @item @var{p} tells us when to stop -- when it returns true
2148 when applied to one of the seed values.
2149 @item @var{f} maps each seed value to a character. These
2150 characters are added to the base character set @var{base_cs} to
2151 form the result; @var{base_cs} defaults to the empty set.
2152 @end itemize
2153 @end deffn
2154
2155 @deffn {Scheme Procedure} char-set-for-each proc cs
2156 @deffnx {C Function} scm_char_set_for_each (proc, cs)
2157 Apply @var{proc} to every character in the character set
2158 @var{cs}. The return value is not specified.
2159 @end deffn
2160
2161 @deffn {Scheme Procedure} char-set-map proc cs
2162 @deffnx {C Function} scm_char_set_map (proc, cs)
2163 Map the procedure @var{proc} over every character in @var{cs}.
2164 @var{proc} must be a character -> character procedure.
2165 @end deffn
2166
2167 @c ===================================================================
2168
2169 @node Creating Character Sets
2170 @subsubsection Creating Character Sets
2171
2172 New character sets are produced with these procedures.
2173
2174 @deffn {Scheme Procedure} char-set-copy cs
2175 @deffnx {C Function} scm_char_set_copy (cs)
2176 Return a newly allocated character set containing all
2177 characters in @var{cs}.
2178 @end deffn
2179
2180 @deffn {Scheme Procedure} char-set . rest
2181 @deffnx {C Function} scm_char_set (rest)
2182 Return a character set containing all given characters.
2183 @end deffn
2184
2185 @deffn {Scheme Procedure} list->char-set list [base_cs]
2186 @deffnx {C Function} scm_list_to_char_set (list, base_cs)
2187 Convert the character list @var{list} to a character set. If
2188 the character set @var{base_cs} is given, the character in this
2189 set are also included in the result.
2190 @end deffn
2191
2192 @deffn {Scheme Procedure} list->char-set! list base_cs
2193 @deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2194 Convert the character list @var{list} to a character set. The
2195 characters are added to @var{base_cs} and @var{base_cs} is
2196 returned.
2197 @end deffn
2198
2199 @deffn {Scheme Procedure} string->char-set str [base_cs]
2200 @deffnx {C Function} scm_string_to_char_set (str, base_cs)
2201 Convert the string @var{str} to a character set. If the
2202 character set @var{base_cs} is given, the characters in this
2203 set are also included in the result.
2204 @end deffn
2205
2206 @deffn {Scheme Procedure} string->char-set! str base_cs
2207 @deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2208 Convert the string @var{str} to a character set. The
2209 characters from the string are added to @var{base_cs}, and
2210 @var{base_cs} is returned.
2211 @end deffn
2212
2213 @deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2214 @deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2215 Return a character set containing every character from @var{cs}
2216 so that it satisfies @var{pred}. If provided, the characters
2217 from @var{base_cs} are added to the result.
2218 @end deffn
2219
2220 @deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2221 @deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2222 Return a character set containing every character from @var{cs}
2223 so that it satisfies @var{pred}. The characters are added to
2224 @var{base_cs} and @var{base_cs} is returned.
2225 @end deffn
2226
2227 @deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2228 @deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2229 Return a character set containing all characters whose
2230 character codes lie in the half-open range
2231 [@var{lower},@var{upper}).
2232
2233 If @var{error} is a true value, an error is signalled if the
2234 specified range contains characters which are not contained in
2235 the implemented character range. If @var{error} is @code{#f},
2236 these characters are silently left out of the resulting
2237 character set.
2238
2239 The characters in @var{base_cs} are added to the result, if
2240 given.
2241 @end deffn
2242
2243 @deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2244 @deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2245 Return a character set containing all characters whose
2246 character codes lie in the half-open range
2247 [@var{lower},@var{upper}).
2248
2249 If @var{error} is a true value, an error is signalled if the
2250 specified range contains characters which are not contained in
2251 the implemented character range. If @var{error} is @code{#f},
2252 these characters are silently left out of the resulting
2253 character set.
2254
2255 The characters are added to @var{base_cs} and @var{base_cs} is
2256 returned.
2257 @end deffn
2258
2259 @deffn {Scheme Procedure} ->char-set x
2260 @deffnx {C Function} scm_to_char_set (x)
2261 Coerces x into a char-set. @var{x} may be a string, character or
2262 char-set. A string is converted to the set of its constituent
2263 characters; a character is converted to a singleton set; a char-set is
2264 returned as-is.
2265 @end deffn
2266
2267 @c ===================================================================
2268
2269 @node Querying Character Sets
2270 @subsubsection Querying Character Sets
2271
2272 Access the elements and other information of a character set with these
2273 procedures.
2274
2275 @deffn {Scheme Procedure} %char-set-dump cs
2276 Returns an association list containing debugging information
2277 for @var{cs}. The association list has the following entries.
2278 @table @code
2279 @item char-set
2280 The char-set itself
2281 @item len
2282 The number of groups of contiguous code points the char-set
2283 contains
2284 @item ranges
2285 A list of lists where each sublist is a range of code points
2286 and their associated characters
2287 @end table
2288 The return value of this function cannot be relied upon to be
2289 consistent between versions of Guile and should not be used in code.
2290 @end deffn
2291
2292 @deffn {Scheme Procedure} char-set-size cs
2293 @deffnx {C Function} scm_char_set_size (cs)
2294 Return the number of elements in character set @var{cs}.
2295 @end deffn
2296
2297 @deffn {Scheme Procedure} char-set-count pred cs
2298 @deffnx {C Function} scm_char_set_count (pred, cs)
2299 Return the number of the elements int the character set
2300 @var{cs} which satisfy the predicate @var{pred}.
2301 @end deffn
2302
2303 @deffn {Scheme Procedure} char-set->list cs
2304 @deffnx {C Function} scm_char_set_to_list (cs)
2305 Return a list containing the elements of the character set
2306 @var{cs}.
2307 @end deffn
2308
2309 @deffn {Scheme Procedure} char-set->string cs
2310 @deffnx {C Function} scm_char_set_to_string (cs)
2311 Return a string containing the elements of the character set
2312 @var{cs}. The order in which the characters are placed in the
2313 string is not defined.
2314 @end deffn
2315
2316 @deffn {Scheme Procedure} char-set-contains? cs ch
2317 @deffnx {C Function} scm_char_set_contains_p (cs, ch)
2318 Return @code{#t} iff the character @var{ch} is contained in the
2319 character set @var{cs}.
2320 @end deffn
2321
2322 @deffn {Scheme Procedure} char-set-every pred cs
2323 @deffnx {C Function} scm_char_set_every (pred, cs)
2324 Return a true value if every character in the character set
2325 @var{cs} satisfies the predicate @var{pred}.
2326 @end deffn
2327
2328 @deffn {Scheme Procedure} char-set-any pred cs
2329 @deffnx {C Function} scm_char_set_any (pred, cs)
2330 Return a true value if any character in the character set
2331 @var{cs} satisfies the predicate @var{pred}.
2332 @end deffn
2333
2334 @c ===================================================================
2335
2336 @node Character-Set Algebra
2337 @subsubsection Character-Set Algebra
2338
2339 Character sets can be manipulated with the common set algebra operation,
2340 such as union, complement, intersection etc. All of these procedures
2341 provide side-effecting variants, which modify their character set
2342 argument(s).
2343
2344 @deffn {Scheme Procedure} char-set-adjoin cs . rest
2345 @deffnx {C Function} scm_char_set_adjoin (cs, rest)
2346 Add all character arguments to the first argument, which must
2347 be a character set.
2348 @end deffn
2349
2350 @deffn {Scheme Procedure} char-set-delete cs . rest
2351 @deffnx {C Function} scm_char_set_delete (cs, rest)
2352 Delete all character arguments from the first argument, which
2353 must be a character set.
2354 @end deffn
2355
2356 @deffn {Scheme Procedure} char-set-adjoin! cs . rest
2357 @deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2358 Add all character arguments to the first argument, which must
2359 be a character set.
2360 @end deffn
2361
2362 @deffn {Scheme Procedure} char-set-delete! cs . rest
2363 @deffnx {C Function} scm_char_set_delete_x (cs, rest)
2364 Delete all character arguments from the first argument, which
2365 must be a character set.
2366 @end deffn
2367
2368 @deffn {Scheme Procedure} char-set-complement cs
2369 @deffnx {C Function} scm_char_set_complement (cs)
2370 Return the complement of the character set @var{cs}.
2371 @end deffn
2372
2373 Note that the complement of a character set is likely to contain many
2374 reserved code points (code points that are not associated with
2375 characters). It may be helpful to modify the output of
2376 @code{char-set-complement} by computing its intersection with the set
2377 of designated code points, @code{char-set:designated}.
2378
2379 @deffn {Scheme Procedure} char-set-union . rest
2380 @deffnx {C Function} scm_char_set_union (rest)
2381 Return the union of all argument character sets.
2382 @end deffn
2383
2384 @deffn {Scheme Procedure} char-set-intersection . rest
2385 @deffnx {C Function} scm_char_set_intersection (rest)
2386 Return the intersection of all argument character sets.
2387 @end deffn
2388
2389 @deffn {Scheme Procedure} char-set-difference cs1 . rest
2390 @deffnx {C Function} scm_char_set_difference (cs1, rest)
2391 Return the difference of all argument character sets.
2392 @end deffn
2393
2394 @deffn {Scheme Procedure} char-set-xor . rest
2395 @deffnx {C Function} scm_char_set_xor (rest)
2396 Return the exclusive-or of all argument character sets.
2397 @end deffn
2398
2399 @deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2400 @deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2401 Return the difference and the intersection of all argument
2402 character sets.
2403 @end deffn
2404
2405 @deffn {Scheme Procedure} char-set-complement! cs
2406 @deffnx {C Function} scm_char_set_complement_x (cs)
2407 Return the complement of the character set @var{cs}.
2408 @end deffn
2409
2410 @deffn {Scheme Procedure} char-set-union! cs1 . rest
2411 @deffnx {C Function} scm_char_set_union_x (cs1, rest)
2412 Return the union of all argument character sets.
2413 @end deffn
2414
2415 @deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2416 @deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2417 Return the intersection of all argument character sets.
2418 @end deffn
2419
2420 @deffn {Scheme Procedure} char-set-difference! cs1 . rest
2421 @deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2422 Return the difference of all argument character sets.
2423 @end deffn
2424
2425 @deffn {Scheme Procedure} char-set-xor! cs1 . rest
2426 @deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2427 Return the exclusive-or of all argument character sets.
2428 @end deffn
2429
2430 @deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2431 @deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2432 Return the difference and the intersection of all argument
2433 character sets.
2434 @end deffn
2435
2436 @c ===================================================================
2437
2438 @node Standard Character Sets
2439 @subsubsection Standard Character Sets
2440
2441 In order to make the use of the character set data type and procedures
2442 useful, several predefined character set variables exist.
2443
2444 @cindex codeset
2445 @cindex charset
2446 @cindex locale
2447
2448 These character sets are locale independent and are not recomputed
2449 upon a @code{setlocale} call. They contain characters from the whole
2450 range of Unicode code points. For instance, @code{char-set:letter}
2451 contains about 94,000 characters.
2452
2453 @defvr {Scheme Variable} char-set:lower-case
2454 @defvrx {C Variable} scm_char_set_lower_case
2455 All lower-case characters.
2456 @end defvr
2457
2458 @defvr {Scheme Variable} char-set:upper-case
2459 @defvrx {C Variable} scm_char_set_upper_case
2460 All upper-case characters.
2461 @end defvr
2462
2463 @defvr {Scheme Variable} char-set:title-case
2464 @defvrx {C Variable} scm_char_set_title_case
2465 All single characters that function as if they were an upper-case
2466 letter followed by a lower-case letter.
2467 @end defvr
2468
2469 @defvr {Scheme Variable} char-set:letter
2470 @defvrx {C Variable} scm_char_set_letter
2471 All letters. This includes @code{char-set:lower-case},
2472 @code{char-set:upper-case}, @code{char-set:title-case}, and many
2473 letters that have no case at all. For example, Chinese and Japanese
2474 characters typically have no concept of case.
2475 @end defvr
2476
2477 @defvr {Scheme Variable} char-set:digit
2478 @defvrx {C Variable} scm_char_set_digit
2479 All digits.
2480 @end defvr
2481
2482 @defvr {Scheme Variable} char-set:letter+digit
2483 @defvrx {C Variable} scm_char_set_letter_and_digit
2484 The union of @code{char-set:letter} and @code{char-set:digit}.
2485 @end defvr
2486
2487 @defvr {Scheme Variable} char-set:graphic
2488 @defvrx {C Variable} scm_char_set_graphic
2489 All characters which would put ink on the paper.
2490 @end defvr
2491
2492 @defvr {Scheme Variable} char-set:printing
2493 @defvrx {C Variable} scm_char_set_printing
2494 The union of @code{char-set:graphic} and @code{char-set:whitespace}.
2495 @end defvr
2496
2497 @defvr {Scheme Variable} char-set:whitespace
2498 @defvrx {C Variable} scm_char_set_whitespace
2499 All whitespace characters.
2500 @end defvr
2501
2502 @defvr {Scheme Variable} char-set:blank
2503 @defvrx {C Variable} scm_char_set_blank
2504 All horizontal whitespace characters, which notably includes
2505 @code{#\space} and @code{#\tab}.
2506 @end defvr
2507
2508 @defvr {Scheme Variable} char-set:iso-control
2509 @defvrx {C Variable} scm_char_set_iso_control
2510 The ISO control characters are the C0 control characters (U+0000 to
2511 U+001F), delete (U+007F), and the C1 control characters (U+0080 to
2512 U+009F).
2513 @end defvr
2514
2515 @defvr {Scheme Variable} char-set:punctuation
2516 @defvrx {C Variable} scm_char_set_punctuation
2517 All punctuation characters, such as the characters
2518 @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
2519 @end defvr
2520
2521 @defvr {Scheme Variable} char-set:symbol
2522 @defvrx {C Variable} scm_char_set_symbol
2523 All symbol characters, such as the characters @code{$+<=>^`|~}.
2524 @end defvr
2525
2526 @defvr {Scheme Variable} char-set:hex-digit
2527 @defvrx {C Variable} scm_char_set_hex_digit
2528 The hexadecimal digits @code{0123456789abcdefABCDEF}.
2529 @end defvr
2530
2531 @defvr {Scheme Variable} char-set:ascii
2532 @defvrx {C Variable} scm_char_set_ascii
2533 All ASCII characters.
2534 @end defvr
2535
2536 @defvr {Scheme Variable} char-set:empty
2537 @defvrx {C Variable} scm_char_set_empty
2538 The empty character set.
2539 @end defvr
2540
2541 @defvr {Scheme Variable} char-set:designated
2542 @defvrx {C Variable} scm_char_set_designated
2543 This character set contains all designated code points. This includes
2544 all the code points to which Unicode has assigned a character or other
2545 meaning.
2546 @end defvr
2547
2548 @defvr {Scheme Variable} char-set:full
2549 @defvrx {C Variable} scm_char_set_full
2550 This character set contains all possible code points. This includes
2551 both designated and reserved code points.
2552 @end defvr
2553
2554 @node Strings
2555 @subsection Strings
2556 @tpindex Strings
2557
2558 Strings are fixed-length sequences of characters. They can be created
2559 by calling constructor procedures, but they can also literally get
2560 entered at the @acronym{REPL} or in Scheme source files.
2561
2562 @c Guile provides a rich set of string processing procedures, because text
2563 @c handling is very important when Guile is used as a scripting language.
2564
2565 Strings always carry the information about how many characters they are
2566 composed of with them, so there is no special end-of-string character,
2567 like in C. That means that Scheme strings can contain any character,
2568 even the @samp{#\nul} character @samp{\0}.
2569
2570 To use strings efficiently, you need to know a bit about how Guile
2571 implements them. In Guile, a string consists of two parts, a head and
2572 the actual memory where the characters are stored. When a string (or
2573 a substring of it) is copied, only a new head gets created, the memory
2574 is usually not copied. The two heads start out pointing to the same
2575 memory.
2576
2577 When one of these two strings is modified, as with @code{string-set!},
2578 their common memory does get copied so that each string has its own
2579 memory and modifying one does not accidentally modify the other as well.
2580 Thus, Guile's strings are `copy on write'; the actual copying of their
2581 memory is delayed until one string is written to.
2582
2583 This implementation makes functions like @code{substring} very
2584 efficient in the common case that no modifications are done to the
2585 involved strings.
2586
2587 If you do know that your strings are getting modified right away, you
2588 can use @code{substring/copy} instead of @code{substring}. This
2589 function performs the copy immediately at the time of creation. This
2590 is more efficient, especially in a multi-threaded program. Also,
2591 @code{substring/copy} can avoid the problem that a short substring
2592 holds on to the memory of a very large original string that could
2593 otherwise be recycled.
2594
2595 If you want to avoid the copy altogether, so that modifications of one
2596 string show up in the other, you can use @code{substring/shared}. The
2597 strings created by this procedure are called @dfn{mutation sharing
2598 substrings} since the substring and the original string share
2599 modifications to each other.
2600
2601 If you want to prevent modifications, use @code{substring/read-only}.
2602
2603 Guile provides all procedures of SRFI-13 and a few more.
2604
2605 @menu
2606 * String Syntax:: Read syntax for strings.
2607 * String Predicates:: Testing strings for certain properties.
2608 * String Constructors:: Creating new string objects.
2609 * List/String Conversion:: Converting from/to lists of characters.
2610 * String Selection:: Select portions from strings.
2611 * String Modification:: Modify parts or whole strings.
2612 * String Comparison:: Lexicographic ordering predicates.
2613 * String Searching:: Searching in strings.
2614 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2615 * Reversing and Appending Strings:: Appending strings to form a new string.
2616 * Mapping Folding and Unfolding:: Iterating over strings.
2617 * Miscellaneous String Operations:: Replicating, insertion, parsing, ...
2618 * Conversion to/from C::
2619 * String Internals:: The storage strategy for strings.
2620 @end menu
2621
2622 @node String Syntax
2623 @subsubsection String Read Syntax
2624
2625 @c In the following @code is used to get a good font in TeX etc, but
2626 @c is omitted for Info format, so as not to risk any confusion over
2627 @c whether surrounding ` ' quotes are part of the escape or are
2628 @c special in a string (they're not).
2629
2630 The read syntax for strings is an arbitrarily long sequence of
2631 characters enclosed in double quotes (@nicode{"}).
2632
2633 Backslash is an escape character and can be used to insert the following
2634 special characters. @nicode{\"} and @nicode{\\} are R5RS standard, the
2635 next seven are R6RS standard --- notice they follow C syntax --- and the
2636 remaining four are Guile extensions.
2637
2638 @table @asis
2639 @item @nicode{\\}
2640 Backslash character.
2641
2642 @item @nicode{\"}
2643 Double quote character (an unescaped @nicode{"} is otherwise the end
2644 of the string).
2645
2646 @item @nicode{\a}
2647 Bell character (ASCII 7).
2648
2649 @item @nicode{\f}
2650 Formfeed character (ASCII 12).
2651
2652 @item @nicode{\n}
2653 Newline character (ASCII 10).
2654
2655 @item @nicode{\r}
2656 Carriage return character (ASCII 13).
2657
2658 @item @nicode{\t}
2659 Tab character (ASCII 9).
2660
2661 @item @nicode{\v}
2662 Vertical tab character (ASCII 11).
2663
2664 @item @nicode{\b}
2665 Backspace character (ASCII 8).
2666
2667 @item @nicode{\0}
2668 NUL character (ASCII 0).
2669
2670 @item @nicode{\} followed by newline (ASCII 10)
2671 Nothing. This way if @nicode{\} is the last character in a line, the
2672 string will continue with the first character from the next line,
2673 without a line break.
2674
2675 If the @code{hungry-eol-escapes} reader option is enabled, which is not
2676 the case by default, leading whitespace on the next line is discarded.
2677
2678 @lisp
2679 "foo\
2680 bar"
2681 @result{} "foo bar"
2682 (read-enable 'hungry-eol-escapes)
2683 "foo\
2684 bar"
2685 @result{} "foobar"
2686 @end lisp
2687 @item @nicode{\xHH}
2688 Character code given by two hexadecimal digits. For example
2689 @nicode{\x7f} for an ASCII DEL (127).
2690
2691 @item @nicode{\uHHHH}
2692 Character code given by four hexadecimal digits. For example
2693 @nicode{\u0100} for a capital A with macron (U+0100).
2694
2695 @item @nicode{\UHHHHHH}
2696 Character code given by six hexadecimal digits. For example
2697 @nicode{\U010402}.
2698 @end table
2699
2700 @noindent
2701 The following are examples of string literals:
2702
2703 @lisp
2704 "foo"
2705 "bar plonk"
2706 "Hello World"
2707 "\"Hi\", he said."
2708 @end lisp
2709
2710 The three escape sequences @code{\xHH}, @code{\uHHHH} and @code{\UHHHHHH} were
2711 chosen to not break compatibility with code written for previous versions of
2712 Guile. The R6RS specification suggests a different, incompatible syntax for hex
2713 escapes: @code{\xHHHH;} -- a character code followed by one to eight hexadecimal
2714 digits terminated with a semicolon. If this escape format is desired instead,
2715 it can be enabled with the reader option @code{r6rs-hex-escapes}.
2716
2717 @lisp
2718 (read-enable 'r6rs-hex-escapes)
2719 @end lisp
2720
2721 For more on reader options, @xref{Scheme Read}.
2722
2723 @node String Predicates
2724 @subsubsection String Predicates
2725
2726 The following procedures can be used to check whether a given string
2727 fulfills some specified property.
2728
2729 @rnindex string?
2730 @deffn {Scheme Procedure} string? obj
2731 @deffnx {C Function} scm_string_p (obj)
2732 Return @code{#t} if @var{obj} is a string, else @code{#f}.
2733 @end deffn
2734
2735 @deftypefn {C Function} int scm_is_string (SCM obj)
2736 Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2737 @end deftypefn
2738
2739 @deffn {Scheme Procedure} string-null? str
2740 @deffnx {C Function} scm_string_null_p (str)
2741 Return @code{#t} if @var{str}'s length is zero, and
2742 @code{#f} otherwise.
2743 @lisp
2744 (string-null? "") @result{} #t
2745 y @result{} "foo"
2746 (string-null? y) @result{} #f
2747 @end lisp
2748 @end deffn
2749
2750 @deffn {Scheme Procedure} string-any char_pred s [start [end]]
2751 @deffnx {C Function} scm_string_any (char_pred, s, start, end)
2752 Check if @var{char_pred} is true for any character in string @var{s}.
2753
2754 @var{char_pred} can be a character to check for any equal to that, or
2755 a character set (@pxref{Character Sets}) to check for any in that set,
2756 or a predicate procedure to call.
2757
2758 For a procedure, calls @code{(@var{char_pred} c)} are made
2759 successively on the characters from @var{start} to @var{end}. If
2760 @var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2761 stops and that return value is the return from @code{string-any}. The
2762 call on the last character (ie.@: at @math{@var{end}-1}), if that
2763 point is reached, is a tail call.
2764
2765 If there are no characters in @var{s} (ie.@: @var{start} equals
2766 @var{end}) then the return is @code{#f}.
2767 @end deffn
2768
2769 @deffn {Scheme Procedure} string-every char_pred s [start [end]]
2770 @deffnx {C Function} scm_string_every (char_pred, s, start, end)
2771 Check if @var{char_pred} is true for every character in string
2772 @var{s}.
2773
2774 @var{char_pred} can be a character to check for every character equal
2775 to that, or a character set (@pxref{Character Sets}) to check for
2776 every character being in that set, or a predicate procedure to call.
2777
2778 For a procedure, calls @code{(@var{char_pred} c)} are made
2779 successively on the characters from @var{start} to @var{end}. If
2780 @var{char_pred} returns @code{#f}, @code{string-every} stops and
2781 returns @code{#f}. The call on the last character (ie.@: at
2782 @math{@var{end}-1}), if that point is reached, is a tail call and the
2783 return from that call is the return from @code{string-every}.
2784
2785 If there are no characters in @var{s} (ie.@: @var{start} equals
2786 @var{end}) then the return is @code{#t}.
2787 @end deffn
2788
2789 @node String Constructors
2790 @subsubsection String Constructors
2791
2792 The string constructor procedures create new string objects, possibly
2793 initializing them with some specified character data. See also
2794 @xref{String Selection}, for ways to create strings from existing
2795 strings.
2796
2797 @c FIXME::martin: list->string belongs into `List/String Conversion'
2798
2799 @deffn {Scheme Procedure} string char@dots{}
2800 @rnindex string
2801 Return a newly allocated string made from the given character
2802 arguments.
2803
2804 @example
2805 (string #\x #\y #\z) @result{} "xyz"
2806 (string) @result{} ""
2807 @end example
2808 @end deffn
2809
2810 @deffn {Scheme Procedure} list->string lst
2811 @deffnx {C Function} scm_string (lst)
2812 @rnindex list->string
2813 Return a newly allocated string made from a list of characters.
2814
2815 @example
2816 (list->string '(#\a #\b #\c)) @result{} "abc"
2817 @end example
2818 @end deffn
2819
2820 @deffn {Scheme Procedure} reverse-list->string lst
2821 @deffnx {C Function} scm_reverse_list_to_string (lst)
2822 Return a newly allocated string made from a list of characters, in
2823 reverse order.
2824
2825 @example
2826 (reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2827 @end example
2828 @end deffn
2829
2830 @rnindex make-string
2831 @deffn {Scheme Procedure} make-string k [chr]
2832 @deffnx {C Function} scm_make_string (k, chr)
2833 Return a newly allocated string of
2834 length @var{k}. If @var{chr} is given, then all elements of
2835 the string are initialized to @var{chr}, otherwise the contents
2836 of the @var{string} are unspecified.
2837 @end deffn
2838
2839 @deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2840 Like @code{scm_make_string}, but expects the length as a
2841 @code{size_t}.
2842 @end deftypefn
2843
2844 @deffn {Scheme Procedure} string-tabulate proc len
2845 @deffnx {C Function} scm_string_tabulate (proc, len)
2846 @var{proc} is an integer->char procedure. Construct a string
2847 of size @var{len} by applying @var{proc} to each index to
2848 produce the corresponding string element. The order in which
2849 @var{proc} is applied to the indices is not specified.
2850 @end deffn
2851
2852 @deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2853 @deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2854 Append the string in the string list @var{ls}, using the string
2855 @var{delim} as a delimiter between the elements of @var{ls}.
2856 @var{grammar} is a symbol which specifies how the delimiter is
2857 placed between the strings, and defaults to the symbol
2858 @code{infix}.
2859
2860 @table @code
2861 @item infix
2862 Insert the separator between list elements. An empty string
2863 will produce an empty list.
2864 @item string-infix
2865 Like @code{infix}, but will raise an error if given the empty
2866 list.
2867 @item suffix
2868 Insert the separator after every list element.
2869 @item prefix
2870 Insert the separator before each list element.
2871 @end table
2872 @end deffn
2873
2874 @node List/String Conversion
2875 @subsubsection List/String conversion
2876
2877 When processing strings, it is often convenient to first convert them
2878 into a list representation by using the procedure @code{string->list},
2879 work with the resulting list, and then convert it back into a string.
2880 These procedures are useful for similar tasks.
2881
2882 @rnindex string->list
2883 @deffn {Scheme Procedure} string->list str [start [end]]
2884 @deffnx {C Function} scm_substring_to_list (str, start, end)
2885 @deffnx {C Function} scm_string_to_list (str)
2886 Convert the string @var{str} into a list of characters.
2887 @end deffn
2888
2889 @deffn {Scheme Procedure} string-split str chr
2890 @deffnx {C Function} scm_string_split (str, chr)
2891 Split the string @var{str} into the a list of the substrings delimited
2892 by appearances of the character @var{chr}. Note that an empty substring
2893 between separator characters will result in an empty string in the
2894 result list.
2895
2896 @lisp
2897 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2898 @result{}
2899 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
2900
2901 (string-split "::" #\:)
2902 @result{}
2903 ("" "" "")
2904
2905 (string-split "" #\:)
2906 @result{}
2907 ("")
2908 @end lisp
2909 @end deffn
2910
2911
2912 @node String Selection
2913 @subsubsection String Selection
2914
2915 Portions of strings can be extracted by these procedures.
2916 @code{string-ref} delivers individual characters whereas
2917 @code{substring} can be used to extract substrings from longer strings.
2918
2919 @rnindex string-length
2920 @deffn {Scheme Procedure} string-length string
2921 @deffnx {C Function} scm_string_length (string)
2922 Return the number of characters in @var{string}.
2923 @end deffn
2924
2925 @deftypefn {C Function} size_t scm_c_string_length (SCM str)
2926 Return the number of characters in @var{str} as a @code{size_t}.
2927 @end deftypefn
2928
2929 @rnindex string-ref
2930 @deffn {Scheme Procedure} string-ref str k
2931 @deffnx {C Function} scm_string_ref (str, k)
2932 Return character @var{k} of @var{str} using zero-origin
2933 indexing. @var{k} must be a valid index of @var{str}.
2934 @end deffn
2935
2936 @deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2937 Return character @var{k} of @var{str} using zero-origin
2938 indexing. @var{k} must be a valid index of @var{str}.
2939 @end deftypefn
2940
2941 @rnindex string-copy
2942 @deffn {Scheme Procedure} string-copy str [start [end]]
2943 @deffnx {C Function} scm_substring_copy (str, start, end)
2944 @deffnx {C Function} scm_string_copy (str)
2945 Return a copy of the given string @var{str}.
2946
2947 The returned string shares storage with @var{str} initially, but it is
2948 copied as soon as one of the two strings is modified.
2949 @end deffn
2950
2951 @rnindex substring
2952 @deffn {Scheme Procedure} substring str start [end]
2953 @deffnx {C Function} scm_substring (str, start, end)
2954 Return a new string formed from the characters
2955 of @var{str} beginning with index @var{start} (inclusive) and
2956 ending with index @var{end} (exclusive).
2957 @var{str} must be a string, @var{start} and @var{end} must be
2958 exact integers satisfying:
2959
2960 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
2961
2962 The returned string shares storage with @var{str} initially, but it is
2963 copied as soon as one of the two strings is modified.
2964 @end deffn
2965
2966 @deffn {Scheme Procedure} substring/shared str start [end]
2967 @deffnx {C Function} scm_substring_shared (str, start, end)
2968 Like @code{substring}, but the strings continue to share their storage
2969 even if they are modified. Thus, modifications to @var{str} show up
2970 in the new string, and vice versa.
2971 @end deffn
2972
2973 @deffn {Scheme Procedure} substring/copy str start [end]
2974 @deffnx {C Function} scm_substring_copy (str, start, end)
2975 Like @code{substring}, but the storage for the new string is copied
2976 immediately.
2977 @end deffn
2978
2979 @deffn {Scheme Procedure} substring/read-only str start [end]
2980 @deffnx {C Function} scm_substring_read_only (str, start, end)
2981 Like @code{substring}, but the resulting string can not be modified.
2982 @end deffn
2983
2984 @deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2985 @deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2986 @deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2987 @deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
2988 Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2989 @end deftypefn
2990
2991 @deffn {Scheme Procedure} string-take s n
2992 @deffnx {C Function} scm_string_take (s, n)
2993 Return the @var{n} first characters of @var{s}.
2994 @end deffn
2995
2996 @deffn {Scheme Procedure} string-drop s n
2997 @deffnx {C Function} scm_string_drop (s, n)
2998 Return all but the first @var{n} characters of @var{s}.
2999 @end deffn
3000
3001 @deffn {Scheme Procedure} string-take-right s n
3002 @deffnx {C Function} scm_string_take_right (s, n)
3003 Return the @var{n} last characters of @var{s}.
3004 @end deffn
3005
3006 @deffn {Scheme Procedure} string-drop-right s n
3007 @deffnx {C Function} scm_string_drop_right (s, n)
3008 Return all but the last @var{n} characters of @var{s}.
3009 @end deffn
3010
3011 @deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
3012 @deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
3013 @deffnx {C Function} scm_string_pad (s, len, chr, start, end)
3014 @deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
3015 Take characters @var{start} to @var{end} from the string @var{s} and
3016 either pad with @var{char} or truncate them to give @var{len}
3017 characters.
3018
3019 @code{string-pad} pads or truncates on the left, so for example
3020
3021 @example
3022 (string-pad "x" 3) @result{} " x"
3023 (string-pad "abcde" 3) @result{} "cde"
3024 @end example
3025
3026 @code{string-pad-right} pads or truncates on the right, so for example
3027
3028 @example
3029 (string-pad-right "x" 3) @result{} "x "
3030 (string-pad-right "abcde" 3) @result{} "abc"
3031 @end example
3032 @end deffn
3033
3034 @deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
3035 @deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
3036 @deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
3037 @deffnx {C Function} scm_string_trim (s, char_pred, start, end)
3038 @deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
3039 @deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
3040 Trim occurrences of @var{char_pred} from the ends of @var{s}.
3041
3042 @code{string-trim} trims @var{char_pred} characters from the left
3043 (start) of the string, @code{string-trim-right} trims them from the
3044 right (end) of the string, @code{string-trim-both} trims from both
3045 ends.
3046
3047 @var{char_pred} can be a character, a character set, or a predicate
3048 procedure to call on each character. If @var{char_pred} is not given
3049 the default is whitespace as per @code{char-set:whitespace}
3050 (@pxref{Standard Character Sets}).
3051
3052 @example
3053 (string-trim " x ") @result{} "x "
3054 (string-trim-right "banana" #\a) @result{} "banan"
3055 (string-trim-both ".,xy:;" char-set:punctuation)
3056 @result{} "xy"
3057 (string-trim-both "xyzzy" (lambda (c)
3058 (or (eqv? c #\x)
3059 (eqv? c #\y))))
3060 @result{} "zz"
3061 @end example
3062 @end deffn
3063
3064 @node String Modification
3065 @subsubsection String Modification
3066
3067 These procedures are for modifying strings in-place. This means that the
3068 result of the operation is not a new string; instead, the original string's
3069 memory representation is modified.
3070
3071 @rnindex string-set!
3072 @deffn {Scheme Procedure} string-set! str k chr
3073 @deffnx {C Function} scm_string_set_x (str, k, chr)
3074 Store @var{chr} in element @var{k} of @var{str} and return
3075 an unspecified value. @var{k} must be a valid index of
3076 @var{str}.
3077 @end deffn
3078
3079 @deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
3080 Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
3081 @end deftypefn
3082
3083 @rnindex string-fill!
3084 @deffn {Scheme Procedure} string-fill! str chr [start [end]]
3085 @deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
3086 @deffnx {C Function} scm_string_fill_x (str, chr)
3087 Stores @var{chr} in every element of the given @var{str} and
3088 returns an unspecified value.
3089 @end deffn
3090
3091 @deffn {Scheme Procedure} substring-fill! str start end fill
3092 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
3093 Change every character in @var{str} between @var{start} and
3094 @var{end} to @var{fill}.
3095
3096 @lisp
3097 (define y "abcdefg")
3098 (substring-fill! y 1 3 #\r)
3099 y
3100 @result{} "arrdefg"
3101 @end lisp
3102 @end deffn
3103
3104 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
3105 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
3106 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
3107 into @var{str2} beginning at position @var{start2}.
3108 @var{str1} and @var{str2} can be the same string.
3109 @end deffn
3110
3111 @deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
3112 @deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
3113 Copy the sequence of characters from index range [@var{start},
3114 @var{end}) in string @var{s} to string @var{target}, beginning
3115 at index @var{tstart}. The characters are copied left-to-right
3116 or right-to-left as needed -- the copy is guaranteed to work,
3117 even if @var{target} and @var{s} are the same string. It is an
3118 error if the copy operation runs off the end of the target
3119 string.
3120 @end deffn
3121
3122
3123 @node String Comparison
3124 @subsubsection String Comparison
3125
3126 The procedures in this section are similar to the character ordering
3127 predicates (@pxref{Characters}), but are defined on character sequences.
3128
3129 The first set is specified in R5RS and has names that end in @code{?}.
3130 The second set is specified in SRFI-13 and the names have not ending
3131 @code{?}.
3132
3133 The predicates ending in @code{-ci} ignore the character case
3134 when comparing strings. For now, case-insensitive comparison is done
3135 using the R5RS rules, where every lower-case character that has a
3136 single character upper-case form is converted to uppercase before
3137 comparison. See @xref{Text Collation, the @code{(ice-9
3138 i18n)} module}, for locale-dependent string comparison.
3139
3140 @rnindex string=?
3141 @deffn {Scheme Procedure} string=? [s1 [s2 . rest]]
3142 @deffnx {C Function} scm_i_string_equal_p (s1, s2, rest)
3143 Lexicographic equality predicate; return @code{#t} if the two
3144 strings are the same length and contain the same characters in
3145 the same positions, otherwise return @code{#f}.
3146
3147 The procedure @code{string-ci=?} treats upper and lower case
3148 letters as though they were the same character, but
3149 @code{string=?} treats upper and lower case as distinct
3150 characters.
3151 @end deffn
3152
3153 @rnindex string<?
3154 @deffn {Scheme Procedure} string<? [s1 [s2 . rest]]
3155 @deffnx {C Function} scm_i_string_less_p (s1, s2, rest)
3156 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3157 is lexicographically less than @var{s2}.
3158 @end deffn
3159
3160 @rnindex string<=?
3161 @deffn {Scheme Procedure} string<=? [s1 [s2 . rest]]
3162 @deffnx {C Function} scm_i_string_leq_p (s1, s2, rest)
3163 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3164 is lexicographically less than or equal to @var{s2}.
3165 @end deffn
3166
3167 @rnindex string>?
3168 @deffn {Scheme Procedure} string>? [s1 [s2 . rest]]
3169 @deffnx {C Function} scm_i_string_gr_p (s1, s2, rest)
3170 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3171 is lexicographically greater than @var{s2}.
3172 @end deffn
3173
3174 @rnindex string>=?
3175 @deffn {Scheme Procedure} string>=? [s1 [s2 . rest]]
3176 @deffnx {C Function} scm_i_string_geq_p (s1, s2, rest)
3177 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3178 is lexicographically greater than or equal to @var{s2}.
3179 @end deffn
3180
3181 @rnindex string-ci=?
3182 @deffn {Scheme Procedure} string-ci=? [s1 [s2 . rest]]
3183 @deffnx {C Function} scm_i_string_ci_equal_p (s1, s2, rest)
3184 Case-insensitive string equality predicate; return @code{#t} if
3185 the two strings are the same length and their component
3186 characters match (ignoring case) at each position; otherwise
3187 return @code{#f}.
3188 @end deffn
3189
3190 @rnindex string-ci<?
3191 @deffn {Scheme Procedure} string-ci<? [s1 [s2 . rest]]
3192 @deffnx {C Function} scm_i_string_ci_less_p (s1, s2, rest)
3193 Case insensitive lexicographic ordering predicate; return
3194 @code{#t} if @var{s1} is lexicographically less than @var{s2}
3195 regardless of case.
3196 @end deffn
3197
3198 @rnindex string<=?
3199 @deffn {Scheme Procedure} string-ci<=? [s1 [s2 . rest]]
3200 @deffnx {C Function} scm_i_string_ci_leq_p (s1, s2, rest)
3201 Case insensitive lexicographic ordering predicate; return
3202 @code{#t} if @var{s1} is lexicographically less than or equal
3203 to @var{s2} regardless of case.
3204 @end deffn
3205
3206 @rnindex string-ci>?
3207 @deffn {Scheme Procedure} string-ci>? [s1 [s2 . rest]]
3208 @deffnx {C Function} scm_i_string_ci_gr_p (s1, s2, rest)
3209 Case insensitive lexicographic ordering predicate; return
3210 @code{#t} if @var{s1} is lexicographically greater than
3211 @var{s2} regardless of case.
3212 @end deffn
3213
3214 @rnindex string-ci>=?
3215 @deffn {Scheme Procedure} string-ci>=? [s1 [s2 . rest]]
3216 @deffnx {C Function} scm_i_string_ci_geq_p (s1, s2, rest)
3217 Case insensitive lexicographic ordering predicate; return
3218 @code{#t} if @var{s1} is lexicographically greater than or
3219 equal to @var{s2} regardless of case.
3220 @end deffn
3221
3222 @deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3223 @deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3224 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3225 mismatch index, depending upon whether @var{s1} is less than,
3226 equal to, or greater than @var{s2}. The mismatch index is the
3227 largest index @var{i} such that for every 0 <= @var{j} <
3228 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3229 @var{i} is the first position that does not match.
3230 @end deffn
3231
3232 @deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3233 @deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3234 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3235 mismatch index, depending upon whether @var{s1} is less than,
3236 equal to, or greater than @var{s2}. The mismatch index is the
3237 largest index @var{i} such that for every 0 <= @var{j} <
3238 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3239 @var{i} is the first position where the lowercased letters
3240 do not match.
3241
3242 @end deffn
3243
3244 @deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3245 @deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3246 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3247 value otherwise.
3248 @end deffn
3249
3250 @deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3251 @deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3252 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3253 value otherwise.
3254 @end deffn
3255
3256 @deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3257 @deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3258 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3259 true value otherwise.
3260 @end deffn
3261
3262 @deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3263 @deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3264 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3265 true value otherwise.
3266 @end deffn
3267
3268 @deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3269 @deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3270 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3271 value otherwise.
3272 @end deffn
3273
3274 @deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3275 @deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3276 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3277 otherwise.
3278 @end deffn
3279
3280 @deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3281 @deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3282 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3283 value otherwise. The character comparison is done
3284 case-insensitively.
3285 @end deffn
3286
3287 @deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3288 @deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3289 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3290 value otherwise. The character comparison is done
3291 case-insensitively.
3292 @end deffn
3293
3294 @deffn {Scheme Procedure} string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
3295 @deffnx {C Function} scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
3296 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3297 true value otherwise. The character comparison is done
3298 case-insensitively.
3299 @end deffn
3300
3301 @deffn {Scheme Procedure} string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
3302 @deffnx {C Function} scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
3303 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3304 true value otherwise. The character comparison is done
3305 case-insensitively.
3306 @end deffn
3307
3308 @deffn {Scheme Procedure} string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
3309 @deffnx {C Function} scm_string_ci_le (s1, s2, start1, end1, start2, end2)
3310 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3311 value otherwise. The character comparison is done
3312 case-insensitively.
3313 @end deffn
3314
3315 @deffn {Scheme Procedure} string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
3316 @deffnx {C Function} scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
3317 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3318 otherwise. The character comparison is done
3319 case-insensitively.
3320 @end deffn
3321
3322 @deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3323 @deffnx {C Function} scm_substring_hash (s, bound, start, end)
3324 Compute a hash value for @var{S}. the optional argument @var{bound} is a non-negative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).
3325 @end deffn
3326
3327 @deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3328 @deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3329 Compute a hash value for @var{S}. the optional argument @var{bound} is a non-negative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).
3330 @end deffn
3331
3332 Because the same visual appearance of an abstract Unicode character can
3333 be obtained via multiple sequences of Unicode characters, even the
3334 case-insensitive string comparison functions described above may return
3335 @code{#f} when presented with strings containing different
3336 representations of the same character. For example, the Unicode
3337 character ``LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE'' can be
3338 represented with a single character (U+1E69) or by the character ``LATIN
3339 SMALL LETTER S'' (U+0073) followed by the combining marks ``COMBINING
3340 DOT BELOW'' (U+0323) and ``COMBINING DOT ABOVE'' (U+0307).
3341
3342 For this reason, it is often desirable to ensure that the strings
3343 to be compared are using a mutually consistent representation for every
3344 character. The Unicode standard defines two methods of normalizing the
3345 contents of strings: Decomposition, which breaks composite characters
3346 into a set of constituent characters with an ordering defined by the
3347 Unicode Standard; and composition, which performs the converse.
3348
3349 There are two decomposition operations. ``Canonical decomposition''
3350 produces character sequences that share the same visual appearance as
3351 the original characters, while ``compatiblity decomposition'' produces
3352 ones whose visual appearances may differ from the originals but which
3353 represent the same abstract character.
3354
3355 These operations are encapsulated in the following set of normalization
3356 forms:
3357
3358 @table @dfn
3359 @item NFD
3360 Characters are decomposed to their canonical forms.
3361
3362 @item NFKD
3363 Characters are decomposed to their compatibility forms.
3364
3365 @item NFC
3366 Characters are decomposed to their canonical forms, then composed.
3367
3368 @item NFKC
3369 Characters are decomposed to their compatibility forms, then composed.
3370
3371 @end table
3372
3373 The functions below put their arguments into one of the forms described
3374 above.
3375
3376 @deffn {Scheme Procedure} string-normalize-nfd s
3377 @deffnx {C Function} scm_string_normalize_nfd (s)
3378 Return the @code{NFD} normalized form of @var{s}.
3379 @end deffn
3380
3381 @deffn {Scheme Procedure} string-normalize-nfkd s
3382 @deffnx {C Function} scm_string_normalize_nfkd (s)
3383 Return the @code{NFKD} normalized form of @var{s}.
3384 @end deffn
3385
3386 @deffn {Scheme Procedure} string-normalize-nfc s
3387 @deffnx {C Function} scm_string_normalize_nfc (s)
3388 Return the @code{NFC} normalized form of @var{s}.
3389 @end deffn
3390
3391 @deffn {Scheme Procedure} string-normalize-nfkc s
3392 @deffnx {C Function} scm_string_normalize_nfkc (s)
3393 Return the @code{NFKC} normalized form of @var{s}.
3394 @end deffn
3395
3396 @node String Searching
3397 @subsubsection String Searching
3398
3399 @deffn {Scheme Procedure} string-index s char_pred [start [end]]
3400 @deffnx {C Function} scm_string_index (s, char_pred, start, end)
3401 Search through the string @var{s} from left to right, returning
3402 the index of the first occurrence of a character which
3403
3404 @itemize @bullet
3405 @item
3406 equals @var{char_pred}, if it is character,
3407
3408 @item
3409 satisfies the predicate @var{char_pred}, if it is a procedure,
3410
3411 @item
3412 is in the set @var{char_pred}, if it is a character set.
3413 @end itemize
3414
3415 Return @code{#f} if no match is found.
3416 @end deffn
3417
3418 @deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3419 @deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3420 Search through the string @var{s} from right to left, returning
3421 the index of the last occurrence of a character which
3422
3423 @itemize @bullet
3424 @item
3425 equals @var{char_pred}, if it is character,
3426
3427 @item
3428 satisfies the predicate @var{char_pred}, if it is a procedure,
3429
3430 @item
3431 is in the set if @var{char_pred} is a character set.
3432 @end itemize
3433
3434 Return @code{#f} if no match is found.
3435 @end deffn
3436
3437 @deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3438 @deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3439 Return the length of the longest common prefix of the two
3440 strings.
3441 @end deffn
3442
3443 @deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3444 @deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3445 Return the length of the longest common prefix of the two
3446 strings, ignoring character case.
3447 @end deffn
3448
3449 @deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3450 @deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3451 Return the length of the longest common suffix of the two
3452 strings.
3453 @end deffn
3454
3455 @deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3456 @deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3457 Return the length of the longest common suffix of the two
3458 strings, ignoring character case.
3459 @end deffn
3460
3461 @deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3462 @deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3463 Is @var{s1} a prefix of @var{s2}?
3464 @end deffn
3465
3466 @deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3467 @deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3468 Is @var{s1} a prefix of @var{s2}, ignoring character case?
3469 @end deffn
3470
3471 @deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3472 @deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3473 Is @var{s1} a suffix of @var{s2}?
3474 @end deffn
3475
3476 @deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3477 @deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3478 Is @var{s1} a suffix of @var{s2}, ignoring character case?
3479 @end deffn
3480
3481 @deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3482 @deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3483 Search through the string @var{s} from right to left, returning
3484 the index of the last occurrence of a character which
3485
3486 @itemize @bullet
3487 @item
3488 equals @var{char_pred}, if it is character,
3489
3490 @item
3491 satisfies the predicate @var{char_pred}, if it is a procedure,
3492
3493 @item
3494 is in the set if @var{char_pred} is a character set.
3495 @end itemize
3496
3497 Return @code{#f} if no match is found.
3498 @end deffn
3499
3500 @deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3501 @deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3502 Search through the string @var{s} from left to right, returning
3503 the index of the first occurrence of a character which
3504
3505 @itemize @bullet
3506 @item
3507 does not equal @var{char_pred}, if it is character,
3508
3509 @item
3510 does not satisfy the predicate @var{char_pred}, if it is a
3511 procedure,
3512
3513 @item
3514 is not in the set if @var{char_pred} is a character set.
3515 @end itemize
3516 @end deffn
3517
3518 @deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3519 @deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3520 Search through the string @var{s} from right to left, returning
3521 the index of the last occurrence of a character which
3522
3523 @itemize @bullet
3524 @item
3525 does not equal @var{char_pred}, if it is character,
3526
3527 @item
3528 does not satisfy the predicate @var{char_pred}, if it is a
3529 procedure,
3530
3531 @item
3532 is not in the set if @var{char_pred} is a character set.
3533 @end itemize
3534 @end deffn
3535
3536 @deffn {Scheme Procedure} string-count s char_pred [start [end]]
3537 @deffnx {C Function} scm_string_count (s, char_pred, start, end)
3538 Return the count of the number of characters in the string
3539 @var{s} which
3540
3541 @itemize @bullet
3542 @item
3543 equals @var{char_pred}, if it is character,
3544
3545 @item
3546 satisfies the predicate @var{char_pred}, if it is a procedure.
3547
3548 @item
3549 is in the set @var{char_pred}, if it is a character set.
3550 @end itemize
3551 @end deffn
3552
3553 @deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3554 @deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3555 Does string @var{s1} contain string @var{s2}? Return the index
3556 in @var{s1} where @var{s2} occurs as a substring, or false.
3557 The optional start/end indices restrict the operation to the
3558 indicated substrings.
3559 @end deffn
3560
3561 @deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3562 @deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3563 Does string @var{s1} contain string @var{s2}? Return the index
3564 in @var{s1} where @var{s2} occurs as a substring, or false.
3565 The optional start/end indices restrict the operation to the
3566 indicated substrings. Character comparison is done
3567 case-insensitively.
3568 @end deffn
3569
3570 @node Alphabetic Case Mapping
3571 @subsubsection Alphabetic Case Mapping
3572
3573 These are procedures for mapping strings to their upper- or lower-case
3574 equivalents, respectively, or for capitalizing strings.
3575
3576 They use the basic case mapping rules for Unicode characters. No
3577 special language or context rules are considered. The resulting strings
3578 are guaranteed to be the same length as the input strings.
3579
3580 @xref{Character Case Mapping, the @code{(ice-9
3581 i18n)} module}, for locale-dependent case conversions.
3582
3583 @deffn {Scheme Procedure} string-upcase str [start [end]]
3584 @deffnx {C Function} scm_substring_upcase (str, start, end)
3585 @deffnx {C Function} scm_string_upcase (str)
3586 Upcase every character in @code{str}.
3587 @end deffn
3588
3589 @deffn {Scheme Procedure} string-upcase! str [start [end]]
3590 @deffnx {C Function} scm_substring_upcase_x (str, start, end)
3591 @deffnx {C Function} scm_string_upcase_x (str)
3592 Destructively upcase every character in @code{str}.
3593
3594 @lisp
3595 (string-upcase! y)
3596 @result{} "ARRDEFG"
3597 y
3598 @result{} "ARRDEFG"
3599 @end lisp
3600 @end deffn
3601
3602 @deffn {Scheme Procedure} string-downcase str [start [end]]
3603 @deffnx {C Function} scm_substring_downcase (str, start, end)
3604 @deffnx {C Function} scm_string_downcase (str)
3605 Downcase every character in @var{str}.
3606 @end deffn
3607
3608 @deffn {Scheme Procedure} string-downcase! str [start [end]]
3609 @deffnx {C Function} scm_substring_downcase_x (str, start, end)
3610 @deffnx {C Function} scm_string_downcase_x (str)
3611 Destructively downcase every character in @var{str}.
3612
3613 @lisp
3614 y
3615 @result{} "ARRDEFG"
3616 (string-downcase! y)
3617 @result{} "arrdefg"
3618 y
3619 @result{} "arrdefg"
3620 @end lisp
3621 @end deffn
3622
3623 @deffn {Scheme Procedure} string-capitalize str
3624 @deffnx {C Function} scm_string_capitalize (str)
3625 Return a freshly allocated string with the characters in
3626 @var{str}, where the first character of every word is
3627 capitalized.
3628 @end deffn
3629
3630 @deffn {Scheme Procedure} string-capitalize! str
3631 @deffnx {C Function} scm_string_capitalize_x (str)
3632 Upcase the first character of every word in @var{str}
3633 destructively and return @var{str}.
3634
3635 @lisp
3636 y @result{} "hello world"
3637 (string-capitalize! y) @result{} "Hello World"
3638 y @result{} "Hello World"
3639 @end lisp
3640 @end deffn
3641
3642 @deffn {Scheme Procedure} string-titlecase str [start [end]]
3643 @deffnx {C Function} scm_string_titlecase (str, start, end)
3644 Titlecase every first character in a word in @var{str}.
3645 @end deffn
3646
3647 @deffn {Scheme Procedure} string-titlecase! str [start [end]]
3648 @deffnx {C Function} scm_string_titlecase_x (str, start, end)
3649 Destructively titlecase every first character in a word in
3650 @var{str}.
3651 @end deffn
3652
3653 @node Reversing and Appending Strings
3654 @subsubsection Reversing and Appending Strings
3655
3656 @deffn {Scheme Procedure} string-reverse str [start [end]]
3657 @deffnx {C Function} scm_string_reverse (str, start, end)
3658 Reverse the string @var{str}. The optional arguments
3659 @var{start} and @var{end} delimit the region of @var{str} to
3660 operate on.
3661 @end deffn
3662
3663 @deffn {Scheme Procedure} string-reverse! str [start [end]]
3664 @deffnx {C Function} scm_string_reverse_x (str, start, end)
3665 Reverse the string @var{str} in-place. The optional arguments
3666 @var{start} and @var{end} delimit the region of @var{str} to
3667 operate on. The return value is unspecified.
3668 @end deffn
3669
3670 @rnindex string-append
3671 @deffn {Scheme Procedure} string-append . args
3672 @deffnx {C Function} scm_string_append (args)
3673 Return a newly allocated string whose characters form the
3674 concatenation of the given strings, @var{args}.
3675
3676 @example
3677 (let ((h "hello "))
3678 (string-append h "world"))
3679 @result{} "hello world"
3680 @end example
3681 @end deffn
3682
3683 @deffn {Scheme Procedure} string-append/shared . rest
3684 @deffnx {C Function} scm_string_append_shared (rest)
3685 Like @code{string-append}, but the result may share memory
3686 with the argument strings.
3687 @end deffn
3688
3689 @deffn {Scheme Procedure} string-concatenate ls
3690 @deffnx {C Function} scm_string_concatenate (ls)
3691 Append the elements of @var{ls} (which must be strings)
3692 together into a single string. Guaranteed to return a freshly
3693 allocated string.
3694 @end deffn
3695
3696 @deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3697 @deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3698 Without optional arguments, this procedure is equivalent to
3699
3700 @lisp
3701 (string-concatenate (reverse ls))
3702 @end lisp
3703
3704 If the optional argument @var{final_string} is specified, it is
3705 consed onto the beginning to @var{ls} before performing the
3706 list-reverse and string-concatenate operations. If @var{end}
3707 is given, only the characters of @var{final_string} up to index
3708 @var{end} are used.
3709
3710 Guaranteed to return a freshly allocated string.
3711 @end deffn
3712
3713 @deffn {Scheme Procedure} string-concatenate/shared ls
3714 @deffnx {C Function} scm_string_concatenate_shared (ls)
3715 Like @code{string-concatenate}, but the result may share memory
3716 with the strings in the list @var{ls}.
3717 @end deffn
3718
3719 @deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3720 @deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3721 Like @code{string-concatenate-reverse}, but the result may
3722 share memory with the strings in the @var{ls} arguments.
3723 @end deffn
3724
3725 @node Mapping Folding and Unfolding
3726 @subsubsection Mapping, Folding, and Unfolding
3727
3728 @deffn {Scheme Procedure} string-map proc s [start [end]]
3729 @deffnx {C Function} scm_string_map (proc, s, start, end)
3730 @var{proc} is a char->char procedure, it is mapped over
3731 @var{s}. The order in which the procedure is applied to the
3732 string elements is not specified.
3733 @end deffn
3734
3735 @deffn {Scheme Procedure} string-map! proc s [start [end]]
3736 @deffnx {C Function} scm_string_map_x (proc, s, start, end)
3737 @var{proc} is a char->char procedure, it is mapped over
3738 @var{s}. The order in which the procedure is applied to the
3739 string elements is not specified. The string @var{s} is
3740 modified in-place, the return value is not specified.
3741 @end deffn
3742
3743 @deffn {Scheme Procedure} string-for-each proc s [start [end]]
3744 @deffnx {C Function} scm_string_for_each (proc, s, start, end)
3745 @var{proc} is mapped over @var{s} in left-to-right order. The
3746 return value is not specified.
3747 @end deffn
3748
3749 @deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3750 @deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
3751 Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3752 right.
3753
3754 For example, to change characters to alternately upper and lower case,
3755
3756 @example
3757 (define str (string-copy "studly"))
3758 (string-for-each-index
3759 (lambda (i)
3760 (string-set! str i
3761 ((if (even? i) char-upcase char-downcase)
3762 (string-ref str i))))
3763 str)
3764 str @result{} "StUdLy"
3765 @end example
3766 @end deffn
3767
3768 @deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3769 @deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3770 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3771 as the terminating element, from left to right. @var{kons}
3772 must expect two arguments: The actual character and the last
3773 result of @var{kons}' application.
3774 @end deffn
3775
3776 @deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3777 @deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3778 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3779 as the terminating element, from right to left. @var{kons}
3780 must expect two arguments: The actual character and the last
3781 result of @var{kons}' application.
3782 @end deffn
3783
3784 @deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3785 @deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3786 @itemize @bullet
3787 @item @var{g} is used to generate a series of @emph{seed}
3788 values from the initial @var{seed}: @var{seed}, (@var{g}
3789 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3790 @dots{}
3791 @item @var{p} tells us when to stop -- when it returns true
3792 when applied to one of these seed values.
3793 @item @var{f} maps each seed value to the corresponding
3794 character in the result string. These chars are assembled
3795 into the string in a left-to-right order.
3796 @item @var{base} is the optional initial/leftmost portion
3797 of the constructed string; it default to the empty
3798 string.
3799 @item @var{make_final} is applied to the terminal seed
3800 value (on which @var{p} returns true) to produce
3801 the final/rightmost portion of the constructed string.
3802 The default is nothing extra.
3803 @end itemize
3804 @end deffn
3805
3806 @deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3807 @deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3808 @itemize @bullet
3809 @item @var{g} is used to generate a series of @emph{seed}
3810 values from the initial @var{seed}: @var{seed}, (@var{g}
3811 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3812 @dots{}
3813 @item @var{p} tells us when to stop -- when it returns true
3814 when applied to one of these seed values.
3815 @item @var{f} maps each seed value to the corresponding
3816 character in the result string. These chars are assembled
3817 into the string in a right-to-left order.
3818 @item @var{base} is the optional initial/rightmost portion
3819 of the constructed string; it default to the empty
3820 string.
3821 @item @var{make_final} is applied to the terminal seed
3822 value (on which @var{p} returns true) to produce
3823 the final/leftmost portion of the constructed string.
3824 It defaults to @code{(lambda (x) )}.
3825 @end itemize
3826 @end deffn
3827
3828 @node Miscellaneous String Operations
3829 @subsubsection Miscellaneous String Operations
3830
3831 @deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3832 @deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3833 This is the @emph{extended substring} procedure that implements
3834 replicated copying of a substring of some string.
3835
3836 @var{s} is a string, @var{start} and @var{end} are optional
3837 arguments that demarcate a substring of @var{s}, defaulting to
3838 0 and the length of @var{s}. Replicate this substring up and
3839 down index space, in both the positive and negative directions.
3840 @code{xsubstring} returns the substring of this string
3841 beginning at index @var{from}, and ending at @var{to}, which
3842 defaults to @var{from} + (@var{end} - @var{start}).
3843 @end deffn
3844
3845 @deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3846 @deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3847 Exactly the same as @code{xsubstring}, but the extracted text
3848 is written into the string @var{target} starting at index
3849 @var{tstart}. The operation is not defined if @code{(eq?
3850 @var{target} @var{s})} or these arguments share storage -- you
3851 cannot copy a string on top of itself.
3852 @end deffn
3853
3854 @deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3855 @deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3856 Return the string @var{s1}, but with the characters
3857 @var{start1} @dots{} @var{end1} replaced by the characters
3858 @var{start2} @dots{} @var{end2} from @var{s2}.
3859 @end deffn
3860
3861 @deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3862 @deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3863 Split the string @var{s} into a list of substrings, where each
3864 substring is a maximal non-empty contiguous sequence of
3865 characters from the character set @var{token_set}, which
3866 defaults to @code{char-set:graphic}.
3867 If @var{start} or @var{end} indices are provided, they restrict
3868 @code{string-tokenize} to operating on the indicated substring
3869 of @var{s}.
3870 @end deffn
3871
3872 @deffn {Scheme Procedure} string-filter char_pred s [start [end]]
3873 @deffnx {C Function} scm_string_filter (char_pred, s, start, end)
3874 Filter the string @var{s}, retaining only those characters which
3875 satisfy @var{char_pred}.
3876
3877 If @var{char_pred} is a procedure, it is applied to each character as
3878 a predicate, if it is a character, it is tested for equality and if it
3879 is a character set, it is tested for membership.
3880 @end deffn
3881
3882 @deffn {Scheme Procedure} string-delete char_pred s [start [end]]
3883 @deffnx {C Function} scm_string_delete (char_pred, s, start, end)
3884 Delete characters satisfying @var{char_pred} from @var{s}.
3885
3886 If @var{char_pred} is a procedure, it is applied to each character as
3887 a predicate, if it is a character, it is tested for equality and if it
3888 is a character set, it is tested for membership.
3889 @end deffn
3890
3891 @node Conversion to/from C
3892 @subsubsection Conversion to/from C
3893
3894 When creating a Scheme string from a C string or when converting a
3895 Scheme string to a C string, the concept of character encoding becomes
3896 important.
3897
3898 In C, a string is just a sequence of bytes, and the character encoding
3899 describes the relation between these bytes and the actual characters
3900 that make up the string. For Scheme strings, character encoding is
3901 not an issue (most of the time), since in Scheme you never get to see
3902 the bytes, only the characters.
3903
3904 Converting to C and converting from C each have their own challenges.
3905
3906 When converting from C to Scheme, it is important that the sequence of
3907 bytes in the C string be valid with respect to its encoding. ASCII
3908 strings, for example, can't have any bytes greater than 127. An ASCII
3909 byte greater than 127 is considered @emph{ill-formed} and cannot be
3910 converted into a Scheme character.
3911
3912 Problems can occur in the reverse operation as well. Not all character
3913 encodings can hold all possible Scheme characters. Some encodings, like
3914 ASCII for example, can only describe a small subset of all possible
3915 characters. So, when converting to C, one must first decide what to do
3916 with Scheme characters that can't be represented in the C string.
3917
3918 Converting a Scheme string to a C string will often allocate fresh
3919 memory to hold the result. You must take care that this memory is
3920 properly freed eventually. In many cases, this can be achieved by
3921 using @code{scm_dynwind_free} inside an appropriate dynwind context,
3922 @xref{Dynamic Wind}.
3923
3924 @deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3925 @deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3926 Creates a new Scheme string that has the same contents as @var{str} when
3927 interpreted in the locale character encoding of the
3928 @code{current-input-port}.
3929
3930 For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3931
3932 For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3933 @var{str} in bytes, and @var{str} does not need to be null-terminated.
3934 If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3935 null-terminated and the real length will be found with @code{strlen}.
3936
3937 If the C string is ill-formed, an error will be raised.
3938 @end deftypefn
3939
3940 @deftypefn {C Function} SCM scm_take_locale_string (char *str)
3941 @deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3942 Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3943 respectively, but also frees @var{str} with @code{free} eventually.
3944 Thus, you can use this function when you would free @var{str} anyway
3945 immediately after creating the Scheme string. In certain cases, Guile
3946 can then use @var{str} directly as its internal representation.
3947 @end deftypefn
3948
3949 @deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3950 @deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
3951 Returns a C string with the same contents as @var{str} in the locale
3952 encoding of the @code{current-output-port}. The C string must be freed
3953 with @code{free} eventually, maybe by using @code{scm_dynwind_free},
3954 @xref{Dynamic Wind}.
3955
3956 For @code{scm_to_locale_string}, the returned string is
3957 null-terminated and an error is signalled when @var{str} contains
3958 @code{#\nul} characters.
3959
3960 For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3961 @var{str} might contain @code{#\nul} characters and the length of the
3962 returned string in bytes is stored in @code{*@var{lenp}}. The
3963 returned string will not be null-terminated in this case. If
3964 @var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3965 @code{scm_to_locale_string}.
3966
3967 If a character in @var{str} cannot be represented in the locale encoding
3968 of the current output port, the port conversion strategy of the current
3969 output port will determine the result, @xref{Ports}. If output port's
3970 conversion strategy is @code{error}, an error will be raised. If it is
3971 @code{subsitute}, a replacement character, such as a question mark, will
3972 be inserted in its place. If it is @code{escape}, a hex escape will be
3973 inserted in its place.
3974 @end deftypefn
3975
3976 @deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3977 Puts @var{str} as a C string in the current locale encoding into the
3978 memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3979 @var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3980 more than that. No terminating @code{'\0'} will be stored.
3981
3982 The return value of @code{scm_to_locale_stringbuf} is the number of
3983 bytes that are needed for all of @var{str}, regardless of whether
3984 @var{buf} was large enough to hold them. Thus, when the return value
3985 is larger than @var{max_len}, only @var{max_len} bytes have been
3986 stored and you probably need to try again with a larger buffer.
3987 @end deftypefn
3988
3989 For most situations, string conversion should occur using the current
3990 locale, such as with the functions above. But there may be cases where
3991 one wants to convert strings from a character encoding other than the
3992 locale's character encoding. For these cases, the lower-level functions
3993 @code{scm_to_stringn} and @code{scm_from_stringn} are provided. These
3994 functions should seldom be necessary if one is properly using locales.
3995
3996 @deftp {C Type} scm_t_string_failed_conversion_handler
3997 This is an enumerated type that can take one of three values:
3998 @code{SCM_FAILED_CONVERSION_ERROR},
3999 @code{SCM_FAILED_CONVERSION_QUESTION_MARK}, and
4000 @code{SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE}. They are used to indicate
4001 a strategy for handling characters that cannot be converted to or from a
4002 given character encoding. @code{SCM_FAILED_CONVERSION_ERROR} indicates
4003 that a conversion should throw an error if some characters cannot be
4004 converted. @code{SCM_FAILED_CONVERSION_QUESTION_MARK} indicates that a
4005 conversion should replace unconvertable characters with the question
4006 mark character. And, @code{SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE}
4007 requests that a conversion should replace an unconvertable character
4008 with an escape sequence.
4009
4010 While all three strategies apply when converting Scheme strings to C,
4011 only @code{SCM_FAILED_CONVERSION_ERROR} and
4012 @code{SCM_FAILED_CONVERSION_QUESTION_MARK} can be used when converting C
4013 strings to Scheme.
4014 @end deftp
4015
4016 @deftypefn {C Function} char *scm_to_stringn (SCM str, size_t *lenp, const char *encoding, scm_t_string_failed_conversion_handler handler)
4017 This function returns a newly allocated C string from the Guile string
4018 @var{str}. The length of the string will be returned in @var{lenp}.
4019 The character encoding of the C string is passed as the ASCII,
4020 null-terminated C string @var{encoding}. The @var{handler} parameter
4021 gives a strategy for dealing with characters that cannot be converted
4022 into @var{encoding}.
4023
4024 If @var{lenp} is NULL, this function will return a null-terminated C
4025 string. It will throw an error if the string contains a null
4026 character.
4027 @end deftypefn
4028
4029 @deftypefn {C Function} SCM scm_from_stringn (const char *str, size_t len, const char *encoding, scm_t_string_failed_conversion_handler handler)
4030 This function returns a scheme string from the C string @var{str}. The
4031 length of the C string is input as @var{len}. The encoding of the C
4032 string is passed as the ASCII, null-terminated C string @code{encoding}.
4033 The @var{handler} parameters suggests a strategy for dealing with
4034 unconvertable characters.
4035 @end deftypefn
4036
4037 ISO-8859-1 is the most common 8-bit character encoding. This encoding
4038 is also referred to as the Latin-1 encoding. The following two
4039 conversion functions are provided to convert between Latin-1 C strings
4040 and Guile strings.
4041
4042 @deftypefn {C Function} SCM scm_from_latin1_stringn (const char *str, size_t len)
4043 @deftypefnx {C Function} SCM scm_from_utf8_stringn (const char *str, size_t len)
4044 @deftypefnx {C Function} SCM scm_from_utf32_stringn (const scm_t_wchar *str, size_t len)
4045 Return a scheme string from C string @var{str}, which is ISO-8859-1-,
4046 UTF-8-, or UTF-32-encoded, of length @var{len}. @var{len} is the number
4047 of bytes pointed to by @var{str} for @code{scm_from_latin1_stringn} and
4048 @code{scm_from_utf8_stringn}; it is the number of elements (code points)
4049 in @var{str} in the case of @code{scm_from_utf32_stringn}.
4050 @end deftypefn
4051
4052 @deftypefn {C function} char *scm_to_latin1_stringn (SCM str, size_t *lenp)
4053 @deftypefnx {C function} char *scm_to_utf8_stringn (SCM str, size_t *lenp)
4054 @deftypefnx {C function} scm_t_wchar *scm_to_utf32_stringn (SCM str, size_t *lenp)
4055 Return a newly allocated, ISO-8859-1-, UTF-8-, or UTF-32-encoded C string
4056 from Scheme string @var{str}. An error is thrown when @var{str}
4057 string cannot be converted to the specified encoding. If @var{lenp} is
4058 @code{NULL}, the returned C string will be null terminated, and an error
4059 will be thrown if the C string would otherwise contain null
4060 characters. If @var{lenp} is not NULL, the length of the string is
4061 returned in @var{lenp}, and the string is not null terminated.
4062 @end deftypefn
4063
4064 @node String Internals
4065 @subsubsection String Internals
4066
4067 Guile stores each string in memory as a contiguous array of Unicode code
4068 points along with an associated set of attributes. If all of the code
4069 points of a string have an integer range between 0 and 255 inclusive,
4070 the code point array is stored as one byte per code point: it is stored
4071 as an ISO-8859-1 (aka Latin-1) string. If any of the code points of the
4072 string has an integer value greater that 255, the code point array is
4073 stored as four bytes per code point: it is stored as a UTF-32 string.
4074
4075 Conversion between the one-byte-per-code-point and
4076 four-bytes-per-code-point representations happens automatically as
4077 necessary.
4078
4079 No API is provided to set the internal representation of strings;
4080 however, there are pair of procedures available to query it. These are
4081 debugging procedures. Using them in production code is discouraged,
4082 since the details of Guile's internal representation of strings may
4083 change from release to release.
4084
4085 @deffn {Scheme Procedure} string-bytes-per-char str
4086 @deffnx {C Function} scm_string_bytes_per_char (str)
4087 Return the number of bytes used to encode a Unicode code point in string
4088 @var{str}. The result is one or four.
4089 @end deffn
4090
4091 @deffn {Scheme Procedure} %string-dump str
4092 @deffnx {C Function} scm_sys_string_dump (str)
4093 Returns an association list containing debugging information for
4094 @var{str}. The association list has the following entries.
4095 @table @code
4096
4097 @item string
4098 The string itself.
4099
4100 @item start
4101 The start index of the string into its stringbuf
4102
4103 @item length
4104 The length of the string
4105
4106 @item shared
4107 If this string is a substring, it returns its
4108 parent string. Otherwise, it returns @code{#f}
4109
4110 @item read-only
4111 @code{#t} if the string is read-only
4112
4113 @item stringbuf-chars
4114 A new string containing this string's stringbuf's characters
4115
4116 @item stringbuf-length
4117 The number of characters in this stringbuf
4118
4119 @item stringbuf-shared
4120 @code{#t} if this stringbuf is shared
4121
4122 @item stringbuf-wide
4123 @code{#t} if this stringbuf's characters are stored in a 32-bit buffer,
4124 or @code{#f} if they are stored in an 8-bit buffer
4125 @end table
4126 @end deffn
4127
4128
4129 @node Bytevectors
4130 @subsection Bytevectors
4131
4132 @cindex bytevector
4133 @cindex R6RS
4134
4135 A @dfn{bytevector} is a raw bit string. The @code{(rnrs bytevectors)}
4136 module provides the programming interface specified by the
4137 @uref{http://www.r6rs.org/, Revised^6 Report on the Algorithmic Language
4138 Scheme (R6RS)}. It contains procedures to manipulate bytevectors and
4139 interpret their contents in a number of ways: bytevector contents can be
4140 accessed as signed or unsigned integer of various sizes and endianness,
4141 as IEEE-754 floating point numbers, or as strings. It is a useful tool
4142 to encode and decode binary data.
4143
4144 The R6RS (Section 4.3.4) specifies an external representation for
4145 bytevectors, whereby the octets (integers in the range 0--255) contained
4146 in the bytevector are represented as a list prefixed by @code{#vu8}:
4147
4148 @lisp
4149 #vu8(1 53 204)
4150 @end lisp
4151
4152 denotes a 3-byte bytevector containing the octets 1, 53, and 204. Like
4153 string literals, booleans, etc., bytevectors are ``self-quoting'', i.e.,
4154 they do not need to be quoted:
4155
4156 @lisp
4157 #vu8(1 53 204)
4158 @result{} #vu8(1 53 204)
4159 @end lisp
4160
4161 Bytevectors can be used with the binary input/output primitives of the
4162 R6RS (@pxref{R6RS I/O Ports}).
4163
4164 @menu
4165 * Bytevector Endianness:: Dealing with byte order.
4166 * Bytevector Manipulation:: Creating, copying, manipulating bytevectors.
4167 * Bytevectors as Integers:: Interpreting bytes as integers.
4168 * Bytevectors and Integer Lists:: Converting to/from an integer list.
4169 * Bytevectors as Floats:: Interpreting bytes as real numbers.
4170 * Bytevectors as Strings:: Interpreting bytes as Unicode strings.
4171 * Bytevectors as Generalized Vectors:: Guile extension to the bytevector API.
4172 * Bytevectors as Uniform Vectors:: Bytevectors and SRFI-4.
4173 @end menu
4174
4175 @node Bytevector Endianness
4176 @subsubsection Endianness
4177
4178 @cindex endianness
4179 @cindex byte order
4180 @cindex word order
4181
4182 Some of the following procedures take an @var{endianness} parameter.
4183 The @dfn{endianness} is defined as the order of bytes in multi-byte
4184 numbers: numbers encoded in @dfn{big endian} have their most
4185 significant bytes written first, whereas numbers encoded in
4186 @dfn{little endian} have their least significant bytes
4187 first@footnote{Big-endian and little-endian are the most common
4188 ``endiannesses'', but others do exist. For instance, the GNU MP
4189 library allows @dfn{word order} to be specified independently of
4190 @dfn{byte order} (@pxref{Integer Import and Export,,, gmp, The GNU
4191 Multiple Precision Arithmetic Library Manual}).}.
4192
4193 Little-endian is the native endianness of the IA32 architecture and
4194 its derivatives, while big-endian is native to SPARC and PowerPC,
4195 among others. The @code{native-endianness} procedure returns the
4196 native endianness of the machine it runs on.
4197
4198 @deffn {Scheme Procedure} native-endianness
4199 @deffnx {C Function} scm_native_endianness ()
4200 Return a value denoting the native endianness of the host machine.
4201 @end deffn
4202
4203 @deffn {Scheme Macro} endianness symbol
4204 Return an object denoting the endianness specified by @var{symbol}. If
4205 @var{symbol} is neither @code{big} nor @code{little} then an error is
4206 raised at expand-time.
4207 @end deffn
4208
4209 @defvr {C Variable} scm_endianness_big
4210 @defvrx {C Variable} scm_endianness_little
4211 The objects denoting big- and little-endianness, respectively.
4212 @end defvr
4213
4214
4215 @node Bytevector Manipulation
4216 @subsubsection Manipulating Bytevectors
4217
4218 Bytevectors can be created, copied, and analyzed with the following
4219 procedures and C functions.
4220
4221 @deffn {Scheme Procedure} make-bytevector len [fill]
4222 @deffnx {C Function} scm_make_bytevector (len, fill)
4223 @deffnx {C Function} scm_c_make_bytevector (size_t len)
4224 Return a new bytevector of @var{len} bytes. Optionally, if @var{fill}
4225 is given, fill it with @var{fill}; @var{fill} must be in the range
4226 [-128,255].
4227 @end deffn
4228
4229 @deffn {Scheme Procedure} bytevector? obj
4230 @deffnx {C Function} scm_bytevector_p (obj)
4231 Return true if @var{obj} is a bytevector.
4232 @end deffn
4233
4234 @deftypefn {C Function} int scm_is_bytevector (SCM obj)
4235 Equivalent to @code{scm_is_true (scm_bytevector_p (obj))}.
4236 @end deftypefn
4237
4238 @deffn {Scheme Procedure} bytevector-length bv
4239 @deffnx {C Function} scm_bytevector_length (bv)
4240 Return the length in bytes of bytevector @var{bv}.
4241 @end deffn
4242
4243 @deftypefn {C Function} size_t scm_c_bytevector_length (SCM bv)
4244 Likewise, return the length in bytes of bytevector @var{bv}.
4245 @end deftypefn
4246
4247 @deffn {Scheme Procedure} bytevector=? bv1 bv2
4248 @deffnx {C Function} scm_bytevector_eq_p (bv1, bv2)
4249 Return is @var{bv1} equals to @var{bv2}---i.e., if they have the same
4250 length and contents.
4251 @end deffn
4252
4253 @deffn {Scheme Procedure} bytevector-fill! bv fill
4254 @deffnx {C Function} scm_bytevector_fill_x (bv, fill)
4255 Fill bytevector @var{bv} with @var{fill}, a byte.
4256 @end deffn
4257
4258 @deffn {Scheme Procedure} bytevector-copy! source source-start target target-start len
4259 @deffnx {C Function} scm_bytevector_copy_x (source, source_start, target, target_start, len)
4260 Copy @var{len} bytes from @var{source} into @var{target}, starting
4261 reading from @var{source-start} (a positive index within @var{source})
4262 and start writing at @var{target-start}.
4263 @end deffn
4264
4265 @deffn {Scheme Procedure} bytevector-copy bv
4266 @deffnx {C Function} scm_bytevector_copy (bv)
4267 Return a newly allocated copy of @var{bv}.
4268 @end deffn
4269
4270 @deftypefn {C Function} scm_t_uint8 scm_c_bytevector_ref (SCM bv, size_t index)
4271 Return the byte at @var{index} in bytevector @var{bv}.
4272 @end deftypefn
4273
4274 @deftypefn {C Function} void scm_c_bytevector_set_x (SCM bv, size_t index, scm_t_uint8 value)
4275 Set the byte at @var{index} in @var{bv} to @var{value}.
4276 @end deftypefn
4277
4278 Low-level C macros are available. They do not perform any
4279 type-checking; as such they should be used with care.
4280
4281 @deftypefn {C Macro} size_t SCM_BYTEVECTOR_LENGTH (bv)
4282 Return the length in bytes of bytevector @var{bv}.
4283 @end deftypefn
4284
4285 @deftypefn {C Macro} {signed char *} SCM_BYTEVECTOR_CONTENTS (bv)
4286 Return a pointer to the contents of bytevector @var{bv}.
4287 @end deftypefn
4288
4289
4290 @node Bytevectors as Integers
4291 @subsubsection Interpreting Bytevector Contents as Integers
4292
4293 The contents of a bytevector can be interpreted as a sequence of
4294 integers of any given size, sign, and endianness.
4295
4296 @lisp
4297 (let ((bv (make-bytevector 4)))
4298 (bytevector-u8-set! bv 0 #x12)
4299 (bytevector-u8-set! bv 1 #x34)
4300 (bytevector-u8-set! bv 2 #x56)
4301 (bytevector-u8-set! bv 3 #x78)
4302
4303 (map (lambda (number)
4304 (number->string number 16))
4305 (list (bytevector-u8-ref bv 0)
4306 (bytevector-u16-ref bv 0 (endianness big))
4307 (bytevector-u32-ref bv 0 (endianness little)))))
4308
4309 @result{} ("12" "1234" "78563412")
4310 @end lisp
4311
4312 The most generic procedures to interpret bytevector contents as integers
4313 are described below.
4314
4315 @deffn {Scheme Procedure} bytevector-uint-ref bv index endianness size
4316 @deffnx {Scheme Procedure} bytevector-sint-ref bv index endianness size
4317 @deffnx {C Function} scm_bytevector_uint_ref (bv, index, endianness, size)
4318 @deffnx {C Function} scm_bytevector_sint_ref (bv, index, endianness, size)
4319 Return the @var{size}-byte long unsigned (resp. signed) integer at
4320 index @var{index} in @var{bv}, decoded according to @var{endianness}.
4321 @end deffn
4322
4323 @deffn {Scheme Procedure} bytevector-uint-set! bv index value endianness size
4324 @deffnx {Scheme Procedure} bytevector-sint-set! bv index value endianness size
4325 @deffnx {C Function} scm_bytevector_uint_set_x (bv, index, value, endianness, size)
4326 @deffnx {C Function} scm_bytevector_sint_set_x (bv, index, value, endianness, size)
4327 Set the @var{size}-byte long unsigned (resp. signed) integer at
4328 @var{index} to @var{value}, encoded according to @var{endianness}.
4329 @end deffn
4330
4331 The following procedures are similar to the ones above, but specialized
4332 to a given integer size:
4333
4334 @deffn {Scheme Procedure} bytevector-u8-ref bv index
4335 @deffnx {Scheme Procedure} bytevector-s8-ref bv index
4336 @deffnx {Scheme Procedure} bytevector-u16-ref bv index endianness
4337 @deffnx {Scheme Procedure} bytevector-s16-ref bv index endianness
4338 @deffnx {Scheme Procedure} bytevector-u32-ref bv index endianness
4339 @deffnx {Scheme Procedure} bytevector-s32-ref bv index endianness
4340 @deffnx {Scheme Procedure} bytevector-u64-ref bv index endianness
4341 @deffnx {Scheme Procedure} bytevector-s64-ref bv index endianness
4342 @deffnx {C Function} scm_bytevector_u8_ref (bv, index)
4343 @deffnx {C Function} scm_bytevector_s8_ref (bv, index)
4344 @deffnx {C Function} scm_bytevector_u16_ref (bv, index, endianness)
4345 @deffnx {C Function} scm_bytevector_s16_ref (bv, index, endianness)
4346 @deffnx {C Function} scm_bytevector_u32_ref (bv, index, endianness)
4347 @deffnx {C Function} scm_bytevector_s32_ref (bv, index, endianness)
4348 @deffnx {C Function} scm_bytevector_u64_ref (bv, index, endianness)
4349 @deffnx {C Function} scm_bytevector_s64_ref (bv, index, endianness)
4350 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4351 16, 32 or 64) from @var{bv} at @var{index}, decoded according to
4352 @var{endianness}.
4353 @end deffn
4354
4355 @deffn {Scheme Procedure} bytevector-u8-set! bv index value
4356 @deffnx {Scheme Procedure} bytevector-s8-set! bv index value
4357 @deffnx {Scheme Procedure} bytevector-u16-set! bv index value endianness
4358 @deffnx {Scheme Procedure} bytevector-s16-set! bv index value endianness
4359 @deffnx {Scheme Procedure} bytevector-u32-set! bv index value endianness
4360 @deffnx {Scheme Procedure} bytevector-s32-set! bv index value endianness
4361 @deffnx {Scheme Procedure} bytevector-u64-set! bv index value endianness
4362 @deffnx {Scheme Procedure} bytevector-s64-set! bv index value endianness
4363 @deffnx {C Function} scm_bytevector_u8_set_x (bv, index, value)
4364 @deffnx {C Function} scm_bytevector_s8_set_x (bv, index, value)
4365 @deffnx {C Function} scm_bytevector_u16_set_x (bv, index, value, endianness)
4366 @deffnx {C Function} scm_bytevector_s16_set_x (bv, index, value, endianness)
4367 @deffnx {C Function} scm_bytevector_u32_set_x (bv, index, value, endianness)
4368 @deffnx {C Function} scm_bytevector_s32_set_x (bv, index, value, endianness)
4369 @deffnx {C Function} scm_bytevector_u64_set_x (bv, index, value, endianness)
4370 @deffnx {C Function} scm_bytevector_s64_set_x (bv, index, value, endianness)
4371 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4372 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to
4373 @var{endianness}.
4374 @end deffn
4375
4376 Finally, a variant specialized for the host's endianness is available
4377 for each of these functions (with the exception of the @code{u8}
4378 accessors, for obvious reasons):
4379
4380 @deffn {Scheme Procedure} bytevector-u16-native-ref bv index
4381 @deffnx {Scheme Procedure} bytevector-s16-native-ref bv index
4382 @deffnx {Scheme Procedure} bytevector-u32-native-ref bv index
4383 @deffnx {Scheme Procedure} bytevector-s32-native-ref bv index
4384 @deffnx {Scheme Procedure} bytevector-u64-native-ref bv index
4385 @deffnx {Scheme Procedure} bytevector-s64-native-ref bv index
4386 @deffnx {C Function} scm_bytevector_u16_native_ref (bv, index)
4387 @deffnx {C Function} scm_bytevector_s16_native_ref (bv, index)
4388 @deffnx {C Function} scm_bytevector_u32_native_ref (bv, index)
4389 @deffnx {C Function} scm_bytevector_s32_native_ref (bv, index)
4390 @deffnx {C Function} scm_bytevector_u64_native_ref (bv, index)
4391 @deffnx {C Function} scm_bytevector_s64_native_ref (bv, index)
4392 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4393 16, 32 or 64) from @var{bv} at @var{index}, decoded according to the
4394 host's native endianness.
4395 @end deffn
4396
4397 @deffn {Scheme Procedure} bytevector-u16-native-set! bv index value
4398 @deffnx {Scheme Procedure} bytevector-s16-native-set! bv index value
4399 @deffnx {Scheme Procedure} bytevector-u32-native-set! bv index value
4400 @deffnx {Scheme Procedure} bytevector-s32-native-set! bv index value
4401 @deffnx {Scheme Procedure} bytevector-u64-native-set! bv index value
4402 @deffnx {Scheme Procedure} bytevector-s64-native-set! bv index value
4403 @deffnx {C Function} scm_bytevector_u16_native_set_x (bv, index, value)
4404 @deffnx {C Function} scm_bytevector_s16_native_set_x (bv, index, value)
4405 @deffnx {C Function} scm_bytevector_u32_native_set_x (bv, index, value)
4406 @deffnx {C Function} scm_bytevector_s32_native_set_x (bv, index, value)
4407 @deffnx {C Function} scm_bytevector_u64_native_set_x (bv, index, value)
4408 @deffnx {C Function} scm_bytevector_s64_native_set_x (bv, index, value)
4409 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4410 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to the
4411 host's native endianness.
4412 @end deffn
4413
4414
4415 @node Bytevectors and Integer Lists
4416 @subsubsection Converting Bytevectors to/from Integer Lists
4417
4418 Bytevector contents can readily be converted to/from lists of signed or
4419 unsigned integers:
4420
4421 @lisp
4422 (bytevector->sint-list (u8-list->bytevector (make-list 4 255))
4423 (endianness little) 2)
4424 @result{} (-1 -1)
4425 @end lisp
4426
4427 @deffn {Scheme Procedure} bytevector->u8-list bv
4428 @deffnx {C Function} scm_bytevector_to_u8_list (bv)
4429 Return a newly allocated list of unsigned 8-bit integers from the
4430 contents of @var{bv}.
4431 @end deffn
4432
4433 @deffn {Scheme Procedure} u8-list->bytevector lst
4434 @deffnx {C Function} scm_u8_list_to_bytevector (lst)
4435 Return a newly allocated bytevector consisting of the unsigned 8-bit
4436 integers listed in @var{lst}.
4437 @end deffn
4438
4439 @deffn {Scheme Procedure} bytevector->uint-list bv endianness size
4440 @deffnx {Scheme Procedure} bytevector->sint-list bv endianness size
4441 @deffnx {C Function} scm_bytevector_to_uint_list (bv, endianness, size)
4442 @deffnx {C Function} scm_bytevector_to_sint_list (bv, endianness, size)
4443 Return a list of unsigned (resp. signed) integers of @var{size} bytes
4444 representing the contents of @var{bv}, decoded according to
4445 @var{endianness}.
4446 @end deffn
4447
4448 @deffn {Scheme Procedure} uint-list->bytevector lst endianness size
4449 @deffnx {Scheme Procedure} sint-list->bytevector lst endianness size
4450 @deffnx {C Function} scm_uint_list_to_bytevector (lst, endianness, size)
4451 @deffnx {C Function} scm_sint_list_to_bytevector (lst, endianness, size)
4452 Return a new bytevector containing the unsigned (resp. signed) integers
4453 listed in @var{lst} and encoded on @var{size} bytes according to
4454 @var{endianness}.
4455 @end deffn
4456
4457 @node Bytevectors as Floats
4458 @subsubsection Interpreting Bytevector Contents as Floating Point Numbers
4459
4460 @cindex IEEE-754 floating point numbers
4461
4462 Bytevector contents can also be accessed as IEEE-754 single- or
4463 double-precision floating point numbers (respectively 32 and 64-bit
4464 long) using the procedures described here.
4465
4466 @deffn {Scheme Procedure} bytevector-ieee-single-ref bv index endianness
4467 @deffnx {Scheme Procedure} bytevector-ieee-double-ref bv index endianness
4468 @deffnx {C Function} scm_bytevector_ieee_single_ref (bv, index, endianness)
4469 @deffnx {C Function} scm_bytevector_ieee_double_ref (bv, index, endianness)
4470 Return the IEEE-754 single-precision floating point number from @var{bv}
4471 at @var{index} according to @var{endianness}.
4472 @end deffn
4473
4474 @deffn {Scheme Procedure} bytevector-ieee-single-set! bv index value endianness
4475 @deffnx {Scheme Procedure} bytevector-ieee-double-set! bv index value endianness
4476 @deffnx {C Function} scm_bytevector_ieee_single_set_x (bv, index, value, endianness)
4477 @deffnx {C Function} scm_bytevector_ieee_double_set_x (bv, index, value, endianness)
4478 Store real number @var{value} in @var{bv} at @var{index} according to
4479 @var{endianness}.
4480 @end deffn
4481
4482 Specialized procedures are also available:
4483
4484 @deffn {Scheme Procedure} bytevector-ieee-single-native-ref bv index
4485 @deffnx {Scheme Procedure} bytevector-ieee-double-native-ref bv index
4486 @deffnx {C Function} scm_bytevector_ieee_single_native_ref (bv, index)
4487 @deffnx {C Function} scm_bytevector_ieee_double_native_ref (bv, index)
4488 Return the IEEE-754 single-precision floating point number from @var{bv}
4489 at @var{index} according to the host's native endianness.
4490 @end deffn
4491
4492 @deffn {Scheme Procedure} bytevector-ieee-single-native-set! bv index value
4493 @deffnx {Scheme Procedure} bytevector-ieee-double-native-set! bv index value
4494 @deffnx {C Function} scm_bytevector_ieee_single_native_set_x (bv, index, value)
4495 @deffnx {C Function} scm_bytevector_ieee_double_native_set_x (bv, index, value)
4496 Store real number @var{value} in @var{bv} at @var{index} according to
4497 the host's native endianness.
4498 @end deffn
4499
4500
4501 @node Bytevectors as Strings
4502 @subsubsection Interpreting Bytevector Contents as Unicode Strings
4503
4504 @cindex Unicode string encoding
4505
4506 Bytevector contents can also be interpreted as Unicode strings encoded
4507 in one of the most commonly available encoding formats.
4508
4509 @lisp
4510 (utf8->string (u8-list->bytevector '(99 97 102 101)))
4511 @result{} "cafe"
4512
4513 (string->utf8 "caf@'e") ;; SMALL LATIN LETTER E WITH ACUTE ACCENT
4514 @result{} #vu8(99 97 102 195 169)
4515 @end lisp
4516
4517 @deffn {Scheme Procedure} string->utf8 str
4518 @deffnx {Scheme Procedure} string->utf16 str [endianness]
4519 @deffnx {Scheme Procedure} string->utf32 str [endianness]
4520 @deffnx {C Function} scm_string_to_utf8 (str)
4521 @deffnx {C Function} scm_string_to_utf16 (str, endianness)
4522 @deffnx {C Function} scm_string_to_utf32 (str, endianness)
4523 Return a newly allocated bytevector that contains the UTF-8, UTF-16, or
4524 UTF-32 (aka. UCS-4) encoding of @var{str}. For UTF-16 and UTF-32,
4525 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4526 it defaults to big endian.
4527 @end deffn
4528
4529 @deffn {Scheme Procedure} utf8->string utf
4530 @deffnx {Scheme Procedure} utf16->string utf [endianness]
4531 @deffnx {Scheme Procedure} utf32->string utf [endianness]
4532 @deffnx {C Function} scm_utf8_to_string (utf)
4533 @deffnx {C Function} scm_utf16_to_string (utf, endianness)
4534 @deffnx {C Function} scm_utf32_to_string (utf, endianness)
4535 Return a newly allocated string that contains from the UTF-8-, UTF-16-,
4536 or UTF-32-decoded contents of bytevector @var{utf}. For UTF-16 and UTF-32,
4537 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4538 it defaults to big endian.
4539 @end deffn
4540
4541 @node Bytevectors as Generalized Vectors
4542 @subsubsection Accessing Bytevectors with the Generalized Vector API
4543
4544 As an extension to the R6RS, Guile allows bytevectors to be manipulated
4545 with the @dfn{generalized vector} procedures (@pxref{Generalized
4546 Vectors}). This also allows bytevectors to be accessed using the
4547 generic @dfn{array} procedures (@pxref{Array Procedures}). When using
4548 these APIs, bytes are accessed one at a time as 8-bit unsigned integers:
4549
4550 @example
4551 (define bv #vu8(0 1 2 3))
4552
4553 (generalized-vector? bv)
4554 @result{} #t
4555
4556 (generalized-vector-ref bv 2)
4557 @result{} 2
4558
4559 (generalized-vector-set! bv 2 77)
4560 (array-ref bv 2)
4561 @result{} 77
4562
4563 (array-type bv)
4564 @result{} vu8
4565 @end example
4566
4567
4568 @node Bytevectors as Uniform Vectors
4569 @subsubsection Accessing Bytevectors with the SRFI-4 API
4570
4571 Bytevectors may also be accessed with the SRFI-4 API. @xref{SRFI-4 and
4572 Bytevectors}, for more information.
4573
4574
4575 @node Symbols
4576 @subsection Symbols
4577 @tpindex Symbols
4578
4579 Symbols in Scheme are widely used in three ways: as items of discrete
4580 data, as lookup keys for alists and hash tables, and to denote variable
4581 references.
4582
4583 A @dfn{symbol} is similar to a string in that it is defined by a
4584 sequence of characters. The sequence of characters is known as the
4585 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
4586 name doesn't include any characters that could be confused with other
4587 elements of Scheme syntax --- a symbol is written in a Scheme program by
4588 writing the sequence of characters that make up the name, @emph{without}
4589 any quotation marks or other special syntax. For example, the symbol
4590 whose name is ``multiply-by-2'' is written, simply:
4591
4592 @lisp
4593 multiply-by-2
4594 @end lisp
4595
4596 Notice how this differs from a @emph{string} with contents
4597 ``multiply-by-2'', which is written with double quotation marks, like
4598 this:
4599
4600 @lisp
4601 "multiply-by-2"
4602 @end lisp
4603
4604 Looking beyond how they are written, symbols are different from strings
4605 in two important respects.
4606
4607 The first important difference is uniqueness. If the same-looking
4608 string is read twice from two different places in a program, the result
4609 is two @emph{different} string objects whose contents just happen to be
4610 the same. If, on the other hand, the same-looking symbol is read twice
4611 from two different places in a program, the result is the @emph{same}
4612 symbol object both times.
4613
4614 Given two read symbols, you can use @code{eq?} to test whether they are
4615 the same (that is, have the same name). @code{eq?} is the most
4616 efficient comparison operator in Scheme, and comparing two symbols like
4617 this is as fast as comparing, for example, two numbers. Given two
4618 strings, on the other hand, you must use @code{equal?} or
4619 @code{string=?}, which are much slower comparison operators, to
4620 determine whether the strings have the same contents.
4621
4622 @lisp
4623 (define sym1 (quote hello))
4624 (define sym2 (quote hello))
4625 (eq? sym1 sym2) @result{} #t
4626
4627 (define str1 "hello")
4628 (define str2 "hello")
4629 (eq? str1 str2) @result{} #f
4630 (equal? str1 str2) @result{} #t
4631 @end lisp
4632
4633 The second important difference is that symbols, unlike strings, are not
4634 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
4635 example above: @code{(quote hello)} evaluates to the symbol named
4636 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
4637 symbol named "hello" and evaluated as a variable reference @dots{} about
4638 which more below (@pxref{Symbol Variables}).
4639
4640 @menu
4641 * Symbol Data:: Symbols as discrete data.
4642 * Symbol Keys:: Symbols as lookup keys.
4643 * Symbol Variables:: Symbols as denoting variables.
4644 * Symbol Primitives:: Operations related to symbols.
4645 * Symbol Props:: Function slots and property lists.
4646 * Symbol Read Syntax:: Extended read syntax for symbols.
4647 * Symbol Uninterned:: Uninterned symbols.
4648 @end menu
4649
4650
4651 @node Symbol Data
4652 @subsubsection Symbols as Discrete Data
4653
4654 Numbers and symbols are similar to the extent that they both lend
4655 themselves to @code{eq?} comparison. But symbols are more descriptive
4656 than numbers, because a symbol's name can be used directly to describe
4657 the concept for which that symbol stands.
4658
4659 For example, imagine that you need to represent some colours in a
4660 computer program. Using numbers, you would have to choose arbitrarily
4661 some mapping between numbers and colours, and then take care to use that
4662 mapping consistently:
4663
4664 @lisp
4665 ;; 1=red, 2=green, 3=purple
4666
4667 (if (eq? (colour-of car) 1)
4668 ...)
4669 @end lisp
4670
4671 @noindent
4672 You can make the mapping more explicit and the code more readable by
4673 defining constants:
4674
4675 @lisp
4676 (define red 1)
4677 (define green 2)
4678 (define purple 3)
4679
4680 (if (eq? (colour-of car) red)
4681 ...)
4682 @end lisp
4683
4684 @noindent
4685 But the simplest and clearest approach is not to use numbers at all, but
4686 symbols whose names specify the colours that they refer to:
4687
4688 @lisp
4689 (if (eq? (colour-of car) 'red)
4690 ...)
4691 @end lisp
4692
4693 The descriptive advantages of symbols over numbers increase as the set
4694 of concepts that you want to describe grows. Suppose that a car object
4695 can have other properties as well, such as whether it has or uses:
4696
4697 @itemize @bullet
4698 @item
4699 automatic or manual transmission
4700 @item
4701 leaded or unleaded fuel
4702 @item
4703 power steering (or not).
4704 @end itemize
4705
4706 @noindent
4707 Then a car's combined property set could be naturally represented and
4708 manipulated as a list of symbols:
4709
4710 @lisp
4711 (properties-of car1)
4712 @result{}
4713 (red manual unleaded power-steering)
4714
4715 (if (memq 'power-steering (properties-of car1))
4716 (display "Unfit people can drive this car.\n")
4717 (display "You'll need strong arms to drive this car!\n"))
4718 @print{}
4719 Unfit people can drive this car.
4720 @end lisp
4721
4722 Remember, the fundamental property of symbols that we are relying on
4723 here is that an occurrence of @code{'red} in one part of a program is an
4724 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
4725 another part of a program; this means that symbols can usefully be
4726 compared using @code{eq?}. At the same time, symbols have naturally
4727 descriptive names. This combination of efficiency and descriptive power
4728 makes them ideal for use as discrete data.
4729
4730
4731 @node Symbol Keys
4732 @subsubsection Symbols as Lookup Keys
4733
4734 Given their efficiency and descriptive power, it is natural to use
4735 symbols as the keys in an association list or hash table.
4736
4737 To illustrate this, consider a more structured representation of the car
4738 properties example from the preceding subsection. Rather than
4739 mixing all the properties up together in a flat list, we could use an
4740 association list like this:
4741
4742 @lisp
4743 (define car1-properties '((colour . red)
4744 (transmission . manual)
4745 (fuel . unleaded)
4746 (steering . power-assisted)))
4747 @end lisp
4748
4749 Notice how this structure is more explicit and extensible than the flat
4750 list. For example it makes clear that @code{manual} refers to the
4751 transmission rather than, say, the windows or the locking of the car.
4752 It also allows further properties to use the same symbols among their
4753 possible values without becoming ambiguous:
4754
4755 @lisp
4756 (define car1-properties '((colour . red)
4757 (transmission . manual)
4758 (fuel . unleaded)
4759 (steering . power-assisted)
4760 (seat-colour . red)
4761 (locking . manual)))
4762 @end lisp
4763
4764 With a representation like this, it is easy to use the efficient
4765 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
4766 extract or change individual pieces of information:
4767
4768 @lisp
4769 (assq-ref car1-properties 'fuel) @result{} unleaded
4770 (assq-ref car1-properties 'transmission) @result{} manual
4771
4772 (assq-set! car1-properties 'seat-colour 'black)
4773 @result{}
4774 ((colour . red)
4775 (transmission . manual)
4776 (fuel . unleaded)
4777 (steering . power-assisted)
4778 (seat-colour . black)
4779 (locking . manual)))
4780 @end lisp
4781
4782 Hash tables also have keys, and exactly the same arguments apply to the
4783 use of symbols in hash tables as in association lists. The hash value
4784 that Guile uses to decide where to add a symbol-keyed entry to a hash
4785 table can be obtained by calling the @code{symbol-hash} procedure:
4786
4787 @deffn {Scheme Procedure} symbol-hash symbol
4788 @deffnx {C Function} scm_symbol_hash (symbol)
4789 Return a hash value for @var{symbol}.
4790 @end deffn
4791
4792 See @ref{Hash Tables} for information about hash tables in general, and
4793 for why you might choose to use a hash table rather than an association
4794 list.
4795
4796
4797 @node Symbol Variables
4798 @subsubsection Symbols as Denoting Variables
4799
4800 When an unquoted symbol in a Scheme program is evaluated, it is
4801 interpreted as a variable reference, and the result of the evaluation is
4802 the appropriate variable's value.
4803
4804 For example, when the expression @code{(string-length "abcd")} is read
4805 and evaluated, the sequence of characters @code{string-length} is read
4806 as the symbol whose name is "string-length". This symbol is associated
4807 with a variable whose value is the procedure that implements string
4808 length calculation. Therefore evaluation of the @code{string-length}
4809 symbol results in that procedure.
4810
4811 The details of the connection between an unquoted symbol and the
4812 variable to which it refers are explained elsewhere. See @ref{Binding
4813 Constructs}, for how associations between symbols and variables are
4814 created, and @ref{Modules}, for how those associations are affected by
4815 Guile's module system.
4816
4817
4818 @node Symbol Primitives
4819 @subsubsection Operations Related to Symbols
4820
4821 Given any Scheme value, you can determine whether it is a symbol using
4822 the @code{symbol?} primitive:
4823
4824 @rnindex symbol?
4825 @deffn {Scheme Procedure} symbol? obj
4826 @deffnx {C Function} scm_symbol_p (obj)
4827 Return @code{#t} if @var{obj} is a symbol, otherwise return
4828 @code{#f}.
4829 @end deffn
4830
4831 @deftypefn {C Function} int scm_is_symbol (SCM val)
4832 Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
4833 @end deftypefn
4834
4835 Once you know that you have a symbol, you can obtain its name as a
4836 string by calling @code{symbol->string}. Note that Guile differs by
4837 default from R5RS on the details of @code{symbol->string} as regards
4838 case-sensitivity:
4839
4840 @rnindex symbol->string
4841 @deffn {Scheme Procedure} symbol->string s
4842 @deffnx {C Function} scm_symbol_to_string (s)
4843 Return the name of symbol @var{s} as a string. By default, Guile reads
4844 symbols case-sensitively, so the string returned will have the same case
4845 variation as the sequence of characters that caused @var{s} to be
4846 created.
4847
4848 If Guile is set to read symbols case-insensitively (as specified by
4849 R5RS), and @var{s} comes into being as part of a literal expression
4850 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
4851 by a call to the @code{read} or @code{string-ci->symbol} procedures,
4852 Guile converts any alphabetic characters in the symbol's name to
4853 lower case before creating the symbol object, so the string returned
4854 here will be in lower case.
4855
4856 If @var{s} was created by @code{string->symbol}, the case of characters
4857 in the string returned will be the same as that in the string that was
4858 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
4859 setting at the time @var{s} was created.
4860
4861 It is an error to apply mutation procedures like @code{string-set!} to
4862 strings returned by this procedure.
4863 @end deffn
4864
4865 Most symbols are created by writing them literally in code. However it
4866 is also possible to create symbols programmatically using the following
4867 procedures:
4868
4869 @deffn {Scheme Procedure} symbol char@dots{}
4870 @rnindex symbol
4871 Return a newly allocated symbol made from the given character arguments.
4872
4873 @example
4874 (symbol #\x #\y #\z) @result{} xyz
4875 @end example
4876 @end deffn
4877
4878 @deffn {Scheme Procedure} list->symbol lst
4879 @rnindex list->symbol
4880 Return a newly allocated symbol made from a list of characters.
4881
4882 @example
4883 (list->symbol '(#\a #\b #\c)) @result{} abc
4884 @end example
4885 @end deffn
4886
4887 @rnindex symbol-append
4888 @deffn {Scheme Procedure} symbol-append . args
4889 Return a newly allocated symbol whose characters form the
4890 concatenation of the given symbols, @var{args}.
4891
4892 @example
4893 (let ((h 'hello))
4894 (symbol-append h 'world))
4895 @result{} helloworld
4896 @end example
4897 @end deffn
4898
4899 @rnindex string->symbol
4900 @deffn {Scheme Procedure} string->symbol string
4901 @deffnx {C Function} scm_string_to_symbol (string)
4902 Return the symbol whose name is @var{string}. This procedure can create
4903 symbols with names containing special characters or letters in the
4904 non-standard case, but it is usually a bad idea to create such symbols
4905 because in some implementations of Scheme they cannot be read as
4906 themselves.
4907 @end deffn
4908
4909 @deffn {Scheme Procedure} string-ci->symbol str
4910 @deffnx {C Function} scm_string_ci_to_symbol (str)
4911 Return the symbol whose name is @var{str}. If Guile is currently
4912 reading symbols case-insensitively, @var{str} is converted to lowercase
4913 before the returned symbol is looked up or created.
4914 @end deffn
4915
4916 The following examples illustrate Guile's detailed behaviour as regards
4917 the case-sensitivity of symbols:
4918
4919 @lisp
4920 (read-enable 'case-insensitive) ; R5RS compliant behaviour
4921
4922 (symbol->string 'flying-fish) @result{} "flying-fish"
4923 (symbol->string 'Martin) @result{} "martin"
4924 (symbol->string
4925 (string->symbol "Malvina")) @result{} "Malvina"
4926
4927 (eq? 'mISSISSIppi 'mississippi) @result{} #t
4928 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4929 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
4930 (eq? 'LolliPop
4931 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4932 (string=? "K. Harper, M.D."
4933 (symbol->string
4934 (string->symbol "K. Harper, M.D."))) @result{} #t
4935
4936 (read-disable 'case-insensitive) ; Guile default behaviour
4937
4938 (symbol->string 'flying-fish) @result{} "flying-fish"
4939 (symbol->string 'Martin) @result{} "Martin"
4940 (symbol->string
4941 (string->symbol "Malvina")) @result{} "Malvina"
4942
4943 (eq? 'mISSISSIppi 'mississippi) @result{} #f
4944 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4945 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
4946 (eq? 'LolliPop
4947 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4948 (string=? "K. Harper, M.D."
4949 (symbol->string
4950 (string->symbol "K. Harper, M.D."))) @result{} #t
4951 @end lisp
4952
4953 From C, there are lower level functions that construct a Scheme symbol
4954 from a C string in the current locale encoding.
4955
4956 When you want to do more from C, you should convert between symbols
4957 and strings using @code{scm_symbol_to_string} and
4958 @code{scm_string_to_symbol} and work with the strings.
4959
4960 @deffn {C Function} scm_from_locale_symbol (const char *name)
4961 @deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
4962 Construct and return a Scheme symbol whose name is specified by
4963 @var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
4964 terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
4965 specified explicitly by @var{len}.
4966 @end deffn
4967
4968 @deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
4969 @deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
4970 Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
4971 respectively, but also frees @var{str} with @code{free} eventually.
4972 Thus, you can use this function when you would free @var{str} anyway
4973 immediately after creating the Scheme string. In certain cases, Guile
4974 can then use @var{str} directly as its internal representation.
4975 @end deftypefn
4976
4977 The size of a symbol can also be obtained from C:
4978
4979 @deftypefn {C Function} size_t scm_c_symbol_length (SCM sym)
4980 Return the number of characters in @var{sym}.
4981 @end deftypefn
4982
4983 Finally, some applications, especially those that generate new Scheme
4984 code dynamically, need to generate symbols for use in the generated
4985 code. The @code{gensym} primitive meets this need:
4986
4987 @deffn {Scheme Procedure} gensym [prefix]
4988 @deffnx {C Function} scm_gensym (prefix)
4989 Create a new symbol with a name constructed from a prefix and a counter
4990 value. The string @var{prefix} can be specified as an optional
4991 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
4992 at each call. There is no provision for resetting the counter.
4993 @end deffn
4994
4995 The symbols generated by @code{gensym} are @emph{likely} to be unique,
4996 since their names begin with a space and it is only otherwise possible
4997 to generate such symbols if a programmer goes out of their way to do
4998 so. Uniqueness can be guaranteed by instead using uninterned symbols
4999 (@pxref{Symbol Uninterned}), though they can't be usefully written out
5000 and read back in.
5001
5002
5003 @node Symbol Props
5004 @subsubsection Function Slots and Property Lists
5005
5006 In traditional Lisp dialects, symbols are often understood as having
5007 three kinds of value at once:
5008
5009 @itemize @bullet
5010 @item
5011 a @dfn{variable} value, which is used when the symbol appears in
5012 code in a variable reference context
5013
5014 @item
5015 a @dfn{function} value, which is used when the symbol appears in
5016 code in a function name position (i.e. as the first element in an
5017 unquoted list)
5018
5019 @item
5020 a @dfn{property list} value, which is used when the symbol is given as
5021 the first argument to Lisp's @code{put} or @code{get} functions.
5022 @end itemize
5023
5024 Although Scheme (as one of its simplifications with respect to Lisp)
5025 does away with the distinction between variable and function namespaces,
5026 Guile currently retains some elements of the traditional structure in
5027 case they turn out to be useful when implementing translators for other
5028 languages, in particular Emacs Lisp.
5029
5030 Specifically, Guile symbols have two extra slots. for a symbol's
5031 property list, and for its ``function value.'' The following procedures
5032 are provided to access these slots.
5033
5034 @deffn {Scheme Procedure} symbol-fref symbol
5035 @deffnx {C Function} scm_symbol_fref (symbol)
5036 Return the contents of @var{symbol}'s @dfn{function slot}.
5037 @end deffn
5038
5039 @deffn {Scheme Procedure} symbol-fset! symbol value
5040 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
5041 Set the contents of @var{symbol}'s function slot to @var{value}.
5042 @end deffn
5043
5044 @deffn {Scheme Procedure} symbol-pref symbol
5045 @deffnx {C Function} scm_symbol_pref (symbol)
5046 Return the @dfn{property list} currently associated with @var{symbol}.
5047 @end deffn
5048
5049 @deffn {Scheme Procedure} symbol-pset! symbol value
5050 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
5051 Set @var{symbol}'s property list to @var{value}.
5052 @end deffn
5053
5054 @deffn {Scheme Procedure} symbol-property sym prop
5055 From @var{sym}'s property list, return the value for property
5056 @var{prop}. The assumption is that @var{sym}'s property list is an
5057 association list whose keys are distinguished from each other using
5058 @code{equal?}; @var{prop} should be one of the keys in that list. If
5059 the property list has no entry for @var{prop}, @code{symbol-property}
5060 returns @code{#f}.
5061 @end deffn
5062
5063 @deffn {Scheme Procedure} set-symbol-property! sym prop val
5064 In @var{sym}'s property list, set the value for property @var{prop} to
5065 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
5066 none already exists. For the structure of the property list, see
5067 @code{symbol-property}.
5068 @end deffn
5069
5070 @deffn {Scheme Procedure} symbol-property-remove! sym prop
5071 From @var{sym}'s property list, remove the entry for property
5072 @var{prop}, if there is one. For the structure of the property list,
5073 see @code{symbol-property}.
5074 @end deffn
5075
5076 Support for these extra slots may be removed in a future release, and it
5077 is probably better to avoid using them. For a more modern and Schemely
5078 approach to properties, see @ref{Object Properties}.
5079
5080
5081 @node Symbol Read Syntax
5082 @subsubsection Extended Read Syntax for Symbols
5083
5084 The read syntax for a symbol is a sequence of letters, digits, and
5085 @dfn{extended alphabetic characters}, beginning with a character that
5086 cannot begin a number. In addition, the special cases of @code{+},
5087 @code{-}, and @code{...} are read as symbols even though numbers can
5088 begin with @code{+}, @code{-} or @code{.}.
5089
5090 Extended alphabetic characters may be used within identifiers as if
5091 they were letters. The set of extended alphabetic characters is:
5092
5093 @example
5094 ! $ % & * + - . / : < = > ? @@ ^ _ ~
5095 @end example
5096
5097 In addition to the standard read syntax defined above (which is taken
5098 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
5099 Scheme})), Guile provides an extended symbol read syntax that allows the
5100 inclusion of unusual characters such as space characters, newlines and
5101 parentheses. If (for whatever reason) you need to write a symbol
5102 containing characters not mentioned above, you can do so as follows.
5103
5104 @itemize @bullet
5105 @item
5106 Begin the symbol with the characters @code{#@{},
5107
5108 @item
5109 write the characters of the symbol and
5110
5111 @item
5112 finish the symbol with the characters @code{@}#}.
5113 @end itemize
5114
5115 Here are a few examples of this form of read syntax. The first symbol
5116 needs to use extended syntax because it contains a space character, the
5117 second because it contains a line break, and the last because it looks
5118 like a number.
5119
5120 @lisp
5121 #@{foo bar@}#
5122
5123 #@{what
5124 ever@}#
5125
5126 #@{4242@}#
5127 @end lisp
5128
5129 Although Guile provides this extended read syntax for symbols,
5130 widespread usage of it is discouraged because it is not portable and not
5131 very readable.
5132
5133
5134 @node Symbol Uninterned
5135 @subsubsection Uninterned Symbols
5136
5137 What makes symbols useful is that they are automatically kept unique.
5138 There are no two symbols that are distinct objects but have the same
5139 name. But of course, there is no rule without exception. In addition
5140 to the normal symbols that have been discussed up to now, you can also
5141 create special @dfn{uninterned} symbols that behave slightly
5142 differently.
5143
5144 To understand what is different about them and why they might be useful,
5145 we look at how normal symbols are actually kept unique.
5146
5147 Whenever Guile wants to find the symbol with a specific name, for
5148 example during @code{read} or when executing @code{string->symbol}, it
5149 first looks into a table of all existing symbols to find out whether a
5150 symbol with the given name already exists. When this is the case, Guile
5151 just returns that symbol. When not, a new symbol with the name is
5152 created and entered into the table so that it can be found later.
5153
5154 Sometimes you might want to create a symbol that is guaranteed `fresh',
5155 i.e. a symbol that did not exist previously. You might also want to
5156 somehow guarantee that no one else will ever unintentionally stumble
5157 across your symbol in the future. These properties of a symbol are
5158 often needed when generating code during macro expansion. When
5159 introducing new temporary variables, you want to guarantee that they
5160 don't conflict with variables in other people's code.
5161
5162 The simplest way to arrange for this is to create a new symbol but
5163 not enter it into the global table of all symbols. That way, no one
5164 will ever get access to your symbol by chance. Symbols that are not in
5165 the table are called @dfn{uninterned}. Of course, symbols that
5166 @emph{are} in the table are called @dfn{interned}.
5167
5168 You create new uninterned symbols with the function @code{make-symbol}.
5169 You can test whether a symbol is interned or not with
5170 @code{symbol-interned?}.
5171
5172 Uninterned symbols break the rule that the name of a symbol uniquely
5173 identifies the symbol object. Because of this, they can not be written
5174 out and read back in like interned symbols. Currently, Guile has no
5175 support for reading uninterned symbols. Note that the function
5176 @code{gensym} does not return uninterned symbols for this reason.
5177
5178 @deffn {Scheme Procedure} make-symbol name
5179 @deffnx {C Function} scm_make_symbol (name)
5180 Return a new uninterned symbol with the name @var{name}. The returned
5181 symbol is guaranteed to be unique and future calls to
5182 @code{string->symbol} will not return it.
5183 @end deffn
5184
5185 @deffn {Scheme Procedure} symbol-interned? symbol
5186 @deffnx {C Function} scm_symbol_interned_p (symbol)
5187 Return @code{#t} if @var{symbol} is interned, otherwise return
5188 @code{#f}.
5189 @end deffn
5190
5191 For example:
5192
5193 @lisp
5194 (define foo-1 (string->symbol "foo"))
5195 (define foo-2 (string->symbol "foo"))
5196 (define foo-3 (make-symbol "foo"))
5197 (define foo-4 (make-symbol "foo"))
5198
5199 (eq? foo-1 foo-2)
5200 @result{} #t
5201 ; Two interned symbols with the same name are the same object,
5202
5203 (eq? foo-1 foo-3)
5204 @result{} #f
5205 ; but a call to make-symbol with the same name returns a
5206 ; distinct object.
5207
5208 (eq? foo-3 foo-4)
5209 @result{} #f
5210 ; A call to make-symbol always returns a new object, even for
5211 ; the same name.
5212
5213 foo-3
5214 @result{} #<uninterned-symbol foo 8085290>
5215 ; Uninterned symbols print differently from interned symbols,
5216
5217 (symbol? foo-3)
5218 @result{} #t
5219 ; but they are still symbols,
5220
5221 (symbol-interned? foo-3)
5222 @result{} #f
5223 ; just not interned.
5224 @end lisp
5225
5226
5227 @node Keywords
5228 @subsection Keywords
5229 @tpindex Keywords
5230
5231 Keywords are self-evaluating objects with a convenient read syntax that
5232 makes them easy to type.
5233
5234 Guile's keyword support conforms to R5RS, and adds a (switchable) read
5235 syntax extension to permit keywords to begin with @code{:} as well as
5236 @code{#:}, or to end with @code{:}.
5237
5238 @menu
5239 * Why Use Keywords?:: Motivation for keyword usage.
5240 * Coding With Keywords:: How to use keywords.
5241 * Keyword Read Syntax:: Read syntax for keywords.
5242 * Keyword Procedures:: Procedures for dealing with keywords.
5243 @end menu
5244
5245 @node Why Use Keywords?
5246 @subsubsection Why Use Keywords?
5247
5248 Keywords are useful in contexts where a program or procedure wants to be
5249 able to accept a large number of optional arguments without making its
5250 interface unmanageable.
5251
5252 To illustrate this, consider a hypothetical @code{make-window}
5253 procedure, which creates a new window on the screen for drawing into
5254 using some graphical toolkit. There are many parameters that the caller
5255 might like to specify, but which could also be sensibly defaulted, for
5256 example:
5257
5258 @itemize @bullet
5259 @item
5260 color depth -- Default: the color depth for the screen
5261
5262 @item
5263 background color -- Default: white
5264
5265 @item
5266 width -- Default: 600
5267
5268 @item
5269 height -- Default: 400
5270 @end itemize
5271
5272 If @code{make-window} did not use keywords, the caller would have to
5273 pass in a value for each possible argument, remembering the correct
5274 argument order and using a special value to indicate the default value
5275 for that argument:
5276
5277 @lisp
5278 (make-window 'default ;; Color depth
5279 'default ;; Background color
5280 800 ;; Width
5281 100 ;; Height
5282 @dots{}) ;; More make-window arguments
5283 @end lisp
5284
5285 With keywords, on the other hand, defaulted arguments are omitted, and
5286 non-default arguments are clearly tagged by the appropriate keyword. As
5287 a result, the invocation becomes much clearer:
5288
5289 @lisp
5290 (make-window #:width 800 #:height 100)
5291 @end lisp
5292
5293 On the other hand, for a simpler procedure with few arguments, the use
5294 of keywords would be a hindrance rather than a help. The primitive
5295 procedure @code{cons}, for example, would not be improved if it had to
5296 be invoked as
5297
5298 @lisp
5299 (cons #:car x #:cdr y)
5300 @end lisp
5301
5302 So the decision whether to use keywords or not is purely pragmatic: use
5303 them if they will clarify the procedure invocation at point of call.
5304
5305 @node Coding With Keywords
5306 @subsubsection Coding With Keywords
5307
5308 If a procedure wants to support keywords, it should take a rest argument
5309 and then use whatever means is convenient to extract keywords and their
5310 corresponding arguments from the contents of that rest argument.
5311
5312 The following example illustrates the principle: the code for
5313 @code{make-window} uses a helper procedure called
5314 @code{get-keyword-value} to extract individual keyword arguments from
5315 the rest argument.
5316
5317 @lisp
5318 (define (get-keyword-value args keyword default)
5319 (let ((kv (memq keyword args)))
5320 (if (and kv (>= (length kv) 2))
5321 (cadr kv)
5322 default)))
5323
5324 (define (make-window . args)
5325 (let ((depth (get-keyword-value args #:depth screen-depth))
5326 (bg (get-keyword-value args #:bg "white"))
5327 (width (get-keyword-value args #:width 800))
5328 (height (get-keyword-value args #:height 100))
5329 @dots{})
5330 @dots{}))
5331 @end lisp
5332
5333 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
5334 optargs)} module provides a set of powerful macros that you can use to
5335 implement keyword-supporting procedures like this:
5336
5337 @lisp
5338 (use-modules (ice-9 optargs))
5339
5340 (define (make-window . args)
5341 (let-keywords args #f ((depth screen-depth)
5342 (bg "white")
5343 (width 800)
5344 (height 100))
5345 ...))
5346 @end lisp
5347
5348 @noindent
5349 Or, even more economically, like this:
5350
5351 @lisp
5352 (use-modules (ice-9 optargs))
5353
5354 (define* (make-window #:key (depth screen-depth)
5355 (bg "white")
5356 (width 800)
5357 (height 100))
5358 ...)
5359 @end lisp
5360
5361 For further details on @code{let-keywords}, @code{define*} and other
5362 facilities provided by the @code{(ice-9 optargs)} module, see
5363 @ref{Optional Arguments}.
5364
5365
5366 @node Keyword Read Syntax
5367 @subsubsection Keyword Read Syntax
5368
5369 Guile, by default, only recognizes a keyword syntax that is compatible
5370 with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
5371 same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
5372 external representation of the keyword named @code{NAME}. Keyword
5373 objects print using this syntax as well, so values containing keyword
5374 objects can be read back into Guile. When used in an expression,
5375 keywords are self-quoting objects.
5376
5377 If the @code{keyword} read option is set to @code{'prefix}, Guile also
5378 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
5379 of the form @code{:NAME} are read as symbols, as required by R5RS.
5380
5381 @cindex SRFI-88 keyword syntax
5382
5383 If the @code{keyword} read option is set to @code{'postfix}, Guile
5384 recognizes the SRFI-88 read syntax @code{NAME:} (@pxref{SRFI-88}).
5385 Otherwise, tokens of this form are read as symbols.
5386
5387 To enable and disable the alternative non-R5RS keyword syntax, you use
5388 the @code{read-set!} procedure documented @ref{Scheme Read}. Note that
5389 the @code{prefix} and @code{postfix} syntax are mutually exclusive.
5390
5391 @lisp
5392 (read-set! keywords 'prefix)
5393
5394 #:type
5395 @result{}
5396 #:type
5397
5398 :type
5399 @result{}
5400 #:type
5401
5402 (read-set! keywords 'postfix)
5403
5404 type:
5405 @result{}
5406 #:type
5407
5408 :type
5409 @result{}
5410 :type
5411
5412 (read-set! keywords #f)
5413
5414 #:type
5415 @result{}
5416 #:type
5417
5418 :type
5419 @print{}
5420 ERROR: In expression :type:
5421 ERROR: Unbound variable: :type
5422 ABORT: (unbound-variable)
5423 @end lisp
5424
5425 @node Keyword Procedures
5426 @subsubsection Keyword Procedures
5427
5428 @deffn {Scheme Procedure} keyword? obj
5429 @deffnx {C Function} scm_keyword_p (obj)
5430 Return @code{#t} if the argument @var{obj} is a keyword, else
5431 @code{#f}.
5432 @end deffn
5433
5434 @deffn {Scheme Procedure} keyword->symbol keyword
5435 @deffnx {C Function} scm_keyword_to_symbol (keyword)
5436 Return the symbol with the same name as @var{keyword}.
5437 @end deffn
5438
5439 @deffn {Scheme Procedure} symbol->keyword symbol
5440 @deffnx {C Function} scm_symbol_to_keyword (symbol)
5441 Return the keyword with the same name as @var{symbol}.
5442 @end deffn
5443
5444 @deftypefn {C Function} int scm_is_keyword (SCM obj)
5445 Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
5446 @end deftypefn
5447
5448 @deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5449 @deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5450 Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5451 (@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5452 (@var{str}, @var{len}))}, respectively.
5453 @end deftypefn
5454
5455 @node Other Types
5456 @subsection ``Functionality-Centric'' Data Types
5457
5458 Procedures and macros are documented in their own sections: see
5459 @ref{Procedures} and @ref{Macros}.
5460
5461 Variable objects are documented as part of the description of Guile's
5462 module system: see @ref{Variables}.
5463
5464 Asyncs, dynamic roots and fluids are described in the section on
5465 scheduling: see @ref{Scheduling}.
5466
5467 Hooks are documented in the section on general utility functions: see
5468 @ref{Hooks}.
5469
5470 Ports are described in the section on I/O: see @ref{Input and Output}.
5471
5472 Regular expressions are described in their own section: see @ref{Regular
5473 Expressions}.
5474
5475 @c Local Variables:
5476 @c TeX-master: "guile.texi"
5477 @c End: