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
554 @deffn {Scheme Procedure} real? obj
555 @deffnx {C Function} scm_real_p (obj)
556 Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
557 that the sets of integer and rational values form subsets of the set
558 of real numbers, so the predicate will also be fulfilled if @var{obj}
559 is an integer number or a rational number.
562 @deffn {Scheme Procedure} rational? x
563 @deffnx {C Function} scm_rational_p (x)
564 Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
565 Note that the set of integer values forms a subset of the set of
566 rational numbers, i. e. the predicate will also be fulfilled if
567 @var{x} is an integer number.
569 Since Guile can not represent irrational numbers, every number
570 satisfying @code{real?} also satisfies @code{rational?} in Guile.
573 @deffn {Scheme Procedure} rationalize x eps
574 @deffnx {C Function} scm_rationalize (x, eps)
575 Returns the @emph{simplest} rational number differing
576 from @var{x} by no more than @var{eps}.
578 As required by @acronym{R5RS}, @code{rationalize} only returns an
579 exact result when both its arguments are exact. Thus, you might need
580 to use @code{inexact->exact} on the arguments.
583 (rationalize (inexact->exact 1.2) 1/100)
589 @deffn {Scheme Procedure} inf? x
590 @deffnx {C Function} scm_inf_p (x)
591 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
595 @deffn {Scheme Procedure} nan? x
596 @deffnx {C Function} scm_nan_p (x)
597 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
600 @deffn {Scheme Procedure} nan
601 @deffnx {C Function} scm_nan ()
605 @deffn {Scheme Procedure} inf
606 @deffnx {C Function} scm_inf ()
610 @deffn {Scheme Procedure} numerator x
611 @deffnx {C Function} scm_numerator (x)
612 Return the numerator of the rational number @var{x}.
615 @deffn {Scheme Procedure} denominator x
616 @deffnx {C Function} scm_denominator (x)
617 Return the denominator of the rational number @var{x}.
620 @deftypefn {C Function} int scm_is_real (SCM val)
621 @deftypefnx {C Function} int scm_is_rational (SCM val)
622 Equivalent to @code{scm_is_true (scm_real_p (val))} and
623 @code{scm_is_true (scm_rational_p (val))}, respectively.
626 @deftypefn {C Function} double scm_to_double (SCM val)
627 Returns the number closest to @var{val} that is representable as a
628 @code{double}. Returns infinity for a @var{val} that is too large in
629 magnitude. The argument @var{val} must be a real number.
632 @deftypefn {C Function} SCM scm_from_double (double val)
633 Return the @code{SCM} value that represents @var{val}. The returned
634 value is inexact according to the predicate @code{inexact?}, but it
635 will be exactly equal to @var{val}.
638 @node Complex Numbers
639 @subsubsection Complex Numbers
640 @tpindex Complex numbers
644 Complex numbers are the set of numbers that describe all possible points
645 in a two-dimensional space. The two coordinates of a particular point
646 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
647 the complex number that describes that point.
649 In Guile, complex numbers are written in rectangular form as the sum of
650 their real and imaginary parts, using the symbol @code{i} to indicate
665 Polar form can also be used, with an @samp{@@} between magnitude and
669 1@@3.141592 @result{} -1.0 (approx)
670 -1@@1.57079 @result{} 0.0-1.0i (approx)
673 Guile represents a complex number with a non-zero imaginary part as a
674 pair of inexact rationals, so the real and imaginary parts of a
675 complex number have the same properties of inexactness and limited
676 precision as single inexact rational numbers. Guile can not represent
677 exact complex numbers with non-zero imaginary parts.
679 @deffn {Scheme Procedure} complex? z
680 @deffnx {C Function} scm_complex_p (z)
681 Return @code{#t} if @var{x} is a complex number, @code{#f}
682 otherwise. Note that the sets of real, rational and integer
683 values form subsets of the set of complex numbers, i. e. the
684 predicate will also be fulfilled if @var{x} is a real,
685 rational or integer number.
688 @deftypefn {C Function} int scm_is_complex (SCM val)
689 Equivalent to @code{scm_is_true (scm_complex_p (val))}.
693 @subsubsection Exact and Inexact Numbers
694 @tpindex Exact numbers
695 @tpindex Inexact numbers
699 @rnindex exact->inexact
700 @rnindex inexact->exact
702 R5RS requires that a calculation involving inexact numbers always
703 produces an inexact result. To meet this requirement, Guile
704 distinguishes between an exact integer value such as @samp{5} and the
705 corresponding inexact real value which, to the limited precision
706 available, has no fractional part, and is printed as @samp{5.0}. Guile
707 will only convert the latter value to the former when forced to do so by
708 an invocation of the @code{inexact->exact} procedure.
710 @deffn {Scheme Procedure} exact? z
711 @deffnx {C Function} scm_exact_p (z)
712 Return @code{#t} if the number @var{z} is exact, @code{#f}
728 @deffn {Scheme Procedure} inexact? z
729 @deffnx {C Function} scm_inexact_p (z)
730 Return @code{#t} if the number @var{z} is inexact, @code{#f}
734 @deffn {Scheme Procedure} inexact->exact z
735 @deffnx {C Function} scm_inexact_to_exact (z)
736 Return an exact number that is numerically closest to @var{z}, when
737 there is one. For inexact rationals, Guile returns the exact rational
738 that is numerically equal to the inexact rational. Inexact complex
739 numbers with a non-zero imaginary part can not be made exact.
746 The following happens because 12/10 is not exactly representable as a
747 @code{double} (on most platforms). However, when reading a decimal
748 number that has been marked exact with the ``#e'' prefix, Guile is
749 able to represent it correctly.
753 @result{} 5404319552844595/4503599627370496
761 @c begin (texi-doc-string "guile" "exact->inexact")
762 @deffn {Scheme Procedure} exact->inexact z
763 @deffnx {C Function} scm_exact_to_inexact (z)
764 Convert the number @var{z} to its inexact representation.
769 @subsubsection Read Syntax for Numerical Data
771 The read syntax for integers is a string of digits, optionally
772 preceded by a minus or plus character, a code indicating the
773 base in which the integer is encoded, and a code indicating whether
774 the number is exact or inexact. The supported base codes are:
779 the integer is written in binary (base 2)
783 the integer is written in octal (base 8)
787 the integer is written in decimal (base 10)
791 the integer is written in hexadecimal (base 16)
794 If the base code is omitted, the integer is assumed to be decimal. The
795 following examples show how these base codes are used.
814 The codes for indicating exactness (which can, incidentally, be applied
815 to all numerical values) are:
824 the number is inexact.
827 If the exactness indicator is omitted, the number is exact unless it
828 contains a radix point. Since Guile can not represent exact complex
829 numbers, an error is signalled when asking for them.
839 ERROR: Wrong type argument
842 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
843 plus and minus infinity, respectively. The value must be written
844 exactly as shown, that is, they always must have a sign and exactly
845 one zero digit after the decimal point. It also understands
846 @samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
847 The sign is ignored for `not-a-number' and the value is always printed
850 @node Integer Operations
851 @subsubsection Operations on Integer Values
860 @deffn {Scheme Procedure} odd? n
861 @deffnx {C Function} scm_odd_p (n)
862 Return @code{#t} if @var{n} is an odd number, @code{#f}
866 @deffn {Scheme Procedure} even? n
867 @deffnx {C Function} scm_even_p (n)
868 Return @code{#t} if @var{n} is an even number, @code{#f}
872 @c begin (texi-doc-string "guile" "quotient")
873 @c begin (texi-doc-string "guile" "remainder")
874 @deffn {Scheme Procedure} quotient n d
875 @deffnx {Scheme Procedure} remainder n d
876 @deffnx {C Function} scm_quotient (n, d)
877 @deffnx {C Function} scm_remainder (n, d)
878 Return the quotient or remainder from @var{n} divided by @var{d}. The
879 quotient is rounded towards zero, and the remainder will have the same
880 sign as @var{n}. In all cases quotient and remainder satisfy
881 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
884 (remainder 13 4) @result{} 1
885 (remainder -13 4) @result{} -1
889 @c begin (texi-doc-string "guile" "modulo")
890 @deffn {Scheme Procedure} modulo n d
891 @deffnx {C Function} scm_modulo (n, d)
892 Return the remainder from @var{n} divided by @var{d}, with the same
896 (modulo 13 4) @result{} 1
897 (modulo -13 4) @result{} 3
898 (modulo 13 -4) @result{} -3
899 (modulo -13 -4) @result{} -1
903 @c begin (texi-doc-string "guile" "gcd")
904 @deffn {Scheme Procedure} gcd x@dots{}
905 @deffnx {C Function} scm_gcd (x, y)
906 Return the greatest common divisor of all arguments.
907 If called without arguments, 0 is returned.
909 The C function @code{scm_gcd} always takes two arguments, while the
910 Scheme function can take an arbitrary number.
913 @c begin (texi-doc-string "guile" "lcm")
914 @deffn {Scheme Procedure} lcm x@dots{}
915 @deffnx {C Function} scm_lcm (x, y)
916 Return the least common multiple of the arguments.
917 If called without arguments, 1 is returned.
919 The C function @code{scm_lcm} always takes two arguments, while the
920 Scheme function can take an arbitrary number.
923 @deffn {Scheme Procedure} modulo-expt n k m
924 @deffnx {C Function} scm_modulo_expt (n, k, m)
925 Return @var{n} raised to the integer exponent
926 @var{k}, modulo @var{m}.
935 @subsubsection Comparison Predicates
940 The C comparison functions below always takes two arguments, while the
941 Scheme functions can take an arbitrary number. Also keep in mind that
942 the C functions return one of the Scheme boolean values
943 @code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
944 is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
945 y))} when testing the two Scheme numbers @code{x} and @code{y} for
946 equality, for example.
948 @c begin (texi-doc-string "guile" "=")
949 @deffn {Scheme Procedure} =
950 @deffnx {C Function} scm_num_eq_p (x, y)
951 Return @code{#t} if all parameters are numerically equal.
954 @c begin (texi-doc-string "guile" "<")
955 @deffn {Scheme Procedure} <
956 @deffnx {C Function} scm_less_p (x, y)
957 Return @code{#t} if the list of parameters is monotonically
961 @c begin (texi-doc-string "guile" ">")
962 @deffn {Scheme Procedure} >
963 @deffnx {C Function} scm_gr_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_leq_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_geq_p (x, y)
978 Return @code{#t} if the list of parameters is monotonically
982 @c begin (texi-doc-string "guile" "zero?")
983 @deffn {Scheme Procedure} zero? z
984 @deffnx {C Function} scm_zero_p (z)
985 Return @code{#t} if @var{z} is an exact or inexact number equal to
989 @c begin (texi-doc-string "guile" "positive?")
990 @deffn {Scheme Procedure} positive? x
991 @deffnx {C Function} scm_positive_p (x)
992 Return @code{#t} if @var{x} is an exact or inexact number greater than
996 @c begin (texi-doc-string "guile" "negative?")
997 @deffn {Scheme Procedure} negative? x
998 @deffnx {C Function} scm_negative_p (x)
999 Return @code{#t} if @var{x} is an exact or inexact number less than
1005 @subsubsection Converting Numbers To and From Strings
1006 @rnindex number->string
1007 @rnindex string->number
1009 The following procedures read and write numbers according to their
1010 external representation as defined by R5RS (@pxref{Lexical structure,
1011 R5RS Lexical Structure,, r5rs, The Revised^5 Report on the Algorithmic
1012 Language Scheme}). @xref{Number Input and Output, the @code{(ice-9
1013 i18n)} module}, for locale-dependent number parsing.
1015 @deffn {Scheme Procedure} number->string n [radix]
1016 @deffnx {C Function} scm_number_to_string (n, radix)
1017 Return a string holding the external representation of the
1018 number @var{n} in the given @var{radix}. If @var{n} is
1019 inexact, a radix of 10 will be used.
1022 @deffn {Scheme Procedure} string->number string [radix]
1023 @deffnx {C Function} scm_string_to_number (string, radix)
1024 Return a number of the maximally precise representation
1025 expressed by the given @var{string}. @var{radix} must be an
1026 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
1027 is a default radix that may be overridden by an explicit radix
1028 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1029 supplied, then the default radix is 10. If string is not a
1030 syntactically valid notation for a number, then
1031 @code{string->number} returns @code{#f}.
1034 @deftypefn {C Function} SCM scm_c_locale_stringn_to_number (const char *string, size_t len, unsigned radix)
1035 As per @code{string->number} above, but taking a C string, as pointer
1036 and length. The string characters should be in the current locale
1037 encoding (@code{locale} in the name refers only to that, there's no
1038 locale-dependent parsing).
1043 @subsubsection Complex Number Operations
1044 @rnindex make-rectangular
1051 @deffn {Scheme Procedure} make-rectangular real_part imaginary_part
1052 @deffnx {C Function} scm_make_rectangular (real_part, imaginary_part)
1053 Return a complex number constructed of the given @var{real-part} and @var{imaginary-part} parts.
1056 @deffn {Scheme Procedure} make-polar x y
1057 @deffnx {C Function} scm_make_polar (x, y)
1059 Return the complex number @var{x} * e^(i * @var{y}).
1062 @c begin (texi-doc-string "guile" "real-part")
1063 @deffn {Scheme Procedure} real-part z
1064 @deffnx {C Function} scm_real_part (z)
1065 Return the real part of the number @var{z}.
1068 @c begin (texi-doc-string "guile" "imag-part")
1069 @deffn {Scheme Procedure} imag-part z
1070 @deffnx {C Function} scm_imag_part (z)
1071 Return the imaginary part of the number @var{z}.
1074 @c begin (texi-doc-string "guile" "magnitude")
1075 @deffn {Scheme Procedure} magnitude z
1076 @deffnx {C Function} scm_magnitude (z)
1077 Return the magnitude of the number @var{z}. This is the same as
1078 @code{abs} for real arguments, but also allows complex numbers.
1081 @c begin (texi-doc-string "guile" "angle")
1082 @deffn {Scheme Procedure} angle z
1083 @deffnx {C Function} scm_angle (z)
1084 Return the angle of the complex number @var{z}.
1087 @deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1088 @deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1089 Like @code{scm_make_rectangular} or @code{scm_make_polar},
1090 respectively, but these functions take @code{double}s as their
1094 @deftypefn {C Function} double scm_c_real_part (z)
1095 @deftypefnx {C Function} double scm_c_imag_part (z)
1096 Returns the real or imaginary part of @var{z} as a @code{double}.
1099 @deftypefn {C Function} double scm_c_magnitude (z)
1100 @deftypefnx {C Function} double scm_c_angle (z)
1101 Returns the magnitude or angle of @var{z} as a @code{double}.
1106 @subsubsection Arithmetic Functions
1121 The C arithmetic functions below always takes two arguments, while the
1122 Scheme functions can take an arbitrary number. When you need to
1123 invoke them with just one argument, for example to compute the
1124 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1125 one: @code{scm_difference (x, SCM_UNDEFINED)}.
1127 @c begin (texi-doc-string "guile" "+")
1128 @deffn {Scheme Procedure} + z1 @dots{}
1129 @deffnx {C Function} scm_sum (z1, z2)
1130 Return the sum of all parameter values. Return 0 if called without any
1134 @c begin (texi-doc-string "guile" "-")
1135 @deffn {Scheme Procedure} - z1 z2 @dots{}
1136 @deffnx {C Function} scm_difference (z1, z2)
1137 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1138 the sum of all but the first argument are subtracted from the first
1142 @c begin (texi-doc-string "guile" "*")
1143 @deffn {Scheme Procedure} * z1 @dots{}
1144 @deffnx {C Function} scm_product (z1, z2)
1145 Return the product of all arguments. If called without arguments, 1 is
1149 @c begin (texi-doc-string "guile" "/")
1150 @deffn {Scheme Procedure} / z1 z2 @dots{}
1151 @deffnx {C Function} scm_divide (z1, z2)
1152 Divide the first argument by the product of the remaining arguments. If
1153 called with one argument @var{z1}, 1/@var{z1} is returned.
1156 @deffn {Scheme Procedure} 1+ z
1157 @deffnx {C Function} scm_oneplus (z)
1158 Return @math{@var{z} + 1}.
1161 @deffn {Scheme Procedure} 1- z
1162 @deffnx {C function} scm_oneminus (z)
1163 Return @math{@var{z} - 1}.
1166 @c begin (texi-doc-string "guile" "abs")
1167 @deffn {Scheme Procedure} abs x
1168 @deffnx {C Function} scm_abs (x)
1169 Return the absolute value of @var{x}.
1171 @var{x} must be a number with zero imaginary part. To calculate the
1172 magnitude of a complex number, use @code{magnitude} instead.
1175 @c begin (texi-doc-string "guile" "max")
1176 @deffn {Scheme Procedure} max x1 x2 @dots{}
1177 @deffnx {C Function} scm_max (x1, x2)
1178 Return the maximum of all parameter values.
1181 @c begin (texi-doc-string "guile" "min")
1182 @deffn {Scheme Procedure} min x1 x2 @dots{}
1183 @deffnx {C Function} scm_min (x1, x2)
1184 Return the minimum of all parameter values.
1187 @c begin (texi-doc-string "guile" "truncate")
1188 @deffn {Scheme Procedure} truncate x
1189 @deffnx {C Function} scm_truncate_number (x)
1190 Round the inexact number @var{x} towards zero.
1193 @c begin (texi-doc-string "guile" "round")
1194 @deffn {Scheme Procedure} round x
1195 @deffnx {C Function} scm_round_number (x)
1196 Round the inexact number @var{x} to the nearest integer. When exactly
1197 halfway between two integers, round to the even one.
1200 @c begin (texi-doc-string "guile" "floor")
1201 @deffn {Scheme Procedure} floor x
1202 @deffnx {C Function} scm_floor (x)
1203 Round the number @var{x} towards minus infinity.
1206 @c begin (texi-doc-string "guile" "ceiling")
1207 @deffn {Scheme Procedure} ceiling x
1208 @deffnx {C Function} scm_ceiling (x)
1209 Round the number @var{x} towards infinity.
1212 @deftypefn {C Function} double scm_c_truncate (double x)
1213 @deftypefnx {C Function} double scm_c_round (double x)
1214 Like @code{scm_truncate_number} or @code{scm_round_number},
1215 respectively, but these functions take and return @code{double}
1220 @subsubsection Scientific Functions
1222 The following procedures accept any kind of number as arguments,
1223 including complex numbers.
1226 @c begin (texi-doc-string "guile" "sqrt")
1227 @deffn {Scheme Procedure} sqrt z
1228 Return the square root of @var{z}. Of the two possible roots
1229 (positive and negative), the one with the a positive real part is
1230 returned, or if that's zero then a positive imaginary part. Thus,
1233 (sqrt 9.0) @result{} 3.0
1234 (sqrt -9.0) @result{} 0.0+3.0i
1235 (sqrt 1.0+1.0i) @result{} 1.09868411346781+0.455089860562227i
1236 (sqrt -1.0-1.0i) @result{} 0.455089860562227-1.09868411346781i
1241 @c begin (texi-doc-string "guile" "expt")
1242 @deffn {Scheme Procedure} expt z1 z2
1243 Return @var{z1} raised to the power of @var{z2}.
1247 @c begin (texi-doc-string "guile" "sin")
1248 @deffn {Scheme Procedure} sin z
1249 Return the sine of @var{z}.
1253 @c begin (texi-doc-string "guile" "cos")
1254 @deffn {Scheme Procedure} cos z
1255 Return the cosine of @var{z}.
1259 @c begin (texi-doc-string "guile" "tan")
1260 @deffn {Scheme Procedure} tan z
1261 Return the tangent of @var{z}.
1265 @c begin (texi-doc-string "guile" "asin")
1266 @deffn {Scheme Procedure} asin z
1267 Return the arcsine of @var{z}.
1271 @c begin (texi-doc-string "guile" "acos")
1272 @deffn {Scheme Procedure} acos z
1273 Return the arccosine of @var{z}.
1277 @c begin (texi-doc-string "guile" "atan")
1278 @deffn {Scheme Procedure} atan z
1279 @deffnx {Scheme Procedure} atan y x
1280 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1284 @c begin (texi-doc-string "guile" "exp")
1285 @deffn {Scheme Procedure} exp z
1286 Return e to the power of @var{z}, where e is the base of natural
1287 logarithms (2.71828@dots{}).
1291 @c begin (texi-doc-string "guile" "log")
1292 @deffn {Scheme Procedure} log z
1293 Return the natural logarithm of @var{z}.
1296 @c begin (texi-doc-string "guile" "log10")
1297 @deffn {Scheme Procedure} log10 z
1298 Return the base 10 logarithm of @var{z}.
1301 @c begin (texi-doc-string "guile" "sinh")
1302 @deffn {Scheme Procedure} sinh z
1303 Return the hyperbolic sine of @var{z}.
1306 @c begin (texi-doc-string "guile" "cosh")
1307 @deffn {Scheme Procedure} cosh z
1308 Return the hyperbolic cosine of @var{z}.
1311 @c begin (texi-doc-string "guile" "tanh")
1312 @deffn {Scheme Procedure} tanh z
1313 Return the hyperbolic tangent of @var{z}.
1316 @c begin (texi-doc-string "guile" "asinh")
1317 @deffn {Scheme Procedure} asinh z
1318 Return the hyperbolic arcsine of @var{z}.
1321 @c begin (texi-doc-string "guile" "acosh")
1322 @deffn {Scheme Procedure} acosh z
1323 Return the hyperbolic arccosine of @var{z}.
1326 @c begin (texi-doc-string "guile" "atanh")
1327 @deffn {Scheme Procedure} atanh z
1328 Return the hyperbolic arctangent of @var{z}.
1332 @node Bitwise Operations
1333 @subsubsection Bitwise Operations
1335 For the following bitwise functions, negative numbers are treated as
1336 infinite precision twos-complements. For instance @math{-6} is bits
1337 @math{@dots{}111010}, with infinitely many ones on the left. It can
1338 be seen that adding 6 (binary 110) to such a bit pattern gives all
1341 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1342 @deffnx {C Function} scm_logand (n1, n2)
1343 Return the bitwise @sc{and} of the integer arguments.
1346 (logand) @result{} -1
1347 (logand 7) @result{} 7
1348 (logand #b111 #b011 #b001) @result{} 1
1352 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1353 @deffnx {C Function} scm_logior (n1, n2)
1354 Return the bitwise @sc{or} of the integer arguments.
1357 (logior) @result{} 0
1358 (logior 7) @result{} 7
1359 (logior #b000 #b001 #b011) @result{} 3
1363 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1364 @deffnx {C Function} scm_loxor (n1, n2)
1365 Return the bitwise @sc{xor} of the integer arguments. A bit is
1366 set in the result if it is set in an odd number of arguments.
1369 (logxor) @result{} 0
1370 (logxor 7) @result{} 7
1371 (logxor #b000 #b001 #b011) @result{} 2
1372 (logxor #b000 #b001 #b011 #b011) @result{} 1
1376 @deffn {Scheme Procedure} lognot n
1377 @deffnx {C Function} scm_lognot (n)
1378 Return the integer which is the ones-complement of the integer
1379 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1382 (number->string (lognot #b10000000) 2)
1383 @result{} "-10000001"
1384 (number->string (lognot #b0) 2)
1389 @deffn {Scheme Procedure} logtest j k
1390 @deffnx {C Function} scm_logtest (j, k)
1391 Test whether @var{j} and @var{k} have any 1 bits in common. This is
1392 equivalent to @code{(not (zero? (logand j k)))}, but without actually
1393 calculating the @code{logand}, just testing for non-zero.
1396 (logtest #b0100 #b1011) @result{} #f
1397 (logtest #b0100 #b0111) @result{} #t
1401 @deffn {Scheme Procedure} logbit? index j
1402 @deffnx {C Function} scm_logbit_p (index, j)
1403 Test whether bit number @var{index} in @var{j} is set. @var{index}
1404 starts from 0 for the least significant bit.
1407 (logbit? 0 #b1101) @result{} #t
1408 (logbit? 1 #b1101) @result{} #f
1409 (logbit? 2 #b1101) @result{} #t
1410 (logbit? 3 #b1101) @result{} #t
1411 (logbit? 4 #b1101) @result{} #f
1415 @deffn {Scheme Procedure} ash n cnt
1416 @deffnx {C Function} scm_ash (n, cnt)
1417 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1418 @var{cnt} is negative. This is an ``arithmetic'' shift.
1420 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1421 when @var{cnt} is negative it's a division, rounded towards negative
1422 infinity. (Note that this is not the same rounding as @code{quotient}
1425 With @var{n} viewed as an infinite precision twos complement,
1426 @code{ash} means a left shift introducing zero bits, or a right shift
1430 (number->string (ash #b1 3) 2) @result{} "1000"
1431 (number->string (ash #b1010 -1) 2) @result{} "101"
1433 ;; -23 is bits ...11101001, -6 is bits ...111010
1434 (ash -23 -2) @result{} -6
1438 @deffn {Scheme Procedure} logcount n
1439 @deffnx {C Function} scm_logcount (n)
1440 Return the number of bits in integer @var{n}. If @var{n} is
1441 positive, the 1-bits in its binary representation are counted.
1442 If negative, the 0-bits in its two's-complement binary
1443 representation are counted. If zero, 0 is returned.
1446 (logcount #b10101010)
1455 @deffn {Scheme Procedure} integer-length n
1456 @deffnx {C Function} scm_integer_length (n)
1457 Return the number of bits necessary to represent @var{n}.
1459 For positive @var{n} this is how many bits to the most significant one
1460 bit. For negative @var{n} it's how many bits to the most significant
1461 zero bit in twos complement form.
1464 (integer-length #b10101010) @result{} 8
1465 (integer-length #b1111) @result{} 4
1466 (integer-length 0) @result{} 0
1467 (integer-length -1) @result{} 0
1468 (integer-length -256) @result{} 8
1469 (integer-length -257) @result{} 9
1473 @deffn {Scheme Procedure} integer-expt n k
1474 @deffnx {C Function} scm_integer_expt (n, k)
1475 Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1476 integer, @var{n} can be any number.
1478 Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1479 in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1483 (integer-expt 2 5) @result{} 32
1484 (integer-expt -3 3) @result{} -27
1485 (integer-expt 5 -3) @result{} 1/125
1486 (integer-expt 0 0) @result{} 1
1490 @deffn {Scheme Procedure} bit-extract n start end
1491 @deffnx {C Function} scm_bit_extract (n, start, end)
1492 Return the integer composed of the @var{start} (inclusive)
1493 through @var{end} (exclusive) bits of @var{n}. The
1494 @var{start}th bit becomes the 0-th bit in the result.
1497 (number->string (bit-extract #b1101101010 0 4) 2)
1499 (number->string (bit-extract #b1101101010 4 9) 2)
1506 @subsubsection Random Number Generation
1508 Pseudo-random numbers are generated from a random state object, which
1509 can be created with @code{seed->random-state} or
1510 @code{datum->random-state}. An external representation (i.e. one
1511 which can written with @code{write} and read with @code{read}) of a
1512 random state object can be obtained via
1513 @code{random-state->datum}. The @var{state} parameter to the
1514 various functions below is optional, it defaults to the state object
1515 in the @code{*random-state*} variable.
1517 @deffn {Scheme Procedure} copy-random-state [state]
1518 @deffnx {C Function} scm_copy_random_state (state)
1519 Return a copy of the random state @var{state}.
1522 @deffn {Scheme Procedure} random n [state]
1523 @deffnx {C Function} scm_random (n, state)
1524 Return a number in [0, @var{n}).
1526 Accepts a positive integer or real n and returns a
1527 number of the same type between zero (inclusive) and
1528 @var{n} (exclusive). The values returned have a uniform
1532 @deffn {Scheme Procedure} random:exp [state]
1533 @deffnx {C Function} scm_random_exp (state)
1534 Return an inexact real in an exponential distribution with mean
1535 1. For an exponential distribution with mean @var{u} use @code{(*
1536 @var{u} (random:exp))}.
1539 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1540 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1541 Fills @var{vect} with inexact real random numbers the sum of whose
1542 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1543 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1544 the coordinates are uniformly distributed over the surface of the unit
1548 @deffn {Scheme Procedure} random:normal [state]
1549 @deffnx {C Function} scm_random_normal (state)
1550 Return an inexact real in a normal distribution. The distribution
1551 used has mean 0 and standard deviation 1. For a normal distribution
1552 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1553 (* @var{d} (random:normal)))}.
1556 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1557 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1558 Fills @var{vect} with inexact real random numbers that are
1559 independent and standard normally distributed
1560 (i.e., with mean 0 and variance 1).
1563 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1564 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1565 Fills @var{vect} with inexact real random numbers the sum of whose
1566 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1567 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1568 the coordinates are uniformly distributed within the unit
1570 @c FIXME: What does this mean, particularly the n-sphere part?
1573 @deffn {Scheme Procedure} random:uniform [state]
1574 @deffnx {C Function} scm_random_uniform (state)
1575 Return a uniformly distributed inexact real random number in
1579 @deffn {Scheme Procedure} seed->random-state seed
1580 @deffnx {C Function} scm_seed_to_random_state (seed)
1581 Return a new random state using @var{seed}.
1584 @deffn {Scheme Procedure} datum->random-state datum
1585 @deffnx {C Function} scm_datum_to_random_state (datum)
1586 Return a new random state from @var{datum}, which should have been
1587 obtained by @code{random-state->datum}.
1590 @deffn {Scheme Procedure} random-state->datum state
1591 @deffnx {C Function} scm_random_state_to_datum (state)
1592 Return a datum representation of @var{state} that may be written out and
1593 read back with the Scheme reader.
1596 @defvar *random-state*
1597 The global random state used by the above functions when the
1598 @var{state} parameter is not given.
1601 Note that the initial value of @code{*random-state*} is the same every
1602 time Guile starts up. Therefore, if you don't pass a @var{state}
1603 parameter to the above procedures, and you don't set
1604 @code{*random-state*} to @code{(seed->random-state your-seed)}, where
1605 @code{your-seed} is something that @emph{isn't} the same every time,
1606 you'll get the same sequence of ``random'' numbers on every run.
1608 For example, unless the relevant source code has changed, @code{(map
1609 random (cdr (iota 30)))}, if the first use of random numbers since
1610 Guile started up, will always give:
1613 (map random (cdr (iota 19)))
1615 (0 1 1 2 2 2 1 2 6 7 10 0 5 3 12 5 5 12)
1618 To use the time of day as the random seed, you can use code like this:
1621 (let ((time (gettimeofday)))
1622 (set! *random-state*
1623 (seed->random-state (+ (car time)
1628 And then (depending on the time of day, of course):
1631 (map random (cdr (iota 19)))
1633 (0 0 1 0 2 4 5 4 5 5 9 3 10 1 8 3 14 17)
1636 For security applications, such as password generation, you should use
1637 more bits of seed. Otherwise an open source password generator could
1638 be attacked by guessing the seed@dots{} but that's a subject for
1643 @subsection Characters
1646 In Scheme, there is a data type to describe a single character.
1648 Defining what exactly a character @emph{is} can be more complicated
1649 than it seems. Guile follows the advice of R6RS and uses The Unicode
1650 Standard to help define what a character is. So, for Guile, a
1651 character is anything in the Unicode Character Database.
1654 @cindex Unicode code point
1656 The Unicode Character Database is basically a table of characters
1657 indexed using integers called 'code points'. Valid code points are in
1658 the ranges 0 to @code{#xD7FF} inclusive or @code{#xE000} to
1659 @code{#x10FFFF} inclusive, which is about 1.1 million code points.
1661 @cindex designated code point
1662 @cindex code point, designated
1664 Any code point that has been assigned to a character or that has
1665 otherwise been given a meaning by Unicode is called a 'designated code
1666 point'. Most of the designated code points, about 200,000 of them,
1667 indicate characters, accents or other combining marks that modify
1668 other characters, symbols, whitespace, and control characters. Some
1669 are not characters but indicators that suggest how to format or
1670 display neighboring characters.
1672 @cindex reserved code point
1673 @cindex code point, reserved
1675 If a code point is not a designated code point -- if it has not been
1676 assigned to a character by The Unicode Standard -- it is a 'reserved
1677 code point', meaning that they are reserved for future use. Most of
1678 the code points, about 800,000, are 'reserved code points'.
1680 By convention, a Unicode code point is written as
1681 ``U+XXXX'' where ``XXXX'' is a hexadecimal number. Please note that
1682 this convenient notation is not valid code. Guile does not interpret
1683 ``U+XXXX'' as a character.
1685 In Scheme, a character literal is written as @code{#\@var{name}} where
1686 @var{name} is the name of the character that you want. Printable
1687 characters have their usual single character name; for example,
1688 @code{#\a} is a lower case @code{a}.
1690 Some of the code points are 'combining characters' that are not meant
1691 to be printed by themselves but are instead meant to modify the
1692 appearance of the previous character. For combining characters, an
1693 alternate form of the character literal is @code{#\} followed by
1694 U+25CC (a small, dotted circle), followed by the combining character.
1695 This allows the combining character to be drawn on the circle, not on
1696 the backslash of @code{#\}.
1698 Many of the non-printing characters, such as whitespace characters and
1699 control characters, also have names.
1701 The most commonly used non-printing characters have long character
1702 names, described in the table below.
1704 @multitable {@code{#\backspace}} {Preferred}
1705 @item Character Name @tab Codepoint
1706 @item @code{#\nul} @tab U+0000
1707 @item @code{#\alarm} @tab u+0007
1708 @item @code{#\backspace} @tab U+0008
1709 @item @code{#\tab} @tab U+0009
1710 @item @code{#\linefeed} @tab U+000A
1711 @item @code{#\newline} @tab U+000A
1712 @item @code{#\vtab} @tab U+000B
1713 @item @code{#\page} @tab U+000C
1714 @item @code{#\return} @tab U+000D
1715 @item @code{#\esc} @tab U+001B
1716 @item @code{#\space} @tab U+0020
1717 @item @code{#\delete} @tab U+007F
1720 There are also short names for all of the ``C0 control characters''
1721 (those with code points below 32). The following table lists the short
1722 name for each character.
1724 @multitable @columnfractions .25 .25 .25 .25
1725 @item 0 = @code{#\nul}
1726 @tab 1 = @code{#\soh}
1727 @tab 2 = @code{#\stx}
1728 @tab 3 = @code{#\etx}
1729 @item 4 = @code{#\eot}
1730 @tab 5 = @code{#\enq}
1731 @tab 6 = @code{#\ack}
1732 @tab 7 = @code{#\bel}
1733 @item 8 = @code{#\bs}
1734 @tab 9 = @code{#\ht}
1735 @tab 10 = @code{#\lf}
1736 @tab 11 = @code{#\vt}
1737 @item 12 = @code{#\ff}
1738 @tab 13 = @code{#\cr}
1739 @tab 14 = @code{#\so}
1740 @tab 15 = @code{#\si}
1741 @item 16 = @code{#\dle}
1742 @tab 17 = @code{#\dc1}
1743 @tab 18 = @code{#\dc2}
1744 @tab 19 = @code{#\dc3}
1745 @item 20 = @code{#\dc4}
1746 @tab 21 = @code{#\nak}
1747 @tab 22 = @code{#\syn}
1748 @tab 23 = @code{#\etb}
1749 @item 24 = @code{#\can}
1750 @tab 25 = @code{#\em}
1751 @tab 26 = @code{#\sub}
1752 @tab 27 = @code{#\esc}
1753 @item 28 = @code{#\fs}
1754 @tab 29 = @code{#\gs}
1755 @tab 30 = @code{#\rs}
1756 @tab 31 = @code{#\us}
1757 @item 32 = @code{#\sp}
1760 The short name for the ``delete'' character (code point U+007F) is
1763 There are also a few alternative names left over for compatibility with
1764 previous versions of Guile.
1766 @multitable {@code{#\backspace}} {Preferred}
1767 @item Alternate @tab Standard
1768 @item @code{#\nl} @tab @code{#\newline}
1769 @item @code{#\np} @tab @code{#\page}
1770 @item @code{#\null} @tab @code{#\nul}
1773 Characters may also be written using their code point values. They can
1774 be written with as an octal number, such as @code{#\10} for
1775 @code{#\bs} or @code{#\177} for @code{#\del}.
1777 If one prefers hex to octal, there is an additional syntax for character
1778 escapes: @code{#\xHHHH} -- the letter 'x' followed by a hexadecimal
1779 number of one to eight digits.
1782 @deffn {Scheme Procedure} char? x
1783 @deffnx {C Function} scm_char_p (x)
1784 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1787 Fundamentally, the character comparison operations below are
1788 numeric comparisons of the character's code points.
1791 @deffn {Scheme Procedure} char=? x y
1792 Return @code{#t} iff code point of @var{x} is equal to the code point
1793 of @var{y}, else @code{#f}.
1797 @deffn {Scheme Procedure} char<? x y
1798 Return @code{#t} iff the code point of @var{x} is less than the code
1799 point of @var{y}, else @code{#f}.
1803 @deffn {Scheme Procedure} char<=? x y
1804 Return @code{#t} iff the code point of @var{x} is less than or equal
1805 to the code point of @var{y}, else @code{#f}.
1809 @deffn {Scheme Procedure} char>? x y
1810 Return @code{#t} iff the code point of @var{x} is greater than the
1811 code point of @var{y}, else @code{#f}.
1815 @deffn {Scheme Procedure} char>=? x y
1816 Return @code{#t} iff the code point of @var{x} is greater than or
1817 equal to the code point of @var{y}, else @code{#f}.
1820 @cindex case folding
1822 Case-insensitive character comparisons use @emph{Unicode case
1823 folding}. In case folding comparisons, if a character is lowercase
1824 and has an uppercase form that can be expressed as a single character,
1825 it is converted to uppercase before comparison. All other characters
1826 undergo no conversion before the comparison occurs. This includes the
1827 German sharp S (Eszett) which is not uppercased before conversion
1828 because its uppercase form has two characters. Unicode case folding
1829 is language independent: it uses rules that are generally true, but,
1830 it cannot cover all cases for all languages.
1833 @deffn {Scheme Procedure} char-ci=? x y
1834 Return @code{#t} iff the case-folded code point of @var{x} is the same
1835 as the case-folded code point of @var{y}, else @code{#f}.
1839 @deffn {Scheme Procedure} char-ci<? x y
1840 Return @code{#t} iff the case-folded code point of @var{x} is less
1841 than the case-folded code point of @var{y}, else @code{#f}.
1845 @deffn {Scheme Procedure} char-ci<=? x y
1846 Return @code{#t} iff the case-folded code point of @var{x} is less
1847 than or equal to the case-folded code point of @var{y}, else
1852 @deffn {Scheme Procedure} char-ci>? x y
1853 Return @code{#t} iff the case-folded code point of @var{x} is greater
1854 than the case-folded code point of @var{y}, else @code{#f}.
1858 @deffn {Scheme Procedure} char-ci>=? x y
1859 Return @code{#t} iff the case-folded code point of @var{x} is greater
1860 than or equal to the case-folded code point of @var{y}, else
1864 @rnindex char-alphabetic?
1865 @deffn {Scheme Procedure} char-alphabetic? chr
1866 @deffnx {C Function} scm_char_alphabetic_p (chr)
1867 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1870 @rnindex char-numeric?
1871 @deffn {Scheme Procedure} char-numeric? chr
1872 @deffnx {C Function} scm_char_numeric_p (chr)
1873 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1876 @rnindex char-whitespace?
1877 @deffn {Scheme Procedure} char-whitespace? chr
1878 @deffnx {C Function} scm_char_whitespace_p (chr)
1879 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1882 @rnindex char-upper-case?
1883 @deffn {Scheme Procedure} char-upper-case? chr
1884 @deffnx {C Function} scm_char_upper_case_p (chr)
1885 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1888 @rnindex char-lower-case?
1889 @deffn {Scheme Procedure} char-lower-case? chr
1890 @deffnx {C Function} scm_char_lower_case_p (chr)
1891 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1894 @deffn {Scheme Procedure} char-is-both? chr
1895 @deffnx {C Function} scm_char_is_both_p (chr)
1896 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1900 @deffn {Scheme Procedure} char-general-category chr
1901 @deffnx {C Function} scm_char_general_category (chr)
1902 Return a symbol giving the two-letter name of the Unicode general
1903 category assigned to @var{chr} or @code{#f} if no named category is
1904 assigned. The following table provides a list of category names along
1905 with their meanings.
1907 @multitable @columnfractions .1 .4 .1 .4
1909 @tab Uppercase letter
1911 @tab Final quote punctuation
1913 @tab Lowercase letter
1915 @tab Other punctuation
1917 @tab Titlecase letter
1921 @tab Modifier letter
1923 @tab Currency symbol
1927 @tab Modifier symbol
1929 @tab Non-spacing mark
1933 @tab Combining spacing mark
1935 @tab Space separator
1941 @tab Decimal digit number
1943 @tab Paragraph separator
1953 @tab Connector punctuation
1957 @tab Dash punctuation
1961 @tab Open punctuation
1965 @tab Close punctuation
1969 @tab Initial quote punctuation
1975 @rnindex char->integer
1976 @deffn {Scheme Procedure} char->integer chr
1977 @deffnx {C Function} scm_char_to_integer (chr)
1978 Return the code point of @var{chr}.
1981 @rnindex integer->char
1982 @deffn {Scheme Procedure} integer->char n
1983 @deffnx {C Function} scm_integer_to_char (n)
1984 Return the character that has code point @var{n}. The integer @var{n}
1985 must be a valid code point. Valid code points are in the ranges 0 to
1986 @code{#xD7FF} inclusive or @code{#xE000} to @code{#x10FFFF} inclusive.
1989 @rnindex char-upcase
1990 @deffn {Scheme Procedure} char-upcase chr
1991 @deffnx {C Function} scm_char_upcase (chr)
1992 Return the uppercase character version of @var{chr}.
1995 @rnindex char-downcase
1996 @deffn {Scheme Procedure} char-downcase chr
1997 @deffnx {C Function} scm_char_downcase (chr)
1998 Return the lowercase character version of @var{chr}.
2001 @rnindex char-titlecase
2002 @deffn {Scheme Procedure} char-titlecase chr
2003 @deffnx {C Function} scm_char_titlecase (chr)
2004 Return the titlecase character version of @var{chr} if one exists;
2005 otherwise return the uppercase version.
2007 For most characters these will be the same, but the Unicode Standard
2008 includes certain digraph compatibility characters, such as @code{U+01F3}
2009 ``dz'', for which the uppercase and titlecase characters are different
2010 (@code{U+01F1} ``DZ'' and @code{U+01F2} ``Dz'' in this case,
2015 @deftypefn {C Function} scm_t_wchar scm_c_upcase (scm_t_wchar @var{c})
2016 @deftypefnx {C Function} scm_t_wchar scm_c_downcase (scm_t_wchar @var{c})
2017 @deftypefnx {C Function} scm_t_wchar scm_c_titlecase (scm_t_wchar @var{c})
2019 These C functions take an integer representation of a Unicode
2020 codepoint and return the codepoint corresponding to its uppercase,
2021 lowercase, and titlecase forms respectively. The type
2022 @code{scm_t_wchar} is a signed, 32-bit integer.
2025 @node Character Sets
2026 @subsection Character Sets
2028 The features described in this section correspond directly to SRFI-14.
2030 The data type @dfn{charset} implements sets of characters
2031 (@pxref{Characters}). Because the internal representation of
2032 character sets is not visible to the user, a lot of procedures for
2033 handling them are provided.
2035 Character sets can be created, extended, tested for the membership of a
2036 characters and be compared to other character sets.
2039 * Character Set Predicates/Comparison::
2040 * Iterating Over Character Sets:: Enumerate charset elements.
2041 * Creating Character Sets:: Making new charsets.
2042 * Querying Character Sets:: Test charsets for membership etc.
2043 * Character-Set Algebra:: Calculating new charsets.
2044 * Standard Character Sets:: Variables containing predefined charsets.
2047 @node Character Set Predicates/Comparison
2048 @subsubsection Character Set Predicates/Comparison
2050 Use these procedures for testing whether an object is a character set,
2051 or whether several character sets are equal or subsets of each other.
2052 @code{char-set-hash} can be used for calculating a hash value, maybe for
2053 usage in fast lookup procedures.
2055 @deffn {Scheme Procedure} char-set? obj
2056 @deffnx {C Function} scm_char_set_p (obj)
2057 Return @code{#t} if @var{obj} is a character set, @code{#f}
2061 @deffn {Scheme Procedure} char-set= . char_sets
2062 @deffnx {C Function} scm_char_set_eq (char_sets)
2063 Return @code{#t} if all given character sets are equal.
2066 @deffn {Scheme Procedure} char-set<= . char_sets
2067 @deffnx {C Function} scm_char_set_leq (char_sets)
2068 Return @code{#t} if every character set @var{cs}i is a subset
2069 of character set @var{cs}i+1.
2072 @deffn {Scheme Procedure} char-set-hash cs [bound]
2073 @deffnx {C Function} scm_char_set_hash (cs, bound)
2074 Compute a hash value for the character set @var{cs}. If
2075 @var{bound} is given and non-zero, it restricts the
2076 returned value to the range 0 @dots{} @var{bound - 1}.
2079 @c ===================================================================
2081 @node Iterating Over Character Sets
2082 @subsubsection Iterating Over Character Sets
2084 Character set cursors are a means for iterating over the members of a
2085 character sets. After creating a character set cursor with
2086 @code{char-set-cursor}, a cursor can be dereferenced with
2087 @code{char-set-ref}, advanced to the next member with
2088 @code{char-set-cursor-next}. Whether a cursor has passed past the last
2089 element of the set can be checked with @code{end-of-char-set?}.
2091 Additionally, mapping and (un-)folding procedures for character sets are
2094 @deffn {Scheme Procedure} char-set-cursor cs
2095 @deffnx {C Function} scm_char_set_cursor (cs)
2096 Return a cursor into the character set @var{cs}.
2099 @deffn {Scheme Procedure} char-set-ref cs cursor
2100 @deffnx {C Function} scm_char_set_ref (cs, cursor)
2101 Return the character at the current cursor position
2102 @var{cursor} in the character set @var{cs}. It is an error to
2103 pass a cursor for which @code{end-of-char-set?} returns true.
2106 @deffn {Scheme Procedure} char-set-cursor-next cs cursor
2107 @deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
2108 Advance the character set cursor @var{cursor} to the next
2109 character in the character set @var{cs}. It is an error if the
2110 cursor given satisfies @code{end-of-char-set?}.
2113 @deffn {Scheme Procedure} end-of-char-set? cursor
2114 @deffnx {C Function} scm_end_of_char_set_p (cursor)
2115 Return @code{#t} if @var{cursor} has reached the end of a
2116 character set, @code{#f} otherwise.
2119 @deffn {Scheme Procedure} char-set-fold kons knil cs
2120 @deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2121 Fold the procedure @var{kons} over the character set @var{cs},
2122 initializing it with @var{knil}.
2125 @deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2126 @deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2127 This is a fundamental constructor for character sets.
2129 @item @var{g} is used to generate a series of ``seed'' values
2130 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2131 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2132 @item @var{p} tells us when to stop -- when it returns true
2133 when applied to one of the seed values.
2134 @item @var{f} maps each seed value to a character. These
2135 characters are added to the base character set @var{base_cs} to
2136 form the result; @var{base_cs} defaults to the empty set.
2140 @deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2141 @deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2142 This is a fundamental constructor for character sets.
2144 @item @var{g} is used to generate a series of ``seed'' values
2145 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2146 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2147 @item @var{p} tells us when to stop -- when it returns true
2148 when applied to one of the seed values.
2149 @item @var{f} maps each seed value to a character. These
2150 characters are added to the base character set @var{base_cs} to
2151 form the result; @var{base_cs} defaults to the empty set.
2155 @deffn {Scheme Procedure} char-set-for-each proc cs
2156 @deffnx {C Function} scm_char_set_for_each (proc, cs)
2157 Apply @var{proc} to every character in the character set
2158 @var{cs}. The return value is not specified.
2161 @deffn {Scheme Procedure} char-set-map proc cs
2162 @deffnx {C Function} scm_char_set_map (proc, cs)
2163 Map the procedure @var{proc} over every character in @var{cs}.
2164 @var{proc} must be a character -> character procedure.
2167 @c ===================================================================
2169 @node Creating Character Sets
2170 @subsubsection Creating Character Sets
2172 New character sets are produced with these procedures.
2174 @deffn {Scheme Procedure} char-set-copy cs
2175 @deffnx {C Function} scm_char_set_copy (cs)
2176 Return a newly allocated character set containing all
2177 characters in @var{cs}.
2180 @deffn {Scheme Procedure} char-set . rest
2181 @deffnx {C Function} scm_char_set (rest)
2182 Return a character set containing all given characters.
2185 @deffn {Scheme Procedure} list->char-set list [base_cs]
2186 @deffnx {C Function} scm_list_to_char_set (list, base_cs)
2187 Convert the character list @var{list} to a character set. If
2188 the character set @var{base_cs} is given, the character in this
2189 set are also included in the result.
2192 @deffn {Scheme Procedure} list->char-set! list base_cs
2193 @deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2194 Convert the character list @var{list} to a character set. The
2195 characters are added to @var{base_cs} and @var{base_cs} is
2199 @deffn {Scheme Procedure} string->char-set str [base_cs]
2200 @deffnx {C Function} scm_string_to_char_set (str, base_cs)
2201 Convert the string @var{str} to a character set. If the
2202 character set @var{base_cs} is given, the characters in this
2203 set are also included in the result.
2206 @deffn {Scheme Procedure} string->char-set! str base_cs
2207 @deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2208 Convert the string @var{str} to a character set. The
2209 characters from the string are added to @var{base_cs}, and
2210 @var{base_cs} is returned.
2213 @deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2214 @deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2215 Return a character set containing every character from @var{cs}
2216 so that it satisfies @var{pred}. If provided, the characters
2217 from @var{base_cs} are added to the result.
2220 @deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2221 @deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2222 Return a character set containing every character from @var{cs}
2223 so that it satisfies @var{pred}. The characters are added to
2224 @var{base_cs} and @var{base_cs} is returned.
2227 @deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2228 @deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2229 Return a character set containing all characters whose
2230 character codes lie in the half-open range
2231 [@var{lower},@var{upper}).
2233 If @var{error} is a true value, an error is signalled if the
2234 specified range contains characters which are not contained in
2235 the implemented character range. If @var{error} is @code{#f},
2236 these characters are silently left out of the resulting
2239 The characters in @var{base_cs} are added to the result, if
2243 @deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2244 @deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2245 Return a character set containing all characters whose
2246 character codes lie in the half-open range
2247 [@var{lower},@var{upper}).
2249 If @var{error} is a true value, an error is signalled if the
2250 specified range contains characters which are not contained in
2251 the implemented character range. If @var{error} is @code{#f},
2252 these characters are silently left out of the resulting
2255 The characters are added to @var{base_cs} and @var{base_cs} is
2259 @deffn {Scheme Procedure} ->char-set x
2260 @deffnx {C Function} scm_to_char_set (x)
2261 Coerces x into a char-set. @var{x} may be a string, character or
2262 char-set. A string is converted to the set of its constituent
2263 characters; a character is converted to a singleton set; a char-set is
2267 @c ===================================================================
2269 @node Querying Character Sets
2270 @subsubsection Querying Character Sets
2272 Access the elements and other information of a character set with these
2275 @deffn {Scheme Procedure} %char-set-dump cs
2276 Returns an association list containing debugging information
2277 for @var{cs}. The association list has the following entries.
2282 The number of groups of contiguous code points the char-set
2285 A list of lists where each sublist is a range of code points
2286 and their associated characters
2288 The return value of this function cannot be relied upon to be
2289 consistent between versions of Guile and should not be used in code.
2292 @deffn {Scheme Procedure} char-set-size cs
2293 @deffnx {C Function} scm_char_set_size (cs)
2294 Return the number of elements in character set @var{cs}.
2297 @deffn {Scheme Procedure} char-set-count pred cs
2298 @deffnx {C Function} scm_char_set_count (pred, cs)
2299 Return the number of the elements int the character set
2300 @var{cs} which satisfy the predicate @var{pred}.
2303 @deffn {Scheme Procedure} char-set->list cs
2304 @deffnx {C Function} scm_char_set_to_list (cs)
2305 Return a list containing the elements of the character set
2309 @deffn {Scheme Procedure} char-set->string cs
2310 @deffnx {C Function} scm_char_set_to_string (cs)
2311 Return a string containing the elements of the character set
2312 @var{cs}. The order in which the characters are placed in the
2313 string is not defined.
2316 @deffn {Scheme Procedure} char-set-contains? cs ch
2317 @deffnx {C Function} scm_char_set_contains_p (cs, ch)
2318 Return @code{#t} iff the character @var{ch} is contained in the
2319 character set @var{cs}.
2322 @deffn {Scheme Procedure} char-set-every pred cs
2323 @deffnx {C Function} scm_char_set_every (pred, cs)
2324 Return a true value if every character in the character set
2325 @var{cs} satisfies the predicate @var{pred}.
2328 @deffn {Scheme Procedure} char-set-any pred cs
2329 @deffnx {C Function} scm_char_set_any (pred, cs)
2330 Return a true value if any character in the character set
2331 @var{cs} satisfies the predicate @var{pred}.
2334 @c ===================================================================
2336 @node Character-Set Algebra
2337 @subsubsection Character-Set Algebra
2339 Character sets can be manipulated with the common set algebra operation,
2340 such as union, complement, intersection etc. All of these procedures
2341 provide side-effecting variants, which modify their character set
2344 @deffn {Scheme Procedure} char-set-adjoin cs . rest
2345 @deffnx {C Function} scm_char_set_adjoin (cs, rest)
2346 Add all character arguments to the first argument, which must
2350 @deffn {Scheme Procedure} char-set-delete cs . rest
2351 @deffnx {C Function} scm_char_set_delete (cs, rest)
2352 Delete all character arguments from the first argument, which
2353 must be a character set.
2356 @deffn {Scheme Procedure} char-set-adjoin! cs . rest
2357 @deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2358 Add all character arguments to the first argument, which must
2362 @deffn {Scheme Procedure} char-set-delete! cs . rest
2363 @deffnx {C Function} scm_char_set_delete_x (cs, rest)
2364 Delete all character arguments from the first argument, which
2365 must be a character set.
2368 @deffn {Scheme Procedure} char-set-complement cs
2369 @deffnx {C Function} scm_char_set_complement (cs)
2370 Return the complement of the character set @var{cs}.
2373 Note that the complement of a character set is likely to contain many
2374 reserved code points (code points that are not associated with
2375 characters). It may be helpful to modify the output of
2376 @code{char-set-complement} by computing its intersection with the set
2377 of designated code points, @code{char-set:designated}.
2379 @deffn {Scheme Procedure} char-set-union . rest
2380 @deffnx {C Function} scm_char_set_union (rest)
2381 Return the union of all argument character sets.
2384 @deffn {Scheme Procedure} char-set-intersection . rest
2385 @deffnx {C Function} scm_char_set_intersection (rest)
2386 Return the intersection of all argument character sets.
2389 @deffn {Scheme Procedure} char-set-difference cs1 . rest
2390 @deffnx {C Function} scm_char_set_difference (cs1, rest)
2391 Return the difference of all argument character sets.
2394 @deffn {Scheme Procedure} char-set-xor . rest
2395 @deffnx {C Function} scm_char_set_xor (rest)
2396 Return the exclusive-or of all argument character sets.
2399 @deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2400 @deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2401 Return the difference and the intersection of all argument
2405 @deffn {Scheme Procedure} char-set-complement! cs
2406 @deffnx {C Function} scm_char_set_complement_x (cs)
2407 Return the complement of the character set @var{cs}.
2410 @deffn {Scheme Procedure} char-set-union! cs1 . rest
2411 @deffnx {C Function} scm_char_set_union_x (cs1, rest)
2412 Return the union of all argument character sets.
2415 @deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2416 @deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2417 Return the intersection of all argument character sets.
2420 @deffn {Scheme Procedure} char-set-difference! cs1 . rest
2421 @deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2422 Return the difference of all argument character sets.
2425 @deffn {Scheme Procedure} char-set-xor! cs1 . rest
2426 @deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2427 Return the exclusive-or of all argument character sets.
2430 @deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2431 @deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2432 Return the difference and the intersection of all argument
2436 @c ===================================================================
2438 @node Standard Character Sets
2439 @subsubsection Standard Character Sets
2441 In order to make the use of the character set data type and procedures
2442 useful, several predefined character set variables exist.
2448 These character sets are locale independent and are not recomputed
2449 upon a @code{setlocale} call. They contain characters from the whole
2450 range of Unicode code points. For instance, @code{char-set:letter}
2451 contains about 94,000 characters.
2453 @defvr {Scheme Variable} char-set:lower-case
2454 @defvrx {C Variable} scm_char_set_lower_case
2455 All lower-case characters.
2458 @defvr {Scheme Variable} char-set:upper-case
2459 @defvrx {C Variable} scm_char_set_upper_case
2460 All upper-case characters.
2463 @defvr {Scheme Variable} char-set:title-case
2464 @defvrx {C Variable} scm_char_set_title_case
2465 All single characters that function as if they were an upper-case
2466 letter followed by a lower-case letter.
2469 @defvr {Scheme Variable} char-set:letter
2470 @defvrx {C Variable} scm_char_set_letter
2471 All letters. This includes @code{char-set:lower-case},
2472 @code{char-set:upper-case}, @code{char-set:title-case}, and many
2473 letters that have no case at all. For example, Chinese and Japanese
2474 characters typically have no concept of case.
2477 @defvr {Scheme Variable} char-set:digit
2478 @defvrx {C Variable} scm_char_set_digit
2482 @defvr {Scheme Variable} char-set:letter+digit
2483 @defvrx {C Variable} scm_char_set_letter_and_digit
2484 The union of @code{char-set:letter} and @code{char-set:digit}.
2487 @defvr {Scheme Variable} char-set:graphic
2488 @defvrx {C Variable} scm_char_set_graphic
2489 All characters which would put ink on the paper.
2492 @defvr {Scheme Variable} char-set:printing
2493 @defvrx {C Variable} scm_char_set_printing
2494 The union of @code{char-set:graphic} and @code{char-set:whitespace}.
2497 @defvr {Scheme Variable} char-set:whitespace
2498 @defvrx {C Variable} scm_char_set_whitespace
2499 All whitespace characters.
2502 @defvr {Scheme Variable} char-set:blank
2503 @defvrx {C Variable} scm_char_set_blank
2504 All horizontal whitespace characters, which notably includes
2505 @code{#\space} and @code{#\tab}.
2508 @defvr {Scheme Variable} char-set:iso-control
2509 @defvrx {C Variable} scm_char_set_iso_control
2510 The ISO control characters are the C0 control characters (U+0000 to
2511 U+001F), delete (U+007F), and the C1 control characters (U+0080 to
2515 @defvr {Scheme Variable} char-set:punctuation
2516 @defvrx {C Variable} scm_char_set_punctuation
2517 All punctuation characters, such as the characters
2518 @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
2521 @defvr {Scheme Variable} char-set:symbol
2522 @defvrx {C Variable} scm_char_set_symbol
2523 All symbol characters, such as the characters @code{$+<=>^`|~}.
2526 @defvr {Scheme Variable} char-set:hex-digit
2527 @defvrx {C Variable} scm_char_set_hex_digit
2528 The hexadecimal digits @code{0123456789abcdefABCDEF}.
2531 @defvr {Scheme Variable} char-set:ascii
2532 @defvrx {C Variable} scm_char_set_ascii
2533 All ASCII characters.
2536 @defvr {Scheme Variable} char-set:empty
2537 @defvrx {C Variable} scm_char_set_empty
2538 The empty character set.
2541 @defvr {Scheme Variable} char-set:designated
2542 @defvrx {C Variable} scm_char_set_designated
2543 This character set contains all designated code points. This includes
2544 all the code points to which Unicode has assigned a character or other
2548 @defvr {Scheme Variable} char-set:full
2549 @defvrx {C Variable} scm_char_set_full
2550 This character set contains all possible code points. This includes
2551 both designated and reserved code points.
2558 Strings are fixed-length sequences of characters. They can be created
2559 by calling constructor procedures, but they can also literally get
2560 entered at the @acronym{REPL} or in Scheme source files.
2562 @c Guile provides a rich set of string processing procedures, because text
2563 @c handling is very important when Guile is used as a scripting language.
2565 Strings always carry the information about how many characters they are
2566 composed of with them, so there is no special end-of-string character,
2567 like in C. That means that Scheme strings can contain any character,
2568 even the @samp{#\nul} character @samp{\0}.
2570 To use strings efficiently, you need to know a bit about how Guile
2571 implements them. In Guile, a string consists of two parts, a head and
2572 the actual memory where the characters are stored. When a string (or
2573 a substring of it) is copied, only a new head gets created, the memory
2574 is usually not copied. The two heads start out pointing to the same
2577 When one of these two strings is modified, as with @code{string-set!},
2578 their common memory does get copied so that each string has its own
2579 memory and modifying one does not accidentally modify the other as well.
2580 Thus, Guile's strings are `copy on write'; the actual copying of their
2581 memory is delayed until one string is written to.
2583 This implementation makes functions like @code{substring} very
2584 efficient in the common case that no modifications are done to the
2587 If you do know that your strings are getting modified right away, you
2588 can use @code{substring/copy} instead of @code{substring}. This
2589 function performs the copy immediately at the time of creation. This
2590 is more efficient, especially in a multi-threaded program. Also,
2591 @code{substring/copy} can avoid the problem that a short substring
2592 holds on to the memory of a very large original string that could
2593 otherwise be recycled.
2595 If you want to avoid the copy altogether, so that modifications of one
2596 string show up in the other, you can use @code{substring/shared}. The
2597 strings created by this procedure are called @dfn{mutation sharing
2598 substrings} since the substring and the original string share
2599 modifications to each other.
2601 If you want to prevent modifications, use @code{substring/read-only}.
2603 Guile provides all procedures of SRFI-13 and a few more.
2606 * String Syntax:: Read syntax for strings.
2607 * String Predicates:: Testing strings for certain properties.
2608 * String Constructors:: Creating new string objects.
2609 * List/String Conversion:: Converting from/to lists of characters.
2610 * String Selection:: Select portions from strings.
2611 * String Modification:: Modify parts or whole strings.
2612 * String Comparison:: Lexicographic ordering predicates.
2613 * String Searching:: Searching in strings.
2614 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2615 * Reversing and Appending Strings:: Appending strings to form a new string.
2616 * Mapping Folding and Unfolding:: Iterating over strings.
2617 * Miscellaneous String Operations:: Replicating, insertion, parsing, ...
2618 * Conversion to/from C::
2619 * String Internals:: The storage strategy for strings.
2623 @subsubsection String Read Syntax
2625 @c In the following @code is used to get a good font in TeX etc, but
2626 @c is omitted for Info format, so as not to risk any confusion over
2627 @c whether surrounding ` ' quotes are part of the escape or are
2628 @c special in a string (they're not).
2630 The read syntax for strings is an arbitrarily long sequence of
2631 characters enclosed in double quotes (@nicode{"}).
2633 Backslash is an escape character and can be used to insert the following
2634 special characters. @nicode{\"} and @nicode{\\} are R5RS standard, the
2635 next seven are R6RS standard --- notice they follow C syntax --- and the
2636 remaining four are Guile extensions.
2640 Backslash character.
2643 Double quote character (an unescaped @nicode{"} is otherwise the end
2647 Bell character (ASCII 7).
2650 Formfeed character (ASCII 12).
2653 Newline character (ASCII 10).
2656 Carriage return character (ASCII 13).
2659 Tab character (ASCII 9).
2662 Vertical tab character (ASCII 11).
2665 Backspace character (ASCII 8).
2668 NUL character (ASCII 0).
2670 @item @nicode{\} followed by newline (ASCII 10)
2671 Nothing. This way if @nicode{\} is the last character in a line, the
2672 string will continue with the first character from the next line,
2673 without a line break.
2675 If the @code{hungry-eol-escapes} reader option is enabled, which is not
2676 the case by default, leading whitespace on the next line is discarded.
2682 (read-enable 'hungry-eol-escapes)
2688 Character code given by two hexadecimal digits. For example
2689 @nicode{\x7f} for an ASCII DEL (127).
2691 @item @nicode{\uHHHH}
2692 Character code given by four hexadecimal digits. For example
2693 @nicode{\u0100} for a capital A with macron (U+0100).
2695 @item @nicode{\UHHHHHH}
2696 Character code given by six hexadecimal digits. For example
2701 The following are examples of string literals:
2710 The three escape sequences @code{\xHH}, @code{\uHHHH} and @code{\UHHHHHH} were
2711 chosen to not break compatibility with code written for previous versions of
2712 Guile. The R6RS specification suggests a different, incompatible syntax for hex
2713 escapes: @code{\xHHHH;} -- a character code followed by one to eight hexadecimal
2714 digits terminated with a semicolon. If this escape format is desired instead,
2715 it can be enabled with the reader option @code{r6rs-hex-escapes}.
2718 (read-enable 'r6rs-hex-escapes)
2721 For more on reader options, @xref{Scheme Read}.
2723 @node String Predicates
2724 @subsubsection String Predicates
2726 The following procedures can be used to check whether a given string
2727 fulfills some specified property.
2730 @deffn {Scheme Procedure} string? obj
2731 @deffnx {C Function} scm_string_p (obj)
2732 Return @code{#t} if @var{obj} is a string, else @code{#f}.
2735 @deftypefn {C Function} int scm_is_string (SCM obj)
2736 Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2739 @deffn {Scheme Procedure} string-null? str
2740 @deffnx {C Function} scm_string_null_p (str)
2741 Return @code{#t} if @var{str}'s length is zero, and
2742 @code{#f} otherwise.
2744 (string-null? "") @result{} #t
2746 (string-null? y) @result{} #f
2750 @deffn {Scheme Procedure} string-any char_pred s [start [end]]
2751 @deffnx {C Function} scm_string_any (char_pred, s, start, end)
2752 Check if @var{char_pred} is true for any character in string @var{s}.
2754 @var{char_pred} can be a character to check for any equal to that, or
2755 a character set (@pxref{Character Sets}) to check for any in that set,
2756 or a predicate procedure to call.
2758 For a procedure, calls @code{(@var{char_pred} c)} are made
2759 successively on the characters from @var{start} to @var{end}. If
2760 @var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2761 stops and that return value is the return from @code{string-any}. The
2762 call on the last character (ie.@: at @math{@var{end}-1}), if that
2763 point is reached, is a tail call.
2765 If there are no characters in @var{s} (ie.@: @var{start} equals
2766 @var{end}) then the return is @code{#f}.
2769 @deffn {Scheme Procedure} string-every char_pred s [start [end]]
2770 @deffnx {C Function} scm_string_every (char_pred, s, start, end)
2771 Check if @var{char_pred} is true for every character in string
2774 @var{char_pred} can be a character to check for every character equal
2775 to that, or a character set (@pxref{Character Sets}) to check for
2776 every character being in that set, or a predicate procedure to call.
2778 For a procedure, calls @code{(@var{char_pred} c)} are made
2779 successively on the characters from @var{start} to @var{end}. If
2780 @var{char_pred} returns @code{#f}, @code{string-every} stops and
2781 returns @code{#f}. The call on the last character (ie.@: at
2782 @math{@var{end}-1}), if that point is reached, is a tail call and the
2783 return from that call is the return from @code{string-every}.
2785 If there are no characters in @var{s} (ie.@: @var{start} equals
2786 @var{end}) then the return is @code{#t}.
2789 @node String Constructors
2790 @subsubsection String Constructors
2792 The string constructor procedures create new string objects, possibly
2793 initializing them with some specified character data. See also
2794 @xref{String Selection}, for ways to create strings from existing
2797 @c FIXME::martin: list->string belongs into `List/String Conversion'
2799 @deffn {Scheme Procedure} string char@dots{}
2801 Return a newly allocated string made from the given character
2805 (string #\x #\y #\z) @result{} "xyz"
2806 (string) @result{} ""
2810 @deffn {Scheme Procedure} list->string lst
2811 @deffnx {C Function} scm_string (lst)
2812 @rnindex list->string
2813 Return a newly allocated string made from a list of characters.
2816 (list->string '(#\a #\b #\c)) @result{} "abc"
2820 @deffn {Scheme Procedure} reverse-list->string lst
2821 @deffnx {C Function} scm_reverse_list_to_string (lst)
2822 Return a newly allocated string made from a list of characters, in
2826 (reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2830 @rnindex make-string
2831 @deffn {Scheme Procedure} make-string k [chr]
2832 @deffnx {C Function} scm_make_string (k, chr)
2833 Return a newly allocated string of
2834 length @var{k}. If @var{chr} is given, then all elements of
2835 the string are initialized to @var{chr}, otherwise the contents
2836 of the @var{string} are unspecified.
2839 @deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2840 Like @code{scm_make_string}, but expects the length as a
2844 @deffn {Scheme Procedure} string-tabulate proc len
2845 @deffnx {C Function} scm_string_tabulate (proc, len)
2846 @var{proc} is an integer->char procedure. Construct a string
2847 of size @var{len} by applying @var{proc} to each index to
2848 produce the corresponding string element. The order in which
2849 @var{proc} is applied to the indices is not specified.
2852 @deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2853 @deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2854 Append the string in the string list @var{ls}, using the string
2855 @var{delim} as a delimiter between the elements of @var{ls}.
2856 @var{grammar} is a symbol which specifies how the delimiter is
2857 placed between the strings, and defaults to the symbol
2862 Insert the separator between list elements. An empty string
2863 will produce an empty list.
2865 Like @code{infix}, but will raise an error if given the empty
2868 Insert the separator after every list element.
2870 Insert the separator before each list element.
2874 @node List/String Conversion
2875 @subsubsection List/String conversion
2877 When processing strings, it is often convenient to first convert them
2878 into a list representation by using the procedure @code{string->list},
2879 work with the resulting list, and then convert it back into a string.
2880 These procedures are useful for similar tasks.
2882 @rnindex string->list
2883 @deffn {Scheme Procedure} string->list str [start [end]]
2884 @deffnx {C Function} scm_substring_to_list (str, start, end)
2885 @deffnx {C Function} scm_string_to_list (str)
2886 Convert the string @var{str} into a list of characters.
2889 @deffn {Scheme Procedure} string-split str chr
2890 @deffnx {C Function} scm_string_split (str, chr)
2891 Split the string @var{str} into the a list of the substrings delimited
2892 by appearances of the character @var{chr}. Note that an empty substring
2893 between separator characters will result in an empty string in the
2897 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2899 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
2901 (string-split "::" #\:)
2905 (string-split "" #\:)
2912 @node String Selection
2913 @subsubsection String Selection
2915 Portions of strings can be extracted by these procedures.
2916 @code{string-ref} delivers individual characters whereas
2917 @code{substring} can be used to extract substrings from longer strings.
2919 @rnindex string-length
2920 @deffn {Scheme Procedure} string-length string
2921 @deffnx {C Function} scm_string_length (string)
2922 Return the number of characters in @var{string}.
2925 @deftypefn {C Function} size_t scm_c_string_length (SCM str)
2926 Return the number of characters in @var{str} as a @code{size_t}.
2930 @deffn {Scheme Procedure} string-ref str k
2931 @deffnx {C Function} scm_string_ref (str, k)
2932 Return character @var{k} of @var{str} using zero-origin
2933 indexing. @var{k} must be a valid index of @var{str}.
2936 @deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2937 Return character @var{k} of @var{str} using zero-origin
2938 indexing. @var{k} must be a valid index of @var{str}.
2941 @rnindex string-copy
2942 @deffn {Scheme Procedure} string-copy str [start [end]]
2943 @deffnx {C Function} scm_substring_copy (str, start, end)
2944 @deffnx {C Function} scm_string_copy (str)
2945 Return a copy of the given string @var{str}.
2947 The returned string shares storage with @var{str} initially, but it is
2948 copied as soon as one of the two strings is modified.
2952 @deffn {Scheme Procedure} substring str start [end]
2953 @deffnx {C Function} scm_substring (str, start, end)
2954 Return a new string formed from the characters
2955 of @var{str} beginning with index @var{start} (inclusive) and
2956 ending with index @var{end} (exclusive).
2957 @var{str} must be a string, @var{start} and @var{end} must be
2958 exact integers satisfying:
2960 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
2962 The returned string shares storage with @var{str} initially, but it is
2963 copied as soon as one of the two strings is modified.
2966 @deffn {Scheme Procedure} substring/shared str start [end]
2967 @deffnx {C Function} scm_substring_shared (str, start, end)
2968 Like @code{substring}, but the strings continue to share their storage
2969 even if they are modified. Thus, modifications to @var{str} show up
2970 in the new string, and vice versa.
2973 @deffn {Scheme Procedure} substring/copy str start [end]
2974 @deffnx {C Function} scm_substring_copy (str, start, end)
2975 Like @code{substring}, but the storage for the new string is copied
2979 @deffn {Scheme Procedure} substring/read-only str start [end]
2980 @deffnx {C Function} scm_substring_read_only (str, start, end)
2981 Like @code{substring}, but the resulting string can not be modified.
2984 @deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2985 @deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2986 @deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2987 @deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
2988 Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2991 @deffn {Scheme Procedure} string-take s n
2992 @deffnx {C Function} scm_string_take (s, n)
2993 Return the @var{n} first characters of @var{s}.
2996 @deffn {Scheme Procedure} string-drop s n
2997 @deffnx {C Function} scm_string_drop (s, n)
2998 Return all but the first @var{n} characters of @var{s}.
3001 @deffn {Scheme Procedure} string-take-right s n
3002 @deffnx {C Function} scm_string_take_right (s, n)
3003 Return the @var{n} last characters of @var{s}.
3006 @deffn {Scheme Procedure} string-drop-right s n
3007 @deffnx {C Function} scm_string_drop_right (s, n)
3008 Return all but the last @var{n} characters of @var{s}.
3011 @deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
3012 @deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
3013 @deffnx {C Function} scm_string_pad (s, len, chr, start, end)
3014 @deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
3015 Take characters @var{start} to @var{end} from the string @var{s} and
3016 either pad with @var{char} or truncate them to give @var{len}
3019 @code{string-pad} pads or truncates on the left, so for example
3022 (string-pad "x" 3) @result{} " x"
3023 (string-pad "abcde" 3) @result{} "cde"
3026 @code{string-pad-right} pads or truncates on the right, so for example
3029 (string-pad-right "x" 3) @result{} "x "
3030 (string-pad-right "abcde" 3) @result{} "abc"
3034 @deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
3035 @deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
3036 @deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
3037 @deffnx {C Function} scm_string_trim (s, char_pred, start, end)
3038 @deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
3039 @deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
3040 Trim occurrences of @var{char_pred} from the ends of @var{s}.
3042 @code{string-trim} trims @var{char_pred} characters from the left
3043 (start) of the string, @code{string-trim-right} trims them from the
3044 right (end) of the string, @code{string-trim-both} trims from both
3047 @var{char_pred} can be a character, a character set, or a predicate
3048 procedure to call on each character. If @var{char_pred} is not given
3049 the default is whitespace as per @code{char-set:whitespace}
3050 (@pxref{Standard Character Sets}).
3053 (string-trim " x ") @result{} "x "
3054 (string-trim-right "banana" #\a) @result{} "banan"
3055 (string-trim-both ".,xy:;" char-set:punctuation)
3057 (string-trim-both "xyzzy" (lambda (c)
3064 @node String Modification
3065 @subsubsection String Modification
3067 These procedures are for modifying strings in-place. This means that the
3068 result of the operation is not a new string; instead, the original string's
3069 memory representation is modified.
3071 @rnindex string-set!
3072 @deffn {Scheme Procedure} string-set! str k chr
3073 @deffnx {C Function} scm_string_set_x (str, k, chr)
3074 Store @var{chr} in element @var{k} of @var{str} and return
3075 an unspecified value. @var{k} must be a valid index of
3079 @deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
3080 Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
3083 @rnindex string-fill!
3084 @deffn {Scheme Procedure} string-fill! str chr [start [end]]
3085 @deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
3086 @deffnx {C Function} scm_string_fill_x (str, chr)
3087 Stores @var{chr} in every element of the given @var{str} and
3088 returns an unspecified value.
3091 @deffn {Scheme Procedure} substring-fill! str start end fill
3092 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
3093 Change every character in @var{str} between @var{start} and
3094 @var{end} to @var{fill}.
3097 (define y "abcdefg")
3098 (substring-fill! y 1 3 #\r)
3104 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
3105 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
3106 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
3107 into @var{str2} beginning at position @var{start2}.
3108 @var{str1} and @var{str2} can be the same string.
3111 @deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
3112 @deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
3113 Copy the sequence of characters from index range [@var{start},
3114 @var{end}) in string @var{s} to string @var{target}, beginning
3115 at index @var{tstart}. The characters are copied left-to-right
3116 or right-to-left as needed -- the copy is guaranteed to work,
3117 even if @var{target} and @var{s} are the same string. It is an
3118 error if the copy operation runs off the end of the target
3123 @node String Comparison
3124 @subsubsection String Comparison
3126 The procedures in this section are similar to the character ordering
3127 predicates (@pxref{Characters}), but are defined on character sequences.
3129 The first set is specified in R5RS and has names that end in @code{?}.
3130 The second set is specified in SRFI-13 and the names have not ending
3133 The predicates ending in @code{-ci} ignore the character case
3134 when comparing strings. For now, case-insensitive comparison is done
3135 using the R5RS rules, where every lower-case character that has a
3136 single character upper-case form is converted to uppercase before
3137 comparison. See @xref{Text Collation, the @code{(ice-9
3138 i18n)} module}, for locale-dependent string comparison.
3141 @deffn {Scheme Procedure} string=? [s1 [s2 . rest]]
3142 @deffnx {C Function} scm_i_string_equal_p (s1, s2, rest)
3143 Lexicographic equality predicate; return @code{#t} if the two
3144 strings are the same length and contain the same characters in
3145 the same positions, otherwise return @code{#f}.
3147 The procedure @code{string-ci=?} treats upper and lower case
3148 letters as though they were the same character, but
3149 @code{string=?} treats upper and lower case as distinct
3154 @deffn {Scheme Procedure} string<? [s1 [s2 . rest]]
3155 @deffnx {C Function} scm_i_string_less_p (s1, s2, rest)
3156 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3157 is lexicographically less than @var{s2}.
3161 @deffn {Scheme Procedure} string<=? [s1 [s2 . rest]]
3162 @deffnx {C Function} scm_i_string_leq_p (s1, s2, rest)
3163 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3164 is lexicographically less than or equal to @var{s2}.
3168 @deffn {Scheme Procedure} string>? [s1 [s2 . rest]]
3169 @deffnx {C Function} scm_i_string_gr_p (s1, s2, rest)
3170 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3171 is lexicographically greater than @var{s2}.
3175 @deffn {Scheme Procedure} string>=? [s1 [s2 . rest]]
3176 @deffnx {C Function} scm_i_string_geq_p (s1, s2, rest)
3177 Lexicographic ordering predicate; return @code{#t} if @var{s1}
3178 is lexicographically greater than or equal to @var{s2}.
3181 @rnindex string-ci=?
3182 @deffn {Scheme Procedure} string-ci=? [s1 [s2 . rest]]
3183 @deffnx {C Function} scm_i_string_ci_equal_p (s1, s2, rest)
3184 Case-insensitive string equality predicate; return @code{#t} if
3185 the two strings are the same length and their component
3186 characters match (ignoring case) at each position; otherwise
3190 @rnindex string-ci<?
3191 @deffn {Scheme Procedure} string-ci<? [s1 [s2 . rest]]
3192 @deffnx {C Function} scm_i_string_ci_less_p (s1, s2, rest)
3193 Case insensitive lexicographic ordering predicate; return
3194 @code{#t} if @var{s1} is lexicographically less than @var{s2}
3199 @deffn {Scheme Procedure} string-ci<=? [s1 [s2 . rest]]
3200 @deffnx {C Function} scm_i_string_ci_leq_p (s1, s2, rest)
3201 Case insensitive lexicographic ordering predicate; return
3202 @code{#t} if @var{s1} is lexicographically less than or equal
3203 to @var{s2} regardless of case.
3206 @rnindex string-ci>?
3207 @deffn {Scheme Procedure} string-ci>? [s1 [s2 . rest]]
3208 @deffnx {C Function} scm_i_string_ci_gr_p (s1, s2, rest)
3209 Case insensitive lexicographic ordering predicate; return
3210 @code{#t} if @var{s1} is lexicographically greater than
3211 @var{s2} regardless of case.
3214 @rnindex string-ci>=?
3215 @deffn {Scheme Procedure} string-ci>=? [s1 [s2 . rest]]
3216 @deffnx {C Function} scm_i_string_ci_geq_p (s1, s2, rest)
3217 Case insensitive lexicographic ordering predicate; return
3218 @code{#t} if @var{s1} is lexicographically greater than or
3219 equal to @var{s2} regardless of case.
3222 @deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3223 @deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3224 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3225 mismatch index, depending upon whether @var{s1} is less than,
3226 equal to, or greater than @var{s2}. The mismatch index is the
3227 largest index @var{i} such that for every 0 <= @var{j} <
3228 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3229 @var{i} is the first position that does not match.
3232 @deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3233 @deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3234 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3235 mismatch index, depending upon whether @var{s1} is less than,
3236 equal to, or greater than @var{s2}. The mismatch index is the
3237 largest index @var{i} such that for every 0 <= @var{j} <
3238 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3239 @var{i} is the first position where the lowercased letters
3244 @deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3245 @deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3246 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3250 @deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3251 @deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3252 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3256 @deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3257 @deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3258 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3259 true value otherwise.
3262 @deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3263 @deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3264 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3265 true value otherwise.
3268 @deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3269 @deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3270 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3274 @deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3275 @deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3276 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3280 @deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3281 @deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3282 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3283 value otherwise. The character comparison is done
3287 @deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3288 @deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3289 Return @code{#f} if @var{s1} and @var{s2} are 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_lt (s1, s2, start1, end1, start2, end2)
3296 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3297 true 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_gt (s1, s2, start1, end1, start2, end2)
3303 Return @code{#f} if @var{s1} is less 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_le (s1, s2, start1, end1, start2, end2)
3310 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3311 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_ge (s1, s2, start1, end1, start2, end2)
3317 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3318 otherwise. The character comparison is done
3322 @deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3323 @deffnx {C Function} scm_substring_hash (s, bound, start, end)
3324 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).
3327 @deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3328 @deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3329 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).
3332 Because the same visual appearance of an abstract Unicode character can
3333 be obtained via multiple sequences of Unicode characters, even the
3334 case-insensitive string comparison functions described above may return
3335 @code{#f} when presented with strings containing different
3336 representations of the same character. For example, the Unicode
3337 character ``LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE'' can be
3338 represented with a single character (U+1E69) or by the character ``LATIN
3339 SMALL LETTER S'' (U+0073) followed by the combining marks ``COMBINING
3340 DOT BELOW'' (U+0323) and ``COMBINING DOT ABOVE'' (U+0307).
3342 For this reason, it is often desirable to ensure that the strings
3343 to be compared are using a mutually consistent representation for every
3344 character. The Unicode standard defines two methods of normalizing the
3345 contents of strings: Decomposition, which breaks composite characters
3346 into a set of constituent characters with an ordering defined by the
3347 Unicode Standard; and composition, which performs the converse.
3349 There are two decomposition operations. ``Canonical decomposition''
3350 produces character sequences that share the same visual appearance as
3351 the original characters, while ``compatiblity decomposition'' produces
3352 ones whose visual appearances may differ from the originals but which
3353 represent the same abstract character.
3355 These operations are encapsulated in the following set of normalization
3360 Characters are decomposed to their canonical forms.
3363 Characters are decomposed to their compatibility forms.
3366 Characters are decomposed to their canonical forms, then composed.
3369 Characters are decomposed to their compatibility forms, then composed.
3373 The functions below put their arguments into one of the forms described
3376 @deffn {Scheme Procedure} string-normalize-nfd s
3377 @deffnx {C Function} scm_string_normalize_nfd (s)
3378 Return the @code{NFD} normalized form of @var{s}.
3381 @deffn {Scheme Procedure} string-normalize-nfkd s
3382 @deffnx {C Function} scm_string_normalize_nfkd (s)
3383 Return the @code{NFKD} normalized form of @var{s}.
3386 @deffn {Scheme Procedure} string-normalize-nfc s
3387 @deffnx {C Function} scm_string_normalize_nfc (s)
3388 Return the @code{NFC} normalized form of @var{s}.
3391 @deffn {Scheme Procedure} string-normalize-nfkc s
3392 @deffnx {C Function} scm_string_normalize_nfkc (s)
3393 Return the @code{NFKC} normalized form of @var{s}.
3396 @node String Searching
3397 @subsubsection String Searching
3399 @deffn {Scheme Procedure} string-index s char_pred [start [end]]
3400 @deffnx {C Function} scm_string_index (s, char_pred, start, end)
3401 Search through the string @var{s} from left to right, returning
3402 the index of the first occurrence of a character which
3406 equals @var{char_pred}, if it is character,
3409 satisfies the predicate @var{char_pred}, if it is a procedure,
3412 is in the set @var{char_pred}, if it is a character set.
3415 Return @code{#f} if no match is found.
3418 @deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3419 @deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3420 Search through the string @var{s} from right to left, returning
3421 the index of the last occurrence of a character which
3425 equals @var{char_pred}, if it is character,
3428 satisfies the predicate @var{char_pred}, if it is a procedure,
3431 is in the set if @var{char_pred} is a character set.
3434 Return @code{#f} if no match is found.
3437 @deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3438 @deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3439 Return the length of the longest common prefix of the two
3443 @deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3444 @deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3445 Return the length of the longest common prefix of the two
3446 strings, ignoring character case.
3449 @deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3450 @deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3451 Return the length of the longest common suffix of the two
3455 @deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3456 @deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3457 Return the length of the longest common suffix of the two
3458 strings, ignoring character case.
3461 @deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3462 @deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3463 Is @var{s1} a prefix of @var{s2}?
3466 @deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3467 @deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3468 Is @var{s1} a prefix of @var{s2}, ignoring character case?
3471 @deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3472 @deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3473 Is @var{s1} a suffix of @var{s2}?
3476 @deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3477 @deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3478 Is @var{s1} a suffix of @var{s2}, ignoring character case?
3481 @deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3482 @deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3483 Search through the string @var{s} from right to left, returning
3484 the index of the last occurrence of a character which
3488 equals @var{char_pred}, if it is character,
3491 satisfies the predicate @var{char_pred}, if it is a procedure,
3494 is in the set if @var{char_pred} is a character set.
3497 Return @code{#f} if no match is found.
3500 @deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3501 @deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3502 Search through the string @var{s} from left to right, returning
3503 the index of the first occurrence of a character which
3507 does not equal @var{char_pred}, if it is character,
3510 does not satisfy the predicate @var{char_pred}, if it is a
3514 is not in the set if @var{char_pred} is a character set.
3518 @deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3519 @deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3520 Search through the string @var{s} from right to left, returning
3521 the index of the last occurrence of a character which
3525 does not equal @var{char_pred}, if it is character,
3528 does not satisfy the predicate @var{char_pred}, if it is a
3532 is not in the set if @var{char_pred} is a character set.
3536 @deffn {Scheme Procedure} string-count s char_pred [start [end]]
3537 @deffnx {C Function} scm_string_count (s, char_pred, start, end)
3538 Return the count of the number of characters in the string
3543 equals @var{char_pred}, if it is character,
3546 satisfies the predicate @var{char_pred}, if it is a procedure.
3549 is in the set @var{char_pred}, if it is a character set.
3553 @deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3554 @deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3555 Does string @var{s1} contain string @var{s2}? Return the index
3556 in @var{s1} where @var{s2} occurs as a substring, or false.
3557 The optional start/end indices restrict the operation to the
3558 indicated substrings.
3561 @deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3562 @deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3563 Does string @var{s1} contain string @var{s2}? Return the index
3564 in @var{s1} where @var{s2} occurs as a substring, or false.
3565 The optional start/end indices restrict the operation to the
3566 indicated substrings. Character comparison is done
3570 @node Alphabetic Case Mapping
3571 @subsubsection Alphabetic Case Mapping
3573 These are procedures for mapping strings to their upper- or lower-case
3574 equivalents, respectively, or for capitalizing strings.
3576 They use the basic case mapping rules for Unicode characters. No
3577 special language or context rules are considered. The resulting strings
3578 are guaranteed to be the same length as the input strings.
3580 @xref{Character Case Mapping, the @code{(ice-9
3581 i18n)} module}, for locale-dependent case conversions.
3583 @deffn {Scheme Procedure} string-upcase str [start [end]]
3584 @deffnx {C Function} scm_substring_upcase (str, start, end)
3585 @deffnx {C Function} scm_string_upcase (str)
3586 Upcase every character in @code{str}.
3589 @deffn {Scheme Procedure} string-upcase! str [start [end]]
3590 @deffnx {C Function} scm_substring_upcase_x (str, start, end)
3591 @deffnx {C Function} scm_string_upcase_x (str)
3592 Destructively upcase every character in @code{str}.
3602 @deffn {Scheme Procedure} string-downcase str [start [end]]
3603 @deffnx {C Function} scm_substring_downcase (str, start, end)
3604 @deffnx {C Function} scm_string_downcase (str)
3605 Downcase every character in @var{str}.
3608 @deffn {Scheme Procedure} string-downcase! str [start [end]]
3609 @deffnx {C Function} scm_substring_downcase_x (str, start, end)
3610 @deffnx {C Function} scm_string_downcase_x (str)
3611 Destructively downcase every character in @var{str}.
3616 (string-downcase! y)
3623 @deffn {Scheme Procedure} string-capitalize str
3624 @deffnx {C Function} scm_string_capitalize (str)
3625 Return a freshly allocated string with the characters in
3626 @var{str}, where the first character of every word is
3630 @deffn {Scheme Procedure} string-capitalize! str
3631 @deffnx {C Function} scm_string_capitalize_x (str)
3632 Upcase the first character of every word in @var{str}
3633 destructively and return @var{str}.
3636 y @result{} "hello world"
3637 (string-capitalize! y) @result{} "Hello World"
3638 y @result{} "Hello World"
3642 @deffn {Scheme Procedure} string-titlecase str [start [end]]
3643 @deffnx {C Function} scm_string_titlecase (str, start, end)
3644 Titlecase every first character in a word in @var{str}.
3647 @deffn {Scheme Procedure} string-titlecase! str [start [end]]
3648 @deffnx {C Function} scm_string_titlecase_x (str, start, end)
3649 Destructively titlecase every first character in a word in
3653 @node Reversing and Appending Strings
3654 @subsubsection Reversing and Appending Strings
3656 @deffn {Scheme Procedure} string-reverse str [start [end]]
3657 @deffnx {C Function} scm_string_reverse (str, start, end)
3658 Reverse the string @var{str}. The optional arguments
3659 @var{start} and @var{end} delimit the region of @var{str} to
3663 @deffn {Scheme Procedure} string-reverse! str [start [end]]
3664 @deffnx {C Function} scm_string_reverse_x (str, start, end)
3665 Reverse the string @var{str} in-place. The optional arguments
3666 @var{start} and @var{end} delimit the region of @var{str} to
3667 operate on. The return value is unspecified.
3670 @rnindex string-append
3671 @deffn {Scheme Procedure} string-append . args
3672 @deffnx {C Function} scm_string_append (args)
3673 Return a newly allocated string whose characters form the
3674 concatenation of the given strings, @var{args}.
3678 (string-append h "world"))
3679 @result{} "hello world"
3683 @deffn {Scheme Procedure} string-append/shared . rest
3684 @deffnx {C Function} scm_string_append_shared (rest)
3685 Like @code{string-append}, but the result may share memory
3686 with the argument strings.
3689 @deffn {Scheme Procedure} string-concatenate ls
3690 @deffnx {C Function} scm_string_concatenate (ls)
3691 Append the elements of @var{ls} (which must be strings)
3692 together into a single string. Guaranteed to return a freshly
3696 @deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3697 @deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3698 Without optional arguments, this procedure is equivalent to
3701 (string-concatenate (reverse ls))
3704 If the optional argument @var{final_string} is specified, it is
3705 consed onto the beginning to @var{ls} before performing the
3706 list-reverse and string-concatenate operations. If @var{end}
3707 is given, only the characters of @var{final_string} up to index
3710 Guaranteed to return a freshly allocated string.
3713 @deffn {Scheme Procedure} string-concatenate/shared ls
3714 @deffnx {C Function} scm_string_concatenate_shared (ls)
3715 Like @code{string-concatenate}, but the result may share memory
3716 with the strings in the list @var{ls}.
3719 @deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3720 @deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3721 Like @code{string-concatenate-reverse}, but the result may
3722 share memory with the strings in the @var{ls} arguments.
3725 @node Mapping Folding and Unfolding
3726 @subsubsection Mapping, Folding, and Unfolding
3728 @deffn {Scheme Procedure} string-map proc s [start [end]]
3729 @deffnx {C Function} scm_string_map (proc, s, start, end)
3730 @var{proc} is a char->char procedure, it is mapped over
3731 @var{s}. The order in which the procedure is applied to the
3732 string elements is not specified.
3735 @deffn {Scheme Procedure} string-map! proc s [start [end]]
3736 @deffnx {C Function} scm_string_map_x (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. The string @var{s} is
3740 modified in-place, the return value is not specified.
3743 @deffn {Scheme Procedure} string-for-each proc s [start [end]]
3744 @deffnx {C Function} scm_string_for_each (proc, s, start, end)
3745 @var{proc} is mapped over @var{s} in left-to-right order. The
3746 return value is not specified.
3749 @deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3750 @deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
3751 Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3754 For example, to change characters to alternately upper and lower case,
3757 (define str (string-copy "studly"))
3758 (string-for-each-index
3761 ((if (even? i) char-upcase char-downcase)
3762 (string-ref str i))))
3764 str @result{} "StUdLy"
3768 @deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3769 @deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3770 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3771 as the terminating element, from left to right. @var{kons}
3772 must expect two arguments: The actual character and the last
3773 result of @var{kons}' application.
3776 @deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3777 @deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3778 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3779 as the terminating element, from right to left. @var{kons}
3780 must expect two arguments: The actual character and the last
3781 result of @var{kons}' application.
3784 @deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3785 @deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3787 @item @var{g} is used to generate a series of @emph{seed}
3788 values from the initial @var{seed}: @var{seed}, (@var{g}
3789 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3791 @item @var{p} tells us when to stop -- when it returns true
3792 when applied to one of these seed values.
3793 @item @var{f} maps each seed value to the corresponding
3794 character in the result string. These chars are assembled
3795 into the string in a left-to-right order.
3796 @item @var{base} is the optional initial/leftmost portion
3797 of the constructed string; it default to the empty
3799 @item @var{make_final} is applied to the terminal seed
3800 value (on which @var{p} returns true) to produce
3801 the final/rightmost portion of the constructed string.
3802 The default is nothing extra.
3806 @deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3807 @deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3809 @item @var{g} is used to generate a series of @emph{seed}
3810 values from the initial @var{seed}: @var{seed}, (@var{g}
3811 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3813 @item @var{p} tells us when to stop -- when it returns true
3814 when applied to one of these seed values.
3815 @item @var{f} maps each seed value to the corresponding
3816 character in the result string. These chars are assembled
3817 into the string in a right-to-left order.
3818 @item @var{base} is the optional initial/rightmost portion
3819 of the constructed string; it default to the empty
3821 @item @var{make_final} is applied to the terminal seed
3822 value (on which @var{p} returns true) to produce
3823 the final/leftmost portion of the constructed string.
3824 It defaults to @code{(lambda (x) )}.
3828 @node Miscellaneous String Operations
3829 @subsubsection Miscellaneous String Operations
3831 @deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3832 @deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3833 This is the @emph{extended substring} procedure that implements
3834 replicated copying of a substring of some string.
3836 @var{s} is a string, @var{start} and @var{end} are optional
3837 arguments that demarcate a substring of @var{s}, defaulting to
3838 0 and the length of @var{s}. Replicate this substring up and
3839 down index space, in both the positive and negative directions.
3840 @code{xsubstring} returns the substring of this string
3841 beginning at index @var{from}, and ending at @var{to}, which
3842 defaults to @var{from} + (@var{end} - @var{start}).
3845 @deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3846 @deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3847 Exactly the same as @code{xsubstring}, but the extracted text
3848 is written into the string @var{target} starting at index
3849 @var{tstart}. The operation is not defined if @code{(eq?
3850 @var{target} @var{s})} or these arguments share storage -- you
3851 cannot copy a string on top of itself.
3854 @deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3855 @deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3856 Return the string @var{s1}, but with the characters
3857 @var{start1} @dots{} @var{end1} replaced by the characters
3858 @var{start2} @dots{} @var{end2} from @var{s2}.
3861 @deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3862 @deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3863 Split the string @var{s} into a list of substrings, where each
3864 substring is a maximal non-empty contiguous sequence of
3865 characters from the character set @var{token_set}, which
3866 defaults to @code{char-set:graphic}.
3867 If @var{start} or @var{end} indices are provided, they restrict
3868 @code{string-tokenize} to operating on the indicated substring
3872 @deffn {Scheme Procedure} string-filter char_pred s [start [end]]
3873 @deffnx {C Function} scm_string_filter (char_pred, s, start, end)
3874 Filter the string @var{s}, retaining only those characters which
3875 satisfy @var{char_pred}.
3877 If @var{char_pred} is a procedure, it is applied to each character as
3878 a predicate, if it is a character, it is tested for equality and if it
3879 is a character set, it is tested for membership.
3882 @deffn {Scheme Procedure} string-delete char_pred s [start [end]]
3883 @deffnx {C Function} scm_string_delete (char_pred, s, start, end)
3884 Delete characters satisfying @var{char_pred} from @var{s}.
3886 If @var{char_pred} is a procedure, it is applied to each character as
3887 a predicate, if it is a character, it is tested for equality and if it
3888 is a character set, it is tested for membership.
3891 @node Conversion to/from C
3892 @subsubsection Conversion to/from C
3894 When creating a Scheme string from a C string or when converting a
3895 Scheme string to a C string, the concept of character encoding becomes
3898 In C, a string is just a sequence of bytes, and the character encoding
3899 describes the relation between these bytes and the actual characters
3900 that make up the string. For Scheme strings, character encoding is
3901 not an issue (most of the time), since in Scheme you never get to see
3902 the bytes, only the characters.
3904 Converting to C and converting from C each have their own challenges.
3906 When converting from C to Scheme, it is important that the sequence of
3907 bytes in the C string be valid with respect to its encoding. ASCII
3908 strings, for example, can't have any bytes greater than 127. An ASCII
3909 byte greater than 127 is considered @emph{ill-formed} and cannot be
3910 converted into a Scheme character.
3912 Problems can occur in the reverse operation as well. Not all character
3913 encodings can hold all possible Scheme characters. Some encodings, like
3914 ASCII for example, can only describe a small subset of all possible
3915 characters. So, when converting to C, one must first decide what to do
3916 with Scheme characters that can't be represented in the C string.
3918 Converting a Scheme string to a C string will often allocate fresh
3919 memory to hold the result. You must take care that this memory is
3920 properly freed eventually. In many cases, this can be achieved by
3921 using @code{scm_dynwind_free} inside an appropriate dynwind context,
3922 @xref{Dynamic Wind}.
3924 @deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3925 @deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3926 Creates a new Scheme string that has the same contents as @var{str} when
3927 interpreted in the locale character encoding of the
3928 @code{current-input-port}.
3930 For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3932 For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3933 @var{str} in bytes, and @var{str} does not need to be null-terminated.
3934 If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3935 null-terminated and the real length will be found with @code{strlen}.
3937 If the C string is ill-formed, an error will be raised.
3940 @deftypefn {C Function} SCM scm_take_locale_string (char *str)
3941 @deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3942 Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3943 respectively, but also frees @var{str} with @code{free} eventually.
3944 Thus, you can use this function when you would free @var{str} anyway
3945 immediately after creating the Scheme string. In certain cases, Guile
3946 can then use @var{str} directly as its internal representation.
3949 @deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3950 @deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
3951 Returns a C string with the same contents as @var{str} in the locale
3952 encoding of the @code{current-output-port}. The C string must be freed
3953 with @code{free} eventually, maybe by using @code{scm_dynwind_free},
3954 @xref{Dynamic Wind}.
3956 For @code{scm_to_locale_string}, the returned string is
3957 null-terminated and an error is signalled when @var{str} contains
3958 @code{#\nul} characters.
3960 For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3961 @var{str} might contain @code{#\nul} characters and the length of the
3962 returned string in bytes is stored in @code{*@var{lenp}}. The
3963 returned string will not be null-terminated in this case. If
3964 @var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3965 @code{scm_to_locale_string}.
3967 If a character in @var{str} cannot be represented in the locale encoding
3968 of the current output port, the port conversion strategy of the current
3969 output port will determine the result, @xref{Ports}. If output port's
3970 conversion strategy is @code{error}, an error will be raised. If it is
3971 @code{subsitute}, a replacement character, such as a question mark, will
3972 be inserted in its place. If it is @code{escape}, a hex escape will be
3973 inserted in its place.
3976 @deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3977 Puts @var{str} as a C string in the current locale encoding into the
3978 memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3979 @var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3980 more than that. No terminating @code{'\0'} will be stored.
3982 The return value of @code{scm_to_locale_stringbuf} is the number of
3983 bytes that are needed for all of @var{str}, regardless of whether
3984 @var{buf} was large enough to hold them. Thus, when the return value
3985 is larger than @var{max_len}, only @var{max_len} bytes have been
3986 stored and you probably need to try again with a larger buffer.
3989 For most situations, string conversion should occur using the current
3990 locale, such as with the functions above. But there may be cases where
3991 one wants to convert strings from a character encoding other than the
3992 locale's character encoding. For these cases, the lower-level functions
3993 @code{scm_to_stringn} and @code{scm_from_stringn} are provided. These
3994 functions should seldom be necessary if one is properly using locales.
3996 @deftp {C Type} scm_t_string_failed_conversion_handler
3997 This is an enumerated type that can take one of three values:
3998 @code{SCM_FAILED_CONVERSION_ERROR},
3999 @code{SCM_FAILED_CONVERSION_QUESTION_MARK}, and
4000 @code{SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE}. They are used to indicate
4001 a strategy for handling characters that cannot be converted to or from a
4002 given character encoding. @code{SCM_FAILED_CONVERSION_ERROR} indicates
4003 that a conversion should throw an error if some characters cannot be
4004 converted. @code{SCM_FAILED_CONVERSION_QUESTION_MARK} indicates that a
4005 conversion should replace unconvertable characters with the question
4006 mark character. And, @code{SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE}
4007 requests that a conversion should replace an unconvertable character
4008 with an escape sequence.
4010 While all three strategies apply when converting Scheme strings to C,
4011 only @code{SCM_FAILED_CONVERSION_ERROR} and
4012 @code{SCM_FAILED_CONVERSION_QUESTION_MARK} can be used when converting C
4016 @deftypefn {C Function} char *scm_to_stringn (SCM str, size_t *lenp, const char *encoding, scm_t_string_failed_conversion_handler handler)
4017 This function returns a newly allocated C string from the Guile string
4018 @var{str}. The length of the string will be returned in @var{lenp}.
4019 The character encoding of the C string is passed as the ASCII,
4020 null-terminated C string @var{encoding}. The @var{handler} parameter
4021 gives a strategy for dealing with characters that cannot be converted
4022 into @var{encoding}.
4024 If @var{lenp} is NULL, this function will return a null-terminated C
4025 string. It will throw an error if the string contains a null
4029 @deftypefn {C Function} SCM scm_from_stringn (const char *str, size_t len, const char *encoding, scm_t_string_failed_conversion_handler handler)
4030 This function returns a scheme string from the C string @var{str}. The
4031 length of the C string is input as @var{len}. The encoding of the C
4032 string is passed as the ASCII, null-terminated C string @code{encoding}.
4033 The @var{handler} parameters suggests a strategy for dealing with
4034 unconvertable characters.
4037 ISO-8859-1 is the most common 8-bit character encoding. This encoding
4038 is also referred to as the Latin-1 encoding. The following two
4039 conversion functions are provided to convert between Latin-1 C strings
4042 @deftypefn {C Function} SCM scm_from_latin1_stringn (const char *str, size_t len)
4043 @deftypefnx {C Function} SCM scm_from_utf8_stringn (const char *str, size_t len)
4044 @deftypefnx {C Function} SCM scm_from_utf32_stringn (const scm_t_wchar *str, size_t len)
4045 Return a scheme string from C string @var{str}, which is ISO-8859-1-,
4046 UTF-8-, or UTF-32-encoded, of length @var{len}. @var{len} is the number
4047 of bytes pointed to by @var{str} for @code{scm_from_latin1_stringn} and
4048 @code{scm_from_utf8_stringn}; it is the number of elements (code points)
4049 in @var{str} in the case of @code{scm_from_utf32_stringn}.
4052 @deftypefn {C function} char *scm_to_latin1_stringn (SCM str, size_t *lenp)
4053 @deftypefnx {C function} char *scm_to_utf8_stringn (SCM str, size_t *lenp)
4054 @deftypefnx {C function} scm_t_wchar *scm_to_utf32_stringn (SCM str, size_t *lenp)
4055 Return a newly allocated, ISO-8859-1-, UTF-8-, or UTF-32-encoded C string
4056 from Scheme string @var{str}. An error is thrown when @var{str}
4057 string cannot be converted to the specified encoding. If @var{lenp} is
4058 @code{NULL}, the returned C string will be null terminated, and an error
4059 will be thrown if the C string would otherwise contain null
4060 characters. If @var{lenp} is not NULL, the length of the string is
4061 returned in @var{lenp}, and the string is not null terminated.
4064 @node String Internals
4065 @subsubsection String Internals
4067 Guile stores each string in memory as a contiguous array of Unicode code
4068 points along with an associated set of attributes. If all of the code
4069 points of a string have an integer range between 0 and 255 inclusive,
4070 the code point array is stored as one byte per code point: it is stored
4071 as an ISO-8859-1 (aka Latin-1) string. If any of the code points of the
4072 string has an integer value greater that 255, the code point array is
4073 stored as four bytes per code point: it is stored as a UTF-32 string.
4075 Conversion between the one-byte-per-code-point and
4076 four-bytes-per-code-point representations happens automatically as
4079 No API is provided to set the internal representation of strings;
4080 however, there are pair of procedures available to query it. These are
4081 debugging procedures. Using them in production code is discouraged,
4082 since the details of Guile's internal representation of strings may
4083 change from release to release.
4085 @deffn {Scheme Procedure} string-bytes-per-char str
4086 @deffnx {C Function} scm_string_bytes_per_char (str)
4087 Return the number of bytes used to encode a Unicode code point in string
4088 @var{str}. The result is one or four.
4091 @deffn {Scheme Procedure} %string-dump str
4092 @deffnx {C Function} scm_sys_string_dump (str)
4093 Returns an association list containing debugging information for
4094 @var{str}. The association list has the following entries.
4101 The start index of the string into its stringbuf
4104 The length of the string
4107 If this string is a substring, it returns its
4108 parent string. Otherwise, it returns @code{#f}
4111 @code{#t} if the string is read-only
4113 @item stringbuf-chars
4114 A new string containing this string's stringbuf's characters
4116 @item stringbuf-length
4117 The number of characters in this stringbuf
4119 @item stringbuf-shared
4120 @code{#t} if this stringbuf is shared
4122 @item stringbuf-wide
4123 @code{#t} if this stringbuf's characters are stored in a 32-bit buffer,
4124 or @code{#f} if they are stored in an 8-bit buffer
4130 @subsection Bytevectors
4135 A @dfn{bytevector} is a raw bit string. The @code{(rnrs bytevectors)}
4136 module provides the programming interface specified by the
4137 @uref{http://www.r6rs.org/, Revised^6 Report on the Algorithmic Language
4138 Scheme (R6RS)}. It contains procedures to manipulate bytevectors and
4139 interpret their contents in a number of ways: bytevector contents can be
4140 accessed as signed or unsigned integer of various sizes and endianness,
4141 as IEEE-754 floating point numbers, or as strings. It is a useful tool
4142 to encode and decode binary data.
4144 The R6RS (Section 4.3.4) specifies an external representation for
4145 bytevectors, whereby the octets (integers in the range 0--255) contained
4146 in the bytevector are represented as a list prefixed by @code{#vu8}:
4152 denotes a 3-byte bytevector containing the octets 1, 53, and 204. Like
4153 string literals, booleans, etc., bytevectors are ``self-quoting'', i.e.,
4154 they do not need to be quoted:
4158 @result{} #vu8(1 53 204)
4161 Bytevectors can be used with the binary input/output primitives of the
4162 R6RS (@pxref{R6RS I/O Ports}).
4165 * Bytevector Endianness:: Dealing with byte order.
4166 * Bytevector Manipulation:: Creating, copying, manipulating bytevectors.
4167 * Bytevectors as Integers:: Interpreting bytes as integers.
4168 * Bytevectors and Integer Lists:: Converting to/from an integer list.
4169 * Bytevectors as Floats:: Interpreting bytes as real numbers.
4170 * Bytevectors as Strings:: Interpreting bytes as Unicode strings.
4171 * Bytevectors as Generalized Vectors:: Guile extension to the bytevector API.
4172 * Bytevectors as Uniform Vectors:: Bytevectors and SRFI-4.
4175 @node Bytevector Endianness
4176 @subsubsection Endianness
4182 Some of the following procedures take an @var{endianness} parameter.
4183 The @dfn{endianness} is defined as the order of bytes in multi-byte
4184 numbers: numbers encoded in @dfn{big endian} have their most
4185 significant bytes written first, whereas numbers encoded in
4186 @dfn{little endian} have their least significant bytes
4187 first@footnote{Big-endian and little-endian are the most common
4188 ``endiannesses'', but others do exist. For instance, the GNU MP
4189 library allows @dfn{word order} to be specified independently of
4190 @dfn{byte order} (@pxref{Integer Import and Export,,, gmp, The GNU
4191 Multiple Precision Arithmetic Library Manual}).}.
4193 Little-endian is the native endianness of the IA32 architecture and
4194 its derivatives, while big-endian is native to SPARC and PowerPC,
4195 among others. The @code{native-endianness} procedure returns the
4196 native endianness of the machine it runs on.
4198 @deffn {Scheme Procedure} native-endianness
4199 @deffnx {C Function} scm_native_endianness ()
4200 Return a value denoting the native endianness of the host machine.
4203 @deffn {Scheme Macro} endianness symbol
4204 Return an object denoting the endianness specified by @var{symbol}. If
4205 @var{symbol} is neither @code{big} nor @code{little} then an error is
4206 raised at expand-time.
4209 @defvr {C Variable} scm_endianness_big
4210 @defvrx {C Variable} scm_endianness_little
4211 The objects denoting big- and little-endianness, respectively.
4215 @node Bytevector Manipulation
4216 @subsubsection Manipulating Bytevectors
4218 Bytevectors can be created, copied, and analyzed with the following
4219 procedures and C functions.
4221 @deffn {Scheme Procedure} make-bytevector len [fill]
4222 @deffnx {C Function} scm_make_bytevector (len, fill)
4223 @deffnx {C Function} scm_c_make_bytevector (size_t len)
4224 Return a new bytevector of @var{len} bytes. Optionally, if @var{fill}
4225 is given, fill it with @var{fill}; @var{fill} must be in the range
4229 @deffn {Scheme Procedure} bytevector? obj
4230 @deffnx {C Function} scm_bytevector_p (obj)
4231 Return true if @var{obj} is a bytevector.
4234 @deftypefn {C Function} int scm_is_bytevector (SCM obj)
4235 Equivalent to @code{scm_is_true (scm_bytevector_p (obj))}.
4238 @deffn {Scheme Procedure} bytevector-length bv
4239 @deffnx {C Function} scm_bytevector_length (bv)
4240 Return the length in bytes of bytevector @var{bv}.
4243 @deftypefn {C Function} size_t scm_c_bytevector_length (SCM bv)
4244 Likewise, return the length in bytes of bytevector @var{bv}.
4247 @deffn {Scheme Procedure} bytevector=? bv1 bv2
4248 @deffnx {C Function} scm_bytevector_eq_p (bv1, bv2)
4249 Return is @var{bv1} equals to @var{bv2}---i.e., if they have the same
4250 length and contents.
4253 @deffn {Scheme Procedure} bytevector-fill! bv fill
4254 @deffnx {C Function} scm_bytevector_fill_x (bv, fill)
4255 Fill bytevector @var{bv} with @var{fill}, a byte.
4258 @deffn {Scheme Procedure} bytevector-copy! source source-start target target-start len
4259 @deffnx {C Function} scm_bytevector_copy_x (source, source_start, target, target_start, len)
4260 Copy @var{len} bytes from @var{source} into @var{target}, starting
4261 reading from @var{source-start} (a positive index within @var{source})
4262 and start writing at @var{target-start}.
4265 @deffn {Scheme Procedure} bytevector-copy bv
4266 @deffnx {C Function} scm_bytevector_copy (bv)
4267 Return a newly allocated copy of @var{bv}.
4270 @deftypefn {C Function} scm_t_uint8 scm_c_bytevector_ref (SCM bv, size_t index)
4271 Return the byte at @var{index} in bytevector @var{bv}.
4274 @deftypefn {C Function} void scm_c_bytevector_set_x (SCM bv, size_t index, scm_t_uint8 value)
4275 Set the byte at @var{index} in @var{bv} to @var{value}.
4278 Low-level C macros are available. They do not perform any
4279 type-checking; as such they should be used with care.
4281 @deftypefn {C Macro} size_t SCM_BYTEVECTOR_LENGTH (bv)
4282 Return the length in bytes of bytevector @var{bv}.
4285 @deftypefn {C Macro} {signed char *} SCM_BYTEVECTOR_CONTENTS (bv)
4286 Return a pointer to the contents of bytevector @var{bv}.
4290 @node Bytevectors as Integers
4291 @subsubsection Interpreting Bytevector Contents as Integers
4293 The contents of a bytevector can be interpreted as a sequence of
4294 integers of any given size, sign, and endianness.
4297 (let ((bv (make-bytevector 4)))
4298 (bytevector-u8-set! bv 0 #x12)
4299 (bytevector-u8-set! bv 1 #x34)
4300 (bytevector-u8-set! bv 2 #x56)
4301 (bytevector-u8-set! bv 3 #x78)
4303 (map (lambda (number)
4304 (number->string number 16))
4305 (list (bytevector-u8-ref bv 0)
4306 (bytevector-u16-ref bv 0 (endianness big))
4307 (bytevector-u32-ref bv 0 (endianness little)))))
4309 @result{} ("12" "1234" "78563412")
4312 The most generic procedures to interpret bytevector contents as integers
4313 are described below.
4315 @deffn {Scheme Procedure} bytevector-uint-ref bv index endianness size
4316 @deffnx {Scheme Procedure} bytevector-sint-ref bv index endianness size
4317 @deffnx {C Function} scm_bytevector_uint_ref (bv, index, endianness, size)
4318 @deffnx {C Function} scm_bytevector_sint_ref (bv, index, endianness, size)
4319 Return the @var{size}-byte long unsigned (resp. signed) integer at
4320 index @var{index} in @var{bv}, decoded according to @var{endianness}.
4323 @deffn {Scheme Procedure} bytevector-uint-set! bv index value endianness size
4324 @deffnx {Scheme Procedure} bytevector-sint-set! bv index value endianness size
4325 @deffnx {C Function} scm_bytevector_uint_set_x (bv, index, value, endianness, size)
4326 @deffnx {C Function} scm_bytevector_sint_set_x (bv, index, value, endianness, size)
4327 Set the @var{size}-byte long unsigned (resp. signed) integer at
4328 @var{index} to @var{value}, encoded according to @var{endianness}.
4331 The following procedures are similar to the ones above, but specialized
4332 to a given integer size:
4334 @deffn {Scheme Procedure} bytevector-u8-ref bv index
4335 @deffnx {Scheme Procedure} bytevector-s8-ref bv index
4336 @deffnx {Scheme Procedure} bytevector-u16-ref bv index endianness
4337 @deffnx {Scheme Procedure} bytevector-s16-ref bv index endianness
4338 @deffnx {Scheme Procedure} bytevector-u32-ref bv index endianness
4339 @deffnx {Scheme Procedure} bytevector-s32-ref bv index endianness
4340 @deffnx {Scheme Procedure} bytevector-u64-ref bv index endianness
4341 @deffnx {Scheme Procedure} bytevector-s64-ref bv index endianness
4342 @deffnx {C Function} scm_bytevector_u8_ref (bv, index)
4343 @deffnx {C Function} scm_bytevector_s8_ref (bv, index)
4344 @deffnx {C Function} scm_bytevector_u16_ref (bv, index, endianness)
4345 @deffnx {C Function} scm_bytevector_s16_ref (bv, index, endianness)
4346 @deffnx {C Function} scm_bytevector_u32_ref (bv, index, endianness)
4347 @deffnx {C Function} scm_bytevector_s32_ref (bv, index, endianness)
4348 @deffnx {C Function} scm_bytevector_u64_ref (bv, index, endianness)
4349 @deffnx {C Function} scm_bytevector_s64_ref (bv, index, endianness)
4350 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4351 16, 32 or 64) from @var{bv} at @var{index}, decoded according to
4355 @deffn {Scheme Procedure} bytevector-u8-set! bv index value
4356 @deffnx {Scheme Procedure} bytevector-s8-set! bv index value
4357 @deffnx {Scheme Procedure} bytevector-u16-set! bv index value endianness
4358 @deffnx {Scheme Procedure} bytevector-s16-set! bv index value endianness
4359 @deffnx {Scheme Procedure} bytevector-u32-set! bv index value endianness
4360 @deffnx {Scheme Procedure} bytevector-s32-set! bv index value endianness
4361 @deffnx {Scheme Procedure} bytevector-u64-set! bv index value endianness
4362 @deffnx {Scheme Procedure} bytevector-s64-set! bv index value endianness
4363 @deffnx {C Function} scm_bytevector_u8_set_x (bv, index, value)
4364 @deffnx {C Function} scm_bytevector_s8_set_x (bv, index, value)
4365 @deffnx {C Function} scm_bytevector_u16_set_x (bv, index, value, endianness)
4366 @deffnx {C Function} scm_bytevector_s16_set_x (bv, index, value, endianness)
4367 @deffnx {C Function} scm_bytevector_u32_set_x (bv, index, value, endianness)
4368 @deffnx {C Function} scm_bytevector_s32_set_x (bv, index, value, endianness)
4369 @deffnx {C Function} scm_bytevector_u64_set_x (bv, index, value, endianness)
4370 @deffnx {C Function} scm_bytevector_s64_set_x (bv, index, value, endianness)
4371 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4372 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to
4376 Finally, a variant specialized for the host's endianness is available
4377 for each of these functions (with the exception of the @code{u8}
4378 accessors, for obvious reasons):
4380 @deffn {Scheme Procedure} bytevector-u16-native-ref bv index
4381 @deffnx {Scheme Procedure} bytevector-s16-native-ref bv index
4382 @deffnx {Scheme Procedure} bytevector-u32-native-ref bv index
4383 @deffnx {Scheme Procedure} bytevector-s32-native-ref bv index
4384 @deffnx {Scheme Procedure} bytevector-u64-native-ref bv index
4385 @deffnx {Scheme Procedure} bytevector-s64-native-ref bv index
4386 @deffnx {C Function} scm_bytevector_u16_native_ref (bv, index)
4387 @deffnx {C Function} scm_bytevector_s16_native_ref (bv, index)
4388 @deffnx {C Function} scm_bytevector_u32_native_ref (bv, index)
4389 @deffnx {C Function} scm_bytevector_s32_native_ref (bv, index)
4390 @deffnx {C Function} scm_bytevector_u64_native_ref (bv, index)
4391 @deffnx {C Function} scm_bytevector_s64_native_ref (bv, index)
4392 Return the unsigned @var{n}-bit (signed) integer (where @var{n} is 8,
4393 16, 32 or 64) from @var{bv} at @var{index}, decoded according to the
4394 host's native endianness.
4397 @deffn {Scheme Procedure} bytevector-u16-native-set! bv index value
4398 @deffnx {Scheme Procedure} bytevector-s16-native-set! bv index value
4399 @deffnx {Scheme Procedure} bytevector-u32-native-set! bv index value
4400 @deffnx {Scheme Procedure} bytevector-s32-native-set! bv index value
4401 @deffnx {Scheme Procedure} bytevector-u64-native-set! bv index value
4402 @deffnx {Scheme Procedure} bytevector-s64-native-set! bv index value
4403 @deffnx {C Function} scm_bytevector_u16_native_set_x (bv, index, value)
4404 @deffnx {C Function} scm_bytevector_s16_native_set_x (bv, index, value)
4405 @deffnx {C Function} scm_bytevector_u32_native_set_x (bv, index, value)
4406 @deffnx {C Function} scm_bytevector_s32_native_set_x (bv, index, value)
4407 @deffnx {C Function} scm_bytevector_u64_native_set_x (bv, index, value)
4408 @deffnx {C Function} scm_bytevector_s64_native_set_x (bv, index, value)
4409 Store @var{value} as an @var{n}-bit (signed) integer (where @var{n} is
4410 8, 16, 32 or 64) in @var{bv} at @var{index}, encoded according to the
4411 host's native endianness.
4415 @node Bytevectors and Integer Lists
4416 @subsubsection Converting Bytevectors to/from Integer Lists
4418 Bytevector contents can readily be converted to/from lists of signed or
4422 (bytevector->sint-list (u8-list->bytevector (make-list 4 255))
4423 (endianness little) 2)
4427 @deffn {Scheme Procedure} bytevector->u8-list bv
4428 @deffnx {C Function} scm_bytevector_to_u8_list (bv)
4429 Return a newly allocated list of unsigned 8-bit integers from the
4430 contents of @var{bv}.
4433 @deffn {Scheme Procedure} u8-list->bytevector lst
4434 @deffnx {C Function} scm_u8_list_to_bytevector (lst)
4435 Return a newly allocated bytevector consisting of the unsigned 8-bit
4436 integers listed in @var{lst}.
4439 @deffn {Scheme Procedure} bytevector->uint-list bv endianness size
4440 @deffnx {Scheme Procedure} bytevector->sint-list bv endianness size
4441 @deffnx {C Function} scm_bytevector_to_uint_list (bv, endianness, size)
4442 @deffnx {C Function} scm_bytevector_to_sint_list (bv, endianness, size)
4443 Return a list of unsigned (resp. signed) integers of @var{size} bytes
4444 representing the contents of @var{bv}, decoded according to
4448 @deffn {Scheme Procedure} uint-list->bytevector lst endianness size
4449 @deffnx {Scheme Procedure} sint-list->bytevector lst endianness size
4450 @deffnx {C Function} scm_uint_list_to_bytevector (lst, endianness, size)
4451 @deffnx {C Function} scm_sint_list_to_bytevector (lst, endianness, size)
4452 Return a new bytevector containing the unsigned (resp. signed) integers
4453 listed in @var{lst} and encoded on @var{size} bytes according to
4457 @node Bytevectors as Floats
4458 @subsubsection Interpreting Bytevector Contents as Floating Point Numbers
4460 @cindex IEEE-754 floating point numbers
4462 Bytevector contents can also be accessed as IEEE-754 single- or
4463 double-precision floating point numbers (respectively 32 and 64-bit
4464 long) using the procedures described here.
4466 @deffn {Scheme Procedure} bytevector-ieee-single-ref bv index endianness
4467 @deffnx {Scheme Procedure} bytevector-ieee-double-ref bv index endianness
4468 @deffnx {C Function} scm_bytevector_ieee_single_ref (bv, index, endianness)
4469 @deffnx {C Function} scm_bytevector_ieee_double_ref (bv, index, endianness)
4470 Return the IEEE-754 single-precision floating point number from @var{bv}
4471 at @var{index} according to @var{endianness}.
4474 @deffn {Scheme Procedure} bytevector-ieee-single-set! bv index value endianness
4475 @deffnx {Scheme Procedure} bytevector-ieee-double-set! bv index value endianness
4476 @deffnx {C Function} scm_bytevector_ieee_single_set_x (bv, index, value, endianness)
4477 @deffnx {C Function} scm_bytevector_ieee_double_set_x (bv, index, value, endianness)
4478 Store real number @var{value} in @var{bv} at @var{index} according to
4482 Specialized procedures are also available:
4484 @deffn {Scheme Procedure} bytevector-ieee-single-native-ref bv index
4485 @deffnx {Scheme Procedure} bytevector-ieee-double-native-ref bv index
4486 @deffnx {C Function} scm_bytevector_ieee_single_native_ref (bv, index)
4487 @deffnx {C Function} scm_bytevector_ieee_double_native_ref (bv, index)
4488 Return the IEEE-754 single-precision floating point number from @var{bv}
4489 at @var{index} according to the host's native endianness.
4492 @deffn {Scheme Procedure} bytevector-ieee-single-native-set! bv index value
4493 @deffnx {Scheme Procedure} bytevector-ieee-double-native-set! bv index value
4494 @deffnx {C Function} scm_bytevector_ieee_single_native_set_x (bv, index, value)
4495 @deffnx {C Function} scm_bytevector_ieee_double_native_set_x (bv, index, value)
4496 Store real number @var{value} in @var{bv} at @var{index} according to
4497 the host's native endianness.
4501 @node Bytevectors as Strings
4502 @subsubsection Interpreting Bytevector Contents as Unicode Strings
4504 @cindex Unicode string encoding
4506 Bytevector contents can also be interpreted as Unicode strings encoded
4507 in one of the most commonly available encoding formats.
4510 (utf8->string (u8-list->bytevector '(99 97 102 101)))
4513 (string->utf8 "caf@'e") ;; SMALL LATIN LETTER E WITH ACUTE ACCENT
4514 @result{} #vu8(99 97 102 195 169)
4517 @deffn {Scheme Procedure} string->utf8 str
4518 @deffnx {Scheme Procedure} string->utf16 str [endianness]
4519 @deffnx {Scheme Procedure} string->utf32 str [endianness]
4520 @deffnx {C Function} scm_string_to_utf8 (str)
4521 @deffnx {C Function} scm_string_to_utf16 (str, endianness)
4522 @deffnx {C Function} scm_string_to_utf32 (str, endianness)
4523 Return a newly allocated bytevector that contains the UTF-8, UTF-16, or
4524 UTF-32 (aka. UCS-4) encoding of @var{str}. For UTF-16 and UTF-32,
4525 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4526 it defaults to big endian.
4529 @deffn {Scheme Procedure} utf8->string utf
4530 @deffnx {Scheme Procedure} utf16->string utf [endianness]
4531 @deffnx {Scheme Procedure} utf32->string utf [endianness]
4532 @deffnx {C Function} scm_utf8_to_string (utf)
4533 @deffnx {C Function} scm_utf16_to_string (utf, endianness)
4534 @deffnx {C Function} scm_utf32_to_string (utf, endianness)
4535 Return a newly allocated string that contains from the UTF-8-, UTF-16-,
4536 or UTF-32-decoded contents of bytevector @var{utf}. For UTF-16 and UTF-32,
4537 @var{endianness} should be the symbol @code{big} or @code{little}; when omitted,
4538 it defaults to big endian.
4541 @node Bytevectors as Generalized Vectors
4542 @subsubsection Accessing Bytevectors with the Generalized Vector API
4544 As an extension to the R6RS, Guile allows bytevectors to be manipulated
4545 with the @dfn{generalized vector} procedures (@pxref{Generalized
4546 Vectors}). This also allows bytevectors to be accessed using the
4547 generic @dfn{array} procedures (@pxref{Array Procedures}). When using
4548 these APIs, bytes are accessed one at a time as 8-bit unsigned integers:
4551 (define bv #vu8(0 1 2 3))
4553 (generalized-vector? bv)
4556 (generalized-vector-ref bv 2)
4559 (generalized-vector-set! bv 2 77)
4568 @node Bytevectors as Uniform Vectors
4569 @subsubsection Accessing Bytevectors with the SRFI-4 API
4571 Bytevectors may also be accessed with the SRFI-4 API. @xref{SRFI-4 and
4572 Bytevectors}, for more information.
4579 Symbols in Scheme are widely used in three ways: as items of discrete
4580 data, as lookup keys for alists and hash tables, and to denote variable
4583 A @dfn{symbol} is similar to a string in that it is defined by a
4584 sequence of characters. The sequence of characters is known as the
4585 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
4586 name doesn't include any characters that could be confused with other
4587 elements of Scheme syntax --- a symbol is written in a Scheme program by
4588 writing the sequence of characters that make up the name, @emph{without}
4589 any quotation marks or other special syntax. For example, the symbol
4590 whose name is ``multiply-by-2'' is written, simply:
4596 Notice how this differs from a @emph{string} with contents
4597 ``multiply-by-2'', which is written with double quotation marks, like
4604 Looking beyond how they are written, symbols are different from strings
4605 in two important respects.
4607 The first important difference is uniqueness. If the same-looking
4608 string is read twice from two different places in a program, the result
4609 is two @emph{different} string objects whose contents just happen to be
4610 the same. If, on the other hand, the same-looking symbol is read twice
4611 from two different places in a program, the result is the @emph{same}
4612 symbol object both times.
4614 Given two read symbols, you can use @code{eq?} to test whether they are
4615 the same (that is, have the same name). @code{eq?} is the most
4616 efficient comparison operator in Scheme, and comparing two symbols like
4617 this is as fast as comparing, for example, two numbers. Given two
4618 strings, on the other hand, you must use @code{equal?} or
4619 @code{string=?}, which are much slower comparison operators, to
4620 determine whether the strings have the same contents.
4623 (define sym1 (quote hello))
4624 (define sym2 (quote hello))
4625 (eq? sym1 sym2) @result{} #t
4627 (define str1 "hello")
4628 (define str2 "hello")
4629 (eq? str1 str2) @result{} #f
4630 (equal? str1 str2) @result{} #t
4633 The second important difference is that symbols, unlike strings, are not
4634 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
4635 example above: @code{(quote hello)} evaluates to the symbol named
4636 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
4637 symbol named "hello" and evaluated as a variable reference @dots{} about
4638 which more below (@pxref{Symbol Variables}).
4641 * Symbol Data:: Symbols as discrete data.
4642 * Symbol Keys:: Symbols as lookup keys.
4643 * Symbol Variables:: Symbols as denoting variables.
4644 * Symbol Primitives:: Operations related to symbols.
4645 * Symbol Props:: Function slots and property lists.
4646 * Symbol Read Syntax:: Extended read syntax for symbols.
4647 * Symbol Uninterned:: Uninterned symbols.
4652 @subsubsection Symbols as Discrete Data
4654 Numbers and symbols are similar to the extent that they both lend
4655 themselves to @code{eq?} comparison. But symbols are more descriptive
4656 than numbers, because a symbol's name can be used directly to describe
4657 the concept for which that symbol stands.
4659 For example, imagine that you need to represent some colours in a
4660 computer program. Using numbers, you would have to choose arbitrarily
4661 some mapping between numbers and colours, and then take care to use that
4662 mapping consistently:
4665 ;; 1=red, 2=green, 3=purple
4667 (if (eq? (colour-of car) 1)
4672 You can make the mapping more explicit and the code more readable by
4680 (if (eq? (colour-of car) red)
4685 But the simplest and clearest approach is not to use numbers at all, but
4686 symbols whose names specify the colours that they refer to:
4689 (if (eq? (colour-of car) 'red)
4693 The descriptive advantages of symbols over numbers increase as the set
4694 of concepts that you want to describe grows. Suppose that a car object
4695 can have other properties as well, such as whether it has or uses:
4699 automatic or manual transmission
4701 leaded or unleaded fuel
4703 power steering (or not).
4707 Then a car's combined property set could be naturally represented and
4708 manipulated as a list of symbols:
4711 (properties-of car1)
4713 (red manual unleaded power-steering)
4715 (if (memq 'power-steering (properties-of car1))
4716 (display "Unfit people can drive this car.\n")
4717 (display "You'll need strong arms to drive this car!\n"))
4719 Unfit people can drive this car.
4722 Remember, the fundamental property of symbols that we are relying on
4723 here is that an occurrence of @code{'red} in one part of a program is an
4724 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
4725 another part of a program; this means that symbols can usefully be
4726 compared using @code{eq?}. At the same time, symbols have naturally
4727 descriptive names. This combination of efficiency and descriptive power
4728 makes them ideal for use as discrete data.
4732 @subsubsection Symbols as Lookup Keys
4734 Given their efficiency and descriptive power, it is natural to use
4735 symbols as the keys in an association list or hash table.
4737 To illustrate this, consider a more structured representation of the car
4738 properties example from the preceding subsection. Rather than
4739 mixing all the properties up together in a flat list, we could use an
4740 association list like this:
4743 (define car1-properties '((colour . red)
4744 (transmission . manual)
4746 (steering . power-assisted)))
4749 Notice how this structure is more explicit and extensible than the flat
4750 list. For example it makes clear that @code{manual} refers to the
4751 transmission rather than, say, the windows or the locking of the car.
4752 It also allows further properties to use the same symbols among their
4753 possible values without becoming ambiguous:
4756 (define car1-properties '((colour . red)
4757 (transmission . manual)
4759 (steering . power-assisted)
4761 (locking . manual)))
4764 With a representation like this, it is easy to use the efficient
4765 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
4766 extract or change individual pieces of information:
4769 (assq-ref car1-properties 'fuel) @result{} unleaded
4770 (assq-ref car1-properties 'transmission) @result{} manual
4772 (assq-set! car1-properties 'seat-colour 'black)
4775 (transmission . manual)
4777 (steering . power-assisted)
4778 (seat-colour . black)
4779 (locking . manual)))
4782 Hash tables also have keys, and exactly the same arguments apply to the
4783 use of symbols in hash tables as in association lists. The hash value
4784 that Guile uses to decide where to add a symbol-keyed entry to a hash
4785 table can be obtained by calling the @code{symbol-hash} procedure:
4787 @deffn {Scheme Procedure} symbol-hash symbol
4788 @deffnx {C Function} scm_symbol_hash (symbol)
4789 Return a hash value for @var{symbol}.
4792 See @ref{Hash Tables} for information about hash tables in general, and
4793 for why you might choose to use a hash table rather than an association
4797 @node Symbol Variables
4798 @subsubsection Symbols as Denoting Variables
4800 When an unquoted symbol in a Scheme program is evaluated, it is
4801 interpreted as a variable reference, and the result of the evaluation is
4802 the appropriate variable's value.
4804 For example, when the expression @code{(string-length "abcd")} is read
4805 and evaluated, the sequence of characters @code{string-length} is read
4806 as the symbol whose name is "string-length". This symbol is associated
4807 with a variable whose value is the procedure that implements string
4808 length calculation. Therefore evaluation of the @code{string-length}
4809 symbol results in that procedure.
4811 The details of the connection between an unquoted symbol and the
4812 variable to which it refers are explained elsewhere. See @ref{Binding
4813 Constructs}, for how associations between symbols and variables are
4814 created, and @ref{Modules}, for how those associations are affected by
4815 Guile's module system.
4818 @node Symbol Primitives
4819 @subsubsection Operations Related to Symbols
4821 Given any Scheme value, you can determine whether it is a symbol using
4822 the @code{symbol?} primitive:
4825 @deffn {Scheme Procedure} symbol? obj
4826 @deffnx {C Function} scm_symbol_p (obj)
4827 Return @code{#t} if @var{obj} is a symbol, otherwise return
4831 @deftypefn {C Function} int scm_is_symbol (SCM val)
4832 Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
4835 Once you know that you have a symbol, you can obtain its name as a
4836 string by calling @code{symbol->string}. Note that Guile differs by
4837 default from R5RS on the details of @code{symbol->string} as regards
4840 @rnindex symbol->string
4841 @deffn {Scheme Procedure} symbol->string s
4842 @deffnx {C Function} scm_symbol_to_string (s)
4843 Return the name of symbol @var{s} as a string. By default, Guile reads
4844 symbols case-sensitively, so the string returned will have the same case
4845 variation as the sequence of characters that caused @var{s} to be
4848 If Guile is set to read symbols case-insensitively (as specified by
4849 R5RS), and @var{s} comes into being as part of a literal expression
4850 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
4851 by a call to the @code{read} or @code{string-ci->symbol} procedures,
4852 Guile converts any alphabetic characters in the symbol's name to
4853 lower case before creating the symbol object, so the string returned
4854 here will be in lower case.
4856 If @var{s} was created by @code{string->symbol}, the case of characters
4857 in the string returned will be the same as that in the string that was
4858 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
4859 setting at the time @var{s} was created.
4861 It is an error to apply mutation procedures like @code{string-set!} to
4862 strings returned by this procedure.
4865 Most symbols are created by writing them literally in code. However it
4866 is also possible to create symbols programmatically using the following
4869 @deffn {Scheme Procedure} symbol char@dots{}
4871 Return a newly allocated symbol made from the given character arguments.
4874 (symbol #\x #\y #\z) @result{} xyz
4878 @deffn {Scheme Procedure} list->symbol lst
4879 @rnindex list->symbol
4880 Return a newly allocated symbol made from a list of characters.
4883 (list->symbol '(#\a #\b #\c)) @result{} abc
4887 @rnindex symbol-append
4888 @deffn {Scheme Procedure} symbol-append . args
4889 Return a newly allocated symbol whose characters form the
4890 concatenation of the given symbols, @var{args}.
4894 (symbol-append h 'world))
4895 @result{} helloworld
4899 @rnindex string->symbol
4900 @deffn {Scheme Procedure} string->symbol string
4901 @deffnx {C Function} scm_string_to_symbol (string)
4902 Return the symbol whose name is @var{string}. This procedure can create
4903 symbols with names containing special characters or letters in the
4904 non-standard case, but it is usually a bad idea to create such symbols
4905 because in some implementations of Scheme they cannot be read as
4909 @deffn {Scheme Procedure} string-ci->symbol str
4910 @deffnx {C Function} scm_string_ci_to_symbol (str)
4911 Return the symbol whose name is @var{str}. If Guile is currently
4912 reading symbols case-insensitively, @var{str} is converted to lowercase
4913 before the returned symbol is looked up or created.
4916 The following examples illustrate Guile's detailed behaviour as regards
4917 the case-sensitivity of symbols:
4920 (read-enable 'case-insensitive) ; R5RS compliant behaviour
4922 (symbol->string 'flying-fish) @result{} "flying-fish"
4923 (symbol->string 'Martin) @result{} "martin"
4925 (string->symbol "Malvina")) @result{} "Malvina"
4927 (eq? 'mISSISSIppi 'mississippi) @result{} #t
4928 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4929 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
4931 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4932 (string=? "K. Harper, M.D."
4934 (string->symbol "K. Harper, M.D."))) @result{} #t
4936 (read-disable 'case-insensitive) ; Guile default behaviour
4938 (symbol->string 'flying-fish) @result{} "flying-fish"
4939 (symbol->string 'Martin) @result{} "Martin"
4941 (string->symbol "Malvina")) @result{} "Malvina"
4943 (eq? 'mISSISSIppi 'mississippi) @result{} #f
4944 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4945 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
4947 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4948 (string=? "K. Harper, M.D."
4950 (string->symbol "K. Harper, M.D."))) @result{} #t
4953 From C, there are lower level functions that construct a Scheme symbol
4954 from a C string in the current locale encoding.
4956 When you want to do more from C, you should convert between symbols
4957 and strings using @code{scm_symbol_to_string} and
4958 @code{scm_string_to_symbol} and work with the strings.
4960 @deffn {C Function} scm_from_locale_symbol (const char *name)
4961 @deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
4962 Construct and return a Scheme symbol whose name is specified by
4963 @var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
4964 terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
4965 specified explicitly by @var{len}.
4968 @deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
4969 @deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
4970 Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
4971 respectively, but also frees @var{str} with @code{free} eventually.
4972 Thus, you can use this function when you would free @var{str} anyway
4973 immediately after creating the Scheme string. In certain cases, Guile
4974 can then use @var{str} directly as its internal representation.
4977 The size of a symbol can also be obtained from C:
4979 @deftypefn {C Function} size_t scm_c_symbol_length (SCM sym)
4980 Return the number of characters in @var{sym}.
4983 Finally, some applications, especially those that generate new Scheme
4984 code dynamically, need to generate symbols for use in the generated
4985 code. The @code{gensym} primitive meets this need:
4987 @deffn {Scheme Procedure} gensym [prefix]
4988 @deffnx {C Function} scm_gensym (prefix)
4989 Create a new symbol with a name constructed from a prefix and a counter
4990 value. The string @var{prefix} can be specified as an optional
4991 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
4992 at each call. There is no provision for resetting the counter.
4995 The symbols generated by @code{gensym} are @emph{likely} to be unique,
4996 since their names begin with a space and it is only otherwise possible
4997 to generate such symbols if a programmer goes out of their way to do
4998 so. Uniqueness can be guaranteed by instead using uninterned symbols
4999 (@pxref{Symbol Uninterned}), though they can't be usefully written out
5004 @subsubsection Function Slots and Property Lists
5006 In traditional Lisp dialects, symbols are often understood as having
5007 three kinds of value at once:
5011 a @dfn{variable} value, which is used when the symbol appears in
5012 code in a variable reference context
5015 a @dfn{function} value, which is used when the symbol appears in
5016 code in a function name position (i.e. as the first element in an
5020 a @dfn{property list} value, which is used when the symbol is given as
5021 the first argument to Lisp's @code{put} or @code{get} functions.
5024 Although Scheme (as one of its simplifications with respect to Lisp)
5025 does away with the distinction between variable and function namespaces,
5026 Guile currently retains some elements of the traditional structure in
5027 case they turn out to be useful when implementing translators for other
5028 languages, in particular Emacs Lisp.
5030 Specifically, Guile symbols have two extra slots. for a symbol's
5031 property list, and for its ``function value.'' The following procedures
5032 are provided to access these slots.
5034 @deffn {Scheme Procedure} symbol-fref symbol
5035 @deffnx {C Function} scm_symbol_fref (symbol)
5036 Return the contents of @var{symbol}'s @dfn{function slot}.
5039 @deffn {Scheme Procedure} symbol-fset! symbol value
5040 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
5041 Set the contents of @var{symbol}'s function slot to @var{value}.
5044 @deffn {Scheme Procedure} symbol-pref symbol
5045 @deffnx {C Function} scm_symbol_pref (symbol)
5046 Return the @dfn{property list} currently associated with @var{symbol}.
5049 @deffn {Scheme Procedure} symbol-pset! symbol value
5050 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
5051 Set @var{symbol}'s property list to @var{value}.
5054 @deffn {Scheme Procedure} symbol-property sym prop
5055 From @var{sym}'s property list, return the value for property
5056 @var{prop}. The assumption is that @var{sym}'s property list is an
5057 association list whose keys are distinguished from each other using
5058 @code{equal?}; @var{prop} should be one of the keys in that list. If
5059 the property list has no entry for @var{prop}, @code{symbol-property}
5063 @deffn {Scheme Procedure} set-symbol-property! sym prop val
5064 In @var{sym}'s property list, set the value for property @var{prop} to
5065 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
5066 none already exists. For the structure of the property list, see
5067 @code{symbol-property}.
5070 @deffn {Scheme Procedure} symbol-property-remove! sym prop
5071 From @var{sym}'s property list, remove the entry for property
5072 @var{prop}, if there is one. For the structure of the property list,
5073 see @code{symbol-property}.
5076 Support for these extra slots may be removed in a future release, and it
5077 is probably better to avoid using them. For a more modern and Schemely
5078 approach to properties, see @ref{Object Properties}.
5081 @node Symbol Read Syntax
5082 @subsubsection Extended Read Syntax for Symbols
5084 The read syntax for a symbol is a sequence of letters, digits, and
5085 @dfn{extended alphabetic characters}, beginning with a character that
5086 cannot begin a number. In addition, the special cases of @code{+},
5087 @code{-}, and @code{...} are read as symbols even though numbers can
5088 begin with @code{+}, @code{-} or @code{.}.
5090 Extended alphabetic characters may be used within identifiers as if
5091 they were letters. The set of extended alphabetic characters is:
5094 ! $ % & * + - . / : < = > ? @@ ^ _ ~
5097 In addition to the standard read syntax defined above (which is taken
5098 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
5099 Scheme})), Guile provides an extended symbol read syntax that allows the
5100 inclusion of unusual characters such as space characters, newlines and
5101 parentheses. If (for whatever reason) you need to write a symbol
5102 containing characters not mentioned above, you can do so as follows.
5106 Begin the symbol with the characters @code{#@{},
5109 write the characters of the symbol and
5112 finish the symbol with the characters @code{@}#}.
5115 Here are a few examples of this form of read syntax. The first symbol
5116 needs to use extended syntax because it contains a space character, the
5117 second because it contains a line break, and the last because it looks
5129 Although Guile provides this extended read syntax for symbols,
5130 widespread usage of it is discouraged because it is not portable and not
5134 @node Symbol Uninterned
5135 @subsubsection Uninterned Symbols
5137 What makes symbols useful is that they are automatically kept unique.
5138 There are no two symbols that are distinct objects but have the same
5139 name. But of course, there is no rule without exception. In addition
5140 to the normal symbols that have been discussed up to now, you can also
5141 create special @dfn{uninterned} symbols that behave slightly
5144 To understand what is different about them and why they might be useful,
5145 we look at how normal symbols are actually kept unique.
5147 Whenever Guile wants to find the symbol with a specific name, for
5148 example during @code{read} or when executing @code{string->symbol}, it
5149 first looks into a table of all existing symbols to find out whether a
5150 symbol with the given name already exists. When this is the case, Guile
5151 just returns that symbol. When not, a new symbol with the name is
5152 created and entered into the table so that it can be found later.
5154 Sometimes you might want to create a symbol that is guaranteed `fresh',
5155 i.e. a symbol that did not exist previously. You might also want to
5156 somehow guarantee that no one else will ever unintentionally stumble
5157 across your symbol in the future. These properties of a symbol are
5158 often needed when generating code during macro expansion. When
5159 introducing new temporary variables, you want to guarantee that they
5160 don't conflict with variables in other people's code.
5162 The simplest way to arrange for this is to create a new symbol but
5163 not enter it into the global table of all symbols. That way, no one
5164 will ever get access to your symbol by chance. Symbols that are not in
5165 the table are called @dfn{uninterned}. Of course, symbols that
5166 @emph{are} in the table are called @dfn{interned}.
5168 You create new uninterned symbols with the function @code{make-symbol}.
5169 You can test whether a symbol is interned or not with
5170 @code{symbol-interned?}.
5172 Uninterned symbols break the rule that the name of a symbol uniquely
5173 identifies the symbol object. Because of this, they can not be written
5174 out and read back in like interned symbols. Currently, Guile has no
5175 support for reading uninterned symbols. Note that the function
5176 @code{gensym} does not return uninterned symbols for this reason.
5178 @deffn {Scheme Procedure} make-symbol name
5179 @deffnx {C Function} scm_make_symbol (name)
5180 Return a new uninterned symbol with the name @var{name}. The returned
5181 symbol is guaranteed to be unique and future calls to
5182 @code{string->symbol} will not return it.
5185 @deffn {Scheme Procedure} symbol-interned? symbol
5186 @deffnx {C Function} scm_symbol_interned_p (symbol)
5187 Return @code{#t} if @var{symbol} is interned, otherwise return
5194 (define foo-1 (string->symbol "foo"))
5195 (define foo-2 (string->symbol "foo"))
5196 (define foo-3 (make-symbol "foo"))
5197 (define foo-4 (make-symbol "foo"))
5201 ; Two interned symbols with the same name are the same object,
5205 ; but a call to make-symbol with the same name returns a
5210 ; A call to make-symbol always returns a new object, even for
5214 @result{} #<uninterned-symbol foo 8085290>
5215 ; Uninterned symbols print differently from interned symbols,
5219 ; but they are still symbols,
5221 (symbol-interned? foo-3)
5223 ; just not interned.
5228 @subsection Keywords
5231 Keywords are self-evaluating objects with a convenient read syntax that
5232 makes them easy to type.
5234 Guile's keyword support conforms to R5RS, and adds a (switchable) read
5235 syntax extension to permit keywords to begin with @code{:} as well as
5236 @code{#:}, or to end with @code{:}.
5239 * Why Use Keywords?:: Motivation for keyword usage.
5240 * Coding With Keywords:: How to use keywords.
5241 * Keyword Read Syntax:: Read syntax for keywords.
5242 * Keyword Procedures:: Procedures for dealing with keywords.
5245 @node Why Use Keywords?
5246 @subsubsection Why Use Keywords?
5248 Keywords are useful in contexts where a program or procedure wants to be
5249 able to accept a large number of optional arguments without making its
5250 interface unmanageable.
5252 To illustrate this, consider a hypothetical @code{make-window}
5253 procedure, which creates a new window on the screen for drawing into
5254 using some graphical toolkit. There are many parameters that the caller
5255 might like to specify, but which could also be sensibly defaulted, for
5260 color depth -- Default: the color depth for the screen
5263 background color -- Default: white
5266 width -- Default: 600
5269 height -- Default: 400
5272 If @code{make-window} did not use keywords, the caller would have to
5273 pass in a value for each possible argument, remembering the correct
5274 argument order and using a special value to indicate the default value
5278 (make-window 'default ;; Color depth
5279 'default ;; Background color
5282 @dots{}) ;; More make-window arguments
5285 With keywords, on the other hand, defaulted arguments are omitted, and
5286 non-default arguments are clearly tagged by the appropriate keyword. As
5287 a result, the invocation becomes much clearer:
5290 (make-window #:width 800 #:height 100)
5293 On the other hand, for a simpler procedure with few arguments, the use
5294 of keywords would be a hindrance rather than a help. The primitive
5295 procedure @code{cons}, for example, would not be improved if it had to
5299 (cons #:car x #:cdr y)
5302 So the decision whether to use keywords or not is purely pragmatic: use
5303 them if they will clarify the procedure invocation at point of call.
5305 @node Coding With Keywords
5306 @subsubsection Coding With Keywords
5308 If a procedure wants to support keywords, it should take a rest argument
5309 and then use whatever means is convenient to extract keywords and their
5310 corresponding arguments from the contents of that rest argument.
5312 The following example illustrates the principle: the code for
5313 @code{make-window} uses a helper procedure called
5314 @code{get-keyword-value} to extract individual keyword arguments from
5318 (define (get-keyword-value args keyword default)
5319 (let ((kv (memq keyword args)))
5320 (if (and kv (>= (length kv) 2))
5324 (define (make-window . args)
5325 (let ((depth (get-keyword-value args #:depth screen-depth))
5326 (bg (get-keyword-value args #:bg "white"))
5327 (width (get-keyword-value args #:width 800))
5328 (height (get-keyword-value args #:height 100))
5333 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
5334 optargs)} module provides a set of powerful macros that you can use to
5335 implement keyword-supporting procedures like this:
5338 (use-modules (ice-9 optargs))
5340 (define (make-window . args)
5341 (let-keywords args #f ((depth screen-depth)
5349 Or, even more economically, like this:
5352 (use-modules (ice-9 optargs))
5354 (define* (make-window #:key (depth screen-depth)
5361 For further details on @code{let-keywords}, @code{define*} and other
5362 facilities provided by the @code{(ice-9 optargs)} module, see
5363 @ref{Optional Arguments}.
5366 @node Keyword Read Syntax
5367 @subsubsection Keyword Read Syntax
5369 Guile, by default, only recognizes a keyword syntax that is compatible
5370 with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
5371 same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
5372 external representation of the keyword named @code{NAME}. Keyword
5373 objects print using this syntax as well, so values containing keyword
5374 objects can be read back into Guile. When used in an expression,
5375 keywords are self-quoting objects.
5377 If the @code{keyword} read option is set to @code{'prefix}, Guile also
5378 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
5379 of the form @code{:NAME} are read as symbols, as required by R5RS.
5381 @cindex SRFI-88 keyword syntax
5383 If the @code{keyword} read option is set to @code{'postfix}, Guile
5384 recognizes the SRFI-88 read syntax @code{NAME:} (@pxref{SRFI-88}).
5385 Otherwise, tokens of this form are read as symbols.
5387 To enable and disable the alternative non-R5RS keyword syntax, you use
5388 the @code{read-set!} procedure documented @ref{Scheme Read}. Note that
5389 the @code{prefix} and @code{postfix} syntax are mutually exclusive.
5392 (read-set! keywords 'prefix)
5402 (read-set! keywords 'postfix)
5412 (read-set! keywords #f)
5420 ERROR: In expression :type:
5421 ERROR: Unbound variable: :type
5422 ABORT: (unbound-variable)
5425 @node Keyword Procedures
5426 @subsubsection Keyword Procedures
5428 @deffn {Scheme Procedure} keyword? obj
5429 @deffnx {C Function} scm_keyword_p (obj)
5430 Return @code{#t} if the argument @var{obj} is a keyword, else
5434 @deffn {Scheme Procedure} keyword->symbol keyword
5435 @deffnx {C Function} scm_keyword_to_symbol (keyword)
5436 Return the symbol with the same name as @var{keyword}.
5439 @deffn {Scheme Procedure} symbol->keyword symbol
5440 @deffnx {C Function} scm_symbol_to_keyword (symbol)
5441 Return the keyword with the same name as @var{symbol}.
5444 @deftypefn {C Function} int scm_is_keyword (SCM obj)
5445 Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
5448 @deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5449 @deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5450 Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5451 (@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5452 (@var{str}, @var{len}))}, respectively.
5456 @subsection ``Functionality-Centric'' Data Types
5458 Procedures and macros are documented in their own sections: see
5459 @ref{Procedures} and @ref{Macros}.
5461 Variable objects are documented as part of the description of Guile's
5462 module system: see @ref{Variables}.
5464 Asyncs, dynamic roots and fluids are described in the section on
5465 scheduling: see @ref{Scheduling}.
5467 Hooks are documented in the section on general utility functions: see
5470 Ports are described in the section on I/O: see @ref{Input and Output}.
5472 Regular expressions are described in their own section: see @ref{Regular
5476 @c TeX-master: "guile.texi"