2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
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.
49 * Keywords:: Self-quoting, customizable display keywords.
50 * Other Types:: "Functionality-centric" data types.
58 The two boolean values are @code{#t} for true and @code{#f} for false.
60 Boolean values are returned by predicate procedures, such as the general
61 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
62 (@pxref{Equality}) and numerical and string comparison operators like
63 @code{string=?} (@pxref{String Comparison}) and @code{<=}
73 (equal? "house" "houses")
81 In test condition contexts like @code{if} and @code{cond} (@pxref{if
82 cond case}), where a group of subexpressions will be evaluated only if a
83 @var{condition} expression evaluates to ``true'', ``true'' means any
84 value at all except @code{#f}.
97 A result of this asymmetry is that typical Scheme source code more often
98 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
99 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
100 not necessary to represent an @code{if} or @code{cond} true value.
102 It is important to note that @code{#f} is @strong{not} equivalent to any
103 other Scheme value. In particular, @code{#f} is not the same as the
104 number 0 (like in C and C++), and not the same as the ``empty list''
105 (like in some Lisp dialects).
107 In C, the two Scheme boolean values are available as the two constants
108 @code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
109 Care must be taken with the false value @code{SCM_BOOL_F}: it is not
110 false when used in C conditionals. In order to test for it, use
111 @code{scm_is_false} or @code{scm_is_true}.
114 @deffn {Scheme Procedure} not x
115 @deffnx {C Function} scm_not (x)
116 Return @code{#t} if @var{x} is @code{#f}, else return @code{#f}.
120 @deffn {Scheme Procedure} boolean? obj
121 @deffnx {C Function} scm_boolean_p (obj)
122 Return @code{#t} if @var{obj} is either @code{#t} or @code{#f}, else
126 @deftypevr {C Macro} SCM SCM_BOOL_T
127 The @code{SCM} representation of the Scheme object @code{#t}.
130 @deftypevr {C Macro} SCM SCM_BOOL_F
131 The @code{SCM} representation of the Scheme object @code{#f}.
134 @deftypefn {C Function} int scm_is_true (SCM obj)
135 Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
138 @deftypefn {C Function} int scm_is_false (SCM obj)
139 Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
142 @deftypefn {C Function} int scm_is_bool (SCM obj)
143 Return @code{1} if @var{obj} is either @code{#t} or @code{#f}, else
147 @deftypefn {C Function} SCM scm_from_bool (int val)
148 Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
151 @deftypefn {C Function} int scm_to_bool (SCM val)
152 Return @code{1} if @var{val} is @code{SCM_BOOL_T}, return @code{0}
153 when @var{val} is @code{SCM_BOOL_F}, else signal a `wrong type' error.
155 You should probably use @code{scm_is_true} instead of this function
156 when you just want to test a @code{SCM} value for trueness.
160 @subsection Numerical data types
163 Guile supports a rich ``tower'' of numerical types --- integer,
164 rational, real and complex --- and provides an extensive set of
165 mathematical and scientific functions for operating on numerical
166 data. This section of the manual documents those types and functions.
168 You may also find it illuminating to read R5RS's presentation of numbers
169 in Scheme, which is particularly clear and accessible: see
170 @ref{Numbers,,,r5rs,R5RS}.
173 * Numerical Tower:: Scheme's numerical "tower".
174 * Integers:: Whole numbers.
175 * Reals and Rationals:: Real and rational numbers.
176 * Complex Numbers:: Complex numbers.
177 * Exactness:: Exactness and inexactness.
178 * Number Syntax:: Read syntax for numerical data.
179 * Integer Operations:: Operations on integer values.
180 * Comparison:: Comparison predicates.
181 * Conversion:: Converting numbers to and from strings.
182 * Complex:: Complex number operations.
183 * Arithmetic:: Arithmetic functions.
184 * Scientific:: Scientific functions.
185 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
186 * Random:: Random number generation.
190 @node Numerical Tower
191 @subsubsection Scheme's Numerical ``Tower''
194 Scheme's numerical ``tower'' consists of the following categories of
199 Whole numbers, positive or negative; e.g.@: --5, 0, 18.
202 The set of numbers that can be expressed as @math{@var{p}/@var{q}}
203 where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
204 pi (an irrational number) doesn't. These include integers
208 The set of numbers that describes all possible positions along a
209 one-dimensional line. This includes rationals as well as irrational
212 @item complex numbers
213 The set of numbers that describes all possible positions in a two
214 dimensional space. This includes real as well as imaginary numbers
215 (@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
216 @var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
220 It is called a tower because each category ``sits on'' the one that
221 follows it, in the sense that every integer is also a rational, every
222 rational is also real, and every real number is also a complex number
223 (but with zero imaginary part).
225 In addition to the classification into integers, rationals, reals and
226 complex numbers, Scheme also distinguishes between whether a number is
227 represented exactly or not. For example, the result of
228 @m{2\sin(\pi/4),2*sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)}, but Guile
229 can represent neither @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
230 Instead, it stores an inexact approximation, using the C type
233 Guile can represent exact rationals of any magnitude, inexact
234 rationals that fit into a C @code{double}, and inexact complex numbers
235 with @code{double} real and imaginary parts.
237 The @code{number?} predicate may be applied to any Scheme value to
238 discover whether the value is any of the supported numerical types.
240 @deffn {Scheme Procedure} number? obj
241 @deffnx {C Function} scm_number_p (obj)
242 Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
251 (number? "hello there!")
254 (define pi 3.141592654)
259 @deftypefn {C Function} int scm_is_number (SCM obj)
260 This is equivalent to @code{scm_is_true (scm_number_p (obj))}.
263 The next few subsections document each of Guile's numerical data types
267 @subsubsection Integers
269 @tpindex Integer numbers
273 Integers are whole numbers, that is numbers with no fractional part,
274 such as 2, 83, and @minus{}3789.
276 Integers in Guile can be arbitrarily big, as shown by the following
280 (define (factorial n)
281 (let loop ((n n) (product 1))
284 (loop (- n 1) (* product n)))))
290 @result{} 2432902008176640000
293 @result{} -119622220865480194561963161495657715064383733760000000000
296 Readers whose background is in programming languages where integers are
297 limited by the need to fit into just 4 or 8 bytes of memory may find
298 this surprising, or suspect that Guile's representation of integers is
299 inefficient. In fact, Guile achieves a near optimal balance of
300 convenience and efficiency by using the host computer's native
301 representation of integers where possible, and a more general
302 representation where the required number does not fit in the native
303 form. Conversion between these two representations is automatic and
304 completely invisible to the Scheme level programmer.
306 C has a host of different integer types, and Guile offers a host of
307 functions to convert between them and the @code{SCM} representation.
308 For example, a C @code{int} can be handled with @code{scm_to_int} and
309 @code{scm_from_int}. Guile also defines a few C integer types of its
310 own, to help with differences between systems.
312 C integer types that are not covered can be handled with the generic
313 @code{scm_to_signed_integer} and @code{scm_from_signed_integer} for
314 signed types, or with @code{scm_to_unsigned_integer} and
315 @code{scm_from_unsigned_integer} for unsigned types.
317 Scheme integers can be exact and inexact. For example, a number
318 written as @code{3.0} with an explicit decimal-point is inexact, but
319 it is also an integer. The functions @code{integer?} and
320 @code{scm_is_integer} report true for such a number, but the functions
321 @code{scm_is_signed_integer} and @code{scm_is_unsigned_integer} only
322 allow exact integers and thus report false. Likewise, the conversion
323 functions like @code{scm_to_signed_integer} only accept exact
326 The motivation for this behavior is that the inexactness of a number
327 should not be lost silently. If you want to allow inexact integers,
328 you can explicitly insert a call to @code{inexact->exact} or to its C
329 equivalent @code{scm_inexact_to_exact}. (Only inexact integers will
330 be converted by this call into exact integers; inexact non-integers
331 will become exact fractions.)
333 @deffn {Scheme Procedure} integer? x
334 @deffnx {C Function} scm_integer_p (x)
335 Return @code{#t} if @var{x} is an exact or inexact integer number, else
353 @deftypefn {C Function} int scm_is_integer (SCM x)
354 This is equivalent to @code{scm_is_true (scm_integer_p (x))}.
357 @defvr {C Type} scm_t_int8
358 @defvrx {C Type} scm_t_uint8
359 @defvrx {C Type} scm_t_int16
360 @defvrx {C Type} scm_t_uint16
361 @defvrx {C Type} scm_t_int32
362 @defvrx {C Type} scm_t_uint32
363 @defvrx {C Type} scm_t_int64
364 @defvrx {C Type} scm_t_uint64
365 @defvrx {C Type} scm_t_intmax
366 @defvrx {C Type} scm_t_uintmax
367 The C types are equivalent to the corresponding ISO C types but are
368 defined on all platforms, with the exception of @code{scm_t_int64} and
369 @code{scm_t_uint64}, which are only defined when a 64-bit type is
370 available. For example, @code{scm_t_int8} is equivalent to
373 You can regard these definitions as a stop-gap measure until all
374 platforms provide these types. If you know that all the platforms
375 that you are interested in already provide these types, it is better
376 to use them directly instead of the types provided by Guile.
379 @deftypefn {C Function} int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
380 @deftypefnx {C Function} int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
381 Return @code{1} when @var{x} represents an exact integer that is
382 between @var{min} and @var{max}, inclusive.
384 These functions can be used to check whether a @code{SCM} value will
385 fit into a given range, such as the range of a given C integer type.
386 If you just want to convert a @code{SCM} value to a given C integer
387 type, use one of the conversion functions directly.
390 @deftypefn {C Function} scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
391 @deftypefnx {C Function} scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
392 When @var{x} represents an exact integer that is between @var{min} and
393 @var{max} inclusive, return that integer. Else signal an error,
394 either a `wrong-type' error when @var{x} is not an exact integer, or
395 an `out-of-range' error when it doesn't fit the given range.
398 @deftypefn {C Function} SCM scm_from_signed_integer (scm_t_intmax x)
399 @deftypefnx {C Function} SCM scm_from_unsigned_integer (scm_t_uintmax x)
400 Return the @code{SCM} value that represents the integer @var{x}. This
401 function will always succeed and will always return an exact number.
404 @deftypefn {C Function} char scm_to_char (SCM x)
405 @deftypefnx {C Function} {signed char} scm_to_schar (SCM x)
406 @deftypefnx {C Function} {unsigned char} scm_to_uchar (SCM x)
407 @deftypefnx {C Function} short scm_to_short (SCM x)
408 @deftypefnx {C Function} {unsigned short} scm_to_ushort (SCM x)
409 @deftypefnx {C Function} int scm_to_int (SCM x)
410 @deftypefnx {C Function} {unsigned int} scm_to_uint (SCM x)
411 @deftypefnx {C Function} long scm_to_long (SCM x)
412 @deftypefnx {C Function} {unsigned long} scm_to_ulong (SCM x)
413 @deftypefnx {C Function} {long long} scm_to_long_long (SCM x)
414 @deftypefnx {C Function} {unsigned long long} scm_to_ulong_long (SCM x)
415 @deftypefnx {C Function} size_t scm_to_size_t (SCM x)
416 @deftypefnx {C Function} ssize_t scm_to_ssize_t (SCM x)
417 @deftypefnx {C Function} scm_t_int8 scm_to_int8 (SCM x)
418 @deftypefnx {C Function} scm_t_uint8 scm_to_uint8 (SCM x)
419 @deftypefnx {C Function} scm_t_int16 scm_to_int16 (SCM x)
420 @deftypefnx {C Function} scm_t_uint16 scm_to_uint16 (SCM x)
421 @deftypefnx {C Function} scm_t_int32 scm_to_int32 (SCM x)
422 @deftypefnx {C Function} scm_t_uint32 scm_to_uint32 (SCM x)
423 @deftypefnx {C Function} scm_t_int64 scm_to_int64 (SCM x)
424 @deftypefnx {C Function} scm_t_uint64 scm_to_uint64 (SCM x)
425 @deftypefnx {C Function} scm_t_intmax scm_to_intmax (SCM x)
426 @deftypefnx {C Function} scm_t_uintmax scm_to_uintmax (SCM x)
427 When @var{x} represents an exact integer that fits into the indicated
428 C type, return that integer. Else signal an error, either a
429 `wrong-type' error when @var{x} is not an exact integer, or an
430 `out-of-range' error when it doesn't fit the given range.
432 The functions @code{scm_to_long_long}, @code{scm_to_ulong_long},
433 @code{scm_to_int64}, and @code{scm_to_uint64} are only available when
434 the corresponding types are.
437 @deftypefn {C Function} SCM scm_from_char (char x)
438 @deftypefnx {C Function} SCM scm_from_schar (signed char x)
439 @deftypefnx {C Function} SCM scm_from_uchar (unsigned char x)
440 @deftypefnx {C Function} SCM scm_from_short (short x)
441 @deftypefnx {C Function} SCM scm_from_ushort (unsigned short x)
442 @deftypefnx {C Function} SCM scm_from_int (int x)
443 @deftypefnx {C Function} SCM scm_from_uint (unsigned int x)
444 @deftypefnx {C Function} SCM scm_from_long (long x)
445 @deftypefnx {C Function} SCM scm_from_ulong (unsigned long x)
446 @deftypefnx {C Function} SCM scm_from_long_long (long long x)
447 @deftypefnx {C Function} SCM scm_from_ulong_long (unsigned long long x)
448 @deftypefnx {C Function} SCM scm_from_size_t (size_t x)
449 @deftypefnx {C Function} SCM scm_from_ssize_t (ssize_t x)
450 @deftypefnx {C Function} SCM scm_from_int8 (scm_t_int8 x)
451 @deftypefnx {C Function} SCM scm_from_uint8 (scm_t_uint8 x)
452 @deftypefnx {C Function} SCM scm_from_int16 (scm_t_int16 x)
453 @deftypefnx {C Function} SCM scm_from_uint16 (scm_t_uint16 x)
454 @deftypefnx {C Function} SCM scm_from_int32 (scm_t_int32 x)
455 @deftypefnx {C Function} SCM scm_from_uint32 (scm_t_uint32 x)
456 @deftypefnx {C Function} SCM scm_from_int64 (scm_t_int64 x)
457 @deftypefnx {C Function} SCM scm_from_uint64 (scm_t_uint64 x)
458 @deftypefnx {C Function} SCM scm_from_intmax (scm_t_intmax x)
459 @deftypefnx {C Function} SCM scm_from_uintmax (scm_t_uintmax x)
460 Return the @code{SCM} value that represents the integer @var{x}.
461 These functions will always succeed and will always return an exact
465 @deftypefn {C Function} void scm_to_mpz (SCM val, mpz_t rop)
466 Assign @var{val} to the multiple precision integer @var{rop}.
467 @var{val} must be an exact integer, otherwise an error will be
468 signalled. @var{rop} must have been initialized with @code{mpz_init}
469 before this function is called. When @var{rop} is no longer needed
470 the occupied space must be freed with @code{mpz_clear}.
471 @xref{Initializing Integers,,, gmp, GNU MP Manual}, for details.
474 @deftypefn {C Function} SCM scm_from_mpz (mpz_t val)
475 Return the @code{SCM} value that represents @var{val}.
478 @node Reals and Rationals
479 @subsubsection Real and Rational Numbers
480 @tpindex Real numbers
481 @tpindex Rational numbers
486 Mathematically, the real numbers are the set of numbers that describe
487 all possible points along a continuous, infinite, one-dimensional line.
488 The rational numbers are the set of all numbers that can be written as
489 fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
490 All rational numbers are also real, but there are real numbers that
491 are not rational, for example @m{\sqrt2, the square root of 2}, and
494 Guile can represent both exact and inexact rational numbers, but it
495 can not represent irrational numbers. Exact rationals are represented
496 by storing the numerator and denominator as two exact integers.
497 Inexact rationals are stored as floating point numbers using the C
500 Exact rationals are written as a fraction of integers. There must be
501 no whitespace around the slash:
508 Even though the actual encoding of inexact rationals is in binary, it
509 may be helpful to think of it as a decimal number with a limited
510 number of significant figures and a decimal point somewhere, since
511 this corresponds to the standard notation for non-whole numbers. For
517 -5648394822220000000000.0
521 The limited precision of Guile's encoding means that any ``real'' number
522 in Guile can be written in a rational form, by multiplying and then dividing
523 by sufficient powers of 10 (or in fact, 2). For example,
524 @samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
525 100000000000000000. In Guile's current incarnation, therefore, the
526 @code{rational?} and @code{real?} predicates are equivalent.
529 Dividing by an exact zero leads to a error message, as one might
530 expect. However, dividing by an inexact zero does not produce an
531 error. Instead, the result of the division is either plus or minus
532 infinity, depending on the sign of the divided number.
534 The infinities are written @samp{+inf.0} and @samp{-inf.0},
535 respectively. This syntax is also recognized by @code{read} as an
536 extension to the usual Scheme syntax. The infinities are considered to
537 be inexact, non-integer values.
539 Dividing zero by zero yields something that is not a number at all:
540 @samp{+nan.0}. This is the special `not a number' value.
542 On platforms that follow @acronym{IEEE} 754 for their floating point
543 arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
544 are implemented using the corresponding @acronym{IEEE} 754 values.
545 They behave in arithmetic operations like @acronym{IEEE} 754 describes
546 it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
548 While @samp{+nan.0} is not @code{=} to itself, it is @code{eqv?} to
551 To test for the special values, use the functions @code{inf?} and
552 @code{nan?}. To test for numbers than are neither infinite nor a NaN,
555 @deffn {Scheme Procedure} real? obj
556 @deffnx {C Function} scm_real_p (obj)
557 Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
558 that the sets of integer and rational values form subsets of the set
559 of real numbers, so the predicate will also be fulfilled if @var{obj}
560 is an integer number or a rational number.
563 @deffn {Scheme Procedure} rational? x
564 @deffnx {C Function} scm_rational_p (x)
565 Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
566 Note that the set of integer values forms a subset of the set of
567 rational numbers, i. e. the predicate will also be fulfilled if
568 @var{x} is an integer number.
570 Since Guile can not represent irrational numbers, every number
571 satisfying @code{real?} also satisfies @code{rational?} in Guile.
574 @deffn {Scheme Procedure} rationalize x eps
575 @deffnx {C Function} scm_rationalize (x, eps)
576 Returns the @emph{simplest} rational number differing
577 from @var{x} by no more than @var{eps}.
579 As required by @acronym{R5RS}, @code{rationalize} only returns an
580 exact result when both its arguments are exact. Thus, you might need
581 to use @code{inexact->exact} on the arguments.
584 (rationalize (inexact->exact 1.2) 1/100)
590 @deffn {Scheme Procedure} inf? x
591 @deffnx {C Function} scm_inf_p (x)
592 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
596 @deffn {Scheme Procedure} nan? x
597 @deffnx {C Function} scm_nan_p (x)
598 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
601 @deffn {Scheme Procedure} finite? x
602 @deffnx {C Function} scm_finite_p (x)
603 Return @code{#t} if @var{x} is neither infinite nor a NaN,
607 @deffn {Scheme Procedure} nan
608 @deffnx {C Function} scm_nan ()
612 @deffn {Scheme Procedure} inf
613 @deffnx {C Function} scm_inf ()
617 @deffn {Scheme Procedure} numerator x
618 @deffnx {C Function} scm_numerator (x)
619 Return the numerator of the rational number @var{x}.
622 @deffn {Scheme Procedure} denominator x
623 @deffnx {C Function} scm_denominator (x)
624 Return the denominator of the rational number @var{x}.
627 @deftypefn {C Function} int scm_is_real (SCM val)
628 @deftypefnx {C Function} int scm_is_rational (SCM val)
629 Equivalent to @code{scm_is_true (scm_real_p (val))} and
630 @code{scm_is_true (scm_rational_p (val))}, respectively.
633 @deftypefn {C Function} double scm_to_double (SCM val)
634 Returns the number closest to @var{val} that is representable as a
635 @code{double}. Returns infinity for a @var{val} that is too large in
636 magnitude. The argument @var{val} must be a real number.
639 @deftypefn {C Function} SCM scm_from_double (double val)
640 Return the @code{SCM} value that represents @var{val}. The returned
641 value is inexact according to the predicate @code{inexact?}, but it
642 will be exactly equal to @var{val}.
645 @node Complex Numbers
646 @subsubsection Complex Numbers
647 @tpindex Complex numbers
651 Complex numbers are the set of numbers that describe all possible points
652 in a two-dimensional space. The two coordinates of a particular point
653 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
654 the complex number that describes that point.
656 In Guile, complex numbers are written in rectangular form as the sum of
657 their real and imaginary parts, using the symbol @code{i} to indicate
672 Polar form can also be used, with an @samp{@@} between magnitude and
676 1@@3.141592 @result{} -1.0 (approx)
677 -1@@1.57079 @result{} 0.0-1.0i (approx)
680 Guile represents a complex number with a non-zero imaginary part as a
681 pair of inexact rationals, so the real and imaginary parts of a
682 complex number have the same properties of inexactness and limited
683 precision as single inexact rational numbers. Guile can not represent
684 exact complex numbers with non-zero imaginary parts.
686 @deffn {Scheme Procedure} complex? z
687 @deffnx {C Function} scm_complex_p (z)
688 Return @code{#t} if @var{x} is a complex number, @code{#f}
689 otherwise. Note that the sets of real, rational and integer
690 values form subsets of the set of complex numbers, i. e. the
691 predicate will also be fulfilled if @var{x} is a real,
692 rational or integer number.
695 @deftypefn {C Function} int scm_is_complex (SCM val)
696 Equivalent to @code{scm_is_true (scm_complex_p (val))}.
700 @subsubsection Exact and Inexact Numbers
701 @tpindex Exact numbers
702 @tpindex Inexact numbers
706 @rnindex exact->inexact
707 @rnindex inexact->exact
709 R5RS requires that a calculation involving inexact numbers always
710 produces an inexact result. To meet this requirement, Guile
711 distinguishes between an exact integer value such as @samp{5} and the
712 corresponding inexact real value which, to the limited precision
713 available, has no fractional part, and is printed as @samp{5.0}. Guile
714 will only convert the latter value to the former when forced to do so by
715 an invocation of the @code{inexact->exact} procedure.
717 @deffn {Scheme Procedure} exact? z
718 @deffnx {C Function} scm_exact_p (z)
719 Return @code{#t} if the number @var{z} is exact, @code{#f}
735 @deffn {Scheme Procedure} inexact? z
736 @deffnx {C Function} scm_inexact_p (z)
737 Return @code{#t} if the number @var{z} is inexact, @code{#f}
741 @deffn {Scheme Procedure} inexact->exact z
742 @deffnx {C Function} scm_inexact_to_exact (z)
743 Return an exact number that is numerically closest to @var{z}, when
744 there is one. For inexact rationals, Guile returns the exact rational
745 that is numerically equal to the inexact rational. Inexact complex
746 numbers with a non-zero imaginary part can not be made exact.
753 The following happens because 12/10 is not exactly representable as a
754 @code{double} (on most platforms). However, when reading a decimal
755 number that has been marked exact with the ``#e'' prefix, Guile is
756 able to represent it correctly.
760 @result{} 5404319552844595/4503599627370496
768 @c begin (texi-doc-string "guile" "exact->inexact")
769 @deffn {Scheme Procedure} exact->inexact z
770 @deffnx {C Function} scm_exact_to_inexact (z)
771 Convert the number @var{z} to its inexact representation.
776 @subsubsection Read Syntax for Numerical Data
778 The read syntax for integers is a string of digits, optionally
779 preceded by a minus or plus character, a code indicating the
780 base in which the integer is encoded, and a code indicating whether
781 the number is exact or inexact. The supported base codes are:
786 the integer is written in binary (base 2)
790 the integer is written in octal (base 8)
794 the integer is written in decimal (base 10)
798 the integer is written in hexadecimal (base 16)
801 If the base code is omitted, the integer is assumed to be decimal. The
802 following examples show how these base codes are used.
821 The codes for indicating exactness (which can, incidentally, be applied
822 to all numerical values) are:
831 the number is inexact.
834 If the exactness indicator is omitted, the number is exact unless it
835 contains a radix point. Since Guile can not represent exact complex
836 numbers, an error is signalled when asking for them.
846 ERROR: Wrong type argument
849 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
850 plus and minus infinity, respectively. The value must be written
851 exactly as shown, that is, they always must have a sign and exactly
852 one zero digit after the decimal point. It also understands
853 @samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
854 The sign is ignored for `not-a-number' and the value is always printed
857 @node Integer Operations
858 @subsubsection Operations on Integer Values
867 @deffn {Scheme Procedure} odd? n
868 @deffnx {C Function} scm_odd_p (n)
869 Return @code{#t} if @var{n} is an odd number, @code{#f}
873 @deffn {Scheme Procedure} even? n
874 @deffnx {C Function} scm_even_p (n)
875 Return @code{#t} if @var{n} is an even number, @code{#f}
879 @c begin (texi-doc-string "guile" "quotient")
880 @c begin (texi-doc-string "guile" "remainder")
881 @deffn {Scheme Procedure} quotient n d
882 @deffnx {Scheme Procedure} remainder n d
883 @deffnx {C Function} scm_quotient (n, d)
884 @deffnx {C Function} scm_remainder (n, d)
885 Return the quotient or remainder from @var{n} divided by @var{d}. The
886 quotient is rounded towards zero, and the remainder will have the same
887 sign as @var{n}. In all cases quotient and remainder satisfy
888 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
891 (remainder 13 4) @result{} 1
892 (remainder -13 4) @result{} -1
896 @c begin (texi-doc-string "guile" "modulo")
897 @deffn {Scheme Procedure} modulo n d
898 @deffnx {C Function} scm_modulo (n, d)
899 Return the remainder from @var{n} divided by @var{d}, with the same
903 (modulo 13 4) @result{} 1
904 (modulo -13 4) @result{} 3
905 (modulo 13 -4) @result{} -3
906 (modulo -13 -4) @result{} -1
910 @c begin (texi-doc-string "guile" "gcd")
911 @deffn {Scheme Procedure} gcd x@dots{}
912 @deffnx {C Function} scm_gcd (x, y)
913 Return the greatest common divisor of all arguments.
914 If called without arguments, 0 is returned.
916 The C function @code{scm_gcd} always takes two arguments, while the
917 Scheme function can take an arbitrary number.
920 @c begin (texi-doc-string "guile" "lcm")
921 @deffn {Scheme Procedure} lcm x@dots{}
922 @deffnx {C Function} scm_lcm (x, y)
923 Return the least common multiple of the arguments.
924 If called without arguments, 1 is returned.
926 The C function @code{scm_lcm} always takes two arguments, while the
927 Scheme function can take an arbitrary number.
930 @deffn {Scheme Procedure} modulo-expt n k m
931 @deffnx {C Function} scm_modulo_expt (n, k, m)
932 Return @var{n} raised to the integer exponent
933 @var{k}, modulo @var{m}.
942 @subsubsection Comparison Predicates
947 The C comparison functions below always takes two arguments, while the
948 Scheme functions can take an arbitrary number. Also keep in mind that
949 the C functions return one of the Scheme boolean values
950 @code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
951 is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
952 y))} when testing the two Scheme numbers @code{x} and @code{y} for
953 equality, for example.
955 @c begin (texi-doc-string "guile" "=")
956 @deffn {Scheme Procedure} =
957 @deffnx {C Function} scm_num_eq_p (x, y)
958 Return @code{#t} if all parameters are numerically equal.
961 @c begin (texi-doc-string "guile" "<")
962 @deffn {Scheme Procedure} <
963 @deffnx {C Function} scm_less_p (x, y)
964 Return @code{#t} if the list of parameters is monotonically
968 @c begin (texi-doc-string "guile" ">")
969 @deffn {Scheme Procedure} >
970 @deffnx {C Function} scm_gr_p (x, y)
971 Return @code{#t} if the list of parameters is monotonically
975 @c begin (texi-doc-string "guile" "<=")
976 @deffn {Scheme Procedure} <=
977 @deffnx {C Function} scm_leq_p (x, y)
978 Return @code{#t} if the list of parameters is monotonically
982 @c begin (texi-doc-string "guile" ">=")
983 @deffn {Scheme Procedure} >=
984 @deffnx {C Function} scm_geq_p (x, y)
985 Return @code{#t} if the list of parameters is monotonically
989 @c begin (texi-doc-string "guile" "zero?")
990 @deffn {Scheme Procedure} zero? z
991 @deffnx {C Function} scm_zero_p (z)
992 Return @code{#t} if @var{z} is an exact or inexact number equal to
996 @c begin (texi-doc-string "guile" "positive?")
997 @deffn {Scheme Procedure} positive? x
998 @deffnx {C Function} scm_positive_p (x)
999 Return @code{#t} if @var{x} is an exact or inexact number greater than
1003 @c begin (texi-doc-string "guile" "negative?")
1004 @deffn {Scheme Procedure} negative? x
1005 @deffnx {C Function} scm_negative_p (x)
1006 Return @code{#t} if @var{x} is an exact or inexact number less than
1012 @subsubsection Converting Numbers To and From Strings
1013 @rnindex number->string
1014 @rnindex string->number
1016 The following procedures read and write numbers according to their
1017 external representation as defined by R5RS (@pxref{Lexical structure,
1018 R5RS Lexical Structure,, r5rs, The Revised^5 Report on the Algorithmic
1019 Language Scheme}). @xref{Number Input and Output, the @code{(ice-9
1020 i18n)} module}, for locale-dependent number parsing.
1022 @deffn {Scheme Procedure} number->string n [radix]
1023 @deffnx {C Function} scm_number_to_string (n, radix)
1024 Return a string holding the external representation of the
1025 number @var{n} in the given @var{radix}. If @var{n} is
1026 inexact, a radix of 10 will be used.
1029 @deffn {Scheme Procedure} string->number string [radix]
1030 @deffnx {C Function} scm_string_to_number (string, radix)
1031 Return a number of the maximally precise representation
1032 expressed by the given @var{string}. @var{radix} must be an
1033 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
1034 is a default radix that may be overridden by an explicit radix
1035 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1036 supplied, then the default radix is 10. If string is not a
1037 syntactically valid notation for a number, then
1038 @code{string->number} returns @code{#f}.
1041 @deftypefn {C Function} SCM scm_c_locale_stringn_to_number (const char *string, size_t len, unsigned radix)
1042 As per @code{string->number} above, but taking a C string, as pointer
1043 and length. The string characters should be in the current locale
1044 encoding (@code{locale} in the name refers only to that, there's no
1045 locale-dependent parsing).
1050 @subsubsection Complex Number Operations
1051 @rnindex make-rectangular
1058 @deffn {Scheme Procedure} make-rectangular real_part imaginary_part
1059 @deffnx {C Function} scm_make_rectangular (real_part, imaginary_part)
1060 Return a complex number constructed of the given @var{real-part} and @var{imaginary-part} parts.
1063 @deffn {Scheme Procedure} make-polar x y
1064 @deffnx {C Function} scm_make_polar (x, y)
1066 Return the complex number @var{x} * e^(i * @var{y}).
1069 @c begin (texi-doc-string "guile" "real-part")
1070 @deffn {Scheme Procedure} real-part z
1071 @deffnx {C Function} scm_real_part (z)
1072 Return the real part of the number @var{z}.
1075 @c begin (texi-doc-string "guile" "imag-part")
1076 @deffn {Scheme Procedure} imag-part z
1077 @deffnx {C Function} scm_imag_part (z)
1078 Return the imaginary part of the number @var{z}.
1081 @c begin (texi-doc-string "guile" "magnitude")
1082 @deffn {Scheme Procedure} magnitude z
1083 @deffnx {C Function} scm_magnitude (z)
1084 Return the magnitude of the number @var{z}. This is the same as
1085 @code{abs} for real arguments, but also allows complex numbers.
1088 @c begin (texi-doc-string "guile" "angle")
1089 @deffn {Scheme Procedure} angle z
1090 @deffnx {C Function} scm_angle (z)
1091 Return the angle of the complex number @var{z}.
1094 @deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1095 @deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1096 Like @code{scm_make_rectangular} or @code{scm_make_polar},
1097 respectively, but these functions take @code{double}s as their
1101 @deftypefn {C Function} double scm_c_real_part (z)
1102 @deftypefnx {C Function} double scm_c_imag_part (z)
1103 Returns the real or imaginary part of @var{z} as a @code{double}.
1106 @deftypefn {C Function} double scm_c_magnitude (z)
1107 @deftypefnx {C Function} double scm_c_angle (z)
1108 Returns the magnitude or angle of @var{z} as a @code{double}.
1113 @subsubsection Arithmetic Functions
1128 The C arithmetic functions below always takes two arguments, while the
1129 Scheme functions can take an arbitrary number. When you need to
1130 invoke them with just one argument, for example to compute the
1131 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1132 one: @code{scm_difference (x, SCM_UNDEFINED)}.
1134 @c begin (texi-doc-string "guile" "+")
1135 @deffn {Scheme Procedure} + z1 @dots{}
1136 @deffnx {C Function} scm_sum (z1, z2)
1137 Return the sum of all parameter values. Return 0 if called without any
1141 @c begin (texi-doc-string "guile" "-")
1142 @deffn {Scheme Procedure} - z1 z2 @dots{}
1143 @deffnx {C Function} scm_difference (z1, z2)
1144 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1145 the sum of all but the first argument are subtracted from the first
1149 @c begin (texi-doc-string "guile" "*")
1150 @deffn {Scheme Procedure} * z1 @dots{}
1151 @deffnx {C Function} scm_product (z1, z2)
1152 Return the product of all arguments. If called without arguments, 1 is
1156 @c begin (texi-doc-string "guile" "/")
1157 @deffn {Scheme Procedure} / z1 z2 @dots{}
1158 @deffnx {C Function} scm_divide (z1, z2)
1159 Divide the first argument by the product of the remaining arguments. If
1160 called with one argument @var{z1}, 1/@var{z1} is returned.
1163 @deffn {Scheme Procedure} 1+ z
1164 @deffnx {C Function} scm_oneplus (z)
1165 Return @math{@var{z} + 1}.
1168 @deffn {Scheme Procedure} 1- z
1169 @deffnx {C function} scm_oneminus (z)
1170 Return @math{@var{z} - 1}.
1173 @c begin (texi-doc-string "guile" "abs")
1174 @deffn {Scheme Procedure} abs x
1175 @deffnx {C Function} scm_abs (x)
1176 Return the absolute value of @var{x}.
1178 @var{x} must be a number with zero imaginary part. To calculate the
1179 magnitude of a complex number, use @code{magnitude} instead.
1182 @c begin (texi-doc-string "guile" "max")
1183 @deffn {Scheme Procedure} max x1 x2 @dots{}
1184 @deffnx {C Function} scm_max (x1, x2)
1185 Return the maximum of all parameter values.
1188 @c begin (texi-doc-string "guile" "min")
1189 @deffn {Scheme Procedure} min x1 x2 @dots{}
1190 @deffnx {C Function} scm_min (x1, x2)
1191 Return the minimum of all parameter values.
1194 @c begin (texi-doc-string "guile" "truncate")
1195 @deffn {Scheme Procedure} truncate x
1196 @deffnx {C Function} scm_truncate_number (x)
1197 Round the inexact number @var{x} towards zero.
1200 @c begin (texi-doc-string "guile" "round")
1201 @deffn {Scheme Procedure} round x
1202 @deffnx {C Function} scm_round_number (x)
1203 Round the inexact number @var{x} to the nearest integer. When exactly
1204 halfway between two integers, round to the even one.
1207 @c begin (texi-doc-string "guile" "floor")
1208 @deffn {Scheme Procedure} floor x
1209 @deffnx {C Function} scm_floor (x)
1210 Round the number @var{x} towards minus infinity.
1213 @c begin (texi-doc-string "guile" "ceiling")
1214 @deffn {Scheme Procedure} ceiling x
1215 @deffnx {C Function} scm_ceiling (x)
1216 Round the number @var{x} towards infinity.
1219 @deftypefn {C Function} double scm_c_truncate (double x)
1220 @deftypefnx {C Function} double scm_c_round (double x)
1221 Like @code{scm_truncate_number} or @code{scm_round_number},
1222 respectively, but these functions take and return @code{double}
1227 @subsubsection Scientific Functions
1229 The following procedures accept any kind of number as arguments,
1230 including complex numbers.
1233 @c begin (texi-doc-string "guile" "sqrt")
1234 @deffn {Scheme Procedure} sqrt z
1235 Return the square root of @var{z}. Of the two possible roots
1236 (positive and negative), the one with the a positive real part is
1237 returned, or if that's zero then a positive imaginary part. Thus,
1240 (sqrt 9.0) @result{} 3.0
1241 (sqrt -9.0) @result{} 0.0+3.0i
1242 (sqrt 1.0+1.0i) @result{} 1.09868411346781+0.455089860562227i
1243 (sqrt -1.0-1.0i) @result{} 0.455089860562227-1.09868411346781i
1248 @c begin (texi-doc-string "guile" "expt")
1249 @deffn {Scheme Procedure} expt z1 z2
1250 Return @var{z1} raised to the power of @var{z2}.
1254 @c begin (texi-doc-string "guile" "sin")
1255 @deffn {Scheme Procedure} sin z
1256 Return the sine of @var{z}.
1260 @c begin (texi-doc-string "guile" "cos")
1261 @deffn {Scheme Procedure} cos z
1262 Return the cosine of @var{z}.
1266 @c begin (texi-doc-string "guile" "tan")
1267 @deffn {Scheme Procedure} tan z
1268 Return the tangent of @var{z}.
1272 @c begin (texi-doc-string "guile" "asin")
1273 @deffn {Scheme Procedure} asin z
1274 Return the arcsine of @var{z}.
1278 @c begin (texi-doc-string "guile" "acos")
1279 @deffn {Scheme Procedure} acos z
1280 Return the arccosine of @var{z}.
1284 @c begin (texi-doc-string "guile" "atan")
1285 @deffn {Scheme Procedure} atan z
1286 @deffnx {Scheme Procedure} atan y x
1287 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1291 @c begin (texi-doc-string "guile" "exp")
1292 @deffn {Scheme Procedure} exp z
1293 Return e to the power of @var{z}, where e is the base of natural
1294 logarithms (2.71828@dots{}).
1298 @c begin (texi-doc-string "guile" "log")
1299 @deffn {Scheme Procedure} log z
1300 Return the natural logarithm of @var{z}.
1303 @c begin (texi-doc-string "guile" "log10")
1304 @deffn {Scheme Procedure} log10 z
1305 Return the base 10 logarithm of @var{z}.
1308 @c begin (texi-doc-string "guile" "sinh")
1309 @deffn {Scheme Procedure} sinh z
1310 Return the hyperbolic sine of @var{z}.
1313 @c begin (texi-doc-string "guile" "cosh")
1314 @deffn {Scheme Procedure} cosh z
1315 Return the hyperbolic cosine of @var{z}.
1318 @c begin (texi-doc-string "guile" "tanh")
1319 @deffn {Scheme Procedure} tanh z
1320 Return the hyperbolic tangent of @var{z}.
1323 @c begin (texi-doc-string "guile" "asinh")
1324 @deffn {Scheme Procedure} asinh z
1325 Return the hyperbolic arcsine of @var{z}.
1328 @c begin (texi-doc-string "guile" "acosh")
1329 @deffn {Scheme Procedure} acosh z
1330 Return the hyperbolic arccosine of @var{z}.
1333 @c begin (texi-doc-string "guile" "atanh")
1334 @deffn {Scheme Procedure} atanh z
1335 Return the hyperbolic arctangent of @var{z}.
1339 @node Bitwise Operations
1340 @subsubsection Bitwise Operations
1342 For the following bitwise functions, negative numbers are treated as
1343 infinite precision twos-complements. For instance @math{-6} is bits
1344 @math{@dots{}111010}, with infinitely many ones on the left. It can
1345 be seen that adding 6 (binary 110) to such a bit pattern gives all
1348 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1349 @deffnx {C Function} scm_logand (n1, n2)
1350 Return the bitwise @sc{and} of the integer arguments.
1353 (logand) @result{} -1
1354 (logand 7) @result{} 7
1355 (logand #b111 #b011 #b001) @result{} 1
1359 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1360 @deffnx {C Function} scm_logior (n1, n2)
1361 Return the bitwise @sc{or} of the integer arguments.
1364 (logior) @result{} 0
1365 (logior 7) @result{} 7
1366 (logior #b000 #b001 #b011) @result{} 3
1370 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1371 @deffnx {C Function} scm_loxor (n1, n2)
1372 Return the bitwise @sc{xor} of the integer arguments. A bit is
1373 set in the result if it is set in an odd number of arguments.
1376 (logxor) @result{} 0
1377 (logxor 7) @result{} 7
1378 (logxor #b000 #b001 #b011) @result{} 2
1379 (logxor #b000 #b001 #b011 #b011) @result{} 1
1383 @deffn {Scheme Procedure} lognot n
1384 @deffnx {C Function} scm_lognot (n)
1385 Return the integer which is the ones-complement of the integer
1386 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1389 (number->string (lognot #b10000000) 2)
1390 @result{} "-10000001"
1391 (number->string (lognot #b0) 2)
1396 @deffn {Scheme Procedure} logtest j k
1397 @deffnx {C Function} scm_logtest (j, k)
1398 Test whether @var{j} and @var{k} have any 1 bits in common. This is
1399 equivalent to @code{(not (zero? (logand j k)))}, but without actually
1400 calculating the @code{logand}, just testing for non-zero.
1403 (logtest #b0100 #b1011) @result{} #f
1404 (logtest #b0100 #b0111) @result{} #t
1408 @deffn {Scheme Procedure} logbit? index j
1409 @deffnx {C Function} scm_logbit_p (index, j)
1410 Test whether bit number @var{index} in @var{j} is set. @var{index}
1411 starts from 0 for the least significant bit.
1414 (logbit? 0 #b1101) @result{} #t
1415 (logbit? 1 #b1101) @result{} #f
1416 (logbit? 2 #b1101) @result{} #t
1417 (logbit? 3 #b1101) @result{} #t
1418 (logbit? 4 #b1101) @result{} #f
1422 @deffn {Scheme Procedure} ash n cnt
1423 @deffnx {C Function} scm_ash (n, cnt)
1424 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1425 @var{cnt} is negative. This is an ``arithmetic'' shift.
1427 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1428 when @var{cnt} is negative it's a division, rounded towards negative
1429 infinity. (Note that this is not the same rounding as @code{quotient}
1432 With @var{n} viewed as an infinite precision twos complement,
1433 @code{ash} means a left shift introducing zero bits, or a right shift
1437 (number->string (ash #b1 3) 2) @result{} "1000"
1438 (number->string (ash #b1010 -1) 2) @result{} "101"
1440 ;; -23 is bits ...11101001, -6 is bits ...111010
1441 (ash -23 -2) @result{} -6
1445 @deffn {Scheme Procedure} logcount n
1446 @deffnx {C Function} scm_logcount (n)
1447 Return the number of bits in integer @var{n}. If @var{n} is
1448 positive, the 1-bits in its binary representation are counted.
1449 If negative, the 0-bits in its two's-complement binary
1450 representation are counted. If zero, 0 is returned.
1453 (logcount #b10101010)
1462 @deffn {Scheme Procedure} integer-length n
1463 @deffnx {C Function} scm_integer_length (n)
1464 Return the number of bits necessary to represent @var{n}.
1466 For positive @var{n} this is how many bits to the most significant one
1467 bit. For negative @var{n} it's how many bits to the most significant
1468 zero bit in twos complement form.
1471 (integer-length #b10101010) @result{} 8
1472 (integer-length #b1111) @result{} 4
1473 (integer-length 0) @result{} 0
1474 (integer-length -1) @result{} 0
1475 (integer-length -256) @result{} 8
1476 (integer-length -257) @result{} 9
1480 @deffn {Scheme Procedure} integer-expt n k
1481 @deffnx {C Function} scm_integer_expt (n, k)
1482 Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1483 integer, @var{n} can be any number.
1485 Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1486 in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1490 (integer-expt 2 5) @result{} 32
1491 (integer-expt -3 3) @result{} -27
1492 (integer-expt 5 -3) @result{} 1/125
1493 (integer-expt 0 0) @result{} 1
1497 @deffn {Scheme Procedure} bit-extract n start end
1498 @deffnx {C Function} scm_bit_extract (n, start, end)
1499 Return the integer composed of the @var{start} (inclusive)
1500 through @var{end} (exclusive) bits of @var{n}. The
1501 @var{start}th bit becomes the 0-th bit in the result.
1504 (number->string (bit-extract #b1101101010 0 4) 2)
1506 (number->string (bit-extract #b1101101010 4 9) 2)
1513 @subsubsection Random Number Generation
1515 Pseudo-random numbers are generated from a random state object, which
1516 can be created with @code{seed->random-state} or
1517 @code{datum->random-state}. An external representation (i.e. one
1518 which can written with @code{write} and read with @code{read}) of a
1519 random state object can be obtained via
1520 @code{random-state->datum}. The @var{state} parameter to the
1521 various functions below is optional, it defaults to the state object
1522 in the @code{*random-state*} variable.
1524 @deffn {Scheme Procedure} copy-random-state [state]
1525 @deffnx {C Function} scm_copy_random_state (state)
1526 Return a copy of the random state @var{state}.
1529 @deffn {Scheme Procedure} random n [state]
1530 @deffnx {C Function} scm_random (n, state)
1531 Return a number in [0, @var{n}).
1533 Accepts a positive integer or real n and returns a
1534 number of the same type between zero (inclusive) and
1535 @var{n} (exclusive). The values returned have a uniform
1539 @deffn {Scheme Procedure} random:exp [state]
1540 @deffnx {C Function} scm_random_exp (state)
1541 Return an inexact real in an exponential distribution with mean
1542 1. For an exponential distribution with mean @var{u} use @code{(*
1543 @var{u} (random:exp))}.
1546 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1547 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1548 Fills @var{vect} with inexact real random numbers the sum of whose
1549 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1550 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1551 the coordinates are uniformly distributed over the surface of the unit
1555 @deffn {Scheme Procedure} random:normal [state]
1556 @deffnx {C Function} scm_random_normal (state)
1557 Return an inexact real in a normal distribution. The distribution
1558 used has mean 0 and standard deviation 1. For a normal distribution
1559 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1560 (* @var{d} (random:normal)))}.
1563 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1564 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1565 Fills @var{vect} with inexact real random numbers that are
1566 independent and standard normally distributed
1567 (i.e., with mean 0 and variance 1).
1570 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1571 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1572 Fills @var{vect} with inexact real random numbers the sum of whose
1573 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1574 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1575 the coordinates are uniformly distributed within the unit
1577 @c FIXME: What does this mean, particularly the n-sphere part?
1580 @deffn {Scheme Procedure} random:uniform [state]
1581 @deffnx {C Function} scm_random_uniform (state)
1582 Return a uniformly distributed inexact real random number in
1586 @deffn {Scheme Procedure} seed->random-state seed
1587 @deffnx {C Function} scm_seed_to_random_state (seed)
1588 Return a new random state using @var{seed}.
1591 @deffn {Scheme Procedure} datum->random-state datum
1592 @deffnx {C Function} scm_datum_to_random_state (datum)
1593 Return a new random state from @var{datum}, which should have been
1594 obtained by @code{random-state->datum}.
1597 @deffn {Scheme Procedure} random-state->datum state
1598 @deffnx {C Function} scm_random_state_to_datum (state)
1599 Return a datum representation of @var{state} that may be written out and
1600 read back with the Scheme reader.
1603 @defvar *random-state*
1604 The global random state used by the above functions when the
1605 @var{state} parameter is not given.
1608 Note that the initial value of @code{*random-state*} is the same every
1609 time Guile starts up. Therefore, if you don't pass a @var{state}
1610 parameter to the above procedures, and you don't set
1611 @code{*random-state*} to @code{(seed->random-state your-seed)}, where
1612 @code{your-seed} is something that @emph{isn't} the same every time,
1613 you'll get the same sequence of ``random'' numbers on every run.
1615 For example, unless the relevant source code has changed, @code{(map
1616 random (cdr (iota 30)))}, if the first use of random numbers since
1617 Guile started up, will always give:
1620 (map random (cdr (iota 19)))
1622 (0 1 1 2 2 2 1 2 6 7 10 0 5 3 12 5 5 12)
1625 To use the time of day as the random seed, you can use code like this:
1628 (let ((time (gettimeofday)))
1629 (set! *random-state*
1630 (seed->random-state (+ (car time)
1635 And then (depending on the time of day, of course):
1638 (map random (cdr (iota 19)))
1640 (0 0 1 0 2 4 5 4 5 5 9 3 10 1 8 3 14 17)
1643 For security applications, such as password generation, you should use
1644 more bits of seed. Otherwise an open source password generator could
1645 be attacked by guessing the seed@dots{} but that's a subject for
1650 @subsection Characters
1653 In Scheme, there is a data type to describe a single character.
1655 Defining what exactly a character @emph{is} can be more complicated
1656 than it seems. Guile follows the advice of R6RS and uses The Unicode
1657 Standard to help define what a character is. So, for Guile, a
1658 character is anything in the Unicode Character Database.
1661 @cindex Unicode code point
1663 The Unicode Character Database is basically a table of characters
1664 indexed using integers called 'code points'. Valid code points are in
1665 the ranges 0 to @code{#xD7FF} inclusive or @code{#xE000} to
1666 @code{#x10FFFF} inclusive, which is about 1.1 million code points.
1668 @cindex designated code point
1669 @cindex code point, designated
1671 Any code point that has been assigned to a character or that has
1672 otherwise been given a meaning by Unicode is called a 'designated code
1673 point'. Most of the designated code points, about 200,000 of them,
1674 indicate characters, accents or other combining marks that modify
1675 other characters, symbols, whitespace, and control characters. Some
1676 are not characters but indicators that suggest how to format or
1677 display neighboring characters.
1679 @cindex reserved code point
1680 @cindex code point, reserved
1682 If a code point is not a designated code point -- if it has not been
1683 assigned to a character by The Unicode Standard -- it is a 'reserved
1684 code point', meaning that they are reserved for future use. Most of
1685 the code points, about 800,000, are 'reserved code points'.
1687 By convention, a Unicode code point is written as
1688 ``U+XXXX'' where ``XXXX'' is a hexadecimal number. Please note that
1689 this convenient notation is not valid code. Guile does not interpret
1690 ``U+XXXX'' as a character.
1692 In Scheme, a character literal is written as @code{#\@var{name}} where
1693 @var{name} is the name of the character that you want. Printable
1694 characters have their usual single character name; for example,
1695 @code{#\a} is a lower case @code{a}.
1697 Some of the code points are 'combining characters' that are not meant
1698 to be printed by themselves but are instead meant to modify the
1699 appearance of the previous character. For combining characters, an
1700 alternate form of the character literal is @code{#\} followed by
1701 U+25CC (a small, dotted circle), followed by the combining character.
1702 This allows the combining character to be drawn on the circle, not on
1703 the backslash of @code{#\}.
1705 Many of the non-printing characters, such as whitespace characters and
1706 control characters, also have names.
1708 The most commonly used non-printing characters have long character
1709 names, described in the table below.
1711 @multitable {@code{#\backspace}} {Preferred}
1712 @item Character Name @tab Codepoint
1713 @item @code{#\nul} @tab U+0000
1714 @item @code{#\alarm} @tab u+0007
1715 @item @code{#\backspace} @tab U+0008
1716 @item @code{#\tab} @tab U+0009
1717 @item @code{#\linefeed} @tab U+000A
1718 @item @code{#\newline} @tab U+000A
1719 @item @code{#\vtab} @tab U+000B
1720 @item @code{#\page} @tab U+000C
1721 @item @code{#\return} @tab U+000D
1722 @item @code{#\esc} @tab U+001B
1723 @item @code{#\space} @tab U+0020
1724 @item @code{#\delete} @tab U+007F
1727 There are also short names for all of the ``C0 control characters''
1728 (those with code points below 32). The following table lists the short
1729 name for each character.
1731 @multitable @columnfractions .25 .25 .25 .25
1732 @item 0 = @code{#\nul}
1733 @tab 1 = @code{#\soh}
1734 @tab 2 = @code{#\stx}
1735 @tab 3 = @code{#\etx}
1736 @item 4 = @code{#\eot}
1737 @tab 5 = @code{#\enq}
1738 @tab 6 = @code{#\ack}
1739 @tab 7 = @code{#\bel}
1740 @item 8 = @code{#\bs}
1741 @tab 9 = @code{#\ht}
1742 @tab 10 = @code{#\lf}
1743 @tab 11 = @code{#\vt}
1744 @item 12 = @code{#\ff}
1745 @tab 13 = @code{#\cr}
1746 @tab 14 = @code{#\so}
1747 @tab 15 = @code{#\si}
1748 @item 16 = @code{#\dle}
1749 @tab 17 = @code{#\dc1}
1750 @tab 18 = @code{#\dc2}
1751 @tab 19 = @code{#\dc3}
1752 @item 20 = @code{#\dc4}
1753 @tab 21 = @code{#\nak}
1754 @tab 22 = @code{#\syn}
1755 @tab 23 = @code{#\etb}
1756 @item 24 = @code{#\can}
1757 @tab 25 = @code{#\em}
1758 @tab 26 = @code{#\sub}
1759 @tab 27 = @code{#\esc}
1760 @item 28 = @code{#\fs}
1761 @tab 29 = @code{#\gs}
1762 @tab 30 = @code{#\rs}
1763 @tab 31 = @code{#\us}
1764 @item 32 = @code{#\sp}
1767 The short name for the ``delete'' character (code point U+007F) is
1770 There are also a few alternative names left over for compatibility with
1771 previous versions of Guile.
1773 @multitable {@code{#\backspace}} {Preferred}
1774 @item Alternate @tab Standard
1775 @item @code{#\nl} @tab @code{#\newline}
1776 @item @code{#\np} @tab @code{#\page}
1777 @item @code{#\null} @tab @code{#\nul}
1780 Characters may also be written using their code point values. They can
1781 be written with as an octal number, such as @code{#\10} for
1782 @code{#\bs} or @code{#\177} for @code{#\del}.
1784 If one prefers hex to octal, there is an additional syntax for character
1785 escapes: @code{#\xHHHH} -- the letter 'x' followed by a hexadecimal
1786 number of one to eight digits.
1789 @deffn {Scheme Procedure} char? x
1790 @deffnx {C Function} scm_char_p (x)
1791 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1794 Fundamentally, the character comparison operations below are
1795 numeric comparisons of the character's code points.
1798 @deffn {Scheme Procedure} char=? x y
1799 Return @code{#t} iff code point of @var{x} is equal to the code point
1800 of @var{y}, else @code{#f}.
1804 @deffn {Scheme Procedure} char<? x y
1805 Return @code{#t} iff the code point of @var{x} is less than the code
1806 point of @var{y}, else @code{#f}.
1810 @deffn {Scheme Procedure} char<=? x y
1811 Return @code{#t} iff the code point of @var{x} is less than or equal
1812 to the code point of @var{y}, else @code{#f}.
1816 @deffn {Scheme Procedure} char>? x y
1817 Return @code{#t} iff the code point of @var{x} is greater than the
1818 code point of @var{y}, else @code{#f}.
1822 @deffn {Scheme Procedure} char>=? x y
1823 Return @code{#t} iff the code point of @var{x} is greater than or
1824 equal to the code point of @var{y}, else @code{#f}.
1827 @cindex case folding
1829 Case-insensitive character comparisons use @emph{Unicode case
1830 folding}. In case folding comparisons, if a character is lowercase
1831 and has an uppercase form that can be expressed as a single character,
1832 it is converted to uppercase before comparison. All other characters
1833 undergo no conversion before the comparison occurs. This includes the
1834 German sharp S (Eszett) which is not uppercased before conversion
1835 because its uppercase form has two characters. Unicode case folding
1836 is language independent: it uses rules that are generally true, but,
1837 it cannot cover all cases for all languages.
1840 @deffn {Scheme Procedure} char-ci=? x y
1841 Return @code{#t} iff the case-folded code point of @var{x} is the same
1842 as the case-folded code point of @var{y}, else @code{#f}.
1846 @deffn {Scheme Procedure} char-ci<? x y
1847 Return @code{#t} iff the case-folded code point of @var{x} is less
1848 than the case-folded code point of @var{y}, else @code{#f}.
1852 @deffn {Scheme Procedure} char-ci<=? x y
1853 Return @code{#t} iff the case-folded code point of @var{x} is less
1854 than or equal to the case-folded code point of @var{y}, else
1859 @deffn {Scheme Procedure} char-ci>? x y
1860 Return @code{#t} iff the case-folded code point of @var{x} is greater
1861 than the case-folded code point of @var{y}, else @code{#f}.
1865 @deffn {Scheme Procedure} char-ci>=? x y
1866 Return @code{#t} iff the case-folded code point of @var{x} is greater
1867 than or equal to the case-folded code point of @var{y}, else
1871 @rnindex char-alphabetic?
1872 @deffn {Scheme Procedure} char-alphabetic? chr
1873 @deffnx {C Function} scm_char_alphabetic_p (chr)
1874 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1877 @rnindex char-numeric?
1878 @deffn {Scheme Procedure} char-numeric? chr
1879 @deffnx {C Function} scm_char_numeric_p (chr)
1880 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1883 @rnindex char-whitespace?
1884 @deffn {Scheme Procedure} char-whitespace? chr
1885 @deffnx {C Function} scm_char_whitespace_p (chr)
1886 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1889 @rnindex char-upper-case?
1890 @deffn {Scheme Procedure} char-upper-case? chr
1891 @deffnx {C Function} scm_char_upper_case_p (chr)
1892 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1895 @rnindex char-lower-case?
1896 @deffn {Scheme Procedure} char-lower-case? chr
1897 @deffnx {C Function} scm_char_lower_case_p (chr)
1898 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1901 @deffn {Scheme Procedure} char-is-both? chr
1902 @deffnx {C Function} scm_char_is_both_p (chr)
1903 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1907 @deffn {Scheme Procedure} char-general-category chr
1908 @deffnx {C Function} scm_char_general_category (chr)
1909 Return a symbol giving the two-letter name of the Unicode general
1910 category assigned to @var{chr} or @code{#f} if no named category is
1911 assigned. The following table provides a list of category names along
1912 with their meanings.
1914 @multitable @columnfractions .1 .4 .1 .4
1916 @tab Uppercase letter
1918 @tab Final quote punctuation
1920 @tab Lowercase letter
1922 @tab Other punctuation
1924 @tab Titlecase letter
1928 @tab Modifier letter
1930 @tab Currency symbol
1934 @tab Modifier symbol
1936 @tab Non-spacing mark
1940 @tab Combining spacing mark
1942 @tab Space separator
1948 @tab Decimal digit number
1950 @tab Paragraph separator
1960 @tab Connector punctuation
1964 @tab Dash punctuation
1968 @tab Open punctuation
1972 @tab Close punctuation
1976 @tab Initial quote punctuation
1982 @rnindex char->integer
1983 @deffn {Scheme Procedure} char->integer chr
1984 @deffnx {C Function} scm_char_to_integer (chr)
1985 Return the code point of @var{chr}.
1988 @rnindex integer->char
1989 @deffn {Scheme Procedure} integer->char n
1990 @deffnx {C Function} scm_integer_to_char (n)
1991 Return the character that has code point @var{n}. The integer @var{n}
1992 must be a valid code point. Valid code points are in the ranges 0 to
1993 @code{#xD7FF} inclusive or @code{#xE000} to @code{#x10FFFF} inclusive.
1996 @rnindex char-upcase
1997 @deffn {Scheme Procedure} char-upcase chr
1998 @deffnx {C Function} scm_char_upcase (chr)
1999 Return the uppercase character version of @var{chr}.
2002 @rnindex char-downcase
2003 @deffn {Scheme Procedure} char-downcase chr
2004 @deffnx {C Function} scm_char_downcase (chr)
2005 Return the lowercase character version of @var{chr}.
2008 @rnindex char-titlecase
2009 @deffn {Scheme Procedure} char-titlecase chr
2010 @deffnx {C Function} scm_char_titlecase (chr)
2011 Return the titlecase character version of @var{chr} if one exists;
2012 otherwise return the uppercase version.
2014 For most characters these will be the same, but the Unicode Standard
2015 includes certain digraph compatibility characters, such as @code{U+01F3}
2016 ``dz'', for which the uppercase and titlecase characters are different
2017 (@code{U+01F1} ``DZ'' and @code{U+01F2} ``Dz'' in this case,
2022 @deftypefn {C Function} scm_t_wchar scm_c_upcase (scm_t_wchar @var{c})
2023 @deftypefnx {C Function} scm_t_wchar scm_c_downcase (scm_t_wchar @var{c})
2024 @deftypefnx {C Function} scm_t_wchar scm_c_titlecase (scm_t_wchar @var{c})
2026 These C functions take an integer representation of a Unicode
2027 codepoint and return the codepoint corresponding to its uppercase,
2028 lowercase, and titlecase forms respectively. The type
2029 @code{scm_t_wchar} is a signed, 32-bit integer.
2032 @node Character Sets
2033 @subsection Character Sets
2035 The features described in this section correspond directly to SRFI-14.
2037 The data type @dfn{charset} implements sets of characters
2038 (@pxref{Characters}). Because the internal representation of
2039 character sets is not visible to the user, a lot of procedures for
2040 handling them are provided.
2042 Character sets can be created, extended, tested for the membership of a
2043 characters and be compared to other character sets.
2046 * Character Set Predicates/Comparison::
2047 * Iterating Over Character Sets:: Enumerate charset elements.
2048 * Creating Character Sets:: Making new charsets.
2049 * Querying Character Sets:: Test charsets for membership etc.
2050 * Character-Set Algebra:: Calculating new charsets.
2051 * Standard Character Sets:: Variables containing predefined charsets.
2054 @node Character Set Predicates/Comparison
2055 @subsubsection Character Set Predicates/Comparison
2057 Use these procedures for testing whether an object is a character set,
2058 or whether several character sets are equal or subsets of each other.
2059 @code{char-set-hash} can be used for calculating a hash value, maybe for
2060 usage in fast lookup procedures.
2062 @deffn {Scheme Procedure} char-set? obj
2063 @deffnx {C Function} scm_char_set_p (obj)
2064 Return @code{#t} if @var{obj} is a character set, @code{#f}
2068 @deffn {Scheme Procedure} char-set= . char_sets
2069 @deffnx {C Function} scm_char_set_eq (char_sets)
2070 Return @code{#t} if all given character sets are equal.
2073 @deffn {Scheme Procedure} char-set<= . char_sets
2074 @deffnx {C Function} scm_char_set_leq (char_sets)
2075 Return @code{#t} if every character set @var{cs}i is a subset
2076 of character set @var{cs}i+1.
2079 @deffn {Scheme Procedure} char-set-hash cs [bound]
2080 @deffnx {C Function} scm_char_set_hash (cs, bound)
2081 Compute a hash value for the character set @var{cs}. If
2082 @var{bound} is given and non-zero, it restricts the
2083 returned value to the range 0 @dots{} @var{bound - 1}.
2086 @c ===================================================================
2088 @node Iterating Over Character Sets
2089 @subsubsection Iterating Over Character Sets
2091 Character set cursors are a means for iterating over the members of a
2092 character sets. After creating a character set cursor with
2093 @code{char-set-cursor}, a cursor can be dereferenced with
2094 @code{char-set-ref}, advanced to the next member with
2095 @code{char-set-cursor-next}. Whether a cursor has passed past the last
2096 element of the set can be checked with @code{end-of-char-set?}.
2098 Additionally, mapping and (un-)folding procedures for character sets are
2101 @deffn {Scheme Procedure} char-set-cursor cs
2102 @deffnx {C Function} scm_char_set_cursor (cs)
2103 Return a cursor into the character set @var{cs}.
2106 @deffn {Scheme Procedure} char-set-ref cs cursor
2107 @deffnx {C Function} scm_char_set_ref (cs, cursor)
2108 Return the character at the current cursor position
2109 @var{cursor} in the character set @var{cs}. It is an error to
2110 pass a cursor for which @code{end-of-char-set?} returns true.
2113 @deffn {Scheme Procedure} char-set-cursor-next cs cursor
2114 @deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
2115 Advance the character set cursor @var{cursor} to the next
2116 character in the character set @var{cs}. It is an error if the
2117 cursor given satisfies @code{end-of-char-set?}.
2120 @deffn {Scheme Procedure} end-of-char-set? cursor
2121 @deffnx {C Function} scm_end_of_char_set_p (cursor)
2122 Return @code{#t} if @var{cursor} has reached the end of a
2123 character set, @code{#f} otherwise.
2126 @deffn {Scheme Procedure} char-set-fold kons knil cs
2127 @deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2128 Fold the procedure @var{kons} over the character set @var{cs},
2129 initializing it with @var{knil}.
2132 @deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2133 @deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2134 This is a fundamental constructor for character sets.
2136 @item @var{g} is used to generate a series of ``seed'' values
2137 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2138 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2139 @item @var{p} tells us when to stop -- when it returns true
2140 when applied to one of the seed values.
2141 @item @var{f} maps each seed value to a character. These
2142 characters are added to the base character set @var{base_cs} to
2143 form the result; @var{base_cs} defaults to the empty set.
2147 @deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2148 @deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2149 This is a fundamental constructor for character sets.
2151 @item @var{g} is used to generate a series of ``seed'' values
2152 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2153 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2154 @item @var{p} tells us when to stop -- when it returns true
2155 when applied to one of the seed values.
2156 @item @var{f} maps each seed value to a character. These
2157 characters are added to the base character set @var{base_cs} to
2158 form the result; @var{base_cs} defaults to the empty set.
2162 @deffn {Scheme Procedure} char-set-for-each proc cs
2163 @deffnx {C Function} scm_char_set_for_each (proc, cs)
2164 Apply @var{proc} to every character in the character set
2165 @var{cs}. The return value is not specified.
2168 @deffn {Scheme Procedure} char-set-map proc cs
2169 @deffnx {C Function} scm_char_set_map (proc, cs)
2170 Map the procedure @var{proc} over every character in @var{cs}.
2171 @var{proc} must be a character -> character procedure.
2174 @c ===================================================================
2176 @node Creating Character Sets
2177 @subsubsection Creating Character Sets
2179 New character sets are produced with these procedures.
2181 @deffn {Scheme Procedure} char-set-copy cs
2182 @deffnx {C Function} scm_char_set_copy (cs)
2183 Return a newly allocated character set containing all
2184 characters in @var{cs}.
2187 @deffn {Scheme Procedure} char-set . rest
2188 @deffnx {C Function} scm_char_set (rest)
2189 Return a character set containing all given characters.
2192 @deffn {Scheme Procedure} list->char-set list [base_cs]
2193 @deffnx {C Function} scm_list_to_char_set (list, base_cs)
2194 Convert the character list @var{list} to a character set. If
2195 the character set @var{base_cs} is given, the character in this
2196 set are also included in the result.
2199 @deffn {Scheme Procedure} list->char-set! list base_cs
2200 @deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2201 Convert the character list @var{list} to a character set. The
2202 characters are added to @var{base_cs} and @var{base_cs} is
2206 @deffn {Scheme Procedure} string->char-set str [base_cs]
2207 @deffnx {C Function} scm_string_to_char_set (str, base_cs)
2208 Convert the string @var{str} to a character set. If the
2209 character set @var{base_cs} is given, the characters in this
2210 set are also included in the result.
2213 @deffn {Scheme Procedure} string->char-set! str base_cs
2214 @deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2215 Convert the string @var{str} to a character set. The
2216 characters from the string are added to @var{base_cs}, and
2217 @var{base_cs} is returned.
2220 @deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2221 @deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2222 Return a character set containing every character from @var{cs}
2223 so that it satisfies @var{pred}. If provided, the characters
2224 from @var{base_cs} are added to the result.
2227 @deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2228 @deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2229 Return a character set containing every character from @var{cs}
2230 so that it satisfies @var{pred}. The characters are added to
2231 @var{base_cs} and @var{base_cs} is returned.
2234 @deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2235 @deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2236 Return a character set containing all characters whose
2237 character codes lie in the half-open range
2238 [@var{lower},@var{upper}).
2240 If @var{error} is a true value, an error is signalled if the
2241 specified range contains characters which are not contained in
2242 the implemented character range. If @var{error} is @code{#f},
2243 these characters are silently left out of the resulting
2246 The characters in @var{base_cs} are added to the result, if
2250 @deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2251 @deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2252 Return a character set containing all characters whose
2253 character codes lie in the half-open range
2254 [@var{lower},@var{upper}).
2256 If @var{error} is a true value, an error is signalled if the
2257 specified range contains characters which are not contained in
2258 the implemented character range. If @var{error} is @code{#f},
2259 these characters are silently left out of the resulting
2262 The characters are added to @var{base_cs} and @var{base_cs} is
2266 @deffn {Scheme Procedure} ->char-set x
2267 @deffnx {C Function} scm_to_char_set (x)
2268 Coerces x into a char-set. @var{x} may be a string, character or
2269 char-set. A string is converted to the set of its constituent
2270 characters; a character is converted to a singleton set; a char-set is
2274 @c ===================================================================
2276 @node Querying Character Sets
2277 @subsubsection Querying Character Sets
2279 Access the elements and other information of a character set with these
2282 @deffn {Scheme Procedure} %char-set-dump cs
2283 Returns an association list containing debugging information
2284 for @var{cs}. The association list has the following entries.
2289 The number of groups of contiguous code points the char-set
2292 A list of lists where each sublist is a range of code points
2293 and their associated characters
2295 The return value of this function cannot be relied upon to be
2296 consistent between versions of Guile and should not be used in code.
2299 @deffn {Scheme Procedure} char-set-size cs
2300 @deffnx {C Function} scm_char_set_size (cs)
2301 Return the number of elements in character set @var{cs}.
2304 @deffn {Scheme Procedure} char-set-count pred cs
2305 @deffnx {C Function} scm_char_set_count (pred, cs)
2306 Return the number of the elements int the character set
2307 @var{cs} which satisfy the predicate @var{pred}.
2310 @deffn {Scheme Procedure} char-set->list cs
2311 @deffnx {C Function} scm_char_set_to_list (cs)
2312 Return a list containing the elements of the character set
2316 @deffn {Scheme Procedure} char-set->string cs
2317 @deffnx {C Function} scm_char_set_to_string (cs)
2318 Return a string containing the elements of the character set
2319 @var{cs}. The order in which the characters are placed in the
2320 string is not defined.
2323 @deffn {Scheme Procedure} char-set-contains? cs ch
2324 @deffnx {C Function} scm_char_set_contains_p (cs, ch)
2325 Return @code{#t} iff the character @var{ch} is contained in the
2326 character set @var{cs}.
2329 @deffn {Scheme Procedure} char-set-every pred cs
2330 @deffnx {C Function} scm_char_set_every (pred, cs)
2331 Return a true value if every character in the character set
2332 @var{cs} satisfies the predicate @var{pred}.
2335 @deffn {Scheme Procedure} char-set-any pred cs
2336 @deffnx {C Function} scm_char_set_any (pred, cs)
2337 Return a true value if any character in the character set
2338 @var{cs} satisfies the predicate @var{pred}.
2341 @c ===================================================================
2343 @node Character-Set Algebra
2344 @subsubsection Character-Set Algebra
2346 Character sets can be manipulated with the common set algebra operation,
2347 such as union, complement, intersection etc. All of these procedures
2348 provide side-effecting variants, which modify their character set
2351 @deffn {Scheme Procedure} char-set-adjoin cs . rest
2352 @deffnx {C Function} scm_char_set_adjoin (cs, rest)
2353 Add all character arguments to the first argument, which must
2357 @deffn {Scheme Procedure} char-set-delete cs . rest
2358 @deffnx {C Function} scm_char_set_delete (cs, rest)
2359 Delete all character arguments from the first argument, which
2360 must be a character set.
2363 @deffn {Scheme Procedure} char-set-adjoin! cs . rest
2364 @deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2365 Add all character arguments to the first argument, which must
2369 @deffn {Scheme Procedure} char-set-delete! cs . rest
2370 @deffnx {C Function} scm_char_set_delete_x (cs, rest)
2371 Delete all character arguments from the first argument, which
2372 must be a character set.
2375 @deffn {Scheme Procedure} char-set-complement cs
2376 @deffnx {C Function} scm_char_set_complement (cs)
2377 Return the complement of the character set @var{cs}.
2380 Note that the complement of a character set is likely to contain many
2381 reserved code points (code points that are not associated with
2382 characters). It may be helpful to modify the output of
2383 @code{char-set-complement} by computing its intersection with the set
2384 of designated code points, @code{char-set:designated}.
2386 @deffn {Scheme Procedure} char-set-union . rest
2387 @deffnx {C Function} scm_char_set_union (rest)
2388 Return the union of all argument character sets.
2391 @deffn {Scheme Procedure} char-set-intersection . rest
2392 @deffnx {C Function} scm_char_set_intersection (rest)
2393 Return the intersection of all argument character sets.
2396 @deffn {Scheme Procedure} char-set-difference cs1 . rest
2397 @deffnx {C Function} scm_char_set_difference (cs1, rest)
2398 Return the difference of all argument character sets.
2401 @deffn {Scheme Procedure} char-set-xor . rest
2402 @deffnx {C Function} scm_char_set_xor (rest)
2403 Return the exclusive-or of all argument character sets.
2406 @deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2407 @deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2408 Return the difference and the intersection of all argument
2412 @deffn {Scheme Procedure} char-set-complement! cs
2413 @deffnx {C Function} scm_char_set_complement_x (cs)
2414 Return the complement of the character set @var{cs}.
2417 @deffn {Scheme Procedure} char-set-union! cs1 . rest
2418 @deffnx {C Function} scm_char_set_union_x (cs1, rest)
2419 Return the union of all argument character sets.
2422 @deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2423 @deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2424 Return the intersection of all argument character sets.
2427 @deffn {Scheme Procedure} char-set-difference! cs1 . rest
2428 @deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2429 Return the difference of all argument character sets.
2432 @deffn {Scheme Procedure} char-set-xor! cs1 . rest
2433 @deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2434 Return the exclusive-or of all argument character sets.
2437 @deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2438 @deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2439 Return the difference and the intersection of all argument
2443 @c ===================================================================
2445 @node Standard Character Sets
2446 @subsubsection Standard Character Sets
2448 In order to make the use of the character set data type and procedures
2449 useful, several predefined character set variables exist.
2455 These character sets are locale independent and are not recomputed
2456 upon a @code{setlocale} call. They contain characters from the whole
2457 range of Unicode code points. For instance, @code{char-set:letter}
2458 contains about 94,000 characters.
2460 @defvr {Scheme Variable} char-set:lower-case
2461 @defvrx {C Variable} scm_char_set_lower_case
2462 All lower-case characters.
2465 @defvr {Scheme Variable} char-set:upper-case
2466 @defvrx {C Variable} scm_char_set_upper_case
2467 All upper-case characters.
2470 @defvr {Scheme Variable} char-set:title-case
2471 @defvrx {C Variable} scm_char_set_title_case
2472 All single characters that function as if they were an upper-case
2473 letter followed by a lower-case letter.
2476 @defvr {Scheme Variable} char-set:letter
2477 @defvrx {C Variable} scm_char_set_letter
2478 All letters. This includes @code{char-set:lower-case},
2479 @code{char-set:upper-case}, @code{char-set:title-case}, and many
2480 letters that have no case at all. For example, Chinese and Japanese
2481 characters typically have no concept of case.
2484 @defvr {Scheme Variable} char-set:digit
2485 @defvrx {C Variable} scm_char_set_digit
2489 @defvr {Scheme Variable} char-set:letter+digit
2490 @defvrx {C Variable} scm_char_set_letter_and_digit
2491 The union of @code{char-set:letter} and @code{char-set:digit}.
2494 @defvr {Scheme Variable} char-set:graphic
2495 @defvrx {C Variable} scm_char_set_graphic
2496 All characters which would put ink on the paper.
2499 @defvr {Scheme Variable} char-set:printing
2500 @defvrx {C Variable} scm_char_set_printing
2501 The union of @code{char-set:graphic} and @code{char-set:whitespace}.
2504 @defvr {Scheme Variable} char-set:whitespace
2505 @defvrx {C Variable} scm_char_set_whitespace
2506 All whitespace characters.
2509 @defvr {Scheme Variable} char-set:blank
2510 @defvrx {C Variable} scm_char_set_blank
2511 All horizontal whitespace characters, which notably includes
2512 @code{#\space} and @code{#\tab}.
2515 @defvr {Scheme Variable} char-set:iso-control
2516 @defvrx {C Variable} scm_char_set_iso_control
2517 The ISO control characters are the C0 control characters (U+0000 to
2518 U+001F), delete (U+007F), and the C1 control characters (U+0080 to
2522 @defvr {Scheme Variable} char-set:punctuation
2523 @defvrx {C Variable} scm_char_set_punctuation
2524 All punctuation characters, such as the characters
2525 @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
2528 @defvr {Scheme Variable} char-set:symbol
2529 @defvrx {C Variable} scm_char_set_symbol
2530 All symbol characters, such as the characters @code{$+<=>^`|~}.
2533 @defvr {Scheme Variable} char-set:hex-digit
2534 @defvrx {C Variable} scm_char_set_hex_digit
2535 The hexadecimal digits @code{0123456789abcdefABCDEF}.
2538 @defvr {Scheme Variable} char-set:ascii
2539 @defvrx {C Variable} scm_char_set_ascii
2540 All ASCII characters.
2543 @defvr {Scheme Variable} char-set:empty
2544 @defvrx {C Variable} scm_char_set_empty
2545 The empty character set.
2548 @defvr {Scheme Variable} char-set:designated
2549 @defvrx {C Variable} scm_char_set_designated
2550 This character set contains all designated code points. This includes
2551 all the code points to which Unicode has assigned a character or other
2555 @defvr {Scheme Variable} char-set:full
2556 @defvrx {C Variable} scm_char_set_full
2557 This character set contains all possible code points. This includes
2558 both designated and reserved code points.
2565 Strings are fixed-length sequences of characters. They can be created
2566 by calling constructor procedures, but they can also literally get
2567 entered at the @acronym{REPL} or in Scheme source files.
2569 @c Guile provides a rich set of string processing procedures, because text
2570 @c handling is very important when Guile is used as a scripting language.
2572 Strings always carry the information about how many characters they are
2573 composed of with them, so there is no special end-of-string character,
2574 like in C. That means that Scheme strings can contain any character,
2575 even the @samp{#\nul} character @samp{\0}.
2577 To use strings efficiently, you need to know a bit about how Guile
2578 implements them. In Guile, a string consists of two parts, a head and
2579 the actual memory where the characters are stored. When a string (or
2580 a substring of it) is copied, only a new head gets created, the memory
2581 is usually not copied. The two heads start out pointing to the same
2584 When one of these two strings is modified, as with @code{string-set!},
2585 their common memory does get copied so that each string has its own
2586 memory and modifying one does not accidentally modify the other as well.
2587 Thus, Guile's strings are `copy on write'; the actual copying of their
2588 memory is delayed until one string is written to.
2590 This implementation makes functions like @code{substring} very
2591 efficient in the common case that no modifications are done to the
2594 If you do know that your strings are getting modified right away, you
2595 can use @code{substring/copy} instead of @code{substring}. This
2596 function performs the copy immediately at the time of creation. This
2597 is more efficient, especially in a multi-threaded program. Also,
2598 @code{substring/copy} can avoid the problem that a short substring
2599 holds on to the memory of a very large original string that could
2600 otherwise be recycled.
2602 If you want to avoid the copy altogether, so that modifications of one
2603 string show up in the other, you can use @code{substring/shared}. The
2604 strings created by this procedure are called @dfn{mutation sharing
2605 substrings} since the substring and the original string share
2606 modifications to each other.
2608 If you want to prevent modifications, use @code{substring/read-only}.
2610 Guile provides all procedures of SRFI-13 and a few more.
2613 * String Syntax:: Read syntax for strings.
2614 * String Predicates:: Testing strings for certain properties.
2615 * String Constructors:: Creating new string objects.
2616 * List/String Conversion:: Converting from/to lists of characters.
2617 * String Selection:: Select portions from strings.
2618 * String Modification:: Modify parts or whole strings.
2619 * String Comparison:: Lexicographic ordering predicates.
2620 * String Searching:: Searching in strings.
2621 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2622 * Reversing and Appending Strings:: Appending strings to form a new string.
2623 * Mapping Folding and Unfolding:: Iterating over strings.
2624 * Miscellaneous String Operations:: Replicating, insertion, parsing, ...
2625 * Conversion to/from C::
2626 * String Internals:: The storage strategy for strings.
2630 @subsubsection String Read Syntax
2632 @c In the following @code is used to get a good font in TeX etc, but
2633 @c is omitted for Info format, so as not to risk any confusion over
2634 @c whether surrounding ` ' quotes are part of the escape or are
2635 @c special in a string (they're not).
2637 The read syntax for strings is an arbitrarily long sequence of
2638 characters enclosed in double quotes (@nicode{"}).
2640 Backslash is an escape character and can be used to insert the following
2641 special characters. @nicode{\"} and @nicode{\\} are R5RS standard, the
2642 next seven are R6RS standard --- notice they follow C syntax --- and the
2643 remaining four are Guile extensions.
2647 Backslash character.
2650 Double quote character (an unescaped @nicode{"} is otherwise the end
2654 Bell character (ASCII 7).
2657 Formfeed character (ASCII 12).
2660 Newline character (ASCII 10).
2663 Carriage return character (ASCII 13).
2666 Tab character (ASCII 9).
2669 Vertical tab character (ASCII 11).
2672 Backspace character (ASCII 8).
2675 NUL character (ASCII 0).
2677 @item @nicode{\} followed by newline (ASCII 10)
2678 Nothing. This way if @nicode{\} is the last character in a line, the
2679 string will continue with the first character from the next line,
2680 without a line break.
2682 If the @code{hungry-eol-escapes} reader option is enabled, which is not
2683 the case by default, leading whitespace on the next line is discarded.
2689 (read-enable 'hungry-eol-escapes)
2695 Character code given by two hexadecimal digits. For example
2696 @nicode{\x7f} for an ASCII DEL (127).
2698 @item @nicode{\uHHHH}
2699 Character code given by four hexadecimal digits. For example
2700 @nicode{\u0100} for a capital A with macron (U+0100).
2702 @item @nicode{\UHHHHHH}
2703 Character code given by six hexadecimal digits. For example
2708 The following are examples of string literals:
2717 The three escape sequences @code{\xHH}, @code{\uHHHH} and @code{\UHHHHHH} were
2718 chosen to not break compatibility with code written for previous versions of
2719 Guile. The R6RS specification suggests a different, incompatible syntax for hex
2720 escapes: @code{\xHHHH;} -- a character code followed by one to eight hexadecimal
2721 digits terminated with a semicolon. If this escape format is desired instead,
2722 it can be enabled with the reader option @code{r6rs-hex-escapes}.
2725 (read-enable 'r6rs-hex-escapes)
2728 For more on reader options, @xref{Scheme Read}.
2730 @node String Predicates
2731 @subsubsection String Predicates
2733 The following procedures can be used to check whether a given string
2734 fulfills some specified property.
2737 @deffn {Scheme Procedure} string? obj
2738 @deffnx {C Function} scm_string_p (obj)
2739 Return @code{#t} if @var{obj} is a string, else @code{#f}.
2742 @deftypefn {C Function} int scm_is_string (SCM obj)
2743 Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2746 @deffn {Scheme Procedure} string-null? str
2747 @deffnx {C Function} scm_string_null_p (str)
2748 Return @code{#t} if @var{str}'s length is zero, and
2749 @code{#f} otherwise.
2751 (string-null? "") @result{} #t
2753 (string-null? y) @result{} #f
2757 @deffn {Scheme Procedure} string-any char_pred s [start [end]]
2758 @deffnx {C Function} scm_string_any (char_pred, s, start, end)
2759 Check if @var{char_pred} is true for any character in string @var{s}.
2761 @var{char_pred} can be a character to check for any equal to that, or
2762 a character set (@pxref{Character Sets}) to check for any in that set,
2763 or a predicate procedure to call.
2765 For a procedure, calls @code{(@var{char_pred} c)} are made
2766 successively on the characters from @var{start} to @var{end}. If
2767 @var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2768 stops and that return value is the return from @code{string-any}. The
2769 call on the last character (ie.@: at @math{@var{end}-1}), if that
2770 point is reached, is a tail call.
2772 If there are no characters in @var{s} (ie.@: @var{start} equals
2773 @var{end}) then the return is @code{#f}.
2776 @deffn {Scheme Procedure} string-every char_pred s [start [end]]
2777 @deffnx {C Function} scm_string_every (char_pred, s, start, end)
2778 Check if @var{char_pred} is true for every character in string
2781 @var{char_pred} can be a character to check for every character equal
2782 to that, or a character set (@pxref{Character Sets}) to check for
2783 every character being in that set, or a predicate procedure to call.
2785 For a procedure, calls @code{(@var{char_pred} c)} are made
2786 successively on the characters from @var{start} to @var{end}. If
2787 @var{char_pred} returns @code{#f}, @code{string-every} stops and
2788 returns @code{#f}. The call on the last character (ie.@: at
2789 @math{@var{end}-1}), if that point is reached, is a tail call and the
2790 return from that call is the return from @code{string-every}.
2792 If there are no characters in @var{s} (ie.@: @var{start} equals
2793 @var{end}) then the return is @code{#t}.
2796 @node String Constructors
2797 @subsubsection String Constructors
2799 The string constructor procedures create new string objects, possibly
2800 initializing them with some specified character data. See also
2801 @xref{String Selection}, for ways to create strings from existing
2804 @c FIXME::martin: list->string belongs into `List/String Conversion'
2806 @deffn {Scheme Procedure} string char@dots{}
2808 Return a newly allocated string made from the given character
2812 (string #\x #\y #\z) @result{} "xyz"
2813 (string) @result{} ""
2817 @deffn {Scheme Procedure} list->string lst
2818 @deffnx {C Function} scm_string (lst)
2819 @rnindex list->string
2820 Return a newly allocated string made from a list of characters.
2823 (list->string '(#\a #\b #\c)) @result{} "abc"
2827 @deffn {Scheme Procedure} reverse-list->string lst
2828 @deffnx {C Function} scm_reverse_list_to_string (lst)
2829 Return a newly allocated string made from a list of characters, in
2833 (reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2837 @rnindex make-string
2838 @deffn {Scheme Procedure} make-string k [chr]
2839 @deffnx {C Function} scm_make_string (k, chr)
2840 Return a newly allocated string of
2841 length @var{k}. If @var{chr} is given, then all elements of
2842 the string are initialized to @var{chr}, otherwise the contents
2843 of the @var{string} are unspecified.
2846 @deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2847 Like @code{scm_make_string}, but expects the length as a
2851 @deffn {Scheme Procedure} string-tabulate proc len
2852 @deffnx {C Function} scm_string_tabulate (proc, len)
2853 @var{proc} is an integer->char procedure. Construct a string
2854 of size @var{len} by applying @var{proc} to each index to
2855 produce the corresponding string element. The order in which
2856 @var{proc} is applied to the indices is not specified.
2859 @deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2860 @deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2861 Append the string in the string list @var{ls}, using the string
2862 @var{delim} as a delimiter between the elements of @var{ls}.
2863 @var{grammar} is a symbol which specifies how the delimiter is
2864 placed between the strings, and defaults to the symbol
2869 Insert the separator between list elements. An empty string
2870 will produce an empty list.
2872 Like @code{infix}, but will raise an error if given the empty
2875 Insert the separator after every list element.
2877 Insert the separator before each list element.
2881 @node List/String Conversion
2882 @subsubsection List/String conversion
2884 When processing strings, it is often convenient to first convert them
2885 into a list representation by using the procedure @code{string->list},
2886 work with the resulting list, and then convert it back into a string.
2887 These procedures are useful for similar tasks.
2889 @rnindex string->list
2890 @deffn {Scheme Procedure} string->list str [start [end]]
2891 @deffnx {C Function} scm_substring_to_list (str, start, end)
2892 @deffnx {C Function} scm_string_to_list (str)
2893 Convert the string @var{str} into a list of characters.
2896 @deffn {Scheme Procedure} string-split str chr
2897 @deffnx {C Function} scm_string_split (str, chr)
2898 Split the string @var{str} into the a list of the substrings delimited
2899 by appearances of the character @var{chr}. Note that an empty substring
2900 between separator characters will result in an empty string in the
2904 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2906 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
2908 (string-split "::" #\:)
2912 (string-split "" #\:)
2919 @node String Selection
2920 @subsubsection String Selection
2922 Portions of strings can be extracted by these procedures.
2923 @code{string-ref} delivers individual characters whereas
2924 @code{substring} can be used to extract substrings from longer strings.
2926 @rnindex string-length
2927 @deffn {Scheme Procedure} string-length string
2928 @deffnx {C Function} scm_string_length (string)
2929 Return the number of characters in @var{string}.
2932 @deftypefn {C Function} size_t scm_c_string_length (SCM str)
2933 Return the number of characters in @var{str} as a @code{size_t}.
2937 @deffn {Scheme Procedure} string-ref str k
2938 @deffnx {C Function} scm_string_ref (str, k)
2939 Return character @var{k} of @var{str} using zero-origin
2940 indexing. @var{k} must be a valid index of @var{str}.
2943 @deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2944 Return character @var{k} of @var{str} using zero-origin
2945 indexing. @var{k} must be a valid index of @var{str}.
2948 @rnindex string-copy
2949 @deffn {Scheme Procedure} string-copy str [start [end]]
2950 @deffnx {C Function} scm_substring_copy (str, start, end)
2951 @deffnx {C Function} scm_string_copy (str)
2952 Return a copy of the given string @var{str}.
2954 The returned string shares storage with @var{str} initially, but it is
2955 copied as soon as one of the two strings is modified.
2959 @deffn {Scheme Procedure} substring str start [end]
2960 @deffnx {C Function} scm_substring (str, start, end)
2961 Return a new string formed from the characters
2962 of @var{str} beginning with index @var{start} (inclusive) and
2963 ending with index @var{end} (exclusive).
2964 @var{str} must be a string, @var{start} and @var{end} must be
2965 exact integers satisfying:
2967 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
2969 The returned string shares storage with @var{str} initially, but it is
2970 copied as soon as one of the two strings is modified.
2973 @deffn {Scheme Procedure} substring/shared str start [end]
2974 @deffnx {C Function} scm_substring_shared (str, start, end)
2975 Like @code{substring}, but the strings continue to share their storage
2976 even if they are modified. Thus, modifications to @var{str} show up
2977 in the new string, and vice versa.
2980 @deffn {Scheme Procedure} substring/copy str start [end]
2981 @deffnx {C Function} scm_substring_copy (str, start, end)
2982 Like @code{substring}, but the storage for the new string is copied
2986 @deffn {Scheme Procedure} substring/read-only str start [end]
2987 @deffnx {C Function} scm_substring_read_only (str, start, end)
2988 Like @code{substring}, but the resulting string can not be modified.
2991 @deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2992 @deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2993 @deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2994 @deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
2995 Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2998 @deffn {Scheme Procedure} string-take s n
2999 @deffnx {C Function} scm_string_take (s, n)
3000 Return the @var{n} first characters of @var{s}.
3003 @deffn {Scheme Procedure} string-drop s n
3004 @deffnx {C Function} scm_string_drop (s, n)
3005 Return all but the first @var{n} characters of @var{s}.
3008 @deffn {Scheme Procedure} string-take-right s n
3009 @deffnx {C Function} scm_string_take_right (s, n)
3010 Return the @var{n} last characters of @var{s}.
3013 @deffn {Scheme Procedure} string-drop-right s n
3014 @deffnx {C Function} scm_string_drop_right (s, n)
3015 Return all but the last @var{n} characters of @var{s}.
3018 @deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
3019 @deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
3020 @deffnx {C Function} scm_string_pad (s, len, chr, start, end)
3021 @deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
3022 Take characters @var{start} to @var{end} from the string @var{s} and
3023 either pad with @var{char} or truncate them to give @var{len}
3026 @code{string-pad} pads or truncates on the left, so for example
3029 (string-pad "x" 3) @result{} " x"
3030 (string-pad "abcde" 3) @result{} "cde"
3033 @code{string-pad-right} pads or truncates on the right, so for example
3036 (string-pad-right "x" 3) @result{} "x "
3037 (string-pad-right "abcde" 3) @result{} "abc"
3041 @deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
3042 @deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
3043 @deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
3044 @deffnx {C Function} scm_string_trim (s, char_pred, start, end)
3045 @deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
3046 @deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
3047 Trim occurrences of @var{char_pred} from the ends of @var{s}.
3049 @code{string-trim} trims @var{char_pred} characters from the left
3050 (start) of the string, @code{string-trim-right} trims them from the
3051 right (end) of the string, @code{string-trim-both} trims from both
3054 @var{char_pred} can be a character, a character set, or a predicate
3055 procedure to call on each character. If @var{char_pred} is not given
3056 the default is whitespace as per @code{char-set:whitespace}
3057 (@pxref{Standard Character Sets}).
3060 (string-trim " x ") @result{} "x "
3061 (string-trim-right "banana" #\a) @result{} "banan"
3062 (string-trim-both ".,xy:;" char-set:punctuation)
3064 (string-trim-both "xyzzy" (lambda (c)
3071 @node String Modification
3072 @subsubsection String Modification
3074 These procedures are for modifying strings in-place. This means that the
3075 result of the operation is not a new string; instead, the original string's
3076 memory representation is modified.
3078 @rnindex string-set!
3079 @deffn {Scheme Procedure} string-set! str k chr
3080 @deffnx {C Function} scm_string_set_x (str, k, chr)
3081 Store @var{chr} in element @var{k} of @var{str} and return
3082 an unspecified value. @var{k} must be a valid index of
3086 @deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
3087 Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
3090 @rnindex string-fill!
3091 @deffn {Scheme Procedure} string-fill! str chr [start [end]]
3092 @deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
3093 @deffnx {C Function} scm_string_fill_x (str, chr)
3094 Stores @var{chr} in every element of the given @var{str} and
3095 returns an unspecified value.
3098 @deffn {Scheme Procedure} substring-fill! str start end fill
3099 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
3100 Change every character in @var{str} between @var{start} and
3101 @var{end} to @var{fill}.
3104 (define y "abcdefg")
3105 (substring-fill! y 1 3 #\r)
3111 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
3112 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
3113 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
3114 into @var{str2} beginning at position @var{start2}.
3115 @var{str1} and @var{str2} can be the same string.
3118 @deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
3119 @deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
3120 Copy the sequence of characters from index range [@var{start},
3121 @var{end}) in string @var{s} to string @var{target}, beginning
3122 at index @var{tstart}. The characters are copied left-to-right
3123 or right-to-left as needed -- the copy is guaranteed to work,
3124 even if @var{target} and @var{s} are the same string. It is an
3125 error if the copy operation runs off the end of the target
3130 @node String Comparison
3131 @subsubsection String Comparison
3133 The procedures in this section are similar to the character ordering
3134 predicates (@pxref{Characters}), but are defined on character sequences.
3136 The first set is specified in R5RS and has names that end in @code{?}.
3137 The second set is specified in SRFI-13 and the names have not ending
3140 The predicates ending in @code{-ci} ignore the character case
3141 when comparing strings. For now, case-insensitive comparison is done
3142 using the R5RS rules, where every lower-case character that has a
3143 single character upper-case form is converted to uppercase before
3144 comparison. See @xref{Text Collation, the @code{(ice-9
3145 i18n)} module}, for locale-dependent string comparison.
3148 @deffn {Scheme Procedure} string=? [s1 [s2 . rest]]
3149 @deffnx {C Function} scm_i_string_equal_p (s1, s2, rest)
3150 Lexicographic equality predicate; return @code{#t} if the two
3151 strings are the same length and contain the same characters in
3152 the same positions, otherwise return @code{#f}.
3154 The procedure @code{string-ci=?} treats upper and lower case
3155 letters as though they were the same character, but
3156 @code{string=?} treats upper and lower case as distinct
3161 @deffn {Scheme Procedure} string<? [s1 [s2 . rest]]
3162 @deffnx {C Function} scm_i_string_less_p (s1, s2, rest)
3163 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3164 is lexicographically less than @var{s2}.
3168 @deffn {Scheme Procedure} string<=? [s1 [s2 . rest]]
3169 @deffnx {C Function} scm_i_string_leq_p (s1, s2, rest)
3170 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3171 is lexicographically less than or equal to @var{s2}.
3175 @deffn {Scheme Procedure} string>? [s1 [s2 . rest]]
3176 @deffnx {C Function} scm_i_string_gr_p (s1, s2, rest)
3177 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3178 is lexicographically greater than @var{s2}.
3182 @deffn {Scheme Procedure} string>=? [s1 [s2 . rest]]
3183 @deffnx {C Function} scm_i_string_geq_p (s1, s2, rest)
3184 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3185 is lexicographically greater than or equal to @var{s2}.
3188 @rnindex string-ci=?
3189 @deffn {Scheme Procedure} string-ci=? [s1 [s2 . rest]]
3190 @deffnx {C Function} scm_i_string_ci_equal_p (s1, s2, rest)
3191 Case-insensitive string equality predicate; return @code{#t} if
3192 the two strings are the same length and their component
3193 characters match (ignoring case) at each position; otherwise
3197 @rnindex string-ci<?
3198 @deffn {Scheme Procedure} string-ci<? [s1 [s2 . rest]]
3199 @deffnx {C Function} scm_i_string_ci_less_p (s1, s2, rest)
3200 Case insensitive lexicographic ordering predicate; return
3201 @code{#t} if @var{s1} is lexicographically less than @var{s2}
3206 @deffn {Scheme Procedure} string-ci<=? [s1 [s2 . rest]]
3207 @deffnx {C Function} scm_i_string_ci_leq_p (s1, s2, rest)
3208 Case insensitive lexicographic ordering predicate; return
3209 @code{#t} if @var{s1} is lexicographically less than or equal
3210 to @var{s2} regardless of case.
3213 @rnindex string-ci>?
3214 @deffn {Scheme Procedure} string-ci>? [s1 [s2 . rest]]
3215 @deffnx {C Function} scm_i_string_ci_gr_p (s1, s2, rest)
3216 Case insensitive lexicographic ordering predicate; return
3217 @code{#t} if @var{s1} is lexicographically greater than
3218 @var{s2} regardless of case.
3221 @rnindex string-ci>=?
3222 @deffn {Scheme Procedure} string-ci>=? [s1 [s2 . rest]]
3223 @deffnx {C Function} scm_i_string_ci_geq_p (s1, s2, rest)
3224 Case insensitive lexicographic ordering predicate; return
3225 @code{#t} if @var{s1} is lexicographically greater than or
3226 equal to @var{s2} regardless of case.
3229 @deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3230 @deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3231 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3232 mismatch index, depending upon whether @var{s1} is less than,
3233 equal to, or greater than @var{s2}. The mismatch index is the
3234 largest index @var{i} such that for every 0 <= @var{j} <
3235 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3236 @var{i} is the first position that does not match.
3239 @deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3240 @deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3241 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3242 mismatch index, depending upon whether @var{s1} is less than,
3243 equal to, or greater than @var{s2}. The mismatch index is the
3244 largest index @var{i} such that for every 0 <= @var{j} <
3245 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3246 @var{i} is the first position where the lowercased letters
3251 @deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3252 @deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3253 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3257 @deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3258 @deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3259 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3263 @deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3264 @deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3265 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3266 true value otherwise.
3269 @deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3270 @deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3271 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3272 true value otherwise.
3275 @deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3276 @deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3277 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3281 @deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3282 @deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3283 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3287 @deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3288 @deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3289 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3290 value otherwise. The character comparison is done
3294 @deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3295 @deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3296 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3297 value otherwise. The character comparison is done
3301 @deffn {Scheme Procedure} string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
3302 @deffnx {C Function} scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
3303 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3304 true value otherwise. The character comparison is done
3308 @deffn {Scheme Procedure} string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
3309 @deffnx {C Function} scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
3310 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3311 true value otherwise. The character comparison is done
3315 @deffn {Scheme Procedure} string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
3316 @deffnx {C Function} scm_string_ci_le (s1, s2, start1, end1, start2, end2)
3317 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3318 value otherwise. The character comparison is done
3322 @deffn {Scheme Procedure} string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
3323 @deffnx {C Function} scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
3324 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3325 otherwise. The character comparison is done
3329 @deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3330 @deffnx {C Function} scm_substring_hash (s, bound, start, end)
3331 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).
3334 @deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3335 @deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3336 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).
3339 Because the same visual appearance of an abstract Unicode character can
3340 be obtained via multiple sequences of Unicode characters, even the
3341 case-insensitive string comparison functions described above may return
3342 @code{#f} when presented with strings containing different
3343 representations of the same character. For example, the Unicode
3344 character ``LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE'' can be
3345 represented with a single character (U+1E69) or by the character ``LATIN
3346 SMALL LETTER S'' (U+0073) followed by the combining marks ``COMBINING
3347 DOT BELOW'' (U+0323) and ``COMBINING DOT ABOVE'' (U+0307).
3349 For this reason, it is often desirable to ensure that the strings
3350 to be compared are using a mutually consistent representation for every
3351 character. The Unicode standard defines two methods of normalizing the
3352 contents of strings: Decomposition, which breaks composite characters
3353 into a set of constituent characters with an ordering defined by the
3354 Unicode Standard; and composition, which performs the converse.
3356 There are two decomposition operations. ``Canonical decomposition''
3357 produces character sequences that share the same visual appearance as
3358 the original characters, while ``compatiblity decomposition'' produces
3359 ones whose visual appearances may differ from the originals but which
3360 represent the same abstract character.
3362 These operations are encapsulated in the following set of normalization
3367 Characters are decomposed to their canonical forms.
3370 Characters are decomposed to their compatibility forms.
3373 Characters are decomposed to their canonical forms, then composed.
3376 Characters are decomposed to their compatibility forms, then composed.
3380 The functions below put their arguments into one of the forms described
3383 @deffn {Scheme Procedure} string-normalize-nfd s
3384 @deffnx {C Function} scm_string_normalize_nfd (s)
3385 Return the @code{NFD} normalized form of @var{s}.
3388 @deffn {Scheme Procedure} string-normalize-nfkd s
3389 @deffnx {C Function} scm_string_normalize_nfkd (s)
3390 Return the @code{NFKD} normalized form of @var{s}.
3393 @deffn {Scheme Procedure} string-normalize-nfc s
3394 @deffnx {C Function} scm_string_normalize_nfc (s)
3395 Return the @code{NFC} normalized form of @var{s}.
3398 @deffn {Scheme Procedure} string-normalize-nfkc s
3399 @deffnx {C Function} scm_string_normalize_nfkc (s)
3400 Return the @code{NFKC} normalized form of @var{s}.
3403 @node String Searching
3404 @subsubsection String Searching
3406 @deffn {Scheme Procedure} string-index s char_pred [start [end]]
3407 @deffnx {C Function} scm_string_index (s, char_pred, start, end)
3408 Search through the string @var{s} from left to right, returning
3409 the index of the first occurrence of a character which
3413 equals @var{char_pred}, if it is character,
3416 satisfies the predicate @var{char_pred}, if it is a procedure,
3419 is in the set @var{char_pred}, if it is a character set.
3422 Return @code{#f} if no match is found.
3425 @deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3426 @deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3427 Search through the string @var{s} from right to left, returning
3428 the index of the last occurrence of a character which
3432 equals @var{char_pred}, if it is character,
3435 satisfies the predicate @var{char_pred}, if it is a procedure,
3438 is in the set if @var{char_pred} is a character set.
3441 Return @code{#f} if no match is found.
3444 @deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3445 @deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3446 Return the length of the longest common prefix of the two
3450 @deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3451 @deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3452 Return the length of the longest common prefix of the two
3453 strings, ignoring character case.
3456 @deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3457 @deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3458 Return the length of the longest common suffix of the two
3462 @deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3463 @deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3464 Return the length of the longest common suffix of the two
3465 strings, ignoring character case.
3468 @deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3469 @deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3470 Is @var{s1} a prefix of @var{s2}?
3473 @deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3474 @deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3475 Is @var{s1} a prefix of @var{s2}, ignoring character case?
3478 @deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3479 @deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3480 Is @var{s1} a suffix of @var{s2}?
3483 @deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3484 @deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3485 Is @var{s1} a suffix of @var{s2}, ignoring character case?
3488 @deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3489 @deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3490 Search through the string @var{s} from right to left, returning
3491 the index of the last occurrence of a character which
3495 equals @var{char_pred}, if it is character,
3498 satisfies the predicate @var{char_pred}, if it is a procedure,
3501 is in the set if @var{char_pred} is a character set.
3504 Return @code{#f} if no match is found.
3507 @deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3508 @deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3509 Search through the string @var{s} from left to right, returning
3510 the index of the first occurrence of a character which
3514 does not equal @var{char_pred}, if it is character,
3517 does not satisfy the predicate @var{char_pred}, if it is a
3521 is not in the set if @var{char_pred} is a character set.
3525 @deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3526 @deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3527 Search through the string @var{s} from right to left, returning
3528 the index of the last occurrence of a character which
3532 does not equal @var{char_pred}, if it is character,
3535 does not satisfy the predicate @var{char_pred}, if it is a
3539 is not in the set if @var{char_pred} is a character set.
3543 @deffn {Scheme Procedure} string-count s char_pred [start [end]]
3544 @deffnx {C Function} scm_string_count (s, char_pred, start, end)
3545 Return the count of the number of characters in the string
3550 equals @var{char_pred}, if it is character,
3553 satisfies the predicate @var{char_pred}, if it is a procedure.
3556 is in the set @var{char_pred}, if it is a character set.
3560 @deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3561 @deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3562 Does string @var{s1} contain string @var{s2}? Return the index
3563 in @var{s1} where @var{s2} occurs as a substring, or false.
3564 The optional start/end indices restrict the operation to the
3565 indicated substrings.
3568 @deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3569 @deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3570 Does string @var{s1} contain string @var{s2}? Return the index
3571 in @var{s1} where @var{s2} occurs as a substring, or false.
3572 The optional start/end indices restrict the operation to the
3573 indicated substrings. Character comparison is done
3577 @node Alphabetic Case Mapping
3578 @subsubsection Alphabetic Case Mapping
3580 These are procedures for mapping strings to their upper- or lower-case
3581 equivalents, respectively, or for capitalizing strings.
3583 They use the basic case mapping rules for Unicode characters. No
3584 special language or context rules are considered. The resulting strings
3585 are guaranteed to be the same length as the input strings.
3587 @xref{Character Case Mapping, the @code{(ice-9
3588 i18n)} module}, for locale-dependent case conversions.
3590 @deffn {Scheme Procedure} string-upcase str [start [end]]
3591 @deffnx {C Function} scm_substring_upcase (str, start, end)
3592 @deffnx {C Function} scm_string_upcase (str)
3593 Upcase every character in @code{str}.
3596 @deffn {Scheme Procedure} string-upcase! str [start [end]]
3597 @deffnx {C Function} scm_substring_upcase_x (str, start, end)
3598 @deffnx {C Function} scm_string_upcase_x (str)
3599 Destructively upcase every character in @code{str}.
3609 @deffn {Scheme Procedure} string-downcase str [start [end]]
3610 @deffnx {C Function} scm_substring_downcase (str, start, end)
3611 @deffnx {C Function} scm_string_downcase (str)
3612 Downcase every character in @var{str}.
3615 @deffn {Scheme Procedure} string-downcase! str [start [end]]
3616 @deffnx {C Function} scm_substring_downcase_x (str, start, end)
3617 @deffnx {C Function} scm_string_downcase_x (str)
3618 Destructively downcase every character in @var{str}.
3623 (string-downcase! y)
3630 @deffn {Scheme Procedure} string-capitalize str
3631 @deffnx {C Function} scm_string_capitalize (str)
3632 Return a freshly allocated string with the characters in
3633 @var{str}, where the first character of every word is
3637 @deffn {Scheme Procedure} string-capitalize! str
3638 @deffnx {C Function} scm_string_capitalize_x (str)
3639 Upcase the first character of every word in @var{str}
3640 destructively and return @var{str}.
3643 y @result{} "hello world"
3644 (string-capitalize! y) @result{} "Hello World"
3645 y @result{} "Hello World"
3649 @deffn {Scheme Procedure} string-titlecase str [start [end]]
3650 @deffnx {C Function} scm_string_titlecase (str, start, end)
3651 Titlecase every first character in a word in @var{str}.
3654 @deffn {Scheme Procedure} string-titlecase! str [start [end]]
3655 @deffnx {C Function} scm_string_titlecase_x (str, start, end)
3656 Destructively titlecase every first character in a word in
3660 @node Reversing and Appending Strings
3661 @subsubsection Reversing and Appending Strings
3663 @deffn {Scheme Procedure} string-reverse str [start [end]]
3664 @deffnx {C Function} scm_string_reverse (str, start, end)
3665 Reverse the string @var{str}. The optional arguments
3666 @var{start} and @var{end} delimit the region of @var{str} to
3670 @deffn {Scheme Procedure} string-reverse! str [start [end]]
3671 @deffnx {C Function} scm_string_reverse_x (str, start, end)
3672 Reverse the string @var{str} in-place. The optional arguments
3673 @var{start} and @var{end} delimit the region of @var{str} to
3674 operate on. The return value is unspecified.
3677 @rnindex string-append
3678 @deffn {Scheme Procedure} string-append . args
3679 @deffnx {C Function} scm_string_append (args)
3680 Return a newly allocated string whose characters form the
3681 concatenation of the given strings, @var{args}.
3685 (string-append h "world"))
3686 @result{} "hello world"
3690 @deffn {Scheme Procedure} string-append/shared . rest
3691 @deffnx {C Function} scm_string_append_shared (rest)
3692 Like @code{string-append}, but the result may share memory
3693 with the argument strings.
3696 @deffn {Scheme Procedure} string-concatenate ls
3697 @deffnx {C Function} scm_string_concatenate (ls)
3698 Append the elements of @var{ls} (which must be strings)
3699 together into a single string. Guaranteed to return a freshly
3703 @deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3704 @deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3705 Without optional arguments, this procedure is equivalent to
3708 (string-concatenate (reverse ls))
3711 If the optional argument @var{final_string} is specified, it is
3712 consed onto the beginning to @var{ls} before performing the
3713 list-reverse and string-concatenate operations. If @var{end}
3714 is given, only the characters of @var{final_string} up to index
3717 Guaranteed to return a freshly allocated string.
3720 @deffn {Scheme Procedure} string-concatenate/shared ls
3721 @deffnx {C Function} scm_string_concatenate_shared (ls)
3722 Like @code{string-concatenate}, but the result may share memory
3723 with the strings in the list @var{ls}.
3726 @deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3727 @deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3728 Like @code{string-concatenate-reverse}, but the result may
3729 share memory with the strings in the @var{ls} arguments.
3732 @node Mapping Folding and Unfolding
3733 @subsubsection Mapping, Folding, and Unfolding
3735 @deffn {Scheme Procedure} string-map proc s [start [end]]
3736 @deffnx {C Function} scm_string_map (proc, s, start, end)
3737 @var{proc} is a char->char procedure, it is mapped over
3738 @var{s}. The order in which the procedure is applied to the
3739 string elements is not specified.
3742 @deffn {Scheme Procedure} string-map! proc s [start [end]]
3743 @deffnx {C Function} scm_string_map_x (proc, s, start, end)
3744 @var{proc} is a char->char procedure, it is mapped over
3745 @var{s}. The order in which the procedure is applied to the
3746 string elements is not specified. The string @var{s} is
3747 modified in-place, the return value is not specified.
3750 @deffn {Scheme Procedure} string-for-each proc s [start [end]]
3751 @deffnx {C Function} scm_string_for_each (proc, s, start, end)
3752 @var{proc} is mapped over @var{s} in left-to-right order. The
3753 return value is not specified.
3756 @deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3757 @deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
3758 Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3761 For example, to change characters to alternately upper and lower case,
3764 (define str (string-copy "studly"))
3765 (string-for-each-index
3768 ((if (even? i) char-upcase char-downcase)
3769 (string-ref str i))))
3771 str @result{} "StUdLy"
3775 @deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3776 @deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3777 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3778 as the terminating element, from left to right. @var{kons}
3779 must expect two arguments: The actual character and the last
3780 result of @var{kons}' application.
3783 @deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3784 @deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3785 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3786 as the terminating element, from right to left. @var{kons}
3787 must expect two arguments: The actual character and the last
3788 result of @var{kons}' application.
3791 @deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3792 @deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3794 @item @var{g} is used to generate a series of @emph{seed}
3795 values from the initial @var{seed}: @var{seed}, (@var{g}
3796 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3798 @item @var{p} tells us when to stop -- when it returns true
3799 when applied to one of these seed values.
3800 @item @var{f} maps each seed value to the corresponding
3801 character in the result string. These chars are assembled
3802 into the string in a left-to-right order.
3803 @item @var{base} is the optional initial/leftmost portion
3804 of the constructed string; it default to the empty
3806 @item @var{make_final} is applied to the terminal seed
3807 value (on which @var{p} returns true) to produce
3808 the final/rightmost portion of the constructed string.
3809 The default is nothing extra.
3813 @deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3814 @deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3816 @item @var{g} is used to generate a series of @emph{seed}
3817 values from the initial @var{seed}: @var{seed}, (@var{g}
3818 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3820 @item @var{p} tells us when to stop -- when it returns true
3821 when applied to one of these seed values.
3822 @item @var{f} maps each seed value to the corresponding
3823 character in the result string. These chars are assembled
3824 into the string in a right-to-left order.
3825 @item @var{base} is the optional initial/rightmost portion
3826 of the constructed string; it default to the empty
3828 @item @var{make_final} is applied to the terminal seed
3829 value (on which @var{p} returns true) to produce
3830 the final/leftmost portion of the constructed string.
3831 It defaults to @code{(lambda (x) )}.
3835 @node Miscellaneous String Operations
3836 @subsubsection Miscellaneous String Operations
3838 @deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3839 @deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3840 This is the @emph{extended substring} procedure that implements
3841 replicated copying of a substring of some string.
3843 @var{s} is a string, @var{start} and @var{end} are optional
3844 arguments that demarcate a substring of @var{s}, defaulting to
3845 0 and the length of @var{s}. Replicate this substring up and
3846 down index space, in both the positive and negative directions.
3847 @code{xsubstring} returns the substring of this string
3848 beginning at index @var{from}, and ending at @var{to}, which
3849 defaults to @var{from} + (@var{end} - @var{start}).
3852 @deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3853 @deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3854 Exactly the same as @code{xsubstring}, but the extracted text
3855 is written into the string @var{target} starting at index
3856 @var{tstart}. The operation is not defined if @code{(eq?
3857 @var{target} @var{s})} or these arguments share storage -- you
3858 cannot copy a string on top of itself.
3861 @deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3862 @deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3863 Return the string @var{s1}, but with the characters
3864 @var{start1} @dots{} @var{end1} replaced by the characters
3865 @var{start2} @dots{} @var{end2} from @var{s2}.
3868 @deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3869 @deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3870 Split the string @var{s} into a list of substrings, where each
3871 substring is a maximal non-empty contiguous sequence of
3872 characters from the character set @var{token_set}, which
3873 defaults to @code{char-set:graphic}.
3874 If @var{start} or @var{end} indices are provided, they restrict
3875 @code{string-tokenize} to operating on the indicated substring
3879 @deffn {Scheme Procedure} string-filter char_pred s [start [end]]
3880 @deffnx {C Function} scm_string_filter (char_pred, s, start, end)
3881 Filter the string @var{s}, retaining only those characters which
3882 satisfy @var{char_pred}.
3884 If @var{char_pred} is a procedure, it is applied to each character as
3885 a predicate, if it is a character, it is tested for equality and if it
3886 is a character set, it is tested for membership.
3889 @deffn {Scheme Procedure} string-delete char_pred s [start [end]]
3890 @deffnx {C Function} scm_string_delete (char_pred, s, start, end)
3891 Delete characters satisfying @var{char_pred} from @var{s}.
3893 If @var{char_pred} is a procedure, it is applied to each character as
3894 a predicate, if it is a character, it is tested for equality and if it
3895 is a character set, it is tested for membership.
3898 @node Conversion to/from C
3899 @subsubsection Conversion to/from C
3901 When creating a Scheme string from a C string or when converting a
3902 Scheme string to a C string, the concept of character encoding becomes
3905 In C, a string is just a sequence of bytes, and the character encoding
3906 describes the relation between these bytes and the actual characters
3907 that make up the string. For Scheme strings, character encoding is
3908 not an issue (most of the time), since in Scheme you never get to see
3909 the bytes, only the characters.
3911 Converting to C and converting from C each have their own challenges.
3913 When converting from C to Scheme, it is important that the sequence of
3914 bytes in the C string be valid with respect to its encoding. ASCII
3915 strings, for example, can't have any bytes greater than 127. An ASCII
3916 byte greater than 127 is considered @emph{ill-formed} and cannot be
3917 converted into a Scheme character.
3919 Problems can occur in the reverse operation as well. Not all character
3920 encodings can hold all possible Scheme characters. Some encodings, like
3921 ASCII for example, can only describe a small subset of all possible
3922 characters. So, when converting to C, one must first decide what to do
3923 with Scheme characters that can't be represented in the C string.
3925 Converting a Scheme string to a C string will often allocate fresh
3926 memory to hold the result. You must take care that this memory is
3927 properly freed eventually. In many cases, this can be achieved by
3928 using @code{scm_dynwind_free} inside an appropriate dynwind context,
3929 @xref{Dynamic Wind}.
3931 @deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3932 @deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3933 Creates a new Scheme string that has the same contents as @var{str} when
3934 interpreted in the locale character encoding of the
3935 @code{current-input-port}.
3937 For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3939 For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3940 @var{str} in bytes, and @var{str} does not need to be null-terminated.
3941 If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3942 null-terminated and the real length will be found with @code{strlen}.
3944 If the C string is ill-formed, an error will be raised.
3947 @deftypefn {C Function} SCM scm_take_locale_string (char *str)
3948 @deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3949 Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3950 respectively, but also frees @var{str} with @code{free} eventually.
3951 Thus, you can use this function when you would free @var{str} anyway
3952 immediately after creating the Scheme string. In certain cases, Guile
3953 can then use @var{str} directly as its internal representation.
3956 @deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3957 @deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
3958 Returns a C string with the same contents as @var{str} in the locale
3959 encoding of the @code{current-output-port}. The C string must be freed
3960 with @code{free} eventually, maybe by using @code{scm_dynwind_free},
3961 @xref{Dynamic Wind}.
3963 For @code{scm_to_locale_string}, the returned string is
3964 null-terminated and an error is signalled when @var{str} contains
3965 @code{#\nul} characters.
3967 For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3968 @var{str} might contain @code{#\nul} characters and the length of the
3969 returned string in bytes is stored in @code{*@var{lenp}}. The
3970 returned string will not be null-terminated in this case. If
3971 @var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3972 @code{scm_to_locale_string}.
3974 If a character in @var{str} cannot be represented in the locale encoding
3975 of the current output port, the port conversion strategy of the current
3976 output port will determine the result, @xref{Ports}. If output port's
3977 conversion strategy is @code{error}, an error will be raised. If it is
3978 @code{subsitute}, a replacement character, such as a question mark, will
3979 be inserted in its place. If it is @code{escape}, a hex escape will be
3980 inserted in its place.
3983 @deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3984 Puts @var{str} as a C string in the current locale encoding into the
3985 memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3986 @var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3987 more than that. No terminating @code{'\0'} will be stored.
3989 The return value of @code{scm_to_locale_stringbuf} is the number of
3990 bytes that are needed for all of @var{str}, regardless of whether
3991 @var{buf} was large enough to hold them. Thus, when the return value
3992 is larger than @var{max_len}, only @var{max_len} bytes have been
3993 stored and you probably need to try again with a larger buffer.
3996 For most situations, string conversion should occur using the current
3997 locale, such as with the functions above. But there may be cases where
3998 one wants to convert strings from a character encoding other than the
3999 locale's character encoding. For these cases, the lower-level functions
4000 @code{scm_to_stringn} and @code{scm_from_stringn} are provided. These
4001 functions should seldom be necessary if one is properly using locales.
4003 @deftp {C Type} scm_t_string_failed_conversion_handler
4004 This is an enumerated type that can take one of three values:
4005 @code{SCM_FAILED_CONVERSION_ERROR},
4006 @code{SCM_FAILED_CONVERSION_QUESTION_MARK}, and
4007 @code{SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE}. They are used to indicate
4008 a strategy for handling characters that cannot be converted to or from a
4009 given character encoding. @code{SCM_FAILED_CONVERSION_ERROR} indicates
4010 that a conversion should throw an error if some characters cannot be
4011 converted. @code{SCM_FAILED_CONVERSION_QUESTION_MARK} indicates that a
4012 conversion should replace unconvertable characters with the question
4013 mark character. And, @code{SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE}
4014 requests that a conversion should replace an unconvertable character
4015 with an escape sequence.
4017 While all three strategies apply when converting Scheme strings to C,
4018 only @code{SCM_FAILED_CONVERSION_ERROR} and
4019 @code{SCM_FAILED_CONVERSION_QUESTION_MARK} can be used when converting C
4023 @deftypefn {C Function} char *scm_to_stringn (SCM str, size_t *lenp, const char *encoding, scm_t_string_failed_conversion_handler handler)
4024 This function returns a newly allocated C string from the Guile string
4025 @var{str}. The length of the string will be returned in @var{lenp}.
4026 The character encoding of the C string is passed as the ASCII,
4027 null-terminated C string @var{encoding}. The @var{handler} parameter
4028 gives a strategy for dealing with characters that cannot be converted
4029 into @var{encoding}.
4031 If @var{lenp} is NULL, this function will return a null-terminated C
4032 string. It will throw an error if the string contains a null
4036 @deftypefn {C Function} SCM scm_from_stringn (const char *str, size_t len, const char *encoding, scm_t_string_failed_conversion_handler handler)
4037 This function returns a scheme string from the C string @var{str}. The
4038 length of the C string is input as @var{len}. The encoding of the C
4039 string is passed as the ASCII, null-terminated C string @code{encoding}.
4040 The @var{handler} parameters suggests a strategy for dealing with
4041 unconvertable characters.
4044 ISO-8859-1 is the most common 8-bit character encoding. This encoding
4045 is also referred to as the Latin-1 encoding. The following two
4046 conversion functions are provided to convert between Latin-1 C strings
4049 @deftypefn {C Function} SCM scm_from_latin1_stringn (const char *str, size_t len)
4050 @deftypefnx {C Function} SCM scm_from_utf8_stringn (const char *str, size_t len)
4051 @deftypefnx {C Function} SCM scm_from_utf32_stringn (const scm_t_wchar *str, size_t len)
4052 Return a scheme string from C string @var{str}, which is ISO-8859-1-,
4053 UTF-8-, or UTF-32-encoded, of length @var{len}. @var{len} is the number
4054 of bytes pointed to by @var{str} for @code{scm_from_latin1_stringn} and
4055 @code{scm_from_utf8_stringn}; it is the number of elements (code points)
4056 in @var{str} in the case of @code{scm_from_utf32_stringn}.
4059 @deftypefn {C function} char *scm_to_latin1_stringn (SCM str, size_t *lenp)
4060 @deftypefnx {C function} char *scm_to_utf8_stringn (SCM str, size_t *lenp)
4061 @deftypefnx {C function} scm_t_wchar *scm_to_utf32_stringn (SCM str, size_t *lenp)
4062 Return a newly allocated, ISO-8859-1-, UTF-8-, or UTF-32-encoded C string
4063 from Scheme string @var{str}. An error is thrown when @var{str}
4064 string cannot be converted to the specified encoding. If @var{lenp} is
4065 @code{NULL}, the returned C string will be null terminated, and an error
4066 will be thrown if the C string would otherwise contain null
4067 characters. If @var{lenp} is not NULL, the length of the string is
4068 returned in @var{lenp}, and the string is not null terminated.
4071 @node String Internals
4072 @subsubsection String Internals
4074 Guile stores each string in memory as a contiguous array of Unicode code
4075 points along with an associated set of attributes. If all of the code
4076 points of a string have an integer range between 0 and 255 inclusive,
4077 the code point array is stored as one byte per code point: it is stored
4078 as an ISO-8859-1 (aka Latin-1) string. If any of the code points of the
4079 string has an integer value greater that 255, the code point array is
4080 stored as four bytes per code point: it is stored as a UTF-32 string.
4082 Conversion between the one-byte-per-code-point and
4083 four-bytes-per-code-point representations happens automatically as
4086 No API is provided to set the internal representation of strings;
4087 however, there are pair of procedures available to query it. These are
4088 debugging procedures. Using them in production code is discouraged,
4089 since the details of Guile's internal representation of strings may
4090 change from release to release.
4092 @deffn {Scheme Procedure} string-bytes-per-char str
4093 @deffnx {C Function} scm_string_bytes_per_char (str)
4094 Return the number of bytes used to encode a Unicode code point in string
4095 @var{str}. The result is one or four.
4098 @deffn {Scheme Procedure} %string-dump str
4099 @deffnx {C Function} scm_sys_string_dump (str)
4100 Returns an association list containing debugging information for
4101 @var{str}. The association list has the following entries.
4108 The start index of the string into its stringbuf
4111 The length of the string
4114 If this string is a substring, it returns its
4115 parent string. Otherwise, it returns @code{#f}
4118 @code{#t} if the string is read-only
4120 @item stringbuf-chars
4121 A new string containing this string's stringbuf's characters
4123 @item stringbuf-length
4124 The number of characters in this stringbuf
4126 @item stringbuf-shared
4127 @code{#t} if this stringbuf is shared
4129 @item stringbuf-wide
4130 @code{#t} if this stringbuf's characters are stored in a 32-bit buffer,
4131 or @code{#f} if they are stored in an 8-bit buffer
4137 @subsection Bytevectors
4142 A @dfn{bytevector} is a raw bit string. The @code{(rnrs bytevectors)}
4143 module provides the programming interface specified by the
4144 @uref{http://www.r6rs.org/, Revised^6 Report on the Algorithmic Language
4145 Scheme (R6RS)}. It contains procedures to manipulate bytevectors and
4146 interpret their contents in a number of ways: bytevector contents can be
4147 accessed as signed or unsigned integer of various sizes and endianness,
4148 as IEEE-754 floating point numbers, or as strings. It is a useful tool
4149 to encode and decode binary data.
4151 The R6RS (Section 4.3.4) specifies an external representation for
4152 bytevectors, whereby the octets (integers in the range 0--255) contained
4153 in the bytevector are represented as a list prefixed by @code{#vu8}:
4159 denotes a 3-byte bytevector containing the octets 1, 53, and 204. Like
4160 string literals, booleans, etc., bytevectors are ``self-quoting'', i.e.,
4161 they do not need to be quoted:
4165 @result{} #vu8(1 53 204)
4168 Bytevectors can be used with the binary input/output primitives of the
4169 R6RS (@pxref{R6RS I/O Ports}).
4172 * Bytevector Endianness:: Dealing with byte order.
4173 * Bytevector Manipulation:: Creating, copying, manipulating bytevectors.
4174 * Bytevectors as Integers:: Interpreting bytes as integers.
4175 * Bytevectors and Integer Lists:: Converting to/from an integer list.
4176 * Bytevectors as Floats:: Interpreting bytes as real numbers.
4177 * Bytevectors as Strings:: Interpreting bytes as Unicode strings.
4178 * Bytevectors as Generalized Vectors:: Guile extension to the bytevector API.
4179 * Bytevectors as Uniform Vectors:: Bytevectors and SRFI-4.
4182 @node Bytevector Endianness
4183 @subsubsection Endianness
4189 Some of the following procedures take an @var{endianness} parameter.
4190 The @dfn{endianness} is defined as the order of bytes in multi-byte
4191 numbers: numbers encoded in @dfn{big endian} have their most
4192 significant bytes written first, whereas numbers encoded in
4193 @dfn{little endian} have their least significant bytes
4194 first@footnote{Big-endian and little-endian are the most common
4195 ``endiannesses'', but others do exist. For instance, the GNU MP
4196 library allows @dfn{word order} to be specified independently of
4197 @dfn{byte order} (@pxref{Integer Import and Export,,, gmp, The GNU
4198 Multiple Precision Arithmetic Library Manual}).}.
4200 Little-endian is the native endianness of the IA32 architecture and
4201 its derivatives, while big-endian is native to SPARC and PowerPC,
4202 among others. The @code{native-endianness} procedure returns the
4203 native endianness of the machine it runs on.
4205 @deffn {Scheme Procedure} native-endianness
4206 @deffnx {C Function} scm_native_endianness ()
4207 Return a value denoting the native endianness of the host machine.
4210 @deffn {Scheme Macro} endianness symbol
4211 Return an object denoting the endianness specified by @var{symbol}. If
4212 @var{symbol} is neither @code{big} nor @code{little} then an error is
4213 raised at expand-time.
4216 @defvr {C Variable} scm_endianness_big
4217 @defvrx {C Variable} scm_endianness_little
4218 The objects denoting big- and little-endianness, respectively.
4222 @node Bytevector Manipulation
4223 @subsubsection Manipulating Bytevectors
4225 Bytevectors can be created, copied, and analyzed with the following
4226 procedures and C functions.
4228 @deffn {Scheme Procedure} make-bytevector len [fill]
4229 @deffnx {C Function} scm_make_bytevector (len, fill)
4230 @deffnx {C Function} scm_c_make_bytevector (size_t len)
4231 Return a new bytevector of @var{len} bytes. Optionally, if @var{fill}
4232 is given, fill it with @var{fill}; @var{fill} must be in the range
4236 @deffn {Scheme Procedure} bytevector? obj
4237 @deffnx {C Function} scm_bytevector_p (obj)
4238 Return true if @var{obj} is a bytevector.
4241 @deftypefn {C Function} int scm_is_bytevector (SCM obj)
4242 Equivalent to @code{scm_is_true (scm_bytevector_p (obj))}.
4245 @deffn {Scheme Procedure} bytevector-length bv
4246 @deffnx {C Function} scm_bytevector_length (bv)
4247 Return the length in bytes of bytevector @var{bv}.
4250 @deftypefn {C Function} size_t scm_c_bytevector_length (SCM bv)
4251 Likewise, return the length in bytes of bytevector @var{bv}.
4254 @deffn {Scheme Procedure} bytevector=? bv1 bv2
4255 @deffnx {C Function} scm_bytevector_eq_p (bv1, bv2)
4256 Return is @var{bv1} equals to @var{bv2}---i.e., if they have the same
4257 length and contents.
4260 @deffn {Scheme Procedure} bytevector-fill! bv fill
4261 @deffnx {C Function} scm_bytevector_fill_x (bv, fill)
4262 Fill bytevector @var{bv} with @var{fill}, a byte.
4265 @deffn {Scheme Procedure} bytevector-copy! source source-start target target-start len
4266 @deffnx {C Function} scm_bytevector_copy_x (source, source_start, target, target_start, len)
4267 Copy @var{len} bytes from @var{source} into @var{target}, starting
4268 reading from @var{source-start} (a positive index within @var{source})
4269 and start writing at @var{target-start}.
4272 @deffn {Scheme Procedure} bytevector-copy bv
4273 @deffnx {C Function} scm_bytevector_copy (bv)
4274 Return a newly allocated copy of @var{bv}.
4277 @deftypefn {C Function} scm_t_uint8 scm_c_bytevector_ref (SCM bv, size_t index)
4278 Return the byte at @var{index} in bytevector @var{bv}.
4281 @deftypefn {C Function} void scm_c_bytevector_set_x (SCM bv, size_t index, scm_t_uint8 value)
4282 Set the byte at @var{index} in @var{bv} to @var{value}.
4285 Low-level C macros are available. They do not perform any
4286 type-checking; as such they should be used with care.
4288 @deftypefn {C Macro} size_t SCM_BYTEVECTOR_LENGTH (bv)
4289 Return the length in bytes of bytevector @var{bv}.
4292 @deftypefn {C Macro} {signed char *} SCM_BYTEVECTOR_CONTENTS (bv)
4293 Return a pointer to the contents of bytevector @var{bv}.
4297 @node Bytevectors as Integers
4298 @subsubsection Interpreting Bytevector Contents as Integers
4300 The contents of a bytevector can be interpreted as a sequence of
4301 integers of any given size, sign, and endianness.
4304 (let ((bv (make-bytevector 4)))
4305 (bytevector-u8-set! bv 0 #x12)
4306 (bytevector-u8-set! bv 1 #x34)
4307 (bytevector-u8-set! bv 2 #x56)
4308 (bytevector-u8-set! bv 3 #x78)
4310 (map (lambda (number)
4311 (number->string number 16))
4312 (list (bytevector-u8-ref bv 0)
4313 (bytevector-u16-ref bv 0 (endianness big))
4314 (bytevector-u32-ref bv 0 (endianness little)))))
4316 @result{} ("12" "1234" "78563412")
4319 The most generic procedures to interpret bytevector contents as integers
4320 are described below.
4322 @deffn {Scheme Procedure} bytevector-uint-ref bv index endianness size
4323 @deffnx {Scheme Procedure} bytevector-sint-ref bv index endianness size
4324 @deffnx {C Function} scm_bytevector_uint_ref (bv, index, endianness, size)
4325 @deffnx {C Function} scm_bytevector_sint_ref (bv, index, endianness, size)
4326 Return the @var{size}-byte long unsigned (resp. signed) integer at
4327 index @var{index} in @var{bv}, decoded according to @var{endianness}.
4330 @deffn {Scheme Procedure} bytevector-uint-set! bv index value endianness size
4331 @deffnx {Scheme Procedure} bytevector-sint-set! bv index value endianness size
4332 @deffnx {C Function} scm_bytevector_uint_set_x (bv, index, value, endianness, size)
4333 @deffnx {C Function} scm_bytevector_sint_set_x (bv, index, value, endianness, size)
4334 Set the @var{size}-byte long unsigned (resp. signed) integer at
4335 @var{index} to @var{value}, encoded according to @var{endianness}.
4338 The following procedures are similar to the ones above, but specialized
4339 to a given integer size:
4341 @deffn {Scheme Procedure} bytevector-u8-ref bv index
4342 @deffnx {Scheme Procedure} bytevector-s8-ref bv index
4343 @deffnx {Scheme Procedure} bytevector-u16-ref bv index endianness
4344 @deffnx {Scheme Procedure} bytevector-s16-ref bv index endianness
4345 @deffnx {Scheme Procedure} bytevector-u32-ref bv index endianness
4346 @deffnx {Scheme Procedure} bytevector-s32-ref bv index endianness
4347 @deffnx {Scheme Procedure} bytevector-u64-ref bv index endianness
4348 @deffnx {Scheme Procedure} bytevector-s64-ref bv index endianness
4349 @deffnx {C Function} scm_bytevector_u8_ref (bv, index)
4350 @deffnx {C Function} scm_bytevector_s8_ref (bv, index)
4351 @deffnx {C Function} scm_bytevector_u16_ref (bv, index, endianness)
4352 @deffnx {C Function} scm_bytevector_s16_ref (bv, index, endianness)
4353 @deffnx {C Function} scm_bytevector_u32_ref (bv, index, endianness)
4354 @deffnx {C Function} scm_bytevector_s32_ref (bv, index, endianness)
4355 @deffnx {C Function} scm_bytevector_u64_ref (bv, index, endianness)
4356 @deffnx {C Function} scm_bytevector_s64_ref (bv, index, endianness)
4357 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4358 16, 32 or 64) from @var{bv} at @var{index}, decoded according to
4362 @deffn {Scheme Procedure} bytevector-u8-set! bv index value
4363 @deffnx {Scheme Procedure} bytevector-s8-set! bv index value
4364 @deffnx {Scheme Procedure} bytevector-u16-set! bv index value endianness
4365 @deffnx {Scheme Procedure} bytevector-s16-set! bv index value endianness
4366 @deffnx {Scheme Procedure} bytevector-u32-set! bv index value endianness
4367 @deffnx {Scheme Procedure} bytevector-s32-set! bv index value endianness
4368 @deffnx {Scheme Procedure} bytevector-u64-set! bv index value endianness
4369 @deffnx {Scheme Procedure} bytevector-s64-set! bv index value endianness
4370 @deffnx {C Function} scm_bytevector_u8_set_x (bv, index, value)
4371 @deffnx {C Function} scm_bytevector_s8_set_x (bv, index, value)
4372 @deffnx {C Function} scm_bytevector_u16_set_x (bv, index, value, endianness)
4373 @deffnx {C Function} scm_bytevector_s16_set_x (bv, index, value, endianness)
4374 @deffnx {C Function} scm_bytevector_u32_set_x (bv, index, value, endianness)
4375 @deffnx {C Function} scm_bytevector_s32_set_x (bv, index, value, endianness)
4376 @deffnx {C Function} scm_bytevector_u64_set_x (bv, index, value, endianness)
4377 @deffnx {C Function} scm_bytevector_s64_set_x (bv, index, value, endianness)
4378 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4379 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to
4383 Finally, a variant specialized for the host's endianness is available
4384 for each of these functions (with the exception of the @code{u8}
4385 accessors, for obvious reasons):
4387 @deffn {Scheme Procedure} bytevector-u16-native-ref bv index
4388 @deffnx {Scheme Procedure} bytevector-s16-native-ref bv index
4389 @deffnx {Scheme Procedure} bytevector-u32-native-ref bv index
4390 @deffnx {Scheme Procedure} bytevector-s32-native-ref bv index
4391 @deffnx {Scheme Procedure} bytevector-u64-native-ref bv index
4392 @deffnx {Scheme Procedure} bytevector-s64-native-ref bv index
4393 @deffnx {C Function} scm_bytevector_u16_native_ref (bv, index)
4394 @deffnx {C Function} scm_bytevector_s16_native_ref (bv, index)
4395 @deffnx {C Function} scm_bytevector_u32_native_ref (bv, index)
4396 @deffnx {C Function} scm_bytevector_s32_native_ref (bv, index)
4397 @deffnx {C Function} scm_bytevector_u64_native_ref (bv, index)
4398 @deffnx {C Function} scm_bytevector_s64_native_ref (bv, index)
4399 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4400 16, 32 or 64) from @var{bv} at @var{index}, decoded according to the
4401 host's native endianness.
4404 @deffn {Scheme Procedure} bytevector-u16-native-set! bv index value
4405 @deffnx {Scheme Procedure} bytevector-s16-native-set! bv index value
4406 @deffnx {Scheme Procedure} bytevector-u32-native-set! bv index value
4407 @deffnx {Scheme Procedure} bytevector-s32-native-set! bv index value
4408 @deffnx {Scheme Procedure} bytevector-u64-native-set! bv index value
4409 @deffnx {Scheme Procedure} bytevector-s64-native-set! bv index value
4410 @deffnx {C Function} scm_bytevector_u16_native_set_x (bv, index, value)
4411 @deffnx {C Function} scm_bytevector_s16_native_set_x (bv, index, value)
4412 @deffnx {C Function} scm_bytevector_u32_native_set_x (bv, index, value)
4413 @deffnx {C Function} scm_bytevector_s32_native_set_x (bv, index, value)
4414 @deffnx {C Function} scm_bytevector_u64_native_set_x (bv, index, value)
4415 @deffnx {C Function} scm_bytevector_s64_native_set_x (bv, index, value)
4416 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4417 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to the
4418 host's native endianness.
4422 @node Bytevectors and Integer Lists
4423 @subsubsection Converting Bytevectors to/from Integer Lists
4425 Bytevector contents can readily be converted to/from lists of signed or
4429 (bytevector->sint-list (u8-list->bytevector (make-list 4 255))
4430 (endianness little) 2)
4434 @deffn {Scheme Procedure} bytevector->u8-list bv
4435 @deffnx {C Function} scm_bytevector_to_u8_list (bv)
4436 Return a newly allocated list of unsigned 8-bit integers from the
4437 contents of @var{bv}.
4440 @deffn {Scheme Procedure} u8-list->bytevector lst
4441 @deffnx {C Function} scm_u8_list_to_bytevector (lst)
4442 Return a newly allocated bytevector consisting of the unsigned 8-bit
4443 integers listed in @var{lst}.
4446 @deffn {Scheme Procedure} bytevector->uint-list bv endianness size
4447 @deffnx {Scheme Procedure} bytevector->sint-list bv endianness size
4448 @deffnx {C Function} scm_bytevector_to_uint_list (bv, endianness, size)
4449 @deffnx {C Function} scm_bytevector_to_sint_list (bv, endianness, size)
4450 Return a list of unsigned (resp. signed) integers of @var{size} bytes
4451 representing the contents of @var{bv}, decoded according to
4455 @deffn {Scheme Procedure} uint-list->bytevector lst endianness size
4456 @deffnx {Scheme Procedure} sint-list->bytevector lst endianness size
4457 @deffnx {C Function} scm_uint_list_to_bytevector (lst, endianness, size)
4458 @deffnx {C Function} scm_sint_list_to_bytevector (lst, endianness, size)
4459 Return a new bytevector containing the unsigned (resp. signed) integers
4460 listed in @var{lst} and encoded on @var{size} bytes according to
4464 @node Bytevectors as Floats
4465 @subsubsection Interpreting Bytevector Contents as Floating Point Numbers
4467 @cindex IEEE-754 floating point numbers
4469 Bytevector contents can also be accessed as IEEE-754 single- or
4470 double-precision floating point numbers (respectively 32 and 64-bit
4471 long) using the procedures described here.
4473 @deffn {Scheme Procedure} bytevector-ieee-single-ref bv index endianness
4474 @deffnx {Scheme Procedure} bytevector-ieee-double-ref bv index endianness
4475 @deffnx {C Function} scm_bytevector_ieee_single_ref (bv, index, endianness)
4476 @deffnx {C Function} scm_bytevector_ieee_double_ref (bv, index, endianness)
4477 Return the IEEE-754 single-precision floating point number from @var{bv}
4478 at @var{index} according to @var{endianness}.
4481 @deffn {Scheme Procedure} bytevector-ieee-single-set! bv index value endianness
4482 @deffnx {Scheme Procedure} bytevector-ieee-double-set! bv index value endianness
4483 @deffnx {C Function} scm_bytevector_ieee_single_set_x (bv, index, value, endianness)
4484 @deffnx {C Function} scm_bytevector_ieee_double_set_x (bv, index, value, endianness)
4485 Store real number @var{value} in @var{bv} at @var{index} according to
4489 Specialized procedures are also available:
4491 @deffn {Scheme Procedure} bytevector-ieee-single-native-ref bv index
4492 @deffnx {Scheme Procedure} bytevector-ieee-double-native-ref bv index
4493 @deffnx {C Function} scm_bytevector_ieee_single_native_ref (bv, index)
4494 @deffnx {C Function} scm_bytevector_ieee_double_native_ref (bv, index)
4495 Return the IEEE-754 single-precision floating point number from @var{bv}
4496 at @var{index} according to the host's native endianness.
4499 @deffn {Scheme Procedure} bytevector-ieee-single-native-set! bv index value
4500 @deffnx {Scheme Procedure} bytevector-ieee-double-native-set! bv index value
4501 @deffnx {C Function} scm_bytevector_ieee_single_native_set_x (bv, index, value)
4502 @deffnx {C Function} scm_bytevector_ieee_double_native_set_x (bv, index, value)
4503 Store real number @var{value} in @var{bv} at @var{index} according to
4504 the host's native endianness.
4508 @node Bytevectors as Strings
4509 @subsubsection Interpreting Bytevector Contents as Unicode Strings
4511 @cindex Unicode string encoding
4513 Bytevector contents can also be interpreted as Unicode strings encoded
4514 in one of the most commonly available encoding formats.
4517 (utf8->string (u8-list->bytevector '(99 97 102 101)))
4520 (string->utf8 "caf@'e") ;; SMALL LATIN LETTER E WITH ACUTE ACCENT
4521 @result{} #vu8(99 97 102 195 169)
4524 @deffn {Scheme Procedure} string->utf8 str
4525 @deffnx {Scheme Procedure} string->utf16 str [endianness]
4526 @deffnx {Scheme Procedure} string->utf32 str [endianness]
4527 @deffnx {C Function} scm_string_to_utf8 (str)
4528 @deffnx {C Function} scm_string_to_utf16 (str, endianness)
4529 @deffnx {C Function} scm_string_to_utf32 (str, endianness)
4530 Return a newly allocated bytevector that contains the UTF-8, UTF-16, or
4531 UTF-32 (aka. UCS-4) encoding of @var{str}. For UTF-16 and UTF-32,
4532 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4533 it defaults to big endian.
4536 @deffn {Scheme Procedure} utf8->string utf
4537 @deffnx {Scheme Procedure} utf16->string utf [endianness]
4538 @deffnx {Scheme Procedure} utf32->string utf [endianness]
4539 @deffnx {C Function} scm_utf8_to_string (utf)
4540 @deffnx {C Function} scm_utf16_to_string (utf, endianness)
4541 @deffnx {C Function} scm_utf32_to_string (utf, endianness)
4542 Return a newly allocated string that contains from the UTF-8-, UTF-16-,
4543 or UTF-32-decoded contents of bytevector @var{utf}. For UTF-16 and UTF-32,
4544 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4545 it defaults to big endian.
4548 @node Bytevectors as Generalized Vectors
4549 @subsubsection Accessing Bytevectors with the Generalized Vector API
4551 As an extension to the R6RS, Guile allows bytevectors to be manipulated
4552 with the @dfn{generalized vector} procedures (@pxref{Generalized
4553 Vectors}). This also allows bytevectors to be accessed using the
4554 generic @dfn{array} procedures (@pxref{Array Procedures}). When using
4555 these APIs, bytes are accessed one at a time as 8-bit unsigned integers:
4558 (define bv #vu8(0 1 2 3))
4560 (generalized-vector? bv)
4563 (generalized-vector-ref bv 2)
4566 (generalized-vector-set! bv 2 77)
4575 @node Bytevectors as Uniform Vectors
4576 @subsubsection Accessing Bytevectors with the SRFI-4 API
4578 Bytevectors may also be accessed with the SRFI-4 API. @xref{SRFI-4 and
4579 Bytevectors}, for more information.
4586 Symbols in Scheme are widely used in three ways: as items of discrete
4587 data, as lookup keys for alists and hash tables, and to denote variable
4590 A @dfn{symbol} is similar to a string in that it is defined by a
4591 sequence of characters. The sequence of characters is known as the
4592 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
4593 name doesn't include any characters that could be confused with other
4594 elements of Scheme syntax --- a symbol is written in a Scheme program by
4595 writing the sequence of characters that make up the name, @emph{without}
4596 any quotation marks or other special syntax. For example, the symbol
4597 whose name is ``multiply-by-2'' is written, simply:
4603 Notice how this differs from a @emph{string} with contents
4604 ``multiply-by-2'', which is written with double quotation marks, like
4611 Looking beyond how they are written, symbols are different from strings
4612 in two important respects.
4614 The first important difference is uniqueness. If the same-looking
4615 string is read twice from two different places in a program, the result
4616 is two @emph{different} string objects whose contents just happen to be
4617 the same. If, on the other hand, the same-looking symbol is read twice
4618 from two different places in a program, the result is the @emph{same}
4619 symbol object both times.
4621 Given two read symbols, you can use @code{eq?} to test whether they are
4622 the same (that is, have the same name). @code{eq?} is the most
4623 efficient comparison operator in Scheme, and comparing two symbols like
4624 this is as fast as comparing, for example, two numbers. Given two
4625 strings, on the other hand, you must use @code{equal?} or
4626 @code{string=?}, which are much slower comparison operators, to
4627 determine whether the strings have the same contents.
4630 (define sym1 (quote hello))
4631 (define sym2 (quote hello))
4632 (eq? sym1 sym2) @result{} #t
4634 (define str1 "hello")
4635 (define str2 "hello")
4636 (eq? str1 str2) @result{} #f
4637 (equal? str1 str2) @result{} #t
4640 The second important difference is that symbols, unlike strings, are not
4641 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
4642 example above: @code{(quote hello)} evaluates to the symbol named
4643 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
4644 symbol named "hello" and evaluated as a variable reference @dots{} about
4645 which more below (@pxref{Symbol Variables}).
4648 * Symbol Data:: Symbols as discrete data.
4649 * Symbol Keys:: Symbols as lookup keys.
4650 * Symbol Variables:: Symbols as denoting variables.
4651 * Symbol Primitives:: Operations related to symbols.
4652 * Symbol Props:: Function slots and property lists.
4653 * Symbol Read Syntax:: Extended read syntax for symbols.
4654 * Symbol Uninterned:: Uninterned symbols.
4659 @subsubsection Symbols as Discrete Data
4661 Numbers and symbols are similar to the extent that they both lend
4662 themselves to @code{eq?} comparison. But symbols are more descriptive
4663 than numbers, because a symbol's name can be used directly to describe
4664 the concept for which that symbol stands.
4666 For example, imagine that you need to represent some colours in a
4667 computer program. Using numbers, you would have to choose arbitrarily
4668 some mapping between numbers and colours, and then take care to use that
4669 mapping consistently:
4672 ;; 1=red, 2=green, 3=purple
4674 (if (eq? (colour-of car) 1)
4679 You can make the mapping more explicit and the code more readable by
4687 (if (eq? (colour-of car) red)
4692 But the simplest and clearest approach is not to use numbers at all, but
4693 symbols whose names specify the colours that they refer to:
4696 (if (eq? (colour-of car) 'red)
4700 The descriptive advantages of symbols over numbers increase as the set
4701 of concepts that you want to describe grows. Suppose that a car object
4702 can have other properties as well, such as whether it has or uses:
4706 automatic or manual transmission
4708 leaded or unleaded fuel
4710 power steering (or not).
4714 Then a car's combined property set could be naturally represented and
4715 manipulated as a list of symbols:
4718 (properties-of car1)
4720 (red manual unleaded power-steering)
4722 (if (memq 'power-steering (properties-of car1))
4723 (display "Unfit people can drive this car.\n")
4724 (display "You'll need strong arms to drive this car!\n"))
4726 Unfit people can drive this car.
4729 Remember, the fundamental property of symbols that we are relying on
4730 here is that an occurrence of @code{'red} in one part of a program is an
4731 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
4732 another part of a program; this means that symbols can usefully be
4733 compared using @code{eq?}. At the same time, symbols have naturally
4734 descriptive names. This combination of efficiency and descriptive power
4735 makes them ideal for use as discrete data.
4739 @subsubsection Symbols as Lookup Keys
4741 Given their efficiency and descriptive power, it is natural to use
4742 symbols as the keys in an association list or hash table.
4744 To illustrate this, consider a more structured representation of the car
4745 properties example from the preceding subsection. Rather than
4746 mixing all the properties up together in a flat list, we could use an
4747 association list like this:
4750 (define car1-properties '((colour . red)
4751 (transmission . manual)
4753 (steering . power-assisted)))
4756 Notice how this structure is more explicit and extensible than the flat
4757 list. For example it makes clear that @code{manual} refers to the
4758 transmission rather than, say, the windows or the locking of the car.
4759 It also allows further properties to use the same symbols among their
4760 possible values without becoming ambiguous:
4763 (define car1-properties '((colour . red)
4764 (transmission . manual)
4766 (steering . power-assisted)
4768 (locking . manual)))
4771 With a representation like this, it is easy to use the efficient
4772 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
4773 extract or change individual pieces of information:
4776 (assq-ref car1-properties 'fuel) @result{} unleaded
4777 (assq-ref car1-properties 'transmission) @result{} manual
4779 (assq-set! car1-properties 'seat-colour 'black)
4782 (transmission . manual)
4784 (steering . power-assisted)
4785 (seat-colour . black)
4786 (locking . manual)))
4789 Hash tables also have keys, and exactly the same arguments apply to the
4790 use of symbols in hash tables as in association lists. The hash value
4791 that Guile uses to decide where to add a symbol-keyed entry to a hash
4792 table can be obtained by calling the @code{symbol-hash} procedure:
4794 @deffn {Scheme Procedure} symbol-hash symbol
4795 @deffnx {C Function} scm_symbol_hash (symbol)
4796 Return a hash value for @var{symbol}.
4799 See @ref{Hash Tables} for information about hash tables in general, and
4800 for why you might choose to use a hash table rather than an association
4804 @node Symbol Variables
4805 @subsubsection Symbols as Denoting Variables
4807 When an unquoted symbol in a Scheme program is evaluated, it is
4808 interpreted as a variable reference, and the result of the evaluation is
4809 the appropriate variable's value.
4811 For example, when the expression @code{(string-length "abcd")} is read
4812 and evaluated, the sequence of characters @code{string-length} is read
4813 as the symbol whose name is "string-length". This symbol is associated
4814 with a variable whose value is the procedure that implements string
4815 length calculation. Therefore evaluation of the @code{string-length}
4816 symbol results in that procedure.
4818 The details of the connection between an unquoted symbol and the
4819 variable to which it refers are explained elsewhere. See @ref{Binding
4820 Constructs}, for how associations between symbols and variables are
4821 created, and @ref{Modules}, for how those associations are affected by
4822 Guile's module system.
4825 @node Symbol Primitives
4826 @subsubsection Operations Related to Symbols
4828 Given any Scheme value, you can determine whether it is a symbol using
4829 the @code{symbol?} primitive:
4832 @deffn {Scheme Procedure} symbol? obj
4833 @deffnx {C Function} scm_symbol_p (obj)
4834 Return @code{#t} if @var{obj} is a symbol, otherwise return
4838 @deftypefn {C Function} int scm_is_symbol (SCM val)
4839 Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
4842 Once you know that you have a symbol, you can obtain its name as a
4843 string by calling @code{symbol->string}. Note that Guile differs by
4844 default from R5RS on the details of @code{symbol->string} as regards
4847 @rnindex symbol->string
4848 @deffn {Scheme Procedure} symbol->string s
4849 @deffnx {C Function} scm_symbol_to_string (s)
4850 Return the name of symbol @var{s} as a string. By default, Guile reads
4851 symbols case-sensitively, so the string returned will have the same case
4852 variation as the sequence of characters that caused @var{s} to be
4855 If Guile is set to read symbols case-insensitively (as specified by
4856 R5RS), and @var{s} comes into being as part of a literal expression
4857 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
4858 by a call to the @code{read} or @code{string-ci->symbol} procedures,
4859 Guile converts any alphabetic characters in the symbol's name to
4860 lower case before creating the symbol object, so the string returned
4861 here will be in lower case.
4863 If @var{s} was created by @code{string->symbol}, the case of characters
4864 in the string returned will be the same as that in the string that was
4865 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
4866 setting at the time @var{s} was created.
4868 It is an error to apply mutation procedures like @code{string-set!} to
4869 strings returned by this procedure.
4872 Most symbols are created by writing them literally in code. However it
4873 is also possible to create symbols programmatically using the following
4876 @deffn {Scheme Procedure} symbol char@dots{}
4878 Return a newly allocated symbol made from the given character arguments.
4881 (symbol #\x #\y #\z) @result{} xyz
4885 @deffn {Scheme Procedure} list->symbol lst
4886 @rnindex list->symbol
4887 Return a newly allocated symbol made from a list of characters.
4890 (list->symbol '(#\a #\b #\c)) @result{} abc
4894 @rnindex symbol-append
4895 @deffn {Scheme Procedure} symbol-append . args
4896 Return a newly allocated symbol whose characters form the
4897 concatenation of the given symbols, @var{args}.
4901 (symbol-append h 'world))
4902 @result{} helloworld
4906 @rnindex string->symbol
4907 @deffn {Scheme Procedure} string->symbol string
4908 @deffnx {C Function} scm_string_to_symbol (string)
4909 Return the symbol whose name is @var{string}. This procedure can create
4910 symbols with names containing special characters or letters in the
4911 non-standard case, but it is usually a bad idea to create such symbols
4912 because in some implementations of Scheme they cannot be read as
4916 @deffn {Scheme Procedure} string-ci->symbol str
4917 @deffnx {C Function} scm_string_ci_to_symbol (str)
4918 Return the symbol whose name is @var{str}. If Guile is currently
4919 reading symbols case-insensitively, @var{str} is converted to lowercase
4920 before the returned symbol is looked up or created.
4923 The following examples illustrate Guile's detailed behaviour as regards
4924 the case-sensitivity of symbols:
4927 (read-enable 'case-insensitive) ; R5RS compliant behaviour
4929 (symbol->string 'flying-fish) @result{} "flying-fish"
4930 (symbol->string 'Martin) @result{} "martin"
4932 (string->symbol "Malvina")) @result{} "Malvina"
4934 (eq? 'mISSISSIppi 'mississippi) @result{} #t
4935 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4936 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
4938 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4939 (string=? "K. Harper, M.D."
4941 (string->symbol "K. Harper, M.D."))) @result{} #t
4943 (read-disable 'case-insensitive) ; Guile default behaviour
4945 (symbol->string 'flying-fish) @result{} "flying-fish"
4946 (symbol->string 'Martin) @result{} "Martin"
4948 (string->symbol "Malvina")) @result{} "Malvina"
4950 (eq? 'mISSISSIppi 'mississippi) @result{} #f
4951 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4952 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
4954 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4955 (string=? "K. Harper, M.D."
4957 (string->symbol "K. Harper, M.D."))) @result{} #t
4960 From C, there are lower level functions that construct a Scheme symbol
4961 from a C string in the current locale encoding.
4963 When you want to do more from C, you should convert between symbols
4964 and strings using @code{scm_symbol_to_string} and
4965 @code{scm_string_to_symbol} and work with the strings.
4967 @deffn {C Function} scm_from_locale_symbol (const char *name)
4968 @deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
4969 Construct and return a Scheme symbol whose name is specified by
4970 @var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
4971 terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
4972 specified explicitly by @var{len}.
4975 @deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
4976 @deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
4977 Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
4978 respectively, but also frees @var{str} with @code{free} eventually.
4979 Thus, you can use this function when you would free @var{str} anyway
4980 immediately after creating the Scheme string. In certain cases, Guile
4981 can then use @var{str} directly as its internal representation.
4984 The size of a symbol can also be obtained from C:
4986 @deftypefn {C Function} size_t scm_c_symbol_length (SCM sym)
4987 Return the number of characters in @var{sym}.
4990 Finally, some applications, especially those that generate new Scheme
4991 code dynamically, need to generate symbols for use in the generated
4992 code. The @code{gensym} primitive meets this need:
4994 @deffn {Scheme Procedure} gensym [prefix]
4995 @deffnx {C Function} scm_gensym (prefix)
4996 Create a new symbol with a name constructed from a prefix and a counter
4997 value. The string @var{prefix} can be specified as an optional
4998 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
4999 at each call. There is no provision for resetting the counter.
5002 The symbols generated by @code{gensym} are @emph{likely} to be unique,
5003 since their names begin with a space and it is only otherwise possible
5004 to generate such symbols if a programmer goes out of their way to do
5005 so. Uniqueness can be guaranteed by instead using uninterned symbols
5006 (@pxref{Symbol Uninterned}), though they can't be usefully written out
5011 @subsubsection Function Slots and Property Lists
5013 In traditional Lisp dialects, symbols are often understood as having
5014 three kinds of value at once:
5018 a @dfn{variable} value, which is used when the symbol appears in
5019 code in a variable reference context
5022 a @dfn{function} value, which is used when the symbol appears in
5023 code in a function name position (i.e. as the first element in an
5027 a @dfn{property list} value, which is used when the symbol is given as
5028 the first argument to Lisp's @code{put} or @code{get} functions.
5031 Although Scheme (as one of its simplifications with respect to Lisp)
5032 does away with the distinction between variable and function namespaces,
5033 Guile currently retains some elements of the traditional structure in
5034 case they turn out to be useful when implementing translators for other
5035 languages, in particular Emacs Lisp.
5037 Specifically, Guile symbols have two extra slots. for a symbol's
5038 property list, and for its ``function value.'' The following procedures
5039 are provided to access these slots.
5041 @deffn {Scheme Procedure} symbol-fref symbol
5042 @deffnx {C Function} scm_symbol_fref (symbol)
5043 Return the contents of @var{symbol}'s @dfn{function slot}.
5046 @deffn {Scheme Procedure} symbol-fset! symbol value
5047 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
5048 Set the contents of @var{symbol}'s function slot to @var{value}.
5051 @deffn {Scheme Procedure} symbol-pref symbol
5052 @deffnx {C Function} scm_symbol_pref (symbol)
5053 Return the @dfn{property list} currently associated with @var{symbol}.
5056 @deffn {Scheme Procedure} symbol-pset! symbol value
5057 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
5058 Set @var{symbol}'s property list to @var{value}.
5061 @deffn {Scheme Procedure} symbol-property sym prop
5062 From @var{sym}'s property list, return the value for property
5063 @var{prop}. The assumption is that @var{sym}'s property list is an
5064 association list whose keys are distinguished from each other using
5065 @code{equal?}; @var{prop} should be one of the keys in that list. If
5066 the property list has no entry for @var{prop}, @code{symbol-property}
5070 @deffn {Scheme Procedure} set-symbol-property! sym prop val
5071 In @var{sym}'s property list, set the value for property @var{prop} to
5072 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
5073 none already exists. For the structure of the property list, see
5074 @code{symbol-property}.
5077 @deffn {Scheme Procedure} symbol-property-remove! sym prop
5078 From @var{sym}'s property list, remove the entry for property
5079 @var{prop}, if there is one. For the structure of the property list,
5080 see @code{symbol-property}.
5083 Support for these extra slots may be removed in a future release, and it
5084 is probably better to avoid using them. For a more modern and Schemely
5085 approach to properties, see @ref{Object Properties}.
5088 @node Symbol Read Syntax
5089 @subsubsection Extended Read Syntax for Symbols
5091 The read syntax for a symbol is a sequence of letters, digits, and
5092 @dfn{extended alphabetic characters}, beginning with a character that
5093 cannot begin a number. In addition, the special cases of @code{+},
5094 @code{-}, and @code{...} are read as symbols even though numbers can
5095 begin with @code{+}, @code{-} or @code{.}.
5097 Extended alphabetic characters may be used within identifiers as if
5098 they were letters. The set of extended alphabetic characters is:
5101 ! $ % & * + - . / : < = > ? @@ ^ _ ~
5104 In addition to the standard read syntax defined above (which is taken
5105 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
5106 Scheme})), Guile provides an extended symbol read syntax that allows the
5107 inclusion of unusual characters such as space characters, newlines and
5108 parentheses. If (for whatever reason) you need to write a symbol
5109 containing characters not mentioned above, you can do so as follows.
5113 Begin the symbol with the characters @code{#@{},
5116 write the characters of the symbol and
5119 finish the symbol with the characters @code{@}#}.
5122 Here are a few examples of this form of read syntax. The first symbol
5123 needs to use extended syntax because it contains a space character, the
5124 second because it contains a line break, and the last because it looks
5136 Although Guile provides this extended read syntax for symbols,
5137 widespread usage of it is discouraged because it is not portable and not
5141 @node Symbol Uninterned
5142 @subsubsection Uninterned Symbols
5144 What makes symbols useful is that they are automatically kept unique.
5145 There are no two symbols that are distinct objects but have the same
5146 name. But of course, there is no rule without exception. In addition
5147 to the normal symbols that have been discussed up to now, you can also
5148 create special @dfn{uninterned} symbols that behave slightly
5151 To understand what is different about them and why they might be useful,
5152 we look at how normal symbols are actually kept unique.
5154 Whenever Guile wants to find the symbol with a specific name, for
5155 example during @code{read} or when executing @code{string->symbol}, it
5156 first looks into a table of all existing symbols to find out whether a
5157 symbol with the given name already exists. When this is the case, Guile
5158 just returns that symbol. When not, a new symbol with the name is
5159 created and entered into the table so that it can be found later.
5161 Sometimes you might want to create a symbol that is guaranteed `fresh',
5162 i.e. a symbol that did not exist previously. You might also want to
5163 somehow guarantee that no one else will ever unintentionally stumble
5164 across your symbol in the future. These properties of a symbol are
5165 often needed when generating code during macro expansion. When
5166 introducing new temporary variables, you want to guarantee that they
5167 don't conflict with variables in other people's code.
5169 The simplest way to arrange for this is to create a new symbol but
5170 not enter it into the global table of all symbols. That way, no one
5171 will ever get access to your symbol by chance. Symbols that are not in
5172 the table are called @dfn{uninterned}. Of course, symbols that
5173 @emph{are} in the table are called @dfn{interned}.
5175 You create new uninterned symbols with the function @code{make-symbol}.
5176 You can test whether a symbol is interned or not with
5177 @code{symbol-interned?}.
5179 Uninterned symbols break the rule that the name of a symbol uniquely
5180 identifies the symbol object. Because of this, they can not be written
5181 out and read back in like interned symbols. Currently, Guile has no
5182 support for reading uninterned symbols. Note that the function
5183 @code{gensym} does not return uninterned symbols for this reason.
5185 @deffn {Scheme Procedure} make-symbol name
5186 @deffnx {C Function} scm_make_symbol (name)
5187 Return a new uninterned symbol with the name @var{name}. The returned
5188 symbol is guaranteed to be unique and future calls to
5189 @code{string->symbol} will not return it.
5192 @deffn {Scheme Procedure} symbol-interned? symbol
5193 @deffnx {C Function} scm_symbol_interned_p (symbol)
5194 Return @code{#t} if @var{symbol} is interned, otherwise return
5201 (define foo-1 (string->symbol "foo"))
5202 (define foo-2 (string->symbol "foo"))
5203 (define foo-3 (make-symbol "foo"))
5204 (define foo-4 (make-symbol "foo"))
5208 ; Two interned symbols with the same name are the same object,
5212 ; but a call to make-symbol with the same name returns a
5217 ; A call to make-symbol always returns a new object, even for
5221 @result{} #<uninterned-symbol foo 8085290>
5222 ; Uninterned symbols print differently from interned symbols,
5226 ; but they are still symbols,
5228 (symbol-interned? foo-3)
5230 ; just not interned.
5235 @subsection Keywords
5238 Keywords are self-evaluating objects with a convenient read syntax that
5239 makes them easy to type.
5241 Guile's keyword support conforms to R5RS, and adds a (switchable) read
5242 syntax extension to permit keywords to begin with @code{:} as well as
5243 @code{#:}, or to end with @code{:}.
5246 * Why Use Keywords?:: Motivation for keyword usage.
5247 * Coding With Keywords:: How to use keywords.
5248 * Keyword Read Syntax:: Read syntax for keywords.
5249 * Keyword Procedures:: Procedures for dealing with keywords.
5252 @node Why Use Keywords?
5253 @subsubsection Why Use Keywords?
5255 Keywords are useful in contexts where a program or procedure wants to be
5256 able to accept a large number of optional arguments without making its
5257 interface unmanageable.
5259 To illustrate this, consider a hypothetical @code{make-window}
5260 procedure, which creates a new window on the screen for drawing into
5261 using some graphical toolkit. There are many parameters that the caller
5262 might like to specify, but which could also be sensibly defaulted, for
5267 color depth -- Default: the color depth for the screen
5270 background color -- Default: white
5273 width -- Default: 600
5276 height -- Default: 400
5279 If @code{make-window} did not use keywords, the caller would have to
5280 pass in a value for each possible argument, remembering the correct
5281 argument order and using a special value to indicate the default value
5285 (make-window 'default ;; Color depth
5286 'default ;; Background color
5289 @dots{}) ;; More make-window arguments
5292 With keywords, on the other hand, defaulted arguments are omitted, and
5293 non-default arguments are clearly tagged by the appropriate keyword. As
5294 a result, the invocation becomes much clearer:
5297 (make-window #:width 800 #:height 100)
5300 On the other hand, for a simpler procedure with few arguments, the use
5301 of keywords would be a hindrance rather than a help. The primitive
5302 procedure @code{cons}, for example, would not be improved if it had to
5306 (cons #:car x #:cdr y)
5309 So the decision whether to use keywords or not is purely pragmatic: use
5310 them if they will clarify the procedure invocation at point of call.
5312 @node Coding With Keywords
5313 @subsubsection Coding With Keywords
5315 If a procedure wants to support keywords, it should take a rest argument
5316 and then use whatever means is convenient to extract keywords and their
5317 corresponding arguments from the contents of that rest argument.
5319 The following example illustrates the principle: the code for
5320 @code{make-window} uses a helper procedure called
5321 @code{get-keyword-value} to extract individual keyword arguments from
5325 (define (get-keyword-value args keyword default)
5326 (let ((kv (memq keyword args)))
5327 (if (and kv (>= (length kv) 2))
5331 (define (make-window . args)
5332 (let ((depth (get-keyword-value args #:depth screen-depth))
5333 (bg (get-keyword-value args #:bg "white"))
5334 (width (get-keyword-value args #:width 800))
5335 (height (get-keyword-value args #:height 100))
5340 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
5341 optargs)} module provides a set of powerful macros that you can use to
5342 implement keyword-supporting procedures like this:
5345 (use-modules (ice-9 optargs))
5347 (define (make-window . args)
5348 (let-keywords args #f ((depth screen-depth)
5356 Or, even more economically, like this:
5359 (use-modules (ice-9 optargs))
5361 (define* (make-window #:key (depth screen-depth)
5368 For further details on @code{let-keywords}, @code{define*} and other
5369 facilities provided by the @code{(ice-9 optargs)} module, see
5370 @ref{Optional Arguments}.
5373 @node Keyword Read Syntax
5374 @subsubsection Keyword Read Syntax
5376 Guile, by default, only recognizes a keyword syntax that is compatible
5377 with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
5378 same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
5379 external representation of the keyword named @code{NAME}. Keyword
5380 objects print using this syntax as well, so values containing keyword
5381 objects can be read back into Guile. When used in an expression,
5382 keywords are self-quoting objects.
5384 If the @code{keyword} read option is set to @code{'prefix}, Guile also
5385 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
5386 of the form @code{:NAME} are read as symbols, as required by R5RS.
5388 @cindex SRFI-88 keyword syntax
5390 If the @code{keyword} read option is set to @code{'postfix}, Guile
5391 recognizes the SRFI-88 read syntax @code{NAME:} (@pxref{SRFI-88}).
5392 Otherwise, tokens of this form are read as symbols.
5394 To enable and disable the alternative non-R5RS keyword syntax, you use
5395 the @code{read-set!} procedure documented @ref{Scheme Read}. Note that
5396 the @code{prefix} and @code{postfix} syntax are mutually exclusive.
5399 (read-set! keywords 'prefix)
5409 (read-set! keywords 'postfix)
5419 (read-set! keywords #f)
5427 ERROR: In expression :type:
5428 ERROR: Unbound variable: :type
5429 ABORT: (unbound-variable)
5432 @node Keyword Procedures
5433 @subsubsection Keyword Procedures
5435 @deffn {Scheme Procedure} keyword? obj
5436 @deffnx {C Function} scm_keyword_p (obj)
5437 Return @code{#t} if the argument @var{obj} is a keyword, else
5441 @deffn {Scheme Procedure} keyword->symbol keyword
5442 @deffnx {C Function} scm_keyword_to_symbol (keyword)
5443 Return the symbol with the same name as @var{keyword}.
5446 @deffn {Scheme Procedure} symbol->keyword symbol
5447 @deffnx {C Function} scm_symbol_to_keyword (symbol)
5448 Return the keyword with the same name as @var{symbol}.
5451 @deftypefn {C Function} int scm_is_keyword (SCM obj)
5452 Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
5455 @deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5456 @deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5457 Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5458 (@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5459 (@var{str}, @var{len}))}, respectively.
5463 @subsection ``Functionality-Centric'' Data Types
5465 Procedures and macros are documented in their own sections: see
5466 @ref{Procedures} and @ref{Macros}.
5468 Variable objects are documented as part of the description of Guile's
5469 module system: see @ref{Variables}.
5471 Asyncs, dynamic roots and fluids are described in the section on
5472 scheduling: see @ref{Scheduling}.
5474 Hooks are documented in the section on general utility functions: see
5477 Ports are described in the section on I/O: see @ref{Input and Output}.
5479 Regular expressions are described in their own section: see @ref{Regular
5483 @c TeX-master: "guile.texi"