merge from 1.8 branch
[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
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 * Regular Expressions:: Pattern matching and substitution.
49 * Symbols:: Symbols.
50 * Keywords:: Self-quoting, customizable display keywords.
51 * Other Types:: "Functionality-centric" data types.
52 @end menu
53
54
55 @node Booleans
56 @subsection Booleans
57 @tpindex Booleans
58
59 The two boolean values are @code{#t} for true and @code{#f} for false.
60
61 Boolean values are returned by predicate procedures, such as the general
62 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
63 (@pxref{Equality}) and numerical and string comparison operators like
64 @code{string=?} (@pxref{String Comparison}) and @code{<=}
65 (@pxref{Comparison}).
66
67 @lisp
68 (<= 3 8)
69 @result{} #t
70
71 (<= 3 -3)
72 @result{} #f
73
74 (equal? "house" "houses")
75 @result{} #f
76
77 (eq? #f #f)
78 @result{}
79 #t
80 @end lisp
81
82 In test condition contexts like @code{if} and @code{cond} (@pxref{if
83 cond case}), where a group of subexpressions will be evaluated only if a
84 @var{condition} expression evaluates to ``true'', ``true'' means any
85 value at all except @code{#f}.
86
87 @lisp
88 (if #t "yes" "no")
89 @result{} "yes"
90
91 (if 0 "yes" "no")
92 @result{} "yes"
93
94 (if #f "yes" "no")
95 @result{} "no"
96 @end lisp
97
98 A result of this asymmetry is that typical Scheme source code more often
99 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
100 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
101 not necessary to represent an @code{if} or @code{cond} true value.
102
103 It is important to note that @code{#f} is @strong{not} equivalent to any
104 other Scheme value. In particular, @code{#f} is not the same as the
105 number 0 (like in C and C++), and not the same as the ``empty list''
106 (like in some Lisp dialects).
107
108 In C, the two Scheme boolean values are available as the two constants
109 @code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
110 Care must be taken with the false value @code{SCM_BOOL_F}: it is not
111 false when used in C conditionals. In order to test for it, use
112 @code{scm_is_false} or @code{scm_is_true}.
113
114 @rnindex not
115 @deffn {Scheme Procedure} not x
116 @deffnx {C Function} scm_not (x)
117 Return @code{#t} if @var{x} is @code{#f}, else return @code{#f}.
118 @end deffn
119
120 @rnindex boolean?
121 @deffn {Scheme Procedure} boolean? obj
122 @deffnx {C Function} scm_boolean_p (obj)
123 Return @code{#t} if @var{obj} is either @code{#t} or @code{#f}, else
124 return @code{#f}.
125 @end deffn
126
127 @deftypevr {C Macro} SCM SCM_BOOL_T
128 The @code{SCM} representation of the Scheme object @code{#t}.
129 @end deftypevr
130
131 @deftypevr {C Macro} SCM SCM_BOOL_F
132 The @code{SCM} representation of the Scheme object @code{#f}.
133 @end deftypevr
134
135 @deftypefn {C Function} int scm_is_true (SCM obj)
136 Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
137 @end deftypefn
138
139 @deftypefn {C Function} int scm_is_false (SCM obj)
140 Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
141 @end deftypefn
142
143 @deftypefn {C Function} int scm_is_bool (SCM obj)
144 Return @code{1} if @var{obj} is either @code{#t} or @code{#f}, else
145 return @code{0}.
146 @end deftypefn
147
148 @deftypefn {C Function} SCM scm_from_bool (int val)
149 Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
150 @end deftypefn
151
152 @deftypefn {C Function} int scm_to_bool (SCM val)
153 Return @code{1} if @var{val} is @code{SCM_BOOL_T}, return @code{0}
154 when @var{val} is @code{SCM_BOOL_F}, else signal a `wrong type' error.
155
156 You should probably use @code{scm_is_true} instead of this function
157 when you just want to test a @code{SCM} value for trueness.
158 @end deftypefn
159
160 @node Numbers
161 @subsection Numerical data types
162 @tpindex Numbers
163
164 Guile supports a rich ``tower'' of numerical types --- integer,
165 rational, real and complex --- and provides an extensive set of
166 mathematical and scientific functions for operating on numerical
167 data. This section of the manual documents those types and functions.
168
169 You may also find it illuminating to read R5RS's presentation of numbers
170 in Scheme, which is particularly clear and accessible: see
171 @ref{Numbers,,,r5rs,R5RS}.
172
173 @menu
174 * Numerical Tower:: Scheme's numerical "tower".
175 * Integers:: Whole numbers.
176 * Reals and Rationals:: Real and rational numbers.
177 * Complex Numbers:: Complex numbers.
178 * Exactness:: Exactness and inexactness.
179 * Number Syntax:: Read syntax for numerical data.
180 * Integer Operations:: Operations on integer values.
181 * Comparison:: Comparison predicates.
182 * Conversion:: Converting numbers to and from strings.
183 * Complex:: Complex number operations.
184 * Arithmetic:: Arithmetic functions.
185 * Scientific:: Scientific functions.
186 * Primitive Numerics:: Primitive numeric 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 explicitely 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 respectivly. 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 representats @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 @deffn {Scheme Procedure} number->string n [radix]
1016 @deffnx {C Function} scm_number_to_string (n, radix)
1017 Return a string holding the external representation of the
1018 number @var{n} in the given @var{radix}. If @var{n} is
1019 inexact, a radix of 10 will be used.
1020 @end deffn
1021
1022 @deffn {Scheme Procedure} string->number string [radix]
1023 @deffnx {C Function} scm_string_to_number (string, radix)
1024 Return a number of the maximally precise representation
1025 expressed by the given @var{string}. @var{radix} must be an
1026 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
1027 is a default radix that may be overridden by an explicit radix
1028 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1029 supplied, then the default radix is 10. If string is not a
1030 syntactically valid notation for a number, then
1031 @code{string->number} returns @code{#f}.
1032 @end deffn
1033
1034 @deftypefn {C Function} SCM scm_c_locale_stringn_to_number (const char *string, size_t len, unsigned radix)
1035 As per @code{string->number} above, but taking a C string, as pointer
1036 and length. The string characters should be in the current locale
1037 encoding (@code{locale} in the name refers only to that, there's no
1038 locale-dependent parsing).
1039 @end deftypefn
1040
1041
1042 @node Complex
1043 @subsubsection Complex Number Operations
1044 @rnindex make-rectangular
1045 @rnindex make-polar
1046 @rnindex real-part
1047 @rnindex imag-part
1048 @rnindex magnitude
1049 @rnindex angle
1050
1051 @deffn {Scheme Procedure} make-rectangular real imaginary
1052 @deffnx {C Function} scm_make_rectangular (real, imaginary)
1053 Return a complex number constructed of the given @var{real} and
1054 @var{imaginary} parts.
1055 @end deffn
1056
1057 @deffn {Scheme Procedure} make-polar x y
1058 @deffnx {C Function} scm_make_polar (x, y)
1059 @cindex polar form
1060 Return the complex number @var{x} * e^(i * @var{y}).
1061 @end deffn
1062
1063 @c begin (texi-doc-string "guile" "real-part")
1064 @deffn {Scheme Procedure} real-part z
1065 @deffnx {C Function} scm_real_part (z)
1066 Return the real part of the number @var{z}.
1067 @end deffn
1068
1069 @c begin (texi-doc-string "guile" "imag-part")
1070 @deffn {Scheme Procedure} imag-part z
1071 @deffnx {C Function} scm_imag_part (z)
1072 Return the imaginary part of the number @var{z}.
1073 @end deffn
1074
1075 @c begin (texi-doc-string "guile" "magnitude")
1076 @deffn {Scheme Procedure} magnitude z
1077 @deffnx {C Function} scm_magnitude (z)
1078 Return the magnitude of the number @var{z}. This is the same as
1079 @code{abs} for real arguments, but also allows complex numbers.
1080 @end deffn
1081
1082 @c begin (texi-doc-string "guile" "angle")
1083 @deffn {Scheme Procedure} angle z
1084 @deffnx {C Function} scm_angle (z)
1085 Return the angle of the complex number @var{z}.
1086 @end deffn
1087
1088 @deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1089 @deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1090 Like @code{scm_make_rectangular} or @code{scm_make_polar},
1091 respectively, but these functions take @code{double}s as their
1092 arguments.
1093 @end deftypefn
1094
1095 @deftypefn {C Function} double scm_c_real_part (z)
1096 @deftypefnx {C Function} double scm_c_imag_part (z)
1097 Returns the real or imaginary part of @var{z} as a @code{double}.
1098 @end deftypefn
1099
1100 @deftypefn {C Function} double scm_c_magnitude (z)
1101 @deftypefnx {C Function} double scm_c_angle (z)
1102 Returns the magnitude or angle of @var{z} as a @code{double}.
1103 @end deftypefn
1104
1105
1106 @node Arithmetic
1107 @subsubsection Arithmetic Functions
1108 @rnindex max
1109 @rnindex min
1110 @rnindex +
1111 @rnindex *
1112 @rnindex -
1113 @rnindex /
1114 @rnindex abs
1115 @rnindex floor
1116 @rnindex ceiling
1117 @rnindex truncate
1118 @rnindex round
1119
1120 The C arithmetic functions below always takes two arguments, while the
1121 Scheme functions can take an arbitrary number. When you need to
1122 invoke them with just one argument, for example to compute the
1123 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1124 one: @code{scm_difference (x, SCM_UNDEFINED)}.
1125
1126 @c begin (texi-doc-string "guile" "+")
1127 @deffn {Scheme Procedure} + z1 @dots{}
1128 @deffnx {C Function} scm_sum (z1, z2)
1129 Return the sum of all parameter values. Return 0 if called without any
1130 parameters.
1131 @end deffn
1132
1133 @c begin (texi-doc-string "guile" "-")
1134 @deffn {Scheme Procedure} - z1 z2 @dots{}
1135 @deffnx {C Function} scm_difference (z1, z2)
1136 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1137 the sum of all but the first argument are subtracted from the first
1138 argument.
1139 @end deffn
1140
1141 @c begin (texi-doc-string "guile" "*")
1142 @deffn {Scheme Procedure} * z1 @dots{}
1143 @deffnx {C Function} scm_product (z1, z2)
1144 Return the product of all arguments. If called without arguments, 1 is
1145 returned.
1146 @end deffn
1147
1148 @c begin (texi-doc-string "guile" "/")
1149 @deffn {Scheme Procedure} / z1 z2 @dots{}
1150 @deffnx {C Function} scm_divide (z1, z2)
1151 Divide the first argument by the product of the remaining arguments. If
1152 called with one argument @var{z1}, 1/@var{z1} is returned.
1153 @end deffn
1154
1155 @c begin (texi-doc-string "guile" "abs")
1156 @deffn {Scheme Procedure} abs x
1157 @deffnx {C Function} scm_abs (x)
1158 Return the absolute value of @var{x}.
1159
1160 @var{x} must be a number with zero imaginary part. To calculate the
1161 magnitude of a complex number, use @code{magnitude} instead.
1162 @end deffn
1163
1164 @c begin (texi-doc-string "guile" "max")
1165 @deffn {Scheme Procedure} max x1 x2 @dots{}
1166 @deffnx {C Function} scm_max (x1, x2)
1167 Return the maximum of all parameter values.
1168 @end deffn
1169
1170 @c begin (texi-doc-string "guile" "min")
1171 @deffn {Scheme Procedure} min x1 x2 @dots{}
1172 @deffnx {C Function} scm_min (x1, x2)
1173 Return the minimum of all parameter values.
1174 @end deffn
1175
1176 @c begin (texi-doc-string "guile" "truncate")
1177 @deffn {Scheme Procedure} truncate x
1178 @deffnx {C Function} scm_truncate_number (x)
1179 Round the inexact number @var{x} towards zero.
1180 @end deffn
1181
1182 @c begin (texi-doc-string "guile" "round")
1183 @deffn {Scheme Procedure} round x
1184 @deffnx {C Function} scm_round_number (x)
1185 Round the inexact number @var{x} to the nearest integer. When exactly
1186 halfway between two integers, round to the even one.
1187 @end deffn
1188
1189 @c begin (texi-doc-string "guile" "floor")
1190 @deffn {Scheme Procedure} floor x
1191 @deffnx {C Function} scm_floor (x)
1192 Round the number @var{x} towards minus infinity.
1193 @end deffn
1194
1195 @c begin (texi-doc-string "guile" "ceiling")
1196 @deffn {Scheme Procedure} ceiling x
1197 @deffnx {C Function} scm_ceiling (x)
1198 Round the number @var{x} towards infinity.
1199 @end deffn
1200
1201 @deftypefn {C Function} double scm_c_truncate (double x)
1202 @deftypefnx {C Function} double scm_c_round (double x)
1203 Like @code{scm_truncate_number} or @code{scm_round_number},
1204 respectively, but these functions take and return @code{double}
1205 values.
1206 @end deftypefn
1207
1208 @node Scientific
1209 @subsubsection Scientific Functions
1210
1211 The following procedures accept any kind of number as arguments,
1212 including complex numbers.
1213
1214 @rnindex sqrt
1215 @c begin (texi-doc-string "guile" "sqrt")
1216 @deffn {Scheme Procedure} sqrt z
1217 Return the square root of @var{z}. Of the two possible roots
1218 (positive and negative), the one with the a positive real part is
1219 returned, or if that's zero then a positive imaginary part. Thus,
1220
1221 @example
1222 (sqrt 9.0) @result{} 3.0
1223 (sqrt -9.0) @result{} 0.0+3.0i
1224 (sqrt 1.0+1.0i) @result{} 1.09868411346781+0.455089860562227i
1225 (sqrt -1.0-1.0i) @result{} 0.455089860562227-1.09868411346781i
1226 @end example
1227 @end deffn
1228
1229 @rnindex expt
1230 @c begin (texi-doc-string "guile" "expt")
1231 @deffn {Scheme Procedure} expt z1 z2
1232 Return @var{z1} raised to the power of @var{z2}.
1233 @end deffn
1234
1235 @rnindex sin
1236 @c begin (texi-doc-string "guile" "sin")
1237 @deffn {Scheme Procedure} sin z
1238 Return the sine of @var{z}.
1239 @end deffn
1240
1241 @rnindex cos
1242 @c begin (texi-doc-string "guile" "cos")
1243 @deffn {Scheme Procedure} cos z
1244 Return the cosine of @var{z}.
1245 @end deffn
1246
1247 @rnindex tan
1248 @c begin (texi-doc-string "guile" "tan")
1249 @deffn {Scheme Procedure} tan z
1250 Return the tangent of @var{z}.
1251 @end deffn
1252
1253 @rnindex asin
1254 @c begin (texi-doc-string "guile" "asin")
1255 @deffn {Scheme Procedure} asin z
1256 Return the arcsine of @var{z}.
1257 @end deffn
1258
1259 @rnindex acos
1260 @c begin (texi-doc-string "guile" "acos")
1261 @deffn {Scheme Procedure} acos z
1262 Return the arccosine of @var{z}.
1263 @end deffn
1264
1265 @rnindex atan
1266 @c begin (texi-doc-string "guile" "atan")
1267 @deffn {Scheme Procedure} atan z
1268 @deffnx {Scheme Procedure} atan y x
1269 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1270 @end deffn
1271
1272 @rnindex exp
1273 @c begin (texi-doc-string "guile" "exp")
1274 @deffn {Scheme Procedure} exp z
1275 Return e to the power of @var{z}, where e is the base of natural
1276 logarithms (2.71828@dots{}).
1277 @end deffn
1278
1279 @rnindex log
1280 @c begin (texi-doc-string "guile" "log")
1281 @deffn {Scheme Procedure} log z
1282 Return the natural logarithm of @var{z}.
1283 @end deffn
1284
1285 @c begin (texi-doc-string "guile" "log10")
1286 @deffn {Scheme Procedure} log10 z
1287 Return the base 10 logarithm of @var{z}.
1288 @end deffn
1289
1290 @c begin (texi-doc-string "guile" "sinh")
1291 @deffn {Scheme Procedure} sinh z
1292 Return the hyperbolic sine of @var{z}.
1293 @end deffn
1294
1295 @c begin (texi-doc-string "guile" "cosh")
1296 @deffn {Scheme Procedure} cosh z
1297 Return the hyperbolic cosine of @var{z}.
1298 @end deffn
1299
1300 @c begin (texi-doc-string "guile" "tanh")
1301 @deffn {Scheme Procedure} tanh z
1302 Return the hyperbolic tangent of @var{z}.
1303 @end deffn
1304
1305 @c begin (texi-doc-string "guile" "asinh")
1306 @deffn {Scheme Procedure} asinh z
1307 Return the hyperbolic arcsine of @var{z}.
1308 @end deffn
1309
1310 @c begin (texi-doc-string "guile" "acosh")
1311 @deffn {Scheme Procedure} acosh z
1312 Return the hyperbolic arccosine of @var{z}.
1313 @end deffn
1314
1315 @c begin (texi-doc-string "guile" "atanh")
1316 @deffn {Scheme Procedure} atanh z
1317 Return the hyperbolic arctangent of @var{z}.
1318 @end deffn
1319
1320
1321 @node Primitive Numerics
1322 @subsubsection Primitive Numeric Functions
1323
1324 Many of Guile's numeric procedures which accept any kind of numbers as
1325 arguments, including complex numbers, are implemented as Scheme
1326 procedures that use the following real number-based primitives. These
1327 primitives signal an error if they are called with complex arguments.
1328
1329 @c begin (texi-doc-string "guile" "$abs")
1330 @deffn {Scheme Procedure} $abs x
1331 Return the absolute value of @var{x}.
1332 @end deffn
1333
1334 @c begin (texi-doc-string "guile" "$sqrt")
1335 @deffn {Scheme Procedure} $sqrt x
1336 Return the square root of @var{x}.
1337 @end deffn
1338
1339 @deffn {Scheme Procedure} $expt x y
1340 @deffnx {C Function} scm_sys_expt (x, y)
1341 Return @var{x} raised to the power of @var{y}. This
1342 procedure does not accept complex arguments.
1343 @end deffn
1344
1345 @c begin (texi-doc-string "guile" "$sin")
1346 @deffn {Scheme Procedure} $sin x
1347 Return the sine of @var{x}.
1348 @end deffn
1349
1350 @c begin (texi-doc-string "guile" "$cos")
1351 @deffn {Scheme Procedure} $cos x
1352 Return the cosine of @var{x}.
1353 @end deffn
1354
1355 @c begin (texi-doc-string "guile" "$tan")
1356 @deffn {Scheme Procedure} $tan x
1357 Return the tangent of @var{x}.
1358 @end deffn
1359
1360 @c begin (texi-doc-string "guile" "$asin")
1361 @deffn {Scheme Procedure} $asin x
1362 Return the arcsine of @var{x}.
1363 @end deffn
1364
1365 @c begin (texi-doc-string "guile" "$acos")
1366 @deffn {Scheme Procedure} $acos x
1367 Return the arccosine of @var{x}.
1368 @end deffn
1369
1370 @c begin (texi-doc-string "guile" "$atan")
1371 @deffn {Scheme Procedure} $atan x
1372 Return the arctangent of @var{x} in the range @minus{}@math{PI/2} to
1373 @math{PI/2}.
1374 @end deffn
1375
1376 @deffn {Scheme Procedure} $atan2 x y
1377 @deffnx {C Function} scm_sys_atan2 (x, y)
1378 Return the arc tangent of the two arguments @var{x} and
1379 @var{y}. This is similar to calculating the arc tangent of
1380 @var{x} / @var{y}, except that the signs of both arguments
1381 are used to determine the quadrant of the result. This
1382 procedure does not accept complex arguments.
1383 @end deffn
1384
1385 @c begin (texi-doc-string "guile" "$exp")
1386 @deffn {Scheme Procedure} $exp x
1387 Return e to the power of @var{x}, where e is the base of natural
1388 logarithms (2.71828@dots{}).
1389 @end deffn
1390
1391 @c begin (texi-doc-string "guile" "$log")
1392 @deffn {Scheme Procedure} $log x
1393 Return the natural logarithm of @var{x}.
1394 @end deffn
1395
1396 @c begin (texi-doc-string "guile" "$sinh")
1397 @deffn {Scheme Procedure} $sinh x
1398 Return the hyperbolic sine of @var{x}.
1399 @end deffn
1400
1401 @c begin (texi-doc-string "guile" "$cosh")
1402 @deffn {Scheme Procedure} $cosh x
1403 Return the hyperbolic cosine of @var{x}.
1404 @end deffn
1405
1406 @c begin (texi-doc-string "guile" "$tanh")
1407 @deffn {Scheme Procedure} $tanh x
1408 Return the hyperbolic tangent of @var{x}.
1409 @end deffn
1410
1411 @c begin (texi-doc-string "guile" "$asinh")
1412 @deffn {Scheme Procedure} $asinh x
1413 Return the hyperbolic arcsine of @var{x}.
1414 @end deffn
1415
1416 @c begin (texi-doc-string "guile" "$acosh")
1417 @deffn {Scheme Procedure} $acosh x
1418 Return the hyperbolic arccosine of @var{x}.
1419 @end deffn
1420
1421 @c begin (texi-doc-string "guile" "$atanh")
1422 @deffn {Scheme Procedure} $atanh x
1423 Return the hyperbolic arctangent of @var{x}.
1424 @end deffn
1425
1426 C functions for the above are provided by the standard mathematics
1427 library. Naturally these expect and return @code{double} arguments
1428 (@pxref{Mathematics,,, libc, GNU C Library Reference Manual}).
1429
1430 @multitable {xx} {Scheme Procedure} {C Function}
1431 @item @tab Scheme Procedure @tab C Function
1432
1433 @item @tab @code{$abs} @tab @code{fabs}
1434 @item @tab @code{$sqrt} @tab @code{sqrt}
1435 @item @tab @code{$sin} @tab @code{sin}
1436 @item @tab @code{$cos} @tab @code{cos}
1437 @item @tab @code{$tan} @tab @code{tan}
1438 @item @tab @code{$asin} @tab @code{asin}
1439 @item @tab @code{$acos} @tab @code{acos}
1440 @item @tab @code{$atan} @tab @code{atan}
1441 @item @tab @code{$atan2} @tab @code{atan2}
1442 @item @tab @code{$exp} @tab @code{exp}
1443 @item @tab @code{$expt} @tab @code{pow}
1444 @item @tab @code{$log} @tab @code{log}
1445 @item @tab @code{$sinh} @tab @code{sinh}
1446 @item @tab @code{$cosh} @tab @code{cosh}
1447 @item @tab @code{$tanh} @tab @code{tanh}
1448 @item @tab @code{$asinh} @tab @code{asinh}
1449 @item @tab @code{$acosh} @tab @code{acosh}
1450 @item @tab @code{$atanh} @tab @code{atanh}
1451 @end multitable
1452
1453 @code{asinh}, @code{acosh} and @code{atanh} are C99 standard but might
1454 not be available on older systems. Guile provides the following
1455 equivalents (on all systems).
1456
1457 @deftypefn {C Function} double scm_asinh (double x)
1458 @deftypefnx {C Function} double scm_acosh (double x)
1459 @deftypefnx {C Function} double scm_atanh (double x)
1460 Return the hyperbolic arcsine, arccosine or arctangent of @var{x}
1461 respectively.
1462 @end deftypefn
1463
1464
1465 @node Bitwise Operations
1466 @subsubsection Bitwise Operations
1467
1468 For the following bitwise functions, negative numbers are treated as
1469 infinite precision twos-complements. For instance @math{-6} is bits
1470 @math{@dots{}111010}, with infinitely many ones on the left. It can
1471 be seen that adding 6 (binary 110) to such a bit pattern gives all
1472 zeros.
1473
1474 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1475 @deffnx {C Function} scm_logand (n1, n2)
1476 Return the bitwise @sc{and} of the integer arguments.
1477
1478 @lisp
1479 (logand) @result{} -1
1480 (logand 7) @result{} 7
1481 (logand #b111 #b011 #b001) @result{} 1
1482 @end lisp
1483 @end deffn
1484
1485 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1486 @deffnx {C Function} scm_logior (n1, n2)
1487 Return the bitwise @sc{or} of the integer arguments.
1488
1489 @lisp
1490 (logior) @result{} 0
1491 (logior 7) @result{} 7
1492 (logior #b000 #b001 #b011) @result{} 3
1493 @end lisp
1494 @end deffn
1495
1496 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1497 @deffnx {C Function} scm_loxor (n1, n2)
1498 Return the bitwise @sc{xor} of the integer arguments. A bit is
1499 set in the result if it is set in an odd number of arguments.
1500
1501 @lisp
1502 (logxor) @result{} 0
1503 (logxor 7) @result{} 7
1504 (logxor #b000 #b001 #b011) @result{} 2
1505 (logxor #b000 #b001 #b011 #b011) @result{} 1
1506 @end lisp
1507 @end deffn
1508
1509 @deffn {Scheme Procedure} lognot n
1510 @deffnx {C Function} scm_lognot (n)
1511 Return the integer which is the ones-complement of the integer
1512 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1513
1514 @lisp
1515 (number->string (lognot #b10000000) 2)
1516 @result{} "-10000001"
1517 (number->string (lognot #b0) 2)
1518 @result{} "-1"
1519 @end lisp
1520 @end deffn
1521
1522 @deffn {Scheme Procedure} logtest j k
1523 @deffnx {C Function} scm_logtest (j, k)
1524 Test whether @var{j} and @var{k} have any 1 bits in common. This is
1525 equivalent to @code{(not (zero? (logand j k)))}, but without actually
1526 calculating the @code{logand}, just testing for non-zero.
1527
1528 @lisp
1529 (logtest #b0100 #b1011) @result{} #f
1530 (logtest #b0100 #b0111) @result{} #t
1531 @end lisp
1532 @end deffn
1533
1534 @deffn {Scheme Procedure} logbit? index j
1535 @deffnx {C Function} scm_logbit_p (index, j)
1536 Test whether bit number @var{index} in @var{j} is set. @var{index}
1537 starts from 0 for the least significant bit.
1538
1539 @lisp
1540 (logbit? 0 #b1101) @result{} #t
1541 (logbit? 1 #b1101) @result{} #f
1542 (logbit? 2 #b1101) @result{} #t
1543 (logbit? 3 #b1101) @result{} #t
1544 (logbit? 4 #b1101) @result{} #f
1545 @end lisp
1546 @end deffn
1547
1548 @deffn {Scheme Procedure} ash n cnt
1549 @deffnx {C Function} scm_ash (n, cnt)
1550 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1551 @var{cnt} is negative. This is an ``arithmetic'' shift.
1552
1553 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1554 when @var{cnt} is negative it's a division, rounded towards negative
1555 infinity. (Note that this is not the same rounding as @code{quotient}
1556 does.)
1557
1558 With @var{n} viewed as an infinite precision twos complement,
1559 @code{ash} means a left shift introducing zero bits, or a right shift
1560 dropping bits.
1561
1562 @lisp
1563 (number->string (ash #b1 3) 2) @result{} "1000"
1564 (number->string (ash #b1010 -1) 2) @result{} "101"
1565
1566 ;; -23 is bits ...11101001, -6 is bits ...111010
1567 (ash -23 -2) @result{} -6
1568 @end lisp
1569 @end deffn
1570
1571 @deffn {Scheme Procedure} logcount n
1572 @deffnx {C Function} scm_logcount (n)
1573 Return the number of bits in integer @var{n}. If @var{n} is
1574 positive, the 1-bits in its binary representation are counted.
1575 If negative, the 0-bits in its two's-complement binary
1576 representation are counted. If zero, 0 is returned.
1577
1578 @lisp
1579 (logcount #b10101010)
1580 @result{} 4
1581 (logcount 0)
1582 @result{} 0
1583 (logcount -2)
1584 @result{} 1
1585 @end lisp
1586 @end deffn
1587
1588 @deffn {Scheme Procedure} integer-length n
1589 @deffnx {C Function} scm_integer_length (n)
1590 Return the number of bits necessary to represent @var{n}.
1591
1592 For positive @var{n} this is how many bits to the most significant one
1593 bit. For negative @var{n} it's how many bits to the most significant
1594 zero bit in twos complement form.
1595
1596 @lisp
1597 (integer-length #b10101010) @result{} 8
1598 (integer-length #b1111) @result{} 4
1599 (integer-length 0) @result{} 0
1600 (integer-length -1) @result{} 0
1601 (integer-length -256) @result{} 8
1602 (integer-length -257) @result{} 9
1603 @end lisp
1604 @end deffn
1605
1606 @deffn {Scheme Procedure} integer-expt n k
1607 @deffnx {C Function} scm_integer_expt (n, k)
1608 Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1609 integer, @var{n} can be any number.
1610
1611 Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1612 in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1613 @math{0^0} is 1.
1614
1615 @lisp
1616 (integer-expt 2 5) @result{} 32
1617 (integer-expt -3 3) @result{} -27
1618 (integer-expt 5 -3) @result{} 1/125
1619 (integer-expt 0 0) @result{} 1
1620 @end lisp
1621 @end deffn
1622
1623 @deffn {Scheme Procedure} bit-extract n start end
1624 @deffnx {C Function} scm_bit_extract (n, start, end)
1625 Return the integer composed of the @var{start} (inclusive)
1626 through @var{end} (exclusive) bits of @var{n}. The
1627 @var{start}th bit becomes the 0-th bit in the result.
1628
1629 @lisp
1630 (number->string (bit-extract #b1101101010 0 4) 2)
1631 @result{} "1010"
1632 (number->string (bit-extract #b1101101010 4 9) 2)
1633 @result{} "10110"
1634 @end lisp
1635 @end deffn
1636
1637
1638 @node Random
1639 @subsubsection Random Number Generation
1640
1641 Pseudo-random numbers are generated from a random state object, which
1642 can be created with @code{seed->random-state}. The @var{state}
1643 parameter to the various functions below is optional, it defaults to
1644 the state object in the @code{*random-state*} variable.
1645
1646 @deffn {Scheme Procedure} copy-random-state [state]
1647 @deffnx {C Function} scm_copy_random_state (state)
1648 Return a copy of the random state @var{state}.
1649 @end deffn
1650
1651 @deffn {Scheme Procedure} random n [state]
1652 @deffnx {C Function} scm_random (n, state)
1653 Return a number in [0, @var{n}).
1654
1655 Accepts a positive integer or real n and returns a
1656 number of the same type between zero (inclusive) and
1657 @var{n} (exclusive). The values returned have a uniform
1658 distribution.
1659 @end deffn
1660
1661 @deffn {Scheme Procedure} random:exp [state]
1662 @deffnx {C Function} scm_random_exp (state)
1663 Return an inexact real in an exponential distribution with mean
1664 1. For an exponential distribution with mean @var{u} use @code{(*
1665 @var{u} (random:exp))}.
1666 @end deffn
1667
1668 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1669 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1670 Fills @var{vect} with inexact real random numbers the sum of whose
1671 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1672 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1673 the coordinates are uniformly distributed over the surface of the unit
1674 n-sphere.
1675 @end deffn
1676
1677 @deffn {Scheme Procedure} random:normal [state]
1678 @deffnx {C Function} scm_random_normal (state)
1679 Return an inexact real in a normal distribution. The distribution
1680 used has mean 0 and standard deviation 1. For a normal distribution
1681 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1682 (* @var{d} (random:normal)))}.
1683 @end deffn
1684
1685 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1686 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1687 Fills @var{vect} with inexact real random numbers that are
1688 independent and standard normally distributed
1689 (i.e., with mean 0 and variance 1).
1690 @end deffn
1691
1692 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1693 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1694 Fills @var{vect} with inexact real random numbers the sum of whose
1695 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1696 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1697 the coordinates are uniformly distributed within the unit
1698 @var{n}-sphere.
1699 @c FIXME: What does this mean, particularly the n-sphere part?
1700 @end deffn
1701
1702 @deffn {Scheme Procedure} random:uniform [state]
1703 @deffnx {C Function} scm_random_uniform (state)
1704 Return a uniformly distributed inexact real random number in
1705 [0,1).
1706 @end deffn
1707
1708 @deffn {Scheme Procedure} seed->random-state seed
1709 @deffnx {C Function} scm_seed_to_random_state (seed)
1710 Return a new random state using @var{seed}.
1711 @end deffn
1712
1713 @defvar *random-state*
1714 The global random state used by the above functions when the
1715 @var{state} parameter is not given.
1716 @end defvar
1717
1718
1719 @node Characters
1720 @subsection Characters
1721 @tpindex Characters
1722
1723 In Scheme, a character literal is written as @code{#\@var{name}} where
1724 @var{name} is the name of the character that you want. Printable
1725 characters have their usual single character name; for example,
1726 @code{#\a} is a lower case @code{a}.
1727
1728 Most of the ``control characters'' (those below codepoint 32) in the
1729 @acronym{ASCII} character set, as well as the space, may be referred
1730 to by longer names: for example, @code{#\tab}, @code{#\esc},
1731 @code{#\stx}, and so on. The following table describes the
1732 @acronym{ASCII} names for each character.
1733
1734 @multitable @columnfractions .25 .25 .25 .25
1735 @item 0 = @code{#\nul}
1736 @tab 1 = @code{#\soh}
1737 @tab 2 = @code{#\stx}
1738 @tab 3 = @code{#\etx}
1739 @item 4 = @code{#\eot}
1740 @tab 5 = @code{#\enq}
1741 @tab 6 = @code{#\ack}
1742 @tab 7 = @code{#\bel}
1743 @item 8 = @code{#\bs}
1744 @tab 9 = @code{#\ht}
1745 @tab 10 = @code{#\nl}
1746 @tab 11 = @code{#\vt}
1747 @item 12 = @code{#\np}
1748 @tab 13 = @code{#\cr}
1749 @tab 14 = @code{#\so}
1750 @tab 15 = @code{#\si}
1751 @item 16 = @code{#\dle}
1752 @tab 17 = @code{#\dc1}
1753 @tab 18 = @code{#\dc2}
1754 @tab 19 = @code{#\dc3}
1755 @item 20 = @code{#\dc4}
1756 @tab 21 = @code{#\nak}
1757 @tab 22 = @code{#\syn}
1758 @tab 23 = @code{#\etb}
1759 @item 24 = @code{#\can}
1760 @tab 25 = @code{#\em}
1761 @tab 26 = @code{#\sub}
1762 @tab 27 = @code{#\esc}
1763 @item 28 = @code{#\fs}
1764 @tab 29 = @code{#\gs}
1765 @tab 30 = @code{#\rs}
1766 @tab 31 = @code{#\us}
1767 @item 32 = @code{#\sp}
1768 @end multitable
1769
1770 The ``delete'' character (octal 177) may be referred to with the name
1771 @code{#\del}.
1772
1773 Several characters have more than one name:
1774
1775 @multitable {@code{#\backspace}} {Original}
1776 @item Alias @tab Original
1777 @item @code{#\space} @tab @code{#\sp}
1778 @item @code{#\newline} @tab @code{#\nl}
1779 @item @code{#\tab} @tab @code{#\ht}
1780 @item @code{#\backspace} @tab @code{#\bs}
1781 @item @code{#\return} @tab @code{#\cr}
1782 @item @code{#\page} @tab @code{#\np}
1783 @item @code{#\null} @tab @code{#\nul}
1784 @end multitable
1785
1786 @rnindex char?
1787 @deffn {Scheme Procedure} char? x
1788 @deffnx {C Function} scm_char_p (x)
1789 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1790 @end deffn
1791
1792 @rnindex char=?
1793 @deffn {Scheme Procedure} char=? x y
1794 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1795 @end deffn
1796
1797 @rnindex char<?
1798 @deffn {Scheme Procedure} char<? x y
1799 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence,
1800 else @code{#f}.
1801 @end deffn
1802
1803 @rnindex char<=?
1804 @deffn {Scheme Procedure} char<=? x y
1805 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1806 @acronym{ASCII} sequence, else @code{#f}.
1807 @end deffn
1808
1809 @rnindex char>?
1810 @deffn {Scheme Procedure} char>? x y
1811 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1812 sequence, else @code{#f}.
1813 @end deffn
1814
1815 @rnindex char>=?
1816 @deffn {Scheme Procedure} char>=? x y
1817 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1818 @acronym{ASCII} sequence, else @code{#f}.
1819 @end deffn
1820
1821 @rnindex char-ci=?
1822 @deffn {Scheme Procedure} char-ci=? x y
1823 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1824 case, else @code{#f}.
1825 @end deffn
1826
1827 @rnindex char-ci<?
1828 @deffn {Scheme Procedure} char-ci<? x y
1829 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence
1830 ignoring case, else @code{#f}.
1831 @end deffn
1832
1833 @rnindex char-ci<=?
1834 @deffn {Scheme Procedure} char-ci<=? x y
1835 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1836 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1837 @end deffn
1838
1839 @rnindex char-ci>?
1840 @deffn {Scheme Procedure} char-ci>? x y
1841 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1842 sequence ignoring case, else @code{#f}.
1843 @end deffn
1844
1845 @rnindex char-ci>=?
1846 @deffn {Scheme Procedure} char-ci>=? x y
1847 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1848 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1849 @end deffn
1850
1851 @rnindex char-alphabetic?
1852 @deffn {Scheme Procedure} char-alphabetic? chr
1853 @deffnx {C Function} scm_char_alphabetic_p (chr)
1854 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1855 @end deffn
1856
1857 @rnindex char-numeric?
1858 @deffn {Scheme Procedure} char-numeric? chr
1859 @deffnx {C Function} scm_char_numeric_p (chr)
1860 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1861 @end deffn
1862
1863 @rnindex char-whitespace?
1864 @deffn {Scheme Procedure} char-whitespace? chr
1865 @deffnx {C Function} scm_char_whitespace_p (chr)
1866 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1867 @end deffn
1868
1869 @rnindex char-upper-case?
1870 @deffn {Scheme Procedure} char-upper-case? chr
1871 @deffnx {C Function} scm_char_upper_case_p (chr)
1872 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1873 @end deffn
1874
1875 @rnindex char-lower-case?
1876 @deffn {Scheme Procedure} char-lower-case? chr
1877 @deffnx {C Function} scm_char_lower_case_p (chr)
1878 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1879 @end deffn
1880
1881 @deffn {Scheme Procedure} char-is-both? chr
1882 @deffnx {C Function} scm_char_is_both_p (chr)
1883 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1884 @code{#f}.
1885 @end deffn
1886
1887 @rnindex char->integer
1888 @deffn {Scheme Procedure} char->integer chr
1889 @deffnx {C Function} scm_char_to_integer (chr)
1890 Return the number corresponding to ordinal position of @var{chr} in the
1891 @acronym{ASCII} sequence.
1892 @end deffn
1893
1894 @rnindex integer->char
1895 @deffn {Scheme Procedure} integer->char n
1896 @deffnx {C Function} scm_integer_to_char (n)
1897 Return the character at position @var{n} in the @acronym{ASCII} sequence.
1898 @end deffn
1899
1900 @rnindex char-upcase
1901 @deffn {Scheme Procedure} char-upcase chr
1902 @deffnx {C Function} scm_char_upcase (chr)
1903 Return the uppercase character version of @var{chr}.
1904 @end deffn
1905
1906 @rnindex char-downcase
1907 @deffn {Scheme Procedure} char-downcase chr
1908 @deffnx {C Function} scm_char_downcase (chr)
1909 Return the lowercase character version of @var{chr}.
1910 @end deffn
1911
1912 @node Character Sets
1913 @subsection Character Sets
1914
1915 The features described in this section correspond directly to SRFI-14.
1916
1917 The data type @dfn{charset} implements sets of characters
1918 (@pxref{Characters}). Because the internal representation of
1919 character sets is not visible to the user, a lot of procedures for
1920 handling them are provided.
1921
1922 Character sets can be created, extended, tested for the membership of a
1923 characters and be compared to other character sets.
1924
1925 The Guile implementation of character sets currently deals only with
1926 8-bit characters. In the future, when Guile gets support for
1927 international character sets, this will change, but the functions
1928 provided here will always then be able to efficiently cope with very
1929 large character sets.
1930
1931 @menu
1932 * Character Set Predicates/Comparison::
1933 * Iterating Over Character Sets:: Enumerate charset elements.
1934 * Creating Character Sets:: Making new charsets.
1935 * Querying Character Sets:: Test charsets for membership etc.
1936 * Character-Set Algebra:: Calculating new charsets.
1937 * Standard Character Sets:: Variables containing predefined charsets.
1938 @end menu
1939
1940 @node Character Set Predicates/Comparison
1941 @subsubsection Character Set Predicates/Comparison
1942
1943 Use these procedures for testing whether an object is a character set,
1944 or whether several character sets are equal or subsets of each other.
1945 @code{char-set-hash} can be used for calculating a hash value, maybe for
1946 usage in fast lookup procedures.
1947
1948 @deffn {Scheme Procedure} char-set? obj
1949 @deffnx {C Function} scm_char_set_p (obj)
1950 Return @code{#t} if @var{obj} is a character set, @code{#f}
1951 otherwise.
1952 @end deffn
1953
1954 @deffn {Scheme Procedure} char-set= . char_sets
1955 @deffnx {C Function} scm_char_set_eq (char_sets)
1956 Return @code{#t} if all given character sets are equal.
1957 @end deffn
1958
1959 @deffn {Scheme Procedure} char-set<= . char_sets
1960 @deffnx {C Function} scm_char_set_leq (char_sets)
1961 Return @code{#t} if every character set @var{cs}i is a subset
1962 of character set @var{cs}i+1.
1963 @end deffn
1964
1965 @deffn {Scheme Procedure} char-set-hash cs [bound]
1966 @deffnx {C Function} scm_char_set_hash (cs, bound)
1967 Compute a hash value for the character set @var{cs}. If
1968 @var{bound} is given and non-zero, it restricts the
1969 returned value to the range 0 @dots{} @var{bound - 1}.
1970 @end deffn
1971
1972 @c ===================================================================
1973
1974 @node Iterating Over Character Sets
1975 @subsubsection Iterating Over Character Sets
1976
1977 Character set cursors are a means for iterating over the members of a
1978 character sets. After creating a character set cursor with
1979 @code{char-set-cursor}, a cursor can be dereferenced with
1980 @code{char-set-ref}, advanced to the next member with
1981 @code{char-set-cursor-next}. Whether a cursor has passed past the last
1982 element of the set can be checked with @code{end-of-char-set?}.
1983
1984 Additionally, mapping and (un-)folding procedures for character sets are
1985 provided.
1986
1987 @deffn {Scheme Procedure} char-set-cursor cs
1988 @deffnx {C Function} scm_char_set_cursor (cs)
1989 Return a cursor into the character set @var{cs}.
1990 @end deffn
1991
1992 @deffn {Scheme Procedure} char-set-ref cs cursor
1993 @deffnx {C Function} scm_char_set_ref (cs, cursor)
1994 Return the character at the current cursor position
1995 @var{cursor} in the character set @var{cs}. It is an error to
1996 pass a cursor for which @code{end-of-char-set?} returns true.
1997 @end deffn
1998
1999 @deffn {Scheme Procedure} char-set-cursor-next cs cursor
2000 @deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
2001 Advance the character set cursor @var{cursor} to the next
2002 character in the character set @var{cs}. It is an error if the
2003 cursor given satisfies @code{end-of-char-set?}.
2004 @end deffn
2005
2006 @deffn {Scheme Procedure} end-of-char-set? cursor
2007 @deffnx {C Function} scm_end_of_char_set_p (cursor)
2008 Return @code{#t} if @var{cursor} has reached the end of a
2009 character set, @code{#f} otherwise.
2010 @end deffn
2011
2012 @deffn {Scheme Procedure} char-set-fold kons knil cs
2013 @deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2014 Fold the procedure @var{kons} over the character set @var{cs},
2015 initializing it with @var{knil}.
2016 @end deffn
2017
2018 @deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2019 @deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2020 This is a fundamental constructor for character sets.
2021 @itemize @bullet
2022 @item @var{g} is used to generate a series of ``seed'' values
2023 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2024 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2025 @item @var{p} tells us when to stop -- when it returns true
2026 when applied to one of the seed values.
2027 @item @var{f} maps each seed value to a character. These
2028 characters are added to the base character set @var{base_cs} to
2029 form the result; @var{base_cs} defaults to the empty set.
2030 @end itemize
2031 @end deffn
2032
2033 @deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2034 @deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2035 This is a fundamental constructor for character sets.
2036 @itemize @bullet
2037 @item @var{g} is used to generate a series of ``seed'' values
2038 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2039 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2040 @item @var{p} tells us when to stop -- when it returns true
2041 when applied to one of the seed values.
2042 @item @var{f} maps each seed value to a character. These
2043 characters are added to the base character set @var{base_cs} to
2044 form the result; @var{base_cs} defaults to the empty set.
2045 @end itemize
2046 @end deffn
2047
2048 @deffn {Scheme Procedure} char-set-for-each proc cs
2049 @deffnx {C Function} scm_char_set_for_each (proc, cs)
2050 Apply @var{proc} to every character in the character set
2051 @var{cs}. The return value is not specified.
2052 @end deffn
2053
2054 @deffn {Scheme Procedure} char-set-map proc cs
2055 @deffnx {C Function} scm_char_set_map (proc, cs)
2056 Map the procedure @var{proc} over every character in @var{cs}.
2057 @var{proc} must be a character -> character procedure.
2058 @end deffn
2059
2060 @c ===================================================================
2061
2062 @node Creating Character Sets
2063 @subsubsection Creating Character Sets
2064
2065 New character sets are produced with these procedures.
2066
2067 @deffn {Scheme Procedure} char-set-copy cs
2068 @deffnx {C Function} scm_char_set_copy (cs)
2069 Return a newly allocated character set containing all
2070 characters in @var{cs}.
2071 @end deffn
2072
2073 @deffn {Scheme Procedure} char-set . rest
2074 @deffnx {C Function} scm_char_set (rest)
2075 Return a character set containing all given characters.
2076 @end deffn
2077
2078 @deffn {Scheme Procedure} list->char-set list [base_cs]
2079 @deffnx {C Function} scm_list_to_char_set (list, base_cs)
2080 Convert the character list @var{list} to a character set. If
2081 the character set @var{base_cs} is given, the character in this
2082 set are also included in the result.
2083 @end deffn
2084
2085 @deffn {Scheme Procedure} list->char-set! list base_cs
2086 @deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2087 Convert the character list @var{list} to a character set. The
2088 characters are added to @var{base_cs} and @var{base_cs} is
2089 returned.
2090 @end deffn
2091
2092 @deffn {Scheme Procedure} string->char-set str [base_cs]
2093 @deffnx {C Function} scm_string_to_char_set (str, base_cs)
2094 Convert the string @var{str} to a character set. If the
2095 character set @var{base_cs} is given, the characters in this
2096 set are also included in the result.
2097 @end deffn
2098
2099 @deffn {Scheme Procedure} string->char-set! str base_cs
2100 @deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2101 Convert the string @var{str} to a character set. The
2102 characters from the string are added to @var{base_cs}, and
2103 @var{base_cs} is returned.
2104 @end deffn
2105
2106 @deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2107 @deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2108 Return a character set containing every character from @var{cs}
2109 so that it satisfies @var{pred}. If provided, the characters
2110 from @var{base_cs} are added to the result.
2111 @end deffn
2112
2113 @deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2114 @deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2115 Return a character set containing every character from @var{cs}
2116 so that it satisfies @var{pred}. The characters are added to
2117 @var{base_cs} and @var{base_cs} is returned.
2118 @end deffn
2119
2120 @deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2121 @deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2122 Return a character set containing all characters whose
2123 character codes lie in the half-open range
2124 [@var{lower},@var{upper}).
2125
2126 If @var{error} is a true value, an error is signalled if the
2127 specified range contains characters which are not contained in
2128 the implemented character range. If @var{error} is @code{#f},
2129 these characters are silently left out of the resultung
2130 character set.
2131
2132 The characters in @var{base_cs} are added to the result, if
2133 given.
2134 @end deffn
2135
2136 @deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2137 @deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2138 Return a character set containing all characters whose
2139 character codes lie in the half-open range
2140 [@var{lower},@var{upper}).
2141
2142 If @var{error} is a true value, an error is signalled if the
2143 specified range contains characters which are not contained in
2144 the implemented character range. If @var{error} is @code{#f},
2145 these characters are silently left out of the resultung
2146 character set.
2147
2148 The characters are added to @var{base_cs} and @var{base_cs} is
2149 returned.
2150 @end deffn
2151
2152 @deffn {Scheme Procedure} ->char-set x
2153 @deffnx {C Function} scm_to_char_set (x)
2154 Coerces x into a char-set. @var{x} may be a string, character or char-set. A string is converted to the set of its constituent characters; a character is converted to a singleton set; a char-set is returned as-is.
2155 @end deffn
2156
2157 @c ===================================================================
2158
2159 @node Querying Character Sets
2160 @subsubsection Querying Character Sets
2161
2162 Access the elements and other information of a character set with these
2163 procedures.
2164
2165 @deffn {Scheme Procedure} char-set-size cs
2166 @deffnx {C Function} scm_char_set_size (cs)
2167 Return the number of elements in character set @var{cs}.
2168 @end deffn
2169
2170 @deffn {Scheme Procedure} char-set-count pred cs
2171 @deffnx {C Function} scm_char_set_count (pred, cs)
2172 Return the number of the elements int the character set
2173 @var{cs} which satisfy the predicate @var{pred}.
2174 @end deffn
2175
2176 @deffn {Scheme Procedure} char-set->list cs
2177 @deffnx {C Function} scm_char_set_to_list (cs)
2178 Return a list containing the elements of the character set
2179 @var{cs}.
2180 @end deffn
2181
2182 @deffn {Scheme Procedure} char-set->string cs
2183 @deffnx {C Function} scm_char_set_to_string (cs)
2184 Return a string containing the elements of the character set
2185 @var{cs}. The order in which the characters are placed in the
2186 string is not defined.
2187 @end deffn
2188
2189 @deffn {Scheme Procedure} char-set-contains? cs ch
2190 @deffnx {C Function} scm_char_set_contains_p (cs, ch)
2191 Return @code{#t} iff the character @var{ch} is contained in the
2192 character set @var{cs}.
2193 @end deffn
2194
2195 @deffn {Scheme Procedure} char-set-every pred cs
2196 @deffnx {C Function} scm_char_set_every (pred, cs)
2197 Return a true value if every character in the character set
2198 @var{cs} satisfies the predicate @var{pred}.
2199 @end deffn
2200
2201 @deffn {Scheme Procedure} char-set-any pred cs
2202 @deffnx {C Function} scm_char_set_any (pred, cs)
2203 Return a true value if any character in the character set
2204 @var{cs} satisfies the predicate @var{pred}.
2205 @end deffn
2206
2207 @c ===================================================================
2208
2209 @node Character-Set Algebra
2210 @subsubsection Character-Set Algebra
2211
2212 Character sets can be manipulated with the common set algebra operation,
2213 such as union, complement, intersection etc. All of these procedures
2214 provide side-effecting variants, which modify their character set
2215 argument(s).
2216
2217 @deffn {Scheme Procedure} char-set-adjoin cs . rest
2218 @deffnx {C Function} scm_char_set_adjoin (cs, rest)
2219 Add all character arguments to the first argument, which must
2220 be a character set.
2221 @end deffn
2222
2223 @deffn {Scheme Procedure} char-set-delete cs . rest
2224 @deffnx {C Function} scm_char_set_delete (cs, rest)
2225 Delete all character arguments from the first argument, which
2226 must be a character set.
2227 @end deffn
2228
2229 @deffn {Scheme Procedure} char-set-adjoin! cs . rest
2230 @deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2231 Add all character arguments to the first argument, which must
2232 be a character set.
2233 @end deffn
2234
2235 @deffn {Scheme Procedure} char-set-delete! cs . rest
2236 @deffnx {C Function} scm_char_set_delete_x (cs, rest)
2237 Delete all character arguments from the first argument, which
2238 must be a character set.
2239 @end deffn
2240
2241 @deffn {Scheme Procedure} char-set-complement cs
2242 @deffnx {C Function} scm_char_set_complement (cs)
2243 Return the complement of the character set @var{cs}.
2244 @end deffn
2245
2246 @deffn {Scheme Procedure} char-set-union . rest
2247 @deffnx {C Function} scm_char_set_union (rest)
2248 Return the union of all argument character sets.
2249 @end deffn
2250
2251 @deffn {Scheme Procedure} char-set-intersection . rest
2252 @deffnx {C Function} scm_char_set_intersection (rest)
2253 Return the intersection of all argument character sets.
2254 @end deffn
2255
2256 @deffn {Scheme Procedure} char-set-difference cs1 . rest
2257 @deffnx {C Function} scm_char_set_difference (cs1, rest)
2258 Return the difference of all argument character sets.
2259 @end deffn
2260
2261 @deffn {Scheme Procedure} char-set-xor . rest
2262 @deffnx {C Function} scm_char_set_xor (rest)
2263 Return the exclusive-or of all argument character sets.
2264 @end deffn
2265
2266 @deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2267 @deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2268 Return the difference and the intersection of all argument
2269 character sets.
2270 @end deffn
2271
2272 @deffn {Scheme Procedure} char-set-complement! cs
2273 @deffnx {C Function} scm_char_set_complement_x (cs)
2274 Return the complement of the character set @var{cs}.
2275 @end deffn
2276
2277 @deffn {Scheme Procedure} char-set-union! cs1 . rest
2278 @deffnx {C Function} scm_char_set_union_x (cs1, rest)
2279 Return the union of all argument character sets.
2280 @end deffn
2281
2282 @deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2283 @deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2284 Return the intersection of all argument character sets.
2285 @end deffn
2286
2287 @deffn {Scheme Procedure} char-set-difference! cs1 . rest
2288 @deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2289 Return the difference of all argument character sets.
2290 @end deffn
2291
2292 @deffn {Scheme Procedure} char-set-xor! cs1 . rest
2293 @deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2294 Return the exclusive-or of all argument character sets.
2295 @end deffn
2296
2297 @deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2298 @deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2299 Return the difference and the intersection of all argument
2300 character sets.
2301 @end deffn
2302
2303 @c ===================================================================
2304
2305 @node Standard Character Sets
2306 @subsubsection Standard Character Sets
2307
2308 In order to make the use of the character set data type and procedures
2309 useful, several predefined character set variables exist.
2310
2311 @cindex codeset
2312 @cindex charset
2313 @cindex locale
2314
2315 Currently, the contents of these character sets are recomputed upon a
2316 successful @code{setlocale} call (@pxref{Locales}) in order to reflect
2317 the characters available in the current locale's codeset. For
2318 instance, @code{char-set:letter} contains 52 characters under an ASCII
2319 locale (e.g., the default @code{C} locale) and 117 characters under an
2320 ISO-8859-1 (``Latin-1'') locale.
2321
2322 @defvr {Scheme Variable} char-set:lower-case
2323 @defvrx {C Variable} scm_char_set_lower_case
2324 All lower-case characters.
2325 @end defvr
2326
2327 @defvr {Scheme Variable} char-set:upper-case
2328 @defvrx {C Variable} scm_char_set_upper_case
2329 All upper-case characters.
2330 @end defvr
2331
2332 @defvr {Scheme Variable} char-set:title-case
2333 @defvrx {C Variable} scm_char_set_title_case
2334 This is empty, because ASCII has no titlecase characters.
2335 @end defvr
2336
2337 @defvr {Scheme Variable} char-set:letter
2338 @defvrx {C Variable} scm_char_set_letter
2339 All letters, e.g. the union of @code{char-set:lower-case} and
2340 @code{char-set:upper-case}.
2341 @end defvr
2342
2343 @defvr {Scheme Variable} char-set:digit
2344 @defvrx {C Variable} scm_char_set_digit
2345 All digits.
2346 @end defvr
2347
2348 @defvr {Scheme Variable} char-set:letter+digit
2349 @defvrx {C Variable} scm_char_set_letter_and_digit
2350 The union of @code{char-set:letter} and @code{char-set:digit}.
2351 @end defvr
2352
2353 @defvr {Scheme Variable} char-set:graphic
2354 @defvrx {C Variable} scm_char_set_graphic
2355 All characters which would put ink on the paper.
2356 @end defvr
2357
2358 @defvr {Scheme Variable} char-set:printing
2359 @defvrx {C Variable} scm_char_set_printing
2360 The union of @code{char-set:graphic} and @code{char-set:whitespace}.
2361 @end defvr
2362
2363 @defvr {Scheme Variable} char-set:whitespace
2364 @defvrx {C Variable} scm_char_set_whitespace
2365 All whitespace characters.
2366 @end defvr
2367
2368 @defvr {Scheme Variable} char-set:blank
2369 @defvrx {C Variable} scm_char_set_blank
2370 All horizontal whitespace characters, that is @code{#\space} and
2371 @code{#\tab}.
2372 @end defvr
2373
2374 @defvr {Scheme Variable} char-set:iso-control
2375 @defvrx {C Variable} scm_char_set_iso_control
2376 The ISO control characters with the codes 0--31 and 127.
2377 @end defvr
2378
2379 @defvr {Scheme Variable} char-set:punctuation
2380 @defvrx {C Variable} scm_char_set_punctuation
2381 The characters @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
2382 @end defvr
2383
2384 @defvr {Scheme Variable} char-set:symbol
2385 @defvrx {C Variable} scm_char_set_symbol
2386 The characters @code{$+<=>^`|~}.
2387 @end defvr
2388
2389 @defvr {Scheme Variable} char-set:hex-digit
2390 @defvrx {C Variable} scm_char_set_hex_digit
2391 The hexadecimal digits @code{0123456789abcdefABCDEF}.
2392 @end defvr
2393
2394 @defvr {Scheme Variable} char-set:ascii
2395 @defvrx {C Variable} scm_char_set_ascii
2396 All ASCII characters.
2397 @end defvr
2398
2399 @defvr {Scheme Variable} char-set:empty
2400 @defvrx {C Variable} scm_char_set_empty
2401 The empty character set.
2402 @end defvr
2403
2404 @defvr {Scheme Variable} char-set:full
2405 @defvrx {C Variable} scm_char_set_full
2406 This character set contains all possible characters.
2407 @end defvr
2408
2409 @node Strings
2410 @subsection Strings
2411 @tpindex Strings
2412
2413 Strings are fixed-length sequences of characters. They can be created
2414 by calling constructor procedures, but they can also literally get
2415 entered at the @acronym{REPL} or in Scheme source files.
2416
2417 @c Guile provides a rich set of string processing procedures, because text
2418 @c handling is very important when Guile is used as a scripting language.
2419
2420 Strings always carry the information about how many characters they are
2421 composed of with them, so there is no special end-of-string character,
2422 like in C. That means that Scheme strings can contain any character,
2423 even the @samp{#\nul} character @samp{\0}.
2424
2425 To use strings efficiently, you need to know a bit about how Guile
2426 implements them. In Guile, a string consists of two parts, a head and
2427 the actual memory where the characters are stored. When a string (or
2428 a substring of it) is copied, only a new head gets created, the memory
2429 is usually not copied. The two heads start out pointing to the same
2430 memory.
2431
2432 When one of these two strings is modified, as with @code{string-set!},
2433 their common memory does get copied so that each string has its own
2434 memory and modifying one does not accidently modify the other as well.
2435 Thus, Guile's strings are `copy on write'; the actual copying of their
2436 memory is delayed until one string is written to.
2437
2438 This implementation makes functions like @code{substring} very
2439 efficient in the common case that no modifications are done to the
2440 involved strings.
2441
2442 If you do know that your strings are getting modified right away, you
2443 can use @code{substring/copy} instead of @code{substring}. This
2444 function performs the copy immediately at the time of creation. This
2445 is more efficient, especially in a multi-threaded program. Also,
2446 @code{substring/copy} can avoid the problem that a short substring
2447 holds on to the memory of a very large original string that could
2448 otherwise be recycled.
2449
2450 If you want to avoid the copy altogether, so that modifications of one
2451 string show up in the other, you can use @code{substring/shared}. The
2452 strings created by this procedure are called @dfn{mutation sharing
2453 substrings} since the substring and the original string share
2454 modifications to each other.
2455
2456 If you want to prevent modifications, use @code{substring/read-only}.
2457
2458 Guile provides all procedures of SRFI-13 and a few more.
2459
2460 @menu
2461 * String Syntax:: Read syntax for strings.
2462 * String Predicates:: Testing strings for certain properties.
2463 * String Constructors:: Creating new string objects.
2464 * List/String Conversion:: Converting from/to lists of characters.
2465 * String Selection:: Select portions from strings.
2466 * String Modification:: Modify parts or whole strings.
2467 * String Comparison:: Lexicographic ordering predicates.
2468 * String Searching:: Searching in strings.
2469 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2470 * Reversing and Appending Strings:: Appending strings to form a new string.
2471 * Mapping Folding and Unfolding:: Iterating over strings.
2472 * Miscellaneous String Operations:: Replicating, insertion, parsing, ...
2473 * Conversion to/from C::
2474 @end menu
2475
2476 @node String Syntax
2477 @subsubsection String Read Syntax
2478
2479 @c In the following @code is used to get a good font in TeX etc, but
2480 @c is omitted for Info format, so as not to risk any confusion over
2481 @c whether surrounding ` ' quotes are part of the escape or are
2482 @c special in a string (they're not).
2483
2484 The read syntax for strings is an arbitrarily long sequence of
2485 characters enclosed in double quotes (@nicode{"}).
2486
2487 Backslash is an escape character and can be used to insert the
2488 following special characters. @nicode{\"} and @nicode{\\} are R5RS
2489 standard, the rest are Guile extensions, notice they follow C string
2490 syntax.
2491
2492 @table @asis
2493 @item @nicode{\\}
2494 Backslash character.
2495
2496 @item @nicode{\"}
2497 Double quote character (an unescaped @nicode{"} is otherwise the end
2498 of the string).
2499
2500 @item @nicode{\0}
2501 NUL character (ASCII 0).
2502
2503 @item @nicode{\a}
2504 Bell character (ASCII 7).
2505
2506 @item @nicode{\f}
2507 Formfeed character (ASCII 12).
2508
2509 @item @nicode{\n}
2510 Newline character (ASCII 10).
2511
2512 @item @nicode{\r}
2513 Carriage return character (ASCII 13).
2514
2515 @item @nicode{\t}
2516 Tab character (ASCII 9).
2517
2518 @item @nicode{\v}
2519 Vertical tab character (ASCII 11).
2520
2521 @item @nicode{\xHH}
2522 Character code given by two hexadecimal digits. For example
2523 @nicode{\x7f} for an ASCII DEL (127).
2524 @end table
2525
2526 @noindent
2527 The following are examples of string literals:
2528
2529 @lisp
2530 "foo"
2531 "bar plonk"
2532 "Hello World"
2533 "\"Hi\", he said."
2534 @end lisp
2535
2536
2537 @node String Predicates
2538 @subsubsection String Predicates
2539
2540 The following procedures can be used to check whether a given string
2541 fulfills some specified property.
2542
2543 @rnindex string?
2544 @deffn {Scheme Procedure} string? obj
2545 @deffnx {C Function} scm_string_p (obj)
2546 Return @code{#t} if @var{obj} is a string, else @code{#f}.
2547 @end deffn
2548
2549 @deftypefn {C Function} int scm_is_string (SCM obj)
2550 Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2551 @end deftypefn
2552
2553 @deffn {Scheme Procedure} string-null? str
2554 @deffnx {C Function} scm_string_null_p (str)
2555 Return @code{#t} if @var{str}'s length is zero, and
2556 @code{#f} otherwise.
2557 @lisp
2558 (string-null? "") @result{} #t
2559 y @result{} "foo"
2560 (string-null? y) @result{} #f
2561 @end lisp
2562 @end deffn
2563
2564 @deffn {Scheme Procedure} string-any char_pred s [start [end]]
2565 @deffnx {C Function} scm_string_any (char_pred, s, start, end)
2566 Check if @var{char_pred} is true for any character in string @var{s}.
2567
2568 @var{char_pred} can be a character to check for any equal to that, or
2569 a character set (@pxref{Character Sets}) to check for any in that set,
2570 or a predicate procedure to call.
2571
2572 For a procedure, calls @code{(@var{char_pred} c)} are made
2573 successively on the characters from @var{start} to @var{end}. If
2574 @var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2575 stops and that return value is the return from @code{string-any}. The
2576 call on the last character (ie.@: at @math{@var{end}-1}), if that
2577 point is reached, is a tail call.
2578
2579 If there are no characters in @var{s} (ie.@: @var{start} equals
2580 @var{end}) then the return is @code{#f}.
2581 @end deffn
2582
2583 @deffn {Scheme Procedure} string-every char_pred s [start [end]]
2584 @deffnx {C Function} scm_string_every (char_pred, s, start, end)
2585 Check if @var{char_pred} is true for every character in string
2586 @var{s}.
2587
2588 @var{char_pred} can be a character to check for every character equal
2589 to that, or a character set (@pxref{Character Sets}) to check for
2590 every character being in that set, or a predicate procedure to call.
2591
2592 For a procedure, calls @code{(@var{char_pred} c)} are made
2593 successively on the characters from @var{start} to @var{end}. If
2594 @var{char_pred} returns @code{#f}, @code{string-every} stops and
2595 returns @code{#f}. The call on the last character (ie.@: at
2596 @math{@var{end}-1}), if that point is reached, is a tail call and the
2597 return from that call is the return from @code{string-every}.
2598
2599 If there are no characters in @var{s} (ie.@: @var{start} equals
2600 @var{end}) then the return is @code{#t}.
2601 @end deffn
2602
2603 @node String Constructors
2604 @subsubsection String Constructors
2605
2606 The string constructor procedures create new string objects, possibly
2607 initializing them with some specified character data. See also
2608 @xref{String Selection}, for ways to create strings from existing
2609 strings.
2610
2611 @c FIXME::martin: list->string belongs into `List/String Conversion'
2612
2613 @deffn {Scheme Procedure} string char@dots{}
2614 @rnindex string
2615 Return a newly allocated string made from the given character
2616 arguments.
2617
2618 @example
2619 (string #\x #\y #\z) @result{} "xyz"
2620 (string) @result{} ""
2621 @end example
2622 @end deffn
2623
2624 @deffn {Scheme Procedure} list->string lst
2625 @deffnx {C Function} scm_string (lst)
2626 @rnindex list->string
2627 Return a newly allocated string made from a list of characters.
2628
2629 @example
2630 (list->string '(#\a #\b #\c)) @result{} "abc"
2631 @end example
2632 @end deffn
2633
2634 @deffn {Scheme Procedure} reverse-list->string lst
2635 @deffnx {C Function} scm_reverse_list_to_string (lst)
2636 Return a newly allocated string made from a list of characters, in
2637 reverse order.
2638
2639 @example
2640 (reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2641 @end example
2642 @end deffn
2643
2644 @rnindex make-string
2645 @deffn {Scheme Procedure} make-string k [chr]
2646 @deffnx {C Function} scm_make_string (k, chr)
2647 Return a newly allocated string of
2648 length @var{k}. If @var{chr} is given, then all elements of
2649 the string are initialized to @var{chr}, otherwise the contents
2650 of the @var{string} are unspecified.
2651 @end deffn
2652
2653 @deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2654 Like @code{scm_make_string}, but expects the length as a
2655 @code{size_t}.
2656 @end deftypefn
2657
2658 @deffn {Scheme Procedure} string-tabulate proc len
2659 @deffnx {C Function} scm_string_tabulate (proc, len)
2660 @var{proc} is an integer->char procedure. Construct a string
2661 of size @var{len} by applying @var{proc} to each index to
2662 produce the corresponding string element. The order in which
2663 @var{proc} is applied to the indices is not specified.
2664 @end deffn
2665
2666 @deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2667 @deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2668 Append the string in the string list @var{ls}, using the string
2669 @var{delim} as a delimiter between the elements of @var{ls}.
2670 @var{grammar} is a symbol which specifies how the delimiter is
2671 placed between the strings, and defaults to the symbol
2672 @code{infix}.
2673
2674 @table @code
2675 @item infix
2676 Insert the separator between list elements. An empty string
2677 will produce an empty list.
2678 @item string-infix
2679 Like @code{infix}, but will raise an error if given the empty
2680 list.
2681 @item suffix
2682 Insert the separator after every list element.
2683 @item prefix
2684 Insert the separator before each list element.
2685 @end table
2686 @end deffn
2687
2688 @node List/String Conversion
2689 @subsubsection List/String conversion
2690
2691 When processing strings, it is often convenient to first convert them
2692 into a list representation by using the procedure @code{string->list},
2693 work with the resulting list, and then convert it back into a string.
2694 These procedures are useful for similar tasks.
2695
2696 @rnindex string->list
2697 @deffn {Scheme Procedure} string->list str [start [end]]
2698 @deffnx {C Function} scm_substring_to_list (str, start, end)
2699 @deffnx {C Function} scm_string_to_list (str)
2700 Convert the string @var{str} into a list of characters.
2701 @end deffn
2702
2703 @deffn {Scheme Procedure} string-split str chr
2704 @deffnx {C Function} scm_string_split (str, chr)
2705 Split the string @var{str} into the a list of the substrings delimited
2706 by appearances of the character @var{chr}. Note that an empty substring
2707 between separator characters will result in an empty string in the
2708 result list.
2709
2710 @lisp
2711 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2712 @result{}
2713 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
2714
2715 (string-split "::" #\:)
2716 @result{}
2717 ("" "" "")
2718
2719 (string-split "" #\:)
2720 @result{}
2721 ("")
2722 @end lisp
2723 @end deffn
2724
2725
2726 @node String Selection
2727 @subsubsection String Selection
2728
2729 Portions of strings can be extracted by these procedures.
2730 @code{string-ref} delivers individual characters whereas
2731 @code{substring} can be used to extract substrings from longer strings.
2732
2733 @rnindex string-length
2734 @deffn {Scheme Procedure} string-length string
2735 @deffnx {C Function} scm_string_length (string)
2736 Return the number of characters in @var{string}.
2737 @end deffn
2738
2739 @deftypefn {C Function} size_t scm_c_string_length (SCM str)
2740 Return the number of characters in @var{str} as a @code{size_t}.
2741 @end deftypefn
2742
2743 @rnindex string-ref
2744 @deffn {Scheme Procedure} string-ref str k
2745 @deffnx {C Function} scm_string_ref (str, k)
2746 Return character @var{k} of @var{str} using zero-origin
2747 indexing. @var{k} must be a valid index of @var{str}.
2748 @end deffn
2749
2750 @deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2751 Return character @var{k} of @var{str} using zero-origin
2752 indexing. @var{k} must be a valid index of @var{str}.
2753 @end deftypefn
2754
2755 @rnindex string-copy
2756 @deffn {Scheme Procedure} string-copy str [start [end]]
2757 @deffnx {C Function} scm_substring_copy (str, start, end)
2758 @deffnx {C Function} scm_string_copy (str)
2759 Return a copy of the given string @var{str}.
2760
2761 The returned string shares storage with @var{str} initially, but it is
2762 copied as soon as one of the two strings is modified.
2763 @end deffn
2764
2765 @rnindex substring
2766 @deffn {Scheme Procedure} substring str start [end]
2767 @deffnx {C Function} scm_substring (str, start, end)
2768 Return a new string formed from the characters
2769 of @var{str} beginning with index @var{start} (inclusive) and
2770 ending with index @var{end} (exclusive).
2771 @var{str} must be a string, @var{start} and @var{end} must be
2772 exact integers satisfying:
2773
2774 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
2775
2776 The returned string shares storage with @var{str} initially, but it is
2777 copied as soon as one of the two strings is modified.
2778 @end deffn
2779
2780 @deffn {Scheme Procedure} substring/shared str start [end]
2781 @deffnx {C Function} scm_substring_shared (str, start, end)
2782 Like @code{substring}, but the strings continue to share their storage
2783 even if they are modified. Thus, modifications to @var{str} show up
2784 in the new string, and vice versa.
2785 @end deffn
2786
2787 @deffn {Scheme Procedure} substring/copy str start [end]
2788 @deffnx {C Function} scm_substring_copy (str, start, end)
2789 Like @code{substring}, but the storage for the new string is copied
2790 immediately.
2791 @end deffn
2792
2793 @deffn {Scheme Procedure} substring/read-only str start [end]
2794 @deffnx {C Function} scm_substring_read_only (str, start, end)
2795 Like @code{substring}, but the resulting string can not be modified.
2796 @end deffn
2797
2798 @deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2799 @deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2800 @deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2801 @deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
2802 Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2803 @end deftypefn
2804
2805 @deffn {Scheme Procedure} string-take s n
2806 @deffnx {C Function} scm_string_take (s, n)
2807 Return the @var{n} first characters of @var{s}.
2808 @end deffn
2809
2810 @deffn {Scheme Procedure} string-drop s n
2811 @deffnx {C Function} scm_string_drop (s, n)
2812 Return all but the first @var{n} characters of @var{s}.
2813 @end deffn
2814
2815 @deffn {Scheme Procedure} string-take-right s n
2816 @deffnx {C Function} scm_string_take_right (s, n)
2817 Return the @var{n} last characters of @var{s}.
2818 @end deffn
2819
2820 @deffn {Scheme Procedure} string-drop-right s n
2821 @deffnx {C Function} scm_string_drop_right (s, n)
2822 Return all but the last @var{n} characters of @var{s}.
2823 @end deffn
2824
2825 @deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
2826 @deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
2827 @deffnx {C Function} scm_string_pad (s, len, chr, start, end)
2828 @deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
2829 Take characters @var{start} to @var{end} from the string @var{s} and
2830 either pad with @var{char} or truncate them to give @var{len}
2831 characters.
2832
2833 @code{string-pad} pads or truncates on the left, so for example
2834
2835 @example
2836 (string-pad "x" 3) @result{} " x"
2837 (string-pad "abcde" 3) @result{} "cde"
2838 @end example
2839
2840 @code{string-pad-right} pads or truncates on the right, so for example
2841
2842 @example
2843 (string-pad-right "x" 3) @result{} "x "
2844 (string-pad-right "abcde" 3) @result{} "abc"
2845 @end example
2846 @end deffn
2847
2848 @deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
2849 @deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
2850 @deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
2851 @deffnx {C Function} scm_string_trim (s, char_pred, start, end)
2852 @deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
2853 @deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
2854 Trim occurrances of @var{char_pred} from the ends of @var{s}.
2855
2856 @code{string-trim} trims @var{char_pred} characters from the left
2857 (start) of the string, @code{string-trim-right} trims them from the
2858 right (end) of the string, @code{string-trim-both} trims from both
2859 ends.
2860
2861 @var{char_pred} can be a character, a character set, or a predicate
2862 procedure to call on each character. If @var{char_pred} is not given
2863 the default is whitespace as per @code{char-set:whitespace}
2864 (@pxref{Standard Character Sets}).
2865
2866 @example
2867 (string-trim " x ") @result{} "x "
2868 (string-trim-right "banana" #\a) @result{} "banan"
2869 (string-trim-both ".,xy:;" char-set:punctuation)
2870 @result{} "xy"
2871 (string-trim-both "xyzzy" (lambda (c)
2872 (or (eqv? c #\x)
2873 (eqv? c #\y))))
2874 @result{} "zz"
2875 @end example
2876 @end deffn
2877
2878 @node String Modification
2879 @subsubsection String Modification
2880
2881 These procedures are for modifying strings in-place. This means that the
2882 result of the operation is not a new string; instead, the original string's
2883 memory representation is modified.
2884
2885 @rnindex string-set!
2886 @deffn {Scheme Procedure} string-set! str k chr
2887 @deffnx {C Function} scm_string_set_x (str, k, chr)
2888 Store @var{chr} in element @var{k} of @var{str} and return
2889 an unspecified value. @var{k} must be a valid index of
2890 @var{str}.
2891 @end deffn
2892
2893 @deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
2894 Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
2895 @end deftypefn
2896
2897 @rnindex string-fill!
2898 @deffn {Scheme Procedure} string-fill! str chr [start [end]]
2899 @deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
2900 @deffnx {C Function} scm_string_fill_x (str, chr)
2901 Stores @var{chr} in every element of the given @var{str} and
2902 returns an unspecified value.
2903 @end deffn
2904
2905 @deffn {Scheme Procedure} substring-fill! str start end fill
2906 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
2907 Change every character in @var{str} between @var{start} and
2908 @var{end} to @var{fill}.
2909
2910 @lisp
2911 (define y "abcdefg")
2912 (substring-fill! y 1 3 #\r)
2913 y
2914 @result{} "arrdefg"
2915 @end lisp
2916 @end deffn
2917
2918 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
2919 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
2920 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
2921 into @var{str2} beginning at position @var{start2}.
2922 @var{str1} and @var{str2} can be the same string.
2923 @end deffn
2924
2925 @deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
2926 @deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
2927 Copy the sequence of characters from index range [@var{start},
2928 @var{end}) in string @var{s} to string @var{target}, beginning
2929 at index @var{tstart}. The characters are copied left-to-right
2930 or right-to-left as needed -- the copy is guaranteed to work,
2931 even if @var{target} and @var{s} are the same string. It is an
2932 error if the copy operation runs off the end of the target
2933 string.
2934 @end deffn
2935
2936
2937 @node String Comparison
2938 @subsubsection String Comparison
2939
2940 The procedures in this section are similar to the character ordering
2941 predicates (@pxref{Characters}), but are defined on character sequences.
2942
2943 The first set is specified in R5RS and has names that end in @code{?}.
2944 The second set is specified in SRFI-13 and the names have no ending
2945 @code{?}. The predicates ending in @code{-ci} ignore the character case
2946 when comparing strings.
2947
2948 @rnindex string=?
2949 @deffn {Scheme Procedure} string=? s1 s2
2950 Lexicographic equality predicate; return @code{#t} if the two
2951 strings are the same length and contain the same characters in
2952 the same positions, otherwise return @code{#f}.
2953
2954 The procedure @code{string-ci=?} treats upper and lower case
2955 letters as though they were the same character, but
2956 @code{string=?} treats upper and lower case as distinct
2957 characters.
2958 @end deffn
2959
2960 @rnindex string<?
2961 @deffn {Scheme Procedure} string<? s1 s2
2962 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2963 is lexicographically less than @var{s2}.
2964 @end deffn
2965
2966 @rnindex string<=?
2967 @deffn {Scheme Procedure} string<=? s1 s2
2968 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2969 is lexicographically less than or equal to @var{s2}.
2970 @end deffn
2971
2972 @rnindex string>?
2973 @deffn {Scheme Procedure} string>? s1 s2
2974 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2975 is lexicographically greater than @var{s2}.
2976 @end deffn
2977
2978 @rnindex string>=?
2979 @deffn {Scheme Procedure} string>=? s1 s2
2980 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2981 is lexicographically greater than or equal to @var{s2}.
2982 @end deffn
2983
2984 @rnindex string-ci=?
2985 @deffn {Scheme Procedure} string-ci=? s1 s2
2986 Case-insensitive string equality predicate; return @code{#t} if
2987 the two strings are the same length and their component
2988 characters match (ignoring case) at each position; otherwise
2989 return @code{#f}.
2990 @end deffn
2991
2992 @rnindex string-ci<?
2993 @deffn {Scheme Procedure} string-ci<? s1 s2
2994 Case insensitive lexicographic ordering predicate; return
2995 @code{#t} if @var{s1} is lexicographically less than @var{s2}
2996 regardless of case.
2997 @end deffn
2998
2999 @rnindex string<=?
3000 @deffn {Scheme Procedure} string-ci<=? s1 s2
3001 Case insensitive lexicographic ordering predicate; return
3002 @code{#t} if @var{s1} is lexicographically less than or equal
3003 to @var{s2} regardless of case.
3004 @end deffn
3005
3006 @rnindex string-ci>?
3007 @deffn {Scheme Procedure} string-ci>? s1 s2
3008 Case insensitive lexicographic ordering predicate; return
3009 @code{#t} if @var{s1} is lexicographically greater than
3010 @var{s2} regardless of case.
3011 @end deffn
3012
3013 @rnindex string-ci>=?
3014 @deffn {Scheme Procedure} string-ci>=? s1 s2
3015 Case insensitive lexicographic ordering predicate; return
3016 @code{#t} if @var{s1} is lexicographically greater than or
3017 equal to @var{s2} regardless of case.
3018 @end deffn
3019
3020 @deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3021 @deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3022 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3023 mismatch index, depending upon whether @var{s1} is less than,
3024 equal to, or greater than @var{s2}. The mismatch index is the
3025 largest index @var{i} such that for every 0 <= @var{j} <
3026 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3027 @var{i} is the first position that does not match.
3028 @end deffn
3029
3030 @deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3031 @deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3032 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3033 mismatch index, depending upon whether @var{s1} is less than,
3034 equal to, or greater than @var{s2}. The mismatch index is the
3035 largest index @var{i} such that for every 0 <= @var{j} <
3036 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3037 @var{i} is the first position that does not match. The
3038 character comparison is done case-insensitively.
3039 @end deffn
3040
3041 @deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3042 @deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3043 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3044 value otherwise.
3045 @end deffn
3046
3047 @deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3048 @deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3049 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3050 value otherwise.
3051 @end deffn
3052
3053 @deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3054 @deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3055 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3056 true value otherwise.
3057 @end deffn
3058
3059 @deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3060 @deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3061 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3062 true value otherwise.
3063 @end deffn
3064
3065 @deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3066 @deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3067 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3068 value otherwise.
3069 @end deffn
3070
3071 @deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3072 @deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3073 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3074 otherwise.
3075 @end deffn
3076
3077 @deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3078 @deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3079 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3080 value otherwise. The character comparison is done
3081 case-insensitively.
3082 @end deffn
3083
3084 @deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3085 @deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3086 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3087 value otherwise. The character comparison is done
3088 case-insensitively.
3089 @end deffn
3090
3091 @deffn {Scheme Procedure} string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
3092 @deffnx {C Function} scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
3093 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3094 true value otherwise. The character comparison is done
3095 case-insensitively.
3096 @end deffn
3097
3098 @deffn {Scheme Procedure} string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
3099 @deffnx {C Function} scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
3100 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3101 true value otherwise. The character comparison is done
3102 case-insensitively.
3103 @end deffn
3104
3105 @deffn {Scheme Procedure} string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
3106 @deffnx {C Function} scm_string_ci_le (s1, s2, start1, end1, start2, end2)
3107 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3108 value otherwise. The character comparison is done
3109 case-insensitively.
3110 @end deffn
3111
3112 @deffn {Scheme Procedure} string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
3113 @deffnx {C Function} scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
3114 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3115 otherwise. The character comparison is done
3116 case-insensitively.
3117 @end deffn
3118
3119 @deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3120 @deffnx {C Function} scm_substring_hash (s, bound, start, end)
3121 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).
3122 @end deffn
3123
3124 @deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3125 @deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3126 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).
3127 @end deffn
3128
3129 @node String Searching
3130 @subsubsection String Searching
3131
3132 @deffn {Scheme Procedure} string-index s char_pred [start [end]]
3133 @deffnx {C Function} scm_string_index (s, char_pred, start, end)
3134 Search through the string @var{s} from left to right, returning
3135 the index of the first occurence of a character which
3136
3137 @itemize @bullet
3138 @item
3139 equals @var{char_pred}, if it is character,
3140
3141 @item
3142 satisifies the predicate @var{char_pred}, if it is a procedure,
3143
3144 @item
3145 is in the set @var{char_pred}, if it is a character set.
3146 @end itemize
3147 @end deffn
3148
3149 @deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3150 @deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3151 Search through the string @var{s} from right to left, returning
3152 the index of the last occurence of a character which
3153
3154 @itemize @bullet
3155 @item
3156 equals @var{char_pred}, if it is character,
3157
3158 @item
3159 satisifies the predicate @var{char_pred}, if it is a procedure,
3160
3161 @item
3162 is in the set if @var{char_pred} is a character set.
3163 @end itemize
3164 @end deffn
3165
3166 @deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3167 @deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3168 Return the length of the longest common prefix of the two
3169 strings.
3170 @end deffn
3171
3172 @deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3173 @deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3174 Return the length of the longest common prefix of the two
3175 strings, ignoring character case.
3176 @end deffn
3177
3178 @deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3179 @deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3180 Return the length of the longest common suffix of the two
3181 strings.
3182 @end deffn
3183
3184 @deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3185 @deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3186 Return the length of the longest common suffix of the two
3187 strings, ignoring character case.
3188 @end deffn
3189
3190 @deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3191 @deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3192 Is @var{s1} a prefix of @var{s2}?
3193 @end deffn
3194
3195 @deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3196 @deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3197 Is @var{s1} a prefix of @var{s2}, ignoring character case?
3198 @end deffn
3199
3200 @deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3201 @deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3202 Is @var{s1} a suffix of @var{s2}?
3203 @end deffn
3204
3205 @deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3206 @deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3207 Is @var{s1} a suffix of @var{s2}, ignoring character case?
3208 @end deffn
3209
3210 @deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3211 @deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3212 Search through the string @var{s} from right to left, returning
3213 the index of the last occurence of a character which
3214
3215 @itemize @bullet
3216 @item
3217 equals @var{char_pred}, if it is character,
3218
3219 @item
3220 satisifies the predicate @var{char_pred}, if it is a procedure,
3221
3222 @item
3223 is in the set if @var{char_pred} is a character set.
3224 @end itemize
3225 @end deffn
3226
3227 @deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3228 @deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3229 Search through the string @var{s} from left to right, returning
3230 the index of the first occurence of a character which
3231
3232 @itemize @bullet
3233 @item
3234 does not equal @var{char_pred}, if it is character,
3235
3236 @item
3237 does not satisify the predicate @var{char_pred}, if it is a
3238 procedure,
3239
3240 @item
3241 is not in the set if @var{char_pred} is a character set.
3242 @end itemize
3243 @end deffn
3244
3245 @deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3246 @deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3247 Search through the string @var{s} from right to left, returning
3248 the index of the last occurence of a character which
3249
3250 @itemize @bullet
3251 @item
3252 does not equal @var{char_pred}, if it is character,
3253
3254 @item
3255 does not satisfy the predicate @var{char_pred}, if it is a
3256 procedure,
3257
3258 @item
3259 is not in the set if @var{char_pred} is a character set.
3260 @end itemize
3261 @end deffn
3262
3263 @deffn {Scheme Procedure} string-count s char_pred [start [end]]
3264 @deffnx {C Function} scm_string_count (s, char_pred, start, end)
3265 Return the count of the number of characters in the string
3266 @var{s} which
3267
3268 @itemize @bullet
3269 @item
3270 equals @var{char_pred}, if it is character,
3271
3272 @item
3273 satisifies the predicate @var{char_pred}, if it is a procedure.
3274
3275 @item
3276 is in the set @var{char_pred}, if it is a character set.
3277 @end itemize
3278 @end deffn
3279
3280 @deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3281 @deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3282 Does string @var{s1} contain string @var{s2}? Return the index
3283 in @var{s1} where @var{s2} occurs as a substring, or false.
3284 The optional start/end indices restrict the operation to the
3285 indicated substrings.
3286 @end deffn
3287
3288 @deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3289 @deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3290 Does string @var{s1} contain string @var{s2}? Return the index
3291 in @var{s1} where @var{s2} occurs as a substring, or false.
3292 The optional start/end indices restrict the operation to the
3293 indicated substrings. Character comparison is done
3294 case-insensitively.
3295 @end deffn
3296
3297 @node Alphabetic Case Mapping
3298 @subsubsection Alphabetic Case Mapping
3299
3300 These are procedures for mapping strings to their upper- or lower-case
3301 equivalents, respectively, or for capitalizing strings.
3302
3303 @deffn {Scheme Procedure} string-upcase str [start [end]]
3304 @deffnx {C Function} scm_substring_upcase (str, start, end)
3305 @deffnx {C Function} scm_string_upcase (str)
3306 Upcase every character in @code{str}.
3307 @end deffn
3308
3309 @deffn {Scheme Procedure} string-upcase! str [start [end]]
3310 @deffnx {C Function} scm_substring_upcase_x (str, start, end)
3311 @deffnx {C Function} scm_string_upcase_x (str)
3312 Destructively upcase every character in @code{str}.
3313
3314 @lisp
3315 (string-upcase! y)
3316 @result{} "ARRDEFG"
3317 y
3318 @result{} "ARRDEFG"
3319 @end lisp
3320 @end deffn
3321
3322 @deffn {Scheme Procedure} string-downcase str [start [end]]
3323 @deffnx {C Function} scm_substring_downcase (str, start, end)
3324 @deffnx {C Function} scm_string_downcase (str)
3325 Downcase every character in @var{str}.
3326 @end deffn
3327
3328 @deffn {Scheme Procedure} string-downcase! str [start [end]]
3329 @deffnx {C Function} scm_substring_downcase_x (str, start, end)
3330 @deffnx {C Function} scm_string_downcase_x (str)
3331 Destructively downcase every character in @var{str}.
3332
3333 @lisp
3334 y
3335 @result{} "ARRDEFG"
3336 (string-downcase! y)
3337 @result{} "arrdefg"
3338 y
3339 @result{} "arrdefg"
3340 @end lisp
3341 @end deffn
3342
3343 @deffn {Scheme Procedure} string-capitalize str
3344 @deffnx {C Function} scm_string_capitalize (str)
3345 Return a freshly allocated string with the characters in
3346 @var{str}, where the first character of every word is
3347 capitalized.
3348 @end deffn
3349
3350 @deffn {Scheme Procedure} string-capitalize! str
3351 @deffnx {C Function} scm_string_capitalize_x (str)
3352 Upcase the first character of every word in @var{str}
3353 destructively and return @var{str}.
3354
3355 @lisp
3356 y @result{} "hello world"
3357 (string-capitalize! y) @result{} "Hello World"
3358 y @result{} "Hello World"
3359 @end lisp
3360 @end deffn
3361
3362 @deffn {Scheme Procedure} string-titlecase str [start [end]]
3363 @deffnx {C Function} scm_string_titlecase (str, start, end)
3364 Titlecase every first character in a word in @var{str}.
3365 @end deffn
3366
3367 @deffn {Scheme Procedure} string-titlecase! str [start [end]]
3368 @deffnx {C Function} scm_string_titlecase_x (str, start, end)
3369 Destructively titlecase every first character in a word in
3370 @var{str}.
3371 @end deffn
3372
3373 @node Reversing and Appending Strings
3374 @subsubsection Reversing and Appending Strings
3375
3376 @deffn {Scheme Procedure} string-reverse str [start [end]]
3377 @deffnx {C Function} scm_string_reverse (str, start, end)
3378 Reverse the string @var{str}. The optional arguments
3379 @var{start} and @var{end} delimit the region of @var{str} to
3380 operate on.
3381 @end deffn
3382
3383 @deffn {Scheme Procedure} string-reverse! str [start [end]]
3384 @deffnx {C Function} scm_string_reverse_x (str, start, end)
3385 Reverse the string @var{str} in-place. The optional arguments
3386 @var{start} and @var{end} delimit the region of @var{str} to
3387 operate on. The return value is unspecified.
3388 @end deffn
3389
3390 @rnindex string-append
3391 @deffn {Scheme Procedure} string-append . args
3392 @deffnx {C Function} scm_string_append (args)
3393 Return a newly allocated string whose characters form the
3394 concatenation of the given strings, @var{args}.
3395
3396 @example
3397 (let ((h "hello "))
3398 (string-append h "world"))
3399 @result{} "hello world"
3400 @end example
3401 @end deffn
3402
3403 @deffn {Scheme Procedure} string-append/shared . ls
3404 @deffnx {C Function} scm_string_append_shared (ls)
3405 Like @code{string-append}, but the result may share memory
3406 with the argument strings.
3407 @end deffn
3408
3409 @deffn {Scheme Procedure} string-concatenate ls
3410 @deffnx {C Function} scm_string_concatenate (ls)
3411 Append the elements of @var{ls} (which must be strings)
3412 together into a single string. Guaranteed to return a freshly
3413 allocated string.
3414 @end deffn
3415
3416 @deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3417 @deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3418 Without optional arguments, this procedure is equivalent to
3419
3420 @smalllisp
3421 (string-concatenate (reverse ls))
3422 @end smalllisp
3423
3424 If the optional argument @var{final_string} is specified, it is
3425 consed onto the beginning to @var{ls} before performing the
3426 list-reverse and string-concatenate operations. If @var{end}
3427 is given, only the characters of @var{final_string} up to index
3428 @var{end} are used.
3429
3430 Guaranteed to return a freshly allocated string.
3431 @end deffn
3432
3433 @deffn {Scheme Procedure} string-concatenate/shared ls
3434 @deffnx {C Function} scm_string_concatenate_shared (ls)
3435 Like @code{string-concatenate}, but the result may share memory
3436 with the strings in the list @var{ls}.
3437 @end deffn
3438
3439 @deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3440 @deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3441 Like @code{string-concatenate-reverse}, but the result may
3442 share memory with the the strings in the @var{ls} arguments.
3443 @end deffn
3444
3445 @node Mapping Folding and Unfolding
3446 @subsubsection Mapping, Folding, and Unfolding
3447
3448 @deffn {Scheme Procedure} string-map proc s [start [end]]
3449 @deffnx {C Function} scm_string_map (proc, s, start, end)
3450 @var{proc} is a char->char procedure, it is mapped over
3451 @var{s}. The order in which the procedure is applied to the
3452 string elements is not specified.
3453 @end deffn
3454
3455 @deffn {Scheme Procedure} string-map! proc s [start [end]]
3456 @deffnx {C Function} scm_string_map_x (proc, s, start, end)
3457 @var{proc} is a char->char procedure, it is mapped over
3458 @var{s}. The order in which the procedure is applied to the
3459 string elements is not specified. The string @var{s} is
3460 modified in-place, the return value is not specified.
3461 @end deffn
3462
3463 @deffn {Scheme Procedure} string-for-each proc s [start [end]]
3464 @deffnx {C Function} scm_string_for_each (proc, s, start, end)
3465 @var{proc} is mapped over @var{s} in left-to-right order. The
3466 return value is not specified.
3467 @end deffn
3468
3469 @deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3470 @deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
3471 Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3472 right.
3473
3474 For example, to change characters to alternately upper and lower case,
3475
3476 @example
3477 (define str (string-copy "studly"))
3478 (string-for-each-index (lambda (i)
3479 (string-set! str i
3480 ((if (even? i) char-upcase char-downcase)
3481 (string-ref str i))))
3482 str)
3483 str @result{} "StUdLy"
3484 @end example
3485 @end deffn
3486
3487 @deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3488 @deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3489 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3490 as the terminating element, from left to right. @var{kons}
3491 must expect two arguments: The actual character and the last
3492 result of @var{kons}' application.
3493 @end deffn
3494
3495 @deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3496 @deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3497 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3498 as the terminating element, from right to left. @var{kons}
3499 must expect two arguments: The actual character and the last
3500 result of @var{kons}' application.
3501 @end deffn
3502
3503 @deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3504 @deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3505 @itemize @bullet
3506 @item @var{g} is used to generate a series of @emph{seed}
3507 values from the initial @var{seed}: @var{seed}, (@var{g}
3508 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3509 @dots{}
3510 @item @var{p} tells us when to stop -- when it returns true
3511 when applied to one of these seed values.
3512 @item @var{f} maps each seed value to the corresponding
3513 character in the result string. These chars are assembled
3514 into the string in a left-to-right order.
3515 @item @var{base} is the optional initial/leftmost portion
3516 of the constructed string; it default to the empty
3517 string.
3518 @item @var{make_final} is applied to the terminal seed
3519 value (on which @var{p} returns true) to produce
3520 the final/rightmost portion of the constructed string.
3521 It defaults to @code{(lambda (x) )}.
3522 @end itemize
3523 @end deffn
3524
3525 @deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3526 @deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3527 @itemize @bullet
3528 @item @var{g} is used to generate a series of @emph{seed}
3529 values from the initial @var{seed}: @var{seed}, (@var{g}
3530 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3531 @dots{}
3532 @item @var{p} tells us when to stop -- when it returns true
3533 when applied to one of these seed values.
3534 @item @var{f} maps each seed value to the corresponding
3535 character in the result string. These chars are assembled
3536 into the string in a right-to-left order.
3537 @item @var{base} is the optional initial/rightmost portion
3538 of the constructed string; it default to the empty
3539 string.
3540 @item @var{make_final} is applied to the terminal seed
3541 value (on which @var{p} returns true) to produce
3542 the final/leftmost portion of the constructed string.
3543 It defaults to @code{(lambda (x) )}.
3544 @end itemize
3545 @end deffn
3546
3547 @node Miscellaneous String Operations
3548 @subsubsection Miscellaneous String Operations
3549
3550 @deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3551 @deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3552 This is the @emph{extended substring} procedure that implements
3553 replicated copying of a substring of some string.
3554
3555 @var{s} is a string, @var{start} and @var{end} are optional
3556 arguments that demarcate a substring of @var{s}, defaulting to
3557 0 and the length of @var{s}. Replicate this substring up and
3558 down index space, in both the positive and negative directions.
3559 @code{xsubstring} returns the substring of this string
3560 beginning at index @var{from}, and ending at @var{to}, which
3561 defaults to @var{from} + (@var{end} - @var{start}).
3562 @end deffn
3563
3564 @deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3565 @deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3566 Exactly the same as @code{xsubstring}, but the extracted text
3567 is written into the string @var{target} starting at index
3568 @var{tstart}. The operation is not defined if @code{(eq?
3569 @var{target} @var{s})} or these arguments share storage -- you
3570 cannot copy a string on top of itself.
3571 @end deffn
3572
3573 @deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3574 @deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3575 Return the string @var{s1}, but with the characters
3576 @var{start1} @dots{} @var{end1} replaced by the characters
3577 @var{start2} @dots{} @var{end2} from @var{s2}.
3578 @end deffn
3579
3580 @deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3581 @deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3582 Split the string @var{s} into a list of substrings, where each
3583 substring is a maximal non-empty contiguous sequence of
3584 characters from the character set @var{token_set}, which
3585 defaults to @code{char-set:graphic}.
3586 If @var{start} or @var{end} indices are provided, they restrict
3587 @code{string-tokenize} to operating on the indicated substring
3588 of @var{s}.
3589 @end deffn
3590
3591 @deffn {Scheme Procedure} string-filter s char_pred [start [end]]
3592 @deffnx {C Function} scm_string_filter (s, char_pred, start, end)
3593 Filter the string @var{s}, retaining only those characters which
3594 satisfy @var{char_pred}.
3595
3596 If @var{char_pred} is a procedure, it is applied to each character as
3597 a predicate, if it is a character, it is tested for equality and if it
3598 is a character set, it is tested for membership.
3599 @end deffn
3600
3601 @deffn {Scheme Procedure} string-delete s char_pred [start [end]]
3602 @deffnx {C Function} scm_string_delete (s, char_pred, start, end)
3603 Delete characters satisfying @var{char_pred} from @var{s}.
3604
3605 If @var{char_pred} is a procedure, it is applied to each character as
3606 a predicate, if it is a character, it is tested for equality and if it
3607 is a character set, it is tested for membership.
3608 @end deffn
3609
3610 @node Conversion to/from C
3611 @subsubsection Conversion to/from C
3612
3613 When creating a Scheme string from a C string or when converting a
3614 Scheme string to a C string, the concept of character encoding becomes
3615 important.
3616
3617 In C, a string is just a sequence of bytes, and the character encoding
3618 describes the relation between these bytes and the actual characters
3619 that make up the string. For Scheme strings, character encoding is
3620 not an issue (most of the time), since in Scheme you never get to see
3621 the bytes, only the characters.
3622
3623 Well, ideally, anyway. Right now, Guile simply equates Scheme
3624 characters and bytes, ignoring the possibility of multi-byte encodings
3625 completely. This will change in the future, where Guile will use
3626 Unicode codepoints as its characters and UTF-8 or some other encoding
3627 as its internal encoding. When you exclusively use the functions
3628 listed in this section, you are `future-proof'.
3629
3630 Converting a Scheme string to a C string will often allocate fresh
3631 memory to hold the result. You must take care that this memory is
3632 properly freed eventually. In many cases, this can be achieved by
3633 using @code{scm_dynwind_free} inside an appropriate dynwind context,
3634 @xref{Dynamic Wind}.
3635
3636 @deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3637 @deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3638 Creates a new Scheme string that has the same contents as @var{str}
3639 when interpreted in the current locale character encoding.
3640
3641 For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3642
3643 For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3644 @var{str} in bytes, and @var{str} does not need to be null-terminated.
3645 If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3646 null-terminated and the real length will be found with @code{strlen}.
3647 @end deftypefn
3648
3649 @deftypefn {C Function} SCM scm_take_locale_string (char *str)
3650 @deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3651 Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3652 respectively, but also frees @var{str} with @code{free} eventually.
3653 Thus, you can use this function when you would free @var{str} anyway
3654 immediately after creating the Scheme string. In certain cases, Guile
3655 can then use @var{str} directly as its internal representation.
3656 @end deftypefn
3657
3658 @deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3659 @deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
3660 Returns a C string in the current locale encoding with the same
3661 contents as @var{str}. The C string must be freed with @code{free}
3662 eventually, maybe by using @code{scm_dynwind_free}, @xref{Dynamic
3663 Wind}.
3664
3665 For @code{scm_to_locale_string}, the returned string is
3666 null-terminated and an error is signalled when @var{str} contains
3667 @code{#\nul} characters.
3668
3669 For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3670 @var{str} might contain @code{#\nul} characters and the length of the
3671 returned string in bytes is stored in @code{*@var{lenp}}. The
3672 returned string will not be null-terminated in this case. If
3673 @var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3674 @code{scm_to_locale_string}.
3675 @end deftypefn
3676
3677 @deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3678 Puts @var{str} as a C string in the current locale encoding into the
3679 memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3680 @var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3681 more than that. No terminating @code{'\0'} will be stored.
3682
3683 The return value of @code{scm_to_locale_stringbuf} is the number of
3684 bytes that are needed for all of @var{str}, regardless of whether
3685 @var{buf} was large enough to hold them. Thus, when the return value
3686 is larger than @var{max_len}, only @var{max_len} bytes have been
3687 stored and you probably need to try again with a larger buffer.
3688 @end deftypefn
3689
3690 @node Regular Expressions
3691 @subsection Regular Expressions
3692 @tpindex Regular expressions
3693
3694 @cindex regular expressions
3695 @cindex regex
3696 @cindex emacs regexp
3697
3698 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
3699 describes a whole class of strings. A full description of regular
3700 expressions and their syntax is beyond the scope of this manual;
3701 an introduction can be found in the Emacs manual (@pxref{Regexps,
3702 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
3703 in many general Unix reference books.
3704
3705 If your system does not include a POSIX regular expression library,
3706 and you have not linked Guile with a third-party regexp library such
3707 as Rx, these functions will not be available. You can tell whether
3708 your Guile installation includes regular expression support by
3709 checking whether @code{(provided? 'regex)} returns true.
3710
3711 The following regexp and string matching features are provided by the
3712 @code{(ice-9 regex)} module. Before using the described functions,
3713 you should load this module by executing @code{(use-modules (ice-9
3714 regex))}.
3715
3716 @menu
3717 * Regexp Functions:: Functions that create and match regexps.
3718 * Match Structures:: Finding what was matched by a regexp.
3719 * Backslash Escapes:: Removing the special meaning of regexp
3720 meta-characters.
3721 @end menu
3722
3723
3724 @node Regexp Functions
3725 @subsubsection Regexp Functions
3726
3727 By default, Guile supports POSIX extended regular expressions.
3728 That means that the characters @samp{(}, @samp{)}, @samp{+} and
3729 @samp{?} are special, and must be escaped if you wish to match the
3730 literal characters.
3731
3732 This regular expression interface was modeled after that
3733 implemented by SCSH, the Scheme Shell. It is intended to be
3734 upwardly compatible with SCSH regular expressions.
3735
3736 Zero bytes (@code{#\nul}) cannot be used in regex patterns or input
3737 strings, since the underlying C functions treat that as the end of
3738 string. If there's a zero byte an error is thrown.
3739
3740 Patterns and input strings are treated as being in the locale
3741 character set if @code{setlocale} has been called (@pxref{Locales}),
3742 and in a multibyte locale this includes treating multi-byte sequences
3743 as a single character. (Guile strings are currently merely bytes,
3744 though this may change in the future, @xref{Conversion to/from C}.)
3745
3746 @deffn {Scheme Procedure} string-match pattern str [start]
3747 Compile the string @var{pattern} into a regular expression and compare
3748 it with @var{str}. The optional numeric argument @var{start} specifies
3749 the position of @var{str} at which to begin matching.
3750
3751 @code{string-match} returns a @dfn{match structure} which
3752 describes what, if anything, was matched by the regular
3753 expression. @xref{Match Structures}. If @var{str} does not match
3754 @var{pattern} at all, @code{string-match} returns @code{#f}.
3755 @end deffn
3756
3757 Two examples of a match follow. In the first example, the pattern
3758 matches the four digits in the match string. In the second, the pattern
3759 matches nothing.
3760
3761 @example
3762 (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
3763 @result{} #("blah2002" (4 . 8))
3764
3765 (string-match "[A-Za-z]" "123456")
3766 @result{} #f
3767 @end example
3768
3769 Each time @code{string-match} is called, it must compile its
3770 @var{pattern} argument into a regular expression structure. This
3771 operation is expensive, which makes @code{string-match} inefficient if
3772 the same regular expression is used several times (for example, in a
3773 loop). For better performance, you can compile a regular expression in
3774 advance and then match strings against the compiled regexp.
3775
3776 @deffn {Scheme Procedure} make-regexp pat flag@dots{}
3777 @deffnx {C Function} scm_make_regexp (pat, flaglst)
3778 Compile the regular expression described by @var{pat}, and
3779 return the compiled regexp structure. If @var{pat} does not
3780 describe a legal regular expression, @code{make-regexp} throws
3781 a @code{regular-expression-syntax} error.
3782
3783 The @var{flag} arguments change the behavior of the compiled
3784 regular expression. The following values may be supplied:
3785
3786 @defvar regexp/icase
3787 Consider uppercase and lowercase letters to be the same when
3788 matching.
3789 @end defvar
3790
3791 @defvar regexp/newline
3792 If a newline appears in the target string, then permit the
3793 @samp{^} and @samp{$} operators to match immediately after or
3794 immediately before the newline, respectively. Also, the
3795 @samp{.} and @samp{[^...]} operators will never match a newline
3796 character. The intent of this flag is to treat the target
3797 string as a buffer containing many lines of text, and the
3798 regular expression as a pattern that may match a single one of
3799 those lines.
3800 @end defvar
3801
3802 @defvar regexp/basic
3803 Compile a basic (``obsolete'') regexp instead of the extended
3804 (``modern'') regexps that are the default. Basic regexps do
3805 not consider @samp{|}, @samp{+} or @samp{?} to be special
3806 characters, and require the @samp{@{...@}} and @samp{(...)}
3807 metacharacters to be backslash-escaped (@pxref{Backslash
3808 Escapes}). There are several other differences between basic
3809 and extended regular expressions, but these are the most
3810 significant.
3811 @end defvar
3812
3813 @defvar regexp/extended
3814 Compile an extended regular expression rather than a basic
3815 regexp. This is the default behavior; this flag will not
3816 usually be needed. If a call to @code{make-regexp} includes
3817 both @code{regexp/basic} and @code{regexp/extended} flags, the
3818 one which comes last will override the earlier one.
3819 @end defvar
3820 @end deffn
3821
3822 @deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
3823 @deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
3824 Match the compiled regular expression @var{rx} against
3825 @code{str}. If the optional integer @var{start} argument is
3826 provided, begin matching from that position in the string.
3827 Return a match structure describing the results of the match,
3828 or @code{#f} if no match could be found.
3829
3830 The @var{flags} argument changes the matching behavior. The following
3831 flag values may be supplied, use @code{logior} (@pxref{Bitwise
3832 Operations}) to combine them,
3833
3834 @defvar regexp/notbol
3835 Consider that the @var{start} offset into @var{str} is not the
3836 beginning of a line and should not match operator @samp{^}.
3837
3838 If @var{rx} was created with the @code{regexp/newline} option above,
3839 @samp{^} will still match after a newline in @var{str}.
3840 @end defvar
3841
3842 @defvar regexp/noteol
3843 Consider that the end of @var{str} is not the end of a line and should
3844 not match operator @samp{$}.
3845
3846 If @var{rx} was created with the @code{regexp/newline} option above,
3847 @samp{$} will still match before a newline in @var{str}.
3848 @end defvar
3849 @end deffn
3850
3851 @lisp
3852 ;; Regexp to match uppercase letters
3853 (define r (make-regexp "[A-Z]*"))
3854
3855 ;; Regexp to match letters, ignoring case
3856 (define ri (make-regexp "[A-Z]*" regexp/icase))
3857
3858 ;; Search for bob using regexp r
3859 (match:substring (regexp-exec r "bob"))
3860 @result{} "" ; no match
3861
3862 ;; Search for bob using regexp ri
3863 (match:substring (regexp-exec ri "Bob"))
3864 @result{} "Bob" ; matched case insensitive
3865 @end lisp
3866
3867 @deffn {Scheme Procedure} regexp? obj
3868 @deffnx {C Function} scm_regexp_p (obj)
3869 Return @code{#t} if @var{obj} is a compiled regular expression,
3870 or @code{#f} otherwise.
3871 @end deffn
3872
3873 @sp 1
3874 @deffn {Scheme Procedure} list-matches regexp str [flags]
3875 Return a list of match structures which are the non-overlapping
3876 matches of @var{regexp} in @var{str}. @var{regexp} can be either a
3877 pattern string or a compiled regexp. The @var{flags} argument is as
3878 per @code{regexp-exec} above.
3879
3880 @example
3881 (map match:substring (list-matches "[a-z]+" "abc 42 def 78"))
3882 @result{} ("abc" "def")
3883 @end example
3884 @end deffn
3885
3886 @deffn {Scheme Procedure} fold-matches regexp str init proc [flags]
3887 Apply @var{proc} to the non-overlapping matches of @var{regexp} in
3888 @var{str}, to build a result. @var{regexp} can be either a pattern
3889 string or a compiled regexp. The @var{flags} argument is as per
3890 @code{regexp-exec} above.
3891
3892 @var{proc} is called as @code{(@var{proc} match prev)} where
3893 @var{match} is a match structure and @var{prev} is the previous return
3894 from @var{proc}. For the first call @var{prev} is the given
3895 @var{init} parameter. @code{fold-matches} returns the final value
3896 from @var{proc}.
3897
3898 For example to count matches,
3899
3900 @example
3901 (fold-matches "[a-z][0-9]" "abc x1 def y2" 0
3902 (lambda (match count)
3903 (1+ count)))
3904 @result{} 2
3905 @end example
3906 @end deffn
3907
3908 @sp 1
3909 Regular expressions are commonly used to find patterns in one string
3910 and replace them with the contents of another string. The following
3911 functions are convenient ways to do this.
3912
3913 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
3914 @deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
3915 Write to @var{port} selected parts of the match structure @var{match}.
3916 Or if @var{port} is @code{#f} then form a string from those parts and
3917 return that.
3918
3919 Each @var{item} specifies a part to be written, and may be one of the
3920 following,
3921
3922 @itemize @bullet
3923 @item
3924 A string. String arguments are written out verbatim.
3925
3926 @item
3927 An integer. The submatch with that number is written
3928 (@code{match:substring}). Zero is the entire match.
3929
3930 @item
3931 The symbol @samp{pre}. The portion of the matched string preceding
3932 the regexp match is written (@code{match:prefix}).
3933
3934 @item
3935 The symbol @samp{post}. The portion of the matched string following
3936 the regexp match is written (@code{match:suffix}).
3937 @end itemize
3938
3939 For example, changing a match and retaining the text before and after,
3940
3941 @example
3942 (regexp-substitute #f (string-match "[0-9]+" "number 25 is good")
3943 'pre "37" 'post)
3944 @result{} "number 37 is good"
3945 @end example
3946
3947 Or matching a @sc{yyyymmdd} format date such as @samp{20020828} and
3948 re-ordering and hyphenating the fields.
3949
3950 @lisp
3951 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
3952 (define s "Date 20020429 12am.")
3953 (regexp-substitute #f (string-match date-regex s)
3954 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
3955 @result{} "Date 04-29-2002 12am. (20020429)"
3956 @end lisp
3957 @end deffn
3958
3959
3960 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
3961 @deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
3962 @cindex search and replace
3963 Write to @var{port} selected parts of matches of @var{regexp} in
3964 @var{target}. If @var{port} is @code{#f} then form a string from
3965 those parts and return that. @var{regexp} can be a string or a
3966 compiled regex.
3967
3968 This is similar to @code{regexp-substitute}, but allows global
3969 substitutions on @var{target}. Each @var{item} behaves as per
3970 @code{regexp-substitute}, with the following differences,
3971
3972 @itemize @bullet
3973 @item
3974 A function. Called as @code{(@var{item} match)} with the match
3975 structure for the @var{regexp} match, it should return a string to be
3976 written to @var{port}.
3977
3978 @item
3979 The symbol @samp{post}. This doesn't output anything, but instead
3980 causes @code{regexp-substitute/global} to recurse on the unmatched
3981 portion of @var{target}.
3982
3983 This @emph{must} be supplied to perform a global search and replace on
3984 @var{target}; without it @code{regexp-substitute/global} returns after
3985 a single match and output.
3986 @end itemize
3987
3988 For example, to collapse runs of tabs and spaces to a single hyphen
3989 each,
3990
3991 @example
3992 (regexp-substitute/global #f "[ \t]+" "this is the text"
3993 'pre "-" 'post)
3994 @result{} "this-is-the-text"
3995 @end example
3996
3997 Or using a function to reverse the letters in each word,
3998
3999 @example
4000 (regexp-substitute/global #f "[a-z]+" "to do and not-do"
4001 'pre (lambda (m) (string-reverse (match:substring m))) 'post)
4002 @result{} "ot od dna ton-od"
4003 @end example
4004
4005 Without the @code{post} symbol, just one regexp match is made. For
4006 example the following is the date example from
4007 @code{regexp-substitute} above, without the need for the separate
4008 @code{string-match} call.
4009
4010 @lisp
4011 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
4012 (define s "Date 20020429 12am.")
4013 (regexp-substitute/global #f date-regex s
4014 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
4015
4016 @result{} "Date 04-29-2002 12am. (20020429)"
4017 @end lisp
4018 @end deffn
4019
4020
4021 @node Match Structures
4022 @subsubsection Match Structures
4023
4024 @cindex match structures
4025
4026 A @dfn{match structure} is the object returned by @code{string-match} and
4027 @code{regexp-exec}. It describes which portion of a string, if any,
4028 matched the given regular expression. Match structures include: a
4029 reference to the string that was checked for matches; the starting and
4030 ending positions of the regexp match; and, if the regexp included any
4031 parenthesized subexpressions, the starting and ending positions of each
4032 submatch.
4033
4034 In each of the regexp match functions described below, the @code{match}
4035 argument must be a match structure returned by a previous call to
4036 @code{string-match} or @code{regexp-exec}. Most of these functions
4037 return some information about the original target string that was
4038 matched against a regular expression; we will call that string
4039 @var{target} for easy reference.
4040
4041 @c begin (scm-doc-string "regex.scm" "regexp-match?")
4042 @deffn {Scheme Procedure} regexp-match? obj
4043 Return @code{#t} if @var{obj} is a match structure returned by a
4044 previous call to @code{regexp-exec}, or @code{#f} otherwise.
4045 @end deffn
4046
4047 @c begin (scm-doc-string "regex.scm" "match:substring")
4048 @deffn {Scheme Procedure} match:substring match [n]
4049 Return the portion of @var{target} matched by subexpression number
4050 @var{n}. Submatch 0 (the default) represents the entire regexp match.
4051 If the regular expression as a whole matched, but the subexpression
4052 number @var{n} did not match, return @code{#f}.
4053 @end deffn
4054
4055 @lisp
4056 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4057 (match:substring s)
4058 @result{} "2002"
4059
4060 ;; match starting at offset 6 in the string
4061 (match:substring
4062 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
4063 @result{} "7654"
4064 @end lisp
4065
4066 @c begin (scm-doc-string "regex.scm" "match:start")
4067 @deffn {Scheme Procedure} match:start match [n]
4068 Return the starting position of submatch number @var{n}.
4069 @end deffn
4070
4071 In the following example, the result is 4, since the match starts at
4072 character index 4:
4073
4074 @lisp
4075 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4076 (match:start s)
4077 @result{} 4
4078 @end lisp
4079
4080 @c begin (scm-doc-string "regex.scm" "match:end")
4081 @deffn {Scheme Procedure} match:end match [n]
4082 Return the ending position of submatch number @var{n}.
4083 @end deffn
4084
4085 In the following example, the result is 8, since the match runs between
4086 characters 4 and 8 (i.e. the ``2002'').
4087
4088 @lisp
4089 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4090 (match:end s)
4091 @result{} 8
4092 @end lisp
4093
4094 @c begin (scm-doc-string "regex.scm" "match:prefix")
4095 @deffn {Scheme Procedure} match:prefix match
4096 Return the unmatched portion of @var{target} preceding the regexp match.
4097
4098 @lisp
4099 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4100 (match:prefix s)
4101 @result{} "blah"
4102 @end lisp
4103 @end deffn
4104
4105 @c begin (scm-doc-string "regex.scm" "match:suffix")
4106 @deffn {Scheme Procedure} match:suffix match
4107 Return the unmatched portion of @var{target} following the regexp match.
4108 @end deffn
4109
4110 @lisp
4111 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4112 (match:suffix s)
4113 @result{} "foo"
4114 @end lisp
4115
4116 @c begin (scm-doc-string "regex.scm" "match:count")
4117 @deffn {Scheme Procedure} match:count match
4118 Return the number of parenthesized subexpressions from @var{match}.
4119 Note that the entire regular expression match itself counts as a
4120 subexpression, and failed submatches are included in the count.
4121 @end deffn
4122
4123 @c begin (scm-doc-string "regex.scm" "match:string")
4124 @deffn {Scheme Procedure} match:string match
4125 Return the original @var{target} string.
4126 @end deffn
4127
4128 @lisp
4129 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4130 (match:string s)
4131 @result{} "blah2002foo"
4132 @end lisp
4133
4134
4135 @node Backslash Escapes
4136 @subsubsection Backslash Escapes
4137
4138 Sometimes you will want a regexp to match characters like @samp{*} or
4139 @samp{$} exactly. For example, to check whether a particular string
4140 represents a menu entry from an Info node, it would be useful to match
4141 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
4142 because the asterisk is a metacharacter, it won't match the @samp{*} at
4143 the beginning of the string. In this case, we want to make the first
4144 asterisk un-magic.
4145
4146 You can do this by preceding the metacharacter with a backslash
4147 character @samp{\}. (This is also called @dfn{quoting} the
4148 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
4149 sees a backslash in a regular expression, it considers the following
4150 glyph to be an ordinary character, no matter what special meaning it
4151 would ordinarily have. Therefore, we can make the above example work by
4152 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
4153 the regular expression engine to match only a single asterisk in the
4154 target string.
4155
4156 Since the backslash is itself a metacharacter, you may force a regexp to
4157 match a backslash in the target string by preceding the backslash with
4158 itself. For example, to find variable references in a @TeX{} program,
4159 you might want to find occurrences of the string @samp{\let\} followed
4160 by any number of alphabetic characters. The regular expression
4161 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
4162 regexp each match a single backslash in the target string.
4163
4164 @c begin (scm-doc-string "regex.scm" "regexp-quote")
4165 @deffn {Scheme Procedure} regexp-quote str
4166 Quote each special character found in @var{str} with a backslash, and
4167 return the resulting string.
4168 @end deffn
4169
4170 @strong{Very important:} Using backslash escapes in Guile source code
4171 (as in Emacs Lisp or C) can be tricky, because the backslash character
4172 has special meaning for the Guile reader. For example, if Guile
4173 encounters the character sequence @samp{\n} in the middle of a string
4174 while processing Scheme code, it replaces those characters with a
4175 newline character. Similarly, the character sequence @samp{\t} is
4176 replaced by a horizontal tab. Several of these @dfn{escape sequences}
4177 are processed by the Guile reader before your code is executed.
4178 Unrecognized escape sequences are ignored: if the characters @samp{\*}
4179 appear in a string, they will be translated to the single character
4180 @samp{*}.
4181
4182 This translation is obviously undesirable for regular expressions, since
4183 we want to be able to include backslashes in a string in order to
4184 escape regexp metacharacters. Therefore, to make sure that a backslash
4185 is preserved in a string in your Guile program, you must use @emph{two}
4186 consecutive backslashes:
4187
4188 @lisp
4189 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
4190 @end lisp
4191
4192 The string in this example is preprocessed by the Guile reader before
4193 any code is executed. The resulting argument to @code{make-regexp} is
4194 the string @samp{^\* [^:]*}, which is what we really want.
4195
4196 This also means that in order to write a regular expression that matches
4197 a single backslash character, the regular expression string in the
4198 source code must include @emph{four} backslashes. Each consecutive pair
4199 of backslashes gets translated by the Guile reader to a single
4200 backslash, and the resulting double-backslash is interpreted by the
4201 regexp engine as matching a single backslash character. Hence:
4202
4203 @lisp
4204 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
4205 @end lisp
4206
4207 The reason for the unwieldiness of this syntax is historical. Both
4208 regular expression pattern matchers and Unix string processing systems
4209 have traditionally used backslashes with the special meanings
4210 described above. The POSIX regular expression specification and ANSI C
4211 standard both require these semantics. Attempting to abandon either
4212 convention would cause other kinds of compatibility problems, possibly
4213 more severe ones. Therefore, without extending the Scheme reader to
4214 support strings with different quoting conventions (an ungainly and
4215 confusing extension when implemented in other languages), we must adhere
4216 to this cumbersome escape syntax.
4217
4218
4219 @node Symbols
4220 @subsection Symbols
4221 @tpindex Symbols
4222
4223 Symbols in Scheme are widely used in three ways: as items of discrete
4224 data, as lookup keys for alists and hash tables, and to denote variable
4225 references.
4226
4227 A @dfn{symbol} is similar to a string in that it is defined by a
4228 sequence of characters. The sequence of characters is known as the
4229 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
4230 name doesn't include any characters that could be confused with other
4231 elements of Scheme syntax --- a symbol is written in a Scheme program by
4232 writing the sequence of characters that make up the name, @emph{without}
4233 any quotation marks or other special syntax. For example, the symbol
4234 whose name is ``multiply-by-2'' is written, simply:
4235
4236 @lisp
4237 multiply-by-2
4238 @end lisp
4239
4240 Notice how this differs from a @emph{string} with contents
4241 ``multiply-by-2'', which is written with double quotation marks, like
4242 this:
4243
4244 @lisp
4245 "multiply-by-2"
4246 @end lisp
4247
4248 Looking beyond how they are written, symbols are different from strings
4249 in two important respects.
4250
4251 The first important difference is uniqueness. If the same-looking
4252 string is read twice from two different places in a program, the result
4253 is two @emph{different} string objects whose contents just happen to be
4254 the same. If, on the other hand, the same-looking symbol is read twice
4255 from two different places in a program, the result is the @emph{same}
4256 symbol object both times.
4257
4258 Given two read symbols, you can use @code{eq?} to test whether they are
4259 the same (that is, have the same name). @code{eq?} is the most
4260 efficient comparison operator in Scheme, and comparing two symbols like
4261 this is as fast as comparing, for example, two numbers. Given two
4262 strings, on the other hand, you must use @code{equal?} or
4263 @code{string=?}, which are much slower comparison operators, to
4264 determine whether the strings have the same contents.
4265
4266 @lisp
4267 (define sym1 (quote hello))
4268 (define sym2 (quote hello))
4269 (eq? sym1 sym2) @result{} #t
4270
4271 (define str1 "hello")
4272 (define str2 "hello")
4273 (eq? str1 str2) @result{} #f
4274 (equal? str1 str2) @result{} #t
4275 @end lisp
4276
4277 The second important difference is that symbols, unlike strings, are not
4278 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
4279 example above: @code{(quote hello)} evaluates to the symbol named
4280 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
4281 symbol named "hello" and evaluated as a variable reference @dots{} about
4282 which more below (@pxref{Symbol Variables}).
4283
4284 @menu
4285 * Symbol Data:: Symbols as discrete data.
4286 * Symbol Keys:: Symbols as lookup keys.
4287 * Symbol Variables:: Symbols as denoting variables.
4288 * Symbol Primitives:: Operations related to symbols.
4289 * Symbol Props:: Function slots and property lists.
4290 * Symbol Read Syntax:: Extended read syntax for symbols.
4291 * Symbol Uninterned:: Uninterned symbols.
4292 @end menu
4293
4294
4295 @node Symbol Data
4296 @subsubsection Symbols as Discrete Data
4297
4298 Numbers and symbols are similar to the extent that they both lend
4299 themselves to @code{eq?} comparison. But symbols are more descriptive
4300 than numbers, because a symbol's name can be used directly to describe
4301 the concept for which that symbol stands.
4302
4303 For example, imagine that you need to represent some colours in a
4304 computer program. Using numbers, you would have to choose arbitrarily
4305 some mapping between numbers and colours, and then take care to use that
4306 mapping consistently:
4307
4308 @lisp
4309 ;; 1=red, 2=green, 3=purple
4310
4311 (if (eq? (colour-of car) 1)
4312 ...)
4313 @end lisp
4314
4315 @noindent
4316 You can make the mapping more explicit and the code more readable by
4317 defining constants:
4318
4319 @lisp
4320 (define red 1)
4321 (define green 2)
4322 (define purple 3)
4323
4324 (if (eq? (colour-of car) red)
4325 ...)
4326 @end lisp
4327
4328 @noindent
4329 But the simplest and clearest approach is not to use numbers at all, but
4330 symbols whose names specify the colours that they refer to:
4331
4332 @lisp
4333 (if (eq? (colour-of car) 'red)
4334 ...)
4335 @end lisp
4336
4337 The descriptive advantages of symbols over numbers increase as the set
4338 of concepts that you want to describe grows. Suppose that a car object
4339 can have other properties as well, such as whether it has or uses:
4340
4341 @itemize @bullet
4342 @item
4343 automatic or manual transmission
4344 @item
4345 leaded or unleaded fuel
4346 @item
4347 power steering (or not).
4348 @end itemize
4349
4350 @noindent
4351 Then a car's combined property set could be naturally represented and
4352 manipulated as a list of symbols:
4353
4354 @lisp
4355 (properties-of car1)
4356 @result{}
4357 (red manual unleaded power-steering)
4358
4359 (if (memq 'power-steering (properties-of car1))
4360 (display "Unfit people can drive this car.\n")
4361 (display "You'll need strong arms to drive this car!\n"))
4362 @print{}
4363 Unfit people can drive this car.
4364 @end lisp
4365
4366 Remember, the fundamental property of symbols that we are relying on
4367 here is that an occurrence of @code{'red} in one part of a program is an
4368 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
4369 another part of a program; this means that symbols can usefully be
4370 compared using @code{eq?}. At the same time, symbols have naturally
4371 descriptive names. This combination of efficiency and descriptive power
4372 makes them ideal for use as discrete data.
4373
4374
4375 @node Symbol Keys
4376 @subsubsection Symbols as Lookup Keys
4377
4378 Given their efficiency and descriptive power, it is natural to use
4379 symbols as the keys in an association list or hash table.
4380
4381 To illustrate this, consider a more structured representation of the car
4382 properties example from the preceding subsection. Rather than
4383 mixing all the properties up together in a flat list, we could use an
4384 association list like this:
4385
4386 @lisp
4387 (define car1-properties '((colour . red)
4388 (transmission . manual)
4389 (fuel . unleaded)
4390 (steering . power-assisted)))
4391 @end lisp
4392
4393 Notice how this structure is more explicit and extensible than the flat
4394 list. For example it makes clear that @code{manual} refers to the
4395 transmission rather than, say, the windows or the locking of the car.
4396 It also allows further properties to use the same symbols among their
4397 possible values without becoming ambiguous:
4398
4399 @lisp
4400 (define car1-properties '((colour . red)
4401 (transmission . manual)
4402 (fuel . unleaded)
4403 (steering . power-assisted)
4404 (seat-colour . red)
4405 (locking . manual)))
4406 @end lisp
4407
4408 With a representation like this, it is easy to use the efficient
4409 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
4410 extract or change individual pieces of information:
4411
4412 @lisp
4413 (assq-ref car1-properties 'fuel) @result{} unleaded
4414 (assq-ref car1-properties 'transmission) @result{} manual
4415
4416 (assq-set! car1-properties 'seat-colour 'black)
4417 @result{}
4418 ((colour . red)
4419 (transmission . manual)
4420 (fuel . unleaded)
4421 (steering . power-assisted)
4422 (seat-colour . black)
4423 (locking . manual)))
4424 @end lisp
4425
4426 Hash tables also have keys, and exactly the same arguments apply to the
4427 use of symbols in hash tables as in association lists. The hash value
4428 that Guile uses to decide where to add a symbol-keyed entry to a hash
4429 table can be obtained by calling the @code{symbol-hash} procedure:
4430
4431 @deffn {Scheme Procedure} symbol-hash symbol
4432 @deffnx {C Function} scm_symbol_hash (symbol)
4433 Return a hash value for @var{symbol}.
4434 @end deffn
4435
4436 See @ref{Hash Tables} for information about hash tables in general, and
4437 for why you might choose to use a hash table rather than an association
4438 list.
4439
4440
4441 @node Symbol Variables
4442 @subsubsection Symbols as Denoting Variables
4443
4444 When an unquoted symbol in a Scheme program is evaluated, it is
4445 interpreted as a variable reference, and the result of the evaluation is
4446 the appropriate variable's value.
4447
4448 For example, when the expression @code{(string-length "abcd")} is read
4449 and evaluated, the sequence of characters @code{string-length} is read
4450 as the symbol whose name is "string-length". This symbol is associated
4451 with a variable whose value is the procedure that implements string
4452 length calculation. Therefore evaluation of the @code{string-length}
4453 symbol results in that procedure.
4454
4455 The details of the connection between an unquoted symbol and the
4456 variable to which it refers are explained elsewhere. See @ref{Binding
4457 Constructs}, for how associations between symbols and variables are
4458 created, and @ref{Modules}, for how those associations are affected by
4459 Guile's module system.
4460
4461
4462 @node Symbol Primitives
4463 @subsubsection Operations Related to Symbols
4464
4465 Given any Scheme value, you can determine whether it is a symbol using
4466 the @code{symbol?} primitive:
4467
4468 @rnindex symbol?
4469 @deffn {Scheme Procedure} symbol? obj
4470 @deffnx {C Function} scm_symbol_p (obj)
4471 Return @code{#t} if @var{obj} is a symbol, otherwise return
4472 @code{#f}.
4473 @end deffn
4474
4475 @deftypefn {C Function} int scm_is_symbol (SCM val)
4476 Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
4477 @end deftypefn
4478
4479 Once you know that you have a symbol, you can obtain its name as a
4480 string by calling @code{symbol->string}. Note that Guile differs by
4481 default from R5RS on the details of @code{symbol->string} as regards
4482 case-sensitivity:
4483
4484 @rnindex symbol->string
4485 @deffn {Scheme Procedure} symbol->string s
4486 @deffnx {C Function} scm_symbol_to_string (s)
4487 Return the name of symbol @var{s} as a string. By default, Guile reads
4488 symbols case-sensitively, so the string returned will have the same case
4489 variation as the sequence of characters that caused @var{s} to be
4490 created.
4491
4492 If Guile is set to read symbols case-insensitively (as specified by
4493 R5RS), and @var{s} comes into being as part of a literal expression
4494 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
4495 by a call to the @code{read} or @code{string-ci->symbol} procedures,
4496 Guile converts any alphabetic characters in the symbol's name to
4497 lower case before creating the symbol object, so the string returned
4498 here will be in lower case.
4499
4500 If @var{s} was created by @code{string->symbol}, the case of characters
4501 in the string returned will be the same as that in the string that was
4502 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
4503 setting at the time @var{s} was created.
4504
4505 It is an error to apply mutation procedures like @code{string-set!} to
4506 strings returned by this procedure.
4507 @end deffn
4508
4509 Most symbols are created by writing them literally in code. However it
4510 is also possible to create symbols programmatically using the following
4511 @code{string->symbol} and @code{string-ci->symbol} procedures:
4512
4513 @rnindex string->symbol
4514 @deffn {Scheme Procedure} string->symbol string
4515 @deffnx {C Function} scm_string_to_symbol (string)
4516 Return the symbol whose name is @var{string}. This procedure can create
4517 symbols with names containing special characters or letters in the
4518 non-standard case, but it is usually a bad idea to create such symbols
4519 because in some implementations of Scheme they cannot be read as
4520 themselves.
4521 @end deffn
4522
4523 @deffn {Scheme Procedure} string-ci->symbol str
4524 @deffnx {C Function} scm_string_ci_to_symbol (str)
4525 Return the symbol whose name is @var{str}. If Guile is currently
4526 reading symbols case-insensitively, @var{str} is converted to lowercase
4527 before the returned symbol is looked up or created.
4528 @end deffn
4529
4530 The following examples illustrate Guile's detailed behaviour as regards
4531 the case-sensitivity of symbols:
4532
4533 @lisp
4534 (read-enable 'case-insensitive) ; R5RS compliant behaviour
4535
4536 (symbol->string 'flying-fish) @result{} "flying-fish"
4537 (symbol->string 'Martin) @result{} "martin"
4538 (symbol->string
4539 (string->symbol "Malvina")) @result{} "Malvina"
4540
4541 (eq? 'mISSISSIppi 'mississippi) @result{} #t
4542 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4543 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
4544 (eq? 'LolliPop
4545 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4546 (string=? "K. Harper, M.D."
4547 (symbol->string
4548 (string->symbol "K. Harper, M.D."))) @result{} #t
4549
4550 (read-disable 'case-insensitive) ; Guile default behaviour
4551
4552 (symbol->string 'flying-fish) @result{} "flying-fish"
4553 (symbol->string 'Martin) @result{} "Martin"
4554 (symbol->string
4555 (string->symbol "Malvina")) @result{} "Malvina"
4556
4557 (eq? 'mISSISSIppi 'mississippi) @result{} #f
4558 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4559 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
4560 (eq? 'LolliPop
4561 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4562 (string=? "K. Harper, M.D."
4563 (symbol->string
4564 (string->symbol "K. Harper, M.D."))) @result{} #t
4565 @end lisp
4566
4567 From C, there are lower level functions that construct a Scheme symbol
4568 from a C string in the current locale encoding.
4569
4570 When you want to do more from C, you should convert between symbols
4571 and strings using @code{scm_symbol_to_string} and
4572 @code{scm_string_to_symbol} and work with the strings.
4573
4574 @deffn {C Function} scm_from_locale_symbol (const char *name)
4575 @deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
4576 Construct and return a Scheme symbol whose name is specified by
4577 @var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
4578 terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
4579 specified explicitly by @var{len}.
4580 @end deffn
4581
4582 @deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
4583 @deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
4584 Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
4585 respectively, but also frees @var{str} with @code{free} eventually.
4586 Thus, you can use this function when you would free @var{str} anyway
4587 immediately after creating the Scheme string. In certain cases, Guile
4588 can then use @var{str} directly as its internal representation.
4589 @end deftypefn
4590
4591
4592 Finally, some applications, especially those that generate new Scheme
4593 code dynamically, need to generate symbols for use in the generated
4594 code. The @code{gensym} primitive meets this need:
4595
4596 @deffn {Scheme Procedure} gensym [prefix]
4597 @deffnx {C Function} scm_gensym (prefix)
4598 Create a new symbol with a name constructed from a prefix and a counter
4599 value. The string @var{prefix} can be specified as an optional
4600 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
4601 at each call. There is no provision for resetting the counter.
4602 @end deffn
4603
4604 The symbols generated by @code{gensym} are @emph{likely} to be unique,
4605 since their names begin with a space and it is only otherwise possible
4606 to generate such symbols if a programmer goes out of their way to do
4607 so. Uniqueness can be guaranteed by instead using uninterned symbols
4608 (@pxref{Symbol Uninterned}), though they can't be usefully written out
4609 and read back in.
4610
4611
4612 @node Symbol Props
4613 @subsubsection Function Slots and Property Lists
4614
4615 In traditional Lisp dialects, symbols are often understood as having
4616 three kinds of value at once:
4617
4618 @itemize @bullet
4619 @item
4620 a @dfn{variable} value, which is used when the symbol appears in
4621 code in a variable reference context
4622
4623 @item
4624 a @dfn{function} value, which is used when the symbol appears in
4625 code in a function name position (i.e. as the first element in an
4626 unquoted list)
4627
4628 @item
4629 a @dfn{property list} value, which is used when the symbol is given as
4630 the first argument to Lisp's @code{put} or @code{get} functions.
4631 @end itemize
4632
4633 Although Scheme (as one of its simplifications with respect to Lisp)
4634 does away with the distinction between variable and function namespaces,
4635 Guile currently retains some elements of the traditional structure in
4636 case they turn out to be useful when implementing translators for other
4637 languages, in particular Emacs Lisp.
4638
4639 Specifically, Guile symbols have two extra slots. for a symbol's
4640 property list, and for its ``function value.'' The following procedures
4641 are provided to access these slots.
4642
4643 @deffn {Scheme Procedure} symbol-fref symbol
4644 @deffnx {C Function} scm_symbol_fref (symbol)
4645 Return the contents of @var{symbol}'s @dfn{function slot}.
4646 @end deffn
4647
4648 @deffn {Scheme Procedure} symbol-fset! symbol value
4649 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
4650 Set the contents of @var{symbol}'s function slot to @var{value}.
4651 @end deffn
4652
4653 @deffn {Scheme Procedure} symbol-pref symbol
4654 @deffnx {C Function} scm_symbol_pref (symbol)
4655 Return the @dfn{property list} currently associated with @var{symbol}.
4656 @end deffn
4657
4658 @deffn {Scheme Procedure} symbol-pset! symbol value
4659 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
4660 Set @var{symbol}'s property list to @var{value}.
4661 @end deffn
4662
4663 @deffn {Scheme Procedure} symbol-property sym prop
4664 From @var{sym}'s property list, return the value for property
4665 @var{prop}. The assumption is that @var{sym}'s property list is an
4666 association list whose keys are distinguished from each other using
4667 @code{equal?}; @var{prop} should be one of the keys in that list. If
4668 the property list has no entry for @var{prop}, @code{symbol-property}
4669 returns @code{#f}.
4670 @end deffn
4671
4672 @deffn {Scheme Procedure} set-symbol-property! sym prop val
4673 In @var{sym}'s property list, set the value for property @var{prop} to
4674 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
4675 none already exists. For the structure of the property list, see
4676 @code{symbol-property}.
4677 @end deffn
4678
4679 @deffn {Scheme Procedure} symbol-property-remove! sym prop
4680 From @var{sym}'s property list, remove the entry for property
4681 @var{prop}, if there is one. For the structure of the property list,
4682 see @code{symbol-property}.
4683 @end deffn
4684
4685 Support for these extra slots may be removed in a future release, and it
4686 is probably better to avoid using them. For a more modern and Schemely
4687 approach to properties, see @ref{Object Properties}.
4688
4689
4690 @node Symbol Read Syntax
4691 @subsubsection Extended Read Syntax for Symbols
4692
4693 The read syntax for a symbol is a sequence of letters, digits, and
4694 @dfn{extended alphabetic characters}, beginning with a character that
4695 cannot begin a number. In addition, the special cases of @code{+},
4696 @code{-}, and @code{...} are read as symbols even though numbers can
4697 begin with @code{+}, @code{-} or @code{.}.
4698
4699 Extended alphabetic characters may be used within identifiers as if
4700 they were letters. The set of extended alphabetic characters is:
4701
4702 @example
4703 ! $ % & * + - . / : < = > ? @@ ^ _ ~
4704 @end example
4705
4706 In addition to the standard read syntax defined above (which is taken
4707 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
4708 Scheme})), Guile provides an extended symbol read syntax that allows the
4709 inclusion of unusual characters such as space characters, newlines and
4710 parentheses. If (for whatever reason) you need to write a symbol
4711 containing characters not mentioned above, you can do so as follows.
4712
4713 @itemize @bullet
4714 @item
4715 Begin the symbol with the characters @code{#@{},
4716
4717 @item
4718 write the characters of the symbol and
4719
4720 @item
4721 finish the symbol with the characters @code{@}#}.
4722 @end itemize
4723
4724 Here are a few examples of this form of read syntax. The first symbol
4725 needs to use extended syntax because it contains a space character, the
4726 second because it contains a line break, and the last because it looks
4727 like a number.
4728
4729 @lisp
4730 #@{foo bar@}#
4731
4732 #@{what
4733 ever@}#
4734
4735 #@{4242@}#
4736 @end lisp
4737
4738 Although Guile provides this extended read syntax for symbols,
4739 widespread usage of it is discouraged because it is not portable and not
4740 very readable.
4741
4742
4743 @node Symbol Uninterned
4744 @subsubsection Uninterned Symbols
4745
4746 What makes symbols useful is that they are automatically kept unique.
4747 There are no two symbols that are distinct objects but have the same
4748 name. But of course, there is no rule without exception. In addition
4749 to the normal symbols that have been discussed up to now, you can also
4750 create special @dfn{uninterned} symbols that behave slightly
4751 differently.
4752
4753 To understand what is different about them and why they might be useful,
4754 we look at how normal symbols are actually kept unique.
4755
4756 Whenever Guile wants to find the symbol with a specific name, for
4757 example during @code{read} or when executing @code{string->symbol}, it
4758 first looks into a table of all existing symbols to find out whether a
4759 symbol with the given name already exists. When this is the case, Guile
4760 just returns that symbol. When not, a new symbol with the name is
4761 created and entered into the table so that it can be found later.
4762
4763 Sometimes you might want to create a symbol that is guaranteed `fresh',
4764 i.e. a symbol that did not exist previously. You might also want to
4765 somehow guarantee that no one else will ever unintentionally stumble
4766 across your symbol in the future. These properties of a symbol are
4767 often needed when generating code during macro expansion. When
4768 introducing new temporary variables, you want to guarantee that they
4769 don't conflict with variables in other people's code.
4770
4771 The simplest way to arrange for this is to create a new symbol but
4772 not enter it into the global table of all symbols. That way, no one
4773 will ever get access to your symbol by chance. Symbols that are not in
4774 the table are called @dfn{uninterned}. Of course, symbols that
4775 @emph{are} in the table are called @dfn{interned}.
4776
4777 You create new uninterned symbols with the function @code{make-symbol}.
4778 You can test whether a symbol is interned or not with
4779 @code{symbol-interned?}.
4780
4781 Uninterned symbols break the rule that the name of a symbol uniquely
4782 identifies the symbol object. Because of this, they can not be written
4783 out and read back in like interned symbols. Currently, Guile has no
4784 support for reading uninterned symbols. Note that the function
4785 @code{gensym} does not return uninterned symbols for this reason.
4786
4787 @deffn {Scheme Procedure} make-symbol name
4788 @deffnx {C Function} scm_make_symbol (name)
4789 Return a new uninterned symbol with the name @var{name}. The returned
4790 symbol is guaranteed to be unique and future calls to
4791 @code{string->symbol} will not return it.
4792 @end deffn
4793
4794 @deffn {Scheme Procedure} symbol-interned? symbol
4795 @deffnx {C Function} scm_symbol_interned_p (symbol)
4796 Return @code{#t} if @var{symbol} is interned, otherwise return
4797 @code{#f}.
4798 @end deffn
4799
4800 For example:
4801
4802 @lisp
4803 (define foo-1 (string->symbol "foo"))
4804 (define foo-2 (string->symbol "foo"))
4805 (define foo-3 (make-symbol "foo"))
4806 (define foo-4 (make-symbol "foo"))
4807
4808 (eq? foo-1 foo-2)
4809 @result{} #t
4810 ; Two interned symbols with the same name are the same object,
4811
4812 (eq? foo-1 foo-3)
4813 @result{} #f
4814 ; but a call to make-symbol with the same name returns a
4815 ; distinct object.
4816
4817 (eq? foo-3 foo-4)
4818 @result{} #f
4819 ; A call to make-symbol always returns a new object, even for
4820 ; the same name.
4821
4822 foo-3
4823 @result{} #<uninterned-symbol foo 8085290>
4824 ; Uninterned symbols print differently from interned symbols,
4825
4826 (symbol? foo-3)
4827 @result{} #t
4828 ; but they are still symbols,
4829
4830 (symbol-interned? foo-3)
4831 @result{} #f
4832 ; just not interned.
4833 @end lisp
4834
4835
4836 @node Keywords
4837 @subsection Keywords
4838 @tpindex Keywords
4839
4840 Keywords are self-evaluating objects with a convenient read syntax that
4841 makes them easy to type.
4842
4843 Guile's keyword support conforms to R5RS, and adds a (switchable) read
4844 syntax extension to permit keywords to begin with @code{:} as well as
4845 @code{#:}.
4846
4847 @menu
4848 * Why Use Keywords?:: Motivation for keyword usage.
4849 * Coding With Keywords:: How to use keywords.
4850 * Keyword Read Syntax:: Read syntax for keywords.
4851 * Keyword Procedures:: Procedures for dealing with keywords.
4852 @end menu
4853
4854 @node Why Use Keywords?
4855 @subsubsection Why Use Keywords?
4856
4857 Keywords are useful in contexts where a program or procedure wants to be
4858 able to accept a large number of optional arguments without making its
4859 interface unmanageable.
4860
4861 To illustrate this, consider a hypothetical @code{make-window}
4862 procedure, which creates a new window on the screen for drawing into
4863 using some graphical toolkit. There are many parameters that the caller
4864 might like to specify, but which could also be sensibly defaulted, for
4865 example:
4866
4867 @itemize @bullet
4868 @item
4869 color depth -- Default: the color depth for the screen
4870
4871 @item
4872 background color -- Default: white
4873
4874 @item
4875 width -- Default: 600
4876
4877 @item
4878 height -- Default: 400
4879 @end itemize
4880
4881 If @code{make-window} did not use keywords, the caller would have to
4882 pass in a value for each possible argument, remembering the correct
4883 argument order and using a special value to indicate the default value
4884 for that argument:
4885
4886 @lisp
4887 (make-window 'default ;; Color depth
4888 'default ;; Background color
4889 800 ;; Width
4890 100 ;; Height
4891 @dots{}) ;; More make-window arguments
4892 @end lisp
4893
4894 With keywords, on the other hand, defaulted arguments are omitted, and
4895 non-default arguments are clearly tagged by the appropriate keyword. As
4896 a result, the invocation becomes much clearer:
4897
4898 @lisp
4899 (make-window #:width 800 #:height 100)
4900 @end lisp
4901
4902 On the other hand, for a simpler procedure with few arguments, the use
4903 of keywords would be a hindrance rather than a help. The primitive
4904 procedure @code{cons}, for example, would not be improved if it had to
4905 be invoked as
4906
4907 @lisp
4908 (cons #:car x #:cdr y)
4909 @end lisp
4910
4911 So the decision whether to use keywords or not is purely pragmatic: use
4912 them if they will clarify the procedure invocation at point of call.
4913
4914 @node Coding With Keywords
4915 @subsubsection Coding With Keywords
4916
4917 If a procedure wants to support keywords, it should take a rest argument
4918 and then use whatever means is convenient to extract keywords and their
4919 corresponding arguments from the contents of that rest argument.
4920
4921 The following example illustrates the principle: the code for
4922 @code{make-window} uses a helper procedure called
4923 @code{get-keyword-value} to extract individual keyword arguments from
4924 the rest argument.
4925
4926 @lisp
4927 (define (get-keyword-value args keyword default)
4928 (let ((kv (memq keyword args)))
4929 (if (and kv (>= (length kv) 2))
4930 (cadr kv)
4931 default)))
4932
4933 (define (make-window . args)
4934 (let ((depth (get-keyword-value args #:depth screen-depth))
4935 (bg (get-keyword-value args #:bg "white"))
4936 (width (get-keyword-value args #:width 800))
4937 (height (get-keyword-value args #:height 100))
4938 @dots{})
4939 @dots{}))
4940 @end lisp
4941
4942 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
4943 optargs)} module provides a set of powerful macros that you can use to
4944 implement keyword-supporting procedures like this:
4945
4946 @lisp
4947 (use-modules (ice-9 optargs))
4948
4949 (define (make-window . args)
4950 (let-keywords args #f ((depth screen-depth)
4951 (bg "white")
4952 (width 800)
4953 (height 100))
4954 ...))
4955 @end lisp
4956
4957 @noindent
4958 Or, even more economically, like this:
4959
4960 @lisp
4961 (use-modules (ice-9 optargs))
4962
4963 (define* (make-window #:key (depth screen-depth)
4964 (bg "white")
4965 (width 800)
4966 (height 100))
4967 ...)
4968 @end lisp
4969
4970 For further details on @code{let-keywords}, @code{define*} and other
4971 facilities provided by the @code{(ice-9 optargs)} module, see
4972 @ref{Optional Arguments}.
4973
4974
4975 @node Keyword Read Syntax
4976 @subsubsection Keyword Read Syntax
4977
4978 Guile, by default, only recognizes a keyword syntax that is compatible
4979 with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
4980 same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
4981 external representation of the keyword named @code{NAME}. Keyword
4982 objects print using this syntax as well, so values containing keyword
4983 objects can be read back into Guile. When used in an expression,
4984 keywords are self-quoting objects.
4985
4986 If the @code{keyword} read option is set to @code{'prefix}, Guile also
4987 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
4988 of the form @code{:NAME} are read as symbols, as required by R5RS.
4989
4990 To enable and disable the alternative non-R5RS keyword syntax, you use
4991 the @code{read-set!} procedure documented in @ref{User level options
4992 interfaces} and @ref{Reader options}.
4993
4994 @smalllisp
4995 (read-set! keywords 'prefix)
4996
4997 #:type
4998 @result{}
4999 #:type
5000
5001 :type
5002 @result{}
5003 #:type
5004
5005 (read-set! keywords #f)
5006
5007 #:type
5008 @result{}
5009 #:type
5010
5011 :type
5012 @print{}
5013 ERROR: In expression :type:
5014 ERROR: Unbound variable: :type
5015 ABORT: (unbound-variable)
5016 @end smalllisp
5017
5018 @node Keyword Procedures
5019 @subsubsection Keyword Procedures
5020
5021 @deffn {Scheme Procedure} keyword? obj
5022 @deffnx {C Function} scm_keyword_p (obj)
5023 Return @code{#t} if the argument @var{obj} is a keyword, else
5024 @code{#f}.
5025 @end deffn
5026
5027 @deffn {Scheme Procedure} keyword->symbol keyword
5028 @deffnx {C Function} scm_keyword_to_symbol (keyword)
5029 Return the symbol with the same name as @var{keyword}.
5030 @end deffn
5031
5032 @deffn {Scheme Procedure} symbol->keyword symbol
5033 @deffnx {C Function} scm_symbol_to_keyword (symbol)
5034 Return the keyword with the same name as @var{symbol}.
5035 @end deffn
5036
5037 @deftypefn {C Function} int scm_is_keyword (SCM obj)
5038 Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
5039 @end deftypefn
5040
5041 @deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5042 @deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5043 Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5044 (@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5045 (@var{str}, @var{len}))}, respectively.
5046 @end deftypefn
5047
5048 @node Other Types
5049 @subsection ``Functionality-Centric'' Data Types
5050
5051 Procedures and macros are documented in their own chapter: see
5052 @ref{Procedures and Macros}.
5053
5054 Variable objects are documented as part of the description of Guile's
5055 module system: see @ref{Variables}.
5056
5057 Asyncs, dynamic roots and fluids are described in the chapter on
5058 scheduling: see @ref{Scheduling}.
5059
5060 Hooks are documented in the chapter on general utility functions: see
5061 @ref{Hooks}.
5062
5063 Ports are described in the chapter on I/O: see @ref{Input and Output}.
5064
5065
5066 @c Local Variables:
5067 @c TeX-master: "guile.texi"
5068 @c End: