2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
7 @node Simple Data Types
8 @section Simple Generic Data Types
10 This chapter describes those of Guile's simple data types which are
11 primarily used for their role as items of generic data. By
12 @dfn{simple} we mean data types that are not primarily used as
13 containers to hold other data --- i.e.@: pairs, lists, vectors and so on.
14 For the documentation of such @dfn{compound} data types, see
15 @ref{Compound Data Types}.
17 @c One of the great strengths of Scheme is that there is no straightforward
18 @c distinction between ``data'' and ``functionality''. For example,
19 @c Guile's support for dynamic linking could be described:
23 @c either in a ``data-centric'' way, as the behaviour and properties of the
24 @c ``dynamically linked object'' data type, and the operations that may be
25 @c applied to instances of this type
28 @c or in a ``functionality-centric'' way, as the set of procedures that
29 @c constitute Guile's support for dynamic linking, in the context of the
33 @c The contents of this chapter are, therefore, a matter of judgment. By
34 @c @dfn{generic}, we mean to select those data types whose typical use as
35 @c @emph{data} in a wide variety of programming contexts is more important
36 @c than their use in the implementation of a particular piece of
37 @c @emph{functionality}. The last section of this chapter provides
38 @c references for all the data types that are documented not here but in a
39 @c ``functionality-centric'' way elsewhere in the manual.
42 * Booleans:: True/false values.
43 * Numbers:: Numerical data types.
44 * Characters:: Single characters.
45 * Character Sets:: Sets of characters.
46 * Strings:: Sequences of characters.
47 * Bytevectors:: Sequences of bytes.
48 * Regular Expressions:: Pattern matching and substitution.
50 * Keywords:: Self-quoting, customizable display keywords.
51 * Other Types:: "Functionality-centric" data types.
59 The two boolean values are @code{#t} for true and @code{#f} for false.
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{<=}
74 (equal? "house" "houses")
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}.
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.
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).
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}.
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}.
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
127 @deftypevr {C Macro} SCM SCM_BOOL_T
128 The @code{SCM} representation of the Scheme object @code{#t}.
131 @deftypevr {C Macro} SCM SCM_BOOL_F
132 The @code{SCM} representation of the Scheme object @code{#f}.
135 @deftypefn {C Function} int scm_is_true (SCM obj)
136 Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
139 @deftypefn {C Function} int scm_is_false (SCM obj)
140 Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
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
148 @deftypefn {C Function} SCM scm_from_bool (int val)
149 Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
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.
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.
161 @subsection Numerical data types
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.
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}.
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 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
187 * Random:: Random number generation.
191 @node Numerical Tower
192 @subsubsection Scheme's Numerical ``Tower''
195 Scheme's numerical ``tower'' consists of the following categories of
200 Whole numbers, positive or negative; e.g.@: --5, 0, 18.
203 The set of numbers that can be expressed as @math{@var{p}/@var{q}}
204 where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
205 pi (an irrational number) doesn't. These include integers
209 The set of numbers that describes all possible positions along a
210 one-dimensional line. This includes rationals as well as irrational
213 @item complex numbers
214 The set of numbers that describes all possible positions in a two
215 dimensional space. This includes real as well as imaginary numbers
216 (@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
217 @var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
221 It is called a tower because each category ``sits on'' the one that
222 follows it, in the sense that every integer is also a rational, every
223 rational is also real, and every real number is also a complex number
224 (but with zero imaginary part).
226 In addition to the classification into integers, rationals, reals and
227 complex numbers, Scheme also distinguishes between whether a number is
228 represented exactly or not. For example, the result of
229 @m{2\sin(\pi/4),2*sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)}, but Guile
230 can represent neither @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
231 Instead, it stores an inexact approximation, using the C type
234 Guile can represent exact rationals of any magnitude, inexact
235 rationals that fit into a C @code{double}, and inexact complex numbers
236 with @code{double} real and imaginary parts.
238 The @code{number?} predicate may be applied to any Scheme value to
239 discover whether the value is any of the supported numerical types.
241 @deffn {Scheme Procedure} number? obj
242 @deffnx {C Function} scm_number_p (obj)
243 Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
252 (number? "hello there!")
255 (define pi 3.141592654)
260 @deftypefn {C Function} int scm_is_number (SCM obj)
261 This is equivalent to @code{scm_is_true (scm_number_p (obj))}.
264 The next few subsections document each of Guile's numerical data types
268 @subsubsection Integers
270 @tpindex Integer numbers
274 Integers are whole numbers, that is numbers with no fractional part,
275 such as 2, 83, and @minus{}3789.
277 Integers in Guile can be arbitrarily big, as shown by the following
281 (define (factorial n)
282 (let loop ((n n) (product 1))
285 (loop (- n 1) (* product n)))))
291 @result{} 2432902008176640000
294 @result{} -119622220865480194561963161495657715064383733760000000000
297 Readers whose background is in programming languages where integers are
298 limited by the need to fit into just 4 or 8 bytes of memory may find
299 this surprising, or suspect that Guile's representation of integers is
300 inefficient. In fact, Guile achieves a near optimal balance of
301 convenience and efficiency by using the host computer's native
302 representation of integers where possible, and a more general
303 representation where the required number does not fit in the native
304 form. Conversion between these two representations is automatic and
305 completely invisible to the Scheme level programmer.
307 The infinities @samp{+inf.0} and @samp{-inf.0} are considered to be
308 inexact integers. They are explained in detail in the next section,
309 together with reals and rationals.
311 C has a host of different integer types, and Guile offers a host of
312 functions to convert between them and the @code{SCM} representation.
313 For example, a C @code{int} can be handled with @code{scm_to_int} and
314 @code{scm_from_int}. Guile also defines a few C integer types of its
315 own, to help with differences between systems.
317 C integer types that are not covered can be handled with the generic
318 @code{scm_to_signed_integer} and @code{scm_from_signed_integer} for
319 signed types, or with @code{scm_to_unsigned_integer} and
320 @code{scm_from_unsigned_integer} for unsigned types.
322 Scheme integers can be exact and inexact. For example, a number
323 written as @code{3.0} with an explicit decimal-point is inexact, but
324 it is also an integer. The functions @code{integer?} and
325 @code{scm_is_integer} report true for such a number, but the functions
326 @code{scm_is_signed_integer} and @code{scm_is_unsigned_integer} only
327 allow exact integers and thus report false. Likewise, the conversion
328 functions like @code{scm_to_signed_integer} only accept exact
331 The motivation for this behavior is that the inexactness of a number
332 should not be lost silently. If you want to allow inexact integers,
333 you can explicitly insert a call to @code{inexact->exact} or to its C
334 equivalent @code{scm_inexact_to_exact}. (Only inexact integers will
335 be converted by this call into exact integers; inexact non-integers
336 will become exact fractions.)
338 @deffn {Scheme Procedure} integer? x
339 @deffnx {C Function} scm_integer_p (x)
340 Return @code{#t} if @var{x} is an exact or inexact integer number, else
358 @deftypefn {C Function} int scm_is_integer (SCM x)
359 This is equivalent to @code{scm_is_true (scm_integer_p (x))}.
362 @defvr {C Type} scm_t_int8
363 @defvrx {C Type} scm_t_uint8
364 @defvrx {C Type} scm_t_int16
365 @defvrx {C Type} scm_t_uint16
366 @defvrx {C Type} scm_t_int32
367 @defvrx {C Type} scm_t_uint32
368 @defvrx {C Type} scm_t_int64
369 @defvrx {C Type} scm_t_uint64
370 @defvrx {C Type} scm_t_intmax
371 @defvrx {C Type} scm_t_uintmax
372 The C types are equivalent to the corresponding ISO C types but are
373 defined on all platforms, with the exception of @code{scm_t_int64} and
374 @code{scm_t_uint64}, which are only defined when a 64-bit type is
375 available. For example, @code{scm_t_int8} is equivalent to
378 You can regard these definitions as a stop-gap measure until all
379 platforms provide these types. If you know that all the platforms
380 that you are interested in already provide these types, it is better
381 to use them directly instead of the types provided by Guile.
384 @deftypefn {C Function} int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
385 @deftypefnx {C Function} int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
386 Return @code{1} when @var{x} represents an exact integer that is
387 between @var{min} and @var{max}, inclusive.
389 These functions can be used to check whether a @code{SCM} value will
390 fit into a given range, such as the range of a given C integer type.
391 If you just want to convert a @code{SCM} value to a given C integer
392 type, use one of the conversion functions directly.
395 @deftypefn {C Function} scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
396 @deftypefnx {C Function} scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
397 When @var{x} represents an exact integer that is between @var{min} and
398 @var{max} inclusive, return that integer. Else signal an error,
399 either a `wrong-type' error when @var{x} is not an exact integer, or
400 an `out-of-range' error when it doesn't fit the given range.
403 @deftypefn {C Function} SCM scm_from_signed_integer (scm_t_intmax x)
404 @deftypefnx {C Function} SCM scm_from_unsigned_integer (scm_t_uintmax x)
405 Return the @code{SCM} value that represents the integer @var{x}. This
406 function will always succeed and will always return an exact number.
409 @deftypefn {C Function} char scm_to_char (SCM x)
410 @deftypefnx {C Function} {signed char} scm_to_schar (SCM x)
411 @deftypefnx {C Function} {unsigned char} scm_to_uchar (SCM x)
412 @deftypefnx {C Function} short scm_to_short (SCM x)
413 @deftypefnx {C Function} {unsigned short} scm_to_ushort (SCM x)
414 @deftypefnx {C Function} int scm_to_int (SCM x)
415 @deftypefnx {C Function} {unsigned int} scm_to_uint (SCM x)
416 @deftypefnx {C Function} long scm_to_long (SCM x)
417 @deftypefnx {C Function} {unsigned long} scm_to_ulong (SCM x)
418 @deftypefnx {C Function} {long long} scm_to_long_long (SCM x)
419 @deftypefnx {C Function} {unsigned long long} scm_to_ulong_long (SCM x)
420 @deftypefnx {C Function} size_t scm_to_size_t (SCM x)
421 @deftypefnx {C Function} ssize_t scm_to_ssize_t (SCM x)
422 @deftypefnx {C Function} scm_t_int8 scm_to_int8 (SCM x)
423 @deftypefnx {C Function} scm_t_uint8 scm_to_uint8 (SCM x)
424 @deftypefnx {C Function} scm_t_int16 scm_to_int16 (SCM x)
425 @deftypefnx {C Function} scm_t_uint16 scm_to_uint16 (SCM x)
426 @deftypefnx {C Function} scm_t_int32 scm_to_int32 (SCM x)
427 @deftypefnx {C Function} scm_t_uint32 scm_to_uint32 (SCM x)
428 @deftypefnx {C Function} scm_t_int64 scm_to_int64 (SCM x)
429 @deftypefnx {C Function} scm_t_uint64 scm_to_uint64 (SCM x)
430 @deftypefnx {C Function} scm_t_intmax scm_to_intmax (SCM x)
431 @deftypefnx {C Function} scm_t_uintmax scm_to_uintmax (SCM x)
432 When @var{x} represents an exact integer that fits into the indicated
433 C type, return that integer. Else signal an error, either a
434 `wrong-type' error when @var{x} is not an exact integer, or an
435 `out-of-range' error when it doesn't fit the given range.
437 The functions @code{scm_to_long_long}, @code{scm_to_ulong_long},
438 @code{scm_to_int64}, and @code{scm_to_uint64} are only available when
439 the corresponding types are.
442 @deftypefn {C Function} SCM scm_from_char (char x)
443 @deftypefnx {C Function} SCM scm_from_schar (signed char x)
444 @deftypefnx {C Function} SCM scm_from_uchar (unsigned char x)
445 @deftypefnx {C Function} SCM scm_from_short (short x)
446 @deftypefnx {C Function} SCM scm_from_ushort (unsigned short x)
447 @deftypefnx {C Function} SCM scm_from_int (int x)
448 @deftypefnx {C Function} SCM scm_from_uint (unsigned int x)
449 @deftypefnx {C Function} SCM scm_from_long (long x)
450 @deftypefnx {C Function} SCM scm_from_ulong (unsigned long x)
451 @deftypefnx {C Function} SCM scm_from_long_long (long long x)
452 @deftypefnx {C Function} SCM scm_from_ulong_long (unsigned long long x)
453 @deftypefnx {C Function} SCM scm_from_size_t (size_t x)
454 @deftypefnx {C Function} SCM scm_from_ssize_t (ssize_t x)
455 @deftypefnx {C Function} SCM scm_from_int8 (scm_t_int8 x)
456 @deftypefnx {C Function} SCM scm_from_uint8 (scm_t_uint8 x)
457 @deftypefnx {C Function} SCM scm_from_int16 (scm_t_int16 x)
458 @deftypefnx {C Function} SCM scm_from_uint16 (scm_t_uint16 x)
459 @deftypefnx {C Function} SCM scm_from_int32 (scm_t_int32 x)
460 @deftypefnx {C Function} SCM scm_from_uint32 (scm_t_uint32 x)
461 @deftypefnx {C Function} SCM scm_from_int64 (scm_t_int64 x)
462 @deftypefnx {C Function} SCM scm_from_uint64 (scm_t_uint64 x)
463 @deftypefnx {C Function} SCM scm_from_intmax (scm_t_intmax x)
464 @deftypefnx {C Function} SCM scm_from_uintmax (scm_t_uintmax x)
465 Return the @code{SCM} value that represents the integer @var{x}.
466 These functions will always succeed and will always return an exact
470 @deftypefn {C Function} void scm_to_mpz (SCM val, mpz_t rop)
471 Assign @var{val} to the multiple precision integer @var{rop}.
472 @var{val} must be an exact integer, otherwise an error will be
473 signalled. @var{rop} must have been initialized with @code{mpz_init}
474 before this function is called. When @var{rop} is no longer needed
475 the occupied space must be freed with @code{mpz_clear}.
476 @xref{Initializing Integers,,, gmp, GNU MP Manual}, for details.
479 @deftypefn {C Function} SCM scm_from_mpz (mpz_t val)
480 Return the @code{SCM} value that represents @var{val}.
483 @node Reals and Rationals
484 @subsubsection Real and Rational Numbers
485 @tpindex Real numbers
486 @tpindex Rational numbers
491 Mathematically, the real numbers are the set of numbers that describe
492 all possible points along a continuous, infinite, one-dimensional line.
493 The rational numbers are the set of all numbers that can be written as
494 fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
495 All rational numbers are also real, but there are real numbers that
496 are not rational, for example @m{\sqrt2, the square root of 2}, and
499 Guile can represent both exact and inexact rational numbers, but it
500 can not represent irrational numbers. Exact rationals are represented
501 by storing the numerator and denominator as two exact integers.
502 Inexact rationals are stored as floating point numbers using the C
505 Exact rationals are written as a fraction of integers. There must be
506 no whitespace around the slash:
513 Even though the actual encoding of inexact rationals is in binary, it
514 may be helpful to think of it as a decimal number with a limited
515 number of significant figures and a decimal point somewhere, since
516 this corresponds to the standard notation for non-whole numbers. For
522 -5648394822220000000000.0
526 The limited precision of Guile's encoding means that any ``real'' number
527 in Guile can be written in a rational form, by multiplying and then dividing
528 by sufficient powers of 10 (or in fact, 2). For example,
529 @samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
530 100000000000000000. In Guile's current incarnation, therefore, the
531 @code{rational?} and @code{real?} predicates are equivalent.
534 Dividing by an exact zero leads to a error message, as one might
535 expect. However, dividing by an inexact zero does not produce an
536 error. Instead, the result of the division is either plus or minus
537 infinity, depending on the sign of the divided number.
539 The infinities are written @samp{+inf.0} and @samp{-inf.0},
540 respectively. This syntax is also recognized by @code{read} as an
541 extension to the usual Scheme syntax.
543 Dividing zero by zero yields something that is not a number at all:
544 @samp{+nan.0}. This is the special `not a number' value.
546 On platforms that follow @acronym{IEEE} 754 for their floating point
547 arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
548 are implemented using the corresponding @acronym{IEEE} 754 values.
549 They behave in arithmetic operations like @acronym{IEEE} 754 describes
550 it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
552 The infinities are inexact integers and are considered to be both even
553 and odd. While @samp{+nan.0} is not @code{=} to itself, it is
554 @code{eqv?} to itself.
556 To test for the special values, use the functions @code{inf?} and
559 @deffn {Scheme Procedure} real? obj
560 @deffnx {C Function} scm_real_p (obj)
561 Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
562 that the sets of integer and rational values form subsets of the set
563 of real numbers, so the predicate will also be fulfilled if @var{obj}
564 is an integer number or a rational number.
567 @deffn {Scheme Procedure} rational? x
568 @deffnx {C Function} scm_rational_p (x)
569 Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
570 Note that the set of integer values forms a subset of the set of
571 rational numbers, i. e. the predicate will also be fulfilled if
572 @var{x} is an integer number.
574 Since Guile can not represent irrational numbers, every number
575 satisfying @code{real?} also satisfies @code{rational?} in Guile.
578 @deffn {Scheme Procedure} rationalize x eps
579 @deffnx {C Function} scm_rationalize (x, eps)
580 Returns the @emph{simplest} rational number differing
581 from @var{x} by no more than @var{eps}.
583 As required by @acronym{R5RS}, @code{rationalize} only returns an
584 exact result when both its arguments are exact. Thus, you might need
585 to use @code{inexact->exact} on the arguments.
588 (rationalize (inexact->exact 1.2) 1/100)
594 @deffn {Scheme Procedure} inf? x
595 @deffnx {C Function} scm_inf_p (x)
596 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
600 @deffn {Scheme Procedure} nan? x
601 @deffnx {C Function} scm_nan_p (x)
602 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
605 @deffn {Scheme Procedure} nan
606 @deffnx {C Function} scm_nan ()
610 @deffn {Scheme Procedure} inf
611 @deffnx {C Function} scm_inf ()
615 @deffn {Scheme Procedure} numerator x
616 @deffnx {C Function} scm_numerator (x)
617 Return the numerator of the rational number @var{x}.
620 @deffn {Scheme Procedure} denominator x
621 @deffnx {C Function} scm_denominator (x)
622 Return the denominator of the rational number @var{x}.
625 @deftypefn {C Function} int scm_is_real (SCM val)
626 @deftypefnx {C Function} int scm_is_rational (SCM val)
627 Equivalent to @code{scm_is_true (scm_real_p (val))} and
628 @code{scm_is_true (scm_rational_p (val))}, respectively.
631 @deftypefn {C Function} double scm_to_double (SCM val)
632 Returns the number closest to @var{val} that is representable as a
633 @code{double}. Returns infinity for a @var{val} that is too large in
634 magnitude. The argument @var{val} must be a real number.
637 @deftypefn {C Function} SCM scm_from_double (double val)
638 Return the @code{SCM} value that represents @var{val}. The returned
639 value is inexact according to the predicate @code{inexact?}, but it
640 will be exactly equal to @var{val}.
643 @node Complex Numbers
644 @subsubsection Complex Numbers
645 @tpindex Complex numbers
649 Complex numbers are the set of numbers that describe all possible points
650 in a two-dimensional space. The two coordinates of a particular point
651 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
652 the complex number that describes that point.
654 In Guile, complex numbers are written in rectangular form as the sum of
655 their real and imaginary parts, using the symbol @code{i} to indicate
670 Polar form can also be used, with an @samp{@@} between magnitude and
674 1@@3.141592 @result{} -1.0 (approx)
675 -1@@1.57079 @result{} 0.0-1.0i (approx)
678 Guile represents a complex number with a non-zero imaginary part as a
679 pair of inexact rationals, so the real and imaginary parts of a
680 complex number have the same properties of inexactness and limited
681 precision as single inexact rational numbers. Guile can not represent
682 exact complex numbers with non-zero imaginary parts.
684 @deffn {Scheme Procedure} complex? z
685 @deffnx {C Function} scm_complex_p (z)
686 Return @code{#t} if @var{x} is a complex number, @code{#f}
687 otherwise. Note that the sets of real, rational and integer
688 values form subsets of the set of complex numbers, i. e. the
689 predicate will also be fulfilled if @var{x} is a real,
690 rational or integer number.
693 @deftypefn {C Function} int scm_is_complex (SCM val)
694 Equivalent to @code{scm_is_true (scm_complex_p (val))}.
698 @subsubsection Exact and Inexact Numbers
699 @tpindex Exact numbers
700 @tpindex Inexact numbers
704 @rnindex exact->inexact
705 @rnindex inexact->exact
707 R5RS requires that a calculation involving inexact numbers always
708 produces an inexact result. To meet this requirement, Guile
709 distinguishes between an exact integer value such as @samp{5} and the
710 corresponding inexact real value which, to the limited precision
711 available, has no fractional part, and is printed as @samp{5.0}. Guile
712 will only convert the latter value to the former when forced to do so by
713 an invocation of the @code{inexact->exact} procedure.
715 @deffn {Scheme Procedure} exact? z
716 @deffnx {C Function} scm_exact_p (z)
717 Return @code{#t} if the number @var{z} is exact, @code{#f}
733 @deffn {Scheme Procedure} inexact? z
734 @deffnx {C Function} scm_inexact_p (z)
735 Return @code{#t} if the number @var{z} is inexact, @code{#f}
739 @deffn {Scheme Procedure} inexact->exact z
740 @deffnx {C Function} scm_inexact_to_exact (z)
741 Return an exact number that is numerically closest to @var{z}, when
742 there is one. For inexact rationals, Guile returns the exact rational
743 that is numerically equal to the inexact rational. Inexact complex
744 numbers with a non-zero imaginary part can not be made exact.
751 The following happens because 12/10 is not exactly representable as a
752 @code{double} (on most platforms). However, when reading a decimal
753 number that has been marked exact with the ``#e'' prefix, Guile is
754 able to represent it correctly.
758 @result{} 5404319552844595/4503599627370496
766 @c begin (texi-doc-string "guile" "exact->inexact")
767 @deffn {Scheme Procedure} exact->inexact z
768 @deffnx {C Function} scm_exact_to_inexact (z)
769 Convert the number @var{z} to its inexact representation.
774 @subsubsection Read Syntax for Numerical Data
776 The read syntax for integers is a string of digits, optionally
777 preceded by a minus or plus character, a code indicating the
778 base in which the integer is encoded, and a code indicating whether
779 the number is exact or inexact. The supported base codes are:
784 the integer is written in binary (base 2)
788 the integer is written in octal (base 8)
792 the integer is written in decimal (base 10)
796 the integer is written in hexadecimal (base 16)
799 If the base code is omitted, the integer is assumed to be decimal. The
800 following examples show how these base codes are used.
819 The codes for indicating exactness (which can, incidentally, be applied
820 to all numerical values) are:
829 the number is inexact.
832 If the exactness indicator is omitted, the number is exact unless it
833 contains a radix point. Since Guile can not represent exact complex
834 numbers, an error is signalled when asking for them.
844 ERROR: Wrong type argument
847 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
848 plus and minus infinity, respectively. The value must be written
849 exactly as shown, that is, they always must have a sign and exactly
850 one zero digit after the decimal point. It also understands
851 @samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
852 The sign is ignored for `not-a-number' and the value is always printed
855 @node Integer Operations
856 @subsubsection Operations on Integer Values
865 @deffn {Scheme Procedure} odd? n
866 @deffnx {C Function} scm_odd_p (n)
867 Return @code{#t} if @var{n} is an odd number, @code{#f}
871 @deffn {Scheme Procedure} even? n
872 @deffnx {C Function} scm_even_p (n)
873 Return @code{#t} if @var{n} is an even number, @code{#f}
877 @c begin (texi-doc-string "guile" "quotient")
878 @c begin (texi-doc-string "guile" "remainder")
879 @deffn {Scheme Procedure} quotient n d
880 @deffnx {Scheme Procedure} remainder n d
881 @deffnx {C Function} scm_quotient (n, d)
882 @deffnx {C Function} scm_remainder (n, d)
883 Return the quotient or remainder from @var{n} divided by @var{d}. The
884 quotient is rounded towards zero, and the remainder will have the same
885 sign as @var{n}. In all cases quotient and remainder satisfy
886 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
889 (remainder 13 4) @result{} 1
890 (remainder -13 4) @result{} -1
894 @c begin (texi-doc-string "guile" "modulo")
895 @deffn {Scheme Procedure} modulo n d
896 @deffnx {C Function} scm_modulo (n, d)
897 Return the remainder from @var{n} divided by @var{d}, with the same
901 (modulo 13 4) @result{} 1
902 (modulo -13 4) @result{} 3
903 (modulo 13 -4) @result{} -3
904 (modulo -13 -4) @result{} -1
908 @c begin (texi-doc-string "guile" "gcd")
909 @deffn {Scheme Procedure} gcd x@dots{}
910 @deffnx {C Function} scm_gcd (x, y)
911 Return the greatest common divisor of all arguments.
912 If called without arguments, 0 is returned.
914 The C function @code{scm_gcd} always takes two arguments, while the
915 Scheme function can take an arbitrary number.
918 @c begin (texi-doc-string "guile" "lcm")
919 @deffn {Scheme Procedure} lcm x@dots{}
920 @deffnx {C Function} scm_lcm (x, y)
921 Return the least common multiple of the arguments.
922 If called without arguments, 1 is returned.
924 The C function @code{scm_lcm} always takes two arguments, while the
925 Scheme function can take an arbitrary number.
928 @deffn {Scheme Procedure} modulo-expt n k m
929 @deffnx {C Function} scm_modulo_expt (n, k, m)
930 Return @var{n} raised to the integer exponent
931 @var{k}, modulo @var{m}.
940 @subsubsection Comparison Predicates
945 The C comparison functions below always takes two arguments, while the
946 Scheme functions can take an arbitrary number. Also keep in mind that
947 the C functions return one of the Scheme boolean values
948 @code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
949 is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
950 y))} when testing the two Scheme numbers @code{x} and @code{y} for
951 equality, for example.
953 @c begin (texi-doc-string "guile" "=")
954 @deffn {Scheme Procedure} =
955 @deffnx {C Function} scm_num_eq_p (x, y)
956 Return @code{#t} if all parameters are numerically equal.
959 @c begin (texi-doc-string "guile" "<")
960 @deffn {Scheme Procedure} <
961 @deffnx {C Function} scm_less_p (x, y)
962 Return @code{#t} if the list of parameters is monotonically
966 @c begin (texi-doc-string "guile" ">")
967 @deffn {Scheme Procedure} >
968 @deffnx {C Function} scm_gr_p (x, y)
969 Return @code{#t} if the list of parameters is monotonically
973 @c begin (texi-doc-string "guile" "<=")
974 @deffn {Scheme Procedure} <=
975 @deffnx {C Function} scm_leq_p (x, y)
976 Return @code{#t} if the list of parameters is monotonically
980 @c begin (texi-doc-string "guile" ">=")
981 @deffn {Scheme Procedure} >=
982 @deffnx {C Function} scm_geq_p (x, y)
983 Return @code{#t} if the list of parameters is monotonically
987 @c begin (texi-doc-string "guile" "zero?")
988 @deffn {Scheme Procedure} zero? z
989 @deffnx {C Function} scm_zero_p (z)
990 Return @code{#t} if @var{z} is an exact or inexact number equal to
994 @c begin (texi-doc-string "guile" "positive?")
995 @deffn {Scheme Procedure} positive? x
996 @deffnx {C Function} scm_positive_p (x)
997 Return @code{#t} if @var{x} is an exact or inexact number greater than
1001 @c begin (texi-doc-string "guile" "negative?")
1002 @deffn {Scheme Procedure} negative? x
1003 @deffnx {C Function} scm_negative_p (x)
1004 Return @code{#t} if @var{x} is an exact or inexact number less than
1010 @subsubsection Converting Numbers To and From Strings
1011 @rnindex number->string
1012 @rnindex string->number
1014 The following procedures read and write numbers according to their
1015 external representation as defined by R5RS (@pxref{Lexical structure,
1016 R5RS Lexical Structure,, r5rs, The Revised^5 Report on the Algorithmic
1017 Language Scheme}). @xref{Number Input and Output, the @code{(ice-9
1018 i18n)} module}, for locale-dependent number parsing.
1020 @deffn {Scheme Procedure} number->string n [radix]
1021 @deffnx {C Function} scm_number_to_string (n, radix)
1022 Return a string holding the external representation of the
1023 number @var{n} in the given @var{radix}. If @var{n} is
1024 inexact, a radix of 10 will be used.
1027 @deffn {Scheme Procedure} string->number string [radix]
1028 @deffnx {C Function} scm_string_to_number (string, radix)
1029 Return a number of the maximally precise representation
1030 expressed by the given @var{string}. @var{radix} must be an
1031 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
1032 is a default radix that may be overridden by an explicit radix
1033 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1034 supplied, then the default radix is 10. If string is not a
1035 syntactically valid notation for a number, then
1036 @code{string->number} returns @code{#f}.
1039 @deftypefn {C Function} SCM scm_c_locale_stringn_to_number (const char *string, size_t len, unsigned radix)
1040 As per @code{string->number} above, but taking a C string, as pointer
1041 and length. The string characters should be in the current locale
1042 encoding (@code{locale} in the name refers only to that, there's no
1043 locale-dependent parsing).
1048 @subsubsection Complex Number Operations
1049 @rnindex make-rectangular
1056 @deffn {Scheme Procedure} make-rectangular real_part imaginary_part
1057 @deffnx {C Function} scm_make_rectangular (real_part, imaginary_part)
1058 Return a complex number constructed of the given @var{real-part} and @var{imaginary-part} parts.
1061 @deffn {Scheme Procedure} make-polar x y
1062 @deffnx {C Function} scm_make_polar (x, y)
1064 Return the complex number @var{x} * e^(i * @var{y}).
1067 @c begin (texi-doc-string "guile" "real-part")
1068 @deffn {Scheme Procedure} real-part z
1069 @deffnx {C Function} scm_real_part (z)
1070 Return the real part of the number @var{z}.
1073 @c begin (texi-doc-string "guile" "imag-part")
1074 @deffn {Scheme Procedure} imag-part z
1075 @deffnx {C Function} scm_imag_part (z)
1076 Return the imaginary part of the number @var{z}.
1079 @c begin (texi-doc-string "guile" "magnitude")
1080 @deffn {Scheme Procedure} magnitude z
1081 @deffnx {C Function} scm_magnitude (z)
1082 Return the magnitude of the number @var{z}. This is the same as
1083 @code{abs} for real arguments, but also allows complex numbers.
1086 @c begin (texi-doc-string "guile" "angle")
1087 @deffn {Scheme Procedure} angle z
1088 @deffnx {C Function} scm_angle (z)
1089 Return the angle of the complex number @var{z}.
1092 @deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1093 @deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1094 Like @code{scm_make_rectangular} or @code{scm_make_polar},
1095 respectively, but these functions take @code{double}s as their
1099 @deftypefn {C Function} double scm_c_real_part (z)
1100 @deftypefnx {C Function} double scm_c_imag_part (z)
1101 Returns the real or imaginary part of @var{z} as a @code{double}.
1104 @deftypefn {C Function} double scm_c_magnitude (z)
1105 @deftypefnx {C Function} double scm_c_angle (z)
1106 Returns the magnitude or angle of @var{z} as a @code{double}.
1111 @subsubsection Arithmetic Functions
1126 The C arithmetic functions below always takes two arguments, while the
1127 Scheme functions can take an arbitrary number. When you need to
1128 invoke them with just one argument, for example to compute the
1129 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1130 one: @code{scm_difference (x, SCM_UNDEFINED)}.
1132 @c begin (texi-doc-string "guile" "+")
1133 @deffn {Scheme Procedure} + z1 @dots{}
1134 @deffnx {C Function} scm_sum (z1, z2)
1135 Return the sum of all parameter values. Return 0 if called without any
1139 @c begin (texi-doc-string "guile" "-")
1140 @deffn {Scheme Procedure} - z1 z2 @dots{}
1141 @deffnx {C Function} scm_difference (z1, z2)
1142 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1143 the sum of all but the first argument are subtracted from the first
1147 @c begin (texi-doc-string "guile" "*")
1148 @deffn {Scheme Procedure} * z1 @dots{}
1149 @deffnx {C Function} scm_product (z1, z2)
1150 Return the product of all arguments. If called without arguments, 1 is
1154 @c begin (texi-doc-string "guile" "/")
1155 @deffn {Scheme Procedure} / z1 z2 @dots{}
1156 @deffnx {C Function} scm_divide (z1, z2)
1157 Divide the first argument by the product of the remaining arguments. If
1158 called with one argument @var{z1}, 1/@var{z1} is returned.
1161 @deffn {Scheme Procedure} 1+ z
1162 @deffnx {C Function} scm_oneplus (z)
1163 Return @math{@var{z} + 1}.
1166 @deffn {Scheme Procedure} 1- z
1167 @deffnx {C function} scm_oneminus (z)
1168 Return @math{@var{z} - 1}.
1171 @c begin (texi-doc-string "guile" "abs")
1172 @deffn {Scheme Procedure} abs x
1173 @deffnx {C Function} scm_abs (x)
1174 Return the absolute value of @var{x}.
1176 @var{x} must be a number with zero imaginary part. To calculate the
1177 magnitude of a complex number, use @code{magnitude} instead.
1180 @c begin (texi-doc-string "guile" "max")
1181 @deffn {Scheme Procedure} max x1 x2 @dots{}
1182 @deffnx {C Function} scm_max (x1, x2)
1183 Return the maximum of all parameter values.
1186 @c begin (texi-doc-string "guile" "min")
1187 @deffn {Scheme Procedure} min x1 x2 @dots{}
1188 @deffnx {C Function} scm_min (x1, x2)
1189 Return the minimum of all parameter values.
1192 @c begin (texi-doc-string "guile" "truncate")
1193 @deffn {Scheme Procedure} truncate x
1194 @deffnx {C Function} scm_truncate_number (x)
1195 Round the inexact number @var{x} towards zero.
1198 @c begin (texi-doc-string "guile" "round")
1199 @deffn {Scheme Procedure} round x
1200 @deffnx {C Function} scm_round_number (x)
1201 Round the inexact number @var{x} to the nearest integer. When exactly
1202 halfway between two integers, round to the even one.
1205 @c begin (texi-doc-string "guile" "floor")
1206 @deffn {Scheme Procedure} floor x
1207 @deffnx {C Function} scm_floor (x)
1208 Round the number @var{x} towards minus infinity.
1211 @c begin (texi-doc-string "guile" "ceiling")
1212 @deffn {Scheme Procedure} ceiling x
1213 @deffnx {C Function} scm_ceiling (x)
1214 Round the number @var{x} towards infinity.
1217 @deftypefn {C Function} double scm_c_truncate (double x)
1218 @deftypefnx {C Function} double scm_c_round (double x)
1219 Like @code{scm_truncate_number} or @code{scm_round_number},
1220 respectively, but these functions take and return @code{double}
1225 @subsubsection Scientific Functions
1227 The following procedures accept any kind of number as arguments,
1228 including complex numbers.
1231 @c begin (texi-doc-string "guile" "sqrt")
1232 @deffn {Scheme Procedure} sqrt z
1233 Return the square root of @var{z}. Of the two possible roots
1234 (positive and negative), the one with the a positive real part is
1235 returned, or if that's zero then a positive imaginary part. Thus,
1238 (sqrt 9.0) @result{} 3.0
1239 (sqrt -9.0) @result{} 0.0+3.0i
1240 (sqrt 1.0+1.0i) @result{} 1.09868411346781+0.455089860562227i
1241 (sqrt -1.0-1.0i) @result{} 0.455089860562227-1.09868411346781i
1246 @c begin (texi-doc-string "guile" "expt")
1247 @deffn {Scheme Procedure} expt z1 z2
1248 Return @var{z1} raised to the power of @var{z2}.
1252 @c begin (texi-doc-string "guile" "sin")
1253 @deffn {Scheme Procedure} sin z
1254 Return the sine of @var{z}.
1258 @c begin (texi-doc-string "guile" "cos")
1259 @deffn {Scheme Procedure} cos z
1260 Return the cosine of @var{z}.
1264 @c begin (texi-doc-string "guile" "tan")
1265 @deffn {Scheme Procedure} tan z
1266 Return the tangent of @var{z}.
1270 @c begin (texi-doc-string "guile" "asin")
1271 @deffn {Scheme Procedure} asin z
1272 Return the arcsine of @var{z}.
1276 @c begin (texi-doc-string "guile" "acos")
1277 @deffn {Scheme Procedure} acos z
1278 Return the arccosine of @var{z}.
1282 @c begin (texi-doc-string "guile" "atan")
1283 @deffn {Scheme Procedure} atan z
1284 @deffnx {Scheme Procedure} atan y x
1285 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1289 @c begin (texi-doc-string "guile" "exp")
1290 @deffn {Scheme Procedure} exp z
1291 Return e to the power of @var{z}, where e is the base of natural
1292 logarithms (2.71828@dots{}).
1296 @c begin (texi-doc-string "guile" "log")
1297 @deffn {Scheme Procedure} log z
1298 Return the natural logarithm of @var{z}.
1301 @c begin (texi-doc-string "guile" "log10")
1302 @deffn {Scheme Procedure} log10 z
1303 Return the base 10 logarithm of @var{z}.
1306 @c begin (texi-doc-string "guile" "sinh")
1307 @deffn {Scheme Procedure} sinh z
1308 Return the hyperbolic sine of @var{z}.
1311 @c begin (texi-doc-string "guile" "cosh")
1312 @deffn {Scheme Procedure} cosh z
1313 Return the hyperbolic cosine of @var{z}.
1316 @c begin (texi-doc-string "guile" "tanh")
1317 @deffn {Scheme Procedure} tanh z
1318 Return the hyperbolic tangent of @var{z}.
1321 @c begin (texi-doc-string "guile" "asinh")
1322 @deffn {Scheme Procedure} asinh z
1323 Return the hyperbolic arcsine of @var{z}.
1326 @c begin (texi-doc-string "guile" "acosh")
1327 @deffn {Scheme Procedure} acosh z
1328 Return the hyperbolic arccosine of @var{z}.
1331 @c begin (texi-doc-string "guile" "atanh")
1332 @deffn {Scheme Procedure} atanh z
1333 Return the hyperbolic arctangent of @var{z}.
1337 @node Bitwise Operations
1338 @subsubsection Bitwise Operations
1340 For the following bitwise functions, negative numbers are treated as
1341 infinite precision twos-complements. For instance @math{-6} is bits
1342 @math{@dots{}111010}, with infinitely many ones on the left. It can
1343 be seen that adding 6 (binary 110) to such a bit pattern gives all
1346 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1347 @deffnx {C Function} scm_logand (n1, n2)
1348 Return the bitwise @sc{and} of the integer arguments.
1351 (logand) @result{} -1
1352 (logand 7) @result{} 7
1353 (logand #b111 #b011 #b001) @result{} 1
1357 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1358 @deffnx {C Function} scm_logior (n1, n2)
1359 Return the bitwise @sc{or} of the integer arguments.
1362 (logior) @result{} 0
1363 (logior 7) @result{} 7
1364 (logior #b000 #b001 #b011) @result{} 3
1368 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1369 @deffnx {C Function} scm_loxor (n1, n2)
1370 Return the bitwise @sc{xor} of the integer arguments. A bit is
1371 set in the result if it is set in an odd number of arguments.
1374 (logxor) @result{} 0
1375 (logxor 7) @result{} 7
1376 (logxor #b000 #b001 #b011) @result{} 2
1377 (logxor #b000 #b001 #b011 #b011) @result{} 1
1381 @deffn {Scheme Procedure} lognot n
1382 @deffnx {C Function} scm_lognot (n)
1383 Return the integer which is the ones-complement of the integer
1384 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1387 (number->string (lognot #b10000000) 2)
1388 @result{} "-10000001"
1389 (number->string (lognot #b0) 2)
1394 @deffn {Scheme Procedure} logtest j k
1395 @deffnx {C Function} scm_logtest (j, k)
1396 Test whether @var{j} and @var{k} have any 1 bits in common. This is
1397 equivalent to @code{(not (zero? (logand j k)))}, but without actually
1398 calculating the @code{logand}, just testing for non-zero.
1401 (logtest #b0100 #b1011) @result{} #f
1402 (logtest #b0100 #b0111) @result{} #t
1406 @deffn {Scheme Procedure} logbit? index j
1407 @deffnx {C Function} scm_logbit_p (index, j)
1408 Test whether bit number @var{index} in @var{j} is set. @var{index}
1409 starts from 0 for the least significant bit.
1412 (logbit? 0 #b1101) @result{} #t
1413 (logbit? 1 #b1101) @result{} #f
1414 (logbit? 2 #b1101) @result{} #t
1415 (logbit? 3 #b1101) @result{} #t
1416 (logbit? 4 #b1101) @result{} #f
1420 @deffn {Scheme Procedure} ash n cnt
1421 @deffnx {C Function} scm_ash (n, cnt)
1422 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1423 @var{cnt} is negative. This is an ``arithmetic'' shift.
1425 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1426 when @var{cnt} is negative it's a division, rounded towards negative
1427 infinity. (Note that this is not the same rounding as @code{quotient}
1430 With @var{n} viewed as an infinite precision twos complement,
1431 @code{ash} means a left shift introducing zero bits, or a right shift
1435 (number->string (ash #b1 3) 2) @result{} "1000"
1436 (number->string (ash #b1010 -1) 2) @result{} "101"
1438 ;; -23 is bits ...11101001, -6 is bits ...111010
1439 (ash -23 -2) @result{} -6
1443 @deffn {Scheme Procedure} logcount n
1444 @deffnx {C Function} scm_logcount (n)
1445 Return the number of bits in integer @var{n}. If @var{n} is
1446 positive, the 1-bits in its binary representation are counted.
1447 If negative, the 0-bits in its two's-complement binary
1448 representation are counted. If zero, 0 is returned.
1451 (logcount #b10101010)
1460 @deffn {Scheme Procedure} integer-length n
1461 @deffnx {C Function} scm_integer_length (n)
1462 Return the number of bits necessary to represent @var{n}.
1464 For positive @var{n} this is how many bits to the most significant one
1465 bit. For negative @var{n} it's how many bits to the most significant
1466 zero bit in twos complement form.
1469 (integer-length #b10101010) @result{} 8
1470 (integer-length #b1111) @result{} 4
1471 (integer-length 0) @result{} 0
1472 (integer-length -1) @result{} 0
1473 (integer-length -256) @result{} 8
1474 (integer-length -257) @result{} 9
1478 @deffn {Scheme Procedure} integer-expt n k
1479 @deffnx {C Function} scm_integer_expt (n, k)
1480 Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1481 integer, @var{n} can be any number.
1483 Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1484 in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1488 (integer-expt 2 5) @result{} 32
1489 (integer-expt -3 3) @result{} -27
1490 (integer-expt 5 -3) @result{} 1/125
1491 (integer-expt 0 0) @result{} 1
1495 @deffn {Scheme Procedure} bit-extract n start end
1496 @deffnx {C Function} scm_bit_extract (n, start, end)
1497 Return the integer composed of the @var{start} (inclusive)
1498 through @var{end} (exclusive) bits of @var{n}. The
1499 @var{start}th bit becomes the 0-th bit in the result.
1502 (number->string (bit-extract #b1101101010 0 4) 2)
1504 (number->string (bit-extract #b1101101010 4 9) 2)
1511 @subsubsection Random Number Generation
1513 Pseudo-random numbers are generated from a random state object, which
1514 can be created with @code{seed->random-state}. The @var{state}
1515 parameter to the various functions below is optional, it defaults to
1516 the state object in the @code{*random-state*} variable.
1518 @deffn {Scheme Procedure} copy-random-state [state]
1519 @deffnx {C Function} scm_copy_random_state (state)
1520 Return a copy of the random state @var{state}.
1523 @deffn {Scheme Procedure} random n [state]
1524 @deffnx {C Function} scm_random (n, state)
1525 Return a number in [0, @var{n}).
1527 Accepts a positive integer or real n and returns a
1528 number of the same type between zero (inclusive) and
1529 @var{n} (exclusive). The values returned have a uniform
1533 @deffn {Scheme Procedure} random:exp [state]
1534 @deffnx {C Function} scm_random_exp (state)
1535 Return an inexact real in an exponential distribution with mean
1536 1. For an exponential distribution with mean @var{u} use @code{(*
1537 @var{u} (random:exp))}.
1540 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1541 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1542 Fills @var{vect} with inexact real random numbers the sum of whose
1543 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1544 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1545 the coordinates are uniformly distributed over the surface of the unit
1549 @deffn {Scheme Procedure} random:normal [state]
1550 @deffnx {C Function} scm_random_normal (state)
1551 Return an inexact real in a normal distribution. The distribution
1552 used has mean 0 and standard deviation 1. For a normal distribution
1553 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1554 (* @var{d} (random:normal)))}.
1557 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1558 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1559 Fills @var{vect} with inexact real random numbers that are
1560 independent and standard normally distributed
1561 (i.e., with mean 0 and variance 1).
1564 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1565 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1566 Fills @var{vect} with inexact real random numbers the sum of whose
1567 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1568 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1569 the coordinates are uniformly distributed within the unit
1571 @c FIXME: What does this mean, particularly the n-sphere part?
1574 @deffn {Scheme Procedure} random:uniform [state]
1575 @deffnx {C Function} scm_random_uniform (state)
1576 Return a uniformly distributed inexact real random number in
1580 @deffn {Scheme Procedure} seed->random-state seed
1581 @deffnx {C Function} scm_seed_to_random_state (seed)
1582 Return a new random state using @var{seed}.
1585 @defvar *random-state*
1586 The global random state used by the above functions when the
1587 @var{state} parameter is not given.
1590 Note that the initial value of @code{*random-state*} is the same every
1591 time Guile starts up. Therefore, if you don't pass a @var{state}
1592 parameter to the above procedures, and you don't set
1593 @code{*random-state*} to @code{(seed->random-state your-seed)}, where
1594 @code{your-seed} is something that @emph{isn't} the same every time,
1595 you'll get the same sequence of ``random'' numbers on every run.
1597 For example, unless the relevant source code has changed, @code{(map
1598 random (cdr (iota 30)))}, if the first use of random numbers since
1599 Guile started up, will always give:
1602 (map random (cdr (iota 19)))
1604 (0 1 1 2 2 2 1 2 6 7 10 0 5 3 12 5 5 12)
1607 To use the time of day as the random seed, you can use code like this:
1610 (let ((time (gettimeofday)))
1611 (set! *random-state*
1612 (seed->random-state (+ (car time)
1617 And then (depending on the time of day, of course):
1620 (map random (cdr (iota 19)))
1622 (0 0 1 0 2 4 5 4 5 5 9 3 10 1 8 3 14 17)
1625 For security applications, such as password generation, you should use
1626 more bits of seed. Otherwise an open source password generator could
1627 be attacked by guessing the seed@dots{} but that's a subject for
1632 @subsection Characters
1635 In Scheme, there is a data type to describe a single character.
1637 Defining what exactly a character @emph{is} can be more complicated
1638 than it seems. Guile follows the advice of R6RS and uses The Unicode
1639 Standard to help define what a character is. So, for Guile, a
1640 character is anything in the Unicode Character Database.
1643 @cindex Unicode code point
1645 The Unicode Character Database is basically a table of characters
1646 indexed using integers called 'code points'. Valid code points are in
1647 the ranges 0 to @code{#xD7FF} inclusive or @code{#xE000} to
1648 @code{#x10FFFF} inclusive, which is about 1.1 million code points.
1650 @cindex designated code point
1651 @cindex code point, designated
1653 Any code point that has been assigned to a character or that has
1654 otherwise been given a meaning by Unicode is called a 'designated code
1655 point'. Most of the designated code points, about 200,000 of them,
1656 indicate characters, accents or other combining marks that modify
1657 other characters, symbols, whitespace, and control characters. Some
1658 are not characters but indicators that suggest how to format or
1659 display neighboring characters.
1661 @cindex reserved code point
1662 @cindex code point, reserved
1664 If a code point is not a designated code point -- if it has not been
1665 assigned to a character by The Unicode Standard -- it is a 'reserved
1666 code point', meaning that they are reserved for future use. Most of
1667 the code points, about 800,000, are 'reserved code points'.
1669 By convention, a Unicode code point is written as
1670 ``U+XXXX'' where ``XXXX'' is a hexadecimal number. Please note that
1671 this convenient notation is not valid code. Guile does not interpret
1672 ``U+XXXX'' as a character.
1674 In Scheme, a character literal is written as @code{#\@var{name}} where
1675 @var{name} is the name of the character that you want. Printable
1676 characters have their usual single character name; for example,
1677 @code{#\a} is a lower case @code{a}.
1679 Some of the code points are 'combining characters' that are not meant
1680 to be printed by themselves but are instead meant to modify the
1681 appearance of the previous character. For combining characters, an
1682 alternate form of the character literal is @code{#\} followed by
1683 U+25CC (a small, dotted circle), followed by the combining character.
1684 This allows the combining character to be drawn on the circle, not on
1685 the backslash of @code{#\}.
1687 Many of the non-printing characters, such as whitespace characters and
1688 control characters, also have names.
1690 The most commonly used non-printing characters have long character
1691 names, described in the table below.
1693 @multitable {@code{#\backspace}} {Preferred}
1694 @item Character Name @tab Codepoint
1695 @item @code{#\nul} @tab U+0000
1696 @item @code{#\alarm} @tab u+0007
1697 @item @code{#\backspace} @tab U+0008
1698 @item @code{#\tab} @tab U+0009
1699 @item @code{#\linefeed} @tab U+000A
1700 @item @code{#\newline} @tab U+000A
1701 @item @code{#\vtab} @tab U+000B
1702 @item @code{#\page} @tab U+000C
1703 @item @code{#\return} @tab U+000D
1704 @item @code{#\esc} @tab U+001B
1705 @item @code{#\space} @tab U+0020
1706 @item @code{#\delete} @tab U+007F
1709 There are also short names for all of the ``C0 control characters''
1710 (those with code points below 32). The following table lists the short
1711 name for each character.
1713 @multitable @columnfractions .25 .25 .25 .25
1714 @item 0 = @code{#\nul}
1715 @tab 1 = @code{#\soh}
1716 @tab 2 = @code{#\stx}
1717 @tab 3 = @code{#\etx}
1718 @item 4 = @code{#\eot}
1719 @tab 5 = @code{#\enq}
1720 @tab 6 = @code{#\ack}
1721 @tab 7 = @code{#\bel}
1722 @item 8 = @code{#\bs}
1723 @tab 9 = @code{#\ht}
1724 @tab 10 = @code{#\lf}
1725 @tab 11 = @code{#\vt}
1726 @item 12 = @code{#\ff}
1727 @tab 13 = @code{#\cr}
1728 @tab 14 = @code{#\so}
1729 @tab 15 = @code{#\si}
1730 @item 16 = @code{#\dle}
1731 @tab 17 = @code{#\dc1}
1732 @tab 18 = @code{#\dc2}
1733 @tab 19 = @code{#\dc3}
1734 @item 20 = @code{#\dc4}
1735 @tab 21 = @code{#\nak}
1736 @tab 22 = @code{#\syn}
1737 @tab 23 = @code{#\etb}
1738 @item 24 = @code{#\can}
1739 @tab 25 = @code{#\em}
1740 @tab 26 = @code{#\sub}
1741 @tab 27 = @code{#\esc}
1742 @item 28 = @code{#\fs}
1743 @tab 29 = @code{#\gs}
1744 @tab 30 = @code{#\rs}
1745 @tab 31 = @code{#\us}
1746 @item 32 = @code{#\sp}
1749 The short name for the ``delete'' character (code point U+007F) is
1752 There are also a few alternative names left over for compatibility with
1753 previous versions of Guile.
1755 @multitable {@code{#\backspace}} {Preferred}
1756 @item Alternate @tab Standard
1757 @item @code{#\nl} @tab @code{#\newline}
1758 @item @code{#\np} @tab @code{#\page}
1759 @item @code{#\null} @tab @code{#\nul}
1762 Characters may also be written using their code point values. They can
1763 be written with as an octal number, such as @code{#\10} for
1764 @code{#\bs} or @code{#\177} for @code{#\del}.
1766 When the @code{r6rs-hex-escapes} reader option is enabled, there is an
1767 additional syntax for character escapes: @code{#\xHHHH} -- the letter 'x'
1768 followed by a hexadecimal number of one to eight digits.
1771 (read-enable 'r6rs-hex-escapes)
1774 Enabling this option will also change the hex escape format for strings. More
1775 on string escapes can be found at (@pxref{String Syntax}). More on reader
1776 options in general can be found at (@pxref{Reader options}).
1779 @deffn {Scheme Procedure} char? x
1780 @deffnx {C Function} scm_char_p (x)
1781 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1784 Fundamentally, the character comparison operations below are
1785 numeric comparisons of the character's code points.
1788 @deffn {Scheme Procedure} char=? x y
1789 Return @code{#t} iff code point of @var{x} is equal to the code point
1790 of @var{y}, else @code{#f}.
1794 @deffn {Scheme Procedure} char<? x y
1795 Return @code{#t} iff the code point of @var{x} is less than the code
1796 point of @var{y}, else @code{#f}.
1800 @deffn {Scheme Procedure} char<=? x y
1801 Return @code{#t} iff the code point of @var{x} is less than or equal
1802 to the code point of @var{y}, else @code{#f}.
1806 @deffn {Scheme Procedure} char>? x y
1807 Return @code{#t} iff the code point of @var{x} is greater than the
1808 code point of @var{y}, else @code{#f}.
1812 @deffn {Scheme Procedure} char>=? x y
1813 Return @code{#t} iff the code point of @var{x} is greater than or
1814 equal to the code point of @var{y}, else @code{#f}.
1817 @cindex case folding
1819 Case-insensitive character comparisons use @emph{Unicode case
1820 folding}. In case folding comparisons, if a character is lowercase
1821 and has an uppercase form that can be expressed as a single character,
1822 it is converted to uppercase before comparison. All other characters
1823 undergo no conversion before the comparison occurs. This includes the
1824 German sharp S (Eszett) which is not uppercased before conversion
1825 because its uppercase form has two characters. Unicode case folding
1826 is language independent: it uses rules that are generally true, but,
1827 it cannot cover all cases for all languages.
1830 @deffn {Scheme Procedure} char-ci=? x y
1831 Return @code{#t} iff the case-folded code point of @var{x} is the same
1832 as the case-folded code point of @var{y}, else @code{#f}.
1836 @deffn {Scheme Procedure} char-ci<? x y
1837 Return @code{#t} iff the case-folded code point of @var{x} is less
1838 than the case-folded code point of @var{y}, else @code{#f}.
1842 @deffn {Scheme Procedure} char-ci<=? x y
1843 Return @code{#t} iff the case-folded code point of @var{x} is less
1844 than or equal to the case-folded code point of @var{y}, else
1849 @deffn {Scheme Procedure} char-ci>? x y
1850 Return @code{#t} iff the case-folded code point of @var{x} is greater
1851 than the case-folded code point of @var{y}, else @code{#f}.
1855 @deffn {Scheme Procedure} char-ci>=? x y
1856 Return @code{#t} iff the case-folded code point of @var{x} is greater
1857 than or equal to the case-folded code point of @var{y}, else
1861 @rnindex char-alphabetic?
1862 @deffn {Scheme Procedure} char-alphabetic? chr
1863 @deffnx {C Function} scm_char_alphabetic_p (chr)
1864 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1867 @rnindex char-numeric?
1868 @deffn {Scheme Procedure} char-numeric? chr
1869 @deffnx {C Function} scm_char_numeric_p (chr)
1870 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1873 @rnindex char-whitespace?
1874 @deffn {Scheme Procedure} char-whitespace? chr
1875 @deffnx {C Function} scm_char_whitespace_p (chr)
1876 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1879 @rnindex char-upper-case?
1880 @deffn {Scheme Procedure} char-upper-case? chr
1881 @deffnx {C Function} scm_char_upper_case_p (chr)
1882 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1885 @rnindex char-lower-case?
1886 @deffn {Scheme Procedure} char-lower-case? chr
1887 @deffnx {C Function} scm_char_lower_case_p (chr)
1888 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1891 @deffn {Scheme Procedure} char-is-both? chr
1892 @deffnx {C Function} scm_char_is_both_p (chr)
1893 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1897 @deffn {Scheme Procedure} char-general-category chr
1898 @deffnx {C Function} scm_char_general_category (chr)
1899 Return a symbol giving the two-letter name of the Unicode general
1900 category assigned to @var{chr} or @code{#f} if no named category is
1901 assigned. The following table provides a list of category names along
1902 with their meanings.
1904 @multitable @columnfractions .1 .4 .1 .4
1906 @tab Uppercase letter
1908 @tab Final quote punctuation
1910 @tab Lowercase letter
1912 @tab Other punctuation
1914 @tab Titlecase letter
1918 @tab Modifier letter
1920 @tab Currency symbol
1924 @tab Modifier symbol
1926 @tab Non-spacing mark
1930 @tab Combining spacing mark
1932 @tab Space separator
1938 @tab Decimal digit number
1940 @tab Paragraph separator
1950 @tab Connector punctuation
1954 @tab Dash punctuation
1958 @tab Open punctuation
1962 @tab Close punctuation
1966 @tab Initial quote punctuation
1972 @rnindex char->integer
1973 @deffn {Scheme Procedure} char->integer chr
1974 @deffnx {C Function} scm_char_to_integer (chr)
1975 Return the code point of @var{chr}.
1978 @rnindex integer->char
1979 @deffn {Scheme Procedure} integer->char n
1980 @deffnx {C Function} scm_integer_to_char (n)
1981 Return the character that has code point @var{n}. The integer @var{n}
1982 must be a valid code point. Valid code points are in the ranges 0 to
1983 @code{#xD7FF} inclusive or @code{#xE000} to @code{#x10FFFF} inclusive.
1986 @rnindex char-upcase
1987 @deffn {Scheme Procedure} char-upcase chr
1988 @deffnx {C Function} scm_char_upcase (chr)
1989 Return the uppercase character version of @var{chr}.
1992 @rnindex char-downcase
1993 @deffn {Scheme Procedure} char-downcase chr
1994 @deffnx {C Function} scm_char_downcase (chr)
1995 Return the lowercase character version of @var{chr}.
1998 @rnindex char-titlecase
1999 @deffn {Scheme Procedure} char-titlecase chr
2000 @deffnx {C Function} scm_char_titlecase (chr)
2001 Return the titlecase character version of @var{chr} if one exists;
2002 otherwise return the uppercase version.
2004 For most characters these will be the same, but the Unicode Standard
2005 includes certain digraph compatibility characters, such as @code{U+01F3}
2006 ``dz'', for which the uppercase and titlecase characters are different
2007 (@code{U+01F1} ``DZ'' and @code{U+01F2} ``Dz'' in this case,
2012 @deftypefn {C Function} scm_t_wchar scm_c_upcase (scm_t_wchar @var{c})
2013 @deftypefnx {C Function} scm_t_wchar scm_c_downcase (scm_t_wchar @var{c})
2014 @deftypefnx {C Function} scm_t_wchar scm_c_titlecase (scm_t_wchar @var{c})
2016 These C functions take an integer representation of a Unicode
2017 codepoint and return the codepoint corresponding to its uppercase,
2018 lowercase, and titlecase forms respectively. The type
2019 @code{scm_t_wchar} is a signed, 32-bit integer.
2022 @node Character Sets
2023 @subsection Character Sets
2025 The features described in this section correspond directly to SRFI-14.
2027 The data type @dfn{charset} implements sets of characters
2028 (@pxref{Characters}). Because the internal representation of
2029 character sets is not visible to the user, a lot of procedures for
2030 handling them are provided.
2032 Character sets can be created, extended, tested for the membership of a
2033 characters and be compared to other character sets.
2036 * Character Set Predicates/Comparison::
2037 * Iterating Over Character Sets:: Enumerate charset elements.
2038 * Creating Character Sets:: Making new charsets.
2039 * Querying Character Sets:: Test charsets for membership etc.
2040 * Character-Set Algebra:: Calculating new charsets.
2041 * Standard Character Sets:: Variables containing predefined charsets.
2044 @node Character Set Predicates/Comparison
2045 @subsubsection Character Set Predicates/Comparison
2047 Use these procedures for testing whether an object is a character set,
2048 or whether several character sets are equal or subsets of each other.
2049 @code{char-set-hash} can be used for calculating a hash value, maybe for
2050 usage in fast lookup procedures.
2052 @deffn {Scheme Procedure} char-set? obj
2053 @deffnx {C Function} scm_char_set_p (obj)
2054 Return @code{#t} if @var{obj} is a character set, @code{#f}
2058 @deffn {Scheme Procedure} char-set= . char_sets
2059 @deffnx {C Function} scm_char_set_eq (char_sets)
2060 Return @code{#t} if all given character sets are equal.
2063 @deffn {Scheme Procedure} char-set<= . char_sets
2064 @deffnx {C Function} scm_char_set_leq (char_sets)
2065 Return @code{#t} if every character set @var{cs}i is a subset
2066 of character set @var{cs}i+1.
2069 @deffn {Scheme Procedure} char-set-hash cs [bound]
2070 @deffnx {C Function} scm_char_set_hash (cs, bound)
2071 Compute a hash value for the character set @var{cs}. If
2072 @var{bound} is given and non-zero, it restricts the
2073 returned value to the range 0 @dots{} @var{bound - 1}.
2076 @c ===================================================================
2078 @node Iterating Over Character Sets
2079 @subsubsection Iterating Over Character Sets
2081 Character set cursors are a means for iterating over the members of a
2082 character sets. After creating a character set cursor with
2083 @code{char-set-cursor}, a cursor can be dereferenced with
2084 @code{char-set-ref}, advanced to the next member with
2085 @code{char-set-cursor-next}. Whether a cursor has passed past the last
2086 element of the set can be checked with @code{end-of-char-set?}.
2088 Additionally, mapping and (un-)folding procedures for character sets are
2091 @deffn {Scheme Procedure} char-set-cursor cs
2092 @deffnx {C Function} scm_char_set_cursor (cs)
2093 Return a cursor into the character set @var{cs}.
2096 @deffn {Scheme Procedure} char-set-ref cs cursor
2097 @deffnx {C Function} scm_char_set_ref (cs, cursor)
2098 Return the character at the current cursor position
2099 @var{cursor} in the character set @var{cs}. It is an error to
2100 pass a cursor for which @code{end-of-char-set?} returns true.
2103 @deffn {Scheme Procedure} char-set-cursor-next cs cursor
2104 @deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
2105 Advance the character set cursor @var{cursor} to the next
2106 character in the character set @var{cs}. It is an error if the
2107 cursor given satisfies @code{end-of-char-set?}.
2110 @deffn {Scheme Procedure} end-of-char-set? cursor
2111 @deffnx {C Function} scm_end_of_char_set_p (cursor)
2112 Return @code{#t} if @var{cursor} has reached the end of a
2113 character set, @code{#f} otherwise.
2116 @deffn {Scheme Procedure} char-set-fold kons knil cs
2117 @deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2118 Fold the procedure @var{kons} over the character set @var{cs},
2119 initializing it with @var{knil}.
2122 @deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2123 @deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2124 This is a fundamental constructor for character sets.
2126 @item @var{g} is used to generate a series of ``seed'' values
2127 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2128 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2129 @item @var{p} tells us when to stop -- when it returns true
2130 when applied to one of the seed values.
2131 @item @var{f} maps each seed value to a character. These
2132 characters are added to the base character set @var{base_cs} to
2133 form the result; @var{base_cs} defaults to the empty set.
2137 @deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2138 @deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2139 This is a fundamental constructor for character sets.
2141 @item @var{g} is used to generate a series of ``seed'' values
2142 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2143 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2144 @item @var{p} tells us when to stop -- when it returns true
2145 when applied to one of the seed values.
2146 @item @var{f} maps each seed value to a character. These
2147 characters are added to the base character set @var{base_cs} to
2148 form the result; @var{base_cs} defaults to the empty set.
2152 @deffn {Scheme Procedure} char-set-for-each proc cs
2153 @deffnx {C Function} scm_char_set_for_each (proc, cs)
2154 Apply @var{proc} to every character in the character set
2155 @var{cs}. The return value is not specified.
2158 @deffn {Scheme Procedure} char-set-map proc cs
2159 @deffnx {C Function} scm_char_set_map (proc, cs)
2160 Map the procedure @var{proc} over every character in @var{cs}.
2161 @var{proc} must be a character -> character procedure.
2164 @c ===================================================================
2166 @node Creating Character Sets
2167 @subsubsection Creating Character Sets
2169 New character sets are produced with these procedures.
2171 @deffn {Scheme Procedure} char-set-copy cs
2172 @deffnx {C Function} scm_char_set_copy (cs)
2173 Return a newly allocated character set containing all
2174 characters in @var{cs}.
2177 @deffn {Scheme Procedure} char-set . rest
2178 @deffnx {C Function} scm_char_set (rest)
2179 Return a character set containing all given characters.
2182 @deffn {Scheme Procedure} list->char-set list [base_cs]
2183 @deffnx {C Function} scm_list_to_char_set (list, base_cs)
2184 Convert the character list @var{list} to a character set. If
2185 the character set @var{base_cs} is given, the character in this
2186 set are also included in the result.
2189 @deffn {Scheme Procedure} list->char-set! list base_cs
2190 @deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2191 Convert the character list @var{list} to a character set. The
2192 characters are added to @var{base_cs} and @var{base_cs} is
2196 @deffn {Scheme Procedure} string->char-set str [base_cs]
2197 @deffnx {C Function} scm_string_to_char_set (str, base_cs)
2198 Convert the string @var{str} to a character set. If the
2199 character set @var{base_cs} is given, the characters in this
2200 set are also included in the result.
2203 @deffn {Scheme Procedure} string->char-set! str base_cs
2204 @deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2205 Convert the string @var{str} to a character set. The
2206 characters from the string are added to @var{base_cs}, and
2207 @var{base_cs} is returned.
2210 @deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2211 @deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2212 Return a character set containing every character from @var{cs}
2213 so that it satisfies @var{pred}. If provided, the characters
2214 from @var{base_cs} are added to the result.
2217 @deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2218 @deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2219 Return a character set containing every character from @var{cs}
2220 so that it satisfies @var{pred}. The characters are added to
2221 @var{base_cs} and @var{base_cs} is returned.
2224 @deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2225 @deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2226 Return a character set containing all characters whose
2227 character codes lie in the half-open range
2228 [@var{lower},@var{upper}).
2230 If @var{error} is a true value, an error is signalled if the
2231 specified range contains characters which are not contained in
2232 the implemented character range. If @var{error} is @code{#f},
2233 these characters are silently left out of the resulting
2236 The characters in @var{base_cs} are added to the result, if
2240 @deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2241 @deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2242 Return a character set containing all characters whose
2243 character codes lie in the half-open range
2244 [@var{lower},@var{upper}).
2246 If @var{error} is a true value, an error is signalled if the
2247 specified range contains characters which are not contained in
2248 the implemented character range. If @var{error} is @code{#f},
2249 these characters are silently left out of the resulting
2252 The characters are added to @var{base_cs} and @var{base_cs} is
2256 @deffn {Scheme Procedure} ->char-set x
2257 @deffnx {C Function} scm_to_char_set (x)
2258 Coerces x into a char-set. @var{x} may be a string, character or
2259 char-set. A string is converted to the set of its constituent
2260 characters; a character is converted to a singleton set; a char-set is
2264 @c ===================================================================
2266 @node Querying Character Sets
2267 @subsubsection Querying Character Sets
2269 Access the elements and other information of a character set with these
2272 @deffn {Scheme Procedure} %char-set-dump cs
2273 Returns an association list containing debugging information
2274 for @var{cs}. The association list has the following entries.
2279 The number of groups of contiguous code points the char-set
2282 A list of lists where each sublist is a range of code points
2283 and their associated characters
2285 The return value of this function cannot be relied upon to be
2286 consistent between versions of Guile and should not be used in code.
2289 @deffn {Scheme Procedure} char-set-size cs
2290 @deffnx {C Function} scm_char_set_size (cs)
2291 Return the number of elements in character set @var{cs}.
2294 @deffn {Scheme Procedure} char-set-count pred cs
2295 @deffnx {C Function} scm_char_set_count (pred, cs)
2296 Return the number of the elements int the character set
2297 @var{cs} which satisfy the predicate @var{pred}.
2300 @deffn {Scheme Procedure} char-set->list cs
2301 @deffnx {C Function} scm_char_set_to_list (cs)
2302 Return a list containing the elements of the character set
2306 @deffn {Scheme Procedure} char-set->string cs
2307 @deffnx {C Function} scm_char_set_to_string (cs)
2308 Return a string containing the elements of the character set
2309 @var{cs}. The order in which the characters are placed in the
2310 string is not defined.
2313 @deffn {Scheme Procedure} char-set-contains? cs ch
2314 @deffnx {C Function} scm_char_set_contains_p (cs, ch)
2315 Return @code{#t} iff the character @var{ch} is contained in the
2316 character set @var{cs}.
2319 @deffn {Scheme Procedure} char-set-every pred cs
2320 @deffnx {C Function} scm_char_set_every (pred, cs)
2321 Return a true value if every character in the character set
2322 @var{cs} satisfies the predicate @var{pred}.
2325 @deffn {Scheme Procedure} char-set-any pred cs
2326 @deffnx {C Function} scm_char_set_any (pred, cs)
2327 Return a true value if any character in the character set
2328 @var{cs} satisfies the predicate @var{pred}.
2331 @c ===================================================================
2333 @node Character-Set Algebra
2334 @subsubsection Character-Set Algebra
2336 Character sets can be manipulated with the common set algebra operation,
2337 such as union, complement, intersection etc. All of these procedures
2338 provide side-effecting variants, which modify their character set
2341 @deffn {Scheme Procedure} char-set-adjoin cs . rest
2342 @deffnx {C Function} scm_char_set_adjoin (cs, rest)
2343 Add all character arguments to the first argument, which must
2347 @deffn {Scheme Procedure} char-set-delete cs . rest
2348 @deffnx {C Function} scm_char_set_delete (cs, rest)
2349 Delete all character arguments from the first argument, which
2350 must be a character set.
2353 @deffn {Scheme Procedure} char-set-adjoin! cs . rest
2354 @deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2355 Add all character arguments to the first argument, which must
2359 @deffn {Scheme Procedure} char-set-delete! cs . rest
2360 @deffnx {C Function} scm_char_set_delete_x (cs, rest)
2361 Delete all character arguments from the first argument, which
2362 must be a character set.
2365 @deffn {Scheme Procedure} char-set-complement cs
2366 @deffnx {C Function} scm_char_set_complement (cs)
2367 Return the complement of the character set @var{cs}.
2370 Note that the complement of a character set is likely to contain many
2371 reserved code points (code points that are not associated with
2372 characters). It may be helpful to modify the output of
2373 @code{char-set-complement} by computing its intersection with the set
2374 of designated code points, @code{char-set:designated}.
2376 @deffn {Scheme Procedure} char-set-union . rest
2377 @deffnx {C Function} scm_char_set_union (rest)
2378 Return the union of all argument character sets.
2381 @deffn {Scheme Procedure} char-set-intersection . rest
2382 @deffnx {C Function} scm_char_set_intersection (rest)
2383 Return the intersection of all argument character sets.
2386 @deffn {Scheme Procedure} char-set-difference cs1 . rest
2387 @deffnx {C Function} scm_char_set_difference (cs1, rest)
2388 Return the difference of all argument character sets.
2391 @deffn {Scheme Procedure} char-set-xor . rest
2392 @deffnx {C Function} scm_char_set_xor (rest)
2393 Return the exclusive-or of all argument character sets.
2396 @deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2397 @deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2398 Return the difference and the intersection of all argument
2402 @deffn {Scheme Procedure} char-set-complement! cs
2403 @deffnx {C Function} scm_char_set_complement_x (cs)
2404 Return the complement of the character set @var{cs}.
2407 @deffn {Scheme Procedure} char-set-union! cs1 . rest
2408 @deffnx {C Function} scm_char_set_union_x (cs1, rest)
2409 Return the union of all argument character sets.
2412 @deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2413 @deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2414 Return the intersection of all argument character sets.
2417 @deffn {Scheme Procedure} char-set-difference! cs1 . rest
2418 @deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2419 Return the difference of all argument character sets.
2422 @deffn {Scheme Procedure} char-set-xor! cs1 . rest
2423 @deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2424 Return the exclusive-or of all argument character sets.
2427 @deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2428 @deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2429 Return the difference and the intersection of all argument
2433 @c ===================================================================
2435 @node Standard Character Sets
2436 @subsubsection Standard Character Sets
2438 In order to make the use of the character set data type and procedures
2439 useful, several predefined character set variables exist.
2445 These character sets are locale independent and are not recomputed
2446 upon a @code{setlocale} call. They contain characters from the whole
2447 range of Unicode code points. For instance, @code{char-set:letter}
2448 contains about 94,000 characters.
2450 @defvr {Scheme Variable} char-set:lower-case
2451 @defvrx {C Variable} scm_char_set_lower_case
2452 All lower-case characters.
2455 @defvr {Scheme Variable} char-set:upper-case
2456 @defvrx {C Variable} scm_char_set_upper_case
2457 All upper-case characters.
2460 @defvr {Scheme Variable} char-set:title-case
2461 @defvrx {C Variable} scm_char_set_title_case
2462 All single characters that function as if they were an upper-case
2463 letter followed by a lower-case letter.
2466 @defvr {Scheme Variable} char-set:letter
2467 @defvrx {C Variable} scm_char_set_letter
2468 All letters. This includes @code{char-set:lower-case},
2469 @code{char-set:upper-case}, @code{char-set:title-case}, and many
2470 letters that have no case at all. For example, Chinese and Japanese
2471 characters typically have no concept of case.
2474 @defvr {Scheme Variable} char-set:digit
2475 @defvrx {C Variable} scm_char_set_digit
2479 @defvr {Scheme Variable} char-set:letter+digit
2480 @defvrx {C Variable} scm_char_set_letter_and_digit
2481 The union of @code{char-set:letter} and @code{char-set:digit}.
2484 @defvr {Scheme Variable} char-set:graphic
2485 @defvrx {C Variable} scm_char_set_graphic
2486 All characters which would put ink on the paper.
2489 @defvr {Scheme Variable} char-set:printing
2490 @defvrx {C Variable} scm_char_set_printing
2491 The union of @code{char-set:graphic} and @code{char-set:whitespace}.
2494 @defvr {Scheme Variable} char-set:whitespace
2495 @defvrx {C Variable} scm_char_set_whitespace
2496 All whitespace characters.
2499 @defvr {Scheme Variable} char-set:blank
2500 @defvrx {C Variable} scm_char_set_blank
2501 All horizontal whitespace characters, which notably includes
2502 @code{#\space} and @code{#\tab}.
2505 @defvr {Scheme Variable} char-set:iso-control
2506 @defvrx {C Variable} scm_char_set_iso_control
2507 The ISO control characters are the C0 control characters (U+0000 to
2508 U+001F), delete (U+007F), and the C1 control characters (U+0080 to
2512 @defvr {Scheme Variable} char-set:punctuation
2513 @defvrx {C Variable} scm_char_set_punctuation
2514 All punctuation characters, such as the characters
2515 @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
2518 @defvr {Scheme Variable} char-set:symbol
2519 @defvrx {C Variable} scm_char_set_symbol
2520 All symbol characters, such as the characters @code{$+<=>^`|~}.
2523 @defvr {Scheme Variable} char-set:hex-digit
2524 @defvrx {C Variable} scm_char_set_hex_digit
2525 The hexadecimal digits @code{0123456789abcdefABCDEF}.
2528 @defvr {Scheme Variable} char-set:ascii
2529 @defvrx {C Variable} scm_char_set_ascii
2530 All ASCII characters.
2533 @defvr {Scheme Variable} char-set:empty
2534 @defvrx {C Variable} scm_char_set_empty
2535 The empty character set.
2538 @defvr {Scheme Variable} char-set:designated
2539 @defvrx {C Variable} scm_char_set_designated
2540 This character set contains all designated code points. This includes
2541 all the code points to which Unicode has assigned a character or other
2545 @defvr {Scheme Variable} char-set:full
2546 @defvrx {C Variable} scm_char_set_full
2547 This character set contains all possible code points. This includes
2548 both designated and reserved code points.
2555 Strings are fixed-length sequences of characters. They can be created
2556 by calling constructor procedures, but they can also literally get
2557 entered at the @acronym{REPL} or in Scheme source files.
2559 @c Guile provides a rich set of string processing procedures, because text
2560 @c handling is very important when Guile is used as a scripting language.
2562 Strings always carry the information about how many characters they are
2563 composed of with them, so there is no special end-of-string character,
2564 like in C. That means that Scheme strings can contain any character,
2565 even the @samp{#\nul} character @samp{\0}.
2567 To use strings efficiently, you need to know a bit about how Guile
2568 implements them. In Guile, a string consists of two parts, a head and
2569 the actual memory where the characters are stored. When a string (or
2570 a substring of it) is copied, only a new head gets created, the memory
2571 is usually not copied. The two heads start out pointing to the same
2574 When one of these two strings is modified, as with @code{string-set!},
2575 their common memory does get copied so that each string has its own
2576 memory and modifying one does not accidentally modify the other as well.
2577 Thus, Guile's strings are `copy on write'; the actual copying of their
2578 memory is delayed until one string is written to.
2580 This implementation makes functions like @code{substring} very
2581 efficient in the common case that no modifications are done to the
2584 If you do know that your strings are getting modified right away, you
2585 can use @code{substring/copy} instead of @code{substring}. This
2586 function performs the copy immediately at the time of creation. This
2587 is more efficient, especially in a multi-threaded program. Also,
2588 @code{substring/copy} can avoid the problem that a short substring
2589 holds on to the memory of a very large original string that could
2590 otherwise be recycled.
2592 If you want to avoid the copy altogether, so that modifications of one
2593 string show up in the other, you can use @code{substring/shared}. The
2594 strings created by this procedure are called @dfn{mutation sharing
2595 substrings} since the substring and the original string share
2596 modifications to each other.
2598 If you want to prevent modifications, use @code{substring/read-only}.
2600 Guile provides all procedures of SRFI-13 and a few more.
2603 * String Syntax:: Read syntax for strings.
2604 * String Predicates:: Testing strings for certain properties.
2605 * String Constructors:: Creating new string objects.
2606 * List/String Conversion:: Converting from/to lists of characters.
2607 * String Selection:: Select portions from strings.
2608 * String Modification:: Modify parts or whole strings.
2609 * String Comparison:: Lexicographic ordering predicates.
2610 * String Searching:: Searching in strings.
2611 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2612 * Reversing and Appending Strings:: Appending strings to form a new string.
2613 * Mapping Folding and Unfolding:: Iterating over strings.
2614 * Miscellaneous String Operations:: Replicating, insertion, parsing, ...
2615 * Conversion to/from C::
2616 * String Internals:: The storage strategy for strings.
2620 @subsubsection String Read Syntax
2622 @c In the following @code is used to get a good font in TeX etc, but
2623 @c is omitted for Info format, so as not to risk any confusion over
2624 @c whether surrounding ` ' quotes are part of the escape or are
2625 @c special in a string (they're not).
2627 The read syntax for strings is an arbitrarily long sequence of
2628 characters enclosed in double quotes (@nicode{"}).
2630 Backslash is an escape character and can be used to insert the following
2631 special characters. @nicode{\"} and @nicode{\\} are R5RS standard, the
2632 next seven are R6RS standard --- notice they follow C syntax --- and the
2633 remaining four are Guile extensions.
2637 Backslash character.
2640 Double quote character (an unescaped @nicode{"} is otherwise the end
2644 Bell character (ASCII 7).
2647 Formfeed character (ASCII 12).
2650 Newline character (ASCII 10).
2653 Carriage return character (ASCII 13).
2656 Tab character (ASCII 9).
2659 Vertical tab character (ASCII 11).
2662 Backspace character (ASCII 8).
2665 NUL character (ASCII 0).
2668 Character code given by two hexadecimal digits. For example
2669 @nicode{\x7f} for an ASCII DEL (127).
2671 @item @nicode{\uHHHH}
2672 Character code given by four hexadecimal digits. For example
2673 @nicode{\u0100} for a capital A with macron (U+0100).
2675 @item @nicode{\UHHHHHH}
2676 Character code given by six hexadecimal digits. For example
2681 The following are examples of string literals:
2690 The three escape sequences @code{\xHH}, @code{\uHHHH} and @code{\UHHHHHH} were
2691 chosen to not break compatibility with code written for previous versions of
2692 Guile. The R6RS specification suggests a different, incompatible syntax for hex
2693 escapes: @code{\xHHHH;} -- a character code followed by one to eight hexadecimal
2694 digits terminated with a semicolon. If this escape format is desired instead,
2695 it can be enabled with the reader option @code{r6rs-hex-escapes}.
2698 (read-enable 'r6rs-hex-escapes)
2701 Enabling this option will also change the hex escape format for characters.
2702 More on character escapes can be found at (@pxref{Characters}). More on
2703 reader options in general can be found at (@pxref{Reader options}).
2705 @node String Predicates
2706 @subsubsection String Predicates
2708 The following procedures can be used to check whether a given string
2709 fulfills some specified property.
2712 @deffn {Scheme Procedure} string? obj
2713 @deffnx {C Function} scm_string_p (obj)
2714 Return @code{#t} if @var{obj} is a string, else @code{#f}.
2717 @deftypefn {C Function} int scm_is_string (SCM obj)
2718 Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2721 @deffn {Scheme Procedure} string-null? str
2722 @deffnx {C Function} scm_string_null_p (str)
2723 Return @code{#t} if @var{str}'s length is zero, and
2724 @code{#f} otherwise.
2726 (string-null? "") @result{} #t
2728 (string-null? y) @result{} #f
2732 @deffn {Scheme Procedure} string-any char_pred s [start [end]]
2733 @deffnx {C Function} scm_string_any (char_pred, s, start, end)
2734 Check if @var{char_pred} is true for any character in string @var{s}.
2736 @var{char_pred} can be a character to check for any equal to that, or
2737 a character set (@pxref{Character Sets}) to check for any in that set,
2738 or a predicate procedure to call.
2740 For a procedure, calls @code{(@var{char_pred} c)} are made
2741 successively on the characters from @var{start} to @var{end}. If
2742 @var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2743 stops and that return value is the return from @code{string-any}. The
2744 call on the last character (ie.@: at @math{@var{end}-1}), if that
2745 point is reached, is a tail call.
2747 If there are no characters in @var{s} (ie.@: @var{start} equals
2748 @var{end}) then the return is @code{#f}.
2751 @deffn {Scheme Procedure} string-every char_pred s [start [end]]
2752 @deffnx {C Function} scm_string_every (char_pred, s, start, end)
2753 Check if @var{char_pred} is true for every character in string
2756 @var{char_pred} can be a character to check for every character equal
2757 to that, or a character set (@pxref{Character Sets}) to check for
2758 every character being in that set, or a predicate procedure to call.
2760 For a procedure, calls @code{(@var{char_pred} c)} are made
2761 successively on the characters from @var{start} to @var{end}. If
2762 @var{char_pred} returns @code{#f}, @code{string-every} stops and
2763 returns @code{#f}. The call on the last character (ie.@: at
2764 @math{@var{end}-1}), if that point is reached, is a tail call and the
2765 return from that call is the return from @code{string-every}.
2767 If there are no characters in @var{s} (ie.@: @var{start} equals
2768 @var{end}) then the return is @code{#t}.
2771 @node String Constructors
2772 @subsubsection String Constructors
2774 The string constructor procedures create new string objects, possibly
2775 initializing them with some specified character data. See also
2776 @xref{String Selection}, for ways to create strings from existing
2779 @c FIXME::martin: list->string belongs into `List/String Conversion'
2781 @deffn {Scheme Procedure} string char@dots{}
2783 Return a newly allocated string made from the given character
2787 (string #\x #\y #\z) @result{} "xyz"
2788 (string) @result{} ""
2792 @deffn {Scheme Procedure} list->string lst
2793 @deffnx {C Function} scm_string (lst)
2794 @rnindex list->string
2795 Return a newly allocated string made from a list of characters.
2798 (list->string '(#\a #\b #\c)) @result{} "abc"
2802 @deffn {Scheme Procedure} reverse-list->string lst
2803 @deffnx {C Function} scm_reverse_list_to_string (lst)
2804 Return a newly allocated string made from a list of characters, in
2808 (reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2812 @rnindex make-string
2813 @deffn {Scheme Procedure} make-string k [chr]
2814 @deffnx {C Function} scm_make_string (k, chr)
2815 Return a newly allocated string of
2816 length @var{k}. If @var{chr} is given, then all elements of
2817 the string are initialized to @var{chr}, otherwise the contents
2818 of the @var{string} are unspecified.
2821 @deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2822 Like @code{scm_make_string}, but expects the length as a
2826 @deffn {Scheme Procedure} string-tabulate proc len
2827 @deffnx {C Function} scm_string_tabulate (proc, len)
2828 @var{proc} is an integer->char procedure. Construct a string
2829 of size @var{len} by applying @var{proc} to each index to
2830 produce the corresponding string element. The order in which
2831 @var{proc} is applied to the indices is not specified.
2834 @deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2835 @deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2836 Append the string in the string list @var{ls}, using the string
2837 @var{delim} as a delimiter between the elements of @var{ls}.
2838 @var{grammar} is a symbol which specifies how the delimiter is
2839 placed between the strings, and defaults to the symbol
2844 Insert the separator between list elements. An empty string
2845 will produce an empty list.
2847 Like @code{infix}, but will raise an error if given the empty
2850 Insert the separator after every list element.
2852 Insert the separator before each list element.
2856 @node List/String Conversion
2857 @subsubsection List/String conversion
2859 When processing strings, it is often convenient to first convert them
2860 into a list representation by using the procedure @code{string->list},
2861 work with the resulting list, and then convert it back into a string.
2862 These procedures are useful for similar tasks.
2864 @rnindex string->list
2865 @deffn {Scheme Procedure} string->list str [start [end]]
2866 @deffnx {C Function} scm_substring_to_list (str, start, end)
2867 @deffnx {C Function} scm_string_to_list (str)
2868 Convert the string @var{str} into a list of characters.
2871 @deffn {Scheme Procedure} string-split str chr
2872 @deffnx {C Function} scm_string_split (str, chr)
2873 Split the string @var{str} into the a list of the substrings delimited
2874 by appearances of the character @var{chr}. Note that an empty substring
2875 between separator characters will result in an empty string in the
2879 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2881 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
2883 (string-split "::" #\:)
2887 (string-split "" #\:)
2894 @node String Selection
2895 @subsubsection String Selection
2897 Portions of strings can be extracted by these procedures.
2898 @code{string-ref} delivers individual characters whereas
2899 @code{substring} can be used to extract substrings from longer strings.
2901 @rnindex string-length
2902 @deffn {Scheme Procedure} string-length string
2903 @deffnx {C Function} scm_string_length (string)
2904 Return the number of characters in @var{string}.
2907 @deftypefn {C Function} size_t scm_c_string_length (SCM str)
2908 Return the number of characters in @var{str} as a @code{size_t}.
2912 @deffn {Scheme Procedure} string-ref str k
2913 @deffnx {C Function} scm_string_ref (str, k)
2914 Return character @var{k} of @var{str} using zero-origin
2915 indexing. @var{k} must be a valid index of @var{str}.
2918 @deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2919 Return character @var{k} of @var{str} using zero-origin
2920 indexing. @var{k} must be a valid index of @var{str}.
2923 @rnindex string-copy
2924 @deffn {Scheme Procedure} string-copy str [start [end]]
2925 @deffnx {C Function} scm_substring_copy (str, start, end)
2926 @deffnx {C Function} scm_string_copy (str)
2927 Return a copy of the given string @var{str}.
2929 The returned string shares storage with @var{str} initially, but it is
2930 copied as soon as one of the two strings is modified.
2934 @deffn {Scheme Procedure} substring str start [end]
2935 @deffnx {C Function} scm_substring (str, start, end)
2936 Return a new string formed from the characters
2937 of @var{str} beginning with index @var{start} (inclusive) and
2938 ending with index @var{end} (exclusive).
2939 @var{str} must be a string, @var{start} and @var{end} must be
2940 exact integers satisfying:
2942 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
2944 The returned string shares storage with @var{str} initially, but it is
2945 copied as soon as one of the two strings is modified.
2948 @deffn {Scheme Procedure} substring/shared str start [end]
2949 @deffnx {C Function} scm_substring_shared (str, start, end)
2950 Like @code{substring}, but the strings continue to share their storage
2951 even if they are modified. Thus, modifications to @var{str} show up
2952 in the new string, and vice versa.
2955 @deffn {Scheme Procedure} substring/copy str start [end]
2956 @deffnx {C Function} scm_substring_copy (str, start, end)
2957 Like @code{substring}, but the storage for the new string is copied
2961 @deffn {Scheme Procedure} substring/read-only str start [end]
2962 @deffnx {C Function} scm_substring_read_only (str, start, end)
2963 Like @code{substring}, but the resulting string can not be modified.
2966 @deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2967 @deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2968 @deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2969 @deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
2970 Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2973 @deffn {Scheme Procedure} string-take s n
2974 @deffnx {C Function} scm_string_take (s, n)
2975 Return the @var{n} first characters of @var{s}.
2978 @deffn {Scheme Procedure} string-drop s n
2979 @deffnx {C Function} scm_string_drop (s, n)
2980 Return all but the first @var{n} characters of @var{s}.
2983 @deffn {Scheme Procedure} string-take-right s n
2984 @deffnx {C Function} scm_string_take_right (s, n)
2985 Return the @var{n} last characters of @var{s}.
2988 @deffn {Scheme Procedure} string-drop-right s n
2989 @deffnx {C Function} scm_string_drop_right (s, n)
2990 Return all but the last @var{n} characters of @var{s}.
2993 @deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
2994 @deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
2995 @deffnx {C Function} scm_string_pad (s, len, chr, start, end)
2996 @deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
2997 Take characters @var{start} to @var{end} from the string @var{s} and
2998 either pad with @var{char} or truncate them to give @var{len}
3001 @code{string-pad} pads or truncates on the left, so for example
3004 (string-pad "x" 3) @result{} " x"
3005 (string-pad "abcde" 3) @result{} "cde"
3008 @code{string-pad-right} pads or truncates on the right, so for example
3011 (string-pad-right "x" 3) @result{} "x "
3012 (string-pad-right "abcde" 3) @result{} "abc"
3016 @deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
3017 @deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
3018 @deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
3019 @deffnx {C Function} scm_string_trim (s, char_pred, start, end)
3020 @deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
3021 @deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
3022 Trim occurrences of @var{char_pred} from the ends of @var{s}.
3024 @code{string-trim} trims @var{char_pred} characters from the left
3025 (start) of the string, @code{string-trim-right} trims them from the
3026 right (end) of the string, @code{string-trim-both} trims from both
3029 @var{char_pred} can be a character, a character set, or a predicate
3030 procedure to call on each character. If @var{char_pred} is not given
3031 the default is whitespace as per @code{char-set:whitespace}
3032 (@pxref{Standard Character Sets}).
3035 (string-trim " x ") @result{} "x "
3036 (string-trim-right "banana" #\a) @result{} "banan"
3037 (string-trim-both ".,xy:;" char-set:punctuation)
3039 (string-trim-both "xyzzy" (lambda (c)
3046 @node String Modification
3047 @subsubsection String Modification
3049 These procedures are for modifying strings in-place. This means that the
3050 result of the operation is not a new string; instead, the original string's
3051 memory representation is modified.
3053 @rnindex string-set!
3054 @deffn {Scheme Procedure} string-set! str k chr
3055 @deffnx {C Function} scm_string_set_x (str, k, chr)
3056 Store @var{chr} in element @var{k} of @var{str} and return
3057 an unspecified value. @var{k} must be a valid index of
3061 @deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
3062 Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
3065 @rnindex string-fill!
3066 @deffn {Scheme Procedure} string-fill! str chr [start [end]]
3067 @deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
3068 @deffnx {C Function} scm_string_fill_x (str, chr)
3069 Stores @var{chr} in every element of the given @var{str} and
3070 returns an unspecified value.
3073 @deffn {Scheme Procedure} substring-fill! str start end fill
3074 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
3075 Change every character in @var{str} between @var{start} and
3076 @var{end} to @var{fill}.
3079 (define y "abcdefg")
3080 (substring-fill! y 1 3 #\r)
3086 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
3087 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
3088 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
3089 into @var{str2} beginning at position @var{start2}.
3090 @var{str1} and @var{str2} can be the same string.
3093 @deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
3094 @deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
3095 Copy the sequence of characters from index range [@var{start},
3096 @var{end}) in string @var{s} to string @var{target}, beginning
3097 at index @var{tstart}. The characters are copied left-to-right
3098 or right-to-left as needed -- the copy is guaranteed to work,
3099 even if @var{target} and @var{s} are the same string. It is an
3100 error if the copy operation runs off the end of the target
3105 @node String Comparison
3106 @subsubsection String Comparison
3108 The procedures in this section are similar to the character ordering
3109 predicates (@pxref{Characters}), but are defined on character sequences.
3111 The first set is specified in R5RS and has names that end in @code{?}.
3112 The second set is specified in SRFI-13 and the names have not ending
3115 The predicates ending in @code{-ci} ignore the character case
3116 when comparing strings. For now, case-insensitive comparison is done
3117 using the R5RS rules, where every lower-case character that has a
3118 single character upper-case form is converted to uppercase before
3119 comparison. See @xref{Text Collation, the @code{(ice-9
3120 i18n)} module}, for locale-dependent string comparison.
3123 @deffn {Scheme Procedure} string=? [s1 [s2 . rest]]
3124 @deffnx {C Function} scm_i_string_equal_p (s1, s2, rest)
3125 Lexicographic equality predicate; return @code{#t} if the two
3126 strings are the same length and contain the same characters in
3127 the same positions, otherwise return @code{#f}.
3129 The procedure @code{string-ci=?} treats upper and lower case
3130 letters as though they were the same character, but
3131 @code{string=?} treats upper and lower case as distinct
3136 @deffn {Scheme Procedure} string<? [s1 [s2 . rest]]
3137 @deffnx {C Function} scm_i_string_less_p (s1, s2, rest)
3138 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3139 is lexicographically less than @var{s2}.
3143 @deffn {Scheme Procedure} string<=? [s1 [s2 . rest]]
3144 @deffnx {C Function} scm_i_string_leq_p (s1, s2, rest)
3145 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3146 is lexicographically less than or equal to @var{s2}.
3150 @deffn {Scheme Procedure} string>? [s1 [s2 . rest]]
3151 @deffnx {C Function} scm_i_string_gr_p (s1, s2, rest)
3152 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3153 is lexicographically greater than @var{s2}.
3157 @deffn {Scheme Procedure} string>=? [s1 [s2 . rest]]
3158 @deffnx {C Function} scm_i_string_geq_p (s1, s2, rest)
3159 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3160 is lexicographically greater than or equal to @var{s2}.
3163 @rnindex string-ci=?
3164 @deffn {Scheme Procedure} string-ci=? [s1 [s2 . rest]]
3165 @deffnx {C Function} scm_i_string_ci_equal_p (s1, s2, rest)
3166 Case-insensitive string equality predicate; return @code{#t} if
3167 the two strings are the same length and their component
3168 characters match (ignoring case) at each position; otherwise
3172 @rnindex string-ci<?
3173 @deffn {Scheme Procedure} string-ci<? [s1 [s2 . rest]]
3174 @deffnx {C Function} scm_i_string_ci_less_p (s1, s2, rest)
3175 Case insensitive lexicographic ordering predicate; return
3176 @code{#t} if @var{s1} is lexicographically less than @var{s2}
3181 @deffn {Scheme Procedure} string-ci<=? [s1 [s2 . rest]]
3182 @deffnx {C Function} scm_i_string_ci_leq_p (s1, s2, rest)
3183 Case insensitive lexicographic ordering predicate; return
3184 @code{#t} if @var{s1} is lexicographically less than or equal
3185 to @var{s2} regardless of case.
3188 @rnindex string-ci>?
3189 @deffn {Scheme Procedure} string-ci>? [s1 [s2 . rest]]
3190 @deffnx {C Function} scm_i_string_ci_gr_p (s1, s2, rest)
3191 Case insensitive lexicographic ordering predicate; return
3192 @code{#t} if @var{s1} is lexicographically greater than
3193 @var{s2} regardless of case.
3196 @rnindex string-ci>=?
3197 @deffn {Scheme Procedure} string-ci>=? [s1 [s2 . rest]]
3198 @deffnx {C Function} scm_i_string_ci_geq_p (s1, s2, rest)
3199 Case insensitive lexicographic ordering predicate; return
3200 @code{#t} if @var{s1} is lexicographically greater than or
3201 equal to @var{s2} regardless of case.
3204 @deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3205 @deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3206 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3207 mismatch index, depending upon whether @var{s1} is less than,
3208 equal to, or greater than @var{s2}. The mismatch index is the
3209 largest index @var{i} such that for every 0 <= @var{j} <
3210 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3211 @var{i} is the first position that does not match.
3214 @deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3215 @deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3216 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3217 mismatch index, depending upon whether @var{s1} is less than,
3218 equal to, or greater than @var{s2}. The mismatch index is the
3219 largest index @var{i} such that for every 0 <= @var{j} <
3220 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3221 @var{i} is the first position where the lowercased letters
3226 @deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3227 @deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3228 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3232 @deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3233 @deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3234 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3238 @deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3239 @deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3240 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3241 true value otherwise.
3244 @deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3245 @deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3246 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3247 true value otherwise.
3250 @deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3251 @deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3252 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3256 @deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3257 @deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3258 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3262 @deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3263 @deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3264 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3265 value otherwise. The character comparison is done
3269 @deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3270 @deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3271 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3272 value otherwise. The character comparison is done
3276 @deffn {Scheme Procedure} string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
3277 @deffnx {C Function} scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
3278 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3279 true value otherwise. The character comparison is done
3283 @deffn {Scheme Procedure} string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
3284 @deffnx {C Function} scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
3285 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3286 true value otherwise. The character comparison is done
3290 @deffn {Scheme Procedure} string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
3291 @deffnx {C Function} scm_string_ci_le (s1, s2, start1, end1, start2, end2)
3292 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3293 value otherwise. The character comparison is done
3297 @deffn {Scheme Procedure} string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
3298 @deffnx {C Function} scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
3299 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3300 otherwise. The character comparison is done
3304 @deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3305 @deffnx {C Function} scm_substring_hash (s, bound, start, end)
3306 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).
3309 @deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3310 @deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3311 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).
3314 Because the same visual appearance of an abstract Unicode character can
3315 be obtained via multiple sequences of Unicode characters, even the
3316 case-insensitive string comparison functions described above may return
3317 @code{#f} when presented with strings containing different
3318 representations of the same character. For example, the Unicode
3319 character ``LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE'' can be
3320 represented with a single character (U+1E69) or by the character ``LATIN
3321 SMALL LETTER S'' (U+0073) followed by the combining marks ``COMBINING
3322 DOT BELOW'' (U+0323) and ``COMBINING DOT ABOVE'' (U+0307).
3324 For this reason, it is often desirable to ensure that the strings
3325 to be compared are using a mutually consistent representation for every
3326 character. The Unicode standard defines two methods of normalizing the
3327 contents of strings: Decomposition, which breaks composite characters
3328 into a set of constituent characters with an ordering defined by the
3329 Unicode Standard; and composition, which performs the converse.
3331 There are two decomposition operations. ``Canonical decomposition''
3332 produces character sequences that share the same visual appearance as
3333 the original characters, while ``compatiblity decomposition'' produces
3334 ones whose visual appearances may differ from the originals but which
3335 represent the same abstract character.
3337 These operations are encapsulated in the following set of normalization
3342 Characters are decomposed to their canonical forms.
3345 Characters are decomposed to their compatibility forms.
3348 Characters are decomposed to their canonical forms, then composed.
3351 Characters are decomposed to their compatibility forms, then composed.
3355 The functions below put their arguments into one of the forms described
3358 @deffn {Scheme Procedure} string-normalize-nfd s
3359 @deffnx {C Function} scm_string_normalize_nfd (s)
3360 Return the @code{NFD} normalized form of @var{s}.
3363 @deffn {Scheme Procedure} string-normalize-nfkd s
3364 @deffnx {C Function} scm_string_normalize_nfkd (s)
3365 Return the @code{NFKD} normalized form of @var{s}.
3368 @deffn {Scheme Procedure} string-normalize-nfc s
3369 @deffnx {C Function} scm_string_normalize_nfc (s)
3370 Return the @code{NFC} normalized form of @var{s}.
3373 @deffn {Scheme Procedure} string-normalize-nfkc s
3374 @deffnx {C Function} scm_string_normalize_nfkc (s)
3375 Return the @code{NFKC} normalized form of @var{s}.
3378 @node String Searching
3379 @subsubsection String Searching
3381 @deffn {Scheme Procedure} string-index s char_pred [start [end]]
3382 @deffnx {C Function} scm_string_index (s, char_pred, start, end)
3383 Search through the string @var{s} from left to right, returning
3384 the index of the first occurrence of a character which
3388 equals @var{char_pred}, if it is character,
3391 satisfies the predicate @var{char_pred}, if it is a procedure,
3394 is in the set @var{char_pred}, if it is a character set.
3398 @deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3399 @deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3400 Search through the string @var{s} from right to left, returning
3401 the index of the last occurrence of a character which
3405 equals @var{char_pred}, if it is character,
3408 satisfies the predicate @var{char_pred}, if it is a procedure,
3411 is in the set if @var{char_pred} is a character set.
3415 @deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3416 @deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3417 Return the length of the longest common prefix of the two
3421 @deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3422 @deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3423 Return the length of the longest common prefix of the two
3424 strings, ignoring character case.
3427 @deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3428 @deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3429 Return the length of the longest common suffix of the two
3433 @deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3434 @deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3435 Return the length of the longest common suffix of the two
3436 strings, ignoring character case.
3439 @deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3440 @deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3441 Is @var{s1} a prefix of @var{s2}?
3444 @deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3445 @deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3446 Is @var{s1} a prefix of @var{s2}, ignoring character case?
3449 @deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3450 @deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3451 Is @var{s1} a suffix of @var{s2}?
3454 @deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3455 @deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3456 Is @var{s1} a suffix of @var{s2}, ignoring character case?
3459 @deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3460 @deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3461 Search through the string @var{s} from right to left, returning
3462 the index of the last occurrence of a character which
3466 equals @var{char_pred}, if it is character,
3469 satisfies the predicate @var{char_pred}, if it is a procedure,
3472 is in the set if @var{char_pred} is a character set.
3476 @deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3477 @deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3478 Search through the string @var{s} from left to right, returning
3479 the index of the first occurrence of a character which
3483 does not equal @var{char_pred}, if it is character,
3486 does not satisfy the predicate @var{char_pred}, if it is a
3490 is not in the set if @var{char_pred} is a character set.
3494 @deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3495 @deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3496 Search through the string @var{s} from right to left, returning
3497 the index of the last occurrence of a character which
3501 does not equal @var{char_pred}, if it is character,
3504 does not satisfy the predicate @var{char_pred}, if it is a
3508 is not in the set if @var{char_pred} is a character set.
3512 @deffn {Scheme Procedure} string-count s char_pred [start [end]]
3513 @deffnx {C Function} scm_string_count (s, char_pred, start, end)
3514 Return the count of the number of characters in the string
3519 equals @var{char_pred}, if it is character,
3522 satisfies the predicate @var{char_pred}, if it is a procedure.
3525 is in the set @var{char_pred}, if it is a character set.
3529 @deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3530 @deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3531 Does string @var{s1} contain string @var{s2}? Return the index
3532 in @var{s1} where @var{s2} occurs as a substring, or false.
3533 The optional start/end indices restrict the operation to the
3534 indicated substrings.
3537 @deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3538 @deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3539 Does string @var{s1} contain string @var{s2}? Return the index
3540 in @var{s1} where @var{s2} occurs as a substring, or false.
3541 The optional start/end indices restrict the operation to the
3542 indicated substrings. Character comparison is done
3546 @node Alphabetic Case Mapping
3547 @subsubsection Alphabetic Case Mapping
3549 These are procedures for mapping strings to their upper- or lower-case
3550 equivalents, respectively, or for capitalizing strings.
3552 They use the basic case mapping rules for Unicode characters. No
3553 special language or context rules are considered. The resulting strings
3554 are guaranteed to be the same length as the input strings.
3556 @xref{Character Case Mapping, the @code{(ice-9
3557 i18n)} module}, for locale-dependent case conversions.
3559 @deffn {Scheme Procedure} string-upcase str [start [end]]
3560 @deffnx {C Function} scm_substring_upcase (str, start, end)
3561 @deffnx {C Function} scm_string_upcase (str)
3562 Upcase every character in @code{str}.
3565 @deffn {Scheme Procedure} string-upcase! str [start [end]]
3566 @deffnx {C Function} scm_substring_upcase_x (str, start, end)
3567 @deffnx {C Function} scm_string_upcase_x (str)
3568 Destructively upcase every character in @code{str}.
3578 @deffn {Scheme Procedure} string-downcase str [start [end]]
3579 @deffnx {C Function} scm_substring_downcase (str, start, end)
3580 @deffnx {C Function} scm_string_downcase (str)
3581 Downcase every character in @var{str}.
3584 @deffn {Scheme Procedure} string-downcase! str [start [end]]
3585 @deffnx {C Function} scm_substring_downcase_x (str, start, end)
3586 @deffnx {C Function} scm_string_downcase_x (str)
3587 Destructively downcase every character in @var{str}.
3592 (string-downcase! y)
3599 @deffn {Scheme Procedure} string-capitalize str
3600 @deffnx {C Function} scm_string_capitalize (str)
3601 Return a freshly allocated string with the characters in
3602 @var{str}, where the first character of every word is
3606 @deffn {Scheme Procedure} string-capitalize! str
3607 @deffnx {C Function} scm_string_capitalize_x (str)
3608 Upcase the first character of every word in @var{str}
3609 destructively and return @var{str}.
3612 y @result{} "hello world"
3613 (string-capitalize! y) @result{} "Hello World"
3614 y @result{} "Hello World"
3618 @deffn {Scheme Procedure} string-titlecase str [start [end]]
3619 @deffnx {C Function} scm_string_titlecase (str, start, end)
3620 Titlecase every first character in a word in @var{str}.
3623 @deffn {Scheme Procedure} string-titlecase! str [start [end]]
3624 @deffnx {C Function} scm_string_titlecase_x (str, start, end)
3625 Destructively titlecase every first character in a word in
3629 @node Reversing and Appending Strings
3630 @subsubsection Reversing and Appending Strings
3632 @deffn {Scheme Procedure} string-reverse str [start [end]]
3633 @deffnx {C Function} scm_string_reverse (str, start, end)
3634 Reverse the string @var{str}. The optional arguments
3635 @var{start} and @var{end} delimit the region of @var{str} to
3639 @deffn {Scheme Procedure} string-reverse! str [start [end]]
3640 @deffnx {C Function} scm_string_reverse_x (str, start, end)
3641 Reverse the string @var{str} in-place. The optional arguments
3642 @var{start} and @var{end} delimit the region of @var{str} to
3643 operate on. The return value is unspecified.
3646 @rnindex string-append
3647 @deffn {Scheme Procedure} string-append . args
3648 @deffnx {C Function} scm_string_append (args)
3649 Return a newly allocated string whose characters form the
3650 concatenation of the given strings, @var{args}.
3654 (string-append h "world"))
3655 @result{} "hello world"
3659 @deffn {Scheme Procedure} string-append/shared . rest
3660 @deffnx {C Function} scm_string_append_shared (rest)
3661 Like @code{string-append}, but the result may share memory
3662 with the argument strings.
3665 @deffn {Scheme Procedure} string-concatenate ls
3666 @deffnx {C Function} scm_string_concatenate (ls)
3667 Append the elements of @var{ls} (which must be strings)
3668 together into a single string. Guaranteed to return a freshly
3672 @deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3673 @deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3674 Without optional arguments, this procedure is equivalent to
3677 (string-concatenate (reverse ls))
3680 If the optional argument @var{final_string} is specified, it is
3681 consed onto the beginning to @var{ls} before performing the
3682 list-reverse and string-concatenate operations. If @var{end}
3683 is given, only the characters of @var{final_string} up to index
3686 Guaranteed to return a freshly allocated string.
3689 @deffn {Scheme Procedure} string-concatenate/shared ls
3690 @deffnx {C Function} scm_string_concatenate_shared (ls)
3691 Like @code{string-concatenate}, but the result may share memory
3692 with the strings in the list @var{ls}.
3695 @deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3696 @deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3697 Like @code{string-concatenate-reverse}, but the result may
3698 share memory with the strings in the @var{ls} arguments.
3701 @node Mapping Folding and Unfolding
3702 @subsubsection Mapping, Folding, and Unfolding
3704 @deffn {Scheme Procedure} string-map proc s [start [end]]
3705 @deffnx {C Function} scm_string_map (proc, s, start, end)
3706 @var{proc} is a char->char procedure, it is mapped over
3707 @var{s}. The order in which the procedure is applied to the
3708 string elements is not specified.
3711 @deffn {Scheme Procedure} string-map! proc s [start [end]]
3712 @deffnx {C Function} scm_string_map_x (proc, s, start, end)
3713 @var{proc} is a char->char procedure, it is mapped over
3714 @var{s}. The order in which the procedure is applied to the
3715 string elements is not specified. The string @var{s} is
3716 modified in-place, the return value is not specified.
3719 @deffn {Scheme Procedure} string-for-each proc s [start [end]]
3720 @deffnx {C Function} scm_string_for_each (proc, s, start, end)
3721 @var{proc} is mapped over @var{s} in left-to-right order. The
3722 return value is not specified.
3725 @deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3726 @deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
3727 Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3730 For example, to change characters to alternately upper and lower case,
3733 (define str (string-copy "studly"))
3734 (string-for-each-index
3737 ((if (even? i) char-upcase char-downcase)
3738 (string-ref str i))))
3740 str @result{} "StUdLy"
3744 @deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3745 @deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3746 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3747 as the terminating element, from left to right. @var{kons}
3748 must expect two arguments: The actual character and the last
3749 result of @var{kons}' application.
3752 @deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3753 @deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3754 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3755 as the terminating element, from right to left. @var{kons}
3756 must expect two arguments: The actual character and the last
3757 result of @var{kons}' application.
3760 @deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3761 @deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3763 @item @var{g} is used to generate a series of @emph{seed}
3764 values from the initial @var{seed}: @var{seed}, (@var{g}
3765 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3767 @item @var{p} tells us when to stop -- when it returns true
3768 when applied to one of these seed values.
3769 @item @var{f} maps each seed value to the corresponding
3770 character in the result string. These chars are assembled
3771 into the string in a left-to-right order.
3772 @item @var{base} is the optional initial/leftmost portion
3773 of the constructed string; it default to the empty
3775 @item @var{make_final} is applied to the terminal seed
3776 value (on which @var{p} returns true) to produce
3777 the final/rightmost portion of the constructed string.
3778 The default is nothing extra.
3782 @deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3783 @deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3785 @item @var{g} is used to generate a series of @emph{seed}
3786 values from the initial @var{seed}: @var{seed}, (@var{g}
3787 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3789 @item @var{p} tells us when to stop -- when it returns true
3790 when applied to one of these seed values.
3791 @item @var{f} maps each seed value to the corresponding
3792 character in the result string. These chars are assembled
3793 into the string in a right-to-left order.
3794 @item @var{base} is the optional initial/rightmost portion
3795 of the constructed string; it default to the empty
3797 @item @var{make_final} is applied to the terminal seed
3798 value (on which @var{p} returns true) to produce
3799 the final/leftmost portion of the constructed string.
3800 It defaults to @code{(lambda (x) )}.
3804 @node Miscellaneous String Operations
3805 @subsubsection Miscellaneous String Operations
3807 @deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3808 @deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3809 This is the @emph{extended substring} procedure that implements
3810 replicated copying of a substring of some string.
3812 @var{s} is a string, @var{start} and @var{end} are optional
3813 arguments that demarcate a substring of @var{s}, defaulting to
3814 0 and the length of @var{s}. Replicate this substring up and
3815 down index space, in both the positive and negative directions.
3816 @code{xsubstring} returns the substring of this string
3817 beginning at index @var{from}, and ending at @var{to}, which
3818 defaults to @var{from} + (@var{end} - @var{start}).
3821 @deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3822 @deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3823 Exactly the same as @code{xsubstring}, but the extracted text
3824 is written into the string @var{target} starting at index
3825 @var{tstart}. The operation is not defined if @code{(eq?
3826 @var{target} @var{s})} or these arguments share storage -- you
3827 cannot copy a string on top of itself.
3830 @deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3831 @deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3832 Return the string @var{s1}, but with the characters
3833 @var{start1} @dots{} @var{end1} replaced by the characters
3834 @var{start2} @dots{} @var{end2} from @var{s2}.
3837 @deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3838 @deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3839 Split the string @var{s} into a list of substrings, where each
3840 substring is a maximal non-empty contiguous sequence of
3841 characters from the character set @var{token_set}, which
3842 defaults to @code{char-set:graphic}.
3843 If @var{start} or @var{end} indices are provided, they restrict
3844 @code{string-tokenize} to operating on the indicated substring
3848 @deffn {Scheme Procedure} string-filter s char_pred [start [end]]
3849 @deffnx {C Function} scm_string_filter (s, char_pred, start, end)
3850 Filter the string @var{s}, retaining only those characters which
3851 satisfy @var{char_pred}.
3853 If @var{char_pred} is a procedure, it is applied to each character as
3854 a predicate, if it is a character, it is tested for equality and if it
3855 is a character set, it is tested for membership.
3858 @deffn {Scheme Procedure} string-delete s char_pred [start [end]]
3859 @deffnx {C Function} scm_string_delete (s, char_pred, start, end)
3860 Delete characters satisfying @var{char_pred} from @var{s}.
3862 If @var{char_pred} is a procedure, it is applied to each character as
3863 a predicate, if it is a character, it is tested for equality and if it
3864 is a character set, it is tested for membership.
3867 @node Conversion to/from C
3868 @subsubsection Conversion to/from C
3870 When creating a Scheme string from a C string or when converting a
3871 Scheme string to a C string, the concept of character encoding becomes
3874 In C, a string is just a sequence of bytes, and the character encoding
3875 describes the relation between these bytes and the actual characters
3876 that make up the string. For Scheme strings, character encoding is
3877 not an issue (most of the time), since in Scheme you never get to see
3878 the bytes, only the characters.
3880 Converting to C and converting from C each have their own challenges.
3882 When converting from C to Scheme, it is important that the sequence of
3883 bytes in the C string be valid with respect to its encoding. ASCII
3884 strings, for example, can't have any bytes greater than 127. An ASCII
3885 byte greater than 127 is considered @emph{ill-formed} and cannot be
3886 converted into a Scheme character.
3888 Problems can occur in the reverse operation as well. Not all character
3889 encodings can hold all possible Scheme characters. Some encodings, like
3890 ASCII for example, can only describe a small subset of all possible
3891 characters. So, when converting to C, one must first decide what to do
3892 with Scheme characters that can't be represented in the C string.
3894 Converting a Scheme string to a C string will often allocate fresh
3895 memory to hold the result. You must take care that this memory is
3896 properly freed eventually. In many cases, this can be achieved by
3897 using @code{scm_dynwind_free} inside an appropriate dynwind context,
3898 @xref{Dynamic Wind}.
3900 @deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3901 @deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3902 Creates a new Scheme string that has the same contents as @var{str} when
3903 interpreted in the locale character encoding of the
3904 @code{current-input-port}.
3906 For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3908 For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3909 @var{str} in bytes, and @var{str} does not need to be null-terminated.
3910 If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3911 null-terminated and the real length will be found with @code{strlen}.
3913 If the C string is ill-formed, an error will be raised.
3916 @deftypefn {C Function} SCM scm_take_locale_string (char *str)
3917 @deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3918 Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3919 respectively, but also frees @var{str} with @code{free} eventually.
3920 Thus, you can use this function when you would free @var{str} anyway
3921 immediately after creating the Scheme string. In certain cases, Guile
3922 can then use @var{str} directly as its internal representation.
3925 @deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3926 @deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
3927 Returns a C string with the same contents as @var{str} in the locale
3928 encoding of the @code{current-output-port}. The C string must be freed
3929 with @code{free} eventually, maybe by using @code{scm_dynwind_free},
3930 @xref{Dynamic Wind}.
3932 For @code{scm_to_locale_string}, the returned string is
3933 null-terminated and an error is signalled when @var{str} contains
3934 @code{#\nul} characters.
3936 For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3937 @var{str} might contain @code{#\nul} characters and the length of the
3938 returned string in bytes is stored in @code{*@var{lenp}}. The
3939 returned string will not be null-terminated in this case. If
3940 @var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3941 @code{scm_to_locale_string}.
3943 If a character in @var{str} cannot be represented in the locale encoding
3944 of the current output port, the port conversion strategy of the current
3945 output port will determine the result, @xref{Ports}. If output port's
3946 conversion strategy is @code{error}, an error will be raised. If it is
3947 @code{subsitute}, a replacement character, such as a question mark, will
3948 be inserted in its place. If it is @code{escape}, a hex escape will be
3949 inserted in its place.
3952 @deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3953 Puts @var{str} as a C string in the current locale encoding into the
3954 memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3955 @var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3956 more than that. No terminating @code{'\0'} will be stored.
3958 The return value of @code{scm_to_locale_stringbuf} is the number of
3959 bytes that are needed for all of @var{str}, regardless of whether
3960 @var{buf} was large enough to hold them. Thus, when the return value
3961 is larger than @var{max_len}, only @var{max_len} bytes have been
3962 stored and you probably need to try again with a larger buffer.
3965 @node String Internals
3966 @subsubsection String Internals
3968 Guile stores each string in memory as a contiguous array of Unicode code
3969 points along with an associated set of attributes. If all of the code
3970 points of a string have an integer range between 0 and 255 inclusive,
3971 the code point array is stored as one byte per code point: it is stored
3972 as an ISO-8859-1 (aka Latin-1) string. If any of the code points of the
3973 string has an integer value greater that 255, the code point array is
3974 stored as four bytes per code point: it is stored as a UTF-32 string.
3976 Conversion between the one-byte-per-code-point and
3977 four-bytes-per-code-point representations happens automatically as
3980 No API is provided to set the internal representation of strings;
3981 however, there are pair of procedures available to query it. These are
3982 debugging procedures. Using them in production code is discouraged,
3983 since the details of Guile's internal representation of strings may
3984 change from release to release.
3986 @deffn {Scheme Procedure} string-bytes-per-char str
3987 @deffnx {C Function} scm_string_bytes_per_char (str)
3988 Return the number of bytes used to encode a Unicode code point in string
3989 @var{str}. The result is one or four.
3992 @deffn {Scheme Procedure} %string-dump str
3993 @deffnx {C Function} scm_sys_string_dump (str)
3994 Returns an association list containing debugging information for
3995 @var{str}. The association list has the following entries.
4002 The start index of the string into its stringbuf
4005 The length of the string
4008 If this string is a substring, it returns its
4009 parent string. Otherwise, it returns @code{#f}
4012 @code{#t} if the string is read-only
4014 @item stringbuf-chars
4015 A new string containing this string's stringbuf's characters
4017 @item stringbuf-length
4018 The number of characters in this stringbuf
4020 @item stringbuf-shared
4021 @code{#t} if this stringbuf is shared
4023 @item stringbuf-wide
4024 @code{#t} if this stringbuf's characters are stored in a 32-bit buffer,
4025 or @code{#f} if they are stored in an 8-bit buffer
4031 @subsection Bytevectors
4036 A @dfn{bytevector} is a raw bit string. The @code{(rnrs bytevector)}
4037 module provides the programming interface specified by the
4038 @uref{http://www.r6rs.org/, Revised^6 Report on the Algorithmic Language
4039 Scheme (R6RS)}. It contains procedures to manipulate bytevectors and
4040 interpret their contents in a number of ways: bytevector contents can be
4041 accessed as signed or unsigned integer of various sizes and endianness,
4042 as IEEE-754 floating point numbers, or as strings. It is a useful tool
4043 to encode and decode binary data.
4045 The R6RS (Section 4.3.4) specifies an external representation for
4046 bytevectors, whereby the octets (integers in the range 0--255) contained
4047 in the bytevector are represented as a list prefixed by @code{#vu8}:
4053 denotes a 3-byte bytevector containing the octets 1, 53, and 204. Like
4054 string literals, booleans, etc., bytevectors are ``self-quoting'', i.e.,
4055 they do not need to be quoted:
4059 @result{} #vu8(1 53 204)
4062 Bytevectors can be used with the binary input/output primitives of the
4063 R6RS (@pxref{R6RS I/O Ports}).
4066 * Bytevector Endianness:: Dealing with byte order.
4067 * Bytevector Manipulation:: Creating, copying, manipulating bytevectors.
4068 * Bytevectors as Integers:: Interpreting bytes as integers.
4069 * Bytevectors and Integer Lists:: Converting to/from an integer list.
4070 * Bytevectors as Floats:: Interpreting bytes as real numbers.
4071 * Bytevectors as Strings:: Interpreting bytes as Unicode strings.
4072 * Bytevectors as Generalized Vectors:: Guile extension to the bytevector API.
4073 * Bytevectors as Uniform Vectors:: Bytevectors and SRFI-4.
4076 @node Bytevector Endianness
4077 @subsubsection Endianness
4083 Some of the following procedures take an @var{endianness} parameter.
4084 The @dfn{endianness} is defined as the order of bytes in multi-byte
4085 numbers: numbers encoded in @dfn{big endian} have their most
4086 significant bytes written first, whereas numbers encoded in
4087 @dfn{little endian} have their least significant bytes
4088 first@footnote{Big-endian and little-endian are the most common
4089 ``endiannesses'', but others do exist. For instance, the GNU MP
4090 library allows @dfn{word order} to be specified independently of
4091 @dfn{byte order} (@pxref{Integer Import and Export,,, gmp, The GNU
4092 Multiple Precision Arithmetic Library Manual}).}.
4094 Little-endian is the native endianness of the IA32 architecture and
4095 its derivatives, while big-endian is native to SPARC and PowerPC,
4096 among others. The @code{native-endianness} procedure returns the
4097 native endianness of the machine it runs on.
4099 @deffn {Scheme Procedure} native-endianness
4100 @deffnx {C Function} scm_native_endianness ()
4101 Return a value denoting the native endianness of the host machine.
4104 @deffn {Scheme Macro} endianness symbol
4105 Return an object denoting the endianness specified by @var{symbol}. If
4106 @var{symbol} is neither @code{big} nor @code{little} then an error is
4107 raised at expand-time.
4110 @defvr {C Variable} scm_endianness_big
4111 @defvrx {C Variable} scm_endianness_little
4112 The objects denoting big- and little-endianness, respectively.
4116 @node Bytevector Manipulation
4117 @subsubsection Manipulating Bytevectors
4119 Bytevectors can be created, copied, and analyzed with the following
4120 procedures and C functions.
4122 @deffn {Scheme Procedure} make-bytevector len [fill]
4123 @deffnx {C Function} scm_make_bytevector (len, fill)
4124 @deffnx {C Function} scm_c_make_bytevector (size_t len)
4125 Return a new bytevector of @var{len} bytes. Optionally, if @var{fill}
4126 is given, fill it with @var{fill}; @var{fill} must be in the range
4130 @deffn {Scheme Procedure} bytevector? obj
4131 @deffnx {C Function} scm_bytevector_p (obj)
4132 Return true if @var{obj} is a bytevector.
4135 @deftypefn {C Function} int scm_is_bytevector (SCM obj)
4136 Equivalent to @code{scm_is_true (scm_bytevector_p (obj))}.
4139 @deffn {Scheme Procedure} bytevector-length bv
4140 @deffnx {C Function} scm_bytevector_length (bv)
4141 Return the length in bytes of bytevector @var{bv}.
4144 @deftypefn {C Function} size_t scm_c_bytevector_length (SCM bv)
4145 Likewise, return the length in bytes of bytevector @var{bv}.
4148 @deffn {Scheme Procedure} bytevector=? bv1 bv2
4149 @deffnx {C Function} scm_bytevector_eq_p (bv1, bv2)
4150 Return is @var{bv1} equals to @var{bv2}---i.e., if they have the same
4151 length and contents.
4154 @deffn {Scheme Procedure} bytevector-fill! bv fill
4155 @deffnx {C Function} scm_bytevector_fill_x (bv, fill)
4156 Fill bytevector @var{bv} with @var{fill}, a byte.
4159 @deffn {Scheme Procedure} bytevector-copy! source source-start target target-start len
4160 @deffnx {C Function} scm_bytevector_copy_x (source, source_start, target, target_start, len)
4161 Copy @var{len} bytes from @var{source} into @var{target}, starting
4162 reading from @var{source-start} (a positive index within @var{source})
4163 and start writing at @var{target-start}.
4166 @deffn {Scheme Procedure} bytevector-copy bv
4167 @deffnx {C Function} scm_bytevector_copy (bv)
4168 Return a newly allocated copy of @var{bv}.
4171 @deftypefn {C Function} scm_t_uint8 scm_c_bytevector_ref (SCM bv, size_t index)
4172 Return the byte at @var{index} in bytevector @var{bv}.
4175 @deftypefn {C Function} void scm_c_bytevector_set_x (SCM bv, size_t index, scm_t_uint8 value)
4176 Set the byte at @var{index} in @var{bv} to @var{value}.
4179 Low-level C macros are available. They do not perform any
4180 type-checking; as such they should be used with care.
4182 @deftypefn {C Macro} size_t SCM_BYTEVECTOR_LENGTH (bv)
4183 Return the length in bytes of bytevector @var{bv}.
4186 @deftypefn {C Macro} {signed char *} SCM_BYTEVECTOR_CONTENTS (bv)
4187 Return a pointer to the contents of bytevector @var{bv}.
4191 @node Bytevectors as Integers
4192 @subsubsection Interpreting Bytevector Contents as Integers
4194 The contents of a bytevector can be interpreted as a sequence of
4195 integers of any given size, sign, and endianness.
4198 (let ((bv (make-bytevector 4)))
4199 (bytevector-u8-set! bv 0 #x12)
4200 (bytevector-u8-set! bv 1 #x34)
4201 (bytevector-u8-set! bv 2 #x56)
4202 (bytevector-u8-set! bv 3 #x78)
4204 (map (lambda (number)
4205 (number->string number 16))
4206 (list (bytevector-u8-ref bv 0)
4207 (bytevector-u16-ref bv 0 (endianness big))
4208 (bytevector-u32-ref bv 0 (endianness little)))))
4210 @result{} ("12" "1234" "78563412")
4213 The most generic procedures to interpret bytevector contents as integers
4214 are described below.
4216 @deffn {Scheme Procedure} bytevector-uint-ref bv index endianness size
4217 @deffnx {Scheme Procedure} bytevector-sint-ref bv index endianness size
4218 @deffnx {C Function} scm_bytevector_uint_ref (bv, index, endianness, size)
4219 @deffnx {C Function} scm_bytevector_sint_ref (bv, index, endianness, size)
4220 Return the @var{size}-byte long unsigned (resp. signed) integer at
4221 index @var{index} in @var{bv}, decoded according to @var{endianness}.
4224 @deffn {Scheme Procedure} bytevector-uint-set! bv index value endianness size
4225 @deffnx {Scheme Procedure} bytevector-sint-set! bv index value endianness size
4226 @deffnx {C Function} scm_bytevector_uint_set_x (bv, index, value, endianness, size)
4227 @deffnx {C Function} scm_bytevector_sint_set_x (bv, index, value, endianness, size)
4228 Set the @var{size}-byte long unsigned (resp. signed) integer at
4229 @var{index} to @var{value}, encoded according to @var{endianness}.
4232 The following procedures are similar to the ones above, but specialized
4233 to a given integer size:
4235 @deffn {Scheme Procedure} bytevector-u8-ref bv index
4236 @deffnx {Scheme Procedure} bytevector-s8-ref bv index
4237 @deffnx {Scheme Procedure} bytevector-u16-ref bv index endianness
4238 @deffnx {Scheme Procedure} bytevector-s16-ref bv index endianness
4239 @deffnx {Scheme Procedure} bytevector-u32-ref bv index endianness
4240 @deffnx {Scheme Procedure} bytevector-s32-ref bv index endianness
4241 @deffnx {Scheme Procedure} bytevector-u64-ref bv index endianness
4242 @deffnx {Scheme Procedure} bytevector-s64-ref bv index endianness
4243 @deffnx {C Function} scm_bytevector_u8_ref (bv, index)
4244 @deffnx {C Function} scm_bytevector_s8_ref (bv, index)
4245 @deffnx {C Function} scm_bytevector_u16_ref (bv, index, endianness)
4246 @deffnx {C Function} scm_bytevector_s16_ref (bv, index, endianness)
4247 @deffnx {C Function} scm_bytevector_u32_ref (bv, index, endianness)
4248 @deffnx {C Function} scm_bytevector_s32_ref (bv, index, endianness)
4249 @deffnx {C Function} scm_bytevector_u64_ref (bv, index, endianness)
4250 @deffnx {C Function} scm_bytevector_s64_ref (bv, index, endianness)
4251 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4252 16, 32 or 64) from @var{bv} at @var{index}, decoded according to
4256 @deffn {Scheme Procedure} bytevector-u8-set! bv index value
4257 @deffnx {Scheme Procedure} bytevector-s8-set! bv index value
4258 @deffnx {Scheme Procedure} bytevector-u16-set! bv index value endianness
4259 @deffnx {Scheme Procedure} bytevector-s16-set! bv index value endianness
4260 @deffnx {Scheme Procedure} bytevector-u32-set! bv index value endianness
4261 @deffnx {Scheme Procedure} bytevector-s32-set! bv index value endianness
4262 @deffnx {Scheme Procedure} bytevector-u64-set! bv index value endianness
4263 @deffnx {Scheme Procedure} bytevector-s64-set! bv index value endianness
4264 @deffnx {C Function} scm_bytevector_u8_set_x (bv, index, value)
4265 @deffnx {C Function} scm_bytevector_s8_set_x (bv, index, value)
4266 @deffnx {C Function} scm_bytevector_u16_set_x (bv, index, value, endianness)
4267 @deffnx {C Function} scm_bytevector_s16_set_x (bv, index, value, endianness)
4268 @deffnx {C Function} scm_bytevector_u32_set_x (bv, index, value, endianness)
4269 @deffnx {C Function} scm_bytevector_s32_set_x (bv, index, value, endianness)
4270 @deffnx {C Function} scm_bytevector_u64_set_x (bv, index, value, endianness)
4271 @deffnx {C Function} scm_bytevector_s64_set_x (bv, index, value, endianness)
4272 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4273 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to
4277 Finally, a variant specialized for the host's endianness is available
4278 for each of these functions (with the exception of the @code{u8}
4279 accessors, for obvious reasons):
4281 @deffn {Scheme Procedure} bytevector-u16-native-ref bv index
4282 @deffnx {Scheme Procedure} bytevector-s16-native-ref bv index
4283 @deffnx {Scheme Procedure} bytevector-u32-native-ref bv index
4284 @deffnx {Scheme Procedure} bytevector-s32-native-ref bv index
4285 @deffnx {Scheme Procedure} bytevector-u64-native-ref bv index
4286 @deffnx {Scheme Procedure} bytevector-s64-native-ref bv index
4287 @deffnx {C Function} scm_bytevector_u16_native_ref (bv, index)
4288 @deffnx {C Function} scm_bytevector_s16_native_ref (bv, index)
4289 @deffnx {C Function} scm_bytevector_u32_native_ref (bv, index)
4290 @deffnx {C Function} scm_bytevector_s32_native_ref (bv, index)
4291 @deffnx {C Function} scm_bytevector_u64_native_ref (bv, index)
4292 @deffnx {C Function} scm_bytevector_s64_native_ref (bv, index)
4293 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4294 16, 32 or 64) from @var{bv} at @var{index}, decoded according to the
4295 host's native endianness.
4298 @deffn {Scheme Procedure} bytevector-u16-native-set! bv index value
4299 @deffnx {Scheme Procedure} bytevector-s16-native-set! bv index value
4300 @deffnx {Scheme Procedure} bytevector-u32-native-set! bv index value
4301 @deffnx {Scheme Procedure} bytevector-s32-native-set! bv index value
4302 @deffnx {Scheme Procedure} bytevector-u64-native-set! bv index value
4303 @deffnx {Scheme Procedure} bytevector-s64-native-set! bv index value
4304 @deffnx {C Function} scm_bytevector_u16_native_set_x (bv, index, value)
4305 @deffnx {C Function} scm_bytevector_s16_native_set_x (bv, index, value)
4306 @deffnx {C Function} scm_bytevector_u32_native_set_x (bv, index, value)
4307 @deffnx {C Function} scm_bytevector_s32_native_set_x (bv, index, value)
4308 @deffnx {C Function} scm_bytevector_u64_native_set_x (bv, index, value)
4309 @deffnx {C Function} scm_bytevector_s64_native_set_x (bv, index, value)
4310 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4311 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to the
4312 host's native endianness.
4316 @node Bytevectors and Integer Lists
4317 @subsubsection Converting Bytevectors to/from Integer Lists
4319 Bytevector contents can readily be converted to/from lists of signed or
4323 (bytevector->sint-list (u8-list->bytevector (make-list 4 255))
4324 (endianness little) 2)
4328 @deffn {Scheme Procedure} bytevector->u8-list bv
4329 @deffnx {C Function} scm_bytevector_to_u8_list (bv)
4330 Return a newly allocated list of unsigned 8-bit integers from the
4331 contents of @var{bv}.
4334 @deffn {Scheme Procedure} u8-list->bytevector lst
4335 @deffnx {C Function} scm_u8_list_to_bytevector (lst)
4336 Return a newly allocated bytevector consisting of the unsigned 8-bit
4337 integers listed in @var{lst}.
4340 @deffn {Scheme Procedure} bytevector->uint-list bv endianness size
4341 @deffnx {Scheme Procedure} bytevector->sint-list bv endianness size
4342 @deffnx {C Function} scm_bytevector_to_uint_list (bv, endianness, size)
4343 @deffnx {C Function} scm_bytevector_to_sint_list (bv, endianness, size)
4344 Return a list of unsigned (resp. signed) integers of @var{size} bytes
4345 representing the contents of @var{bv}, decoded according to
4349 @deffn {Scheme Procedure} uint-list->bytevector lst endianness size
4350 @deffnx {Scheme Procedure} sint-list->bytevector lst endianness size
4351 @deffnx {C Function} scm_uint_list_to_bytevector (lst, endianness, size)
4352 @deffnx {C Function} scm_sint_list_to_bytevector (lst, endianness, size)
4353 Return a new bytevector containing the unsigned (resp. signed) integers
4354 listed in @var{lst} and encoded on @var{size} bytes according to
4358 @node Bytevectors as Floats
4359 @subsubsection Interpreting Bytevector Contents as Floating Point Numbers
4361 @cindex IEEE-754 floating point numbers
4363 Bytevector contents can also be accessed as IEEE-754 single- or
4364 double-precision floating point numbers (respectively 32 and 64-bit
4365 long) using the procedures described here.
4367 @deffn {Scheme Procedure} bytevector-ieee-single-ref bv index endianness
4368 @deffnx {Scheme Procedure} bytevector-ieee-double-ref bv index endianness
4369 @deffnx {C Function} scm_bytevector_ieee_single_ref (bv, index, endianness)
4370 @deffnx {C Function} scm_bytevector_ieee_double_ref (bv, index, endianness)
4371 Return the IEEE-754 single-precision floating point number from @var{bv}
4372 at @var{index} according to @var{endianness}.
4375 @deffn {Scheme Procedure} bytevector-ieee-single-set! bv index value endianness
4376 @deffnx {Scheme Procedure} bytevector-ieee-double-set! bv index value endianness
4377 @deffnx {C Function} scm_bytevector_ieee_single_set_x (bv, index, value, endianness)
4378 @deffnx {C Function} scm_bytevector_ieee_double_set_x (bv, index, value, endianness)
4379 Store real number @var{value} in @var{bv} at @var{index} according to
4383 Specialized procedures are also available:
4385 @deffn {Scheme Procedure} bytevector-ieee-single-native-ref bv index
4386 @deffnx {Scheme Procedure} bytevector-ieee-double-native-ref bv index
4387 @deffnx {C Function} scm_bytevector_ieee_single_native_ref (bv, index)
4388 @deffnx {C Function} scm_bytevector_ieee_double_native_ref (bv, index)
4389 Return the IEEE-754 single-precision floating point number from @var{bv}
4390 at @var{index} according to the host's native endianness.
4393 @deffn {Scheme Procedure} bytevector-ieee-single-native-set! bv index value
4394 @deffnx {Scheme Procedure} bytevector-ieee-double-native-set! bv index value
4395 @deffnx {C Function} scm_bytevector_ieee_single_native_set_x (bv, index, value)
4396 @deffnx {C Function} scm_bytevector_ieee_double_native_set_x (bv, index, value)
4397 Store real number @var{value} in @var{bv} at @var{index} according to
4398 the host's native endianness.
4402 @node Bytevectors as Strings
4403 @subsubsection Interpreting Bytevector Contents as Unicode Strings
4405 @cindex Unicode string encoding
4407 Bytevector contents can also be interpreted as Unicode strings encoded
4408 in one of the most commonly available encoding formats.
4411 (utf8->string (u8-list->bytevector '(99 97 102 101)))
4414 (string->utf8 "caf@'e") ;; SMALL LATIN LETTER E WITH ACUTE ACCENT
4415 @result{} #vu8(99 97 102 195 169)
4418 @deffn {Scheme Procedure} string->utf8 str
4419 @deffnx {Scheme Procedure} string->utf16 str [endianness]
4420 @deffnx {Scheme Procedure} string->utf32 str [endianness]
4421 @deffnx {C Function} scm_string_to_utf8 (str)
4422 @deffnx {C Function} scm_string_to_utf16 (str, endianness)
4423 @deffnx {C Function} scm_string_to_utf32 (str, endianness)
4424 Return a newly allocated bytevector that contains the UTF-8, UTF-16, or
4425 UTF-32 (aka. UCS-4) encoding of @var{str}. For UTF-16 and UTF-32,
4426 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4427 it defaults to big endian.
4430 @deffn {Scheme Procedure} utf8->string utf
4431 @deffnx {Scheme Procedure} utf16->string utf [endianness]
4432 @deffnx {Scheme Procedure} utf32->string utf [endianness]
4433 @deffnx {C Function} scm_utf8_to_string (utf)
4434 @deffnx {C Function} scm_utf16_to_string (utf, endianness)
4435 @deffnx {C Function} scm_utf32_to_string (utf, endianness)
4436 Return a newly allocated string that contains from the UTF-8-, UTF-16-,
4437 or UTF-32-decoded contents of bytevector @var{utf}. For UTF-16 and UTF-32,
4438 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4439 it defaults to big endian.
4442 @node Bytevectors as Generalized Vectors
4443 @subsubsection Accessing Bytevectors with the Generalized Vector API
4445 As an extension to the R6RS, Guile allows bytevectors to be manipulated
4446 with the @dfn{generalized vector} procedures (@pxref{Generalized
4447 Vectors}). This also allows bytevectors to be accessed using the
4448 generic @dfn{array} procedures (@pxref{Array Procedures}). When using
4449 these APIs, bytes are accessed one at a time as 8-bit unsigned integers:
4452 (define bv #vu8(0 1 2 3))
4454 (generalized-vector? bv)
4457 (generalized-vector-ref bv 2)
4460 (generalized-vector-set! bv 2 77)
4469 @node Bytevectors as Uniform Vectors
4470 @subsubsection Accessing Bytevectors with the SRFI-4 API
4472 Bytevectors may also be accessed with the SRFI-4 API. @xref{SRFI-4 and
4473 Bytevectors}, for more information.
4476 @node Regular Expressions
4477 @subsection Regular Expressions
4478 @tpindex Regular expressions
4480 @cindex regular expressions
4482 @cindex emacs regexp
4484 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
4485 describes a whole class of strings. A full description of regular
4486 expressions and their syntax is beyond the scope of this manual;
4487 an introduction can be found in the Emacs manual (@pxref{Regexps,
4488 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
4489 in many general Unix reference books.
4491 If your system does not include a POSIX regular expression library,
4492 and you have not linked Guile with a third-party regexp library such
4493 as Rx, these functions will not be available. You can tell whether
4494 your Guile installation includes regular expression support by
4495 checking whether @code{(provided? 'regex)} returns true.
4497 The following regexp and string matching features are provided by the
4498 @code{(ice-9 regex)} module. Before using the described functions,
4499 you should load this module by executing @code{(use-modules (ice-9
4503 * Regexp Functions:: Functions that create and match regexps.
4504 * Match Structures:: Finding what was matched by a regexp.
4505 * Backslash Escapes:: Removing the special meaning of regexp
4510 @node Regexp Functions
4511 @subsubsection Regexp Functions
4513 By default, Guile supports POSIX extended regular expressions.
4514 That means that the characters @samp{(}, @samp{)}, @samp{+} and
4515 @samp{?} are special, and must be escaped if you wish to match the
4518 This regular expression interface was modeled after that
4519 implemented by SCSH, the Scheme Shell. It is intended to be
4520 upwardly compatible with SCSH regular expressions.
4522 Zero bytes (@code{#\nul}) cannot be used in regex patterns or input
4523 strings, since the underlying C functions treat that as the end of
4524 string. If there's a zero byte an error is thrown.
4526 Patterns and input strings are treated as being in the locale
4527 character set if @code{setlocale} has been called (@pxref{Locales}),
4528 and in a multibyte locale this includes treating multi-byte sequences
4529 as a single character. (Guile strings are currently merely bytes,
4530 though this may change in the future, @xref{Conversion to/from C}.)
4532 @deffn {Scheme Procedure} string-match pattern str [start]
4533 Compile the string @var{pattern} into a regular expression and compare
4534 it with @var{str}. The optional numeric argument @var{start} specifies
4535 the position of @var{str} at which to begin matching.
4537 @code{string-match} returns a @dfn{match structure} which
4538 describes what, if anything, was matched by the regular
4539 expression. @xref{Match Structures}. If @var{str} does not match
4540 @var{pattern} at all, @code{string-match} returns @code{#f}.
4543 Two examples of a match follow. In the first example, the pattern
4544 matches the four digits in the match string. In the second, the pattern
4548 (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
4549 @result{} #("blah2002" (4 . 8))
4551 (string-match "[A-Za-z]" "123456")
4555 Each time @code{string-match} is called, it must compile its
4556 @var{pattern} argument into a regular expression structure. This
4557 operation is expensive, which makes @code{string-match} inefficient if
4558 the same regular expression is used several times (for example, in a
4559 loop). For better performance, you can compile a regular expression in
4560 advance and then match strings against the compiled regexp.
4562 @deffn {Scheme Procedure} make-regexp pat flag@dots{}
4563 @deffnx {C Function} scm_make_regexp (pat, flaglst)
4564 Compile the regular expression described by @var{pat}, and
4565 return the compiled regexp structure. If @var{pat} does not
4566 describe a legal regular expression, @code{make-regexp} throws
4567 a @code{regular-expression-syntax} error.
4569 The @var{flag} arguments change the behavior of the compiled
4570 regular expression. The following values may be supplied:
4572 @defvar regexp/icase
4573 Consider uppercase and lowercase letters to be the same when
4577 @defvar regexp/newline
4578 If a newline appears in the target string, then permit the
4579 @samp{^} and @samp{$} operators to match immediately after or
4580 immediately before the newline, respectively. Also, the
4581 @samp{.} and @samp{[^...]} operators will never match a newline
4582 character. The intent of this flag is to treat the target
4583 string as a buffer containing many lines of text, and the
4584 regular expression as a pattern that may match a single one of
4588 @defvar regexp/basic
4589 Compile a basic (``obsolete'') regexp instead of the extended
4590 (``modern'') regexps that are the default. Basic regexps do
4591 not consider @samp{|}, @samp{+} or @samp{?} to be special
4592 characters, and require the @samp{@{...@}} and @samp{(...)}
4593 metacharacters to be backslash-escaped (@pxref{Backslash
4594 Escapes}). There are several other differences between basic
4595 and extended regular expressions, but these are the most
4599 @defvar regexp/extended
4600 Compile an extended regular expression rather than a basic
4601 regexp. This is the default behavior; this flag will not
4602 usually be needed. If a call to @code{make-regexp} includes
4603 both @code{regexp/basic} and @code{regexp/extended} flags, the
4604 one which comes last will override the earlier one.
4608 @deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
4609 @deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
4610 Match the compiled regular expression @var{rx} against
4611 @code{str}. If the optional integer @var{start} argument is
4612 provided, begin matching from that position in the string.
4613 Return a match structure describing the results of the match,
4614 or @code{#f} if no match could be found.
4616 The @var{flags} argument changes the matching behavior. The following
4617 flag values may be supplied, use @code{logior} (@pxref{Bitwise
4618 Operations}) to combine them,
4620 @defvar regexp/notbol
4621 Consider that the @var{start} offset into @var{str} is not the
4622 beginning of a line and should not match operator @samp{^}.
4624 If @var{rx} was created with the @code{regexp/newline} option above,
4625 @samp{^} will still match after a newline in @var{str}.
4628 @defvar regexp/noteol
4629 Consider that the end of @var{str} is not the end of a line and should
4630 not match operator @samp{$}.
4632 If @var{rx} was created with the @code{regexp/newline} option above,
4633 @samp{$} will still match before a newline in @var{str}.
4638 ;; Regexp to match uppercase letters
4639 (define r (make-regexp "[A-Z]*"))
4641 ;; Regexp to match letters, ignoring case
4642 (define ri (make-regexp "[A-Z]*" regexp/icase))
4644 ;; Search for bob using regexp r
4645 (match:substring (regexp-exec r "bob"))
4646 @result{} "" ; no match
4648 ;; Search for bob using regexp ri
4649 (match:substring (regexp-exec ri "Bob"))
4650 @result{} "Bob" ; matched case insensitive
4653 @deffn {Scheme Procedure} regexp? obj
4654 @deffnx {C Function} scm_regexp_p (obj)
4655 Return @code{#t} if @var{obj} is a compiled regular expression,
4656 or @code{#f} otherwise.
4660 @deffn {Scheme Procedure} list-matches regexp str [flags]
4661 Return a list of match structures which are the non-overlapping
4662 matches of @var{regexp} in @var{str}. @var{regexp} can be either a
4663 pattern string or a compiled regexp. The @var{flags} argument is as
4664 per @code{regexp-exec} above.
4667 (map match:substring (list-matches "[a-z]+" "abc 42 def 78"))
4668 @result{} ("abc" "def")
4672 @deffn {Scheme Procedure} fold-matches regexp str init proc [flags]
4673 Apply @var{proc} to the non-overlapping matches of @var{regexp} in
4674 @var{str}, to build a result. @var{regexp} can be either a pattern
4675 string or a compiled regexp. The @var{flags} argument is as per
4676 @code{regexp-exec} above.
4678 @var{proc} is called as @code{(@var{proc} match prev)} where
4679 @var{match} is a match structure and @var{prev} is the previous return
4680 from @var{proc}. For the first call @var{prev} is the given
4681 @var{init} parameter. @code{fold-matches} returns the final value
4684 For example to count matches,
4687 (fold-matches "[a-z][0-9]" "abc x1 def y2" 0
4688 (lambda (match count)
4695 Regular expressions are commonly used to find patterns in one string
4696 and replace them with the contents of another string. The following
4697 functions are convenient ways to do this.
4699 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
4700 @deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
4701 Write to @var{port} selected parts of the match structure @var{match}.
4702 Or if @var{port} is @code{#f} then form a string from those parts and
4705 Each @var{item} specifies a part to be written, and may be one of the
4710 A string. String arguments are written out verbatim.
4713 An integer. The submatch with that number is written
4714 (@code{match:substring}). Zero is the entire match.
4717 The symbol @samp{pre}. The portion of the matched string preceding
4718 the regexp match is written (@code{match:prefix}).
4721 The symbol @samp{post}. The portion of the matched string following
4722 the regexp match is written (@code{match:suffix}).
4725 For example, changing a match and retaining the text before and after,
4728 (regexp-substitute #f (string-match "[0-9]+" "number 25 is good")
4730 @result{} "number 37 is good"
4733 Or matching a @sc{yyyymmdd} format date such as @samp{20020828} and
4734 re-ordering and hyphenating the fields.
4738 "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
4739 (define s "Date 20020429 12am.")
4740 (regexp-substitute #f (string-match date-regex s)
4741 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
4742 @result{} "Date 04-29-2002 12am. (20020429)"
4747 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
4748 @deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
4749 @cindex search and replace
4750 Write to @var{port} selected parts of matches of @var{regexp} in
4751 @var{target}. If @var{port} is @code{#f} then form a string from
4752 those parts and return that. @var{regexp} can be a string or a
4755 This is similar to @code{regexp-substitute}, but allows global
4756 substitutions on @var{target}. Each @var{item} behaves as per
4757 @code{regexp-substitute}, with the following differences,
4761 A function. Called as @code{(@var{item} match)} with the match
4762 structure for the @var{regexp} match, it should return a string to be
4763 written to @var{port}.
4766 The symbol @samp{post}. This doesn't output anything, but instead
4767 causes @code{regexp-substitute/global} to recurse on the unmatched
4768 portion of @var{target}.
4770 This @emph{must} be supplied to perform a global search and replace on
4771 @var{target}; without it @code{regexp-substitute/global} returns after
4772 a single match and output.
4775 For example, to collapse runs of tabs and spaces to a single hyphen
4779 (regexp-substitute/global #f "[ \t]+" "this is the text"
4781 @result{} "this-is-the-text"
4784 Or using a function to reverse the letters in each word,
4787 (regexp-substitute/global #f "[a-z]+" "to do and not-do"
4788 'pre (lambda (m) (string-reverse (match:substring m))) 'post)
4789 @result{} "ot od dna ton-od"
4792 Without the @code{post} symbol, just one regexp match is made. For
4793 example the following is the date example from
4794 @code{regexp-substitute} above, without the need for the separate
4795 @code{string-match} call.
4799 "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
4800 (define s "Date 20020429 12am.")
4801 (regexp-substitute/global #f date-regex s
4802 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
4804 @result{} "Date 04-29-2002 12am. (20020429)"
4809 @node Match Structures
4810 @subsubsection Match Structures
4812 @cindex match structures
4814 A @dfn{match structure} is the object returned by @code{string-match} and
4815 @code{regexp-exec}. It describes which portion of a string, if any,
4816 matched the given regular expression. Match structures include: a
4817 reference to the string that was checked for matches; the starting and
4818 ending positions of the regexp match; and, if the regexp included any
4819 parenthesized subexpressions, the starting and ending positions of each
4822 In each of the regexp match functions described below, the @code{match}
4823 argument must be a match structure returned by a previous call to
4824 @code{string-match} or @code{regexp-exec}. Most of these functions
4825 return some information about the original target string that was
4826 matched against a regular expression; we will call that string
4827 @var{target} for easy reference.
4829 @c begin (scm-doc-string "regex.scm" "regexp-match?")
4830 @deffn {Scheme Procedure} regexp-match? obj
4831 Return @code{#t} if @var{obj} is a match structure returned by a
4832 previous call to @code{regexp-exec}, or @code{#f} otherwise.
4835 @c begin (scm-doc-string "regex.scm" "match:substring")
4836 @deffn {Scheme Procedure} match:substring match [n]
4837 Return the portion of @var{target} matched by subexpression number
4838 @var{n}. Submatch 0 (the default) represents the entire regexp match.
4839 If the regular expression as a whole matched, but the subexpression
4840 number @var{n} did not match, return @code{#f}.
4844 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4848 ;; match starting at offset 6 in the string
4850 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
4854 @c begin (scm-doc-string "regex.scm" "match:start")
4855 @deffn {Scheme Procedure} match:start match [n]
4856 Return the starting position of submatch number @var{n}.
4859 In the following example, the result is 4, since the match starts at
4863 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4868 @c begin (scm-doc-string "regex.scm" "match:end")
4869 @deffn {Scheme Procedure} match:end match [n]
4870 Return the ending position of submatch number @var{n}.
4873 In the following example, the result is 8, since the match runs between
4874 characters 4 and 8 (i.e. the ``2002'').
4877 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4882 @c begin (scm-doc-string "regex.scm" "match:prefix")
4883 @deffn {Scheme Procedure} match:prefix match
4884 Return the unmatched portion of @var{target} preceding the regexp match.
4887 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4893 @c begin (scm-doc-string "regex.scm" "match:suffix")
4894 @deffn {Scheme Procedure} match:suffix match
4895 Return the unmatched portion of @var{target} following the regexp match.
4899 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4904 @c begin (scm-doc-string "regex.scm" "match:count")
4905 @deffn {Scheme Procedure} match:count match
4906 Return the number of parenthesized subexpressions from @var{match}.
4907 Note that the entire regular expression match itself counts as a
4908 subexpression, and failed submatches are included in the count.
4911 @c begin (scm-doc-string "regex.scm" "match:string")
4912 @deffn {Scheme Procedure} match:string match
4913 Return the original @var{target} string.
4917 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4919 @result{} "blah2002foo"
4923 @node Backslash Escapes
4924 @subsubsection Backslash Escapes
4926 Sometimes you will want a regexp to match characters like @samp{*} or
4927 @samp{$} exactly. For example, to check whether a particular string
4928 represents a menu entry from an Info node, it would be useful to match
4929 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
4930 because the asterisk is a metacharacter, it won't match the @samp{*} at
4931 the beginning of the string. In this case, we want to make the first
4934 You can do this by preceding the metacharacter with a backslash
4935 character @samp{\}. (This is also called @dfn{quoting} the
4936 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
4937 sees a backslash in a regular expression, it considers the following
4938 glyph to be an ordinary character, no matter what special meaning it
4939 would ordinarily have. Therefore, we can make the above example work by
4940 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
4941 the regular expression engine to match only a single asterisk in the
4944 Since the backslash is itself a metacharacter, you may force a regexp to
4945 match a backslash in the target string by preceding the backslash with
4946 itself. For example, to find variable references in a @TeX{} program,
4947 you might want to find occurrences of the string @samp{\let\} followed
4948 by any number of alphabetic characters. The regular expression
4949 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
4950 regexp each match a single backslash in the target string.
4952 @c begin (scm-doc-string "regex.scm" "regexp-quote")
4953 @deffn {Scheme Procedure} regexp-quote str
4954 Quote each special character found in @var{str} with a backslash, and
4955 return the resulting string.
4958 @strong{Very important:} Using backslash escapes in Guile source code
4959 (as in Emacs Lisp or C) can be tricky, because the backslash character
4960 has special meaning for the Guile reader. For example, if Guile
4961 encounters the character sequence @samp{\n} in the middle of a string
4962 while processing Scheme code, it replaces those characters with a
4963 newline character. Similarly, the character sequence @samp{\t} is
4964 replaced by a horizontal tab. Several of these @dfn{escape sequences}
4965 are processed by the Guile reader before your code is executed.
4966 Unrecognized escape sequences are ignored: if the characters @samp{\*}
4967 appear in a string, they will be translated to the single character
4970 This translation is obviously undesirable for regular expressions, since
4971 we want to be able to include backslashes in a string in order to
4972 escape regexp metacharacters. Therefore, to make sure that a backslash
4973 is preserved in a string in your Guile program, you must use @emph{two}
4974 consecutive backslashes:
4977 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
4980 The string in this example is preprocessed by the Guile reader before
4981 any code is executed. The resulting argument to @code{make-regexp} is
4982 the string @samp{^\* [^:]*}, which is what we really want.
4984 This also means that in order to write a regular expression that matches
4985 a single backslash character, the regular expression string in the
4986 source code must include @emph{four} backslashes. Each consecutive pair
4987 of backslashes gets translated by the Guile reader to a single
4988 backslash, and the resulting double-backslash is interpreted by the
4989 regexp engine as matching a single backslash character. Hence:
4992 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
4995 The reason for the unwieldiness of this syntax is historical. Both
4996 regular expression pattern matchers and Unix string processing systems
4997 have traditionally used backslashes with the special meanings
4998 described above. The POSIX regular expression specification and ANSI C
4999 standard both require these semantics. Attempting to abandon either
5000 convention would cause other kinds of compatibility problems, possibly
5001 more severe ones. Therefore, without extending the Scheme reader to
5002 support strings with different quoting conventions (an ungainly and
5003 confusing extension when implemented in other languages), we must adhere
5004 to this cumbersome escape syntax.
5011 Symbols in Scheme are widely used in three ways: as items of discrete
5012 data, as lookup keys for alists and hash tables, and to denote variable
5015 A @dfn{symbol} is similar to a string in that it is defined by a
5016 sequence of characters. The sequence of characters is known as the
5017 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
5018 name doesn't include any characters that could be confused with other
5019 elements of Scheme syntax --- a symbol is written in a Scheme program by
5020 writing the sequence of characters that make up the name, @emph{without}
5021 any quotation marks or other special syntax. For example, the symbol
5022 whose name is ``multiply-by-2'' is written, simply:
5028 Notice how this differs from a @emph{string} with contents
5029 ``multiply-by-2'', which is written with double quotation marks, like
5036 Looking beyond how they are written, symbols are different from strings
5037 in two important respects.
5039 The first important difference is uniqueness. If the same-looking
5040 string is read twice from two different places in a program, the result
5041 is two @emph{different} string objects whose contents just happen to be
5042 the same. If, on the other hand, the same-looking symbol is read twice
5043 from two different places in a program, the result is the @emph{same}
5044 symbol object both times.
5046 Given two read symbols, you can use @code{eq?} to test whether they are
5047 the same (that is, have the same name). @code{eq?} is the most
5048 efficient comparison operator in Scheme, and comparing two symbols like
5049 this is as fast as comparing, for example, two numbers. Given two
5050 strings, on the other hand, you must use @code{equal?} or
5051 @code{string=?}, which are much slower comparison operators, to
5052 determine whether the strings have the same contents.
5055 (define sym1 (quote hello))
5056 (define sym2 (quote hello))
5057 (eq? sym1 sym2) @result{} #t
5059 (define str1 "hello")
5060 (define str2 "hello")
5061 (eq? str1 str2) @result{} #f
5062 (equal? str1 str2) @result{} #t
5065 The second important difference is that symbols, unlike strings, are not
5066 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
5067 example above: @code{(quote hello)} evaluates to the symbol named
5068 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
5069 symbol named "hello" and evaluated as a variable reference @dots{} about
5070 which more below (@pxref{Symbol Variables}).
5073 * Symbol Data:: Symbols as discrete data.
5074 * Symbol Keys:: Symbols as lookup keys.
5075 * Symbol Variables:: Symbols as denoting variables.
5076 * Symbol Primitives:: Operations related to symbols.
5077 * Symbol Props:: Function slots and property lists.
5078 * Symbol Read Syntax:: Extended read syntax for symbols.
5079 * Symbol Uninterned:: Uninterned symbols.
5084 @subsubsection Symbols as Discrete Data
5086 Numbers and symbols are similar to the extent that they both lend
5087 themselves to @code{eq?} comparison. But symbols are more descriptive
5088 than numbers, because a symbol's name can be used directly to describe
5089 the concept for which that symbol stands.
5091 For example, imagine that you need to represent some colours in a
5092 computer program. Using numbers, you would have to choose arbitrarily
5093 some mapping between numbers and colours, and then take care to use that
5094 mapping consistently:
5097 ;; 1=red, 2=green, 3=purple
5099 (if (eq? (colour-of car) 1)
5104 You can make the mapping more explicit and the code more readable by
5112 (if (eq? (colour-of car) red)
5117 But the simplest and clearest approach is not to use numbers at all, but
5118 symbols whose names specify the colours that they refer to:
5121 (if (eq? (colour-of car) 'red)
5125 The descriptive advantages of symbols over numbers increase as the set
5126 of concepts that you want to describe grows. Suppose that a car object
5127 can have other properties as well, such as whether it has or uses:
5131 automatic or manual transmission
5133 leaded or unleaded fuel
5135 power steering (or not).
5139 Then a car's combined property set could be naturally represented and
5140 manipulated as a list of symbols:
5143 (properties-of car1)
5145 (red manual unleaded power-steering)
5147 (if (memq 'power-steering (properties-of car1))
5148 (display "Unfit people can drive this car.\n")
5149 (display "You'll need strong arms to drive this car!\n"))
5151 Unfit people can drive this car.
5154 Remember, the fundamental property of symbols that we are relying on
5155 here is that an occurrence of @code{'red} in one part of a program is an
5156 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
5157 another part of a program; this means that symbols can usefully be
5158 compared using @code{eq?}. At the same time, symbols have naturally
5159 descriptive names. This combination of efficiency and descriptive power
5160 makes them ideal for use as discrete data.
5164 @subsubsection Symbols as Lookup Keys
5166 Given their efficiency and descriptive power, it is natural to use
5167 symbols as the keys in an association list or hash table.
5169 To illustrate this, consider a more structured representation of the car
5170 properties example from the preceding subsection. Rather than
5171 mixing all the properties up together in a flat list, we could use an
5172 association list like this:
5175 (define car1-properties '((colour . red)
5176 (transmission . manual)
5178 (steering . power-assisted)))
5181 Notice how this structure is more explicit and extensible than the flat
5182 list. For example it makes clear that @code{manual} refers to the
5183 transmission rather than, say, the windows or the locking of the car.
5184 It also allows further properties to use the same symbols among their
5185 possible values without becoming ambiguous:
5188 (define car1-properties '((colour . red)
5189 (transmission . manual)
5191 (steering . power-assisted)
5193 (locking . manual)))
5196 With a representation like this, it is easy to use the efficient
5197 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
5198 extract or change individual pieces of information:
5201 (assq-ref car1-properties 'fuel) @result{} unleaded
5202 (assq-ref car1-properties 'transmission) @result{} manual
5204 (assq-set! car1-properties 'seat-colour 'black)
5207 (transmission . manual)
5209 (steering . power-assisted)
5210 (seat-colour . black)
5211 (locking . manual)))
5214 Hash tables also have keys, and exactly the same arguments apply to the
5215 use of symbols in hash tables as in association lists. The hash value
5216 that Guile uses to decide where to add a symbol-keyed entry to a hash
5217 table can be obtained by calling the @code{symbol-hash} procedure:
5219 @deffn {Scheme Procedure} symbol-hash symbol
5220 @deffnx {C Function} scm_symbol_hash (symbol)
5221 Return a hash value for @var{symbol}.
5224 See @ref{Hash Tables} for information about hash tables in general, and
5225 for why you might choose to use a hash table rather than an association
5229 @node Symbol Variables
5230 @subsubsection Symbols as Denoting Variables
5232 When an unquoted symbol in a Scheme program is evaluated, it is
5233 interpreted as a variable reference, and the result of the evaluation is
5234 the appropriate variable's value.
5236 For example, when the expression @code{(string-length "abcd")} is read
5237 and evaluated, the sequence of characters @code{string-length} is read
5238 as the symbol whose name is "string-length". This symbol is associated
5239 with a variable whose value is the procedure that implements string
5240 length calculation. Therefore evaluation of the @code{string-length}
5241 symbol results in that procedure.
5243 The details of the connection between an unquoted symbol and the
5244 variable to which it refers are explained elsewhere. See @ref{Binding
5245 Constructs}, for how associations between symbols and variables are
5246 created, and @ref{Modules}, for how those associations are affected by
5247 Guile's module system.
5250 @node Symbol Primitives
5251 @subsubsection Operations Related to Symbols
5253 Given any Scheme value, you can determine whether it is a symbol using
5254 the @code{symbol?} primitive:
5257 @deffn {Scheme Procedure} symbol? obj
5258 @deffnx {C Function} scm_symbol_p (obj)
5259 Return @code{#t} if @var{obj} is a symbol, otherwise return
5263 @deftypefn {C Function} int scm_is_symbol (SCM val)
5264 Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
5267 Once you know that you have a symbol, you can obtain its name as a
5268 string by calling @code{symbol->string}. Note that Guile differs by
5269 default from R5RS on the details of @code{symbol->string} as regards
5272 @rnindex symbol->string
5273 @deffn {Scheme Procedure} symbol->string s
5274 @deffnx {C Function} scm_symbol_to_string (s)
5275 Return the name of symbol @var{s} as a string. By default, Guile reads
5276 symbols case-sensitively, so the string returned will have the same case
5277 variation as the sequence of characters that caused @var{s} to be
5280 If Guile is set to read symbols case-insensitively (as specified by
5281 R5RS), and @var{s} comes into being as part of a literal expression
5282 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
5283 by a call to the @code{read} or @code{string-ci->symbol} procedures,
5284 Guile converts any alphabetic characters in the symbol's name to
5285 lower case before creating the symbol object, so the string returned
5286 here will be in lower case.
5288 If @var{s} was created by @code{string->symbol}, the case of characters
5289 in the string returned will be the same as that in the string that was
5290 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
5291 setting at the time @var{s} was created.
5293 It is an error to apply mutation procedures like @code{string-set!} to
5294 strings returned by this procedure.
5297 Most symbols are created by writing them literally in code. However it
5298 is also possible to create symbols programmatically using the following
5299 @code{string->symbol} and @code{string-ci->symbol} procedures:
5301 @rnindex string->symbol
5302 @deffn {Scheme Procedure} string->symbol string
5303 @deffnx {C Function} scm_string_to_symbol (string)
5304 Return the symbol whose name is @var{string}. This procedure can create
5305 symbols with names containing special characters or letters in the
5306 non-standard case, but it is usually a bad idea to create such symbols
5307 because in some implementations of Scheme they cannot be read as
5311 @deffn {Scheme Procedure} string-ci->symbol str
5312 @deffnx {C Function} scm_string_ci_to_symbol (str)
5313 Return the symbol whose name is @var{str}. If Guile is currently
5314 reading symbols case-insensitively, @var{str} is converted to lowercase
5315 before the returned symbol is looked up or created.
5318 The following examples illustrate Guile's detailed behaviour as regards
5319 the case-sensitivity of symbols:
5322 (read-enable 'case-insensitive) ; R5RS compliant behaviour
5324 (symbol->string 'flying-fish) @result{} "flying-fish"
5325 (symbol->string 'Martin) @result{} "martin"
5327 (string->symbol "Malvina")) @result{} "Malvina"
5329 (eq? 'mISSISSIppi 'mississippi) @result{} #t
5330 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
5331 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
5333 (string->symbol (symbol->string 'LolliPop))) @result{} #t
5334 (string=? "K. Harper, M.D."
5336 (string->symbol "K. Harper, M.D."))) @result{} #t
5338 (read-disable 'case-insensitive) ; Guile default behaviour
5340 (symbol->string 'flying-fish) @result{} "flying-fish"
5341 (symbol->string 'Martin) @result{} "Martin"
5343 (string->symbol "Malvina")) @result{} "Malvina"
5345 (eq? 'mISSISSIppi 'mississippi) @result{} #f
5346 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
5347 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
5349 (string->symbol (symbol->string 'LolliPop))) @result{} #t
5350 (string=? "K. Harper, M.D."
5352 (string->symbol "K. Harper, M.D."))) @result{} #t
5355 From C, there are lower level functions that construct a Scheme symbol
5356 from a C string in the current locale encoding.
5358 When you want to do more from C, you should convert between symbols
5359 and strings using @code{scm_symbol_to_string} and
5360 @code{scm_string_to_symbol} and work with the strings.
5362 @deffn {C Function} scm_from_locale_symbol (const char *name)
5363 @deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
5364 Construct and return a Scheme symbol whose name is specified by
5365 @var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
5366 terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
5367 specified explicitly by @var{len}.
5370 @deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
5371 @deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
5372 Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
5373 respectively, but also frees @var{str} with @code{free} eventually.
5374 Thus, you can use this function when you would free @var{str} anyway
5375 immediately after creating the Scheme string. In certain cases, Guile
5376 can then use @var{str} directly as its internal representation.
5379 The size of a symbol can also be obtained from C:
5381 @deftypefn {C Function} size_t scm_c_symbol_length (SCM sym)
5382 Return the number of characters in @var{sym}.
5385 Finally, some applications, especially those that generate new Scheme
5386 code dynamically, need to generate symbols for use in the generated
5387 code. The @code{gensym} primitive meets this need:
5389 @deffn {Scheme Procedure} gensym [prefix]
5390 @deffnx {C Function} scm_gensym (prefix)
5391 Create a new symbol with a name constructed from a prefix and a counter
5392 value. The string @var{prefix} can be specified as an optional
5393 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
5394 at each call. There is no provision for resetting the counter.
5397 The symbols generated by @code{gensym} are @emph{likely} to be unique,
5398 since their names begin with a space and it is only otherwise possible
5399 to generate such symbols if a programmer goes out of their way to do
5400 so. Uniqueness can be guaranteed by instead using uninterned symbols
5401 (@pxref{Symbol Uninterned}), though they can't be usefully written out
5406 @subsubsection Function Slots and Property Lists
5408 In traditional Lisp dialects, symbols are often understood as having
5409 three kinds of value at once:
5413 a @dfn{variable} value, which is used when the symbol appears in
5414 code in a variable reference context
5417 a @dfn{function} value, which is used when the symbol appears in
5418 code in a function name position (i.e. as the first element in an
5422 a @dfn{property list} value, which is used when the symbol is given as
5423 the first argument to Lisp's @code{put} or @code{get} functions.
5426 Although Scheme (as one of its simplifications with respect to Lisp)
5427 does away with the distinction between variable and function namespaces,
5428 Guile currently retains some elements of the traditional structure in
5429 case they turn out to be useful when implementing translators for other
5430 languages, in particular Emacs Lisp.
5432 Specifically, Guile symbols have two extra slots. for a symbol's
5433 property list, and for its ``function value.'' The following procedures
5434 are provided to access these slots.
5436 @deffn {Scheme Procedure} symbol-fref symbol
5437 @deffnx {C Function} scm_symbol_fref (symbol)
5438 Return the contents of @var{symbol}'s @dfn{function slot}.
5441 @deffn {Scheme Procedure} symbol-fset! symbol value
5442 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
5443 Set the contents of @var{symbol}'s function slot to @var{value}.
5446 @deffn {Scheme Procedure} symbol-pref symbol
5447 @deffnx {C Function} scm_symbol_pref (symbol)
5448 Return the @dfn{property list} currently associated with @var{symbol}.
5451 @deffn {Scheme Procedure} symbol-pset! symbol value
5452 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
5453 Set @var{symbol}'s property list to @var{value}.
5456 @deffn {Scheme Procedure} symbol-property sym prop
5457 From @var{sym}'s property list, return the value for property
5458 @var{prop}. The assumption is that @var{sym}'s property list is an
5459 association list whose keys are distinguished from each other using
5460 @code{equal?}; @var{prop} should be one of the keys in that list. If
5461 the property list has no entry for @var{prop}, @code{symbol-property}
5465 @deffn {Scheme Procedure} set-symbol-property! sym prop val
5466 In @var{sym}'s property list, set the value for property @var{prop} to
5467 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
5468 none already exists. For the structure of the property list, see
5469 @code{symbol-property}.
5472 @deffn {Scheme Procedure} symbol-property-remove! sym prop
5473 From @var{sym}'s property list, remove the entry for property
5474 @var{prop}, if there is one. For the structure of the property list,
5475 see @code{symbol-property}.
5478 Support for these extra slots may be removed in a future release, and it
5479 is probably better to avoid using them. For a more modern and Schemely
5480 approach to properties, see @ref{Object Properties}.
5483 @node Symbol Read Syntax
5484 @subsubsection Extended Read Syntax for Symbols
5486 The read syntax for a symbol is a sequence of letters, digits, and
5487 @dfn{extended alphabetic characters}, beginning with a character that
5488 cannot begin a number. In addition, the special cases of @code{+},
5489 @code{-}, and @code{...} are read as symbols even though numbers can
5490 begin with @code{+}, @code{-} or @code{.}.
5492 Extended alphabetic characters may be used within identifiers as if
5493 they were letters. The set of extended alphabetic characters is:
5496 ! $ % & * + - . / : < = > ? @@ ^ _ ~
5499 In addition to the standard read syntax defined above (which is taken
5500 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
5501 Scheme})), Guile provides an extended symbol read syntax that allows the
5502 inclusion of unusual characters such as space characters, newlines and
5503 parentheses. If (for whatever reason) you need to write a symbol
5504 containing characters not mentioned above, you can do so as follows.
5508 Begin the symbol with the characters @code{#@{},
5511 write the characters of the symbol and
5514 finish the symbol with the characters @code{@}#}.
5517 Here are a few examples of this form of read syntax. The first symbol
5518 needs to use extended syntax because it contains a space character, the
5519 second because it contains a line break, and the last because it looks
5531 Although Guile provides this extended read syntax for symbols,
5532 widespread usage of it is discouraged because it is not portable and not
5536 @node Symbol Uninterned
5537 @subsubsection Uninterned Symbols
5539 What makes symbols useful is that they are automatically kept unique.
5540 There are no two symbols that are distinct objects but have the same
5541 name. But of course, there is no rule without exception. In addition
5542 to the normal symbols that have been discussed up to now, you can also
5543 create special @dfn{uninterned} symbols that behave slightly
5546 To understand what is different about them and why they might be useful,
5547 we look at how normal symbols are actually kept unique.
5549 Whenever Guile wants to find the symbol with a specific name, for
5550 example during @code{read} or when executing @code{string->symbol}, it
5551 first looks into a table of all existing symbols to find out whether a
5552 symbol with the given name already exists. When this is the case, Guile
5553 just returns that symbol. When not, a new symbol with the name is
5554 created and entered into the table so that it can be found later.
5556 Sometimes you might want to create a symbol that is guaranteed `fresh',
5557 i.e. a symbol that did not exist previously. You might also want to
5558 somehow guarantee that no one else will ever unintentionally stumble
5559 across your symbol in the future. These properties of a symbol are
5560 often needed when generating code during macro expansion. When
5561 introducing new temporary variables, you want to guarantee that they
5562 don't conflict with variables in other people's code.
5564 The simplest way to arrange for this is to create a new symbol but
5565 not enter it into the global table of all symbols. That way, no one
5566 will ever get access to your symbol by chance. Symbols that are not in
5567 the table are called @dfn{uninterned}. Of course, symbols that
5568 @emph{are} in the table are called @dfn{interned}.
5570 You create new uninterned symbols with the function @code{make-symbol}.
5571 You can test whether a symbol is interned or not with
5572 @code{symbol-interned?}.
5574 Uninterned symbols break the rule that the name of a symbol uniquely
5575 identifies the symbol object. Because of this, they can not be written
5576 out and read back in like interned symbols. Currently, Guile has no
5577 support for reading uninterned symbols. Note that the function
5578 @code{gensym} does not return uninterned symbols for this reason.
5580 @deffn {Scheme Procedure} make-symbol name
5581 @deffnx {C Function} scm_make_symbol (name)
5582 Return a new uninterned symbol with the name @var{name}. The returned
5583 symbol is guaranteed to be unique and future calls to
5584 @code{string->symbol} will not return it.
5587 @deffn {Scheme Procedure} symbol-interned? symbol
5588 @deffnx {C Function} scm_symbol_interned_p (symbol)
5589 Return @code{#t} if @var{symbol} is interned, otherwise return
5596 (define foo-1 (string->symbol "foo"))
5597 (define foo-2 (string->symbol "foo"))
5598 (define foo-3 (make-symbol "foo"))
5599 (define foo-4 (make-symbol "foo"))
5603 ; Two interned symbols with the same name are the same object,
5607 ; but a call to make-symbol with the same name returns a
5612 ; A call to make-symbol always returns a new object, even for
5616 @result{} #<uninterned-symbol foo 8085290>
5617 ; Uninterned symbols print differently from interned symbols,
5621 ; but they are still symbols,
5623 (symbol-interned? foo-3)
5625 ; just not interned.
5630 @subsection Keywords
5633 Keywords are self-evaluating objects with a convenient read syntax that
5634 makes them easy to type.
5636 Guile's keyword support conforms to R5RS, and adds a (switchable) read
5637 syntax extension to permit keywords to begin with @code{:} as well as
5638 @code{#:}, or to end with @code{:}.
5641 * Why Use Keywords?:: Motivation for keyword usage.
5642 * Coding With Keywords:: How to use keywords.
5643 * Keyword Read Syntax:: Read syntax for keywords.
5644 * Keyword Procedures:: Procedures for dealing with keywords.
5647 @node Why Use Keywords?
5648 @subsubsection Why Use Keywords?
5650 Keywords are useful in contexts where a program or procedure wants to be
5651 able to accept a large number of optional arguments without making its
5652 interface unmanageable.
5654 To illustrate this, consider a hypothetical @code{make-window}
5655 procedure, which creates a new window on the screen for drawing into
5656 using some graphical toolkit. There are many parameters that the caller
5657 might like to specify, but which could also be sensibly defaulted, for
5662 color depth -- Default: the color depth for the screen
5665 background color -- Default: white
5668 width -- Default: 600
5671 height -- Default: 400
5674 If @code{make-window} did not use keywords, the caller would have to
5675 pass in a value for each possible argument, remembering the correct
5676 argument order and using a special value to indicate the default value
5680 (make-window 'default ;; Color depth
5681 'default ;; Background color
5684 @dots{}) ;; More make-window arguments
5687 With keywords, on the other hand, defaulted arguments are omitted, and
5688 non-default arguments are clearly tagged by the appropriate keyword. As
5689 a result, the invocation becomes much clearer:
5692 (make-window #:width 800 #:height 100)
5695 On the other hand, for a simpler procedure with few arguments, the use
5696 of keywords would be a hindrance rather than a help. The primitive
5697 procedure @code{cons}, for example, would not be improved if it had to
5701 (cons #:car x #:cdr y)
5704 So the decision whether to use keywords or not is purely pragmatic: use
5705 them if they will clarify the procedure invocation at point of call.
5707 @node Coding With Keywords
5708 @subsubsection Coding With Keywords
5710 If a procedure wants to support keywords, it should take a rest argument
5711 and then use whatever means is convenient to extract keywords and their
5712 corresponding arguments from the contents of that rest argument.
5714 The following example illustrates the principle: the code for
5715 @code{make-window} uses a helper procedure called
5716 @code{get-keyword-value} to extract individual keyword arguments from
5720 (define (get-keyword-value args keyword default)
5721 (let ((kv (memq keyword args)))
5722 (if (and kv (>= (length kv) 2))
5726 (define (make-window . args)
5727 (let ((depth (get-keyword-value args #:depth screen-depth))
5728 (bg (get-keyword-value args #:bg "white"))
5729 (width (get-keyword-value args #:width 800))
5730 (height (get-keyword-value args #:height 100))
5735 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
5736 optargs)} module provides a set of powerful macros that you can use to
5737 implement keyword-supporting procedures like this:
5740 (use-modules (ice-9 optargs))
5742 (define (make-window . args)
5743 (let-keywords args #f ((depth screen-depth)
5751 Or, even more economically, like this:
5754 (use-modules (ice-9 optargs))
5756 (define* (make-window #:key (depth screen-depth)
5763 For further details on @code{let-keywords}, @code{define*} and other
5764 facilities provided by the @code{(ice-9 optargs)} module, see
5765 @ref{Optional Arguments}.
5768 @node Keyword Read Syntax
5769 @subsubsection Keyword Read Syntax
5771 Guile, by default, only recognizes a keyword syntax that is compatible
5772 with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
5773 same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
5774 external representation of the keyword named @code{NAME}. Keyword
5775 objects print using this syntax as well, so values containing keyword
5776 objects can be read back into Guile. When used in an expression,
5777 keywords are self-quoting objects.
5779 If the @code{keyword} read option is set to @code{'prefix}, Guile also
5780 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
5781 of the form @code{:NAME} are read as symbols, as required by R5RS.
5783 @cindex SRFI-88 keyword syntax
5785 If the @code{keyword} read option is set to @code{'postfix}, Guile
5786 recognizes the SRFI-88 read syntax @code{NAME:} (@pxref{SRFI-88}).
5787 Otherwise, tokens of this form are read as symbols.
5789 To enable and disable the alternative non-R5RS keyword syntax, you use
5790 the @code{read-set!} procedure documented in @ref{User level options
5791 interfaces} and @ref{Reader options}. Note that the @code{prefix} and
5792 @code{postfix} syntax are mutually exclusive.
5795 (read-set! keywords 'prefix)
5805 (read-set! keywords 'postfix)
5815 (read-set! keywords #f)
5823 ERROR: In expression :type:
5824 ERROR: Unbound variable: :type
5825 ABORT: (unbound-variable)
5828 @node Keyword Procedures
5829 @subsubsection Keyword Procedures
5831 @deffn {Scheme Procedure} keyword? obj
5832 @deffnx {C Function} scm_keyword_p (obj)
5833 Return @code{#t} if the argument @var{obj} is a keyword, else
5837 @deffn {Scheme Procedure} keyword->symbol keyword
5838 @deffnx {C Function} scm_keyword_to_symbol (keyword)
5839 Return the symbol with the same name as @var{keyword}.
5842 @deffn {Scheme Procedure} symbol->keyword symbol
5843 @deffnx {C Function} scm_symbol_to_keyword (symbol)
5844 Return the keyword with the same name as @var{symbol}.
5847 @deftypefn {C Function} int scm_is_keyword (SCM obj)
5848 Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
5851 @deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5852 @deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5853 Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5854 (@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5855 (@var{str}, @var{len}))}, respectively.
5859 @subsection ``Functionality-Centric'' Data Types
5861 Procedures and macros are documented in their own chapter: see
5862 @ref{Procedures} and @ref{Macros}.
5864 Variable objects are documented as part of the description of Guile's
5865 module system: see @ref{Variables}.
5867 Asyncs, dynamic roots and fluids are described in the chapter on
5868 scheduling: see @ref{Scheduling}.
5870 Hooks are documented in the chapter on general utility functions: see
5873 Ports are described in the chapter on I/O: see @ref{Input and Output}.
5877 @c TeX-master: "guile.texi"