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