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