2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
8 @node Simple Data Types
9 @section Simple Generic Data Types
11 This chapter describes those of Guile's simple data types which are
12 primarily used for their role as items of generic data. By
13 @dfn{simple} we mean data types that are not primarily used as
14 containers to hold other data --- i.e.@: pairs, lists, vectors and so on.
15 For the documentation of such @dfn{compound} data types, see
16 @ref{Compound Data Types}.
18 @c One of the great strengths of Scheme is that there is no straightforward
19 @c distinction between ``data'' and ``functionality''. For example,
20 @c Guile's support for dynamic linking could be described:
24 @c either in a ``data-centric'' way, as the behaviour and properties of the
25 @c ``dynamically linked object'' data type, and the operations that may be
26 @c applied to instances of this type
29 @c or in a ``functionality-centric'' way, as the set of procedures that
30 @c constitute Guile's support for dynamic linking, in the context of the
34 @c The contents of this chapter are, therefore, a matter of judgment. By
35 @c @dfn{generic}, we mean to select those data types whose typical use as
36 @c @emph{data} in a wide variety of programming contexts is more important
37 @c than their use in the implementation of a particular piece of
38 @c @emph{functionality}. The last section of this chapter provides
39 @c references for all the data types that are documented not here but in a
40 @c ``functionality-centric'' way elsewhere in the manual.
43 * Booleans:: True/false values.
44 * Numbers:: Numerical data types.
45 * Characters:: Single characters.
46 * Character Sets:: Sets of characters.
47 * Strings:: Sequences of characters.
48 * Regular Expressions:: Pattern matching and substitution.
50 * Keywords:: Self-quoting, customizable display keywords.
51 * Other Types:: "Functionality-centric" data types.
59 The two boolean values are @code{#t} for true and @code{#f} for false.
61 Boolean values are returned by predicate procedures, such as the general
62 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
63 (@pxref{Equality}) and numerical and string comparison operators like
64 @code{string=?} (@pxref{String Comparison}) and @code{<=}
74 (equal? "house" "houses")
82 In test condition contexts like @code{if} and @code{cond} (@pxref{if
83 cond case}), where a group of subexpressions will be evaluated only if a
84 @var{condition} expression evaluates to ``true'', ``true'' means any
85 value at all except @code{#f}.
98 A result of this asymmetry is that typical Scheme source code more often
99 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
100 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
101 not necessary to represent an @code{if} or @code{cond} true value.
103 It is important to note that @code{#f} is @strong{not} equivalent to any
104 other Scheme value. In particular, @code{#f} is not the same as the
105 number 0 (like in C and C++), and not the same as the ``empty list''
106 (like in some Lisp dialects).
108 In C, the two Scheme boolean values are available as the two constants
109 @code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
110 Care must be taken with the false value @code{SCM_BOOL_F}: it is not
111 false when used in C conditionals. In order to test for it, use
112 @code{scm_is_false} or @code{scm_is_true}.
115 @deffn {Scheme Procedure} not x
116 @deffnx {C Function} scm_not (x)
117 Return @code{#t} if @var{x} is @code{#f}, else return @code{#f}.
121 @deffn {Scheme Procedure} boolean? obj
122 @deffnx {C Function} scm_boolean_p (obj)
123 Return @code{#t} if @var{obj} is either @code{#t} or @code{#f}, else
127 @deftypevr {C Macro} SCM SCM_BOOL_T
128 The @code{SCM} representation of the Scheme object @code{#t}.
131 @deftypevr {C Macro} SCM SCM_BOOL_F
132 The @code{SCM} representation of the Scheme object @code{#f}.
135 @deftypefn {C Function} int scm_is_true (SCM obj)
136 Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
139 @deftypefn {C Function} int scm_is_false (SCM obj)
140 Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
143 @deftypefn {C Function} int scm_is_bool (SCM obj)
144 Return @code{1} if @var{obj} is either @code{#t} or @code{#f}, else
148 @deftypefn {C Function} SCM scm_from_bool (int val)
149 Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
152 @deftypefn {C Function} int scm_to_bool (SCM val)
153 Return @code{1} if @var{val} is @code{SCM_BOOL_T}, return @code{0}
154 when @var{val} is @code{SCM_BOOL_F}, else signal a `wrong type' error.
156 You should probably use @code{scm_is_true} instead of this function
157 when you just want to test a @code{SCM} value for trueness.
161 @subsection Numerical data types
164 Guile supports a rich ``tower'' of numerical types --- integer,
165 rational, real and complex --- and provides an extensive set of
166 mathematical and scientific functions for operating on numerical
167 data. This section of the manual documents those types and functions.
169 You may also find it illuminating to read R5RS's presentation of numbers
170 in Scheme, which is particularly clear and accessible: see
171 @ref{Numbers,,,r5rs,R5RS}.
174 * Numerical Tower:: Scheme's numerical "tower".
175 * Integers:: Whole numbers.
176 * Reals and Rationals:: Real and rational numbers.
177 * Complex Numbers:: Complex numbers.
178 * Exactness:: Exactness and inexactness.
179 * Number Syntax:: Read syntax for numerical data.
180 * Integer Operations:: Operations on integer values.
181 * Comparison:: Comparison predicates.
182 * Conversion:: Converting numbers to and from strings.
183 * Complex:: Complex number operations.
184 * Arithmetic:: Arithmetic functions.
185 * Scientific:: Scientific functions.
186 * Primitive Numerics:: Primitive numeric functions.
187 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
188 * Random:: Random number generation.
192 @node Numerical Tower
193 @subsubsection Scheme's Numerical ``Tower''
196 Scheme's numerical ``tower'' consists of the following categories of
201 Whole numbers, positive or negative; e.g.@: --5, 0, 18.
204 The set of numbers that can be expressed as @math{@var{p}/@var{q}}
205 where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
206 pi (an irrational number) doesn't. These include integers
210 The set of numbers that describes all possible positions along a
211 one-dimensional line. This includes rationals as well as irrational
214 @item complex numbers
215 The set of numbers that describes all possible positions in a two
216 dimensional space. This includes real as well as imaginary numbers
217 (@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
218 @var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
222 It is called a tower because each category ``sits on'' the one that
223 follows it, in the sense that every integer is also a rational, every
224 rational is also real, and every real number is also a complex number
225 (but with zero imaginary part).
227 In addition to the classification into integers, rationals, reals and
228 complex numbers, Scheme also distinguishes between whether a number is
229 represented exactly or not. For example, the result of
230 @m{2\sin(\pi/4),2*sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)}, but Guile
231 can represent neither @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
232 Instead, it stores an inexact approximation, using the C type
235 Guile can represent exact rationals of any magnitude, inexact
236 rationals that fit into a C @code{double}, and inexact complex numbers
237 with @code{double} real and imaginary parts.
239 The @code{number?} predicate may be applied to any Scheme value to
240 discover whether the value is any of the supported numerical types.
242 @deffn {Scheme Procedure} number? obj
243 @deffnx {C Function} scm_number_p (obj)
244 Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
253 (number? "hello there!")
256 (define pi 3.141592654)
261 @deftypefn {C Function} int scm_is_number (SCM obj)
262 This is equivalent to @code{scm_is_true (scm_number_p (obj))}.
265 The next few subsections document each of Guile's numerical data types
269 @subsubsection Integers
271 @tpindex Integer numbers
275 Integers are whole numbers, that is numbers with no fractional part,
276 such as 2, 83, and @minus{}3789.
278 Integers in Guile can be arbitrarily big, as shown by the following
282 (define (factorial n)
283 (let loop ((n n) (product 1))
286 (loop (- n 1) (* product n)))))
292 @result{} 2432902008176640000
295 @result{} -119622220865480194561963161495657715064383733760000000000
298 Readers whose background is in programming languages where integers are
299 limited by the need to fit into just 4 or 8 bytes of memory may find
300 this surprising, or suspect that Guile's representation of integers is
301 inefficient. In fact, Guile achieves a near optimal balance of
302 convenience and efficiency by using the host computer's native
303 representation of integers where possible, and a more general
304 representation where the required number does not fit in the native
305 form. Conversion between these two representations is automatic and
306 completely invisible to the Scheme level programmer.
308 The infinities @samp{+inf.0} and @samp{-inf.0} are considered to be
309 inexact integers. They are explained in detail in the next section,
310 together with reals and rationals.
312 C has a host of different integer types, and Guile offers a host of
313 functions to convert between them and the @code{SCM} representation.
314 For example, a C @code{int} can be handled with @code{scm_to_int} and
315 @code{scm_from_int}. Guile also defines a few C integer types of its
316 own, to help with differences between systems.
318 C integer types that are not covered can be handled with the generic
319 @code{scm_to_signed_integer} and @code{scm_from_signed_integer} for
320 signed types, or with @code{scm_to_unsigned_integer} and
321 @code{scm_from_unsigned_integer} for unsigned types.
323 Scheme integers can be exact and inexact. For example, a number
324 written as @code{3.0} with an explicit decimal-point is inexact, but
325 it is also an integer. The functions @code{integer?} and
326 @code{scm_is_integer} report true for such a number, but the functions
327 @code{scm_is_signed_integer} and @code{scm_is_unsigned_integer} only
328 allow exact integers and thus report false. Likewise, the conversion
329 functions like @code{scm_to_signed_integer} only accept exact
332 The motivation for this behavior is that the inexactness of a number
333 should not be lost silently. If you want to allow inexact integers,
334 you can explicitely insert a call to @code{inexact->exact} or to its C
335 equivalent @code{scm_inexact_to_exact}. (Only inexact integers will
336 be converted by this call into exact integers; inexact non-integers
337 will become exact fractions.)
339 @deffn {Scheme Procedure} integer? x
340 @deffnx {C Function} scm_integer_p (x)
341 Return @code{#t} if @var{x} is an exact or inexact integer number, else
359 @deftypefn {C Function} int scm_is_integer (SCM x)
360 This is equivalent to @code{scm_is_true (scm_integer_p (x))}.
363 @defvr {C Type} scm_t_int8
364 @defvrx {C Type} scm_t_uint8
365 @defvrx {C Type} scm_t_int16
366 @defvrx {C Type} scm_t_uint16
367 @defvrx {C Type} scm_t_int32
368 @defvrx {C Type} scm_t_uint32
369 @defvrx {C Type} scm_t_int64
370 @defvrx {C Type} scm_t_uint64
371 @defvrx {C Type} scm_t_intmax
372 @defvrx {C Type} scm_t_uintmax
373 The C types are equivalent to the corresponding ISO C types but are
374 defined on all platforms, with the exception of @code{scm_t_int64} and
375 @code{scm_t_uint64}, which are only defined when a 64-bit type is
376 available. For example, @code{scm_t_int8} is equivalent to
379 You can regard these definitions as a stop-gap measure until all
380 platforms provide these types. If you know that all the platforms
381 that you are interested in already provide these types, it is better
382 to use them directly instead of the types provided by Guile.
385 @deftypefn {C Function} int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
386 @deftypefnx {C Function} int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
387 Return @code{1} when @var{x} represents an exact integer that is
388 between @var{min} and @var{max}, inclusive.
390 These functions can be used to check whether a @code{SCM} value will
391 fit into a given range, such as the range of a given C integer type.
392 If you just want to convert a @code{SCM} value to a given C integer
393 type, use one of the conversion functions directly.
396 @deftypefn {C Function} scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
397 @deftypefnx {C Function} scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
398 When @var{x} represents an exact integer that is between @var{min} and
399 @var{max} inclusive, return that integer. Else signal an error,
400 either a `wrong-type' error when @var{x} is not an exact integer, or
401 an `out-of-range' error when it doesn't fit the given range.
404 @deftypefn {C Function} SCM scm_from_signed_integer (scm_t_intmax x)
405 @deftypefnx {C Function} SCM scm_from_unsigned_integer (scm_t_uintmax x)
406 Return the @code{SCM} value that represents the integer @var{x}. This
407 function will always succeed and will always return an exact number.
410 @deftypefn {C Function} char scm_to_char (SCM x)
411 @deftypefnx {C Function} {signed char} scm_to_schar (SCM x)
412 @deftypefnx {C Function} {unsigned char} scm_to_uchar (SCM x)
413 @deftypefnx {C Function} short scm_to_short (SCM x)
414 @deftypefnx {C Function} {unsigned short} scm_to_ushort (SCM x)
415 @deftypefnx {C Function} int scm_to_int (SCM x)
416 @deftypefnx {C Function} {unsigned int} scm_to_uint (SCM x)
417 @deftypefnx {C Function} long scm_to_long (SCM x)
418 @deftypefnx {C Function} {unsigned long} scm_to_ulong (SCM x)
419 @deftypefnx {C Function} {long long} scm_to_long_long (SCM x)
420 @deftypefnx {C Function} {unsigned long long} scm_to_ulong_long (SCM x)
421 @deftypefnx {C Function} size_t scm_to_size_t (SCM x)
422 @deftypefnx {C Function} ssize_t scm_to_ssize_t (SCM x)
423 @deftypefnx {C Function} scm_t_int8 scm_to_int8 (SCM x)
424 @deftypefnx {C Function} scm_t_uint8 scm_to_uint8 (SCM x)
425 @deftypefnx {C Function} scm_t_int16 scm_to_int16 (SCM x)
426 @deftypefnx {C Function} scm_t_uint16 scm_to_uint16 (SCM x)
427 @deftypefnx {C Function} scm_t_int32 scm_to_int32 (SCM x)
428 @deftypefnx {C Function} scm_t_uint32 scm_to_uint32 (SCM x)
429 @deftypefnx {C Function} scm_t_int64 scm_to_int64 (SCM x)
430 @deftypefnx {C Function} scm_t_uint64 scm_to_uint64 (SCM x)
431 @deftypefnx {C Function} scm_t_intmax scm_to_intmax (SCM x)
432 @deftypefnx {C Function} scm_t_uintmax scm_to_uintmax (SCM x)
433 When @var{x} represents an exact integer that fits into the indicated
434 C type, return that integer. Else signal an error, either a
435 `wrong-type' error when @var{x} is not an exact integer, or an
436 `out-of-range' error when it doesn't fit the given range.
438 The functions @code{scm_to_long_long}, @code{scm_to_ulong_long},
439 @code{scm_to_int64}, and @code{scm_to_uint64} are only available when
440 the corresponding types are.
443 @deftypefn {C Function} SCM scm_from_char (char x)
444 @deftypefnx {C Function} SCM scm_from_schar (signed char x)
445 @deftypefnx {C Function} SCM scm_from_uchar (unsigned char x)
446 @deftypefnx {C Function} SCM scm_from_short (short x)
447 @deftypefnx {C Function} SCM scm_from_ushort (unsigned short x)
448 @deftypefnx {C Function} SCM scm_from_int (int x)
449 @deftypefnx {C Function} SCM scm_from_uint (unsigned int x)
450 @deftypefnx {C Function} SCM scm_from_long (long x)
451 @deftypefnx {C Function} SCM scm_from_ulong (unsigned long x)
452 @deftypefnx {C Function} SCM scm_from_long_long (long long x)
453 @deftypefnx {C Function} SCM scm_from_ulong_long (unsigned long long x)
454 @deftypefnx {C Function} SCM scm_from_size_t (size_t x)
455 @deftypefnx {C Function} SCM scm_from_ssize_t (ssize_t x)
456 @deftypefnx {C Function} SCM scm_from_int8 (scm_t_int8 x)
457 @deftypefnx {C Function} SCM scm_from_uint8 (scm_t_uint8 x)
458 @deftypefnx {C Function} SCM scm_from_int16 (scm_t_int16 x)
459 @deftypefnx {C Function} SCM scm_from_uint16 (scm_t_uint16 x)
460 @deftypefnx {C Function} SCM scm_from_int32 (scm_t_int32 x)
461 @deftypefnx {C Function} SCM scm_from_uint32 (scm_t_uint32 x)
462 @deftypefnx {C Function} SCM scm_from_int64 (scm_t_int64 x)
463 @deftypefnx {C Function} SCM scm_from_uint64 (scm_t_uint64 x)
464 @deftypefnx {C Function} SCM scm_from_intmax (scm_t_intmax x)
465 @deftypefnx {C Function} SCM scm_from_uintmax (scm_t_uintmax x)
466 Return the @code{SCM} value that represents the integer @var{x}.
467 These functions will always succeed and will always return an exact
471 @deftypefn {C Function} void scm_to_mpz (SCM val, mpz_t rop)
472 Assign @var{val} to the multiple precision integer @var{rop}.
473 @var{val} must be an exact integer, otherwise an error will be
474 signalled. @var{rop} must have been initialized with @code{mpz_init}
475 before this function is called. When @var{rop} is no longer needed
476 the occupied space must be freed with @code{mpz_clear}.
477 @xref{Initializing Integers,,, gmp, GNU MP Manual}, for details.
480 @deftypefn {C Function} SCM scm_from_mpz (mpz_t val)
481 Return the @code{SCM} value that represents @var{val}.
484 @node Reals and Rationals
485 @subsubsection Real and Rational Numbers
486 @tpindex Real numbers
487 @tpindex Rational numbers
492 Mathematically, the real numbers are the set of numbers that describe
493 all possible points along a continuous, infinite, one-dimensional line.
494 The rational numbers are the set of all numbers that can be written as
495 fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
496 All rational numbers are also real, but there are real numbers that
497 are not rational, for example @m{\sqrt2, the square root of 2}, and
500 Guile can represent both exact and inexact rational numbers, but it
501 can not represent irrational numbers. Exact rationals are represented
502 by storing the numerator and denominator as two exact integers.
503 Inexact rationals are stored as floating point numbers using the C
506 Exact rationals are written as a fraction of integers. There must be
507 no whitespace around the slash:
514 Even though the actual encoding of inexact rationals is in binary, it
515 may be helpful to think of it as a decimal number with a limited
516 number of significant figures and a decimal point somewhere, since
517 this corresponds to the standard notation for non-whole numbers. For
523 -5648394822220000000000.0
527 The limited precision of Guile's encoding means that any ``real'' number
528 in Guile can be written in a rational form, by multiplying and then dividing
529 by sufficient powers of 10 (or in fact, 2). For example,
530 @samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
531 100000000000000000. In Guile's current incarnation, therefore, the
532 @code{rational?} and @code{real?} predicates are equivalent.
535 Dividing by an exact zero leads to a error message, as one might
536 expect. However, dividing by an inexact zero does not produce an
537 error. Instead, the result of the division is either plus or minus
538 infinity, depending on the sign of the divided number.
540 The infinities are written @samp{+inf.0} and @samp{-inf.0},
541 respectivly. This syntax is also recognized by @code{read} as an
542 extension to the usual Scheme syntax.
544 Dividing zero by zero yields something that is not a number at all:
545 @samp{+nan.0}. This is the special `not a number' value.
547 On platforms that follow @acronym{IEEE} 754 for their floating point
548 arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
549 are implemented using the corresponding @acronym{IEEE} 754 values.
550 They behave in arithmetic operations like @acronym{IEEE} 754 describes
551 it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
553 The infinities are inexact integers and are considered to be both even
554 and odd. While @samp{+nan.0} is not @code{=} to itself, it is
555 @code{eqv?} to itself.
557 To test for the special values, use the functions @code{inf?} and
560 @deffn {Scheme Procedure} real? obj
561 @deffnx {C Function} scm_real_p (obj)
562 Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
563 that the sets of integer and rational values form subsets of the set
564 of real numbers, so the predicate will also be fulfilled if @var{obj}
565 is an integer number or a rational number.
568 @deffn {Scheme Procedure} rational? x
569 @deffnx {C Function} scm_rational_p (x)
570 Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
571 Note that the set of integer values forms a subset of the set of
572 rational numbers, i. e. the predicate will also be fulfilled if
573 @var{x} is an integer number.
575 Since Guile can not represent irrational numbers, every number
576 satisfying @code{real?} also satisfies @code{rational?} in Guile.
579 @deffn {Scheme Procedure} rationalize x eps
580 @deffnx {C Function} scm_rationalize (x, eps)
581 Returns the @emph{simplest} rational number differing
582 from @var{x} by no more than @var{eps}.
584 As required by @acronym{R5RS}, @code{rationalize} only returns an
585 exact result when both its arguments are exact. Thus, you might need
586 to use @code{inexact->exact} on the arguments.
589 (rationalize (inexact->exact 1.2) 1/100)
595 @deffn {Scheme Procedure} inf? x
596 @deffnx {C Function} scm_inf_p (x)
597 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
601 @deffn {Scheme Procedure} nan? x
602 @deffnx {C Function} scm_nan_p (x)
603 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
606 @deffn {Scheme Procedure} nan
607 @deffnx {C Function} scm_nan ()
611 @deffn {Scheme Procedure} inf
612 @deffnx {C Function} scm_inf ()
616 @deffn {Scheme Procedure} numerator x
617 @deffnx {C Function} scm_numerator (x)
618 Return the numerator of the rational number @var{x}.
621 @deffn {Scheme Procedure} denominator x
622 @deffnx {C Function} scm_denominator (x)
623 Return the denominator of the rational number @var{x}.
626 @deftypefn {C Function} int scm_is_real (SCM val)
627 @deftypefnx {C Function} int scm_is_rational (SCM val)
628 Equivalent to @code{scm_is_true (scm_real_p (val))} and
629 @code{scm_is_true (scm_rational_p (val))}, respectively.
632 @deftypefn {C Function} double scm_to_double (SCM val)
633 Returns the number closest to @var{val} that is representable as a
634 @code{double}. Returns infinity for a @var{val} that is too large in
635 magnitude. The argument @var{val} must be a real number.
638 @deftypefn {C Function} SCM scm_from_double (double val)
639 Return the @code{SCM} value that representats @var{val}. The returned
640 value is inexact according to the predicate @code{inexact?}, but it
641 will be exactly equal to @var{val}.
644 @node Complex Numbers
645 @subsubsection Complex Numbers
646 @tpindex Complex numbers
650 Complex numbers are the set of numbers that describe all possible points
651 in a two-dimensional space. The two coordinates of a particular point
652 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
653 the complex number that describes that point.
655 In Guile, complex numbers are written in rectangular form as the sum of
656 their real and imaginary parts, using the symbol @code{i} to indicate
671 Polar form can also be used, with an @samp{@@} between magnitude and
675 1@@3.141592 @result{} -1.0 (approx)
676 -1@@1.57079 @result{} 0.0-1.0i (approx)
679 Guile represents a complex number with a non-zero imaginary part as a
680 pair of inexact rationals, so the real and imaginary parts of a
681 complex number have the same properties of inexactness and limited
682 precision as single inexact rational numbers. Guile can not represent
683 exact complex numbers with non-zero imaginary parts.
685 @deffn {Scheme Procedure} complex? z
686 @deffnx {C Function} scm_complex_p (z)
687 Return @code{#t} if @var{x} is a complex number, @code{#f}
688 otherwise. Note that the sets of real, rational and integer
689 values form subsets of the set of complex numbers, i. e. the
690 predicate will also be fulfilled if @var{x} is a real,
691 rational or integer number.
694 @deftypefn {C Function} int scm_is_complex (SCM val)
695 Equivalent to @code{scm_is_true (scm_complex_p (val))}.
699 @subsubsection Exact and Inexact Numbers
700 @tpindex Exact numbers
701 @tpindex Inexact numbers
705 @rnindex exact->inexact
706 @rnindex inexact->exact
708 R5RS requires that a calculation involving inexact numbers always
709 produces an inexact result. To meet this requirement, Guile
710 distinguishes between an exact integer value such as @samp{5} and the
711 corresponding inexact real value which, to the limited precision
712 available, has no fractional part, and is printed as @samp{5.0}. Guile
713 will only convert the latter value to the former when forced to do so by
714 an invocation of the @code{inexact->exact} procedure.
716 @deffn {Scheme Procedure} exact? z
717 @deffnx {C Function} scm_exact_p (z)
718 Return @code{#t} if the number @var{z} is exact, @code{#f}
734 @deffn {Scheme Procedure} inexact? z
735 @deffnx {C Function} scm_inexact_p (z)
736 Return @code{#t} if the number @var{z} is inexact, @code{#f}
740 @deffn {Scheme Procedure} inexact->exact z
741 @deffnx {C Function} scm_inexact_to_exact (z)
742 Return an exact number that is numerically closest to @var{z}, when
743 there is one. For inexact rationals, Guile returns the exact rational
744 that is numerically equal to the inexact rational. Inexact complex
745 numbers with a non-zero imaginary part can not be made exact.
752 The following happens because 12/10 is not exactly representable as a
753 @code{double} (on most platforms). However, when reading a decimal
754 number that has been marked exact with the ``#e'' prefix, Guile is
755 able to represent it correctly.
759 @result{} 5404319552844595/4503599627370496
767 @c begin (texi-doc-string "guile" "exact->inexact")
768 @deffn {Scheme Procedure} exact->inexact z
769 @deffnx {C Function} scm_exact_to_inexact (z)
770 Convert the number @var{z} to its inexact representation.
775 @subsubsection Read Syntax for Numerical Data
777 The read syntax for integers is a string of digits, optionally
778 preceded by a minus or plus character, a code indicating the
779 base in which the integer is encoded, and a code indicating whether
780 the number is exact or inexact. The supported base codes are:
785 the integer is written in binary (base 2)
789 the integer is written in octal (base 8)
793 the integer is written in decimal (base 10)
797 the integer is written in hexadecimal (base 16)
800 If the base code is omitted, the integer is assumed to be decimal. The
801 following examples show how these base codes are used.
820 The codes for indicating exactness (which can, incidentally, be applied
821 to all numerical values) are:
830 the number is inexact.
833 If the exactness indicator is omitted, the number is exact unless it
834 contains a radix point. Since Guile can not represent exact complex
835 numbers, an error is signalled when asking for them.
845 ERROR: Wrong type argument
848 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
849 plus and minus infinity, respectively. The value must be written
850 exactly as shown, that is, they always must have a sign and exactly
851 one zero digit after the decimal point. It also understands
852 @samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
853 The sign is ignored for `not-a-number' and the value is always printed
856 @node Integer Operations
857 @subsubsection Operations on Integer Values
866 @deffn {Scheme Procedure} odd? n
867 @deffnx {C Function} scm_odd_p (n)
868 Return @code{#t} if @var{n} is an odd number, @code{#f}
872 @deffn {Scheme Procedure} even? n
873 @deffnx {C Function} scm_even_p (n)
874 Return @code{#t} if @var{n} is an even number, @code{#f}
878 @c begin (texi-doc-string "guile" "quotient")
879 @c begin (texi-doc-string "guile" "remainder")
880 @deffn {Scheme Procedure} quotient n d
881 @deffnx {Scheme Procedure} remainder n d
882 @deffnx {C Function} scm_quotient (n, d)
883 @deffnx {C Function} scm_remainder (n, d)
884 Return the quotient or remainder from @var{n} divided by @var{d}. The
885 quotient is rounded towards zero, and the remainder will have the same
886 sign as @var{n}. In all cases quotient and remainder satisfy
887 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
890 (remainder 13 4) @result{} 1
891 (remainder -13 4) @result{} -1
895 @c begin (texi-doc-string "guile" "modulo")
896 @deffn {Scheme Procedure} modulo n d
897 @deffnx {C Function} scm_modulo (n, d)
898 Return the remainder from @var{n} divided by @var{d}, with the same
902 (modulo 13 4) @result{} 1
903 (modulo -13 4) @result{} 3
904 (modulo 13 -4) @result{} -3
905 (modulo -13 -4) @result{} -1
909 @c begin (texi-doc-string "guile" "gcd")
910 @deffn {Scheme Procedure} gcd x@dots{}
911 @deffnx {C Function} scm_gcd (x, y)
912 Return the greatest common divisor of all arguments.
913 If called without arguments, 0 is returned.
915 The C function @code{scm_gcd} always takes two arguments, while the
916 Scheme function can take an arbitrary number.
919 @c begin (texi-doc-string "guile" "lcm")
920 @deffn {Scheme Procedure} lcm x@dots{}
921 @deffnx {C Function} scm_lcm (x, y)
922 Return the least common multiple of the arguments.
923 If called without arguments, 1 is returned.
925 The C function @code{scm_lcm} always takes two arguments, while the
926 Scheme function can take an arbitrary number.
929 @deffn {Scheme Procedure} modulo-expt n k m
930 @deffnx {C Function} scm_modulo_expt (n, k, m)
931 Return @var{n} raised to the integer exponent
932 @var{k}, modulo @var{m}.
941 @subsubsection Comparison Predicates
946 The C comparison functions below always takes two arguments, while the
947 Scheme functions can take an arbitrary number. Also keep in mind that
948 the C functions return one of the Scheme boolean values
949 @code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
950 is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
951 y))} when testing the two Scheme numbers @code{x} and @code{y} for
952 equality, for example.
954 @c begin (texi-doc-string "guile" "=")
955 @deffn {Scheme Procedure} =
956 @deffnx {C Function} scm_num_eq_p (x, y)
957 Return @code{#t} if all parameters are numerically equal.
960 @c begin (texi-doc-string "guile" "<")
961 @deffn {Scheme Procedure} <
962 @deffnx {C Function} scm_less_p (x, y)
963 Return @code{#t} if the list of parameters is monotonically
967 @c begin (texi-doc-string "guile" ">")
968 @deffn {Scheme Procedure} >
969 @deffnx {C Function} scm_gr_p (x, y)
970 Return @code{#t} if the list of parameters is monotonically
974 @c begin (texi-doc-string "guile" "<=")
975 @deffn {Scheme Procedure} <=
976 @deffnx {C Function} scm_leq_p (x, y)
977 Return @code{#t} if the list of parameters is monotonically
981 @c begin (texi-doc-string "guile" ">=")
982 @deffn {Scheme Procedure} >=
983 @deffnx {C Function} scm_geq_p (x, y)
984 Return @code{#t} if the list of parameters is monotonically
988 @c begin (texi-doc-string "guile" "zero?")
989 @deffn {Scheme Procedure} zero? z
990 @deffnx {C Function} scm_zero_p (z)
991 Return @code{#t} if @var{z} is an exact or inexact number equal to
995 @c begin (texi-doc-string "guile" "positive?")
996 @deffn {Scheme Procedure} positive? x
997 @deffnx {C Function} scm_positive_p (x)
998 Return @code{#t} if @var{x} is an exact or inexact number greater than
1002 @c begin (texi-doc-string "guile" "negative?")
1003 @deffn {Scheme Procedure} negative? x
1004 @deffnx {C Function} scm_negative_p (x)
1005 Return @code{#t} if @var{x} is an exact or inexact number less than
1011 @subsubsection Converting Numbers To and From Strings
1012 @rnindex number->string
1013 @rnindex string->number
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 imaginary
1052 @deffnx {C Function} scm_make_rectangular (real, imaginary)
1053 Return a complex number constructed of the given @var{real} and
1054 @var{imaginary} parts.
1057 @deffn {Scheme Procedure} make-polar x y
1058 @deffnx {C Function} scm_make_polar (x, y)
1060 Return the complex number @var{x} * e^(i * @var{y}).
1063 @c begin (texi-doc-string "guile" "real-part")
1064 @deffn {Scheme Procedure} real-part z
1065 @deffnx {C Function} scm_real_part (z)
1066 Return the real part of the number @var{z}.
1069 @c begin (texi-doc-string "guile" "imag-part")
1070 @deffn {Scheme Procedure} imag-part z
1071 @deffnx {C Function} scm_imag_part (z)
1072 Return the imaginary part of the number @var{z}.
1075 @c begin (texi-doc-string "guile" "magnitude")
1076 @deffn {Scheme Procedure} magnitude z
1077 @deffnx {C Function} scm_magnitude (z)
1078 Return the magnitude of the number @var{z}. This is the same as
1079 @code{abs} for real arguments, but also allows complex numbers.
1082 @c begin (texi-doc-string "guile" "angle")
1083 @deffn {Scheme Procedure} angle z
1084 @deffnx {C Function} scm_angle (z)
1085 Return the angle of the complex number @var{z}.
1088 @deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1089 @deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1090 Like @code{scm_make_rectangular} or @code{scm_make_polar},
1091 respectively, but these functions take @code{double}s as their
1095 @deftypefn {C Function} double scm_c_real_part (z)
1096 @deftypefnx {C Function} double scm_c_imag_part (z)
1097 Returns the real or imaginary part of @var{z} as a @code{double}.
1100 @deftypefn {C Function} double scm_c_magnitude (z)
1101 @deftypefnx {C Function} double scm_c_angle (z)
1102 Returns the magnitude or angle of @var{z} as a @code{double}.
1107 @subsubsection Arithmetic Functions
1120 The C arithmetic functions below always takes two arguments, while the
1121 Scheme functions can take an arbitrary number. When you need to
1122 invoke them with just one argument, for example to compute the
1123 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1124 one: @code{scm_difference (x, SCM_UNDEFINED)}.
1126 @c begin (texi-doc-string "guile" "+")
1127 @deffn {Scheme Procedure} + z1 @dots{}
1128 @deffnx {C Function} scm_sum (z1, z2)
1129 Return the sum of all parameter values. Return 0 if called without any
1133 @c begin (texi-doc-string "guile" "-")
1134 @deffn {Scheme Procedure} - z1 z2 @dots{}
1135 @deffnx {C Function} scm_difference (z1, z2)
1136 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1137 the sum of all but the first argument are subtracted from the first
1141 @c begin (texi-doc-string "guile" "*")
1142 @deffn {Scheme Procedure} * z1 @dots{}
1143 @deffnx {C Function} scm_product (z1, z2)
1144 Return the product of all arguments. If called without arguments, 1 is
1148 @c begin (texi-doc-string "guile" "/")
1149 @deffn {Scheme Procedure} / z1 z2 @dots{}
1150 @deffnx {C Function} scm_divide (z1, z2)
1151 Divide the first argument by the product of the remaining arguments. If
1152 called with one argument @var{z1}, 1/@var{z1} is returned.
1155 @c begin (texi-doc-string "guile" "abs")
1156 @deffn {Scheme Procedure} abs x
1157 @deffnx {C Function} scm_abs (x)
1158 Return the absolute value of @var{x}.
1160 @var{x} must be a number with zero imaginary part. To calculate the
1161 magnitude of a complex number, use @code{magnitude} instead.
1164 @c begin (texi-doc-string "guile" "max")
1165 @deffn {Scheme Procedure} max x1 x2 @dots{}
1166 @deffnx {C Function} scm_max (x1, x2)
1167 Return the maximum of all parameter values.
1170 @c begin (texi-doc-string "guile" "min")
1171 @deffn {Scheme Procedure} min x1 x2 @dots{}
1172 @deffnx {C Function} scm_min (x1, x2)
1173 Return the minimum of all parameter values.
1176 @c begin (texi-doc-string "guile" "truncate")
1177 @deffn {Scheme Procedure} truncate x
1178 @deffnx {C Function} scm_truncate_number (x)
1179 Round the inexact number @var{x} towards zero.
1182 @c begin (texi-doc-string "guile" "round")
1183 @deffn {Scheme Procedure} round x
1184 @deffnx {C Function} scm_round_number (x)
1185 Round the inexact number @var{x} to the nearest integer. When exactly
1186 halfway between two integers, round to the even one.
1189 @c begin (texi-doc-string "guile" "floor")
1190 @deffn {Scheme Procedure} floor x
1191 @deffnx {C Function} scm_floor (x)
1192 Round the number @var{x} towards minus infinity.
1195 @c begin (texi-doc-string "guile" "ceiling")
1196 @deffn {Scheme Procedure} ceiling x
1197 @deffnx {C Function} scm_ceiling (x)
1198 Round the number @var{x} towards infinity.
1201 @deftypefn {C Function} double scm_c_truncate (double x)
1202 @deftypefnx {C Function} double scm_c_round (double x)
1203 Like @code{scm_truncate_number} or @code{scm_round_number},
1204 respectively, but these functions take and return @code{double}
1209 @subsubsection Scientific Functions
1211 The following procedures accept any kind of number as arguments,
1212 including complex numbers.
1215 @c begin (texi-doc-string "guile" "sqrt")
1216 @deffn {Scheme Procedure} sqrt z
1217 Return the square root of @var{z}.
1221 @c begin (texi-doc-string "guile" "expt")
1222 @deffn {Scheme Procedure} expt z1 z2
1223 Return @var{z1} raised to the power of @var{z2}.
1227 @c begin (texi-doc-string "guile" "sin")
1228 @deffn {Scheme Procedure} sin z
1229 Return the sine of @var{z}.
1233 @c begin (texi-doc-string "guile" "cos")
1234 @deffn {Scheme Procedure} cos z
1235 Return the cosine of @var{z}.
1239 @c begin (texi-doc-string "guile" "tan")
1240 @deffn {Scheme Procedure} tan z
1241 Return the tangent of @var{z}.
1245 @c begin (texi-doc-string "guile" "asin")
1246 @deffn {Scheme Procedure} asin z
1247 Return the arcsine of @var{z}.
1251 @c begin (texi-doc-string "guile" "acos")
1252 @deffn {Scheme Procedure} acos z
1253 Return the arccosine of @var{z}.
1257 @c begin (texi-doc-string "guile" "atan")
1258 @deffn {Scheme Procedure} atan z
1259 @deffnx {Scheme Procedure} atan y x
1260 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1264 @c begin (texi-doc-string "guile" "exp")
1265 @deffn {Scheme Procedure} exp z
1266 Return e to the power of @var{z}, where e is the base of natural
1267 logarithms (2.71828@dots{}).
1271 @c begin (texi-doc-string "guile" "log")
1272 @deffn {Scheme Procedure} log z
1273 Return the natural logarithm of @var{z}.
1276 @c begin (texi-doc-string "guile" "log10")
1277 @deffn {Scheme Procedure} log10 z
1278 Return the base 10 logarithm of @var{z}.
1281 @c begin (texi-doc-string "guile" "sinh")
1282 @deffn {Scheme Procedure} sinh z
1283 Return the hyperbolic sine of @var{z}.
1286 @c begin (texi-doc-string "guile" "cosh")
1287 @deffn {Scheme Procedure} cosh z
1288 Return the hyperbolic cosine of @var{z}.
1291 @c begin (texi-doc-string "guile" "tanh")
1292 @deffn {Scheme Procedure} tanh z
1293 Return the hyperbolic tangent of @var{z}.
1296 @c begin (texi-doc-string "guile" "asinh")
1297 @deffn {Scheme Procedure} asinh z
1298 Return the hyperbolic arcsine of @var{z}.
1301 @c begin (texi-doc-string "guile" "acosh")
1302 @deffn {Scheme Procedure} acosh z
1303 Return the hyperbolic arccosine of @var{z}.
1306 @c begin (texi-doc-string "guile" "atanh")
1307 @deffn {Scheme Procedure} atanh z
1308 Return the hyperbolic arctangent of @var{z}.
1312 @node Primitive Numerics
1313 @subsubsection Primitive Numeric Functions
1315 Many of Guile's numeric procedures which accept any kind of numbers as
1316 arguments, including complex numbers, are implemented as Scheme
1317 procedures that use the following real number-based primitives. These
1318 primitives signal an error if they are called with complex arguments.
1320 @c begin (texi-doc-string "guile" "$abs")
1321 @deffn {Scheme Procedure} $abs x
1322 Return the absolute value of @var{x}.
1325 @c begin (texi-doc-string "guile" "$sqrt")
1326 @deffn {Scheme Procedure} $sqrt x
1327 Return the square root of @var{x}.
1330 @deffn {Scheme Procedure} $expt x y
1331 @deffnx {C Function} scm_sys_expt (x, y)
1332 Return @var{x} raised to the power of @var{y}. This
1333 procedure does not accept complex arguments.
1336 @c begin (texi-doc-string "guile" "$sin")
1337 @deffn {Scheme Procedure} $sin x
1338 Return the sine of @var{x}.
1341 @c begin (texi-doc-string "guile" "$cos")
1342 @deffn {Scheme Procedure} $cos x
1343 Return the cosine of @var{x}.
1346 @c begin (texi-doc-string "guile" "$tan")
1347 @deffn {Scheme Procedure} $tan x
1348 Return the tangent of @var{x}.
1351 @c begin (texi-doc-string "guile" "$asin")
1352 @deffn {Scheme Procedure} $asin x
1353 Return the arcsine of @var{x}.
1356 @c begin (texi-doc-string "guile" "$acos")
1357 @deffn {Scheme Procedure} $acos x
1358 Return the arccosine of @var{x}.
1361 @c begin (texi-doc-string "guile" "$atan")
1362 @deffn {Scheme Procedure} $atan x
1363 Return the arctangent of @var{x} in the range @minus{}@math{PI/2} to
1367 @deffn {Scheme Procedure} $atan2 x y
1368 @deffnx {C Function} scm_sys_atan2 (x, y)
1369 Return the arc tangent of the two arguments @var{x} and
1370 @var{y}. This is similar to calculating the arc tangent of
1371 @var{x} / @var{y}, except that the signs of both arguments
1372 are used to determine the quadrant of the result. This
1373 procedure does not accept complex arguments.
1376 @c begin (texi-doc-string "guile" "$exp")
1377 @deffn {Scheme Procedure} $exp x
1378 Return e to the power of @var{x}, where e is the base of natural
1379 logarithms (2.71828@dots{}).
1382 @c begin (texi-doc-string "guile" "$log")
1383 @deffn {Scheme Procedure} $log x
1384 Return the natural logarithm of @var{x}.
1387 @c begin (texi-doc-string "guile" "$sinh")
1388 @deffn {Scheme Procedure} $sinh x
1389 Return the hyperbolic sine of @var{x}.
1392 @c begin (texi-doc-string "guile" "$cosh")
1393 @deffn {Scheme Procedure} $cosh x
1394 Return the hyperbolic cosine of @var{x}.
1397 @c begin (texi-doc-string "guile" "$tanh")
1398 @deffn {Scheme Procedure} $tanh x
1399 Return the hyperbolic tangent of @var{x}.
1402 @c begin (texi-doc-string "guile" "$asinh")
1403 @deffn {Scheme Procedure} $asinh x
1404 Return the hyperbolic arcsine of @var{x}.
1407 @c begin (texi-doc-string "guile" "$acosh")
1408 @deffn {Scheme Procedure} $acosh x
1409 Return the hyperbolic arccosine of @var{x}.
1412 @c begin (texi-doc-string "guile" "$atanh")
1413 @deffn {Scheme Procedure} $atanh x
1414 Return the hyperbolic arctangent of @var{x}.
1417 C functions for the above are provided by the standard mathematics
1418 library. Naturally these expect and return @code{double} arguments
1419 (@pxref{Mathematics,,, libc, GNU C Library Reference Manual}).
1421 @multitable {xx} {Scheme Procedure} {C Function}
1422 @item @tab Scheme Procedure @tab C Function
1424 @item @tab @code{$abs} @tab @code{fabs}
1425 @item @tab @code{$sqrt} @tab @code{sqrt}
1426 @item @tab @code{$sin} @tab @code{sin}
1427 @item @tab @code{$cos} @tab @code{cos}
1428 @item @tab @code{$tan} @tab @code{tan}
1429 @item @tab @code{$asin} @tab @code{asin}
1430 @item @tab @code{$acos} @tab @code{acos}
1431 @item @tab @code{$atan} @tab @code{atan}
1432 @item @tab @code{$atan2} @tab @code{atan2}
1433 @item @tab @code{$exp} @tab @code{exp}
1434 @item @tab @code{$expt} @tab @code{pow}
1435 @item @tab @code{$log} @tab @code{log}
1436 @item @tab @code{$sinh} @tab @code{sinh}
1437 @item @tab @code{$cosh} @tab @code{cosh}
1438 @item @tab @code{$tanh} @tab @code{tanh}
1439 @item @tab @code{$asinh} @tab @code{asinh}
1440 @item @tab @code{$acosh} @tab @code{acosh}
1441 @item @tab @code{$atanh} @tab @code{atanh}
1444 @code{asinh}, @code{acosh} and @code{atanh} are C99 standard but might
1445 not be available on older systems. Guile provides the following
1446 equivalents (on all systems).
1448 @deftypefn {C Function} double scm_asinh (double x)
1449 @deftypefnx {C Function} double scm_acosh (double x)
1450 @deftypefnx {C Function} double scm_atanh (double x)
1451 Return the hyperbolic arcsine, arccosine or arctangent of @var{x}
1456 @node Bitwise Operations
1457 @subsubsection Bitwise Operations
1459 For the following bitwise functions, negative numbers are treated as
1460 infinite precision twos-complements. For instance @math{-6} is bits
1461 @math{@dots{}111010}, with infinitely many ones on the left. It can
1462 be seen that adding 6 (binary 110) to such a bit pattern gives all
1465 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1466 @deffnx {C Function} scm_logand (n1, n2)
1467 Return the bitwise @sc{and} of the integer arguments.
1470 (logand) @result{} -1
1471 (logand 7) @result{} 7
1472 (logand #b111 #b011 #b001) @result{} 1
1476 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1477 @deffnx {C Function} scm_logior (n1, n2)
1478 Return the bitwise @sc{or} of the integer arguments.
1481 (logior) @result{} 0
1482 (logior 7) @result{} 7
1483 (logior #b000 #b001 #b011) @result{} 3
1487 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1488 @deffnx {C Function} scm_loxor (n1, n2)
1489 Return the bitwise @sc{xor} of the integer arguments. A bit is
1490 set in the result if it is set in an odd number of arguments.
1493 (logxor) @result{} 0
1494 (logxor 7) @result{} 7
1495 (logxor #b000 #b001 #b011) @result{} 2
1496 (logxor #b000 #b001 #b011 #b011) @result{} 1
1500 @deffn {Scheme Procedure} lognot n
1501 @deffnx {C Function} scm_lognot (n)
1502 Return the integer which is the ones-complement of the integer
1503 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1506 (number->string (lognot #b10000000) 2)
1507 @result{} "-10000001"
1508 (number->string (lognot #b0) 2)
1513 @deffn {Scheme Procedure} logtest j k
1514 @deffnx {C Function} scm_logtest (j, k)
1515 Test whether @var{j} and @var{k} have any 1 bits in common. This is
1516 equivalent to @code{(not (zero? (logand j k)))}, but without actually
1517 calculating the @code{logand}, just testing for non-zero.
1520 (logtest #b0100 #b1011) @result{} #f
1521 (logtest #b0100 #b0111) @result{} #t
1525 @deffn {Scheme Procedure} logbit? index j
1526 @deffnx {C Function} scm_logbit_p (index, j)
1527 Test whether bit number @var{index} in @var{j} is set. @var{index}
1528 starts from 0 for the least significant bit.
1531 (logbit? 0 #b1101) @result{} #t
1532 (logbit? 1 #b1101) @result{} #f
1533 (logbit? 2 #b1101) @result{} #t
1534 (logbit? 3 #b1101) @result{} #t
1535 (logbit? 4 #b1101) @result{} #f
1539 @deffn {Scheme Procedure} ash n cnt
1540 @deffnx {C Function} scm_ash (n, cnt)
1541 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1542 @var{cnt} is negative. This is an ``arithmetic'' shift.
1544 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1545 when @var{cnt} is negative it's a division, rounded towards negative
1546 infinity. (Note that this is not the same rounding as @code{quotient}
1549 With @var{n} viewed as an infinite precision twos complement,
1550 @code{ash} means a left shift introducing zero bits, or a right shift
1554 (number->string (ash #b1 3) 2) @result{} "1000"
1555 (number->string (ash #b1010 -1) 2) @result{} "101"
1557 ;; -23 is bits ...11101001, -6 is bits ...111010
1558 (ash -23 -2) @result{} -6
1562 @deffn {Scheme Procedure} logcount n
1563 @deffnx {C Function} scm_logcount (n)
1564 Return the number of bits in integer @var{n}. If @var{n} is
1565 positive, the 1-bits in its binary representation are counted.
1566 If negative, the 0-bits in its two's-complement binary
1567 representation are counted. If zero, 0 is returned.
1570 (logcount #b10101010)
1579 @deffn {Scheme Procedure} integer-length n
1580 @deffnx {C Function} scm_integer_length (n)
1581 Return the number of bits necessary to represent @var{n}.
1583 For positive @var{n} this is how many bits to the most significant one
1584 bit. For negative @var{n} it's how many bits to the most significant
1585 zero bit in twos complement form.
1588 (integer-length #b10101010) @result{} 8
1589 (integer-length #b1111) @result{} 4
1590 (integer-length 0) @result{} 0
1591 (integer-length -1) @result{} 0
1592 (integer-length -256) @result{} 8
1593 (integer-length -257) @result{} 9
1597 @deffn {Scheme Procedure} integer-expt n k
1598 @deffnx {C Function} scm_integer_expt (n, k)
1599 Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1600 integer, @var{n} can be any number.
1602 Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1603 in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1607 (integer-expt 2 5) @result{} 32
1608 (integer-expt -3 3) @result{} -27
1609 (integer-expt 5 -3) @result{} 1/125
1610 (integer-expt 0 0) @result{} 1
1614 @deffn {Scheme Procedure} bit-extract n start end
1615 @deffnx {C Function} scm_bit_extract (n, start, end)
1616 Return the integer composed of the @var{start} (inclusive)
1617 through @var{end} (exclusive) bits of @var{n}. The
1618 @var{start}th bit becomes the 0-th bit in the result.
1621 (number->string (bit-extract #b1101101010 0 4) 2)
1623 (number->string (bit-extract #b1101101010 4 9) 2)
1630 @subsubsection Random Number Generation
1632 Pseudo-random numbers are generated from a random state object, which
1633 can be created with @code{seed->random-state}. The @var{state}
1634 parameter to the various functions below is optional, it defaults to
1635 the state object in the @code{*random-state*} variable.
1637 @deffn {Scheme Procedure} copy-random-state [state]
1638 @deffnx {C Function} scm_copy_random_state (state)
1639 Return a copy of the random state @var{state}.
1642 @deffn {Scheme Procedure} random n [state]
1643 @deffnx {C Function} scm_random (n, state)
1644 Return a number in [0, @var{n}).
1646 Accepts a positive integer or real n and returns a
1647 number of the same type between zero (inclusive) and
1648 @var{n} (exclusive). The values returned have a uniform
1652 @deffn {Scheme Procedure} random:exp [state]
1653 @deffnx {C Function} scm_random_exp (state)
1654 Return an inexact real in an exponential distribution with mean
1655 1. For an exponential distribution with mean @var{u} use @code{(*
1656 @var{u} (random:exp))}.
1659 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1660 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1661 Fills @var{vect} with inexact real random numbers the sum of whose
1662 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1663 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1664 the coordinates are uniformly distributed over the surface of the unit
1668 @deffn {Scheme Procedure} random:normal [state]
1669 @deffnx {C Function} scm_random_normal (state)
1670 Return an inexact real in a normal distribution. The distribution
1671 used has mean 0 and standard deviation 1. For a normal distribution
1672 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1673 (* @var{d} (random:normal)))}.
1676 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1677 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1678 Fills @var{vect} with inexact real random numbers that are
1679 independent and standard normally distributed
1680 (i.e., with mean 0 and variance 1).
1683 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1684 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1685 Fills @var{vect} with inexact real random numbers the sum of whose
1686 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1687 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1688 the coordinates are uniformly distributed within the unit
1690 @c FIXME: What does this mean, particularly the n-sphere part?
1693 @deffn {Scheme Procedure} random:uniform [state]
1694 @deffnx {C Function} scm_random_uniform (state)
1695 Return a uniformly distributed inexact real random number in
1699 @deffn {Scheme Procedure} seed->random-state seed
1700 @deffnx {C Function} scm_seed_to_random_state (seed)
1701 Return a new random state using @var{seed}.
1704 @defvar *random-state*
1705 The global random state used by the above functions when the
1706 @var{state} parameter is not given.
1711 @subsection Characters
1714 In Scheme, a character literal is written as @code{#\@var{name}} where
1715 @var{name} is the name of the character that you want. Printable
1716 characters have their usual single character name; for example,
1717 @code{#\a} is a lower case @code{a}.
1719 Most of the ``control characters'' (those below codepoint 32) in the
1720 @acronym{ASCII} character set, as well as the space, may be referred
1721 to by longer names: for example, @code{#\tab}, @code{#\esc},
1722 @code{#\stx}, and so on. The following table describes the
1723 @acronym{ASCII} names for each character.
1725 @multitable @columnfractions .25 .25 .25 .25
1726 @item 0 = @code{#\nul}
1727 @tab 1 = @code{#\soh}
1728 @tab 2 = @code{#\stx}
1729 @tab 3 = @code{#\etx}
1730 @item 4 = @code{#\eot}
1731 @tab 5 = @code{#\enq}
1732 @tab 6 = @code{#\ack}
1733 @tab 7 = @code{#\bel}
1734 @item 8 = @code{#\bs}
1735 @tab 9 = @code{#\ht}
1736 @tab 10 = @code{#\nl}
1737 @tab 11 = @code{#\vt}
1738 @item 12 = @code{#\np}
1739 @tab 13 = @code{#\cr}
1740 @tab 14 = @code{#\so}
1741 @tab 15 = @code{#\si}
1742 @item 16 = @code{#\dle}
1743 @tab 17 = @code{#\dc1}
1744 @tab 18 = @code{#\dc2}
1745 @tab 19 = @code{#\dc3}
1746 @item 20 = @code{#\dc4}
1747 @tab 21 = @code{#\nak}
1748 @tab 22 = @code{#\syn}
1749 @tab 23 = @code{#\etb}
1750 @item 24 = @code{#\can}
1751 @tab 25 = @code{#\em}
1752 @tab 26 = @code{#\sub}
1753 @tab 27 = @code{#\esc}
1754 @item 28 = @code{#\fs}
1755 @tab 29 = @code{#\gs}
1756 @tab 30 = @code{#\rs}
1757 @tab 31 = @code{#\us}
1758 @item 32 = @code{#\sp}
1761 The ``delete'' character (octal 177) may be referred to with the name
1764 Several characters have more than one name:
1766 @multitable {@code{#\backspace}} {Original}
1767 @item Alias @tab Original
1768 @item @code{#\space} @tab @code{#\sp}
1769 @item @code{#\newline} @tab @code{#\nl}
1770 @item @code{#\tab} @tab @code{#\ht}
1771 @item @code{#\backspace} @tab @code{#\bs}
1772 @item @code{#\return} @tab @code{#\cr}
1773 @item @code{#\page} @tab @code{#\np}
1774 @item @code{#\null} @tab @code{#\nul}
1778 @deffn {Scheme Procedure} char? x
1779 @deffnx {C Function} scm_char_p (x)
1780 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1784 @deffn {Scheme Procedure} char=? x y
1785 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1789 @deffn {Scheme Procedure} char<? x y
1790 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence,
1795 @deffn {Scheme Procedure} char<=? x y
1796 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1797 @acronym{ASCII} sequence, else @code{#f}.
1801 @deffn {Scheme Procedure} char>? x y
1802 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1803 sequence, else @code{#f}.
1807 @deffn {Scheme Procedure} char>=? x y
1808 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1809 @acronym{ASCII} sequence, else @code{#f}.
1813 @deffn {Scheme Procedure} char-ci=? x y
1814 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1815 case, else @code{#f}.
1819 @deffn {Scheme Procedure} char-ci<? x y
1820 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence
1821 ignoring case, else @code{#f}.
1825 @deffn {Scheme Procedure} char-ci<=? x y
1826 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1827 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1831 @deffn {Scheme Procedure} char-ci>? x y
1832 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1833 sequence ignoring case, else @code{#f}.
1837 @deffn {Scheme Procedure} char-ci>=? x y
1838 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1839 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1842 @rnindex char-alphabetic?
1843 @deffn {Scheme Procedure} char-alphabetic? chr
1844 @deffnx {C Function} scm_char_alphabetic_p (chr)
1845 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1848 @rnindex char-numeric?
1849 @deffn {Scheme Procedure} char-numeric? chr
1850 @deffnx {C Function} scm_char_numeric_p (chr)
1851 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1854 @rnindex char-whitespace?
1855 @deffn {Scheme Procedure} char-whitespace? chr
1856 @deffnx {C Function} scm_char_whitespace_p (chr)
1857 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1860 @rnindex char-upper-case?
1861 @deffn {Scheme Procedure} char-upper-case? chr
1862 @deffnx {C Function} scm_char_upper_case_p (chr)
1863 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1866 @rnindex char-lower-case?
1867 @deffn {Scheme Procedure} char-lower-case? chr
1868 @deffnx {C Function} scm_char_lower_case_p (chr)
1869 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1872 @deffn {Scheme Procedure} char-is-both? chr
1873 @deffnx {C Function} scm_char_is_both_p (chr)
1874 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1878 @rnindex char->integer
1879 @deffn {Scheme Procedure} char->integer chr
1880 @deffnx {C Function} scm_char_to_integer (chr)
1881 Return the number corresponding to ordinal position of @var{chr} in the
1882 @acronym{ASCII} sequence.
1885 @rnindex integer->char
1886 @deffn {Scheme Procedure} integer->char n
1887 @deffnx {C Function} scm_integer_to_char (n)
1888 Return the character at position @var{n} in the @acronym{ASCII} sequence.
1891 @rnindex char-upcase
1892 @deffn {Scheme Procedure} char-upcase chr
1893 @deffnx {C Function} scm_char_upcase (chr)
1894 Return the uppercase character version of @var{chr}.
1897 @rnindex char-downcase
1898 @deffn {Scheme Procedure} char-downcase chr
1899 @deffnx {C Function} scm_char_downcase (chr)
1900 Return the lowercase character version of @var{chr}.
1903 @node Character Sets
1904 @subsection Character Sets
1906 The features described in this section correspond directly to SRFI-14.
1908 The data type @dfn{charset} implements sets of characters
1909 (@pxref{Characters}). Because the internal representation of
1910 character sets is not visible to the user, a lot of procedures for
1911 handling them are provided.
1913 Character sets can be created, extended, tested for the membership of a
1914 characters and be compared to other character sets.
1916 The Guile implementation of character sets currently deals only with
1917 8-bit characters. In the future, when Guile gets support for
1918 international character sets, this will change, but the functions
1919 provided here will always then be able to efficiently cope with very
1920 large character sets.
1923 * Character Set Predicates/Comparison::
1924 * Iterating Over Character Sets:: Enumerate charset elements.
1925 * Creating Character Sets:: Making new charsets.
1926 * Querying Character Sets:: Test charsets for membership etc.
1927 * Character-Set Algebra:: Calculating new charsets.
1928 * Standard Character Sets:: Variables containing predefined charsets.
1931 @node Character Set Predicates/Comparison
1932 @subsubsection Character Set Predicates/Comparison
1934 Use these procedures for testing whether an object is a character set,
1935 or whether several character sets are equal or subsets of each other.
1936 @code{char-set-hash} can be used for calculating a hash value, maybe for
1937 usage in fast lookup procedures.
1939 @deffn {Scheme Procedure} char-set? obj
1940 @deffnx {C Function} scm_char_set_p (obj)
1941 Return @code{#t} if @var{obj} is a character set, @code{#f}
1945 @deffn {Scheme Procedure} char-set= . char_sets
1946 @deffnx {C Function} scm_char_set_eq (char_sets)
1947 Return @code{#t} if all given character sets are equal.
1950 @deffn {Scheme Procedure} char-set<= . char_sets
1951 @deffnx {C Function} scm_char_set_leq (char_sets)
1952 Return @code{#t} if every character set @var{cs}i is a subset
1953 of character set @var{cs}i+1.
1956 @deffn {Scheme Procedure} char-set-hash cs [bound]
1957 @deffnx {C Function} scm_char_set_hash (cs, bound)
1958 Compute a hash value for the character set @var{cs}. If
1959 @var{bound} is given and non-zero, it restricts the
1960 returned value to the range 0 @dots{} @var{bound - 1}.
1963 @c ===================================================================
1965 @node Iterating Over Character Sets
1966 @subsubsection Iterating Over Character Sets
1968 Character set cursors are a means for iterating over the members of a
1969 character sets. After creating a character set cursor with
1970 @code{char-set-cursor}, a cursor can be dereferenced with
1971 @code{char-set-ref}, advanced to the next member with
1972 @code{char-set-cursor-next}. Whether a cursor has passed past the last
1973 element of the set can be checked with @code{end-of-char-set?}.
1975 Additionally, mapping and (un-)folding procedures for character sets are
1978 @deffn {Scheme Procedure} char-set-cursor cs
1979 @deffnx {C Function} scm_char_set_cursor (cs)
1980 Return a cursor into the character set @var{cs}.
1983 @deffn {Scheme Procedure} char-set-ref cs cursor
1984 @deffnx {C Function} scm_char_set_ref (cs, cursor)
1985 Return the character at the current cursor position
1986 @var{cursor} in the character set @var{cs}. It is an error to
1987 pass a cursor for which @code{end-of-char-set?} returns true.
1990 @deffn {Scheme Procedure} char-set-cursor-next cs cursor
1991 @deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
1992 Advance the character set cursor @var{cursor} to the next
1993 character in the character set @var{cs}. It is an error if the
1994 cursor given satisfies @code{end-of-char-set?}.
1997 @deffn {Scheme Procedure} end-of-char-set? cursor
1998 @deffnx {C Function} scm_end_of_char_set_p (cursor)
1999 Return @code{#t} if @var{cursor} has reached the end of a
2000 character set, @code{#f} otherwise.
2003 @deffn {Scheme Procedure} char-set-fold kons knil cs
2004 @deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2005 Fold the procedure @var{kons} over the character set @var{cs},
2006 initializing it with @var{knil}.
2009 @deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2010 @deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2011 This is a fundamental constructor for character sets.
2013 @item @var{g} is used to generate a series of ``seed'' values
2014 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2015 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2016 @item @var{p} tells us when to stop -- when it returns true
2017 when applied to one of the seed values.
2018 @item @var{f} maps each seed value to a character. These
2019 characters are added to the base character set @var{base_cs} to
2020 form the result; @var{base_cs} defaults to the empty set.
2024 @deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2025 @deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2026 This is a fundamental constructor for character sets.
2028 @item @var{g} is used to generate a series of ``seed'' values
2029 from the initial seed: @var{seed}, (@var{g} @var{seed}),
2030 (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2031 @item @var{p} tells us when to stop -- when it returns true
2032 when applied to one of the seed values.
2033 @item @var{f} maps each seed value to a character. These
2034 characters are added to the base character set @var{base_cs} to
2035 form the result; @var{base_cs} defaults to the empty set.
2039 @deffn {Scheme Procedure} char-set-for-each proc cs
2040 @deffnx {C Function} scm_char_set_for_each (proc, cs)
2041 Apply @var{proc} to every character in the character set
2042 @var{cs}. The return value is not specified.
2045 @deffn {Scheme Procedure} char-set-map proc cs
2046 @deffnx {C Function} scm_char_set_map (proc, cs)
2047 Map the procedure @var{proc} over every character in @var{cs}.
2048 @var{proc} must be a character -> character procedure.
2051 @c ===================================================================
2053 @node Creating Character Sets
2054 @subsubsection Creating Character Sets
2056 New character sets are produced with these procedures.
2058 @deffn {Scheme Procedure} char-set-copy cs
2059 @deffnx {C Function} scm_char_set_copy (cs)
2060 Return a newly allocated character set containing all
2061 characters in @var{cs}.
2064 @deffn {Scheme Procedure} char-set . rest
2065 @deffnx {C Function} scm_char_set (rest)
2066 Return a character set containing all given characters.
2069 @deffn {Scheme Procedure} list->char-set list [base_cs]
2070 @deffnx {C Function} scm_list_to_char_set (list, base_cs)
2071 Convert the character list @var{list} to a character set. If
2072 the character set @var{base_cs} is given, the character in this
2073 set are also included in the result.
2076 @deffn {Scheme Procedure} list->char-set! list base_cs
2077 @deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2078 Convert the character list @var{list} to a character set. The
2079 characters are added to @var{base_cs} and @var{base_cs} is
2083 @deffn {Scheme Procedure} string->char-set str [base_cs]
2084 @deffnx {C Function} scm_string_to_char_set (str, base_cs)
2085 Convert the string @var{str} to a character set. If the
2086 character set @var{base_cs} is given, the characters in this
2087 set are also included in the result.
2090 @deffn {Scheme Procedure} string->char-set! str base_cs
2091 @deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2092 Convert the string @var{str} to a character set. The
2093 characters from the string are added to @var{base_cs}, and
2094 @var{base_cs} is returned.
2097 @deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2098 @deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2099 Return a character set containing every character from @var{cs}
2100 so that it satisfies @var{pred}. If provided, the characters
2101 from @var{base_cs} are added to the result.
2104 @deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2105 @deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2106 Return a character set containing every character from @var{cs}
2107 so that it satisfies @var{pred}. The characters are added to
2108 @var{base_cs} and @var{base_cs} is returned.
2111 @deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2112 @deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2113 Return a character set containing all characters whose
2114 character codes lie in the half-open range
2115 [@var{lower},@var{upper}).
2117 If @var{error} is a true value, an error is signalled if the
2118 specified range contains characters which are not contained in
2119 the implemented character range. If @var{error} is @code{#f},
2120 these characters are silently left out of the resultung
2123 The characters in @var{base_cs} are added to the result, if
2127 @deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2128 @deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2129 Return a character set containing all characters whose
2130 character codes lie in the half-open range
2131 [@var{lower},@var{upper}).
2133 If @var{error} is a true value, an error is signalled if the
2134 specified range contains characters which are not contained in
2135 the implemented character range. If @var{error} is @code{#f},
2136 these characters are silently left out of the resultung
2139 The characters are added to @var{base_cs} and @var{base_cs} is
2143 @deffn {Scheme Procedure} ->char-set x
2144 @deffnx {C Function} scm_to_char_set (x)
2145 Coerces x into a char-set. @var{x} may be a string, character or char-set. A string is converted to the set of its constituent characters; a character is converted to a singleton set; a char-set is returned as-is.
2148 @c ===================================================================
2150 @node Querying Character Sets
2151 @subsubsection Querying Character Sets
2153 Access the elements and other information of a character set with these
2156 @deffn {Scheme Procedure} char-set-size cs
2157 @deffnx {C Function} scm_char_set_size (cs)
2158 Return the number of elements in character set @var{cs}.
2161 @deffn {Scheme Procedure} char-set-count pred cs
2162 @deffnx {C Function} scm_char_set_count (pred, cs)
2163 Return the number of the elements int the character set
2164 @var{cs} which satisfy the predicate @var{pred}.
2167 @deffn {Scheme Procedure} char-set->list cs
2168 @deffnx {C Function} scm_char_set_to_list (cs)
2169 Return a list containing the elements of the character set
2173 @deffn {Scheme Procedure} char-set->string cs
2174 @deffnx {C Function} scm_char_set_to_string (cs)
2175 Return a string containing the elements of the character set
2176 @var{cs}. The order in which the characters are placed in the
2177 string is not defined.
2180 @deffn {Scheme Procedure} char-set-contains? cs ch
2181 @deffnx {C Function} scm_char_set_contains_p (cs, ch)
2182 Return @code{#t} iff the character @var{ch} is contained in the
2183 character set @var{cs}.
2186 @deffn {Scheme Procedure} char-set-every pred cs
2187 @deffnx {C Function} scm_char_set_every (pred, cs)
2188 Return a true value if every character in the character set
2189 @var{cs} satisfies the predicate @var{pred}.
2192 @deffn {Scheme Procedure} char-set-any pred cs
2193 @deffnx {C Function} scm_char_set_any (pred, cs)
2194 Return a true value if any character in the character set
2195 @var{cs} satisfies the predicate @var{pred}.
2198 @c ===================================================================
2200 @node Character-Set Algebra
2201 @subsubsection Character-Set Algebra
2203 Character sets can be manipulated with the common set algebra operation,
2204 such as union, complement, intersection etc. All of these procedures
2205 provide side-effecting variants, which modify their character set
2208 @deffn {Scheme Procedure} char-set-adjoin cs . rest
2209 @deffnx {C Function} scm_char_set_adjoin (cs, rest)
2210 Add all character arguments to the first argument, which must
2214 @deffn {Scheme Procedure} char-set-delete cs . rest
2215 @deffnx {C Function} scm_char_set_delete (cs, rest)
2216 Delete all character arguments from the first argument, which
2217 must be a character set.
2220 @deffn {Scheme Procedure} char-set-adjoin! cs . rest
2221 @deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2222 Add all character arguments to the first argument, which must
2226 @deffn {Scheme Procedure} char-set-delete! cs . rest
2227 @deffnx {C Function} scm_char_set_delete_x (cs, rest)
2228 Delete all character arguments from the first argument, which
2229 must be a character set.
2232 @deffn {Scheme Procedure} char-set-complement cs
2233 @deffnx {C Function} scm_char_set_complement (cs)
2234 Return the complement of the character set @var{cs}.
2237 @deffn {Scheme Procedure} char-set-union . rest
2238 @deffnx {C Function} scm_char_set_union (rest)
2239 Return the union of all argument character sets.
2242 @deffn {Scheme Procedure} char-set-intersection . rest
2243 @deffnx {C Function} scm_char_set_intersection (rest)
2244 Return the intersection of all argument character sets.
2247 @deffn {Scheme Procedure} char-set-difference cs1 . rest
2248 @deffnx {C Function} scm_char_set_difference (cs1, rest)
2249 Return the difference of all argument character sets.
2252 @deffn {Scheme Procedure} char-set-xor . rest
2253 @deffnx {C Function} scm_char_set_xor (rest)
2254 Return the exclusive-or of all argument character sets.
2257 @deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2258 @deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2259 Return the difference and the intersection of all argument
2263 @deffn {Scheme Procedure} char-set-complement! cs
2264 @deffnx {C Function} scm_char_set_complement_x (cs)
2265 Return the complement of the character set @var{cs}.
2268 @deffn {Scheme Procedure} char-set-union! cs1 . rest
2269 @deffnx {C Function} scm_char_set_union_x (cs1, rest)
2270 Return the union of all argument character sets.
2273 @deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2274 @deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2275 Return the intersection of all argument character sets.
2278 @deffn {Scheme Procedure} char-set-difference! cs1 . rest
2279 @deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2280 Return the difference of all argument character sets.
2283 @deffn {Scheme Procedure} char-set-xor! cs1 . rest
2284 @deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2285 Return the exclusive-or of all argument character sets.
2288 @deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2289 @deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2290 Return the difference and the intersection of all argument
2294 @c ===================================================================
2296 @node Standard Character Sets
2297 @subsubsection Standard Character Sets
2299 In order to make the use of the character set data type and procedures
2300 useful, several predefined character set variables exist.
2306 Currently, the contents of these character sets are recomputed upon a
2307 successful @code{setlocale} call (@pxref{Locales}) in order to reflect
2308 the characters available in the current locale's codeset. For
2309 instance, @code{char-set:letter} contains 52 characters under an ASCII
2310 locale (e.g., the default @code{C} locale) and 117 characters under an
2311 ISO-8859-1 (``Latin-1'') locale.
2313 @defvr {Scheme Variable} char-set:lower-case
2314 @defvrx {C Variable} scm_char_set_lower_case
2315 All lower-case characters.
2318 @defvr {Scheme Variable} char-set:upper-case
2319 @defvrx {C Variable} scm_char_set_upper_case
2320 All upper-case characters.
2323 @defvr {Scheme Variable} char-set:title-case
2324 @defvrx {C Variable} scm_char_set_title_case
2325 This is empty, because ASCII has no titlecase characters.
2328 @defvr {Scheme Variable} char-set:letter
2329 @defvrx {C Variable} scm_char_set_letter
2330 All letters, e.g. the union of @code{char-set:lower-case} and
2331 @code{char-set:upper-case}.
2334 @defvr {Scheme Variable} char-set:digit
2335 @defvrx {C Variable} scm_char_set_digit
2339 @defvr {Scheme Variable} char-set:letter+digit
2340 @defvrx {C Variable} scm_char_set_letter_and_digit
2341 The union of @code{char-set:letter} and @code{char-set:digit}.
2344 @defvr {Scheme Variable} char-set:graphic
2345 @defvrx {C Variable} scm_char_set_graphic
2346 All characters which would put ink on the paper.
2349 @defvr {Scheme Variable} char-set:printing
2350 @defvrx {C Variable} scm_char_set_printing
2351 The union of @code{char-set:graphic} and @code{char-set:whitespace}.
2354 @defvr {Scheme Variable} char-set:whitespace
2355 @defvrx {C Variable} scm_char_set_whitespace
2356 All whitespace characters.
2359 @defvr {Scheme Variable} char-set:blank
2360 @defvrx {C Variable} scm_char_set_blank
2361 All horizontal whitespace characters, that is @code{#\space} and
2365 @defvr {Scheme Variable} char-set:iso-control
2366 @defvrx {C Variable} scm_char_set_iso_control
2367 The ISO control characters with the codes 0--31 and 127.
2370 @defvr {Scheme Variable} char-set:punctuation
2371 @defvrx {C Variable} scm_char_set_punctuation
2372 The characters @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
2375 @defvr {Scheme Variable} char-set:symbol
2376 @defvrx {C Variable} scm_char_set_symbol
2377 The characters @code{$+<=>^`|~}.
2380 @defvr {Scheme Variable} char-set:hex-digit
2381 @defvrx {C Variable} scm_char_set_hex_digit
2382 The hexadecimal digits @code{0123456789abcdefABCDEF}.
2385 @defvr {Scheme Variable} char-set:ascii
2386 @defvrx {C Variable} scm_char_set_ascii
2387 All ASCII characters.
2390 @defvr {Scheme Variable} char-set:empty
2391 @defvrx {C Variable} scm_char_set_empty
2392 The empty character set.
2395 @defvr {Scheme Variable} char-set:full
2396 @defvrx {C Variable} scm_char_set_full
2397 This character set contains all possible characters.
2404 Strings are fixed-length sequences of characters. They can be created
2405 by calling constructor procedures, but they can also literally get
2406 entered at the @acronym{REPL} or in Scheme source files.
2408 @c Guile provides a rich set of string processing procedures, because text
2409 @c handling is very important when Guile is used as a scripting language.
2411 Strings always carry the information about how many characters they are
2412 composed of with them, so there is no special end-of-string character,
2413 like in C. That means that Scheme strings can contain any character,
2414 even the @samp{#\nul} character @samp{\0}.
2416 To use strings efficiently, you need to know a bit about how Guile
2417 implements them. In Guile, a string consists of two parts, a head and
2418 the actual memory where the characters are stored. When a string (or
2419 a substring of it) is copied, only a new head gets created, the memory
2420 is usually not copied. The two heads start out pointing to the same
2423 When one of these two strings is modified, as with @code{string-set!},
2424 their common memory does get copied so that each string has its own
2425 memory and modifying one does not accidently modify the other as well.
2426 Thus, Guile's strings are `copy on write'; the actual copying of their
2427 memory is delayed until one string is written to.
2429 This implementation makes functions like @code{substring} very
2430 efficient in the common case that no modifications are done to the
2433 If you do know that your strings are getting modified right away, you
2434 can use @code{substring/copy} instead of @code{substring}. This
2435 function performs the copy immediately at the time of creation. This
2436 is more efficient, especially in a multi-threaded program. Also,
2437 @code{substring/copy} can avoid the problem that a short substring
2438 holds on to the memory of a very large original string that could
2439 otherwise be recycled.
2441 If you want to avoid the copy altogether, so that modifications of one
2442 string show up in the other, you can use @code{substring/shared}. The
2443 strings created by this procedure are called @dfn{mutation sharing
2444 substrings} since the substring and the original string share
2445 modifications to each other.
2447 If you want to prevent modifications, use @code{substring/read-only}.
2449 Guile provides all procedures of SRFI-13 and a few more.
2452 * String Syntax:: Read syntax for strings.
2453 * String Predicates:: Testing strings for certain properties.
2454 * String Constructors:: Creating new string objects.
2455 * List/String Conversion:: Converting from/to lists of characters.
2456 * String Selection:: Select portions from strings.
2457 * String Modification:: Modify parts or whole strings.
2458 * String Comparison:: Lexicographic ordering predicates.
2459 * String Searching:: Searching in strings.
2460 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2461 * Reversing and Appending Strings:: Appending strings to form a new string.
2462 * Mapping Folding and Unfolding:: Iterating over strings.
2463 * Miscellaneous String Operations:: Replicating, insertion, parsing, ...
2464 * Conversion to/from C::
2468 @subsubsection String Read Syntax
2470 @c In the following @code is used to get a good font in TeX etc, but
2471 @c is omitted for Info format, so as not to risk any confusion over
2472 @c whether surrounding ` ' quotes are part of the escape or are
2473 @c special in a string (they're not).
2475 The read syntax for strings is an arbitrarily long sequence of
2476 characters enclosed in double quotes (@nicode{"}).
2478 Backslash is an escape character and can be used to insert the
2479 following special characters. @nicode{\"} and @nicode{\\} are R5RS
2480 standard, the rest are Guile extensions, notice they follow C string
2485 Backslash character.
2488 Double quote character (an unescaped @nicode{"} is otherwise the end
2492 NUL character (ASCII 0).
2495 Bell character (ASCII 7).
2498 Formfeed character (ASCII 12).
2501 Newline character (ASCII 10).
2504 Carriage return character (ASCII 13).
2507 Tab character (ASCII 9).
2510 Vertical tab character (ASCII 11).
2513 Character code given by two hexadecimal digits. For example
2514 @nicode{\x7f} for an ASCII DEL (127).
2518 The following are examples of string literals:
2528 @node String Predicates
2529 @subsubsection String Predicates
2531 The following procedures can be used to check whether a given string
2532 fulfills some specified property.
2535 @deffn {Scheme Procedure} string? obj
2536 @deffnx {C Function} scm_string_p (obj)
2537 Return @code{#t} if @var{obj} is a string, else @code{#f}.
2540 @deftypefn {C Function} int scm_is_string (SCM obj)
2541 Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2544 @deffn {Scheme Procedure} string-null? str
2545 @deffnx {C Function} scm_string_null_p (str)
2546 Return @code{#t} if @var{str}'s length is zero, and
2547 @code{#f} otherwise.
2549 (string-null? "") @result{} #t
2551 (string-null? y) @result{} #f
2555 @deffn {Scheme Procedure} string-any char_pred s [start [end]]
2556 @deffnx {C Function} scm_string_any (char_pred, s, start, end)
2557 Check if @var{char_pred} is true for any character in string @var{s}.
2559 @var{char_pred} can be a character to check for any equal to that, or
2560 a character set (@pxref{Character Sets}) to check for any in that set,
2561 or a predicate procedure to call.
2563 For a procedure, calls @code{(@var{char_pred} c)} are made
2564 successively on the characters from @var{start} to @var{end}. If
2565 @var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2566 stops and that return value is the return from @code{string-any}. The
2567 call on the last character (ie.@: at @math{@var{end}-1}), if that
2568 point is reached, is a tail call.
2570 If there are no characters in @var{s} (ie.@: @var{start} equals
2571 @var{end}) then the return is @code{#f}.
2574 @deffn {Scheme Procedure} string-every char_pred s [start [end]]
2575 @deffnx {C Function} scm_string_every (char_pred, s, start, end)
2576 Check if @var{char_pred} is true for every character in string
2579 @var{char_pred} can be a character to check for every character equal
2580 to that, or a character set (@pxref{Character Sets}) to check for
2581 every character being in that set, or a predicate procedure to call.
2583 For a procedure, calls @code{(@var{char_pred} c)} are made
2584 successively on the characters from @var{start} to @var{end}. If
2585 @var{char_pred} returns @code{#f}, @code{string-every} stops and
2586 returns @code{#f}. The call on the last character (ie.@: at
2587 @math{@var{end}-1}), if that point is reached, is a tail call and the
2588 return from that call is the return from @code{string-every}.
2590 If there are no characters in @var{s} (ie.@: @var{start} equals
2591 @var{end}) then the return is @code{#t}.
2594 @node String Constructors
2595 @subsubsection String Constructors
2597 The string constructor procedures create new string objects, possibly
2598 initializing them with some specified character data. See also
2599 @xref{String Selection}, for ways to create strings from existing
2602 @c FIXME::martin: list->string belongs into `List/String Conversion'
2604 @deffn {Scheme Procedure} string char@dots{}
2606 Return a newly allocated string made from the given character
2610 (string #\x #\y #\z) @result{} "xyz"
2611 (string) @result{} ""
2615 @deffn {Scheme Procedure} list->string lst
2616 @deffnx {C Function} scm_string (lst)
2617 @rnindex list->string
2618 Return a newly allocated string made from a list of characters.
2621 (list->string '(#\a #\b #\c)) @result{} "abc"
2625 @deffn {Scheme Procedure} reverse-list->string lst
2626 @deffnx {C Function} scm_reverse_list_to_string (lst)
2627 Return a newly allocated string made from a list of characters, in
2631 (reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2635 @rnindex make-string
2636 @deffn {Scheme Procedure} make-string k [chr]
2637 @deffnx {C Function} scm_make_string (k, chr)
2638 Return a newly allocated string of
2639 length @var{k}. If @var{chr} is given, then all elements of
2640 the string are initialized to @var{chr}, otherwise the contents
2641 of the @var{string} are unspecified.
2644 @deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2645 Like @code{scm_make_string}, but expects the length as a
2649 @deffn {Scheme Procedure} string-tabulate proc len
2650 @deffnx {C Function} scm_string_tabulate (proc, len)
2651 @var{proc} is an integer->char procedure. Construct a string
2652 of size @var{len} by applying @var{proc} to each index to
2653 produce the corresponding string element. The order in which
2654 @var{proc} is applied to the indices is not specified.
2657 @deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2658 @deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2659 Append the string in the string list @var{ls}, using the string
2660 @var{delim} as a delimiter between the elements of @var{ls}.
2661 @var{grammar} is a symbol which specifies how the delimiter is
2662 placed between the strings, and defaults to the symbol
2667 Insert the separator between list elements. An empty string
2668 will produce an empty list.
2670 Like @code{infix}, but will raise an error if given the empty
2673 Insert the separator after every list element.
2675 Insert the separator before each list element.
2679 @node List/String Conversion
2680 @subsubsection List/String conversion
2682 When processing strings, it is often convenient to first convert them
2683 into a list representation by using the procedure @code{string->list},
2684 work with the resulting list, and then convert it back into a string.
2685 These procedures are useful for similar tasks.
2687 @rnindex string->list
2688 @deffn {Scheme Procedure} string->list str [start [end]]
2689 @deffnx {C Function} scm_substring_to_list (str, start, end)
2690 @deffnx {C Function} scm_string_to_list (str)
2691 Convert the string @var{str} into a list of characters.
2694 @deffn {Scheme Procedure} string-split str chr
2695 @deffnx {C Function} scm_string_split (str, chr)
2696 Split the string @var{str} into the a list of the substrings delimited
2697 by appearances of the character @var{chr}. Note that an empty substring
2698 between separator characters will result in an empty string in the
2702 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2704 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
2706 (string-split "::" #\:)
2710 (string-split "" #\:)
2717 @node String Selection
2718 @subsubsection String Selection
2720 Portions of strings can be extracted by these procedures.
2721 @code{string-ref} delivers individual characters whereas
2722 @code{substring} can be used to extract substrings from longer strings.
2724 @rnindex string-length
2725 @deffn {Scheme Procedure} string-length string
2726 @deffnx {C Function} scm_string_length (string)
2727 Return the number of characters in @var{string}.
2730 @deftypefn {C Function} size_t scm_c_string_length (SCM str)
2731 Return the number of characters in @var{str} as a @code{size_t}.
2735 @deffn {Scheme Procedure} string-ref str k
2736 @deffnx {C Function} scm_string_ref (str, k)
2737 Return character @var{k} of @var{str} using zero-origin
2738 indexing. @var{k} must be a valid index of @var{str}.
2741 @deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2742 Return character @var{k} of @var{str} using zero-origin
2743 indexing. @var{k} must be a valid index of @var{str}.
2746 @rnindex string-copy
2747 @deffn {Scheme Procedure} string-copy str [start [end]]
2748 @deffnx {C Function} scm_substring_copy (str, start, end)
2749 @deffnx {C Function} scm_string_copy (str)
2750 Return a copy of the given string @var{str}.
2752 The returned string shares storage with @var{str} initially, but it is
2753 copied as soon as one of the two strings is modified.
2757 @deffn {Scheme Procedure} substring str start [end]
2758 @deffnx {C Function} scm_substring (str, start, end)
2759 Return a new string formed from the characters
2760 of @var{str} beginning with index @var{start} (inclusive) and
2761 ending with index @var{end} (exclusive).
2762 @var{str} must be a string, @var{start} and @var{end} must be
2763 exact integers satisfying:
2765 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
2767 The returned string shares storage with @var{str} initially, but it is
2768 copied as soon as one of the two strings is modified.
2771 @deffn {Scheme Procedure} substring/shared str start [end]
2772 @deffnx {C Function} scm_substring_shared (str, start, end)
2773 Like @code{substring}, but the strings continue to share their storage
2774 even if they are modified. Thus, modifications to @var{str} show up
2775 in the new string, and vice versa.
2778 @deffn {Scheme Procedure} substring/copy str start [end]
2779 @deffnx {C Function} scm_substring_copy (str, start, end)
2780 Like @code{substring}, but the storage for the new string is copied
2784 @deffn {Scheme Procedure} substring/read-only str start [end]
2785 @deffnx {C Function} scm_substring_read_only (str, start, end)
2786 Like @code{substring}, but the resulting string can not be modified.
2789 @deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2790 @deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2791 @deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2792 @deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
2793 Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2796 @deffn {Scheme Procedure} string-take s n
2797 @deffnx {C Function} scm_string_take (s, n)
2798 Return the @var{n} first characters of @var{s}.
2801 @deffn {Scheme Procedure} string-drop s n
2802 @deffnx {C Function} scm_string_drop (s, n)
2803 Return all but the first @var{n} characters of @var{s}.
2806 @deffn {Scheme Procedure} string-take-right s n
2807 @deffnx {C Function} scm_string_take_right (s, n)
2808 Return the @var{n} last characters of @var{s}.
2811 @deffn {Scheme Procedure} string-drop-right s n
2812 @deffnx {C Function} scm_string_drop_right (s, n)
2813 Return all but the last @var{n} characters of @var{s}.
2816 @deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
2817 @deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
2818 @deffnx {C Function} scm_string_pad (s, len, chr, start, end)
2819 @deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
2820 Take characters @var{start} to @var{end} from the string @var{s} and
2821 either pad with @var{char} or truncate them to give @var{len}
2824 @code{string-pad} pads or truncates on the left, so for example
2827 (string-pad "x" 3) @result{} " x"
2828 (string-pad "abcde" 3) @result{} "cde"
2831 @code{string-pad-right} pads or truncates on the right, so for example
2834 (string-pad-right "x" 3) @result{} "x "
2835 (string-pad-right "abcde" 3) @result{} "abc"
2839 @deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
2840 @deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
2841 @deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
2842 @deffnx {C Function} scm_string_trim (s, char_pred, start, end)
2843 @deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
2844 @deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
2845 Trim occurrances of @var{char_pred} from the ends of @var{s}.
2847 @code{string-trim} trims @var{char_pred} characters from the left
2848 (start) of the string, @code{string-trim-right} trims them from the
2849 right (end) of the string, @code{string-trim-both} trims from both
2852 @var{char_pred} can be a character, a character set, or a predicate
2853 procedure to call on each character. If @var{char_pred} is not given
2854 the default is whitespace as per @code{char-set:whitespace}
2855 (@pxref{Standard Character Sets}).
2858 (string-trim " x ") @result{} "x "
2859 (string-trim-right "banana" #\a) @result{} "banan"
2860 (string-trim-both ".,xy:;" char-set:punctuation)
2862 (string-trim-both "xyzzy" (lambda (c)
2869 @node String Modification
2870 @subsubsection String Modification
2872 These procedures are for modifying strings in-place. This means that the
2873 result of the operation is not a new string; instead, the original string's
2874 memory representation is modified.
2876 @rnindex string-set!
2877 @deffn {Scheme Procedure} string-set! str k chr
2878 @deffnx {C Function} scm_string_set_x (str, k, chr)
2879 Store @var{chr} in element @var{k} of @var{str} and return
2880 an unspecified value. @var{k} must be a valid index of
2884 @deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
2885 Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
2888 @rnindex string-fill!
2889 @deffn {Scheme Procedure} string-fill! str chr [start [end]]
2890 @deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
2891 @deffnx {C Function} scm_string_fill_x (str, chr)
2892 Stores @var{chr} in every element of the given @var{str} and
2893 returns an unspecified value.
2896 @deffn {Scheme Procedure} substring-fill! str start end fill
2897 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
2898 Change every character in @var{str} between @var{start} and
2899 @var{end} to @var{fill}.
2902 (define y "abcdefg")
2903 (substring-fill! y 1 3 #\r)
2909 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
2910 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
2911 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
2912 into @var{str2} beginning at position @var{start2}.
2913 @var{str1} and @var{str2} can be the same string.
2916 @deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
2917 @deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
2918 Copy the sequence of characters from index range [@var{start},
2919 @var{end}) in string @var{s} to string @var{target}, beginning
2920 at index @var{tstart}. The characters are copied left-to-right
2921 or right-to-left as needed -- the copy is guaranteed to work,
2922 even if @var{target} and @var{s} are the same string. It is an
2923 error if the copy operation runs off the end of the target
2928 @node String Comparison
2929 @subsubsection String Comparison
2931 The procedures in this section are similar to the character ordering
2932 predicates (@pxref{Characters}), but are defined on character sequences.
2934 The first set is specified in R5RS and has names that end in @code{?}.
2935 The second set is specified in SRFI-13 and the names have no ending
2936 @code{?}. The predicates ending in @code{-ci} ignore the character case
2937 when comparing strings.
2940 @deffn {Scheme Procedure} string=? s1 s2
2941 Lexicographic equality predicate; return @code{#t} if the two
2942 strings are the same length and contain the same characters in
2943 the same positions, otherwise return @code{#f}.
2945 The procedure @code{string-ci=?} treats upper and lower case
2946 letters as though they were the same character, but
2947 @code{string=?} treats upper and lower case as distinct
2952 @deffn {Scheme Procedure} string<? s1 s2
2953 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2954 is lexicographically less than @var{s2}.
2958 @deffn {Scheme Procedure} string<=? s1 s2
2959 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2960 is lexicographically less than or equal to @var{s2}.
2964 @deffn {Scheme Procedure} string>? s1 s2
2965 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2966 is lexicographically greater than @var{s2}.
2970 @deffn {Scheme Procedure} string>=? s1 s2
2971 Lexicographic ordering predicate; return @code{#t} if @var{s1}
2972 is lexicographically greater than or equal to @var{s2}.
2975 @rnindex string-ci=?
2976 @deffn {Scheme Procedure} string-ci=? s1 s2
2977 Case-insensitive string equality predicate; return @code{#t} if
2978 the two strings are the same length and their component
2979 characters match (ignoring case) at each position; otherwise
2983 @rnindex string-ci<?
2984 @deffn {Scheme Procedure} string-ci<? s1 s2
2985 Case insensitive lexicographic ordering predicate; return
2986 @code{#t} if @var{s1} is lexicographically less than @var{s2}
2991 @deffn {Scheme Procedure} string-ci<=? s1 s2
2992 Case insensitive lexicographic ordering predicate; return
2993 @code{#t} if @var{s1} is lexicographically less than or equal
2994 to @var{s2} regardless of case.
2997 @rnindex string-ci>?
2998 @deffn {Scheme Procedure} string-ci>? s1 s2
2999 Case insensitive lexicographic ordering predicate; return
3000 @code{#t} if @var{s1} is lexicographically greater than
3001 @var{s2} regardless of case.
3004 @rnindex string-ci>=?
3005 @deffn {Scheme Procedure} string-ci>=? s1 s2
3006 Case insensitive lexicographic ordering predicate; return
3007 @code{#t} if @var{s1} is lexicographically greater than or
3008 equal to @var{s2} regardless of case.
3011 @deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3012 @deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3013 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3014 mismatch index, depending upon whether @var{s1} is less than,
3015 equal to, or greater than @var{s2}. The mismatch index is the
3016 largest index @var{i} such that for every 0 <= @var{j} <
3017 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3018 @var{i} is the first position that does not match.
3021 @deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3022 @deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3023 Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3024 mismatch index, depending upon whether @var{s1} is less than,
3025 equal to, or greater than @var{s2}. The mismatch index is the
3026 largest index @var{i} such that for every 0 <= @var{j} <
3027 @var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3028 @var{i} is the first position that does not match. The
3029 character comparison is done case-insensitively.
3032 @deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3033 @deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3034 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3038 @deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3039 @deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3040 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3044 @deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3045 @deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3046 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3047 true value otherwise.
3050 @deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3051 @deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3052 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3053 true value otherwise.
3056 @deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3057 @deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3058 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3062 @deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3063 @deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3064 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3068 @deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3069 @deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3070 Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3071 value otherwise. The character comparison is done
3075 @deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3076 @deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3077 Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3078 value otherwise. The character comparison is done
3082 @deffn {Scheme Procedure} string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
3083 @deffnx {C Function} scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
3084 Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3085 true value otherwise. The character comparison is done
3089 @deffn {Scheme Procedure} string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
3090 @deffnx {C Function} scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
3091 Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3092 true value otherwise. The character comparison is done
3096 @deffn {Scheme Procedure} string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
3097 @deffnx {C Function} scm_string_ci_le (s1, s2, start1, end1, start2, end2)
3098 Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3099 value otherwise. The character comparison is done
3103 @deffn {Scheme Procedure} string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
3104 @deffnx {C Function} scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
3105 Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3106 otherwise. The character comparison is done
3110 @deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3111 @deffnx {C Function} scm_substring_hash (s, bound, start, end)
3112 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).
3115 @deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3116 @deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3117 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).
3120 @node String Searching
3121 @subsubsection String Searching
3123 @deffn {Scheme Procedure} string-index s char_pred [start [end]]
3124 @deffnx {C Function} scm_string_index (s, char_pred, start, end)
3125 Search through the string @var{s} from left to right, returning
3126 the index of the first occurence of a character which
3130 equals @var{char_pred}, if it is character,
3133 satisifies the predicate @var{char_pred}, if it is a procedure,
3136 is in the set @var{char_pred}, if it is a character set.
3140 @deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3141 @deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3142 Search through the string @var{s} from right to left, returning
3143 the index of the last occurence of a character which
3147 equals @var{char_pred}, if it is character,
3150 satisifies the predicate @var{char_pred}, if it is a procedure,
3153 is in the set if @var{char_pred} is a character set.
3157 @deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3158 @deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3159 Return the length of the longest common prefix of the two
3163 @deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3164 @deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3165 Return the length of the longest common prefix of the two
3166 strings, ignoring character case.
3169 @deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3170 @deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3171 Return the length of the longest common suffix of the two
3175 @deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3176 @deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3177 Return the length of the longest common suffix of the two
3178 strings, ignoring character case.
3181 @deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3182 @deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3183 Is @var{s1} a prefix of @var{s2}?
3186 @deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3187 @deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3188 Is @var{s1} a prefix of @var{s2}, ignoring character case?
3191 @deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3192 @deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3193 Is @var{s1} a suffix of @var{s2}?
3196 @deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3197 @deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3198 Is @var{s1} a suffix of @var{s2}, ignoring character case?
3201 @deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3202 @deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3203 Search through the string @var{s} from right to left, returning
3204 the index of the last occurence of a character which
3208 equals @var{char_pred}, if it is character,
3211 satisifies the predicate @var{char_pred}, if it is a procedure,
3214 is in the set if @var{char_pred} is a character set.
3218 @deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3219 @deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3220 Search through the string @var{s} from left to right, returning
3221 the index of the first occurence of a character which
3225 does not equal @var{char_pred}, if it is character,
3228 does not satisify the predicate @var{char_pred}, if it is a
3232 is not in the set if @var{char_pred} is a character set.
3236 @deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3237 @deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3238 Search through the string @var{s} from right to left, returning
3239 the index of the last occurence of a character which
3243 does not equal @var{char_pred}, if it is character,
3246 does not satisfy the predicate @var{char_pred}, if it is a
3250 is not in the set if @var{char_pred} is a character set.
3254 @deffn {Scheme Procedure} string-count s char_pred [start [end]]
3255 @deffnx {C Function} scm_string_count (s, char_pred, start, end)
3256 Return the count of the number of characters in the string
3261 equals @var{char_pred}, if it is character,
3264 satisifies the predicate @var{char_pred}, if it is a procedure.
3267 is in the set @var{char_pred}, if it is a character set.
3271 @deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3272 @deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3273 Does string @var{s1} contain string @var{s2}? Return the index
3274 in @var{s1} where @var{s2} occurs as a substring, or false.
3275 The optional start/end indices restrict the operation to the
3276 indicated substrings.
3279 @deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3280 @deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3281 Does string @var{s1} contain string @var{s2}? Return the index
3282 in @var{s1} where @var{s2} occurs as a substring, or false.
3283 The optional start/end indices restrict the operation to the
3284 indicated substrings. Character comparison is done
3288 @node Alphabetic Case Mapping
3289 @subsubsection Alphabetic Case Mapping
3291 These are procedures for mapping strings to their upper- or lower-case
3292 equivalents, respectively, or for capitalizing strings.
3294 @deffn {Scheme Procedure} string-upcase str [start [end]]
3295 @deffnx {C Function} scm_substring_upcase (str, start, end)
3296 @deffnx {C Function} scm_string_upcase (str)
3297 Upcase every character in @code{str}.
3300 @deffn {Scheme Procedure} string-upcase! str [start [end]]
3301 @deffnx {C Function} scm_substring_upcase_x (str, start, end)
3302 @deffnx {C Function} scm_string_upcase_x (str)
3303 Destructively upcase every character in @code{str}.
3313 @deffn {Scheme Procedure} string-downcase str [start [end]]
3314 @deffnx {C Function} scm_substring_downcase (str, start, end)
3315 @deffnx {C Function} scm_string_downcase (str)
3316 Downcase every character in @var{str}.
3319 @deffn {Scheme Procedure} string-downcase! str [start [end]]
3320 @deffnx {C Function} scm_substring_downcase_x (str, start, end)
3321 @deffnx {C Function} scm_string_downcase_x (str)
3322 Destructively downcase every character in @var{str}.
3327 (string-downcase! y)
3334 @deffn {Scheme Procedure} string-capitalize str
3335 @deffnx {C Function} scm_string_capitalize (str)
3336 Return a freshly allocated string with the characters in
3337 @var{str}, where the first character of every word is
3341 @deffn {Scheme Procedure} string-capitalize! str
3342 @deffnx {C Function} scm_string_capitalize_x (str)
3343 Upcase the first character of every word in @var{str}
3344 destructively and return @var{str}.
3347 y @result{} "hello world"
3348 (string-capitalize! y) @result{} "Hello World"
3349 y @result{} "Hello World"
3353 @deffn {Scheme Procedure} string-titlecase str [start [end]]
3354 @deffnx {C Function} scm_string_titlecase (str, start, end)
3355 Titlecase every first character in a word in @var{str}.
3358 @deffn {Scheme Procedure} string-titlecase! str [start [end]]
3359 @deffnx {C Function} scm_string_titlecase_x (str, start, end)
3360 Destructively titlecase every first character in a word in
3364 @node Reversing and Appending Strings
3365 @subsubsection Reversing and Appending Strings
3367 @deffn {Scheme Procedure} string-reverse str [start [end]]
3368 @deffnx {C Function} scm_string_reverse (str, start, end)
3369 Reverse the string @var{str}. The optional arguments
3370 @var{start} and @var{end} delimit the region of @var{str} to
3374 @deffn {Scheme Procedure} string-reverse! str [start [end]]
3375 @deffnx {C Function} scm_string_reverse_x (str, start, end)
3376 Reverse the string @var{str} in-place. The optional arguments
3377 @var{start} and @var{end} delimit the region of @var{str} to
3378 operate on. The return value is unspecified.
3381 @rnindex string-append
3382 @deffn {Scheme Procedure} string-append . args
3383 @deffnx {C Function} scm_string_append (args)
3384 Return a newly allocated string whose characters form the
3385 concatenation of the given strings, @var{args}.
3389 (string-append h "world"))
3390 @result{} "hello world"
3394 @deffn {Scheme Procedure} string-append/shared . ls
3395 @deffnx {C Function} scm_string_append_shared (ls)
3396 Like @code{string-append}, but the result may share memory
3397 with the argument strings.
3400 @deffn {Scheme Procedure} string-concatenate ls
3401 @deffnx {C Function} scm_string_concatenate (ls)
3402 Append the elements of @var{ls} (which must be strings)
3403 together into a single string. Guaranteed to return a freshly
3407 @deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3408 @deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3409 Without optional arguments, this procedure is equivalent to
3412 (string-concatenate (reverse ls))
3415 If the optional argument @var{final_string} is specified, it is
3416 consed onto the beginning to @var{ls} before performing the
3417 list-reverse and string-concatenate operations. If @var{end}
3418 is given, only the characters of @var{final_string} up to index
3421 Guaranteed to return a freshly allocated string.
3424 @deffn {Scheme Procedure} string-concatenate/shared ls
3425 @deffnx {C Function} scm_string_concatenate_shared (ls)
3426 Like @code{string-concatenate}, but the result may share memory
3427 with the strings in the list @var{ls}.
3430 @deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3431 @deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3432 Like @code{string-concatenate-reverse}, but the result may
3433 share memory with the the strings in the @var{ls} arguments.
3436 @node Mapping Folding and Unfolding
3437 @subsubsection Mapping, Folding, and Unfolding
3439 @deffn {Scheme Procedure} string-map proc s [start [end]]
3440 @deffnx {C Function} scm_string_map (proc, s, start, end)
3441 @var{proc} is a char->char procedure, it is mapped over
3442 @var{s}. The order in which the procedure is applied to the
3443 string elements is not specified.
3446 @deffn {Scheme Procedure} string-map! proc s [start [end]]
3447 @deffnx {C Function} scm_string_map_x (proc, s, start, end)
3448 @var{proc} is a char->char procedure, it is mapped over
3449 @var{s}. The order in which the procedure is applied to the
3450 string elements is not specified. The string @var{s} is
3451 modified in-place, the return value is not specified.
3454 @deffn {Scheme Procedure} string-for-each proc s [start [end]]
3455 @deffnx {C Function} scm_string_for_each (proc, s, start, end)
3456 @var{proc} is mapped over @var{s} in left-to-right order. The
3457 return value is not specified.
3460 @deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3461 @deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
3462 Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3465 For example, to change characters to alternately upper and lower case,
3468 (define str (string-copy "studly"))
3469 (string-for-each-index (lambda (i)
3471 ((if (even? i) char-upcase char-downcase)
3472 (string-ref str i))))
3474 str @result{} "StUdLy"
3478 @deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3479 @deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3480 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3481 as the terminating element, from left to right. @var{kons}
3482 must expect two arguments: The actual character and the last
3483 result of @var{kons}' application.
3486 @deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3487 @deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3488 Fold @var{kons} over the characters of @var{s}, with @var{knil}
3489 as the terminating element, from right to left. @var{kons}
3490 must expect two arguments: The actual character and the last
3491 result of @var{kons}' application.
3494 @deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3495 @deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3497 @item @var{g} is used to generate a series of @emph{seed}
3498 values from the initial @var{seed}: @var{seed}, (@var{g}
3499 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3501 @item @var{p} tells us when to stop -- when it returns true
3502 when applied to one of these seed values.
3503 @item @var{f} maps each seed value to the corresponding
3504 character in the result string. These chars are assembled
3505 into the string in a left-to-right order.
3506 @item @var{base} is the optional initial/leftmost portion
3507 of the constructed string; it default to the empty
3509 @item @var{make_final} is applied to the terminal seed
3510 value (on which @var{p} returns true) to produce
3511 the final/rightmost portion of the constructed string.
3512 It defaults to @code{(lambda (x) )}.
3516 @deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3517 @deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3519 @item @var{g} is used to generate a series of @emph{seed}
3520 values from the initial @var{seed}: @var{seed}, (@var{g}
3521 @var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3523 @item @var{p} tells us when to stop -- when it returns true
3524 when applied to one of these seed values.
3525 @item @var{f} maps each seed value to the corresponding
3526 character in the result string. These chars are assembled
3527 into the string in a right-to-left order.
3528 @item @var{base} is the optional initial/rightmost portion
3529 of the constructed string; it default to the empty
3531 @item @var{make_final} is applied to the terminal seed
3532 value (on which @var{p} returns true) to produce
3533 the final/leftmost portion of the constructed string.
3534 It defaults to @code{(lambda (x) )}.
3538 @node Miscellaneous String Operations
3539 @subsubsection Miscellaneous String Operations
3541 @deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3542 @deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3543 This is the @emph{extended substring} procedure that implements
3544 replicated copying of a substring of some string.
3546 @var{s} is a string, @var{start} and @var{end} are optional
3547 arguments that demarcate a substring of @var{s}, defaulting to
3548 0 and the length of @var{s}. Replicate this substring up and
3549 down index space, in both the positive and negative directions.
3550 @code{xsubstring} returns the substring of this string
3551 beginning at index @var{from}, and ending at @var{to}, which
3552 defaults to @var{from} + (@var{end} - @var{start}).
3555 @deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3556 @deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3557 Exactly the same as @code{xsubstring}, but the extracted text
3558 is written into the string @var{target} starting at index
3559 @var{tstart}. The operation is not defined if @code{(eq?
3560 @var{target} @var{s})} or these arguments share storage -- you
3561 cannot copy a string on top of itself.
3564 @deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3565 @deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3566 Return the string @var{s1}, but with the characters
3567 @var{start1} @dots{} @var{end1} replaced by the characters
3568 @var{start2} @dots{} @var{end2} from @var{s2}.
3571 @deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3572 @deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3573 Split the string @var{s} into a list of substrings, where each
3574 substring is a maximal non-empty contiguous sequence of
3575 characters from the character set @var{token_set}, which
3576 defaults to @code{char-set:graphic}.
3577 If @var{start} or @var{end} indices are provided, they restrict
3578 @code{string-tokenize} to operating on the indicated substring
3582 @deffn {Scheme Procedure} string-filter s char_pred [start [end]]
3583 @deffnx {C Function} scm_string_filter (s, char_pred, start, end)
3584 Filter the string @var{s}, retaining only those characters which
3585 satisfy @var{char_pred}.
3587 If @var{char_pred} is a procedure, it is applied to each character as
3588 a predicate, if it is a character, it is tested for equality and if it
3589 is a character set, it is tested for membership.
3592 @deffn {Scheme Procedure} string-delete s char_pred [start [end]]
3593 @deffnx {C Function} scm_string_delete (s, char_pred, start, end)
3594 Delete characters satisfying @var{char_pred} from @var{s}.
3596 If @var{char_pred} is a procedure, it is applied to each character as
3597 a predicate, if it is a character, it is tested for equality and if it
3598 is a character set, it is tested for membership.
3601 @node Conversion to/from C
3602 @subsubsection Conversion to/from C
3604 When creating a Scheme string from a C string or when converting a
3605 Scheme string to a C string, the concept of character encoding becomes
3608 In C, a string is just a sequence of bytes, and the character encoding
3609 describes the relation between these bytes and the actual characters
3610 that make up the string. For Scheme strings, character encoding is
3611 not an issue (most of the time), since in Scheme you never get to see
3612 the bytes, only the characters.
3614 Well, ideally, anyway. Right now, Guile simply equates Scheme
3615 characters and bytes, ignoring the possibility of multi-byte encodings
3616 completely. This will change in the future, where Guile will use
3617 Unicode codepoints as its characters and UTF-8 or some other encoding
3618 as its internal encoding. When you exclusively use the functions
3619 listed in this section, you are `future-proof'.
3621 Converting a Scheme string to a C string will often allocate fresh
3622 memory to hold the result. You must take care that this memory is
3623 properly freed eventually. In many cases, this can be achieved by
3624 using @code{scm_dynwind_free} inside an appropriate dynwind context,
3625 @xref{Dynamic Wind}.
3627 @deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3628 @deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3629 Creates a new Scheme string that has the same contents as @var{str}
3630 when interpreted in the current locale character encoding.
3632 For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3634 For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3635 @var{str} in bytes, and @var{str} does not need to be null-terminated.
3636 If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3637 null-terminated and the real length will be found with @code{strlen}.
3640 @deftypefn {C Function} SCM scm_take_locale_string (char *str)
3641 @deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3642 Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3643 respectively, but also frees @var{str} with @code{free} eventually.
3644 Thus, you can use this function when you would free @var{str} anyway
3645 immediately after creating the Scheme string. In certain cases, Guile
3646 can then use @var{str} directly as its internal representation.
3649 @deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3650 @deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
3651 Returns a C string in the current locale encoding with the same
3652 contents as @var{str}. The C string must be freed with @code{free}
3653 eventually, maybe by using @code{scm_dynwind_free}, @xref{Dynamic
3656 For @code{scm_to_locale_string}, the returned string is
3657 null-terminated and an error is signalled when @var{str} contains
3658 @code{#\nul} characters.
3660 For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3661 @var{str} might contain @code{#\nul} characters and the length of the
3662 returned string in bytes is stored in @code{*@var{lenp}}. The
3663 returned string will not be null-terminated in this case. If
3664 @var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3665 @code{scm_to_locale_string}.
3668 @deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3669 Puts @var{str} as a C string in the current locale encoding into the
3670 memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3671 @var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3672 more than that. No terminating @code{'\0'} will be stored.
3674 The return value of @code{scm_to_locale_stringbuf} is the number of
3675 bytes that are needed for all of @var{str}, regardless of whether
3676 @var{buf} was large enough to hold them. Thus, when the return value
3677 is larger than @var{max_len}, only @var{max_len} bytes have been
3678 stored and you probably need to try again with a larger buffer.
3681 @node Regular Expressions
3682 @subsection Regular Expressions
3683 @tpindex Regular expressions
3685 @cindex regular expressions
3687 @cindex emacs regexp
3689 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
3690 describes a whole class of strings. A full description of regular
3691 expressions and their syntax is beyond the scope of this manual;
3692 an introduction can be found in the Emacs manual (@pxref{Regexps,
3693 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
3694 in many general Unix reference books.
3696 If your system does not include a POSIX regular expression library,
3697 and you have not linked Guile with a third-party regexp library such
3698 as Rx, these functions will not be available. You can tell whether
3699 your Guile installation includes regular expression support by
3700 checking whether @code{(provided? 'regex)} returns true.
3702 The following regexp and string matching features are provided by the
3703 @code{(ice-9 regex)} module. Before using the described functions,
3704 you should load this module by executing @code{(use-modules (ice-9
3708 * Regexp Functions:: Functions that create and match regexps.
3709 * Match Structures:: Finding what was matched by a regexp.
3710 * Backslash Escapes:: Removing the special meaning of regexp
3715 @node Regexp Functions
3716 @subsubsection Regexp Functions
3718 By default, Guile supports POSIX extended regular expressions.
3719 That means that the characters @samp{(}, @samp{)}, @samp{+} and
3720 @samp{?} are special, and must be escaped if you wish to match the
3723 This regular expression interface was modeled after that
3724 implemented by SCSH, the Scheme Shell. It is intended to be
3725 upwardly compatible with SCSH regular expressions.
3727 Zero bytes (@code{#\nul}) cannot be used in regex patterns or input
3728 strings, since the underlying C functions treat that as the end of
3729 string. If there's a zero byte an error is thrown.
3731 Patterns and input strings are treated as being in the locale
3732 character set if @code{setlocale} has been called (@pxref{Locales}),
3733 and in a multibyte locale this includes treating multi-byte sequences
3734 as a single character. (Guile strings are currently merely bytes,
3735 though this may change in the future, @xref{Conversion to/from C}.)
3737 @deffn {Scheme Procedure} string-match pattern str [start]
3738 Compile the string @var{pattern} into a regular expression and compare
3739 it with @var{str}. The optional numeric argument @var{start} specifies
3740 the position of @var{str} at which to begin matching.
3742 @code{string-match} returns a @dfn{match structure} which
3743 describes what, if anything, was matched by the regular
3744 expression. @xref{Match Structures}. If @var{str} does not match
3745 @var{pattern} at all, @code{string-match} returns @code{#f}.
3748 Two examples of a match follow. In the first example, the pattern
3749 matches the four digits in the match string. In the second, the pattern
3753 (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
3754 @result{} #("blah2002" (4 . 8))
3756 (string-match "[A-Za-z]" "123456")
3760 Each time @code{string-match} is called, it must compile its
3761 @var{pattern} argument into a regular expression structure. This
3762 operation is expensive, which makes @code{string-match} inefficient if
3763 the same regular expression is used several times (for example, in a
3764 loop). For better performance, you can compile a regular expression in
3765 advance and then match strings against the compiled regexp.
3767 @deffn {Scheme Procedure} make-regexp pat flag@dots{}
3768 @deffnx {C Function} scm_make_regexp (pat, flaglst)
3769 Compile the regular expression described by @var{pat}, and
3770 return the compiled regexp structure. If @var{pat} does not
3771 describe a legal regular expression, @code{make-regexp} throws
3772 a @code{regular-expression-syntax} error.
3774 The @var{flag} arguments change the behavior of the compiled
3775 regular expression. The following values may be supplied:
3777 @defvar regexp/icase
3778 Consider uppercase and lowercase letters to be the same when
3782 @defvar regexp/newline
3783 If a newline appears in the target string, then permit the
3784 @samp{^} and @samp{$} operators to match immediately after or
3785 immediately before the newline, respectively. Also, the
3786 @samp{.} and @samp{[^...]} operators will never match a newline
3787 character. The intent of this flag is to treat the target
3788 string as a buffer containing many lines of text, and the
3789 regular expression as a pattern that may match a single one of
3793 @defvar regexp/basic
3794 Compile a basic (``obsolete'') regexp instead of the extended
3795 (``modern'') regexps that are the default. Basic regexps do
3796 not consider @samp{|}, @samp{+} or @samp{?} to be special
3797 characters, and require the @samp{@{...@}} and @samp{(...)}
3798 metacharacters to be backslash-escaped (@pxref{Backslash
3799 Escapes}). There are several other differences between basic
3800 and extended regular expressions, but these are the most
3804 @defvar regexp/extended
3805 Compile an extended regular expression rather than a basic
3806 regexp. This is the default behavior; this flag will not
3807 usually be needed. If a call to @code{make-regexp} includes
3808 both @code{regexp/basic} and @code{regexp/extended} flags, the
3809 one which comes last will override the earlier one.
3813 @deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
3814 @deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
3815 Match the compiled regular expression @var{rx} against
3816 @code{str}. If the optional integer @var{start} argument is
3817 provided, begin matching from that position in the string.
3818 Return a match structure describing the results of the match,
3819 or @code{#f} if no match could be found.
3821 The @var{flags} argument changes the matching behavior. The following
3822 flag values may be supplied, use @code{logior} (@pxref{Bitwise
3823 Operations}) to combine them,
3825 @defvar regexp/notbol
3826 Consider that the @var{start} offset into @var{str} is not the
3827 beginning of a line and should not match operator @samp{^}.
3829 If @var{rx} was created with the @code{regexp/newline} option above,
3830 @samp{^} will still match after a newline in @var{str}.
3833 @defvar regexp/noteol
3834 Consider that the end of @var{str} is not the end of a line and should
3835 not match operator @samp{$}.
3837 If @var{rx} was created with the @code{regexp/newline} option above,
3838 @samp{$} will still match before a newline in @var{str}.
3843 ;; Regexp to match uppercase letters
3844 (define r (make-regexp "[A-Z]*"))
3846 ;; Regexp to match letters, ignoring case
3847 (define ri (make-regexp "[A-Z]*" regexp/icase))
3849 ;; Search for bob using regexp r
3850 (match:substring (regexp-exec r "bob"))
3851 @result{} "" ; no match
3853 ;; Search for bob using regexp ri
3854 (match:substring (regexp-exec ri "Bob"))
3855 @result{} "Bob" ; matched case insensitive
3858 @deffn {Scheme Procedure} regexp? obj
3859 @deffnx {C Function} scm_regexp_p (obj)
3860 Return @code{#t} if @var{obj} is a compiled regular expression,
3861 or @code{#f} otherwise.
3865 @deffn {Scheme Procedure} list-matches regexp str [flags]
3866 Return a list of match structures which are the non-overlapping
3867 matches of @var{regexp} in @var{str}. @var{regexp} can be either a
3868 pattern string or a compiled regexp. The @var{flags} argument is as
3869 per @code{regexp-exec} above.
3872 (map match:substring (list-matches "[a-z]+" "abc 42 def 78"))
3873 @result{} ("abc" "def")
3877 @deffn {Scheme Procedure} fold-matches regexp str init proc [flags]
3878 Apply @var{proc} to the non-overlapping matches of @var{regexp} in
3879 @var{str}, to build a result. @var{regexp} can be either a pattern
3880 string or a compiled regexp. The @var{flags} argument is as per
3881 @code{regexp-exec} above.
3883 @var{proc} is called as @code{(@var{proc} match prev)} where
3884 @var{match} is a match structure and @var{prev} is the previous return
3885 from @var{proc}. For the first call @var{prev} is the given
3886 @var{init} parameter. @code{fold-matches} returns the final value
3889 For example to count matches,
3892 (fold-matches "[a-z][0-9]" "abc x1 def y2" 0
3893 (lambda (match count)
3900 Regular expressions are commonly used to find patterns in one string
3901 and replace them with the contents of another string. The following
3902 functions are convenient ways to do this.
3904 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
3905 @deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
3906 Write to @var{port} selected parts of the match structure @var{match}.
3907 Or if @var{port} is @code{#f} then form a string from those parts and
3910 Each @var{item} specifies a part to be written, and may be one of the
3915 A string. String arguments are written out verbatim.
3918 An integer. The submatch with that number is written
3919 (@code{match:substring}). Zero is the entire match.
3922 The symbol @samp{pre}. The portion of the matched string preceding
3923 the regexp match is written (@code{match:prefix}).
3926 The symbol @samp{post}. The portion of the matched string following
3927 the regexp match is written (@code{match:suffix}).
3930 For example, changing a match and retaining the text before and after,
3933 (regexp-substitute #f (string-match "[0-9]+" "number 25 is good")
3935 @result{} "number 37 is good"
3938 Or matching a @sc{yyyymmdd} format date such as @samp{20020828} and
3939 re-ordering and hyphenating the fields.
3942 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
3943 (define s "Date 20020429 12am.")
3944 (regexp-substitute #f (string-match date-regex s)
3945 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
3946 @result{} "Date 04-29-2002 12am. (20020429)"
3951 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
3952 @deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
3953 @cindex search and replace
3954 Write to @var{port} selected parts of matches of @var{regexp} in
3955 @var{target}. If @var{port} is @code{#f} then form a string from
3956 those parts and return that. @var{regexp} can be a string or a
3959 This is similar to @code{regexp-substitute}, but allows global
3960 substitutions on @var{target}. Each @var{item} behaves as per
3961 @code{regexp-substitute}, with the following differences,
3965 A function. Called as @code{(@var{item} match)} with the match
3966 structure for the @var{regexp} match, it should return a string to be
3967 written to @var{port}.
3970 The symbol @samp{post}. This doesn't output anything, but instead
3971 causes @code{regexp-substitute/global} to recurse on the unmatched
3972 portion of @var{target}.
3974 This @emph{must} be supplied to perform a global search and replace on
3975 @var{target}; without it @code{regexp-substitute/global} returns after
3976 a single match and output.
3979 For example, to collapse runs of tabs and spaces to a single hyphen
3983 (regexp-substitute/global #f "[ \t]+" "this is the text"
3985 @result{} "this-is-the-text"
3988 Or using a function to reverse the letters in each word,
3991 (regexp-substitute/global #f "[a-z]+" "to do and not-do"
3992 'pre (lambda (m) (string-reverse (match:substring m))) 'post)
3993 @result{} "ot od dna ton-od"
3996 Without the @code{post} symbol, just one regexp match is made. For
3997 example the following is the date example from
3998 @code{regexp-substitute} above, without the need for the separate
3999 @code{string-match} call.
4002 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
4003 (define s "Date 20020429 12am.")
4004 (regexp-substitute/global #f date-regex s
4005 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
4007 @result{} "Date 04-29-2002 12am. (20020429)"
4012 @node Match Structures
4013 @subsubsection Match Structures
4015 @cindex match structures
4017 A @dfn{match structure} is the object returned by @code{string-match} and
4018 @code{regexp-exec}. It describes which portion of a string, if any,
4019 matched the given regular expression. Match structures include: a
4020 reference to the string that was checked for matches; the starting and
4021 ending positions of the regexp match; and, if the regexp included any
4022 parenthesized subexpressions, the starting and ending positions of each
4025 In each of the regexp match functions described below, the @code{match}
4026 argument must be a match structure returned by a previous call to
4027 @code{string-match} or @code{regexp-exec}. Most of these functions
4028 return some information about the original target string that was
4029 matched against a regular expression; we will call that string
4030 @var{target} for easy reference.
4032 @c begin (scm-doc-string "regex.scm" "regexp-match?")
4033 @deffn {Scheme Procedure} regexp-match? obj
4034 Return @code{#t} if @var{obj} is a match structure returned by a
4035 previous call to @code{regexp-exec}, or @code{#f} otherwise.
4038 @c begin (scm-doc-string "regex.scm" "match:substring")
4039 @deffn {Scheme Procedure} match:substring match [n]
4040 Return the portion of @var{target} matched by subexpression number
4041 @var{n}. Submatch 0 (the default) represents the entire regexp match.
4042 If the regular expression as a whole matched, but the subexpression
4043 number @var{n} did not match, return @code{#f}.
4047 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4051 ;; match starting at offset 6 in the string
4053 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
4057 @c begin (scm-doc-string "regex.scm" "match:start")
4058 @deffn {Scheme Procedure} match:start match [n]
4059 Return the starting position of submatch number @var{n}.
4062 In the following example, the result is 4, since the match starts at
4066 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4071 @c begin (scm-doc-string "regex.scm" "match:end")
4072 @deffn {Scheme Procedure} match:end match [n]
4073 Return the ending position of submatch number @var{n}.
4076 In the following example, the result is 8, since the match runs between
4077 characters 4 and 8 (i.e. the ``2002'').
4080 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4085 @c begin (scm-doc-string "regex.scm" "match:prefix")
4086 @deffn {Scheme Procedure} match:prefix match
4087 Return the unmatched portion of @var{target} preceding the regexp match.
4090 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4096 @c begin (scm-doc-string "regex.scm" "match:suffix")
4097 @deffn {Scheme Procedure} match:suffix match
4098 Return the unmatched portion of @var{target} following the regexp match.
4102 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4107 @c begin (scm-doc-string "regex.scm" "match:count")
4108 @deffn {Scheme Procedure} match:count match
4109 Return the number of parenthesized subexpressions from @var{match}.
4110 Note that the entire regular expression match itself counts as a
4111 subexpression, and failed submatches are included in the count.
4114 @c begin (scm-doc-string "regex.scm" "match:string")
4115 @deffn {Scheme Procedure} match:string match
4116 Return the original @var{target} string.
4120 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4122 @result{} "blah2002foo"
4126 @node Backslash Escapes
4127 @subsubsection Backslash Escapes
4129 Sometimes you will want a regexp to match characters like @samp{*} or
4130 @samp{$} exactly. For example, to check whether a particular string
4131 represents a menu entry from an Info node, it would be useful to match
4132 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
4133 because the asterisk is a metacharacter, it won't match the @samp{*} at
4134 the beginning of the string. In this case, we want to make the first
4137 You can do this by preceding the metacharacter with a backslash
4138 character @samp{\}. (This is also called @dfn{quoting} the
4139 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
4140 sees a backslash in a regular expression, it considers the following
4141 glyph to be an ordinary character, no matter what special meaning it
4142 would ordinarily have. Therefore, we can make the above example work by
4143 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
4144 the regular expression engine to match only a single asterisk in the
4147 Since the backslash is itself a metacharacter, you may force a regexp to
4148 match a backslash in the target string by preceding the backslash with
4149 itself. For example, to find variable references in a @TeX{} program,
4150 you might want to find occurrences of the string @samp{\let\} followed
4151 by any number of alphabetic characters. The regular expression
4152 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
4153 regexp each match a single backslash in the target string.
4155 @c begin (scm-doc-string "regex.scm" "regexp-quote")
4156 @deffn {Scheme Procedure} regexp-quote str
4157 Quote each special character found in @var{str} with a backslash, and
4158 return the resulting string.
4161 @strong{Very important:} Using backslash escapes in Guile source code
4162 (as in Emacs Lisp or C) can be tricky, because the backslash character
4163 has special meaning for the Guile reader. For example, if Guile
4164 encounters the character sequence @samp{\n} in the middle of a string
4165 while processing Scheme code, it replaces those characters with a
4166 newline character. Similarly, the character sequence @samp{\t} is
4167 replaced by a horizontal tab. Several of these @dfn{escape sequences}
4168 are processed by the Guile reader before your code is executed.
4169 Unrecognized escape sequences are ignored: if the characters @samp{\*}
4170 appear in a string, they will be translated to the single character
4173 This translation is obviously undesirable for regular expressions, since
4174 we want to be able to include backslashes in a string in order to
4175 escape regexp metacharacters. Therefore, to make sure that a backslash
4176 is preserved in a string in your Guile program, you must use @emph{two}
4177 consecutive backslashes:
4180 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
4183 The string in this example is preprocessed by the Guile reader before
4184 any code is executed. The resulting argument to @code{make-regexp} is
4185 the string @samp{^\* [^:]*}, which is what we really want.
4187 This also means that in order to write a regular expression that matches
4188 a single backslash character, the regular expression string in the
4189 source code must include @emph{four} backslashes. Each consecutive pair
4190 of backslashes gets translated by the Guile reader to a single
4191 backslash, and the resulting double-backslash is interpreted by the
4192 regexp engine as matching a single backslash character. Hence:
4195 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
4198 The reason for the unwieldiness of this syntax is historical. Both
4199 regular expression pattern matchers and Unix string processing systems
4200 have traditionally used backslashes with the special meanings
4201 described above. The POSIX regular expression specification and ANSI C
4202 standard both require these semantics. Attempting to abandon either
4203 convention would cause other kinds of compatibility problems, possibly
4204 more severe ones. Therefore, without extending the Scheme reader to
4205 support strings with different quoting conventions (an ungainly and
4206 confusing extension when implemented in other languages), we must adhere
4207 to this cumbersome escape syntax.
4214 Symbols in Scheme are widely used in three ways: as items of discrete
4215 data, as lookup keys for alists and hash tables, and to denote variable
4218 A @dfn{symbol} is similar to a string in that it is defined by a
4219 sequence of characters. The sequence of characters is known as the
4220 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
4221 name doesn't include any characters that could be confused with other
4222 elements of Scheme syntax --- a symbol is written in a Scheme program by
4223 writing the sequence of characters that make up the name, @emph{without}
4224 any quotation marks or other special syntax. For example, the symbol
4225 whose name is ``multiply-by-2'' is written, simply:
4231 Notice how this differs from a @emph{string} with contents
4232 ``multiply-by-2'', which is written with double quotation marks, like
4239 Looking beyond how they are written, symbols are different from strings
4240 in two important respects.
4242 The first important difference is uniqueness. If the same-looking
4243 string is read twice from two different places in a program, the result
4244 is two @emph{different} string objects whose contents just happen to be
4245 the same. If, on the other hand, the same-looking symbol is read twice
4246 from two different places in a program, the result is the @emph{same}
4247 symbol object both times.
4249 Given two read symbols, you can use @code{eq?} to test whether they are
4250 the same (that is, have the same name). @code{eq?} is the most
4251 efficient comparison operator in Scheme, and comparing two symbols like
4252 this is as fast as comparing, for example, two numbers. Given two
4253 strings, on the other hand, you must use @code{equal?} or
4254 @code{string=?}, which are much slower comparison operators, to
4255 determine whether the strings have the same contents.
4258 (define sym1 (quote hello))
4259 (define sym2 (quote hello))
4260 (eq? sym1 sym2) @result{} #t
4262 (define str1 "hello")
4263 (define str2 "hello")
4264 (eq? str1 str2) @result{} #f
4265 (equal? str1 str2) @result{} #t
4268 The second important difference is that symbols, unlike strings, are not
4269 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
4270 example above: @code{(quote hello)} evaluates to the symbol named
4271 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
4272 symbol named "hello" and evaluated as a variable reference @dots{} about
4273 which more below (@pxref{Symbol Variables}).
4276 * Symbol Data:: Symbols as discrete data.
4277 * Symbol Keys:: Symbols as lookup keys.
4278 * Symbol Variables:: Symbols as denoting variables.
4279 * Symbol Primitives:: Operations related to symbols.
4280 * Symbol Props:: Function slots and property lists.
4281 * Symbol Read Syntax:: Extended read syntax for symbols.
4282 * Symbol Uninterned:: Uninterned symbols.
4287 @subsubsection Symbols as Discrete Data
4289 Numbers and symbols are similar to the extent that they both lend
4290 themselves to @code{eq?} comparison. But symbols are more descriptive
4291 than numbers, because a symbol's name can be used directly to describe
4292 the concept for which that symbol stands.
4294 For example, imagine that you need to represent some colours in a
4295 computer program. Using numbers, you would have to choose arbitrarily
4296 some mapping between numbers and colours, and then take care to use that
4297 mapping consistently:
4300 ;; 1=red, 2=green, 3=purple
4302 (if (eq? (colour-of car) 1)
4307 You can make the mapping more explicit and the code more readable by
4315 (if (eq? (colour-of car) red)
4320 But the simplest and clearest approach is not to use numbers at all, but
4321 symbols whose names specify the colours that they refer to:
4324 (if (eq? (colour-of car) 'red)
4328 The descriptive advantages of symbols over numbers increase as the set
4329 of concepts that you want to describe grows. Suppose that a car object
4330 can have other properties as well, such as whether it has or uses:
4334 automatic or manual transmission
4336 leaded or unleaded fuel
4338 power steering (or not).
4342 Then a car's combined property set could be naturally represented and
4343 manipulated as a list of symbols:
4346 (properties-of car1)
4348 (red manual unleaded power-steering)
4350 (if (memq 'power-steering (properties-of car1))
4351 (display "Unfit people can drive this car.\n")
4352 (display "You'll need strong arms to drive this car!\n"))
4354 Unfit people can drive this car.
4357 Remember, the fundamental property of symbols that we are relying on
4358 here is that an occurrence of @code{'red} in one part of a program is an
4359 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
4360 another part of a program; this means that symbols can usefully be
4361 compared using @code{eq?}. At the same time, symbols have naturally
4362 descriptive names. This combination of efficiency and descriptive power
4363 makes them ideal for use as discrete data.
4367 @subsubsection Symbols as Lookup Keys
4369 Given their efficiency and descriptive power, it is natural to use
4370 symbols as the keys in an association list or hash table.
4372 To illustrate this, consider a more structured representation of the car
4373 properties example from the preceding subsection. Rather than
4374 mixing all the properties up together in a flat list, we could use an
4375 association list like this:
4378 (define car1-properties '((colour . red)
4379 (transmission . manual)
4381 (steering . power-assisted)))
4384 Notice how this structure is more explicit and extensible than the flat
4385 list. For example it makes clear that @code{manual} refers to the
4386 transmission rather than, say, the windows or the locking of the car.
4387 It also allows further properties to use the same symbols among their
4388 possible values without becoming ambiguous:
4391 (define car1-properties '((colour . red)
4392 (transmission . manual)
4394 (steering . power-assisted)
4396 (locking . manual)))
4399 With a representation like this, it is easy to use the efficient
4400 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
4401 extract or change individual pieces of information:
4404 (assq-ref car1-properties 'fuel) @result{} unleaded
4405 (assq-ref car1-properties 'transmission) @result{} manual
4407 (assq-set! car1-properties 'seat-colour 'black)
4410 (transmission . manual)
4412 (steering . power-assisted)
4413 (seat-colour . black)
4414 (locking . manual)))
4417 Hash tables also have keys, and exactly the same arguments apply to the
4418 use of symbols in hash tables as in association lists. The hash value
4419 that Guile uses to decide where to add a symbol-keyed entry to a hash
4420 table can be obtained by calling the @code{symbol-hash} procedure:
4422 @deffn {Scheme Procedure} symbol-hash symbol
4423 @deffnx {C Function} scm_symbol_hash (symbol)
4424 Return a hash value for @var{symbol}.
4427 See @ref{Hash Tables} for information about hash tables in general, and
4428 for why you might choose to use a hash table rather than an association
4432 @node Symbol Variables
4433 @subsubsection Symbols as Denoting Variables
4435 When an unquoted symbol in a Scheme program is evaluated, it is
4436 interpreted as a variable reference, and the result of the evaluation is
4437 the appropriate variable's value.
4439 For example, when the expression @code{(string-length "abcd")} is read
4440 and evaluated, the sequence of characters @code{string-length} is read
4441 as the symbol whose name is "string-length". This symbol is associated
4442 with a variable whose value is the procedure that implements string
4443 length calculation. Therefore evaluation of the @code{string-length}
4444 symbol results in that procedure.
4446 The details of the connection between an unquoted symbol and the
4447 variable to which it refers are explained elsewhere. See @ref{Binding
4448 Constructs}, for how associations between symbols and variables are
4449 created, and @ref{Modules}, for how those associations are affected by
4450 Guile's module system.
4453 @node Symbol Primitives
4454 @subsubsection Operations Related to Symbols
4456 Given any Scheme value, you can determine whether it is a symbol using
4457 the @code{symbol?} primitive:
4460 @deffn {Scheme Procedure} symbol? obj
4461 @deffnx {C Function} scm_symbol_p (obj)
4462 Return @code{#t} if @var{obj} is a symbol, otherwise return
4466 @deftypefn {C Function} int scm_is_symbol (SCM val)
4467 Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
4470 Once you know that you have a symbol, you can obtain its name as a
4471 string by calling @code{symbol->string}. Note that Guile differs by
4472 default from R5RS on the details of @code{symbol->string} as regards
4475 @rnindex symbol->string
4476 @deffn {Scheme Procedure} symbol->string s
4477 @deffnx {C Function} scm_symbol_to_string (s)
4478 Return the name of symbol @var{s} as a string. By default, Guile reads
4479 symbols case-sensitively, so the string returned will have the same case
4480 variation as the sequence of characters that caused @var{s} to be
4483 If Guile is set to read symbols case-insensitively (as specified by
4484 R5RS), and @var{s} comes into being as part of a literal expression
4485 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
4486 by a call to the @code{read} or @code{string-ci->symbol} procedures,
4487 Guile converts any alphabetic characters in the symbol's name to
4488 lower case before creating the symbol object, so the string returned
4489 here will be in lower case.
4491 If @var{s} was created by @code{string->symbol}, the case of characters
4492 in the string returned will be the same as that in the string that was
4493 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
4494 setting at the time @var{s} was created.
4496 It is an error to apply mutation procedures like @code{string-set!} to
4497 strings returned by this procedure.
4500 Most symbols are created by writing them literally in code. However it
4501 is also possible to create symbols programmatically using the following
4502 @code{string->symbol} and @code{string-ci->symbol} procedures:
4504 @rnindex string->symbol
4505 @deffn {Scheme Procedure} string->symbol string
4506 @deffnx {C Function} scm_string_to_symbol (string)
4507 Return the symbol whose name is @var{string}. This procedure can create
4508 symbols with names containing special characters or letters in the
4509 non-standard case, but it is usually a bad idea to create such symbols
4510 because in some implementations of Scheme they cannot be read as
4514 @deffn {Scheme Procedure} string-ci->symbol str
4515 @deffnx {C Function} scm_string_ci_to_symbol (str)
4516 Return the symbol whose name is @var{str}. If Guile is currently
4517 reading symbols case-insensitively, @var{str} is converted to lowercase
4518 before the returned symbol is looked up or created.
4521 The following examples illustrate Guile's detailed behaviour as regards
4522 the case-sensitivity of symbols:
4525 (read-enable 'case-insensitive) ; R5RS compliant behaviour
4527 (symbol->string 'flying-fish) @result{} "flying-fish"
4528 (symbol->string 'Martin) @result{} "martin"
4530 (string->symbol "Malvina")) @result{} "Malvina"
4532 (eq? 'mISSISSIppi 'mississippi) @result{} #t
4533 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4534 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
4536 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4537 (string=? "K. Harper, M.D."
4539 (string->symbol "K. Harper, M.D."))) @result{} #t
4541 (read-disable 'case-insensitive) ; Guile default behaviour
4543 (symbol->string 'flying-fish) @result{} "flying-fish"
4544 (symbol->string 'Martin) @result{} "Martin"
4546 (string->symbol "Malvina")) @result{} "Malvina"
4548 (eq? 'mISSISSIppi 'mississippi) @result{} #f
4549 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
4550 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
4552 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4553 (string=? "K. Harper, M.D."
4555 (string->symbol "K. Harper, M.D."))) @result{} #t
4558 From C, there are lower level functions that construct a Scheme symbol
4559 from a C string in the current locale encoding.
4561 When you want to do more from C, you should convert between symbols
4562 and strings using @code{scm_symbol_to_string} and
4563 @code{scm_string_to_symbol} and work with the strings.
4565 @deffn {C Function} scm_from_locale_symbol (const char *name)
4566 @deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
4567 Construct and return a Scheme symbol whose name is specified by
4568 @var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
4569 terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
4570 specified explicitly by @var{len}.
4573 @deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
4574 @deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
4575 Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
4576 respectively, but also frees @var{str} with @code{free} eventually.
4577 Thus, you can use this function when you would free @var{str} anyway
4578 immediately after creating the Scheme string. In certain cases, Guile
4579 can then use @var{str} directly as its internal representation.
4583 Finally, some applications, especially those that generate new Scheme
4584 code dynamically, need to generate symbols for use in the generated
4585 code. The @code{gensym} primitive meets this need:
4587 @deffn {Scheme Procedure} gensym [prefix]
4588 @deffnx {C Function} scm_gensym (prefix)
4589 Create a new symbol with a name constructed from a prefix and a counter
4590 value. The string @var{prefix} can be specified as an optional
4591 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
4592 at each call. There is no provision for resetting the counter.
4595 The symbols generated by @code{gensym} are @emph{likely} to be unique,
4596 since their names begin with a space and it is only otherwise possible
4597 to generate such symbols if a programmer goes out of their way to do
4598 so. Uniqueness can be guaranteed by instead using uninterned symbols
4599 (@pxref{Symbol Uninterned}), though they can't be usefully written out
4604 @subsubsection Function Slots and Property Lists
4606 In traditional Lisp dialects, symbols are often understood as having
4607 three kinds of value at once:
4611 a @dfn{variable} value, which is used when the symbol appears in
4612 code in a variable reference context
4615 a @dfn{function} value, which is used when the symbol appears in
4616 code in a function name position (i.e. as the first element in an
4620 a @dfn{property list} value, which is used when the symbol is given as
4621 the first argument to Lisp's @code{put} or @code{get} functions.
4624 Although Scheme (as one of its simplifications with respect to Lisp)
4625 does away with the distinction between variable and function namespaces,
4626 Guile currently retains some elements of the traditional structure in
4627 case they turn out to be useful when implementing translators for other
4628 languages, in particular Emacs Lisp.
4630 Specifically, Guile symbols have two extra slots. for a symbol's
4631 property list, and for its ``function value.'' The following procedures
4632 are provided to access these slots.
4634 @deffn {Scheme Procedure} symbol-fref symbol
4635 @deffnx {C Function} scm_symbol_fref (symbol)
4636 Return the contents of @var{symbol}'s @dfn{function slot}.
4639 @deffn {Scheme Procedure} symbol-fset! symbol value
4640 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
4641 Set the contents of @var{symbol}'s function slot to @var{value}.
4644 @deffn {Scheme Procedure} symbol-pref symbol
4645 @deffnx {C Function} scm_symbol_pref (symbol)
4646 Return the @dfn{property list} currently associated with @var{symbol}.
4649 @deffn {Scheme Procedure} symbol-pset! symbol value
4650 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
4651 Set @var{symbol}'s property list to @var{value}.
4654 @deffn {Scheme Procedure} symbol-property sym prop
4655 From @var{sym}'s property list, return the value for property
4656 @var{prop}. The assumption is that @var{sym}'s property list is an
4657 association list whose keys are distinguished from each other using
4658 @code{equal?}; @var{prop} should be one of the keys in that list. If
4659 the property list has no entry for @var{prop}, @code{symbol-property}
4663 @deffn {Scheme Procedure} set-symbol-property! sym prop val
4664 In @var{sym}'s property list, set the value for property @var{prop} to
4665 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
4666 none already exists. For the structure of the property list, see
4667 @code{symbol-property}.
4670 @deffn {Scheme Procedure} symbol-property-remove! sym prop
4671 From @var{sym}'s property list, remove the entry for property
4672 @var{prop}, if there is one. For the structure of the property list,
4673 see @code{symbol-property}.
4676 Support for these extra slots may be removed in a future release, and it
4677 is probably better to avoid using them. (In release 1.6, Guile itself
4678 uses the property list slot sparingly, and the function slot not at
4679 all.) For a more modern and Schemely approach to properties, see
4680 @ref{Object Properties}.
4683 @node Symbol Read Syntax
4684 @subsubsection Extended Read Syntax for Symbols
4686 The read syntax for a symbol is a sequence of letters, digits, and
4687 @dfn{extended alphabetic characters}, beginning with a character that
4688 cannot begin a number. In addition, the special cases of @code{+},
4689 @code{-}, and @code{...} are read as symbols even though numbers can
4690 begin with @code{+}, @code{-} or @code{.}.
4692 Extended alphabetic characters may be used within identifiers as if
4693 they were letters. The set of extended alphabetic characters is:
4696 ! $ % & * + - . / : < = > ? @@ ^ _ ~
4699 In addition to the standard read syntax defined above (which is taken
4700 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
4701 Scheme})), Guile provides an extended symbol read syntax that allows the
4702 inclusion of unusual characters such as space characters, newlines and
4703 parentheses. If (for whatever reason) you need to write a symbol
4704 containing characters not mentioned above, you can do so as follows.
4708 Begin the symbol with the characters @code{#@{},
4711 write the characters of the symbol and
4714 finish the symbol with the characters @code{@}#}.
4717 Here are a few examples of this form of read syntax. The first symbol
4718 needs to use extended syntax because it contains a space character, the
4719 second because it contains a line break, and the last because it looks
4731 Although Guile provides this extended read syntax for symbols,
4732 widespread usage of it is discouraged because it is not portable and not
4736 @node Symbol Uninterned
4737 @subsubsection Uninterned Symbols
4739 What makes symbols useful is that they are automatically kept unique.
4740 There are no two symbols that are distinct objects but have the same
4741 name. But of course, there is no rule without exception. In addition
4742 to the normal symbols that have been discussed up to now, you can also
4743 create special @dfn{uninterned} symbols that behave slightly
4746 To understand what is different about them and why they might be useful,
4747 we look at how normal symbols are actually kept unique.
4749 Whenever Guile wants to find the symbol with a specific name, for
4750 example during @code{read} or when executing @code{string->symbol}, it
4751 first looks into a table of all existing symbols to find out whether a
4752 symbol with the given name already exists. When this is the case, Guile
4753 just returns that symbol. When not, a new symbol with the name is
4754 created and entered into the table so that it can be found later.
4756 Sometimes you might want to create a symbol that is guaranteed `fresh',
4757 i.e. a symbol that did not exist previously. You might also want to
4758 somehow guarantee that no one else will ever unintentionally stumble
4759 across your symbol in the future. These properties of a symbol are
4760 often needed when generating code during macro expansion. When
4761 introducing new temporary variables, you want to guarantee that they
4762 don't conflict with variables in other people's code.
4764 The simplest way to arrange for this is to create a new symbol but
4765 not enter it into the global table of all symbols. That way, no one
4766 will ever get access to your symbol by chance. Symbols that are not in
4767 the table are called @dfn{uninterned}. Of course, symbols that
4768 @emph{are} in the table are called @dfn{interned}.
4770 You create new uninterned symbols with the function @code{make-symbol}.
4771 You can test whether a symbol is interned or not with
4772 @code{symbol-interned?}.
4774 Uninterned symbols break the rule that the name of a symbol uniquely
4775 identifies the symbol object. Because of this, they can not be written
4776 out and read back in like interned symbols. Currently, Guile has no
4777 support for reading uninterned symbols. Note that the function
4778 @code{gensym} does not return uninterned symbols for this reason.
4780 @deffn {Scheme Procedure} make-symbol name
4781 @deffnx {C Function} scm_make_symbol (name)
4782 Return a new uninterned symbol with the name @var{name}. The returned
4783 symbol is guaranteed to be unique and future calls to
4784 @code{string->symbol} will not return it.
4787 @deffn {Scheme Procedure} symbol-interned? symbol
4788 @deffnx {C Function} scm_symbol_interned_p (symbol)
4789 Return @code{#t} if @var{symbol} is interned, otherwise return
4796 (define foo-1 (string->symbol "foo"))
4797 (define foo-2 (string->symbol "foo"))
4798 (define foo-3 (make-symbol "foo"))
4799 (define foo-4 (make-symbol "foo"))
4803 ; Two interned symbols with the same name are the same object,
4807 ; but a call to make-symbol with the same name returns a
4812 ; A call to make-symbol always returns a new object, even for
4816 @result{} #<uninterned-symbol foo 8085290>
4817 ; Uninterned symbols print differently from interned symbols,
4821 ; but they are still symbols,
4823 (symbol-interned? foo-3)
4825 ; just not interned.
4830 @subsection Keywords
4833 Keywords are self-evaluating objects with a convenient read syntax that
4834 makes them easy to type.
4836 Guile's keyword support conforms to R5RS, and adds a (switchable) read
4837 syntax extension to permit keywords to begin with @code{:} as well as
4841 * Why Use Keywords?:: Motivation for keyword usage.
4842 * Coding With Keywords:: How to use keywords.
4843 * Keyword Read Syntax:: Read syntax for keywords.
4844 * Keyword Procedures:: Procedures for dealing with keywords.
4847 @node Why Use Keywords?
4848 @subsubsection Why Use Keywords?
4850 Keywords are useful in contexts where a program or procedure wants to be
4851 able to accept a large number of optional arguments without making its
4852 interface unmanageable.
4854 To illustrate this, consider a hypothetical @code{make-window}
4855 procedure, which creates a new window on the screen for drawing into
4856 using some graphical toolkit. There are many parameters that the caller
4857 might like to specify, but which could also be sensibly defaulted, for
4862 color depth -- Default: the color depth for the screen
4865 background color -- Default: white
4868 width -- Default: 600
4871 height -- Default: 400
4874 If @code{make-window} did not use keywords, the caller would have to
4875 pass in a value for each possible argument, remembering the correct
4876 argument order and using a special value to indicate the default value
4880 (make-window 'default ;; Color depth
4881 'default ;; Background color
4884 @dots{}) ;; More make-window arguments
4887 With keywords, on the other hand, defaulted arguments are omitted, and
4888 non-default arguments are clearly tagged by the appropriate keyword. As
4889 a result, the invocation becomes much clearer:
4892 (make-window #:width 800 #:height 100)
4895 On the other hand, for a simpler procedure with few arguments, the use
4896 of keywords would be a hindrance rather than a help. The primitive
4897 procedure @code{cons}, for example, would not be improved if it had to
4901 (cons #:car x #:cdr y)
4904 So the decision whether to use keywords or not is purely pragmatic: use
4905 them if they will clarify the procedure invocation at point of call.
4907 @node Coding With Keywords
4908 @subsubsection Coding With Keywords
4910 If a procedure wants to support keywords, it should take a rest argument
4911 and then use whatever means is convenient to extract keywords and their
4912 corresponding arguments from the contents of that rest argument.
4914 The following example illustrates the principle: the code for
4915 @code{make-window} uses a helper procedure called
4916 @code{get-keyword-value} to extract individual keyword arguments from
4920 (define (get-keyword-value args keyword default)
4921 (let ((kv (memq keyword args)))
4922 (if (and kv (>= (length kv) 2))
4926 (define (make-window . args)
4927 (let ((depth (get-keyword-value args #:depth screen-depth))
4928 (bg (get-keyword-value args #:bg "white"))
4929 (width (get-keyword-value args #:width 800))
4930 (height (get-keyword-value args #:height 100))
4935 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
4936 optargs)} module provides a set of powerful macros that you can use to
4937 implement keyword-supporting procedures like this:
4940 (use-modules (ice-9 optargs))
4942 (define (make-window . args)
4943 (let-keywords args #f ((depth screen-depth)
4951 Or, even more economically, like this:
4954 (use-modules (ice-9 optargs))
4956 (define* (make-window #:key (depth screen-depth)
4963 For further details on @code{let-keywords}, @code{define*} and other
4964 facilities provided by the @code{(ice-9 optargs)} module, see
4965 @ref{Optional Arguments}.
4968 @node Keyword Read Syntax
4969 @subsubsection Keyword Read Syntax
4971 Guile, by default, only recognizes a keyword syntax that is compatible
4972 with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
4973 same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
4974 external representation of the keyword named @code{NAME}. Keyword
4975 objects print using this syntax as well, so values containing keyword
4976 objects can be read back into Guile. When used in an expression,
4977 keywords are self-quoting objects.
4979 If the @code{keyword} read option is set to @code{'prefix}, Guile also
4980 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
4981 of the form @code{:NAME} are read as symbols, as required by R5RS.
4983 To enable and disable the alternative non-R5RS keyword syntax, you use
4984 the @code{read-set!} procedure documented in @ref{User level options
4985 interfaces} and @ref{Reader options}.
4988 (read-set! keywords 'prefix)
4998 (read-set! keywords #f)
5006 ERROR: In expression :type:
5007 ERROR: Unbound variable: :type
5008 ABORT: (unbound-variable)
5011 @node Keyword Procedures
5012 @subsubsection Keyword Procedures
5014 @deffn {Scheme Procedure} keyword? obj
5015 @deffnx {C Function} scm_keyword_p (obj)
5016 Return @code{#t} if the argument @var{obj} is a keyword, else
5020 @deffn {Scheme Procedure} keyword->symbol keyword
5021 @deffnx {C Function} scm_keyword_to_symbol (keyword)
5022 Return the symbol with the same name as @var{keyword}.
5025 @deffn {Scheme Procedure} symbol->keyword symbol
5026 @deffnx {C Function} scm_symbol_to_keyword (symbol)
5027 Return the keyword with the same name as @var{symbol}.
5030 @deftypefn {C Function} int scm_is_keyword (SCM obj)
5031 Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
5034 @deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5035 @deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5036 Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5037 (@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5038 (@var{str}, @var{len}))}, respectively.
5042 @subsection ``Functionality-Centric'' Data Types
5044 Procedures and macros are documented in their own chapter: see
5045 @ref{Procedures and Macros}.
5047 Variable objects are documented as part of the description of Guile's
5048 module system: see @ref{Variables}.
5050 Asyncs, dynamic roots and fluids are described in the chapter on
5051 scheduling: see @ref{Scheduling}.
5053 Hooks are documented in the chapter on general utility functions: see
5056 Ports are described in the chapter on I/O: see @ref{Input and Output}.
5060 @c TeX-master: "guile.texi"